diff --git a/third-party/InterFormer/mmseg.yaml b/third-party/InterFormer/mmseg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..233a5ccbdcad1009fc868c6688a901746fbe0fcb --- /dev/null +++ b/third-party/InterFormer/mmseg.yaml @@ -0,0 +1,257 @@ +name: mmseg +channels: + - pytorch + - nvidia + - defaults +dependencies: + - _libgcc_mutex=0.1=main + - _openmp_mutex=5.1=1_gnu + - blas=1.0=mkl + - brotlipy=0.7.0=py310h7f8727e_1002 + - bzip2=1.0.8=h7b6447c_0 + - ca-certificates=2023.05.30=h06a4308_0 + - certifi=2023.5.7=py310h06a4308_0 + - cffi=1.15.1=py310h5eee18b_3 + - charset-normalizer=2.0.4=pyhd3eb1b0_0 + - cryptography=39.0.1=py310h9ce1e76_2 + - cuda=11.6.1=0 + - cuda-cccl=11.6.55=hf6102b2_0 + - cuda-command-line-tools=11.6.2=0 + - cuda-compiler=11.6.2=0 + - cuda-cudart=11.6.55=he381448_0 + - cuda-cudart-dev=11.6.55=h42ad0f4_0 + - cuda-cuobjdump=11.6.124=h2eeebcb_0 + - cuda-cupti=11.6.124=h86345e5_0 + - cuda-cuxxfilt=11.6.124=hecbf4f6_0 + - cuda-driver-dev=11.6.55=0 + - cuda-gdb=12.1.105=0 + - cuda-libraries=11.6.1=0 + - cuda-libraries-dev=11.6.1=0 + - cuda-memcheck=11.8.86=0 + - cuda-nsight=12.1.105=0 + - cuda-nsight-compute=12.1.1=0 + - cuda-nvcc=11.6.124=hbba6d2d_0 + - cuda-nvdisasm=12.1.105=0 + - cuda-nvml-dev=11.6.55=haa9ef22_0 + - cuda-nvprof=12.1.105=0 + - cuda-nvprune=11.6.124=he22ec0a_0 + - cuda-nvrtc=11.6.124=h020bade_0 + - cuda-nvrtc-dev=11.6.124=h249d397_0 + - cuda-nvtx=11.6.124=h0630a44_0 + - cuda-nvvp=12.1.105=0 + - cuda-runtime=11.6.1=0 + - cuda-samples=11.6.101=h8efea70_0 + - cuda-sanitizer-api=12.1.105=0 + - cuda-toolkit=11.6.1=0 + - cuda-tools=11.6.1=0 + - cuda-visual-tools=11.6.1=0 + - ffmpeg=4.2.2=h20bf706_0 + - freetype=2.12.1=h4a9f257_0 + - gds-tools=1.6.1.9=0 + - giflib=5.2.1=h5eee18b_3 + - gmp=6.2.1=h295c915_3 + - gnutls=3.6.15=he1e5248_0 + - idna=3.4=py310h06a4308_0 + - intel-openmp=2023.1.0=hdb19cb5_46305 + - jpeg=9e=h5eee18b_1 + - lame=3.100=h7b6447c_0 + - lcms2=2.12=h3be6417_0 + - ld_impl_linux-64=2.38=h1181459_1 + - lerc=3.0=h295c915_0 + - libcublas=11.9.2.110=h5e84587_0 + - libcublas-dev=11.9.2.110=h5c901ab_0 + - libcufft=10.7.1.112=hf425ae0_0 + - libcufft-dev=10.7.1.112=ha5ce4c0_0 + - libcufile=1.6.1.9=0 + - libcufile-dev=1.6.1.9=0 + - libcurand=10.3.2.106=0 + - libcurand-dev=10.3.2.106=0 + - libcusolver=11.3.4.124=h33c3c4e_0 + - libcusparse=11.7.2.124=h7538f96_0 + - libcusparse-dev=11.7.2.124=hbbe9722_0 + - libdeflate=1.17=h5eee18b_0 + - libffi=3.4.4=h6a678d5_0 + - libgcc-ng=11.2.0=h1234567_1 + - libgomp=11.2.0=h1234567_1 + - libidn2=2.3.4=h5eee18b_0 + - libnpp=11.6.3.124=hd2722f0_0 + - libnpp-dev=11.6.3.124=h3c42840_0 + - libnvjpeg=11.6.2.124=hd473ad6_0 + - libnvjpeg-dev=11.6.2.124=hb5906b9_0 + - libopus=1.3.1=h7b6447c_0 + - libpng=1.6.39=h5eee18b_0 + - libstdcxx-ng=11.2.0=h1234567_1 + - libtasn1=4.19.0=h5eee18b_0 + - libtiff=4.5.0=h6a678d5_2 + - libunistring=0.9.10=h27cfd23_0 + - libuuid=1.41.5=h5eee18b_0 + - libvpx=1.7.0=h439df22_0 + - libwebp=1.2.4=h11a3e52_1 + - libwebp-base=1.2.4=h5eee18b_1 + - lz4-c=1.9.4=h6a678d5_0 + - mkl=2023.1.0=h6d00ec8_46342 + - mkl-service=2.4.0=py310h5eee18b_1 + - mkl_fft=1.3.6=py310h1128e8f_1 + - mkl_random=1.2.2=py310h1128e8f_1 + - ncurses=6.4=h6a678d5_0 + - nettle=3.7.3=hbbd107a_1 + - nsight-compute=2023.1.1.4=0 + - numpy=1.25.0=py310h5f9d8c6_0 + - numpy-base=1.25.0=py310hb5e798b_0 + - openh264=2.1.1=h4ff587b_0 + - openssl=3.0.9=h7f8727e_0 + - pillow=9.4.0=py310h6a678d5_0 + - pip=23.1.2=py310h06a4308_0 + - pycparser=2.21=pyhd3eb1b0_0 + - pyopenssl=23.0.0=py310h06a4308_0 + - pysocks=1.7.1=py310h06a4308_0 + - python=3.10.11=h955ad1f_3 + - pytorch=1.13.1=py3.10_cuda11.6_cudnn8.3.2_0 + - pytorch-cuda=11.6=h867d48c_1 + - pytorch-mutex=1.0=cuda + - readline=8.2=h5eee18b_0 + - sqlite=3.41.2=h5eee18b_0 + - tbb=2021.8.0=hdb19cb5_0 + - tk=8.6.12=h1ccaba5_0 + - torchaudio=0.13.1=py310_cu116 + - torchvision=0.14.1=py310_cu116 + - typing_extensions=4.6.3=py310h06a4308_0 + - urllib3=1.26.16=py310h06a4308_0 + - x264=1!157.20191217=h7b6447c_0 + - xz=5.4.2=h5eee18b_0 + - zlib=1.2.13=h5eee18b_0 + - zstd=1.5.5=hc292b87_0 + - pip: + - absl-py==2.1.0 + - addict==2.4.0 + - aiohappyeyeballs==2.6.1 + - aiohttp==3.12.15 + - aiosignal==1.4.0 + - aliyun-python-sdk-core==2.15.1 + - aliyun-python-sdk-kms==2.16.3 + - asttokens==2.4.1 + - async-timeout==5.0.1 + - attrs==25.3.0 + - basicsr==0.0.0 + - beautifulsoup4==4.12.3 + - cachetools==5.3.3 + - click==8.1.7 + - colorama==0.4.6 + - contourpy==1.2.1 + - crcmod==1.7 + - cycler==0.12.1 + - datasets==4.0.0 + - decorator==5.1.1 + - dill==0.3.8 + - einops==0.8.0 + - exceptiongroup==1.2.2 + - executing==2.0.1 + - filelock==3.14.0 + - fonttools==4.51.0 + - frozenlist==1.7.0 + - fsspec==2024.5.0 + - ftfy==6.2.0 + - future==1.0.0 + - fvcore==0.1.5.post20221221 + - gdown==5.2.0 + - google-auth==2.29.0 + - google-auth-oauthlib==1.0.0 + - grpcio==1.63.0 + - h5py==3.11.0 + - hf-xet==1.1.7 + - huggingface-hub==0.34.4 + - imageio==2.34.1 + - importlib-metadata==7.1.0 + - iopath==0.1.10 + - ipdb==0.13.13 + - ipython==8.26.0 + - jedi==0.19.1 + - jmespath==0.10.0 + - kiwisolver==1.4.5 + - lazy-loader==0.4 + - lmdb==1.7.2 + - markdown==3.6 + - markdown-it-py==3.0.0 + - markupsafe==2.1.5 + - matplotlib==3.9.0 + - matplotlib-inline==0.1.7 + - mdurl==0.1.2 + - mmcv==2.0.0 + - mmdet==3.3.0 + - mmengine==0.10.4 + - mmsegmentation==1.2.2 + - model-index==0.1.11 + - modelscope==1.30.0 + - multidict==6.6.4 + - multiprocess==0.70.16 + - networkx==3.3 + - oauthlib==3.2.2 + - omegaconf==2.4.0.dev3 + - opencv-python==4.9.0.80 + - opendatalab==0.0.10 + - openmim==0.3.9 + - openxlab==0.0.38 + - ordered-set==4.1.0 + - oss2==2.17.0 + - packaging==24.0 + - pandas==2.2.2 + - parso==0.8.4 + - pexpect==4.9.0 + - platformdirs==4.2.2 + - portalocker==3.2.0 + - prettytable==3.10.0 + - prompt-toolkit==3.0.47 + - propcache==0.3.2 + - protobuf==3.20.3 + - psutil==6.0.0 + - ptyprocess==0.7.0 + - pure-eval==0.2.2 + - pyarrow==21.0.0 + - pyasn1==0.6.0 + - pyasn1-modules==0.4.0 + - pycocotools==2.0.7 + - pycryptodome==3.20.0 + - pygments==2.18.0 + - pyparsing==3.1.2 + - python-dateutil==2.9.0.post0 + - pytz==2023.4 + - pyyaml==6.0.1 + - regex==2024.5.15 + - requests==2.32.4 + - requests-oauthlib==2.0.0 + - rich==13.4.2 + - rsa==4.9 + - safetensors==0.4.3 + - scikit-image==0.23.2 + - scipy==1.13.0 + - seaborn==0.13.2 + - setuptools==60.2.0 + - shapely==2.0.4 + - six==1.16.0 + - smmap==5.0.1 + - soupsieve==2.6 + - stack-data==0.6.3 + - tabulate==0.9.0 + - tb-nightly==2.21.0a20250719 + - tensorboard==2.13.0 + - tensorboard-data-server==0.7.0 + - tensorboardx==2.6 + - termcolor==2.3.0 + - terminaltables==3.1.10 + - thop==0.1.1-2209072238 + - threadpoolctl==3.1.0 + - tifffile==2024.5.10 + - timm==1.0.3 + - tomli==2.0.1 + - tqdm==4.67.1 + - traitlets==5.14.3 + - tzdata==2024.1 + - wcwidth==0.2.13 + - werkzeug==3.0.3 + - wheel==0.26.0 + - xxhash==3.5.0 + - yacs==0.1.8 + - yapf==0.40.2 + - yarl==1.20.1 + - zipp==3.18.2 +prefix: /home/suyuejiao/anaconda3/envs/mmseg diff --git a/third-party/InterFormer/mmseg/datasets/transforms/__init__.py b/third-party/InterFormer/mmseg/datasets/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..125f07081810c980ebc6ded077bcf5dfd955cfcf --- /dev/null +++ b/third-party/InterFormer/mmseg/datasets/transforms/__init__.py @@ -0,0 +1,30 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .formatting import PackSegInputs +from .loading import (LoadAnnotations, LoadBiomedicalAnnotation, + LoadBiomedicalData, LoadBiomedicalImageFromFile, + LoadDepthAnnotation, LoadImageFromNDArray, + LoadMultipleRSImageFromFile, LoadSingleRSImageFromFile) +# yapf: disable +from .transforms import (CLAHE, AdjustGamma, Albu, BioMedical3DPad, + BioMedical3DRandomCrop, BioMedical3DRandomFlip, + BioMedicalGaussianBlur, BioMedicalGaussianNoise, + BioMedicalRandomGamma, ConcatCDInput, GenerateEdge, + PhotoMetricDistortion, RandomCrop, RandomCutOut, + RandomDepthMix, RandomFlip, RandomMosaic, + RandomRotate, RandomRotFlip, Rerange, Resize, + ResizeShortestEdge, ResizeToMultiple, RGB2Gray, + SegRescale) + +# yapf: enable +__all__ = [ + 'LoadAnnotations', 'RandomCrop', 'BioMedical3DRandomCrop', 'SegRescale', + 'PhotoMetricDistortion', 'RandomRotate', 'AdjustGamma', 'CLAHE', 'Rerange', + 'RGB2Gray', 'RandomCutOut', 'RandomMosaic', 'PackSegInputs', + 'ResizeToMultiple', 'LoadImageFromNDArray', 'LoadBiomedicalImageFromFile', + 'LoadBiomedicalAnnotation', 'LoadBiomedicalData', 'GenerateEdge', + 'ResizeShortestEdge', 'BioMedicalGaussianNoise', 'BioMedicalGaussianBlur', + 'BioMedical3DRandomFlip', 'BioMedicalRandomGamma', 'BioMedical3DPad', + 'RandomRotFlip', 'Albu', 'LoadSingleRSImageFromFile', 'ConcatCDInput', + 'LoadMultipleRSImageFromFile', 'LoadDepthAnnotation', 'RandomDepthMix', + 'RandomFlip', 'Resize' +] diff --git a/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..526f423698ed7d897f3b7b36c284cf2091751b3e Binary files /dev/null and b/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/formatting.cpython-38.pyc b/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/formatting.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08fa39201f26e691b7a6a67c86476ba7cc5f145f Binary files /dev/null and b/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/formatting.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/loading.cpython-38.pyc b/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/loading.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a52b8fd8fa0e25e0f2fa980e3be316ec4b1d59c Binary files /dev/null and b/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/loading.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/transforms.cpython-38.pyc b/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/transforms.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10e90096b816c862bee11a91c862890f555c1ae1 Binary files /dev/null and b/third-party/InterFormer/mmseg/datasets/transforms/__pycache__/transforms.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/datasets/transforms/formatting.py b/third-party/InterFormer/mmseg/datasets/transforms/formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..bd250551e98ffc9decaa2e168943821501844c1f --- /dev/null +++ b/third-party/InterFormer/mmseg/datasets/transforms/formatting.py @@ -0,0 +1,112 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import numpy as np +from mmcv.transforms import to_tensor +from mmcv.transforms.base import BaseTransform +from mmengine.structures import PixelData + +from mmseg.registry import TRANSFORMS +from mmseg.structures import SegDataSample + + +@TRANSFORMS.register_module() +class PackSegInputs(BaseTransform): + """Pack the inputs data for the semantic segmentation. + + The ``img_meta`` item is always populated. The contents of the + ``img_meta`` dictionary depends on ``meta_keys``. By default this includes: + + - ``img_path``: filename of the image + + - ``ori_shape``: original shape of the image as a tuple (h, w, c) + + - ``img_shape``: shape of the image input to the network as a tuple \ + (h, w, c). Note that images may be zero padded on the \ + bottom/right if the batch tensor is larger than this shape. + + - ``pad_shape``: shape of padded images + + - ``scale_factor``: a float indicating the preprocessing scale + + - ``flip``: a boolean indicating if image flip transform was used + + - ``flip_direction``: the flipping direction + + Args: + meta_keys (Sequence[str], optional): Meta keys to be packed from + ``SegDataSample`` and collected in ``data[img_metas]``. + Default: ``('img_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction')`` + """ + + def __init__(self, + meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label')): + self.meta_keys = meta_keys + + def transform(self, results: dict) -> dict: + """Method to pack the input data. + + Args: + results (dict): Result dict from the data pipeline. + + Returns: + dict: + + - 'inputs' (obj:`torch.Tensor`): The forward data of models. + - 'data_sample' (obj:`SegDataSample`): The annotation info of the + sample. + """ + packed_results = dict() + if 'img' in results: + img = results['img'] + if len(img.shape) < 3: + img = np.expand_dims(img, -1) + if not img.flags.c_contiguous: + img = to_tensor(np.ascontiguousarray(img.transpose(2, 0, 1))) + else: + img = img.transpose(2, 0, 1) + img = to_tensor(img).contiguous() + packed_results['inputs'] = img + + data_sample = SegDataSample() + if 'gt_seg_map' in results: + if len(results['gt_seg_map'].shape) == 2: + data = to_tensor(results['gt_seg_map'][None, + ...].astype(np.int64)) + else: + warnings.warn('Please pay attention your ground truth ' + 'segmentation map, usually the segmentation ' + 'map is 2D, but got ' + f'{results["gt_seg_map"].shape}') + data = to_tensor(results['gt_seg_map'].astype(np.int64)) + gt_sem_seg_data = dict(data=data) + data_sample.gt_sem_seg = PixelData(**gt_sem_seg_data) + + if 'gt_edge_map' in results: + gt_edge_data = dict( + data=to_tensor(results['gt_edge_map'][None, + ...].astype(np.int64))) + data_sample.set_data(dict(gt_edge_map=PixelData(**gt_edge_data))) + + if 'gt_depth_map' in results: + gt_depth_data = dict( + data=to_tensor(results['gt_depth_map'][None, ...])) + data_sample.set_data(dict(gt_depth_map=PixelData(**gt_depth_data))) + + img_meta = {} + for key in self.meta_keys: + if key in results: + img_meta[key] = results[key] + data_sample.set_metainfo(img_meta) + packed_results['data_samples'] = data_sample + + return packed_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(meta_keys={self.meta_keys})' + return repr_str diff --git a/third-party/InterFormer/mmseg/datasets/transforms/loading.py b/third-party/InterFormer/mmseg/datasets/transforms/loading.py new file mode 100644 index 0000000000000000000000000000000000000000..c28937e55eed0aeb9c9cf2f3cd367541a7e81d07 --- /dev/null +++ b/third-party/InterFormer/mmseg/datasets/transforms/loading.py @@ -0,0 +1,771 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings +from pathlib import Path +from typing import Dict, Optional, Union + +import mmcv +import mmengine.fileio as fileio +import numpy as np +from mmcv.transforms import BaseTransform +from mmcv.transforms import LoadAnnotations as MMCV_LoadAnnotations +from mmcv.transforms import LoadImageFromFile + +from mmseg.registry import TRANSFORMS +from mmseg.utils import datafrombytes + +try: + from osgeo import gdal +except ImportError: + gdal = None + + +@TRANSFORMS.register_module() +class LoadAnnotations(MMCV_LoadAnnotations): + """Load annotations for semantic segmentation provided by dataset. + + The annotation format is as the following: + + .. code-block:: python + + { + # Filename of semantic segmentation ground truth file. + 'seg_map_path': 'a/b/c' + } + + After this module, the annotation has been changed to the format below: + + .. code-block:: python + + { + # in str + 'seg_fields': List + # In uint8 type. + 'gt_seg_map': np.ndarray (H, W) + } + + Required Keys: + + - seg_map_path (str): Path of semantic segmentation ground truth file. + + Added Keys: + + - seg_fields (List) + - gt_seg_map (np.uint8) + + Args: + reduce_zero_label (bool, optional): Whether reduce all label value + by 1. Usually used for datasets where 0 is background label. + Defaults to None. + imdecode_backend (str): The image decoding backend type. The backend + argument for :func:``mmcv.imfrombytes``. + See :fun:``mmcv.imfrombytes`` for details. + Defaults to 'pillow'. + backend_args (dict): Arguments to instantiate a file backend. + See https://mmengine.readthedocs.io/en/latest/api/fileio.htm + for details. Defaults to None. + Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. + """ + + def __init__( + self, + reduce_zero_label=None, + backend_args=None, + imdecode_backend='pillow', + ) -> None: + super().__init__( + with_bbox=False, + with_label=False, + with_seg=True, + with_keypoints=False, + imdecode_backend=imdecode_backend, + backend_args=backend_args) + self.reduce_zero_label = reduce_zero_label + if self.reduce_zero_label is not None: + warnings.warn('`reduce_zero_label` will be deprecated, ' + 'if you would like to ignore the zero label, please ' + 'set `reduce_zero_label=True` when dataset ' + 'initialized') + self.imdecode_backend = imdecode_backend + + def _load_seg_map(self, results: dict) -> None: + """Private function to load semantic segmentation annotations. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded semantic segmentation annotations. + """ + + img_bytes = fileio.get( + results['seg_map_path'], backend_args=self.backend_args) + gt_semantic_seg = mmcv.imfrombytes( + img_bytes, flag='unchanged', + backend=self.imdecode_backend).squeeze().astype(np.uint8) + + # reduce zero_label + if self.reduce_zero_label is None: + self.reduce_zero_label = results['reduce_zero_label'] + assert self.reduce_zero_label == results['reduce_zero_label'], \ + 'Initialize dataset with `reduce_zero_label` as ' \ + f'{results["reduce_zero_label"]} but when load annotation ' \ + f'the `reduce_zero_label` is {self.reduce_zero_label}' + if self.reduce_zero_label: + # avoid using underflow conversion + gt_semantic_seg[gt_semantic_seg == 0] = 255 + gt_semantic_seg = gt_semantic_seg - 1 + gt_semantic_seg[gt_semantic_seg == 254] = 255 + # modify if custom classes + if results.get('label_map', None) is not None: + # Add deep copy to solve bug of repeatedly + # replace `gt_semantic_seg`, which is reported in + # https://github.com/open-mmlab/mmsegmentation/pull/1445/ + gt_semantic_seg_copy = gt_semantic_seg.copy() + for old_id, new_id in results['label_map'].items(): + gt_semantic_seg[gt_semantic_seg_copy == old_id] = new_id + results['gt_seg_map'] = gt_semantic_seg + results['seg_fields'].append('gt_seg_map') + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(reduce_zero_label={self.reduce_zero_label}, ' + repr_str += f"imdecode_backend='{self.imdecode_backend}', " + repr_str += f'backend_args={self.backend_args})' + return repr_str + + +@TRANSFORMS.register_module() +class LoadImageFromNDArray(LoadImageFromFile): + """Load an image from ``results['img']``. + + Similar with :obj:`LoadImageFromFile`, but the image has been loaded as + :obj:`np.ndarray` in ``results['img']``. Can be used when loading image + from webcam. + + Required Keys: + + - img + + Modified Keys: + + - img + - img_path + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + """ + + def transform(self, results: dict) -> dict: + """Transform function to add image meta information. + + Args: + results (dict): Result dict with Webcam read image in + ``results['img']``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + + img = results['img'] + if self.to_float32: + img = img.astype(np.float32) + + results['img_path'] = None + results['img'] = img + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + return results + + +@TRANSFORMS.register_module() +class LoadBiomedicalImageFromFile(BaseTransform): + """Load an biomedical mage from file. + + Required Keys: + + - img_path + + Added Keys: + + - img (np.ndarray): Biomedical image with shape (N, Z, Y, X) by default, + N is the number of modalities, and data type is float32 + if set to_float32 = True, or float64 if decode_backend is 'nifti' and + to_float32 is False. + - img_shape + - ori_shape + + Args: + decode_backend (str): The data decoding backend type. Options are + 'numpy'and 'nifti', and there is a convention that when backend is + 'nifti' the axis of data loaded is XYZ, and when backend is + 'numpy', the the axis is ZYX. The data will be transposed if the + backend is 'nifti'. Defaults to 'nifti'. + to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z. + Defaults to False. + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an float64 array. + Defaults to True. + backend_args (dict, Optional): Arguments to instantiate a file backend. + See https://mmengine.readthedocs.io/en/latest/api/fileio.htm + for details. Defaults to None. + Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. + """ + + def __init__(self, + decode_backend: str = 'nifti', + to_xyz: bool = False, + to_float32: bool = True, + backend_args: Optional[dict] = None) -> None: + self.decode_backend = decode_backend + self.to_xyz = to_xyz + self.to_float32 = to_float32 + self.backend_args = backend_args.copy() if backend_args else None + + def transform(self, results: Dict) -> Dict: + """Functions to load image. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + + filename = results['img_path'] + + data_bytes = fileio.get(filename, self.backend_args) + img = datafrombytes(data_bytes, backend=self.decode_backend) + + if self.to_float32: + img = img.astype(np.float32) + + if len(img.shape) == 3: + img = img[None, ...] + + if self.decode_backend == 'nifti': + img = img.transpose(0, 3, 2, 1) + + if self.to_xyz: + img = img.transpose(0, 3, 2, 1) + + results['img'] = img + results['img_shape'] = img.shape[1:] + results['ori_shape'] = img.shape[1:] + return results + + def __repr__(self): + repr_str = (f'{self.__class__.__name__}(' + f"decode_backend='{self.decode_backend}', " + f'to_xyz={self.to_xyz}, ' + f'to_float32={self.to_float32}, ' + f'backend_args={self.backend_args})') + return repr_str + + +@TRANSFORMS.register_module() +class LoadBiomedicalAnnotation(BaseTransform): + """Load ``seg_map`` annotation provided by biomedical dataset. + + The annotation format is as the following: + + .. code-block:: python + + { + 'gt_seg_map': np.ndarray (X, Y, Z) or (Z, Y, X) + } + + Required Keys: + + - seg_map_path + + Added Keys: + + - gt_seg_map (np.ndarray): Biomedical seg map with shape (Z, Y, X) by + default, and data type is float32 if set to_float32 = True, or + float64 if decode_backend is 'nifti' and to_float32 is False. + + Args: + decode_backend (str): The data decoding backend type. Options are + 'numpy'and 'nifti', and there is a convention that when backend is + 'nifti' the axis of data loaded is XYZ, and when backend is + 'numpy', the the axis is ZYX. The data will be transposed if the + backend is 'nifti'. Defaults to 'nifti'. + to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z. + Defaults to False. + to_float32 (bool): Whether to convert the loaded seg map to a float32 + numpy array. If set to False, the loaded image is an float64 array. + Defaults to True. + backend_args (dict, Optional): Arguments to instantiate a file backend. + See :class:`mmengine.fileio` for details. + Defaults to None. + Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. + """ + + def __init__(self, + decode_backend: str = 'nifti', + to_xyz: bool = False, + to_float32: bool = True, + backend_args: Optional[dict] = None) -> None: + super().__init__() + self.decode_backend = decode_backend + self.to_xyz = to_xyz + self.to_float32 = to_float32 + self.backend_args = backend_args.copy() if backend_args else None + + def transform(self, results: Dict) -> Dict: + """Functions to load image. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + data_bytes = fileio.get(results['seg_map_path'], self.backend_args) + gt_seg_map = datafrombytes(data_bytes, backend=self.decode_backend) + + if self.to_float32: + gt_seg_map = gt_seg_map.astype(np.float32) + + if self.decode_backend == 'nifti': + gt_seg_map = gt_seg_map.transpose(2, 1, 0) + + if self.to_xyz: + gt_seg_map = gt_seg_map.transpose(2, 1, 0) + + results['gt_seg_map'] = gt_seg_map + return results + + def __repr__(self): + repr_str = (f'{self.__class__.__name__}(' + f"decode_backend='{self.decode_backend}', " + f'to_xyz={self.to_xyz}, ' + f'to_float32={self.to_float32}, ' + f'backend_args={self.backend_args})') + return repr_str + + +@TRANSFORMS.register_module() +class LoadBiomedicalData(BaseTransform): + """Load an biomedical image and annotation from file. + + The loading data format is as the following: + + .. code-block:: python + + { + 'img': np.ndarray data[:-1, X, Y, Z] + 'seg_map': np.ndarray data[-1, X, Y, Z] + } + + + Required Keys: + + - img_path + + Added Keys: + + - img (np.ndarray): Biomedical image with shape (N, Z, Y, X) by default, + N is the number of modalities. + - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape + (Z, Y, X) by default. + - img_shape + - ori_shape + + Args: + with_seg (bool): Whether to parse and load the semantic segmentation + annotation. Defaults to False. + decode_backend (str): The data decoding backend type. Options are + 'numpy'and 'nifti', and there is a convention that when backend is + 'nifti' the axis of data loaded is XYZ, and when backend is + 'numpy', the the axis is ZYX. The data will be transposed if the + backend is 'nifti'. Defaults to 'nifti'. + to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z. + Defaults to False. + backend_args (dict, Optional): Arguments to instantiate a file backend. + See https://mmengine.readthedocs.io/en/latest/api/fileio.htm + for details. Defaults to None. + Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. + """ + + def __init__(self, + with_seg=False, + decode_backend: str = 'numpy', + to_xyz: bool = False, + backend_args: Optional[dict] = None) -> None: # noqa + self.with_seg = with_seg + self.decode_backend = decode_backend + self.to_xyz = to_xyz + self.backend_args = backend_args.copy() if backend_args else None + + def transform(self, results: Dict) -> Dict: + """Functions to load image. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + data_bytes = fileio.get(results['img_path'], self.backend_args) + data = datafrombytes(data_bytes, backend=self.decode_backend) + # img is 4D data (N, X, Y, Z), N is the number of protocol + img = data[:-1, :] + + if self.decode_backend == 'nifti': + img = img.transpose(0, 3, 2, 1) + + if self.to_xyz: + img = img.transpose(0, 3, 2, 1) + + results['img'] = img + results['img_shape'] = img.shape[1:] + results['ori_shape'] = img.shape[1:] + + if self.with_seg: + gt_seg_map = data[-1, :] + if self.decode_backend == 'nifti': + gt_seg_map = gt_seg_map.transpose(2, 1, 0) + + if self.to_xyz: + gt_seg_map = gt_seg_map.transpose(2, 1, 0) + results['gt_seg_map'] = gt_seg_map + return results + + def __repr__(self) -> str: + repr_str = (f'{self.__class__.__name__}(' + f'with_seg={self.with_seg}, ' + f"decode_backend='{self.decode_backend}', " + f'to_xyz={self.to_xyz}, ' + f'backend_args={self.backend_args})') + return repr_str + + +@TRANSFORMS.register_module() +class InferencerLoader(BaseTransform): + """Load an image from ``results['img']``. + + Similar with :obj:`LoadImageFromFile`, but the image has been loaded as + :obj:`np.ndarray` in ``results['img']``. Can be used when loading image + from webcam. + + Required Keys: + + - img + + Modified Keys: + + - img + - img_path + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + """ + + def __init__(self, **kwargs) -> None: + super().__init__() + self.from_file = TRANSFORMS.build( + dict(type='LoadImageFromFile', **kwargs)) + self.from_ndarray = TRANSFORMS.build( + dict(type='LoadImageFromNDArray', **kwargs)) + + def transform(self, single_input: Union[str, np.ndarray, dict]) -> dict: + """Transform function to add image meta information. + + Args: + results (dict): Result dict with Webcam read image in + ``results['img']``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + if isinstance(single_input, str): + inputs = dict(img_path=single_input) + elif isinstance(single_input, np.ndarray): + inputs = dict(img=single_input) + elif isinstance(single_input, dict): + inputs = single_input + else: + raise NotImplementedError + + if 'img' in inputs: + return self.from_ndarray(inputs) + return self.from_file(inputs) + + +@TRANSFORMS.register_module() +class LoadSingleRSImageFromFile(BaseTransform): + """Load a Remote Sensing mage from file. + + Required Keys: + + - img_path + + Modified Keys: + + - img + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is a float64 array. + Defaults to True. + """ + + def __init__(self, to_float32: bool = True): + self.to_float32 = to_float32 + + if gdal is None: + raise RuntimeError('gdal is not installed') + + def transform(self, results: Dict) -> Dict: + """Functions to load image. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + + filename = results['img_path'] + ds = gdal.Open(filename) + if ds is None: + raise Exception(f'Unable to open file: {filename}') + img = np.einsum('ijk->jki', ds.ReadAsArray()) + + if self.to_float32: + img = img.astype(np.float32) + + results['img'] = img + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + return results + + def __repr__(self): + repr_str = (f'{self.__class__.__name__}(' + f'to_float32={self.to_float32})') + return repr_str + + +@TRANSFORMS.register_module() +class LoadMultipleRSImageFromFile(BaseTransform): + """Load two Remote Sensing mage from file. + + Required Keys: + + - img_path + - img_path2 + + Modified Keys: + + - img + - img2 + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is a float64 array. + Defaults to True. + """ + + def __init__(self, to_float32: bool = True): + if gdal is None: + raise RuntimeError('gdal is not installed') + self.to_float32 = to_float32 + + def transform(self, results: Dict) -> Dict: + """Functions to load image. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + + filename = results['img_path'] + filename2 = results['img_path2'] + + ds = gdal.Open(filename) + ds2 = gdal.Open(filename2) + + if ds is None: + raise Exception(f'Unable to open file: {filename}') + if ds2 is None: + raise Exception(f'Unable to open file: {filename2}') + + img = np.einsum('ijk->jki', ds.ReadAsArray()) + img2 = np.einsum('ijk->jki', ds2.ReadAsArray()) + + if self.to_float32: + img = img.astype(np.float32) + img2 = img2.astype(np.float32) + + if img.shape != img2.shape: + raise Exception(f'Image shapes do not match:' + f' {img.shape} vs {img2.shape}') + + results['img'] = img + results['img2'] = img2 + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + return results + + def __repr__(self): + repr_str = (f'{self.__class__.__name__}(' + f'to_float32={self.to_float32})') + return repr_str + + +@TRANSFORMS.register_module() +class LoadDepthAnnotation(BaseTransform): + """Load ``depth_map`` annotation provided by depth estimation dataset. + + The annotation format is as the following: + + .. code-block:: python + + { + 'gt_depth_map': np.ndarray [Y, X] + } + + Required Keys: + + - seg_depth_path + + Added Keys: + + - gt_depth_map (np.ndarray): Depth map with shape (Y, X) by + default, and data type is float32 if set to_float32 = True. + - depth_rescale_factor (float): The rescale factor of depth map, which + can be used to recover the original value of depth map. + + Args: + decode_backend (str): The data decoding backend type. Options are + 'numpy', 'nifti', and 'cv2'. Defaults to 'cv2'. + to_float32 (bool): Whether to convert the loaded depth map to a float32 + numpy array. If set to False, the loaded image is an uint16 array. + Defaults to True. + depth_rescale_factor (float): Factor to rescale the depth value to + limit the range. Defaults to 1.0. + backend_args (dict, Optional): Arguments to instantiate a file backend. + See :class:`mmengine.fileio` for details. + Defaults to None. + Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. + """ + + def __init__(self, + decode_backend: str = 'cv2', + to_float32: bool = True, + depth_rescale_factor: float = 1.0, + backend_args: Optional[dict] = None) -> None: + super().__init__() + self.decode_backend = decode_backend + self.to_float32 = to_float32 + self.depth_rescale_factor = depth_rescale_factor + self.backend_args = backend_args.copy() if backend_args else None + + def transform(self, results: Dict) -> Dict: + """Functions to load depth map. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded depth map. + """ + data_bytes = fileio.get(results['depth_map_path'], self.backend_args) + gt_depth_map = datafrombytes(data_bytes, backend=self.decode_backend) + + if self.to_float32: + gt_depth_map = gt_depth_map.astype(np.float32) + + gt_depth_map *= self.depth_rescale_factor + results['gt_depth_map'] = gt_depth_map + results['seg_fields'].append('gt_depth_map') + results['depth_rescale_factor'] = self.depth_rescale_factor + return results + + def __repr__(self): + repr_str = (f'{self.__class__.__name__}(' + f"decode_backend='{self.decode_backend}', " + f'to_float32={self.to_float32}, ' + f'backend_args={self.backend_args})') + return repr_str + + +@TRANSFORMS.register_module() +class LoadImageFromNpyFile(LoadImageFromFile): + """Load an image from ``results['img_path']``. + + Required Keys: + + - img_path + + Modified Keys: + + - img + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + """ + + def transform(self, results: dict) -> Optional[dict]: + """Functions to load image. + + Args: + results (dict): Result dict from + :class:`mmengine.dataset.BaseDataset`. + + Returns: + dict: The dict contains loaded image and meta information. + """ + + filename = results['img_path'] + + try: + if Path(filename).suffix in ['.npy', '.npz']: + img = np.load(filename) + else: + if self.file_client_args is not None: + file_client = fileio.FileClient.infer_client( + self.file_client_args, filename) + img_bytes = file_client.get(filename) + else: + img_bytes = fileio.get( + filename, backend_args=self.backend_args) + img = mmcv.imfrombytes( + img_bytes, + flag=self.color_type, + backend=self.imdecode_backend) + except Exception as e: + if self.ignore_empty: + return None + else: + raise e + + # in some cases, images are not read successfully, the img would be + # `None`, refer to https://github.com/open-mmlab/mmpretrain/issues/1427 + assert img is not None, f'failed to load image: {filename}' + if self.to_float32: + img = img.astype(np.float32) + + results['img'] = img + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + return results diff --git a/third-party/InterFormer/mmseg/datasets/transforms/transforms.py b/third-party/InterFormer/mmseg/datasets/transforms/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..64e23230c66e2cbe13370770646c83e936443398 --- /dev/null +++ b/third-party/InterFormer/mmseg/datasets/transforms/transforms.py @@ -0,0 +1,2537 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import inspect +import warnings +from typing import Dict, List, Optional, Sequence, Tuple, Union + +import cv2 +import mmcv +import mmengine +import numpy as np +from mmcv.transforms import RandomFlip as MMCV_RandomFlip +from mmcv.transforms import Resize as MMCV_Resize +from mmcv.transforms.base import BaseTransform +from mmcv.transforms.utils import cache_randomness +from mmengine.utils import is_tuple_of +from numpy import random +from scipy.ndimage import gaussian_filter + +from mmseg.datasets.dataset_wrappers import MultiImageMixDataset +from mmseg.registry import TRANSFORMS + +try: + import albumentations + from albumentations import Compose + ALBU_INSTALLED = True +except ImportError: + albumentations = None + Compose = None + ALBU_INSTALLED = False + + +@TRANSFORMS.register_module() +class ResizeToMultiple(BaseTransform): + """Resize images & seg to multiple of divisor. + + Required Keys: + + - img + - gt_seg_map + + Modified Keys: + + - img + - img_shape + - pad_shape + + Args: + size_divisor (int): images and gt seg maps need to resize to multiple + of size_divisor. Default: 32. + interpolation (str, optional): The interpolation mode of image resize. + Default: None + """ + + def __init__(self, size_divisor=32, interpolation=None): + self.size_divisor = size_divisor + self.interpolation = interpolation + + def transform(self, results: dict) -> dict: + """Call function to resize images, semantic segmentation map to + multiple of size divisor. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Resized results, 'img_shape', 'pad_shape' keys are updated. + """ + # Align image to multiple of size divisor. + img = results['img'] + img = mmcv.imresize_to_multiple( + img, + self.size_divisor, + scale_factor=1, + interpolation=self.interpolation + if self.interpolation else 'bilinear') + + results['img'] = img + results['img_shape'] = img.shape[:2] + results['pad_shape'] = img.shape[:2] + + # Align segmentation map to multiple of size divisor. + for key in results.get('seg_fields', []): + gt_seg = results[key] + gt_seg = mmcv.imresize_to_multiple( + gt_seg, + self.size_divisor, + scale_factor=1, + interpolation='nearest') + results[key] = gt_seg + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += (f'(size_divisor={self.size_divisor}, ' + f'interpolation={self.interpolation})') + return repr_str + + +@TRANSFORMS.register_module() +class Rerange(BaseTransform): + """Rerange the image pixel value. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + min_value (float or int): Minimum value of the reranged image. + Default: 0. + max_value (float or int): Maximum value of the reranged image. + Default: 255. + """ + + def __init__(self, min_value=0, max_value=255): + assert isinstance(min_value, float) or isinstance(min_value, int) + assert isinstance(max_value, float) or isinstance(max_value, int) + assert min_value < max_value + self.min_value = min_value + self.max_value = max_value + + def transform(self, results: dict) -> dict: + """Call function to rerange images. + + Args: + results (dict): Result dict from loading pipeline. + Returns: + dict: Reranged results. + """ + + img = results['img'] + img_min_value = np.min(img) + img_max_value = np.max(img) + + assert img_min_value < img_max_value + # rerange to [0, 1] + img = (img - img_min_value) / (img_max_value - img_min_value) + # rerange to [min_value, max_value] + img = img * (self.max_value - self.min_value) + self.min_value + results['img'] = img + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(min_value={self.min_value}, max_value={self.max_value})' + return repr_str + + +@TRANSFORMS.register_module() +class CLAHE(BaseTransform): + """Use CLAHE method to process the image. + + See `ZUIDERVELD,K. Contrast Limited Adaptive Histogram Equalization[J]. + Graphics Gems, 1994:474-485.` for more information. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + clip_limit (float): Threshold for contrast limiting. Default: 40.0. + tile_grid_size (tuple[int]): Size of grid for histogram equalization. + Input image will be divided into equally sized rectangular tiles. + It defines the number of tiles in row and column. Default: (8, 8). + """ + + def __init__(self, clip_limit=40.0, tile_grid_size=(8, 8)): + assert isinstance(clip_limit, (float, int)) + self.clip_limit = clip_limit + assert is_tuple_of(tile_grid_size, int) + assert len(tile_grid_size) == 2 + self.tile_grid_size = tile_grid_size + + def transform(self, results: dict) -> dict: + """Call function to Use CLAHE method process images. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Processed results. + """ + + for i in range(results['img'].shape[2]): + results['img'][:, :, i] = mmcv.clahe( + np.array(results['img'][:, :, i], dtype=np.uint8), + self.clip_limit, self.tile_grid_size) + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(clip_limit={self.clip_limit}, ' \ + f'tile_grid_size={self.tile_grid_size})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomCrop(BaseTransform): + """Random crop the image & seg. + + Required Keys: + + - img + - gt_seg_map + + Modified Keys: + + - img + - img_shape + - gt_seg_map + + + Args: + crop_size (Union[int, Tuple[int, int]]): Expected size after cropping + with the format of (h, w). If set to an integer, then cropping + width and height are equal to this integer. + cat_max_ratio (float): The maximum ratio that single category could + occupy. + ignore_index (int): The label index to be ignored. Default: 255 + """ + + def __init__(self, + crop_size: Union[int, Tuple[int, int]], + cat_max_ratio: float = 1., + ignore_index: int = 255): + super().__init__() + assert isinstance(crop_size, int) or ( + isinstance(crop_size, tuple) and len(crop_size) == 2 + ), 'The expected crop_size is an integer, or a tuple containing two ' + 'intergers' + + if isinstance(crop_size, int): + crop_size = (crop_size, crop_size) + assert crop_size[0] > 0 and crop_size[1] > 0 + self.crop_size = crop_size + self.cat_max_ratio = cat_max_ratio + self.ignore_index = ignore_index + + @cache_randomness + def crop_bbox(self, results: dict) -> tuple: + """get a crop bounding box. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + tuple: Coordinates of the cropped image. + """ + + def generate_crop_bbox(img: np.ndarray) -> tuple: + """Randomly get a crop bounding box. + + Args: + img (np.ndarray): Original input image. + + Returns: + tuple: Coordinates of the cropped image. + """ + + margin_h = max(img.shape[0] - self.crop_size[0], 0) + margin_w = max(img.shape[1] - self.crop_size[1], 0) + offset_h = np.random.randint(0, margin_h + 1) + offset_w = np.random.randint(0, margin_w + 1) + crop_y1, crop_y2 = offset_h, offset_h + self.crop_size[0] + crop_x1, crop_x2 = offset_w, offset_w + self.crop_size[1] + + return crop_y1, crop_y2, crop_x1, crop_x2 + + img = results['img'] + crop_bbox = generate_crop_bbox(img) + if self.cat_max_ratio < 1.: + # Repeat 10 times + for _ in range(10): + seg_temp = self.crop(results['gt_seg_map'], crop_bbox) + labels, cnt = np.unique(seg_temp, return_counts=True) + cnt = cnt[labels != self.ignore_index] + if len(cnt) > 1 and np.max(cnt) / np.sum( + cnt) < self.cat_max_ratio: + break + crop_bbox = generate_crop_bbox(img) + + return crop_bbox + + def crop(self, img: np.ndarray, crop_bbox: tuple) -> np.ndarray: + """Crop from ``img`` + + Args: + img (np.ndarray): Original input image. + crop_bbox (tuple): Coordinates of the cropped image. + + Returns: + np.ndarray: The cropped image. + """ + + crop_y1, crop_y2, crop_x1, crop_x2 = crop_bbox + img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...] + return img + + def transform(self, results: dict) -> dict: + """Transform function to randomly crop images, semantic segmentation + maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Randomly cropped results, 'img_shape' key in result dict is + updated according to crop size. + """ + + img = results['img'] + crop_bbox = self.crop_bbox(results) + + # crop the image + img = self.crop(img, crop_bbox) + + # crop semantic seg + for key in results.get('seg_fields', []): + results[key] = self.crop(results[key], crop_bbox) + + results['img'] = img + results['img_shape'] = img.shape[:2] + return results + + def __repr__(self): + return self.__class__.__name__ + f'(crop_size={self.crop_size})' + + +@TRANSFORMS.register_module() +class RandomRotate(BaseTransform): + """Rotate the image & seg. + + Required Keys: + + - img + - gt_seg_map + + Modified Keys: + + - img + - gt_seg_map + + Args: + prob (float): The rotation probability. + degree (float, tuple[float]): Range of degrees to select from. If + degree is a number instead of tuple like (min, max), + the range of degree will be (``-degree``, ``+degree``) + pad_val (float, optional): Padding value of image. Default: 0. + seg_pad_val (float, optional): Padding value of segmentation map. + Default: 255. + center (tuple[float], optional): Center point (w, h) of the rotation in + the source image. If not specified, the center of the image will be + used. Default: None. + auto_bound (bool): Whether to adjust the image size to cover the whole + rotated image. Default: False + """ + + def __init__(self, + prob, + degree, + pad_val=0, + seg_pad_val=255, + center=None, + auto_bound=False): + self.prob = prob + assert prob >= 0 and prob <= 1 + if isinstance(degree, (float, int)): + assert degree > 0, f'degree {degree} should be positive' + self.degree = (-degree, degree) + else: + self.degree = degree + assert len(self.degree) == 2, f'degree {self.degree} should be a ' \ + f'tuple of (min, max)' + self.pal_val = pad_val + self.seg_pad_val = seg_pad_val + self.center = center + self.auto_bound = auto_bound + + @cache_randomness + def generate_degree(self): + return np.random.rand() < self.prob, np.random.uniform( + min(*self.degree), max(*self.degree)) + + def transform(self, results: dict) -> dict: + """Call function to rotate image, semantic segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Rotated results. + """ + + rotate, degree = self.generate_degree() + if rotate: + # rotate image + results['img'] = mmcv.imrotate( + results['img'], + angle=degree, + border_value=self.pal_val, + center=self.center, + auto_bound=self.auto_bound) + + # rotate segs + for key in results.get('seg_fields', []): + results[key] = mmcv.imrotate( + results[key], + angle=degree, + border_value=self.seg_pad_val, + center=self.center, + auto_bound=self.auto_bound, + interpolation='nearest') + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' \ + f'degree={self.degree}, ' \ + f'pad_val={self.pal_val}, ' \ + f'seg_pad_val={self.seg_pad_val}, ' \ + f'center={self.center}, ' \ + f'auto_bound={self.auto_bound})' + return repr_str + + +@TRANSFORMS.register_module() +class RGB2Gray(BaseTransform): + """Convert RGB image to grayscale image. + + Required Keys: + + - img + + Modified Keys: + + - img + - img_shape + + This transform calculate the weighted mean of input image channels with + ``weights`` and then expand the channels to ``out_channels``. When + ``out_channels`` is None, the number of output channels is the same as + input channels. + + Args: + out_channels (int): Expected number of output channels after + transforming. Default: None. + weights (tuple[float]): The weights to calculate the weighted mean. + Default: (0.299, 0.587, 0.114). + """ + + def __init__(self, out_channels=None, weights=(0.299, 0.587, 0.114)): + assert out_channels is None or out_channels > 0 + self.out_channels = out_channels + assert isinstance(weights, tuple) + for item in weights: + assert isinstance(item, (float, int)) + self.weights = weights + + def transform(self, results: dict) -> dict: + """Call function to convert RGB image to grayscale image. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with grayscale image. + """ + img = results['img'] + assert len(img.shape) == 3 + assert img.shape[2] == len(self.weights) + weights = np.array(self.weights).reshape((1, 1, -1)) + img = (img * weights).sum(2, keepdims=True) + if self.out_channels is None: + img = img.repeat(weights.shape[2], axis=2) + else: + img = img.repeat(self.out_channels, axis=2) + + results['img'] = img + results['img_shape'] = img.shape + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(out_channels={self.out_channels}, ' \ + f'weights={self.weights})' + return repr_str + + +@TRANSFORMS.register_module() +class AdjustGamma(BaseTransform): + """Using gamma correction to process the image. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + gamma (float or int): Gamma value used in gamma correction. + Default: 1.0. + """ + + def __init__(self, gamma=1.0): + assert isinstance(gamma, float) or isinstance(gamma, int) + assert gamma > 0 + self.gamma = gamma + inv_gamma = 1.0 / gamma + self.table = np.array([(i / 255.0)**inv_gamma * 255 + for i in np.arange(256)]).astype('uint8') + + def transform(self, results: dict) -> dict: + """Call function to process the image with gamma correction. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Processed results. + """ + + results['img'] = mmcv.lut_transform( + np.array(results['img'], dtype=np.uint8), self.table) + + return results + + def __repr__(self): + return self.__class__.__name__ + f'(gamma={self.gamma})' + + +@TRANSFORMS.register_module() +class SegRescale(BaseTransform): + """Rescale semantic segmentation maps. + + Required Keys: + + - gt_seg_map + + Modified Keys: + + - gt_seg_map + + Args: + scale_factor (float): The scale factor of the final output. + """ + + def __init__(self, scale_factor=1): + self.scale_factor = scale_factor + + def transform(self, results: dict) -> dict: + """Call function to scale the semantic segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with semantic segmentation map scaled. + """ + for key in results.get('seg_fields', []): + if self.scale_factor != 1: + results[key] = mmcv.imrescale( + results[key], self.scale_factor, interpolation='nearest') + return results + + def __repr__(self): + return self.__class__.__name__ + f'(scale_factor={self.scale_factor})' + + +@TRANSFORMS.register_module() +class PhotoMetricDistortion(BaseTransform): + """Apply photometric distortion to image sequentially, every transformation + is applied with a probability of 0.5. The position of random contrast is in + second or second to last. + + 1. random brightness + 2. random contrast (mode 0) + 3. convert color from BGR to HSV + 4. random saturation + 5. random hue + 6. convert color from HSV to BGR + 7. random contrast (mode 1) + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + brightness_delta (int): delta of brightness. + contrast_range (tuple): range of contrast. + saturation_range (tuple): range of saturation. + hue_delta (int): delta of hue. + """ + + def __init__(self, + brightness_delta: int = 32, + contrast_range: Sequence[float] = (0.5, 1.5), + saturation_range: Sequence[float] = (0.5, 1.5), + hue_delta: int = 18): + self.brightness_delta = brightness_delta + self.contrast_lower, self.contrast_upper = contrast_range + self.saturation_lower, self.saturation_upper = saturation_range + self.hue_delta = hue_delta + + def convert(self, + img: np.ndarray, + alpha: int = 1, + beta: int = 0) -> np.ndarray: + """Multiple with alpha and add beat with clip. + + Args: + img (np.ndarray): The input image. + alpha (int): Image weights, change the contrast/saturation + of the image. Default: 1 + beta (int): Image bias, change the brightness of the + image. Default: 0 + + Returns: + np.ndarray: The transformed image. + """ + + img = img.astype(np.float32) * alpha + beta + img = np.clip(img, 0, 255) + return img.astype(np.uint8) + + def brightness(self, img: np.ndarray) -> np.ndarray: + """Brightness distortion. + + Args: + img (np.ndarray): The input image. + Returns: + np.ndarray: Image after brightness change. + """ + + if random.randint(2): + return self.convert( + img, + beta=random.uniform(-self.brightness_delta, + self.brightness_delta)) + return img + + def contrast(self, img: np.ndarray) -> np.ndarray: + """Contrast distortion. + + Args: + img (np.ndarray): The input image. + Returns: + np.ndarray: Image after contrast change. + """ + + if random.randint(2): + return self.convert( + img, + alpha=random.uniform(self.contrast_lower, self.contrast_upper)) + return img + + def saturation(self, img: np.ndarray) -> np.ndarray: + """Saturation distortion. + + Args: + img (np.ndarray): The input image. + Returns: + np.ndarray: Image after saturation change. + """ + + if random.randint(2): + img = mmcv.bgr2hsv(img) + img[:, :, 1] = self.convert( + img[:, :, 1], + alpha=random.uniform(self.saturation_lower, + self.saturation_upper)) + img = mmcv.hsv2bgr(img) + return img + + def hue(self, img: np.ndarray) -> np.ndarray: + """Hue distortion. + + Args: + img (np.ndarray): The input image. + Returns: + np.ndarray: Image after hue change. + """ + + if random.randint(2): + img = mmcv.bgr2hsv(img) + img[:, :, + 0] = (img[:, :, 0].astype(int) + + random.randint(-self.hue_delta, self.hue_delta)) % 180 + img = mmcv.hsv2bgr(img) + return img + + def transform(self, results: dict) -> dict: + """Transform function to perform photometric distortion on images. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images distorted. + """ + + img = results['img'] + # random brightness + img = self.brightness(img) + + # mode == 0 --> do random contrast first + # mode == 1 --> do random contrast last + mode = random.randint(2) + if mode == 1: + img = self.contrast(img) + + # random saturation + img = self.saturation(img) + + # random hue + img = self.hue(img) + + # random contrast + if mode == 0: + img = self.contrast(img) + + results['img'] = img + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += (f'(brightness_delta={self.brightness_delta}, ' + f'contrast_range=({self.contrast_lower}, ' + f'{self.contrast_upper}), ' + f'saturation_range=({self.saturation_lower}, ' + f'{self.saturation_upper}), ' + f'hue_delta={self.hue_delta})') + return repr_str + + +@TRANSFORMS.register_module() +class RandomCutOut(BaseTransform): + """CutOut operation. + + Randomly drop some regions of image used in + `Cutout `_. + + Required Keys: + + - img + - gt_seg_map + + Modified Keys: + + - img + - gt_seg_map + + Args: + prob (float): cutout probability. + n_holes (int | tuple[int, int]): Number of regions to be dropped. + If it is given as a list, number of holes will be randomly + selected from the closed interval [`n_holes[0]`, `n_holes[1]`]. + cutout_shape (tuple[int, int] | list[tuple[int, int]]): The candidate + shape of dropped regions. It can be `tuple[int, int]` to use a + fixed cutout shape, or `list[tuple[int, int]]` to randomly choose + shape from the list. + cutout_ratio (tuple[float, float] | list[tuple[float, float]]): The + candidate ratio of dropped regions. It can be `tuple[float, float]` + to use a fixed ratio or `list[tuple[float, float]]` to randomly + choose ratio from the list. Please note that `cutout_shape` + and `cutout_ratio` cannot be both given at the same time. + fill_in (tuple[float, float, float] | tuple[int, int, int]): The value + of pixel to fill in the dropped regions. Default: (0, 0, 0). + seg_fill_in (int): The labels of pixel to fill in the dropped regions. + If seg_fill_in is None, skip. Default: None. + """ + + def __init__(self, + prob, + n_holes, + cutout_shape=None, + cutout_ratio=None, + fill_in=(0, 0, 0), + seg_fill_in=None): + + assert 0 <= prob and prob <= 1 + assert (cutout_shape is None) ^ (cutout_ratio is None), \ + 'Either cutout_shape or cutout_ratio should be specified.' + assert (isinstance(cutout_shape, (list, tuple)) + or isinstance(cutout_ratio, (list, tuple))) + if isinstance(n_holes, tuple): + assert len(n_holes) == 2 and 0 <= n_holes[0] < n_holes[1] + else: + n_holes = (n_holes, n_holes) + if seg_fill_in is not None: + assert (isinstance(seg_fill_in, int) and 0 <= seg_fill_in + and seg_fill_in <= 255) + self.prob = prob + self.n_holes = n_holes + self.fill_in = fill_in + self.seg_fill_in = seg_fill_in + self.with_ratio = cutout_ratio is not None + self.candidates = cutout_ratio if self.with_ratio else cutout_shape + if not isinstance(self.candidates, list): + self.candidates = [self.candidates] + + @cache_randomness + def do_cutout(self): + return np.random.rand() < self.prob + + @cache_randomness + def generate_patches(self, results): + cutout = self.do_cutout() + + h, w, _ = results['img'].shape + if cutout: + n_holes = np.random.randint(self.n_holes[0], self.n_holes[1] + 1) + else: + n_holes = 0 + x1_lst = [] + y1_lst = [] + index_lst = [] + for _ in range(n_holes): + x1_lst.append(np.random.randint(0, w)) + y1_lst.append(np.random.randint(0, h)) + index_lst.append(np.random.randint(0, len(self.candidates))) + return cutout, n_holes, x1_lst, y1_lst, index_lst + + def transform(self, results: dict) -> dict: + """Call function to drop some regions of image.""" + cutout, n_holes, x1_lst, y1_lst, index_lst = self.generate_patches( + results) + if cutout: + h, w, c = results['img'].shape + for i in range(n_holes): + x1 = x1_lst[i] + y1 = y1_lst[i] + index = index_lst[i] + if not self.with_ratio: + cutout_w, cutout_h = self.candidates[index] + else: + cutout_w = int(self.candidates[index][0] * w) + cutout_h = int(self.candidates[index][1] * h) + + x2 = np.clip(x1 + cutout_w, 0, w) + y2 = np.clip(y1 + cutout_h, 0, h) + results['img'][y1:y2, x1:x2, :] = self.fill_in + + if self.seg_fill_in is not None: + for key in results.get('seg_fields', []): + results[key][y1:y2, x1:x2] = self.seg_fill_in + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'n_holes={self.n_holes}, ' + repr_str += (f'cutout_ratio={self.candidates}, ' if self.with_ratio + else f'cutout_shape={self.candidates}, ') + repr_str += f'fill_in={self.fill_in}, ' + repr_str += f'seg_fill_in={self.seg_fill_in})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomRotFlip(BaseTransform): + """Rotate and flip the image & seg or just rotate the image & seg. + + Required Keys: + + - img + - gt_seg_map + + Modified Keys: + + - img + - gt_seg_map + + Args: + rotate_prob (float): The probability of rotate image. + flip_prob (float): The probability of rotate&flip image. + degree (float, tuple[float]): Range of degrees to select from. If + degree is a number instead of tuple like (min, max), + the range of degree will be (``-degree``, ``+degree``) + """ + + def __init__(self, rotate_prob=0.5, flip_prob=0.5, degree=(-20, 20)): + self.rotate_prob = rotate_prob + self.flip_prob = flip_prob + assert 0 <= rotate_prob <= 1 and 0 <= flip_prob <= 1 + if isinstance(degree, (float, int)): + assert degree > 0, f'degree {degree} should be positive' + self.degree = (-degree, degree) + else: + self.degree = degree + assert len(self.degree) == 2, f'degree {self.degree} should be a ' \ + f'tuple of (min, max)' + + def random_rot_flip(self, results: dict) -> dict: + k = np.random.randint(0, 4) + results['img'] = np.rot90(results['img'], k) + for key in results.get('seg_fields', []): + results[key] = np.rot90(results[key], k) + axis = np.random.randint(0, 2) + results['img'] = np.flip(results['img'], axis=axis).copy() + for key in results.get('seg_fields', []): + results[key] = np.flip(results[key], axis=axis).copy() + return results + + def random_rotate(self, results: dict) -> dict: + angle = np.random.uniform(min(*self.degree), max(*self.degree)) + results['img'] = mmcv.imrotate(results['img'], angle=angle) + for key in results.get('seg_fields', []): + results[key] = mmcv.imrotate(results[key], angle=angle) + return results + + def transform(self, results: dict) -> dict: + """Call function to rotate or rotate & flip image, semantic + segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Rotated or rotated & flipped results. + """ + rotate_flag = 0 + if random.random() < self.rotate_prob: + results = self.random_rotate(results) + rotate_flag = 1 + if random.random() < self.flip_prob and rotate_flag == 0: + results = self.random_rot_flip(results) + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(rotate_prob={self.rotate_prob}, ' \ + f'flip_prob={self.flip_prob}, ' \ + f'degree={self.degree})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomFlip(MMCV_RandomFlip): + """Flip the image & bbox & segmentation map. Added or Updated + keys: flip, flip_direction, img, gt_bboxes, gt_seg_map, and gt_depth_map. + There are 3 flip modes: + + - ``prob`` is float, ``direction`` is string: the image will be + ``direction``ly flipped with probability of ``prob`` . + E.g., ``prob=0.5``, ``direction='horizontal'``, + then image will be horizontally flipped with probability of 0.5. + + - ``prob`` is float, ``direction`` is list of string: the image will + be ``direction[i]``ly flipped with probability of + ``prob/len(direction)``. + E.g., ``prob=0.5``, ``direction=['horizontal', 'vertical']``, + then image will be horizontally flipped with probability of 0.25, + vertically with probability of 0.25. + + - ``prob`` is list of float, ``direction`` is list of string: + given ``len(prob) == len(direction)``, the image will + be ``direction[i]``ly flipped with probability of ``prob[i]``. + E.g., ``prob=[0.3, 0.5]``, ``direction=['horizontal', + 'vertical']``, then image will be horizontally flipped with + probability of 0.3, vertically with probability of 0.5. + + Required Keys: + + - img + - gt_bboxes (optional) + - gt_seg_map (optional) + - gt_depth_map (optional) + + Modified Keys: + + - img + - gt_bboxes (optional) + - gt_seg_map (optional) + - gt_depth_map (optional) + + Added Keys: + + - flip + - flip_direction + - swap_seg_labels (optional) + + Args: + prob (float | list[float], optional): The flipping probability. + Defaults to None. + direction(str | list[str]): The flipping direction. Options + If input is a list, the length must equal ``prob``. Each + element in ``prob`` indicates the flip probability of + corresponding direction. Defaults to 'horizontal'. + swap_seg_labels (list, optional): The label pair need to be swapped + for ground truth, like 'left arm' and 'right arm' need to be + swapped after horizontal flipping. For example, ``[(1, 5)]``, + where 1/5 is the label of the left/right arm. Defaults to None. + """ + + def _flip(self, results: dict) -> None: + """Flip images, bounding boxes and semantic segmentation map.""" + # flip image + results['img'] = mmcv.imflip( + results['img'], direction=results['flip_direction']) + + img_shape = results['img'].shape[:2] + + # flip bboxes + if results.get('gt_bboxes', None) is not None: + results['gt_bboxes'] = self._flip_bbox(results['gt_bboxes'], + img_shape, + results['flip_direction']) + + # flip seg map + for key in results.get('seg_fields', []): + if results.get(key, None) is not None: + results[key] = self._flip_seg_map( + results[key], direction=results['flip_direction']).copy() + results['swap_seg_labels'] = self.swap_seg_labels + + +@TRANSFORMS.register_module() +class Resize(MMCV_Resize): + """Resize images & seg & depth map. + + This transform resizes the input image according to ``scale`` or + ``scale_factor``. Seg map, depth map and other relative annotations are + then resized with the same scale factor. + if ``scale`` and ``scale_factor`` are both set, it will use ``scale`` to + resize. + + Required Keys: + + - img + - gt_seg_map (optional) + - gt_depth_map (optional) + + Modified Keys: + + - img + - gt_seg_map + - gt_depth_map + + Added Keys: + + - scale + - scale_factor + - keep_ratio + + Args: + scale (int or tuple): Images scales for resizing. Defaults to None + scale_factor (float or tuple[float]): Scale factors for resizing. + Defaults to None. + keep_ratio (bool): Whether to keep the aspect ratio when resizing the + image. Defaults to False. + clip_object_border (bool): Whether to clip the objects + outside the border of the image. In some dataset like MOT17, the gt + bboxes are allowed to cross the border of images. Therefore, we + don't need to clip the gt bboxes in these cases. Defaults to True. + backend (str): Image resize backend, choices are 'cv2' and 'pillow'. + These two backends generates slightly different results. Defaults + to 'cv2'. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def _resize_seg(self, results: dict) -> None: + """Resize semantic segmentation map with ``results['scale']``.""" + for seg_key in results.get('seg_fields', []): + if results.get(seg_key, None) is not None: + if self.keep_ratio: + gt_seg = mmcv.imrescale( + results[seg_key], + results['scale'], + interpolation='nearest', + backend=self.backend) + else: + gt_seg = mmcv.imresize( + results[seg_key], + results['scale'], + interpolation='nearest', + backend=self.backend) + results[seg_key] = gt_seg + + +@TRANSFORMS.register_module() +class RandomMosaic(BaseTransform): + """Mosaic augmentation. Given 4 images, mosaic transform combines them into + one output image. The output image is composed of the parts from each sub- + image. + + .. code:: text + + mosaic transform + center_x + +------------------------------+ + | pad | pad | + | +-----------+ | + | | | | + | | image1 |--------+ | + | | | | | + | | | image2 | | + center_y |----+-------------+-----------| + | | cropped | | + |pad | image3 | image4 | + | | | | + +----|-------------+-----------+ + | | + +-------------+ + + The mosaic transform steps are as follows: + 1. Choose the mosaic center as the intersections of 4 images + 2. Get the left top image according to the index, and randomly + sample another 3 images from the custom dataset. + 3. Sub image will be cropped if image is larger than mosaic patch + + Required Keys: + + - img + - gt_seg_map + - mix_results + + Modified Keys: + + - img + - img_shape + - ori_shape + - gt_seg_map + + Args: + prob (float): mosaic probability. + img_scale (Sequence[int]): Image size after mosaic pipeline of + a single image. The size of the output image is four times + that of a single image. The output image comprises 4 single images. + Default: (640, 640). + center_ratio_range (Sequence[float]): Center ratio range of mosaic + output. Default: (0.5, 1.5). + pad_val (int): Pad value. Default: 0. + seg_pad_val (int): Pad value of segmentation map. Default: 255. + """ + + def __init__(self, + prob, + img_scale=(640, 640), + center_ratio_range=(0.5, 1.5), + pad_val=0, + seg_pad_val=255): + assert 0 <= prob and prob <= 1 + assert isinstance(img_scale, tuple) + self.prob = prob + self.img_scale = img_scale + self.center_ratio_range = center_ratio_range + self.pad_val = pad_val + self.seg_pad_val = seg_pad_val + + @cache_randomness + def do_mosaic(self): + return np.random.rand() < self.prob + + def transform(self, results: dict) -> dict: + """Call function to make a mosaic of image. + + Args: + results (dict): Result dict. + + Returns: + dict: Result dict with mosaic transformed. + """ + mosaic = self.do_mosaic() + if mosaic: + results = self._mosaic_transform_img(results) + results = self._mosaic_transform_seg(results) + return results + + def get_indices(self, dataset: MultiImageMixDataset) -> list: + """Call function to collect indices. + + Args: + dataset (:obj:`MultiImageMixDataset`): The dataset. + + Returns: + list: indices. + """ + + indices = [random.randint(0, len(dataset)) for _ in range(3)] + return indices + + @cache_randomness + def generate_mosaic_center(self): + # mosaic center x, y + center_x = int( + random.uniform(*self.center_ratio_range) * self.img_scale[1]) + center_y = int( + random.uniform(*self.center_ratio_range) * self.img_scale[0]) + return center_x, center_y + + def _mosaic_transform_img(self, results: dict) -> dict: + """Mosaic transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + + assert 'mix_results' in results + if len(results['img'].shape) == 3: + c = results['img'].shape[2] + mosaic_img = np.full( + (int(self.img_scale[0] * 2), int(self.img_scale[1] * 2), c), + self.pad_val, + dtype=results['img'].dtype) + else: + mosaic_img = np.full( + (int(self.img_scale[0] * 2), int(self.img_scale[1] * 2)), + self.pad_val, + dtype=results['img'].dtype) + + # mosaic center x, y + self.center_x, self.center_y = self.generate_mosaic_center() + center_position = (self.center_x, self.center_y) + + loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') + for i, loc in enumerate(loc_strs): + if loc == 'top_left': + result_patch = copy.deepcopy(results) + else: + result_patch = copy.deepcopy(results['mix_results'][i - 1]) + + img_i = result_patch['img'] + h_i, w_i = img_i.shape[:2] + # keep_ratio resize + scale_ratio_i = min(self.img_scale[0] / h_i, + self.img_scale[1] / w_i) + img_i = mmcv.imresize( + img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i))) + + # compute the combine parameters + paste_coord, crop_coord = self._mosaic_combine( + loc, center_position, img_i.shape[:2][::-1]) + x1_p, y1_p, x2_p, y2_p = paste_coord + x1_c, y1_c, x2_c, y2_c = crop_coord + + # crop and paste image + mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c] + + results['img'] = mosaic_img + results['img_shape'] = mosaic_img.shape + results['ori_shape'] = mosaic_img.shape + + return results + + def _mosaic_transform_seg(self, results: dict) -> dict: + """Mosaic transform function for label annotations. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + + assert 'mix_results' in results + for key in results.get('seg_fields', []): + mosaic_seg = np.full( + (int(self.img_scale[0] * 2), int(self.img_scale[1] * 2)), + self.seg_pad_val, + dtype=results[key].dtype) + + # mosaic center x, y + center_position = (self.center_x, self.center_y) + + loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') + for i, loc in enumerate(loc_strs): + if loc == 'top_left': + result_patch = copy.deepcopy(results) + else: + result_patch = copy.deepcopy(results['mix_results'][i - 1]) + + gt_seg_i = result_patch[key] + h_i, w_i = gt_seg_i.shape[:2] + # keep_ratio resize + scale_ratio_i = min(self.img_scale[0] / h_i, + self.img_scale[1] / w_i) + gt_seg_i = mmcv.imresize( + gt_seg_i, + (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i)), + interpolation='nearest') + + # compute the combine parameters + paste_coord, crop_coord = self._mosaic_combine( + loc, center_position, gt_seg_i.shape[:2][::-1]) + x1_p, y1_p, x2_p, y2_p = paste_coord + x1_c, y1_c, x2_c, y2_c = crop_coord + + # crop and paste image + mosaic_seg[y1_p:y2_p, x1_p:x2_p] = \ + gt_seg_i[y1_c:y2_c, x1_c:x2_c] + + results[key] = mosaic_seg + + return results + + def _mosaic_combine(self, loc: str, center_position_xy: Sequence[float], + img_shape_wh: Sequence[int]) -> tuple: + """Calculate global coordinate of mosaic image and local coordinate of + cropped sub-image. + + Args: + loc (str): Index for the sub-image, loc in ('top_left', + 'top_right', 'bottom_left', 'bottom_right'). + center_position_xy (Sequence[float]): Mixing center for 4 images, + (x, y). + img_shape_wh (Sequence[int]): Width and height of sub-image + + Returns: + tuple[tuple[float]]: Corresponding coordinate of pasting and + cropping + - paste_coord (tuple): paste corner coordinate in mosaic image. + - crop_coord (tuple): crop corner coordinate in mosaic image. + """ + + assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right') + if loc == 'top_left': + # index0 to top left part of image + x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ + max(center_position_xy[1] - img_shape_wh[1], 0), \ + center_position_xy[0], \ + center_position_xy[1] + crop_coord = img_shape_wh[0] - (x2 - x1), img_shape_wh[1] - ( + y2 - y1), img_shape_wh[0], img_shape_wh[1] + + elif loc == 'top_right': + # index1 to top right part of image + x1, y1, x2, y2 = center_position_xy[0], \ + max(center_position_xy[1] - img_shape_wh[1], 0), \ + min(center_position_xy[0] + img_shape_wh[0], + self.img_scale[1] * 2), \ + center_position_xy[1] + crop_coord = 0, img_shape_wh[1] - (y2 - y1), min( + img_shape_wh[0], x2 - x1), img_shape_wh[1] + + elif loc == 'bottom_left': + # index2 to bottom left part of image + x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ + center_position_xy[1], \ + center_position_xy[0], \ + min(self.img_scale[0] * 2, center_position_xy[1] + + img_shape_wh[1]) + crop_coord = img_shape_wh[0] - (x2 - x1), 0, img_shape_wh[0], min( + y2 - y1, img_shape_wh[1]) + + else: + # index3 to bottom right part of image + x1, y1, x2, y2 = center_position_xy[0], \ + center_position_xy[1], \ + min(center_position_xy[0] + img_shape_wh[0], + self.img_scale[1] * 2), \ + min(self.img_scale[0] * 2, center_position_xy[1] + + img_shape_wh[1]) + crop_coord = 0, 0, min(img_shape_wh[0], + x2 - x1), min(y2 - y1, img_shape_wh[1]) + + paste_coord = x1, y1, x2, y2 + return paste_coord, crop_coord + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'img_scale={self.img_scale}, ' + repr_str += f'center_ratio_range={self.center_ratio_range}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'seg_pad_val={self.pad_val})' + return repr_str + + +@TRANSFORMS.register_module() +class GenerateEdge(BaseTransform): + """Generate Edge for CE2P approach. + + Edge will be used to calculate loss of + `CE2P `_. + + Modified from https://github.com/liutinglt/CE2P/blob/master/dataset/target_generation.py # noqa:E501 + + Required Keys: + + - img_shape + - gt_seg_map + + Added Keys: + - gt_edge_map (np.ndarray, uint8): The edge annotation generated from the + seg map by extracting border between different semantics. + + Args: + edge_width (int): The width of edge. Default to 3. + ignore_index (int): Index that will be ignored. Default to 255. + """ + + def __init__(self, edge_width: int = 3, ignore_index: int = 255) -> None: + super().__init__() + self.edge_width = edge_width + self.ignore_index = ignore_index + + def transform(self, results: Dict) -> Dict: + """Call function to generate edge from segmentation map. + + Args: + results (dict): Result dict. + + Returns: + dict: Result dict with edge mask. + """ + h, w = results['img_shape'] + edge = np.zeros((h, w), dtype=np.uint8) + seg_map = results['gt_seg_map'] + + # down + edge_down = edge[1:h, :] + edge_down[(seg_map[1:h, :] != seg_map[:h - 1, :]) + & (seg_map[1:h, :] != self.ignore_index) & + (seg_map[:h - 1, :] != self.ignore_index)] = 1 + # left + edge_left = edge[:, :w - 1] + edge_left[(seg_map[:, :w - 1] != seg_map[:, 1:w]) + & (seg_map[:, :w - 1] != self.ignore_index) & + (seg_map[:, 1:w] != self.ignore_index)] = 1 + # up_left + edge_upleft = edge[:h - 1, :w - 1] + edge_upleft[(seg_map[:h - 1, :w - 1] != seg_map[1:h, 1:w]) + & (seg_map[:h - 1, :w - 1] != self.ignore_index) & + (seg_map[1:h, 1:w] != self.ignore_index)] = 1 + # up_right + edge_upright = edge[:h - 1, 1:w] + edge_upright[(seg_map[:h - 1, 1:w] != seg_map[1:h, :w - 1]) + & (seg_map[:h - 1, 1:w] != self.ignore_index) & + (seg_map[1:h, :w - 1] != self.ignore_index)] = 1 + + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, + (self.edge_width, self.edge_width)) + edge = cv2.dilate(edge, kernel) + + results['gt_edge_map'] = edge + results['edge_width'] = self.edge_width + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'edge_width={self.edge_width}, ' + repr_str += f'ignore_index={self.ignore_index})' + return repr_str + + +@TRANSFORMS.register_module() +class ResizeShortestEdge(BaseTransform): + """Resize the image and mask while keeping the aspect ratio unchanged. + + Modified from https://github.com/facebookresearch/detectron2/blob/main/detectron2/data/transforms/augmentation_impl.py#L130 # noqa:E501 + Copyright (c) Facebook, Inc. and its affiliates. + Licensed under the Apache-2.0 License + + This transform attempts to scale the shorter edge to the given + `scale`, as long as the longer edge does not exceed `max_size`. + If `max_size` is reached, then downscale so that the longer + edge does not exceed `max_size`. + + Required Keys: + + - img + - gt_seg_map (optional) + + Modified Keys: + + - img + - img_shape + - gt_seg_map (optional)) + + Added Keys: + + - scale + - scale_factor + - keep_ratio + + + Args: + scale (Union[int, Tuple[int, int]]): The target short edge length. + If it's tuple, will select the min value as the short edge length. + max_size (int): The maximum allowed longest edge length. + """ + + def __init__(self, scale: Union[int, Tuple[int, int]], + max_size: int) -> None: + super().__init__() + self.scale = scale + self.max_size = max_size + + # Create a empty Resize object + self.resize = TRANSFORMS.build({ + 'type': 'Resize', + 'scale': 0, + 'keep_ratio': True + }) + + def _get_output_shape(self, img, short_edge_length) -> Tuple[int, int]: + """Compute the target image shape with the given `short_edge_length`. + + Args: + img (np.ndarray): The input image. + short_edge_length (Union[int, Tuple[int, int]]): The target short + edge length. If it's tuple, will select the min value as the + short edge length. + """ + h, w = img.shape[:2] + if isinstance(short_edge_length, int): + size = short_edge_length * 1.0 + elif isinstance(short_edge_length, tuple): + size = min(short_edge_length) * 1.0 + scale = size / min(h, w) + if h < w: + new_h, new_w = size, scale * w + else: + new_h, new_w = scale * h, size + + if max(new_h, new_w) > self.max_size: + scale = self.max_size * 1.0 / max(new_h, new_w) + new_h *= scale + new_w *= scale + + new_h = int(new_h + 0.5) + new_w = int(new_w + 0.5) + return (new_w, new_h) + + def transform(self, results: Dict) -> Dict: + self.resize.scale = self._get_output_shape(results['img'], self.scale) + return self.resize(results) + + +@TRANSFORMS.register_module() +class BioMedical3DRandomCrop(BaseTransform): + """Crop the input patch for medical image & segmentation mask. + + Required Keys: + + - img (np.ndarray): Biomedical image with shape (N, Z, Y, X), + N is the number of modalities, and data type is float32. + - gt_seg_map (np.ndarray, optional): Biomedical semantic segmentation mask + with shape (Z, Y, X). + + Modified Keys: + + - img + - img_shape + - gt_seg_map (optional) + + Args: + crop_shape (Union[int, Tuple[int, int, int]]): Expected size after + cropping with the format of (z, y, x). If set to an integer, + then cropping width and height are equal to this integer. + keep_foreground (bool): If keep_foreground is True, it will sample a + voxel of foreground classes randomly, and will take it as the + center of the crop bounding-box. Default to True. + """ + + def __init__(self, + crop_shape: Union[int, Tuple[int, int, int]], + keep_foreground: bool = True): + super().__init__() + assert isinstance(crop_shape, int) or ( + isinstance(crop_shape, tuple) and len(crop_shape) == 3 + ), 'The expected crop_shape is an integer, or a tuple containing ' + 'three integers' + + if isinstance(crop_shape, int): + crop_shape = (crop_shape, crop_shape, crop_shape) + assert crop_shape[0] > 0 and crop_shape[1] > 0 and crop_shape[2] > 0 + self.crop_shape = crop_shape + self.keep_foreground = keep_foreground + + def random_sample_location(self, seg_map: np.ndarray) -> dict: + """sample foreground voxel when keep_foreground is True. + + Args: + seg_map (np.ndarray): gt seg map. + + Returns: + dict: Coordinates of selected foreground voxel. + """ + num_samples = 10000 + # at least 1% of the class voxels need to be selected, + # otherwise it may be too sparse + min_percent_coverage = 0.01 + class_locs = {} + foreground_classes = [] + all_classes = np.unique(seg_map) + for c in all_classes: + if c == 0: + # to avoid the segmentation mask full of background 0 + # and the class_locs is just void dictionary {} when it return + # there add a void list for background 0. + class_locs[c] = [] + else: + all_locs = np.argwhere(seg_map == c) + target_num_samples = min(num_samples, len(all_locs)) + target_num_samples = max( + target_num_samples, + int(np.ceil(len(all_locs) * min_percent_coverage))) + + selected = all_locs[np.random.choice( + len(all_locs), target_num_samples, replace=False)] + class_locs[c] = selected + foreground_classes.append(c) + + selected_voxel = None + if len(foreground_classes) > 0: + selected_class = np.random.choice(foreground_classes) + voxels_of_that_class = class_locs[selected_class] + selected_voxel = voxels_of_that_class[np.random.choice( + len(voxels_of_that_class))] + + return selected_voxel + + def random_generate_crop_bbox(self, margin_z: int, margin_y: int, + margin_x: int) -> tuple: + """Randomly get a crop bounding box. + + Args: + seg_map (np.ndarray): Ground truth segmentation map. + + Returns: + tuple: Coordinates of the cropped image. + """ + offset_z = np.random.randint(0, margin_z + 1) + offset_y = np.random.randint(0, margin_y + 1) + offset_x = np.random.randint(0, margin_x + 1) + crop_z1, crop_z2 = offset_z, offset_z + self.crop_shape[0] + crop_y1, crop_y2 = offset_y, offset_y + self.crop_shape[1] + crop_x1, crop_x2 = offset_x, offset_x + self.crop_shape[2] + + return crop_z1, crop_z2, crop_y1, crop_y2, crop_x1, crop_x2 + + def generate_margin(self, results: dict) -> tuple: + """Generate margin of crop bounding-box. + + If keep_foreground is True, it will sample a voxel of foreground + classes randomly, and will take it as the center of the bounding-box, + and return the margin between of the bounding-box and image. + If keep_foreground is False, it will return the difference from crop + shape and image shape. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + tuple: The margin for 3 dimensions of crop bounding-box and image. + """ + + seg_map = results['gt_seg_map'] + if self.keep_foreground: + selected_voxel = self.random_sample_location(seg_map) + if selected_voxel is None: + # this only happens if some image does not contain + # foreground voxels at all + warnings.warn(f'case does not contain any foreground classes' + f': {results["img_path"]}') + margin_z = max(seg_map.shape[0] - self.crop_shape[0], 0) + margin_y = max(seg_map.shape[1] - self.crop_shape[1], 0) + margin_x = max(seg_map.shape[2] - self.crop_shape[2], 0) + else: + margin_z = max(0, selected_voxel[0] - self.crop_shape[0] // 2) + margin_y = max(0, selected_voxel[1] - self.crop_shape[1] // 2) + margin_x = max(0, selected_voxel[2] - self.crop_shape[2] // 2) + margin_z = max( + 0, min(seg_map.shape[0] - self.crop_shape[0], margin_z)) + margin_y = max( + 0, min(seg_map.shape[1] - self.crop_shape[1], margin_y)) + margin_x = max( + 0, min(seg_map.shape[2] - self.crop_shape[2], margin_x)) + else: + margin_z = max(seg_map.shape[0] - self.crop_shape[0], 0) + margin_y = max(seg_map.shape[1] - self.crop_shape[1], 0) + margin_x = max(seg_map.shape[2] - self.crop_shape[2], 0) + + return margin_z, margin_y, margin_x + + def crop(self, img: np.ndarray, crop_bbox: tuple) -> np.ndarray: + """Crop from ``img`` + + Args: + img (np.ndarray): Original input image. + crop_bbox (tuple): Coordinates of the cropped image. + + Returns: + np.ndarray: The cropped image. + """ + crop_z1, crop_z2, crop_y1, crop_y2, crop_x1, crop_x2 = crop_bbox + if len(img.shape) == 3: + # crop seg map + img = img[crop_z1:crop_z2, crop_y1:crop_y2, crop_x1:crop_x2] + else: + # crop image + assert len(img.shape) == 4 + img = img[:, crop_z1:crop_z2, crop_y1:crop_y2, crop_x1:crop_x2] + return img + + def transform(self, results: dict) -> dict: + """Transform function to randomly crop images, semantic segmentation + maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Randomly cropped results, 'img_shape' key in result dict is + updated according to crop size. + """ + margin = self.generate_margin(results) + crop_bbox = self.random_generate_crop_bbox(*margin) + + # crop the image + img = results['img'] + results['img'] = self.crop(img, crop_bbox) + results['img_shape'] = results['img'].shape[1:] + + # crop semantic seg + seg_map = results['gt_seg_map'] + results['gt_seg_map'] = self.crop(seg_map, crop_bbox) + + return results + + def __repr__(self): + return self.__class__.__name__ + f'(crop_shape={self.crop_shape})' + + +@TRANSFORMS.register_module() +class BioMedicalGaussianNoise(BaseTransform): + """Add random Gaussian noise to image. + + Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/noise_transforms.py#L53 # noqa:E501 + + Copyright (c) German Cancer Research Center (DKFZ) + Licensed under the Apache License, Version 2.0 + + Required Keys: + + - img (np.ndarray): Biomedical image with shape (N, Z, Y, X), + N is the number of modalities, and data type is float32. + + Modified Keys: + + - img + + Args: + prob (float): Probability to add Gaussian noise for + each sample. Default to 0.1. + mean (float): Mean or “centre” of the distribution. Default to 0.0. + std (float): Standard deviation of distribution. Default to 0.1. + """ + + def __init__(self, + prob: float = 0.1, + mean: float = 0.0, + std: float = 0.1) -> None: + super().__init__() + assert 0.0 <= prob <= 1.0 and std >= 0.0 + self.prob = prob + self.mean = mean + self.std = std + + def transform(self, results: Dict) -> Dict: + """Call function to add random Gaussian noise to image. + + Args: + results (dict): Result dict. + + Returns: + dict: Result dict with random Gaussian noise. + """ + if np.random.rand() < self.prob: + rand_std = np.random.uniform(0, self.std) + noise = np.random.normal( + self.mean, rand_std, size=results['img'].shape) + # noise is float64 array, convert to the results['img'].dtype + noise = noise.astype(results['img'].dtype) + results['img'] = results['img'] + noise + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'mean={self.mean}, ' + repr_str += f'std={self.std})' + return repr_str + + +@TRANSFORMS.register_module() +class BioMedicalGaussianBlur(BaseTransform): + """Add Gaussian blur with random sigma to image. + + Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/noise_transforms.py#L81 # noqa:E501 + + Copyright (c) German Cancer Research Center (DKFZ) + Licensed under the Apache License, Version 2.0 + + Required Keys: + + - img (np.ndarray): Biomedical image with shape (N, Z, Y, X), + N is the number of modalities, and data type is float32. + + Modified Keys: + + - img + + Args: + sigma_range (Tuple[float, float]|float): range to randomly + select sigma value. Default to (0.5, 1.0). + prob (float): Probability to apply Gaussian blur + for each sample. Default to 0.2. + prob_per_channel (float): Probability to apply Gaussian blur + for each channel (axis N of the image). Default to 0.5. + different_sigma_per_channel (bool): whether to use different + sigma for each channel (axis N of the image). Default to True. + different_sigma_per_axis (bool): whether to use different + sigma for axis Z, X and Y of the image. Default to True. + """ + + def __init__(self, + sigma_range: Tuple[float, float] = (0.5, 1.0), + prob: float = 0.2, + prob_per_channel: float = 0.5, + different_sigma_per_channel: bool = True, + different_sigma_per_axis: bool = True) -> None: + super().__init__() + assert 0.0 <= prob <= 1.0 + assert 0.0 <= prob_per_channel <= 1.0 + assert isinstance(sigma_range, Sequence) and len(sigma_range) == 2 + self.sigma_range = sigma_range + self.prob = prob + self.prob_per_channel = prob_per_channel + self.different_sigma_per_channel = different_sigma_per_channel + self.different_sigma_per_axis = different_sigma_per_axis + + def _get_valid_sigma(self, value_range) -> Tuple[float, ...]: + """Ensure the `value_range` to be either a single value or a sequence + of two values. If the `value_range` is a sequence, generate a random + value with `[value_range[0], value_range[1]]` based on uniform + sampling. + + Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/augmentations/utils.py#L625 # noqa:E501 + + Args: + value_range (tuple|list|float|int): the input value range + """ + if (isinstance(value_range, (list, tuple))): + if (value_range[0] == value_range[1]): + value = value_range[0] + else: + orig_type = type(value_range[0]) + value = np.random.uniform(value_range[0], value_range[1]) + value = orig_type(value) + return value + + def _gaussian_blur(self, data_sample: np.ndarray) -> np.ndarray: + """Random generate sigma and apply Gaussian Blur to the data + Args: + data_sample (np.ndarray): data sample with multiple modalities, + the data shape is (N, Z, Y, X) + """ + sigma = None + for c in range(data_sample.shape[0]): + if np.random.rand() < self.prob_per_channel: + # if no `sigma` is generated, generate one + # if `self.different_sigma_per_channel` is True, + # re-generate random sigma for each channel + if (sigma is None or self.different_sigma_per_channel): + if (not self.different_sigma_per_axis): + sigma = self._get_valid_sigma(self.sigma_range) + else: + sigma = [ + self._get_valid_sigma(self.sigma_range) + for _ in data_sample.shape[1:] + ] + # apply gaussian filter with `sigma` + data_sample[c] = gaussian_filter( + data_sample[c], sigma, order=0) + return data_sample + + def transform(self, results: Dict) -> Dict: + """Call function to add random Gaussian blur to image. + + Args: + results (dict): Result dict. + + Returns: + dict: Result dict with random Gaussian noise. + """ + if np.random.rand() < self.prob: + results['img'] = self._gaussian_blur(results['img']) + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'prob_per_channel={self.prob_per_channel}, ' + repr_str += f'sigma_range={self.sigma_range}, ' + repr_str += 'different_sigma_per_channel=' \ + f'{self.different_sigma_per_channel}, ' + repr_str += 'different_sigma_per_axis=' \ + f'{self.different_sigma_per_axis})' + return repr_str + + +@TRANSFORMS.register_module() +class BioMedicalRandomGamma(BaseTransform): + """Using random gamma correction to process the biomedical image. + + Modified from + https://github.com/MIC-DKFZ/batchgenerators/blob/master/batchgenerators/transforms/color_transforms.py#L132 # noqa:E501 + With licence: Apache 2.0 + + Required Keys: + + - img (np.ndarray): Biomedical image with shape (N, Z, Y, X), + N is the number of modalities, and data type is float32. + + Modified Keys: + - img + + Args: + prob (float): The probability to perform this transform. Default: 0.5. + gamma_range (Tuple[float]): Range of gamma values. Default: (0.5, 2). + invert_image (bool): Whether invert the image before applying gamma + augmentation. Default: False. + per_channel (bool): Whether perform the transform each channel + individually. Default: False + retain_stats (bool): Gamma transformation will alter the mean and std + of the data in the patch. If retain_stats=True, the data will be + transformed to match the mean and standard deviation before gamma + augmentation. Default: False. + """ + + def __init__(self, + prob: float = 0.5, + gamma_range: Tuple[float] = (0.5, 2), + invert_image: bool = False, + per_channel: bool = False, + retain_stats: bool = False): + assert 0 <= prob and prob <= 1 + assert isinstance(gamma_range, tuple) and len(gamma_range) == 2 + assert isinstance(invert_image, bool) + assert isinstance(per_channel, bool) + assert isinstance(retain_stats, bool) + self.prob = prob + self.gamma_range = gamma_range + self.invert_image = invert_image + self.per_channel = per_channel + self.retain_stats = retain_stats + + @cache_randomness + def _do_gamma(self): + """Whether do adjust gamma for image.""" + return np.random.rand() < self.prob + + def _adjust_gamma(self, img: np.array): + """Gamma adjustment for image. + + Args: + img (np.array): Input image before gamma adjust. + + Returns: + np.arrays: Image after gamma adjust. + """ + + if self.invert_image: + img = -img + + def _do_adjust(img): + if retain_stats_here: + img_mean = img.mean() + img_std = img.std() + if np.random.random() < 0.5 and self.gamma_range[0] < 1: + gamma = np.random.uniform(self.gamma_range[0], 1) + else: + gamma = np.random.uniform( + max(self.gamma_range[0], 1), self.gamma_range[1]) + img_min = img.min() + img_range = img.max() - img_min # range + img = np.power(((img - img_min) / float(img_range + 1e-7)), + gamma) * img_range + img_min + if retain_stats_here: + img = img - img.mean() + img = img / (img.std() + 1e-8) * img_std + img = img + img_mean + return img + + if not self.per_channel: + retain_stats_here = self.retain_stats + img = _do_adjust(img) + else: + for c in range(img.shape[0]): + img[c] = _do_adjust(img[c]) + if self.invert_image: + img = -img + return img + + def transform(self, results: dict) -> dict: + """Call function to perform random gamma correction + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with random gamma correction performed. + """ + do_gamma = self._do_gamma() + + if do_gamma: + results['img'] = self._adjust_gamma(results['img']) + else: + pass + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'gamma_range={self.gamma_range},' + repr_str += f'invert_image={self.invert_image},' + repr_str += f'per_channel={self.per_channel},' + repr_str += f'retain_stats={self.retain_stats}' + return repr_str + + +@TRANSFORMS.register_module() +class BioMedical3DPad(BaseTransform): + """Pad the biomedical 3d image & biomedical 3d semantic segmentation maps. + + Required Keys: + + - img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default, + N is the number of modalities. + - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape + (Z, Y, X) by default. + + Modified Keys: + + - img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default, + N is the number of modalities. + - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape + (Z, Y, X) by default. + + Added Keys: + + - pad_shape (Tuple[int, int, int]): The padded shape. + + Args: + pad_shape (Tuple[int, int, int]): Fixed padding size. + Expected padding shape (Z, Y, X). + pad_val (float): Padding value for biomedical image. + The padding mode is set to "constant". The value + to be filled in padding area. Default: 0. + seg_pad_val (int): Padding value for biomedical 3d semantic + segmentation maps. The padding mode is set to "constant". + The value to be filled in padding area. Default: 0. + """ + + def __init__(self, + pad_shape: Tuple[int, int, int], + pad_val: float = 0., + seg_pad_val: int = 0) -> None: + + # check pad_shape + assert pad_shape is not None + if not isinstance(pad_shape, tuple): + assert len(pad_shape) == 3 + + self.pad_shape = pad_shape + self.pad_val = pad_val + self.seg_pad_val = seg_pad_val + + def _pad_img(self, results: dict) -> None: + """Pad images according to ``self.pad_shape`` + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: The dict contains the padded image and shape + information. + """ + padded_img = self._to_pad( + results['img'], pad_shape=self.pad_shape, pad_val=self.pad_val) + + results['img'] = padded_img + results['pad_shape'] = padded_img.shape[1:] + + def _pad_seg(self, results: dict) -> None: + """Pad semantic segmentation map according to ``self.pad_shape`` if + ``gt_seg_map`` is not None in results dict. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Update the padded gt seg map in dict. + """ + if results.get('gt_seg_map', None) is not None: + pad_gt_seg = self._to_pad( + results['gt_seg_map'][None, ...], + pad_shape=results['pad_shape'], + pad_val=self.seg_pad_val) + results['gt_seg_map'] = pad_gt_seg[1:] + + @staticmethod + def _to_pad(img: np.ndarray, + pad_shape: Tuple[int, int, int], + pad_val: Union[int, float] = 0) -> np.ndarray: + """Pad the given 3d image to a certain shape with specified padding + value. + + Args: + img (ndarray): Biomedical image with shape (N, Z, Y, X) + to be padded. N is the number of modalities. + pad_shape (Tuple[int,int,int]): Expected padding shape (Z, Y, X). + pad_val (float, int): Values to be filled in padding areas + and the padding_mode is set to 'constant'. Default: 0. + + Returns: + ndarray: The padded image. + """ + # compute pad width + d = max(pad_shape[0] - img.shape[1], 0) + pad_d = (d // 2, d - d // 2) + h = max(pad_shape[1] - img.shape[2], 0) + pad_h = (h // 2, h - h // 2) + w = max(pad_shape[2] - img.shape[2], 0) + pad_w = (w // 2, w - w // 2) + + pad_list = [(0, 0), pad_d, pad_h, pad_w] + + img = np.pad(img, pad_list, mode='constant', constant_values=pad_val) + return img + + def transform(self, results: dict) -> dict: + """Call function to pad images, semantic segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Updated result dict. + """ + self._pad_img(results) + self._pad_seg(results) + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'pad_shape={self.pad_shape}, ' + repr_str += f'pad_val={self.pad_val}), ' + repr_str += f'seg_pad_val={self.seg_pad_val})' + return repr_str + + +@TRANSFORMS.register_module() +class BioMedical3DRandomFlip(BaseTransform): + """Flip biomedical 3D images and segmentations. + + Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/master/batchgenerators/transforms/spatial_transforms.py # noqa:E501 + + Copyright 2021 Division of + Medical Image Computing, German Cancer Research Center (DKFZ) and Applied + Computer Vision Lab, Helmholtz Imaging Platform. + Licensed under the Apache-2.0 License. + + Required Keys: + + - img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default, + N is the number of modalities. + - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape + (Z, Y, X) by default. + + Modified Keys: + + - img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default, + N is the number of modalities. + - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape + (Z, Y, X) by default. + + Added Keys: + + - do_flip + - flip_axes + + Args: + prob (float): Flipping probability. + axes (Tuple[int, ...]): Flipping axes with order 'ZXY'. + swap_label_pairs (Optional[List[Tuple[int, int]]]): + The segmentation label pairs that are swapped when flipping. + """ + + def __init__(self, + prob: float, + axes: Tuple[int, ...], + swap_label_pairs: Optional[List[Tuple[int, int]]] = None): + self.prob = prob + self.axes = axes + self.swap_label_pairs = swap_label_pairs + assert prob >= 0 and prob <= 1 + if axes is not None: + assert max(axes) <= 2 + + @staticmethod + def _flip(img, direction: Tuple[bool, bool, bool]) -> np.ndarray: + if direction[0]: + img[:, :] = img[:, ::-1] + if direction[1]: + img[:, :, :] = img[:, :, ::-1] + if direction[2]: + img[:, :, :, :] = img[:, :, :, ::-1] + return img + + def _do_flip(self, img: np.ndarray) -> Tuple[bool, bool, bool]: + """Call function to determine which axis to flip. + + Args: + img (np.ndarry): Image or segmentation map array. + Returns: + tuple: Flip action, whether to flip on the z, x, and y axes. + """ + flip_c, flip_x, flip_y = False, False, False + if self.axes is not None: + flip_c = 0 in self.axes and np.random.rand() < self.prob + flip_x = 1 in self.axes and np.random.rand() < self.prob + if len(img.shape) == 4: + flip_y = 2 in self.axes and np.random.rand() < self.prob + return flip_c, flip_x, flip_y + + def _swap_label(self, seg: np.ndarray) -> np.ndarray: + out = seg.copy() + for first, second in self.swap_label_pairs: + first_area = (seg == first) + second_area = (seg == second) + out[first_area] = second + out[second_area] = first + return out + + def transform(self, results: Dict) -> Dict: + """Call function to flip and swap pair labels. + + Args: + results (dict): Result dict. + Returns: + dict: Flipped results, 'do_flip', 'flip_axes' keys are added into + result dict. + """ + # get actual flipped axis + if 'do_flip' not in results: + results['do_flip'] = self._do_flip(results['img']) + if 'flip_axes' not in results: + results['flip_axes'] = self.axes + # flip image + results['img'] = self._flip( + results['img'], direction=results['do_flip']) + # flip seg + if results['gt_seg_map'] is not None: + if results['gt_seg_map'].shape != results['img'].shape: + results['gt_seg_map'] = results['gt_seg_map'][None, :] + results['gt_seg_map'] = self._flip( + results['gt_seg_map'], direction=results['do_flip']) + results['gt_seg_map'] = results['gt_seg_map'].squeeze() + # swap label pairs + if self.swap_label_pairs is not None: + results['gt_seg_map'] = self._swap_label(results['gt_seg_map']) + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, axes={self.axes}, ' \ + f'swap_label_pairs={self.swap_label_pairs})' + return repr_str + + +@TRANSFORMS.register_module() +class Albu(BaseTransform): + """Albumentation augmentation. Adds custom transformations from + Albumentations library. Please, visit + `https://albumentations.readthedocs.io` to get more information. An example + of ``transforms`` is as followed: + + .. code-block:: + [ + dict( + type='ShiftScaleRotate', + shift_limit=0.0625, + scale_limit=0.0, + rotate_limit=0, + interpolation=1, + p=0.5), + dict( + type='RandomBrightnessContrast', + brightness_limit=[0.1, 0.3], + contrast_limit=[0.1, 0.3], + p=0.2), + dict(type='ChannelShuffle', p=0.1), + dict( + type='OneOf', + transforms=[ + dict(type='Blur', blur_limit=3, p=1.0), + dict(type='MedianBlur', blur_limit=3, p=1.0) + ], + p=0.1), + ] + Args: + transforms (list[dict]): A list of albu transformations + keymap (dict): Contains {'input key':'albumentation-style key'} + additional_targets(dict): Allows applying same augmentations to \ + multiple objects of same type. + update_pad_shape (bool): Whether to update padding shape according to \ + the output shape of the last transform + bgr_to_rgb (bool): Whether to convert the band order to RGB + """ + + def __init__(self, + transforms: List[dict], + keymap: Optional[dict] = None, + additional_targets: Optional[dict] = None, + update_pad_shape: bool = False, + bgr_to_rgb: bool = True): + if not ALBU_INSTALLED: + raise ImportError( + 'albumentations is not installed, ' + 'we suggest install albumentation by ' + '"pip install albumentations>=0.3.2 --no-binary qudida,albumentations"' # noqa + ) + + # Args will be modified later, copying it will be safer + transforms = copy.deepcopy(transforms) + + self.transforms = transforms + self.keymap = keymap + self.additional_targets = additional_targets + self.update_pad_shape = update_pad_shape + self.bgr_to_rgb = bgr_to_rgb + + self.aug = Compose([self.albu_builder(t) for t in self.transforms], + additional_targets=self.additional_targets) + + if not keymap: + self.keymap_to_albu = {'img': 'image', 'gt_seg_map': 'mask'} + else: + self.keymap_to_albu = copy.deepcopy(keymap) + self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()} + + def albu_builder(self, cfg: dict) -> object: + """Build a callable object from a dict containing albu arguments. + + Args: + cfg (dict): Config dict. It should at least contain the key "type". + + Returns: + Callable: A callable object. + """ + + assert isinstance(cfg, dict) and 'type' in cfg + args = cfg.copy() + + obj_type = args.pop('type') + if mmengine.is_str(obj_type): + if not ALBU_INSTALLED: + raise ImportError( + 'albumentations is not installed, ' + 'we suggest install albumentation by ' + '"pip install albumentations>=0.3.2 --no-binary qudida,albumentations"' # noqa + ) + obj_cls = getattr(albumentations, obj_type) + elif inspect.isclass(obj_type): + obj_cls = obj_type + else: + raise TypeError( + f'type must be a valid type or str, but got {type(obj_type)}') + + if 'transforms' in args: + args['transforms'] = [ + self.albu_builder(t) for t in args['transforms'] + ] + + return obj_cls(**args) + + @staticmethod + def mapper(d: dict, keymap: dict): + """Dictionary mapper. + + Renames keys according to keymap provided. + Args: + d (dict): old dict + keymap (dict): {'old_key':'new_key'} + Returns: + dict: new dict. + """ + + updated_dict = {} + for k, _ in zip(d.keys(), d.values()): + new_k = keymap.get(k, k) + updated_dict[new_k] = d[k] + return updated_dict + + def transform(self, results): + # dict to albumentations format + results = self.mapper(results, self.keymap_to_albu) + + # Convert to RGB since Albumentations works with RGB images + if self.bgr_to_rgb: + results['image'] = cv2.cvtColor(results['image'], + cv2.COLOR_BGR2RGB) + if self.additional_targets: + for key, value in self.additional_targets.items(): + if value == 'image': + results[key] = cv2.cvtColor(results[key], + cv2.COLOR_BGR2RGB) + + # Apply Transform + results = self.aug(**results) + + # Convert back to BGR + if self.bgr_to_rgb: + results['image'] = cv2.cvtColor(results['image'], + cv2.COLOR_RGB2BGR) + if self.additional_targets: + for key, value in self.additional_targets.items(): + if value == 'image': + results[key] = cv2.cvtColor(results['image2'], + cv2.COLOR_RGB2BGR) + + # back to the original format + results = self.mapper(results, self.keymap_back) + + # update final shape + if self.update_pad_shape: + results['pad_shape'] = results['img'].shape + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + f'(transforms={self.transforms})' + return repr_str + + +@TRANSFORMS.register_module() +class ConcatCDInput(BaseTransform): + """Concat images for change detection. + + Required Keys: + + - img + - img2 + + Args: + input_keys (tuple): Input image keys for change detection. + Default: ('img', 'img2'). + """ + + def __init__(self, input_keys=('img', 'img2')): + self.input_keys = input_keys + + def transform(self, results: dict) -> dict: + img = [] + for input_key in self.input_keys: + img.append(results.pop(input_key)) + results['img'] = np.concatenate(img, axis=2) + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(input_keys={self.input_keys}, ' + return repr_str + + +@TRANSFORMS.register_module() +class RandomDepthMix(BaseTransform): + """This class implements the RandomDepthMix transform. + + Args: + prob (float): Probability of applying the transformation. + Defaults to 0.25. + mix_scale_ratio (float): Ratio to scale the mix width. + Defaults to 0.75. + """ + + def __init__( + self, + prob: float = 0.25, + mix_scale_ratio: float = 0.75, + ): + super().__init__() + + self.prob = prob + self.mix_scale_ratio = mix_scale_ratio + + def transform(self, results: dict) -> dict: + if random.random() > self.prob: + return results + + h, w = results['img_shape'][:2] + left = int(w * random.random()) + width_ratio = self.mix_scale_ratio * random.random() + width = int(max(1, (w - left) * width_ratio)) + + img = results['img'] + depth_rescale_factor = results.get('depth_rescale_factor', 1) + depth_map = results['gt_depth_map'] / depth_rescale_factor + + if img.ndim == 3: + for c in range(img.shape[-1]): + img[:, left:left + width, c] = depth_map[:, left:left + width] + elif img.ndim == 2: + img[:, left:left + width] = depth_map[:, left:left + width] + else: + raise ValueError(f'Invalid image shape ({img.shape})') + + results['img'] = img + return results diff --git a/third-party/InterFormer/mmseg/datasets/voc.py b/third-party/InterFormer/mmseg/datasets/voc.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5d6025c03760953a82f80e337185afc51f1386 --- /dev/null +++ b/third-party/InterFormer/mmseg/datasets/voc.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp + +import mmengine.fileio as fileio + +from mmseg.registry import DATASETS +from .basesegdataset import BaseSegDataset + + +@DATASETS.register_module() +class PascalVOCDataset(BaseSegDataset): + """Pascal VOC dataset. + + Args: + split (str): Split txt file for Pascal VOC. + """ + METAINFO = dict( + classes=('background', 'aeroplane', 'bicycle', 'bird', 'boat', + 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', + 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', + 'sofa', 'train', 'tvmonitor'), + palette=[[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], + [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], + [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], + [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], + [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], + [0, 64, 128]]) + + def __init__(self, + ann_file, + img_suffix='.jpg', + seg_map_suffix='.png', + **kwargs) -> None: + super().__init__( + img_suffix=img_suffix, + seg_map_suffix=seg_map_suffix, + ann_file=ann_file, + **kwargs) + assert fileio.exists(self.data_prefix['img_path'], + self.backend_args) and osp.isfile(self.ann_file) diff --git a/third-party/InterFormer/mmseg/engine/__init__.py b/third-party/InterFormer/mmseg/engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..98139a0047fd2f076d659ba5aed2cd3452dbd235 --- /dev/null +++ b/third-party/InterFormer/mmseg/engine/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .hooks import SegVisualizationHook +from .optimizers import (ForceDefaultOptimWrapperConstructor, + LayerDecayOptimizerConstructor, + LearningRateDecayOptimizerConstructor) +from .schedulers import PolyLRRatio + +__all__ = [ + 'LearningRateDecayOptimizerConstructor', 'LayerDecayOptimizerConstructor', + 'SegVisualizationHook', 'PolyLRRatio', + 'ForceDefaultOptimWrapperConstructor' +] diff --git a/third-party/InterFormer/mmseg/engine/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/engine/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ae6de8fadefcf5d62360b5233b74598eedd7f76 Binary files /dev/null and b/third-party/InterFormer/mmseg/engine/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/engine/hooks/__init__.py b/third-party/InterFormer/mmseg/engine/hooks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c6048088a7fd322890ced17569e855acee826eca --- /dev/null +++ b/third-party/InterFormer/mmseg/engine/hooks/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .visualization_hook import SegVisualizationHook + +__all__ = ['SegVisualizationHook'] diff --git a/third-party/InterFormer/mmseg/engine/hooks/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/engine/hooks/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d2e0bb7b310d82587e021463d29463af7853d4b Binary files /dev/null and b/third-party/InterFormer/mmseg/engine/hooks/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/engine/hooks/__pycache__/visualization_hook.cpython-38.pyc b/third-party/InterFormer/mmseg/engine/hooks/__pycache__/visualization_hook.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef0a5571524f78cd92d58e627c9d834abcf867bf Binary files /dev/null and b/third-party/InterFormer/mmseg/engine/hooks/__pycache__/visualization_hook.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/engine/hooks/visualization_hook.py b/third-party/InterFormer/mmseg/engine/hooks/visualization_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..21cddde89d96c77ffe5b711a5efe524ced668b5c --- /dev/null +++ b/third-party/InterFormer/mmseg/engine/hooks/visualization_hook.py @@ -0,0 +1,129 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import warnings +from typing import Optional, Sequence + +import mmcv +from mmengine.fileio import get +from mmengine.hooks import Hook +from mmengine.runner import Runner +from mmengine.visualization import Visualizer + +from mmseg.registry import HOOKS +from mmseg.structures import SegDataSample + + +@HOOKS.register_module() +class SegVisualizationHook(Hook): + """Segmentation Visualization Hook. Used to visualize validation and + testing process prediction results. + + In the testing phase: + + 1. If ``show`` is True, it means that only the prediction results are + visualized without storing data, so ``vis_backends`` needs to + be excluded. + + Args: + draw (bool): whether to draw prediction results. If it is False, + it means that no drawing will be done. Defaults to False. + interval (int): The interval of visualization. Defaults to 50. + show (bool): Whether to display the drawn image. Default to False. + wait_time (float): The interval of show (s). Defaults to 0. + backend_args (dict, Optional): Arguments to instantiate a file backend. + See https://mmengine.readthedocs.io/en/latest/api/fileio.htm + for details. Defaults to None. + Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. + """ + + def __init__(self, + draw: bool = False, + interval: int = 50, + show: bool = False, + wait_time: float = 0., + backend_args: Optional[dict] = None): + self._visualizer: Visualizer = Visualizer.get_current_instance() + self.interval = interval + self.show = show + if self.show: + # No need to think about vis backends. + self._visualizer._vis_backends = {} + warnings.warn('The show is True, it means that only ' + 'the prediction results are visualized ' + 'without storing data, so vis_backends ' + 'needs to be excluded.') + + self.wait_time = wait_time + self.backend_args = backend_args.copy() if backend_args else None + self.draw = draw + if not self.draw: + warnings.warn('The draw is False, it means that the ' + 'hook for visualization will not take ' + 'effect. The results will NOT be ' + 'visualized or stored.') + self._test_index = 0 + + def after_val_iter(self, runner: Runner, batch_idx: int, data_batch: dict, + outputs: Sequence[SegDataSample]) -> None: + """Run after every ``self.interval`` validation iterations. + + Args: + runner (:obj:`Runner`): The runner of the validation process. + batch_idx (int): The index of the current batch in the val loop. + data_batch (dict): Data from dataloader. + outputs (Sequence[:obj:`SegDataSample`]]): A batch of data samples + that contain annotations and predictions. + """ + if self.draw is False: + return + + # There is no guarantee that the same batch of images + # is visualized for each evaluation. + total_curr_iter = runner.iter + batch_idx + + # Visualize only the first data + img_path = outputs[0].img_path + img_bytes = get(img_path, backend_args=self.backend_args) + img = mmcv.imfrombytes(img_bytes, channel_order='rgb') + window_name = f'val_{osp.basename(img_path)}' + + if total_curr_iter % self.interval == 0: + self._visualizer.add_datasample( + window_name, + img, + data_sample=outputs[0], + show=self.show, + wait_time=self.wait_time, + step=total_curr_iter) + + def after_test_iter(self, runner: Runner, batch_idx: int, data_batch: dict, + outputs: Sequence[SegDataSample]) -> None: + """Run after every testing iterations. + + Args: + runner (:obj:`Runner`): The runner of the testing process. + batch_idx (int): The index of the current batch in the val loop. + data_batch (dict): Data from dataloader. + outputs (Sequence[:obj:`SegDataSample`]): A batch of data samples + that contain annotations and predictions. + """ + if self.draw is False: + return + + for data_sample in outputs: + self._test_index += 1 + + img_path = data_sample.img_path + window_name = f'test_{osp.basename(img_path)}' + + img_path = data_sample.img_path + img_bytes = get(img_path, backend_args=self.backend_args) + img = mmcv.imfrombytes(img_bytes, channel_order='rgb') + + self._visualizer.add_datasample( + window_name, + img, + data_sample=data_sample, + show=self.show, + wait_time=self.wait_time, + step=self._test_index) diff --git a/third-party/InterFormer/mmseg/engine/optimizers/__init__.py b/third-party/InterFormer/mmseg/engine/optimizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4cf58741febfc20ea33664ea8e1b1ac68bbb327 --- /dev/null +++ b/third-party/InterFormer/mmseg/engine/optimizers/__init__.py @@ -0,0 +1,9 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .force_default_constructor import ForceDefaultOptimWrapperConstructor +from .layer_decay_optimizer_constructor import ( + LayerDecayOptimizerConstructor, LearningRateDecayOptimizerConstructor) + +__all__ = [ + 'LearningRateDecayOptimizerConstructor', 'LayerDecayOptimizerConstructor', + 'ForceDefaultOptimWrapperConstructor' +] diff --git a/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b1ed70ca3f8c38827195def0c27750085107e66 Binary files /dev/null and b/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/force_default_constructor.cpython-38.pyc b/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/force_default_constructor.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67194d2a9bb4d3c0692e2a071cfc793143c865c9 Binary files /dev/null and b/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/force_default_constructor.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/layer_decay_optimizer_constructor.cpython-38.pyc b/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/layer_decay_optimizer_constructor.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..937c81dff4ff8214adafce43f210338c489e4212 Binary files /dev/null and b/third-party/InterFormer/mmseg/engine/optimizers/__pycache__/layer_decay_optimizer_constructor.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/engine/optimizers/force_default_constructor.py b/third-party/InterFormer/mmseg/engine/optimizers/force_default_constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..12c642ad411bfd547d63c894c84636e2f1896128 --- /dev/null +++ b/third-party/InterFormer/mmseg/engine/optimizers/force_default_constructor.py @@ -0,0 +1,255 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import logging +from typing import List, Optional, Union + +import torch +import torch.nn as nn +from mmengine.logging import print_log +from mmengine.optim import DefaultOptimWrapperConstructor +from mmengine.utils.dl_utils import mmcv_full_available +from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm, _InstanceNorm +from torch.nn import GroupNorm, LayerNorm + +from mmseg.registry import OPTIM_WRAPPER_CONSTRUCTORS + + +@OPTIM_WRAPPER_CONSTRUCTORS.register_module() +class ForceDefaultOptimWrapperConstructor(DefaultOptimWrapperConstructor): + """Default constructor with forced optimizer settings. + + This constructor extends the default constructor to add an option for + forcing default optimizer settings. This is useful for ensuring that + certain parameters or layers strictly adhere to pre-defined default + settings, regardless of any custom settings specified. + + By default, each parameter share the same optimizer settings, and we + provide an argument ``paramwise_cfg`` to specify parameter-wise settings. + It is a dict and may contain various fields like 'custom_keys', + 'bias_lr_mult', etc., as well as the additional field + `force_default_settings` which allows for enforcing default settings on + optimizer parameters. + + - ``custom_keys`` (dict): Specified parameters-wise settings by keys. If + one of the keys in ``custom_keys`` is a substring of the name of one + parameter, then the setting of the parameter will be specified by + ``custom_keys[key]`` and other setting like ``bias_lr_mult`` etc. will + be ignored. It should be noted that the aforementioned ``key`` is the + longest key that is a substring of the name of the parameter. If there + are multiple matched keys with the same length, then the key with lower + alphabet order will be chosen. + ``custom_keys[key]`` should be a dict and may contain fields ``lr_mult`` + and ``decay_mult``. See Example 2 below. + - ``bias_lr_mult`` (float): It will be multiplied to the learning + rate for all bias parameters (except for those in normalization + layers and offset layers of DCN). + - ``bias_decay_mult`` (float): It will be multiplied to the weight + decay for all bias parameters (except for those in + normalization layers, depthwise conv layers, offset layers of DCN). + - ``norm_decay_mult`` (float): It will be multiplied to the weight + decay for all weight and bias parameters of normalization + layers. + - ``flat_decay_mult`` (float): It will be multiplied to the weight + decay for all one-dimensional parameters + - ``dwconv_decay_mult`` (float): It will be multiplied to the weight + decay for all weight and bias parameters of depthwise conv + layers. + - ``dcn_offset_lr_mult`` (float): It will be multiplied to the learning + rate for parameters of offset layer in the deformable convs + of a model. + - ``bypass_duplicate`` (bool): If true, the duplicate parameters + would not be added into optimizer. Defaults to False. + - ``force_default_settings`` (bool): If true, this will override any + custom settings defined by ``custom_keys`` and enforce the use of + default settings for optimizer parameters like ``bias_lr_mult``. + This is particularly useful when you want to ensure that certain layers + or parameters adhere strictly to the pre-defined default settings. + + Note: + + 1. If the option ``dcn_offset_lr_mult`` is used, the constructor will + override the effect of ``bias_lr_mult`` in the bias of offset layer. + So be careful when using both ``bias_lr_mult`` and + ``dcn_offset_lr_mult``. If you wish to apply both of them to the offset + layer in deformable convs, set ``dcn_offset_lr_mult`` to the original + ``dcn_offset_lr_mult`` * ``bias_lr_mult``. + + 2. If the option ``dcn_offset_lr_mult`` is used, the constructor will + apply it to all the DCN layers in the model. So be careful when the + model contains multiple DCN layers in places other than backbone. + + 3. When the option ``force_default_settings`` is true, it will override + any custom settings provided in ``custom_keys``. This ensures that the + default settings for the optimizer parameters are used. + + Args: + optim_wrapper_cfg (dict): The config dict of the optimizer wrapper. + + Required fields of ``optim_wrapper_cfg`` are + + - ``type``: class name of the OptimizerWrapper + - ``optimizer``: The configuration of optimizer. + + Optional fields of ``optim_wrapper_cfg`` are + + - any arguments of the corresponding optimizer wrapper type, + e.g., accumulative_counts, clip_grad, etc. + + Required fields of ``optimizer`` are + + - `type`: class name of the optimizer. + + Optional fields of ``optimizer`` are + + - any arguments of the corresponding optimizer type, e.g., + lr, weight_decay, momentum, etc. + + paramwise_cfg (dict, optional): Parameter-wise options. + + Example 1: + >>> model = torch.nn.modules.Conv1d(1, 1, 1) + >>> optim_wrapper_cfg = dict( + >>> dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01, + >>> momentum=0.9, weight_decay=0.0001)) + >>> paramwise_cfg = dict(norm_decay_mult=0.) + >>> optim_wrapper_builder = DefaultOptimWrapperConstructor( + >>> optim_wrapper_cfg, paramwise_cfg) + >>> optim_wrapper = optim_wrapper_builder(model) + + Example 2: + >>> # assume model have attribute model.backbone and model.cls_head + >>> optim_wrapper_cfg = dict(type='OptimWrapper', optimizer=dict( + >>> type='SGD', lr=0.01, weight_decay=0.95)) + >>> paramwise_cfg = dict(custom_keys={ + >>> 'backbone': dict(lr_mult=0.1, decay_mult=0.9)}) + >>> optim_wrapper_builder = DefaultOptimWrapperConstructor( + >>> optim_wrapper_cfg, paramwise_cfg) + >>> optim_wrapper = optim_wrapper_builder(model) + >>> # Then the `lr` and `weight_decay` for model.backbone is + >>> # (0.01 * 0.1, 0.95 * 0.9). `lr` and `weight_decay` for + >>> # model.cls_head is (0.01, 0.95). + """ + + def add_params(self, + params: List[dict], + module: nn.Module, + prefix: str = '', + is_dcn_module: Optional[Union[int, float]] = None) -> None: + """Add all parameters of module to the params list. + + The parameters of the given module will be added to the list of param + groups, with specific rules defined by paramwise_cfg. + + Args: + params (list[dict]): A list of param groups, it will be modified + in place. + module (nn.Module): The module to be added. + prefix (str): The prefix of the module + is_dcn_module (int|float|None): If the current module is a + submodule of DCN, `is_dcn_module` will be passed to + control conv_offset layer's learning rate. Defaults to None. + """ + # get param-wise options + custom_keys = self.paramwise_cfg.get('custom_keys', {}) + # first sort with alphabet order and then sort with reversed len of str + sorted_keys = sorted(sorted(custom_keys.keys()), key=len, reverse=True) + + bias_lr_mult = self.paramwise_cfg.get('bias_lr_mult', None) + bias_decay_mult = self.paramwise_cfg.get('bias_decay_mult', None) + norm_decay_mult = self.paramwise_cfg.get('norm_decay_mult', None) + dwconv_decay_mult = self.paramwise_cfg.get('dwconv_decay_mult', None) + flat_decay_mult = self.paramwise_cfg.get('flat_decay_mult', None) + bypass_duplicate = self.paramwise_cfg.get('bypass_duplicate', False) + dcn_offset_lr_mult = self.paramwise_cfg.get('dcn_offset_lr_mult', None) + force_default_settings = self.paramwise_cfg.get( + 'force_default_settings', False) + + # special rules for norm layers and depth-wise conv layers + is_norm = isinstance(module, + (_BatchNorm, _InstanceNorm, GroupNorm, LayerNorm)) + is_dwconv = ( + isinstance(module, torch.nn.Conv2d) + and module.in_channels == module.groups) + + for name, param in module.named_parameters(recurse=False): + param_group = {'params': [param]} + if bypass_duplicate and self._is_in(param_group, params): + print_log( + f'{prefix} is duplicate. It is skipped since ' + f'bypass_duplicate={bypass_duplicate}', + logger='current', + level=logging.WARNING) + continue + if not param.requires_grad: + params.append(param_group) + continue + + # if the parameter match one of the custom keys, ignore other rules + is_custom = False + for key in sorted_keys: + if key in f'{prefix}.{name}': + is_custom = True + lr_mult = custom_keys[key].get('lr_mult', 1.) + param_group['lr'] = self.base_lr * lr_mult + if self.base_wd is not None: + decay_mult = custom_keys[key].get('decay_mult', 1.) + param_group['weight_decay'] = self.base_wd * decay_mult + # add custom settings to param_group + for k, v in custom_keys[key].items(): + param_group[k] = v + break + + if not is_custom or force_default_settings: + # bias_lr_mult affects all bias parameters + # except for norm.bias dcn.conv_offset.bias + if name == 'bias' and not ( + is_norm or is_dcn_module) and bias_lr_mult is not None: + param_group['lr'] = self.base_lr * bias_lr_mult + + if (prefix.find('conv_offset') != -1 and is_dcn_module + and dcn_offset_lr_mult is not None + and isinstance(module, torch.nn.Conv2d)): + # deal with both dcn_offset's bias & weight + param_group['lr'] = self.base_lr * dcn_offset_lr_mult + + # apply weight decay policies + if self.base_wd is not None: + # norm decay + if is_norm and norm_decay_mult is not None: + param_group[ + 'weight_decay'] = self.base_wd * norm_decay_mult + # bias lr and decay + elif (name == 'bias' and not is_dcn_module + and bias_decay_mult is not None): + param_group[ + 'weight_decay'] = self.base_wd * bias_decay_mult + # depth-wise conv + elif is_dwconv and dwconv_decay_mult is not None: + param_group[ + 'weight_decay'] = self.base_wd * dwconv_decay_mult + # flatten parameters except dcn offset + elif (param.ndim == 1 and not is_dcn_module + and flat_decay_mult is not None): + param_group[ + 'weight_decay'] = self.base_wd * flat_decay_mult + params.append(param_group) + for key, value in param_group.items(): + if key == 'params': + continue + full_name = f'{prefix}.{name}' if prefix else name + print_log( + f'paramwise_options -- {full_name}:{key}={value}', + logger='current') + + if mmcv_full_available(): + from mmcv.ops import DeformConv2d, ModulatedDeformConv2d + is_dcn_module = isinstance(module, + (DeformConv2d, ModulatedDeformConv2d)) + else: + is_dcn_module = False + for child_name, child_mod in module.named_children(): + child_prefix = f'{prefix}.{child_name}' if prefix else child_name + self.add_params( + params, + child_mod, + prefix=child_prefix, + is_dcn_module=is_dcn_module) diff --git a/third-party/InterFormer/mmseg/engine/optimizers/layer_decay_optimizer_constructor.py b/third-party/InterFormer/mmseg/engine/optimizers/layer_decay_optimizer_constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..fdae3ca698c65879056b969f04185f80452ff8d0 --- /dev/null +++ b/third-party/InterFormer/mmseg/engine/optimizers/layer_decay_optimizer_constructor.py @@ -0,0 +1,207 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import json +import warnings + +from mmengine.dist import get_dist_info +from mmengine.logging import print_log +from mmengine.optim import DefaultOptimWrapperConstructor + +from mmseg.registry import OPTIM_WRAPPER_CONSTRUCTORS + + +def get_layer_id_for_convnext(var_name, max_layer_id): + """Get the layer id to set the different learning rates in ``layer_wise`` + decay_type. + + Args: + var_name (str): The key of the model. + max_layer_id (int): Maximum number of backbone layers. + + Returns: + int: The id number corresponding to different learning rate in + ``LearningRateDecayOptimizerConstructor``. + """ + + if var_name in ('backbone.cls_token', 'backbone.mask_token', + 'backbone.pos_embed'): + return 0 + elif var_name.startswith('backbone.downsample_layers'): + stage_id = int(var_name.split('.')[2]) + if stage_id == 0: + layer_id = 0 + elif stage_id == 1: + layer_id = 2 + elif stage_id == 2: + layer_id = 3 + elif stage_id == 3: + layer_id = max_layer_id + return layer_id + elif var_name.startswith('backbone.stages'): + stage_id = int(var_name.split('.')[2]) + block_id = int(var_name.split('.')[3]) + if stage_id == 0: + layer_id = 1 + elif stage_id == 1: + layer_id = 2 + elif stage_id == 2: + layer_id = 3 + block_id // 3 + elif stage_id == 3: + layer_id = max_layer_id + return layer_id + else: + return max_layer_id + 1 + + +def get_stage_id_for_convnext(var_name, max_stage_id): + """Get the stage id to set the different learning rates in ``stage_wise`` + decay_type. + + Args: + var_name (str): The key of the model. + max_stage_id (int): Maximum number of backbone layers. + + Returns: + int: The id number corresponding to different learning rate in + ``LearningRateDecayOptimizerConstructor``. + """ + + if var_name in ('backbone.cls_token', 'backbone.mask_token', + 'backbone.pos_embed'): + return 0 + elif var_name.startswith('backbone.downsample_layers'): + return 0 + elif var_name.startswith('backbone.stages'): + stage_id = int(var_name.split('.')[2]) + return stage_id + 1 + else: + return max_stage_id - 1 + + +def get_layer_id_for_vit(var_name, max_layer_id): + """Get the layer id to set the different learning rates. + + Args: + var_name (str): The key of the model. + num_max_layer (int): Maximum number of backbone layers. + + Returns: + int: Returns the layer id of the key. + """ + + if var_name in ('backbone.cls_token', 'backbone.mask_token', + 'backbone.pos_embed'): + return 0 + elif var_name.startswith('backbone.patch_embed'): + return 0 + elif var_name.startswith('backbone.layers'): + layer_id = int(var_name.split('.')[2]) + return layer_id + 1 + else: + return max_layer_id - 1 + + +@OPTIM_WRAPPER_CONSTRUCTORS.register_module() +class LearningRateDecayOptimizerConstructor(DefaultOptimWrapperConstructor): + """Different learning rates are set for different layers of backbone. + + Note: Currently, this optimizer constructor is built for ConvNeXt, + BEiT and MAE. + """ + + def add_params(self, params, module, **kwargs): + """Add all parameters of module to the params list. + + The parameters of the given module will be added to the list of param + groups, with specific rules defined by paramwise_cfg. + + Args: + params (list[dict]): A list of param groups, it will be modified + in place. + module (nn.Module): The module to be added. + """ + + parameter_groups = {} + print_log(f'self.paramwise_cfg is {self.paramwise_cfg}') + num_layers = self.paramwise_cfg.get('num_layers') + 2 + decay_rate = self.paramwise_cfg.get('decay_rate') + decay_type = self.paramwise_cfg.get('decay_type', 'layer_wise') + print_log('Build LearningRateDecayOptimizerConstructor ' + f'{decay_type} {decay_rate} - {num_layers}') + weight_decay = self.base_wd + for name, param in module.named_parameters(): + if not param.requires_grad: + continue # frozen weights + if len(param.shape) == 1 or name.endswith('.bias') or name in ( + 'pos_embed', 'cls_token'): + group_name = 'no_decay' + this_weight_decay = 0. + else: + group_name = 'decay' + this_weight_decay = weight_decay + if 'layer_wise' in decay_type: + if 'ConvNeXt' in module.backbone.__class__.__name__: + layer_id = get_layer_id_for_convnext( + name, self.paramwise_cfg.get('num_layers')) + print_log(f'set param {name} as id {layer_id}') + elif 'BEiT' in module.backbone.__class__.__name__ or \ + 'MAE' in module.backbone.__class__.__name__: + layer_id = get_layer_id_for_vit(name, num_layers) + print_log(f'set param {name} as id {layer_id}') + else: + raise NotImplementedError() + elif decay_type == 'stage_wise': + if 'ConvNeXt' in module.backbone.__class__.__name__: + layer_id = get_stage_id_for_convnext(name, num_layers) + print_log(f'set param {name} as id {layer_id}') + else: + raise NotImplementedError() + group_name = f'layer_{layer_id}_{group_name}' + + if group_name not in parameter_groups: + scale = decay_rate**(num_layers - layer_id - 1) + + parameter_groups[group_name] = { + 'weight_decay': this_weight_decay, + 'params': [], + 'param_names': [], + 'lr_scale': scale, + 'group_name': group_name, + 'lr': scale * self.base_lr, + } + + parameter_groups[group_name]['params'].append(param) + parameter_groups[group_name]['param_names'].append(name) + rank, _ = get_dist_info() + if rank == 0: + to_display = {} + for key in parameter_groups: + to_display[key] = { + 'param_names': parameter_groups[key]['param_names'], + 'lr_scale': parameter_groups[key]['lr_scale'], + 'lr': parameter_groups[key]['lr'], + 'weight_decay': parameter_groups[key]['weight_decay'], + } + print_log(f'Param groups = {json.dumps(to_display, indent=2)}') + params.extend(parameter_groups.values()) + + +@OPTIM_WRAPPER_CONSTRUCTORS.register_module() +class LayerDecayOptimizerConstructor(LearningRateDecayOptimizerConstructor): + """Different learning rates are set for different layers of backbone. + + Note: Currently, this optimizer constructor is built for BEiT, + and it will be deprecated. + Please use ``LearningRateDecayOptimizerConstructor`` instead. + """ + + def __init__(self, optim_wrapper_cfg, paramwise_cfg): + warnings.warn('DeprecationWarning: Original ' + 'LayerDecayOptimizerConstructor of BEiT ' + 'will be deprecated. Please use ' + 'LearningRateDecayOptimizerConstructor instead, ' + 'and set decay_type = layer_wise_vit in paramwise_cfg.') + paramwise_cfg.update({'decay_type': 'layer_wise_vit'}) + warnings.warn('DeprecationWarning: Layer_decay_rate will ' + 'be deleted, please use decay_rate instead.') + paramwise_cfg['decay_rate'] = paramwise_cfg.pop('layer_decay_rate') + super().__init__(optim_wrapper_cfg, paramwise_cfg) diff --git a/third-party/InterFormer/mmseg/engine/schedulers/__init__.py b/third-party/InterFormer/mmseg/engine/schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd3f6211345bb3627b76d683291f48efd934a77 --- /dev/null +++ b/third-party/InterFormer/mmseg/engine/schedulers/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .poly_ratio_scheduler import PolyLRRatio + +__all__ = ['PolyLRRatio'] diff --git a/third-party/InterFormer/mmseg/engine/schedulers/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/engine/schedulers/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd135686c54352883517918c773d6edd36a2f9c3 Binary files /dev/null and b/third-party/InterFormer/mmseg/engine/schedulers/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/engine/schedulers/__pycache__/poly_ratio_scheduler.cpython-38.pyc b/third-party/InterFormer/mmseg/engine/schedulers/__pycache__/poly_ratio_scheduler.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2223c105a72c15bbbf55e267d69255a0c389a590 Binary files /dev/null and b/third-party/InterFormer/mmseg/engine/schedulers/__pycache__/poly_ratio_scheduler.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/engine/schedulers/poly_ratio_scheduler.py b/third-party/InterFormer/mmseg/engine/schedulers/poly_ratio_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..057203acc9cc9fc72306d2039669b90f35704436 --- /dev/null +++ b/third-party/InterFormer/mmseg/engine/schedulers/poly_ratio_scheduler.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional + +from mmengine.optim.scheduler import PolyLR + +from mmseg.registry import PARAM_SCHEDULERS + + +@PARAM_SCHEDULERS.register_module() +class PolyLRRatio(PolyLR): + """Implements polynomial learning rate decay with ratio. + + This scheduler adjusts the learning rate of each parameter group + following a polynomial decay equation. The decay can occur in + conjunction with external parameter adjustments made outside this + scheduler. + + Args: + optimizer (Optimizer or OptimWrapper): Wrapped optimizer. + eta_min (float): Minimum learning rate at the end of scheduling. + Defaults to 0. + eta_min_ratio (float, optional): The ratio of the minimum parameter + value to the base parameter value. Either `eta_min` or + `eta_min_ratio` should be specified. Defaults to None. + power (float): The power of the polynomial. Defaults to 1.0. + begin (int): Step at which to start updating the parameters. + Defaults to 0. + end (int): Step at which to stop updating the parameters. + Defaults to INF. + last_step (int): The index of last step. Used for resume without + state dict. Defaults to -1. + by_epoch (bool): Whether the scheduled parameters are updated by + epochs. Defaults to True. + verbose (bool): Whether to print the value for each update. + Defaults to False. + """ + + def __init__(self, eta_min_ratio: Optional[int] = None, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.eta_min_ratio = eta_min_ratio + + def _get_value(self): + """Compute value using chainable form of the scheduler.""" + + if self.last_step == 0: + return [ + group[self.param_name] for group in self.optimizer.param_groups + ] + + param_groups_value = [] + for base_value, param_group in zip(self.base_values, + self.optimizer.param_groups): + eta_min = self.eta_min if self.eta_min_ratio is None else \ + base_value * self.eta_min_ratio + step_ratio = (1 - 1 / + (self.total_iters - self.last_step + 1))**self.power + step_value = (param_group[self.param_name] - + eta_min) * step_ratio + eta_min + param_groups_value.append(step_value) + + return param_groups_value diff --git a/third-party/InterFormer/mmseg/evaluation/__init__.py b/third-party/InterFormer/mmseg/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..82b3a8d68d3aefcc23542fc1006eaddde05ca2ab --- /dev/null +++ b/third-party/InterFormer/mmseg/evaluation/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .metrics import CityscapesMetric, DepthMetric, IoUMetric + +__all__ = ['IoUMetric', 'CityscapesMetric', 'DepthMetric'] diff --git a/third-party/InterFormer/mmseg/evaluation/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/evaluation/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e01e67023011f3fe25cee7c1a0681e084250176 Binary files /dev/null and b/third-party/InterFormer/mmseg/evaluation/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/evaluation/metrics/__init__.py b/third-party/InterFormer/mmseg/evaluation/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..848d4713dc8c0b6a08569d536bb72bd04ca1b1cc --- /dev/null +++ b/third-party/InterFormer/mmseg/evaluation/metrics/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .citys_metric import CityscapesMetric +from .depth_metric import DepthMetric +from .iou_metric import IoUMetric + +__all__ = ['IoUMetric', 'CityscapesMetric', 'DepthMetric'] diff --git a/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5d29af172618335f97d6cad9716ce7ddff7ac42 Binary files /dev/null and b/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/citys_metric.cpython-38.pyc b/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/citys_metric.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb0105ae2b2d9fa0ca55eb9727ed0b1eeb574cba Binary files /dev/null and b/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/citys_metric.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/depth_metric.cpython-38.pyc b/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/depth_metric.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..977d132c1f8b0bf2b3f77a5fd35d5db39e56cb67 Binary files /dev/null and b/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/depth_metric.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/iou_metric.cpython-38.pyc b/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/iou_metric.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29ed733f2b24aaf3d57758a09489b37e70ea7102 Binary files /dev/null and b/third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/iou_metric.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/evaluation/metrics/citys_metric.py b/third-party/InterFormer/mmseg/evaluation/metrics/citys_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..32984653c3fa9c13d8c6a7402033001012b5031f --- /dev/null +++ b/third-party/InterFormer/mmseg/evaluation/metrics/citys_metric.py @@ -0,0 +1,158 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import shutil +from collections import OrderedDict +from typing import Dict, Optional, Sequence + +try: + + import cityscapesscripts.evaluation.evalPixelLevelSemanticLabeling as CSEval # noqa + import cityscapesscripts.helpers.labels as CSLabels +except ImportError: + CSLabels = None + CSEval = None + +import numpy as np +from mmengine.dist import is_main_process, master_only +from mmengine.evaluator import BaseMetric +from mmengine.logging import MMLogger, print_log +from mmengine.utils import mkdir_or_exist +from PIL import Image + +from mmseg.registry import METRICS + + +@METRICS.register_module() +class CityscapesMetric(BaseMetric): + """Cityscapes evaluation metric. + + Args: + output_dir (str): The directory for output prediction + ignore_index (int): Index that will be ignored in evaluation. + Default: 255. + format_only (bool): Only format result for results commit without + perform evaluation. It is useful when you want to format the result + to a specific format and submit it to the test server. + Defaults to False. + keep_results (bool): Whether to keep the results. When ``format_only`` + is True, ``keep_results`` must be True. Defaults to False. + collect_device (str): Device name used for collecting results from + different ranks during distributed training. Must be 'cpu' or + 'gpu'. Defaults to 'cpu'. + prefix (str, optional): The prefix that will be added in the metric + names to disambiguate homonymous metrics of different evaluators. + If prefix is not provided in the argument, self.default_prefix + will be used instead. Defaults to None. + """ + + def __init__(self, + output_dir: str, + ignore_index: int = 255, + format_only: bool = False, + keep_results: bool = False, + collect_device: str = 'cpu', + prefix: Optional[str] = None, + **kwargs) -> None: + super().__init__(collect_device=collect_device, prefix=prefix) + if CSEval is None: + raise ImportError('Please run "pip install cityscapesscripts" to ' + 'install cityscapesscripts first.') + self.output_dir = output_dir + self.ignore_index = ignore_index + + self.format_only = format_only + if format_only: + assert keep_results, ( + 'When format_only is True, the results must be keep, please ' + f'set keep_results as True, but got {keep_results}') + self.keep_results = keep_results + self.prefix = prefix + if is_main_process(): + mkdir_or_exist(self.output_dir) + + @master_only + def __del__(self) -> None: + """Clean up.""" + if not self.keep_results: + shutil.rmtree(self.output_dir) + + def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None: + """Process one batch of data and data_samples. + + The processed results should be stored in ``self.results``, which will + be used to computed the metrics when all batches have been processed. + + Args: + data_batch (dict): A batch of data from the dataloader. + data_samples (Sequence[dict]): A batch of outputs from the model. + """ + mkdir_or_exist(self.output_dir) + + for data_sample in data_samples: + pred_label = data_sample['pred_sem_seg']['data'][0].cpu().numpy() + # when evaluating with official cityscapesscripts, + # labelIds should be used + pred_label = self._convert_to_label_id(pred_label) + basename = osp.splitext(osp.basename(data_sample['img_path']))[0] + png_filename = osp.abspath( + osp.join(self.output_dir, f'{basename}.png')) + output = Image.fromarray(pred_label.astype(np.uint8)).convert('P') + output.save(png_filename) + if self.format_only: + # format_only always for test dataset without ground truth + gt_filename = '' + else: + # when evaluating with official cityscapesscripts, + # **_gtFine_labelIds.png is used + gt_filename = data_sample['seg_map_path'].replace( + 'labelTrainIds.png', 'labelIds.png') + self.results.append((png_filename, gt_filename)) + + def compute_metrics(self, results: list) -> Dict[str, float]: + """Compute the metrics from processed results. + + Args: + results (list): Testing results of the dataset. + + Returns: + dict[str: float]: Cityscapes evaluation results. + """ + logger: MMLogger = MMLogger.get_current_instance() + if self.format_only: + logger.info(f'results are saved to {osp.dirname(self.output_dir)}') + return OrderedDict() + + msg = 'Evaluating in Cityscapes style' + if logger is None: + msg = '\n' + msg + print_log(msg, logger=logger) + + eval_results = dict() + print_log( + f'Evaluating results under {self.output_dir} ...', logger=logger) + + CSEval.args.evalInstLevelScore = True + CSEval.args.predictionPath = osp.abspath(self.output_dir) + CSEval.args.evalPixelAccuracy = True + CSEval.args.JSONOutput = False + + pred_list, gt_list = zip(*results) + metric = dict() + eval_results.update( + CSEval.evaluateImgLists(pred_list, gt_list, CSEval.args)) + metric['averageScoreCategories'] = eval_results[ + 'averageScoreCategories'] + metric['averageScoreInstCategories'] = eval_results[ + 'averageScoreInstCategories'] + return metric + + @staticmethod + def _convert_to_label_id(result): + """Convert trainId to id for cityscapes.""" + if isinstance(result, str): + result = np.load(result) + result_copy = result.copy() + for trainId, label in CSLabels.trainId2label.items(): + result_copy[result == trainId] = label.id + + return result_copy diff --git a/third-party/InterFormer/mmseg/evaluation/metrics/depth_metric.py b/third-party/InterFormer/mmseg/evaluation/metrics/depth_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..621d4a31c9fe69cdbf83790e8f320218f755557a --- /dev/null +++ b/third-party/InterFormer/mmseg/evaluation/metrics/depth_metric.py @@ -0,0 +1,212 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from collections import OrderedDict, defaultdict +from typing import Dict, List, Optional, Sequence + +import cv2 +import numpy as np +import torch +from mmengine.dist import is_main_process +from mmengine.evaluator import BaseMetric +from mmengine.logging import MMLogger, print_log +from mmengine.utils import mkdir_or_exist +from prettytable import PrettyTable +from torch import Tensor + +from mmseg.registry import METRICS + + +@METRICS.register_module() +class DepthMetric(BaseMetric): + """Depth estimation evaluation metric. + + Args: + depth_metrics (List[str], optional): List of metrics to compute. If + not specified, defaults to all metrics in self.METRICS. + min_depth_eval (float): Minimum depth value for evaluation. + Defaults to 0.0. + max_depth_eval (float): Maximum depth value for evaluation. + Defaults to infinity. + crop_type (str, optional): Specifies the type of cropping to be used + during evaluation. This option can affect how the evaluation mask + is generated. Currently, 'nyu_crop' is supported, but other + types can be added in future. Defaults to None if no cropping + should be applied. + depth_scale_factor (float): Factor to scale the depth values. + Defaults to 1.0. + collect_device (str): Device name used for collecting results from + different ranks during distributed training. Must be 'cpu' or + 'gpu'. Defaults to 'cpu'. + output_dir (str): The directory for output prediction. Defaults to + None. + format_only (bool): Only format result for results commit without + perform evaluation. It is useful when you want to save the result + to a specific format and submit it to the test server. + Defaults to False. + prefix (str, optional): The prefix that will be added in the metric + names to disambiguate homonymous metrics of different evaluators. + If prefix is not provided in the argument, self.default_prefix + will be used instead. Defaults to None. + """ + METRICS = ('d1', 'd2', 'd3', 'abs_rel', 'sq_rel', 'rmse', 'rmse_log', + 'log10', 'silog') + + def __init__(self, + depth_metrics: Optional[List[str]] = None, + min_depth_eval: float = 0.0, + max_depth_eval: float = float('inf'), + crop_type: Optional[str] = None, + depth_scale_factor: float = 1.0, + collect_device: str = 'cpu', + output_dir: Optional[str] = None, + format_only: bool = False, + prefix: Optional[str] = None, + **kwargs) -> None: + super().__init__(collect_device=collect_device, prefix=prefix) + + if depth_metrics is None: + self.metrics = self.METRICS + elif isinstance(depth_metrics, [tuple, list]): + for metric in depth_metrics: + assert metric in self.METRICS, f'the metric {metric} is not ' \ + f'supported. Please use metrics in {self.METRICS}' + self.metrics = depth_metrics + + # Validate crop_type, if provided + assert crop_type in [ + None, 'nyu_crop' + ], (f'Invalid value for crop_type: {crop_type}. Supported values are ' + 'None or \'nyu_crop\'.') + self.crop_type = crop_type + self.min_depth_eval = min_depth_eval + self.max_depth_eval = max_depth_eval + self.output_dir = output_dir + if self.output_dir and is_main_process(): + mkdir_or_exist(self.output_dir) + self.format_only = format_only + self.depth_scale_factor = depth_scale_factor + + def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None: + """Process one batch of data and data_samples. + + The processed results should be stored in ``self.results``, which will + be used to compute the metrics when all batches have been processed. + + Args: + data_batch (dict): A batch of data from the dataloader. + data_samples (Sequence[dict]): A batch of outputs from the model. + """ + for data_sample in data_samples: + pred_label = data_sample['pred_depth_map']['data'].squeeze() + # format_only always for test dataset without ground truth + if not self.format_only: + gt_depth = data_sample['gt_depth_map']['data'].squeeze().to( + pred_label) + + eval_mask = self._get_eval_mask(gt_depth) + self.results.append( + (gt_depth[eval_mask], pred_label[eval_mask])) + # format_result + if self.output_dir is not None: + basename = osp.splitext(osp.basename( + data_sample['img_path']))[0] + png_filename = osp.abspath( + osp.join(self.output_dir, f'{basename}.png')) + output_mask = pred_label.cpu().numpy( + ) * self.depth_scale_factor + + cv2.imwrite(png_filename, output_mask.astype(np.uint16), + [cv2.IMWRITE_PNG_COMPRESSION, 0]) + + def _get_eval_mask(self, gt_depth: Tensor): + """Generates an evaluation mask based on ground truth depth and + cropping. + + Args: + gt_depth (Tensor): Ground truth depth map. + + Returns: + Tensor: Boolean mask where evaluation should be performed. + """ + valid_mask = torch.logical_and(gt_depth > self.min_depth_eval, + gt_depth < self.max_depth_eval) + + if self.crop_type == 'nyu_crop': + # this implementation is adapted from + # https://github.com/zhyever/Monocular-Depth-Estimation-Toolbox/blob/main/depth/datasets/nyu.py # noqa + crop_mask = torch.zeros_like(valid_mask) + crop_mask[45:471, 41:601] = 1 + else: + crop_mask = torch.ones_like(valid_mask) + + eval_mask = torch.logical_and(valid_mask, crop_mask) + return eval_mask + + @staticmethod + def _calc_all_metrics(gt_depth, pred_depth): + """Computes final evaluation metrics based on accumulated results.""" + assert gt_depth.shape == pred_depth.shape + + thresh = torch.max((gt_depth / pred_depth), (pred_depth / gt_depth)) + diff = pred_depth - gt_depth + diff_log = torch.log(pred_depth) - torch.log(gt_depth) + + d1 = torch.sum(thresh < 1.25).float() / len(thresh) + d2 = torch.sum(thresh < 1.25**2).float() / len(thresh) + d3 = torch.sum(thresh < 1.25**3).float() / len(thresh) + + abs_rel = torch.mean(torch.abs(diff) / gt_depth) + sq_rel = torch.mean(torch.pow(diff, 2) / gt_depth) + + rmse = torch.sqrt(torch.mean(torch.pow(diff, 2))) + rmse_log = torch.sqrt(torch.mean(torch.pow(diff_log, 2))) + + log10 = torch.mean( + torch.abs(torch.log10(pred_depth) - torch.log10(gt_depth))) + silog = torch.sqrt( + torch.pow(diff_log, 2).mean() - + 0.5 * torch.pow(diff_log.mean(), 2)) + + return { + 'd1': d1.item(), + 'd2': d2.item(), + 'd3': d3.item(), + 'abs_rel': abs_rel.item(), + 'sq_rel': sq_rel.item(), + 'rmse': rmse.item(), + 'rmse_log': rmse_log.item(), + 'log10': log10.item(), + 'silog': silog.item() + } + + def compute_metrics(self, results: list) -> Dict[str, float]: + """Compute the metrics from processed results. + + Args: + results (list): The processed results of each batch. + + Returns: + Dict[str, float]: The computed metrics. The keys are the names of + the metrics, and the values are corresponding results. The keys + are identical with self.metrics. + """ + logger: MMLogger = MMLogger.get_current_instance() + if self.format_only: + logger.info(f'results are saved to {osp.dirname(self.output_dir)}') + return OrderedDict() + + metrics = defaultdict(list) + for gt_depth, pred_depth in results: + for key, value in self._calc_all_metrics(gt_depth, + pred_depth).items(): + metrics[key].append(value) + metrics = {k: sum(metrics[k]) / len(metrics[k]) for k in self.metrics} + + table_data = PrettyTable() + for key, val in metrics.items(): + table_data.add_column(key, [round(val, 5)]) + + print_log('results:', logger) + print_log('\n' + table_data.get_string(), logger=logger) + + return metrics diff --git a/third-party/InterFormer/mmseg/evaluation/metrics/iou_metric.py b/third-party/InterFormer/mmseg/evaluation/metrics/iou_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..16014c74001d7295f9fff8f03ef185077e3f613b --- /dev/null +++ b/third-party/InterFormer/mmseg/evaluation/metrics/iou_metric.py @@ -0,0 +1,286 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from collections import OrderedDict +from typing import Dict, List, Optional, Sequence + +import numpy as np +import torch +from mmengine.dist import is_main_process +from mmengine.evaluator import BaseMetric +from mmengine.logging import MMLogger, print_log +from mmengine.utils import mkdir_or_exist +from PIL import Image +from prettytable import PrettyTable + +from mmseg.registry import METRICS + + +@METRICS.register_module() +class IoUMetric(BaseMetric): + """IoU evaluation metric. + + Args: + ignore_index (int): Index that will be ignored in evaluation. + Default: 255. + iou_metrics (list[str] | str): Metrics to be calculated, the options + includes 'mIoU', 'mDice' and 'mFscore'. + nan_to_num (int, optional): If specified, NaN values will be replaced + by the numbers defined by the user. Default: None. + beta (int): Determines the weight of recall in the combined score. + Default: 1. + collect_device (str): Device name used for collecting results from + different ranks during distributed training. Must be 'cpu' or + 'gpu'. Defaults to 'cpu'. + output_dir (str): The directory for output prediction. Defaults to + None. + format_only (bool): Only format result for results commit without + perform evaluation. It is useful when you want to save the result + to a specific format and submit it to the test server. + Defaults to False. + prefix (str, optional): The prefix that will be added in the metric + names to disambiguate homonymous metrics of different evaluators. + If prefix is not provided in the argument, self.default_prefix + will be used instead. Defaults to None. + """ + + def __init__(self, + ignore_index: int = 255, + iou_metrics: List[str] = ['mIoU'], + nan_to_num: Optional[int] = None, + beta: int = 1, + collect_device: str = 'cpu', + output_dir: Optional[str] = None, + format_only: bool = False, + prefix: Optional[str] = None, + **kwargs) -> None: + super().__init__(collect_device=collect_device, prefix=prefix) + + self.ignore_index = ignore_index + self.metrics = iou_metrics + self.nan_to_num = nan_to_num + self.beta = beta + self.output_dir = output_dir + if self.output_dir and is_main_process(): + mkdir_or_exist(self.output_dir) + self.format_only = format_only + + def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None: + """Process one batch of data and data_samples. + + The processed results should be stored in ``self.results``, which will + be used to compute the metrics when all batches have been processed. + + Args: + data_batch (dict): A batch of data from the dataloader. + data_samples (Sequence[dict]): A batch of outputs from the model. + """ + num_classes = len(self.dataset_meta['classes']) + for data_sample in data_samples: + pred_label = data_sample['pred_sem_seg']['data'].squeeze() + # format_only always for test dataset without ground truth + if not self.format_only: + label = data_sample['gt_sem_seg']['data'].squeeze().to( + pred_label) + self.results.append( + self.intersect_and_union(pred_label, label, num_classes, + self.ignore_index)) + # format_result + if self.output_dir is not None: + basename = osp.splitext(osp.basename( + data_sample['img_path']))[0] + png_filename = osp.abspath( + osp.join(self.output_dir, f'{basename}.png')) + output_mask = pred_label.cpu().numpy() + # The index range of official ADE20k dataset is from 0 to 150. + # But the index range of output is from 0 to 149. + # That is because we set reduce_zero_label=True. + if data_sample.get('reduce_zero_label', False): + output_mask = output_mask + 1 + output = Image.fromarray(output_mask.astype(np.uint8)) + output.save(png_filename) + + def compute_metrics(self, results: list) -> Dict[str, float]: + """Compute the metrics from processed results. + + Args: + results (list): The processed results of each batch. + + Returns: + Dict[str, float]: The computed metrics. The keys are the names of + the metrics, and the values are corresponding results. The key + mainly includes aAcc, mIoU, mAcc, mDice, mFscore, mPrecision, + mRecall. + """ + logger: MMLogger = MMLogger.get_current_instance() + if self.format_only: + logger.info(f'results are saved to {osp.dirname(self.output_dir)}') + return OrderedDict() + # convert list of tuples to tuple of lists, e.g. + # [(A_1, B_1, C_1, D_1), ..., (A_n, B_n, C_n, D_n)] to + # ([A_1, ..., A_n], ..., [D_1, ..., D_n]) + results = tuple(zip(*results)) + assert len(results) == 4 + + total_area_intersect = sum(results[0]) + total_area_union = sum(results[1]) + total_area_pred_label = sum(results[2]) + total_area_label = sum(results[3]) + ret_metrics = self.total_area_to_metrics( + total_area_intersect, total_area_union, total_area_pred_label, + total_area_label, self.metrics, self.nan_to_num, self.beta) + + class_names = self.dataset_meta['classes'] + + # summary table + ret_metrics_summary = OrderedDict({ + ret_metric: np.round(np.nanmean(ret_metric_value) * 100, 2) + for ret_metric, ret_metric_value in ret_metrics.items() + }) + metrics = dict() + for key, val in ret_metrics_summary.items(): + if key == 'aAcc': + metrics[key] = val + else: + metrics['m' + key] = val + + # each class table + ret_metrics.pop('aAcc', None) + ret_metrics_class = OrderedDict({ + ret_metric: np.round(ret_metric_value * 100, 2) + for ret_metric, ret_metric_value in ret_metrics.items() + }) + ret_metrics_class.update({'Class': class_names}) + ret_metrics_class.move_to_end('Class', last=False) + class_table_data = PrettyTable() + for key, val in ret_metrics_class.items(): + class_table_data.add_column(key, val) + + print_log('per class results:', logger) + print_log('\n' + class_table_data.get_string(), logger=logger) + + return metrics + + @staticmethod + def intersect_and_union(pred_label: torch.tensor, label: torch.tensor, + num_classes: int, ignore_index: int): + """Calculate Intersection and Union. + + Args: + pred_label (torch.tensor): Prediction segmentation map + or predict result filename. The shape is (H, W). + label (torch.tensor): Ground truth segmentation map + or label filename. The shape is (H, W). + num_classes (int): Number of categories. + ignore_index (int): Index that will be ignored in evaluation. + + Returns: + torch.Tensor: The intersection of prediction and ground truth + histogram on all classes. + torch.Tensor: The union of prediction and ground truth histogram on + all classes. + torch.Tensor: The prediction histogram on all classes. + torch.Tensor: The ground truth histogram on all classes. + """ + + mask = (label != ignore_index) + pred_label = pred_label[mask] + label = label[mask] + + intersect = pred_label[pred_label == label] + area_intersect = torch.histc( + intersect.float(), bins=(num_classes), min=0, + max=num_classes - 1).cpu() + area_pred_label = torch.histc( + pred_label.float(), bins=(num_classes), min=0, + max=num_classes - 1).cpu() + area_label = torch.histc( + label.float(), bins=(num_classes), min=0, + max=num_classes - 1).cpu() + area_union = area_pred_label + area_label - area_intersect + return area_intersect, area_union, area_pred_label, area_label + + @staticmethod + def total_area_to_metrics(total_area_intersect: np.ndarray, + total_area_union: np.ndarray, + total_area_pred_label: np.ndarray, + total_area_label: np.ndarray, + metrics: List[str] = ['mIoU'], + nan_to_num: Optional[int] = None, + beta: int = 1): + """Calculate evaluation metrics + Args: + total_area_intersect (np.ndarray): The intersection of prediction + and ground truth histogram on all classes. + total_area_union (np.ndarray): The union of prediction and ground + truth histogram on all classes. + total_area_pred_label (np.ndarray): The prediction histogram on + all classes. + total_area_label (np.ndarray): The ground truth histogram on + all classes. + metrics (List[str] | str): Metrics to be evaluated, 'mIoU' and + 'mDice'. + nan_to_num (int, optional): If specified, NaN values will be + replaced by the numbers defined by the user. Default: None. + beta (int): Determines the weight of recall in the combined score. + Default: 1. + Returns: + Dict[str, np.ndarray]: per category evaluation metrics, + shape (num_classes, ). + """ + + def f_score(precision, recall, beta=1): + """calculate the f-score value. + + Args: + precision (float | torch.Tensor): The precision value. + recall (float | torch.Tensor): The recall value. + beta (int): Determines the weight of recall in the combined + score. Default: 1. + + Returns: + [torch.tensor]: The f-score value. + """ + score = (1 + beta**2) * (precision * recall) / ( + (beta**2 * precision) + recall) + return score + + if isinstance(metrics, str): + metrics = [metrics] + allowed_metrics = ['mIoU', 'mDice', 'mFscore'] + if not set(metrics).issubset(set(allowed_metrics)): + raise KeyError(f'metrics {metrics} is not supported') + + all_acc = total_area_intersect.sum() / total_area_label.sum() + ret_metrics = OrderedDict({'aAcc': all_acc}) + for metric in metrics: + if metric == 'mIoU': + iou = total_area_intersect / total_area_union + acc = total_area_intersect / total_area_label + ret_metrics['IoU'] = iou + ret_metrics['Acc'] = acc + elif metric == 'mDice': + dice = 2 * total_area_intersect / ( + total_area_pred_label + total_area_label) + acc = total_area_intersect / total_area_label + ret_metrics['Dice'] = dice + ret_metrics['Acc'] = acc + elif metric == 'mFscore': + precision = total_area_intersect / total_area_pred_label + recall = total_area_intersect / total_area_label + f_value = torch.tensor([ + f_score(x[0], x[1], beta) for x in zip(precision, recall) + ]) + ret_metrics['Fscore'] = f_value + ret_metrics['Precision'] = precision + ret_metrics['Recall'] = recall + + ret_metrics = { + metric: value.numpy() + for metric, value in ret_metrics.items() + } + if nan_to_num is not None: + ret_metrics = OrderedDict({ + metric: np.nan_to_num(metric_value, nan=nan_to_num) + for metric, metric_value in ret_metrics.items() + }) + return ret_metrics diff --git a/third-party/InterFormer/mmseg/models/__init__.py b/third-party/InterFormer/mmseg/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a98951283c1ac4047c5f5ca3cdc827a43c42cf60 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .assigners import * # noqa: F401,F403 +from .backbones import * # noqa: F401,F403 +from .builder import (BACKBONES, HEADS, LOSSES, SEGMENTORS, build_backbone, + build_head, build_loss, build_segmentor) +from .data_preprocessor import SegDataPreProcessor +from .decode_heads import * # noqa: F401,F403 +from .losses import * # noqa: F401,F403 +from .necks import * # noqa: F401,F403 +from .segmentors import * # noqa: F401,F403 +from .text_encoder import * # noqa: F401,F403 + +__all__ = [ + 'BACKBONES', 'HEADS', 'LOSSES', 'SEGMENTORS', 'build_backbone', + 'build_head', 'build_loss', 'build_segmentor', 'SegDataPreProcessor' +] diff --git a/third-party/InterFormer/mmseg/models/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf6dcc4d7cc00fe625f867906484083e459ce363 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/__pycache__/builder.cpython-38.pyc b/third-party/InterFormer/mmseg/models/__pycache__/builder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..418328447c346c0fcbdfad3694f82bbbfacbde88 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/__pycache__/builder.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/__pycache__/data_preprocessor.cpython-38.pyc b/third-party/InterFormer/mmseg/models/__pycache__/data_preprocessor.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..926d01c95247b1fae0748ff74ab46210f03f76fc Binary files /dev/null and b/third-party/InterFormer/mmseg/models/__pycache__/data_preprocessor.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/assigners/__init__.py b/third-party/InterFormer/mmseg/models/assigners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d49b1b18b9e3e6d4e3b19c48eb1c80cbb1205f69 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/assigners/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .base_assigner import BaseAssigner +from .hungarian_assigner import HungarianAssigner +from .match_cost import ClassificationCost, CrossEntropyLossCost, DiceCost + +__all__ = [ + 'BaseAssigner', + 'HungarianAssigner', + 'ClassificationCost', + 'CrossEntropyLossCost', + 'DiceCost', +] diff --git a/third-party/InterFormer/mmseg/models/assigners/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/assigners/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cd6a348a9ff69d9a6e4cb5a6ebe7be762508653 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/assigners/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/assigners/__pycache__/base_assigner.cpython-38.pyc b/third-party/InterFormer/mmseg/models/assigners/__pycache__/base_assigner.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6417700294a1708458da8503e82d0f41f269b99 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/assigners/__pycache__/base_assigner.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/assigners/__pycache__/hungarian_assigner.cpython-38.pyc b/third-party/InterFormer/mmseg/models/assigners/__pycache__/hungarian_assigner.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18ec00b2b5aca69a3dd8cfcba155988586985aa2 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/assigners/__pycache__/hungarian_assigner.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/assigners/__pycache__/match_cost.cpython-38.pyc b/third-party/InterFormer/mmseg/models/assigners/__pycache__/match_cost.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..deff82ca7387a21611ae6caef662343bc438fba6 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/assigners/__pycache__/match_cost.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/assigners/base_assigner.py b/third-party/InterFormer/mmseg/models/assigners/base_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..97895cdac2789a62c3e8a381caaf944679f1e5a4 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/assigners/base_assigner.py @@ -0,0 +1,18 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from abc import ABCMeta, abstractmethod +from typing import Optional + +from mmengine.structures import InstanceData + + +class BaseAssigner(metaclass=ABCMeta): + """Base assigner that assigns masks to ground truth class labels.""" + + @abstractmethod + def assign(self, + pred_instances: InstanceData, + gt_instances: InstanceData, + gt_instances_ignore: Optional[InstanceData] = None, + **kwargs): + """Assign masks to either a ground truth class label or a negative + label.""" diff --git a/third-party/InterFormer/mmseg/models/assigners/hungarian_assigner.py b/third-party/InterFormer/mmseg/models/assigners/hungarian_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..28868f0a04e7feaf3de20e39fac5059d789047d3 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/assigners/hungarian_assigner.py @@ -0,0 +1,86 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Union + +import torch +from mmengine import ConfigDict +from mmengine.structures import InstanceData +from scipy.optimize import linear_sum_assignment +from torch.cuda.amp import autocast + +from mmseg.registry import TASK_UTILS +from .base_assigner import BaseAssigner + + +@TASK_UTILS.register_module() +class HungarianAssigner(BaseAssigner): + """Computes one-to-one matching between prediction masks and ground truth. + + This class uses bipartite matching-based assignment to computes an + assignment between the prediction masks and the ground truth. The + assignment result is based on the weighted sum of match costs. The + Hungarian algorithm is used to calculate the best matching with the + minimum cost. The prediction masks that are not matched are classified + as background. + + Args: + match_costs (ConfigDict|List[ConfigDict]): Match cost configs. + """ + + def __init__( + self, match_costs: Union[List[Union[dict, ConfigDict]], dict, + ConfigDict] + ) -> None: + + if isinstance(match_costs, dict): + match_costs = [match_costs] + elif isinstance(match_costs, list): + assert len(match_costs) > 0, \ + 'match_costs must not be a empty list.' + + self.match_costs = [ + TASK_UTILS.build(match_cost) for match_cost in match_costs + ] + + def assign(self, pred_instances: InstanceData, gt_instances: InstanceData, + **kwargs): + """Computes one-to-one matching based on the weighted costs. + + This method assign each query prediction to a ground truth or + background. The assignment first calculates the cost for each + category assigned to each query mask, and then uses the + Hungarian algorithm to calculate the minimum cost as the best + match. + + Args: + pred_instances (InstanceData): Instances of model + predictions. It includes "masks", with shape + (n, h, w) or (n, l), and "cls", with shape (n, num_classes+1) + gt_instances (InstanceData): Ground truth of instance + annotations. It includes "labels", with shape (k, ), + and "masks", with shape (k, h, w) or (k, l). + + Returns: + matched_quiery_inds (Tensor): The indexes of matched quieres. + matched_label_inds (Tensor): The indexes of matched labels. + """ + # compute weighted cost + cost_list = [] + with autocast(enabled=False): + for match_cost in self.match_costs: + cost = match_cost( + pred_instances=pred_instances, gt_instances=gt_instances) + cost_list.append(cost) + cost = torch.stack(cost_list).sum(dim=0) + + device = cost.device + # do Hungarian matching on CPU using linear_sum_assignment + cost = cost.detach().cpu() + if linear_sum_assignment is None: + raise ImportError('Please run "pip install scipy" ' + 'to install scipy first.') + + matched_quiery_inds, matched_label_inds = linear_sum_assignment(cost) + matched_quiery_inds = torch.from_numpy(matched_quiery_inds).to(device) + matched_label_inds = torch.from_numpy(matched_label_inds).to(device) + + return matched_quiery_inds, matched_label_inds diff --git a/third-party/InterFormer/mmseg/models/assigners/match_cost.py b/third-party/InterFormer/mmseg/models/assigners/match_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..560df852902fa7a2167cc7cfdf86595bf8d6e3f8 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/assigners/match_cost.py @@ -0,0 +1,231 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from abc import abstractmethod +from typing import Union + +import torch +import torch.nn.functional as F +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import TASK_UTILS + + +class BaseMatchCost: + """Base match cost class. + + Args: + weight (Union[float, int]): Cost weight. Defaults to 1. + """ + + def __init__(self, weight: Union[float, int] = 1.) -> None: + self.weight = weight + + @abstractmethod + def __call__(self, pred_instances: InstanceData, + gt_instances: InstanceData, **kwargs) -> Tensor: + """Compute match cost. + + Args: + pred_instances (InstanceData): Instances of model predictions. + It often includes "labels" and "scores". + gt_instances (InstanceData): Ground truth of instance + annotations. It usually includes "labels". + + Returns: + Tensor: Match Cost matrix of shape (num_preds, num_gts). + """ + pass + + +@TASK_UTILS.register_module() +class ClassificationCost(BaseMatchCost): + """ClsSoftmaxCost. + + Args: + weight (Union[float, int]): Cost weight. Defaults to 1. + + Examples: + >>> from mmseg.models.assigners import ClassificationCost + >>> import torch + >>> self = ClassificationCost() + >>> cls_pred = torch.rand(4, 3) + >>> gt_labels = torch.tensor([0, 1, 2]) + >>> factor = torch.tensor([10, 8, 10, 8]) + >>> self(cls_pred, gt_labels) + tensor([[-0.3430, -0.3525, -0.3045], + [-0.3077, -0.2931, -0.3992], + [-0.3664, -0.3455, -0.2881], + [-0.3343, -0.2701, -0.3956]]) + """ + + def __init__(self, weight: Union[float, int] = 1) -> None: + super().__init__(weight=weight) + + def __call__(self, pred_instances: InstanceData, + gt_instances: InstanceData, **kwargs) -> Tensor: + """Compute match cost. + + Args: + pred_instances (InstanceData): "scores" inside is + predicted classification logits, of shape + (num_queries, num_class). + gt_instances (InstanceData): "labels" inside should have + shape (num_gt, ). + + Returns: + Tensor: Match Cost matrix of shape (num_preds, num_gts). + """ + assert hasattr(pred_instances, 'scores'), \ + "pred_instances must contain 'scores'" + assert hasattr(gt_instances, 'labels'), \ + "gt_instances must contain 'labels'" + pred_scores = pred_instances.scores + gt_labels = gt_instances.labels + + pred_scores = pred_scores.softmax(-1) + cls_cost = -pred_scores[:, gt_labels] + + return cls_cost * self.weight + + +@TASK_UTILS.register_module() +class DiceCost(BaseMatchCost): + """Cost of mask assignments based on dice losses. + + Args: + pred_act (bool): Whether to apply sigmoid to mask_pred. + Defaults to False. + eps (float): Defaults to 1e-3. + naive_dice (bool): If True, use the naive dice loss + in which the power of the number in the denominator is + the first power. If False, use the second power that + is adopted by K-Net and SOLO. Defaults to True. + weight (Union[float, int]): Cost weight. Defaults to 1. + """ + + def __init__(self, + pred_act: bool = False, + eps: float = 1e-3, + naive_dice: bool = True, + weight: Union[float, int] = 1.) -> None: + super().__init__(weight=weight) + self.pred_act = pred_act + self.eps = eps + self.naive_dice = naive_dice + + def _binary_mask_dice_loss(self, mask_preds: Tensor, + gt_masks: Tensor) -> Tensor: + """ + Args: + mask_preds (Tensor): Mask prediction in shape (num_queries, *). + gt_masks (Tensor): Ground truth in shape (num_gt, *) + store 0 or 1, 0 for negative class and 1 for + positive class. + + Returns: + Tensor: Dice cost matrix in shape (num_queries, num_gt). + """ + mask_preds = mask_preds.flatten(1) + gt_masks = gt_masks.flatten(1).float() + numerator = 2 * torch.einsum('nc,mc->nm', mask_preds, gt_masks) + if self.naive_dice: + denominator = mask_preds.sum(-1)[:, None] + \ + gt_masks.sum(-1)[None, :] + else: + denominator = mask_preds.pow(2).sum(1)[:, None] + \ + gt_masks.pow(2).sum(1)[None, :] + loss = 1 - (numerator + self.eps) / (denominator + self.eps) + return loss + + def __call__(self, pred_instances: InstanceData, + gt_instances: InstanceData, **kwargs) -> Tensor: + """Compute match cost. + + Args: + pred_instances (InstanceData): Predicted instances which + must contain "masks". + gt_instances (InstanceData): Ground truth which must contain + "mask". + + Returns: + Tensor: Match Cost matrix of shape (num_preds, num_gts). + """ + assert hasattr(pred_instances, 'masks'), \ + "pred_instances must contain 'masks'" + assert hasattr(gt_instances, 'masks'), \ + "gt_instances must contain 'masks'" + pred_masks = pred_instances.masks + gt_masks = gt_instances.masks + + if self.pred_act: + pred_masks = pred_masks.sigmoid() + dice_cost = self._binary_mask_dice_loss(pred_masks, gt_masks) + return dice_cost * self.weight + + +@TASK_UTILS.register_module() +class CrossEntropyLossCost(BaseMatchCost): + """CrossEntropyLossCost. + + Args: + use_sigmoid (bool): Whether the prediction uses sigmoid + of softmax. Defaults to True. + weight (Union[float, int]): Cost weight. Defaults to 1. + """ + + def __init__(self, + use_sigmoid: bool = True, + weight: Union[float, int] = 1.) -> None: + super().__init__(weight=weight) + self.use_sigmoid = use_sigmoid + + def _binary_cross_entropy(self, cls_pred: Tensor, + gt_labels: Tensor) -> Tensor: + """ + Args: + cls_pred (Tensor): The prediction with shape (num_queries, 1, *) or + (num_queries, *). + gt_labels (Tensor): The learning label of prediction with + shape (num_gt, *). + + Returns: + Tensor: Cross entropy cost matrix in shape (num_queries, num_gt). + """ + cls_pred = cls_pred.flatten(1).float() + gt_labels = gt_labels.flatten(1).float() + n = cls_pred.shape[1] + pos = F.binary_cross_entropy_with_logits( + cls_pred, torch.ones_like(cls_pred), reduction='none') + neg = F.binary_cross_entropy_with_logits( + cls_pred, torch.zeros_like(cls_pred), reduction='none') + cls_cost = torch.einsum('nc,mc->nm', pos, gt_labels) + \ + torch.einsum('nc,mc->nm', neg, 1 - gt_labels) + cls_cost = cls_cost / n + + return cls_cost + + def __call__(self, pred_instances: InstanceData, + gt_instances: InstanceData, **kwargs) -> Tensor: + """Compute match cost. + + Args: + pred_instances (:obj:`InstanceData`): Predicted instances which + must contain ``masks``. + gt_instances (:obj:`InstanceData`): Ground truth which must contain + ``masks``. + + Returns: + Tensor: Match Cost matrix of shape (num_preds, num_gts). + """ + assert hasattr(pred_instances, 'masks'), \ + "pred_instances must contain 'masks'" + assert hasattr(gt_instances, 'masks'), \ + "gt_instances must contain 'masks'" + pred_masks = pred_instances.masks + gt_masks = gt_instances.masks + if self.use_sigmoid: + cls_cost = self._binary_cross_entropy(pred_masks, gt_masks) + else: + raise NotImplementedError + + return cls_cost * self.weight diff --git a/third-party/InterFormer/mmseg/models/backbones/__init__.py b/third-party/InterFormer/mmseg/models/backbones/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..784d3dfdb709f6b63f042836b0fe4047271e05a5 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/__init__.py @@ -0,0 +1,35 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .beit import BEiT +from .bisenetv1 import BiSeNetV1 +from .bisenetv2 import BiSeNetV2 +from .cgnet import CGNet +from .ddrnet import DDRNet +from .erfnet import ERFNet +from .fast_scnn import FastSCNN +from .hrnet import HRNet +from .icnet import ICNet +from .mae import MAE +from .mit import MixVisionTransformer +from .mobilenet_v2 import MobileNetV2 +from .mobilenet_v3 import MobileNetV3 +from .mscan import MSCAN +from .pidnet import PIDNet +from .resnest import ResNeSt +from .resnet import ResNet, ResNetV1c, ResNetV1d +from .resnext import ResNeXt +from .stdc import STDCContextPathNet, STDCNet +from .swin import SwinTransformer +from .timm_backbone import TIMMBackbone +from .twins import PCPVT, SVT +from .unet import UNet +from .vit import VisionTransformer +from .vpd import VPD + +__all__ = [ + 'ResNet', 'ResNetV1c', 'ResNetV1d', 'ResNeXt', 'HRNet', 'FastSCNN', + 'ResNeSt', 'MobileNetV2', 'UNet', 'CGNet', 'MobileNetV3', + 'VisionTransformer', 'SwinTransformer', 'MixVisionTransformer', + 'BiSeNetV1', 'BiSeNetV2', 'ICNet', 'TIMMBackbone', 'ERFNet', 'PCPVT', + 'SVT', 'STDCNet', 'STDCContextPathNet', 'BEiT', 'MAE', 'PIDNet', 'MSCAN', + 'DDRNet', 'VPD' +] diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53853f5e39f4ba61b588b9d029dd07a867a18d05 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/beit.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/beit.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4ec31a9dd76ba5d1ea16ee6b53e5bfb50c2db1f Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/beit.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/bisenetv1.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/bisenetv1.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6636d0366aab4c80c4626b792e2027b7dab60762 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/bisenetv1.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/bisenetv2.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/bisenetv2.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac5a93ea73f0210907856fd48f5bf4835ec80901 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/bisenetv2.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/cgnet.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/cgnet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92c1350f8cb78c5025954b176bfeb029d56e4c3d Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/cgnet.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/ddrnet.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/ddrnet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..281f3956ffc6c39c9eb1c55416c92d8783f6de02 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/ddrnet.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/erfnet.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/erfnet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1e82fa1ba7d7a6d9685569745399a01c2334072 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/erfnet.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/fast_scnn.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/fast_scnn.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5ff2eae8371ee0a2ceb306fc47e98a1cae55903 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/fast_scnn.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/hrnet.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/hrnet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caa8b1e317883bb45e217ecbf3a58cb6dcef36c4 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/hrnet.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/icnet.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/icnet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10355e6937ccc7156b9d846a3131dbe048471695 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/icnet.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/mae.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mae.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..296cc645ff0cb4026349abad7a9602c66d89a4e8 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mae.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/mit.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mit.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23147bf02e3721b4bdca9f339c423957c56ff409 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mit.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/mobilenet_v2.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mobilenet_v2.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d1d0ccafe5044c1a267c6f7ef37f4ce0f5bb85b Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mobilenet_v2.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/mobilenet_v3.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mobilenet_v3.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9842d2ba452c654050e9e1c0cf16eefc93d684ed Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mobilenet_v3.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/mscan.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mscan.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65822e2f8d80293843813a3433c62fd26dbb72a6 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/mscan.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/pidnet.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/pidnet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d4c8d524096c8258613aecb4f0df4cb47b69fd8 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/pidnet.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnest.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnest.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1bcc5705c535b7d641791aac4253adb175ec3bb Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnest.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnet.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3808098ffc58d50f81e04602b6a11d0cb8685894 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnet.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnext.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnext.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e772f21f0670485bbe2c22971c5792c0ed20926 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/resnext.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/stdc.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/stdc.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c49172f9390bd49634af90631c1d37dc6fc1180c Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/stdc.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/swin.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/swin.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6b75bac8cd8e5114f04848529543df19945ec67 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/swin.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/timm_backbone.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/timm_backbone.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb776a8ee7def63e1fcbb9671971d0f744cc5956 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/timm_backbone.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/twins.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/twins.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5b4edaf1366eee8356e8d5bbe30c9dbd85781f0 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/twins.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/unet.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/unet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cc8d08ee03a03feae945d13873a92c7ad38fa37 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/unet.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/vit.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/vit.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36c5faa84a32966b67a9348d60f2b5d90238d7c9 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/vit.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/__pycache__/vpd.cpython-38.pyc b/third-party/InterFormer/mmseg/models/backbones/__pycache__/vpd.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3881898bffae4278a1e3e28ac51d03984e19e704 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/backbones/__pycache__/vpd.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/backbones/beit.py b/third-party/InterFormer/mmseg/models/backbones/beit.py new file mode 100644 index 0000000000000000000000000000000000000000..e5da71e729256a9dd12b70d32886c9db27d9fa3c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/beit.py @@ -0,0 +1,554 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import build_norm_layer +from mmcv.cnn.bricks.drop import build_dropout +from mmengine.model import BaseModule, ModuleList +from mmengine.model.weight_init import (constant_init, kaiming_init, + trunc_normal_) +from mmengine.runner.checkpoint import _load_checkpoint +from scipy import interpolate +from torch.nn.modules.batchnorm import _BatchNorm +from torch.nn.modules.utils import _pair as to_2tuple + +from mmseg.registry import MODELS +from ..utils import PatchEmbed +from .vit import TransformerEncoderLayer as VisionTransformerEncoderLayer + + +class BEiTAttention(BaseModule): + """Window based multi-head self-attention (W-MSA) module with relative + position bias. + + Args: + embed_dims (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (tuple[int]): The height and width of the window. + bias (bool): The option to add leanable bias for q, k, v. If bias is + True, it will add leanable bias. If bias is 'qv_bias', it will only + add leanable bias for q, v. If bias is False, it will not add bias + for q, k, v. Default to 'qv_bias'. + qk_scale (float | None, optional): Override default qk scale of + head_dim ** -0.5 if set. Default: None. + attn_drop_rate (float): Dropout ratio of attention weight. + Default: 0.0 + proj_drop_rate (float): Dropout ratio of output. Default: 0. + init_cfg (dict | None, optional): The Config for initialization. + Default: None. + """ + + def __init__(self, + embed_dims, + num_heads, + window_size, + bias='qv_bias', + qk_scale=None, + attn_drop_rate=0., + proj_drop_rate=0., + init_cfg=None, + **kwargs): + super().__init__(init_cfg=init_cfg) + self.embed_dims = embed_dims + self.num_heads = num_heads + head_embed_dims = embed_dims // num_heads + self.bias = bias + self.scale = qk_scale or head_embed_dims**-0.5 + + qkv_bias = bias + if bias == 'qv_bias': + self._init_qv_bias() + qkv_bias = False + + self.window_size = window_size + self._init_rel_pos_embedding() + + self.qkv = nn.Linear(embed_dims, embed_dims * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop_rate) + self.proj = nn.Linear(embed_dims, embed_dims) + self.proj_drop = nn.Dropout(proj_drop_rate) + + def _init_qv_bias(self): + self.q_bias = nn.Parameter(torch.zeros(self.embed_dims)) + self.v_bias = nn.Parameter(torch.zeros(self.embed_dims)) + + def _init_rel_pos_embedding(self): + Wh, Ww = self.window_size + # cls to token & token 2 cls & cls to cls + self.num_relative_distance = (2 * Wh - 1) * (2 * Ww - 1) + 3 + # relative_position_bias_table shape is (2*Wh-1 * 2*Ww-1 + 3, nH) + self.relative_position_bias_table = nn.Parameter( + torch.zeros(self.num_relative_distance, self.num_heads)) + + # get pair-wise relative position index for + # each token inside the window + coords_h = torch.arange(Wh) + coords_w = torch.arange(Ww) + # coords shape is (2, Wh, Ww) + coords = torch.stack(torch.meshgrid([coords_h, coords_w])) + # coords_flatten shape is (2, Wh*Ww) + coords_flatten = torch.flatten(coords, 1) + relative_coords = ( + coords_flatten[:, :, None] - coords_flatten[:, None, :]) + # relative_coords shape is (Wh*Ww, Wh*Ww, 2) + relative_coords = relative_coords.permute(1, 2, 0).contiguous() + # shift to start from 0 + relative_coords[:, :, 0] += Wh - 1 + relative_coords[:, :, 1] += Ww - 1 + relative_coords[:, :, 0] *= 2 * Ww - 1 + relative_position_index = torch.zeros( + size=(Wh * Ww + 1, ) * 2, dtype=relative_coords.dtype) + # relative_position_index shape is (Wh*Ww, Wh*Ww) + relative_position_index[1:, 1:] = relative_coords.sum(-1) + relative_position_index[0, 0:] = self.num_relative_distance - 3 + relative_position_index[0:, 0] = self.num_relative_distance - 2 + relative_position_index[0, 0] = self.num_relative_distance - 1 + + self.register_buffer('relative_position_index', + relative_position_index) + + def init_weights(self): + trunc_normal_(self.relative_position_bias_table, std=0.02) + + def forward(self, x): + """ + Args: + x (tensor): input features with shape of (num_windows*B, N, C). + """ + B, N, C = x.shape + + if self.bias == 'qv_bias': + k_bias = torch.zeros_like(self.v_bias, requires_grad=False) + qkv_bias = torch.cat((self.q_bias, k_bias, self.v_bias)) + qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) + else: + qkv = self.qkv(x) + + qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + q = q * self.scale + attn = (q @ k.transpose(-2, -1)) + if self.relative_position_bias_table is not None: + Wh = self.window_size[0] + Ww = self.window_size[1] + relative_position_bias = self.relative_position_bias_table[ + self.relative_position_index.view(-1)].view( + Wh * Ww + 1, Wh * Ww + 1, -1) + relative_position_bias = relative_position_bias.permute( + 2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class BEiTTransformerEncoderLayer(VisionTransformerEncoderLayer): + """Implements one encoder layer in Vision Transformer. + + Args: + embed_dims (int): The feature dimension. + num_heads (int): Parallel attention heads. + feedforward_channels (int): The hidden dimension for FFNs. + attn_drop_rate (float): The drop out rate for attention layer. + Default: 0.0. + drop_path_rate (float): Stochastic depth rate. Default 0.0. + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + bias (bool): The option to add leanable bias for q, k, v. If bias is + True, it will add leanable bias. If bias is 'qv_bias', it will only + add leanable bias for q, v. If bias is False, it will not add bias + for q, k, v. Default to 'qv_bias'. + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + window_size (tuple[int], optional): The height and width of the window. + Default: None. + init_values (float, optional): Initialize the values of BEiTAttention + and FFN with learnable scaling. Default: None. + """ + + def __init__(self, + embed_dims, + num_heads, + feedforward_channels, + attn_drop_rate=0., + drop_path_rate=0., + num_fcs=2, + bias='qv_bias', + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + window_size=None, + attn_cfg=dict(), + ffn_cfg=dict(add_identity=False), + init_values=None): + attn_cfg.update(dict(window_size=window_size, qk_scale=None)) + + super().__init__( + embed_dims=embed_dims, + num_heads=num_heads, + feedforward_channels=feedforward_channels, + attn_drop_rate=attn_drop_rate, + drop_path_rate=0., + drop_rate=0., + num_fcs=num_fcs, + qkv_bias=bias, + act_cfg=act_cfg, + norm_cfg=norm_cfg, + attn_cfg=attn_cfg, + ffn_cfg=ffn_cfg) + + # NOTE: drop path for stochastic depth, we shall see if + # this is better than dropout here + dropout_layer = dict(type='DropPath', drop_prob=drop_path_rate) + self.drop_path = build_dropout( + dropout_layer) if dropout_layer else nn.Identity() + self.gamma_1 = nn.Parameter( + init_values * torch.ones(embed_dims), requires_grad=True) + self.gamma_2 = nn.Parameter( + init_values * torch.ones(embed_dims), requires_grad=True) + + def build_attn(self, attn_cfg): + self.attn = BEiTAttention(**attn_cfg) + + def forward(self, x): + x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x))) + x = x + self.drop_path(self.gamma_2 * self.ffn(self.norm2(x))) + return x + + +@MODELS.register_module() +class BEiT(BaseModule): + """BERT Pre-Training of Image Transformers. + + Args: + img_size (int | tuple): Input image size. Default: 224. + patch_size (int): The patch size. Default: 16. + in_channels (int): Number of input channels. Default: 3. + embed_dims (int): Embedding dimension. Default: 768. + num_layers (int): Depth of transformer. Default: 12. + num_heads (int): Number of attention heads. Default: 12. + mlp_ratio (int): Ratio of mlp hidden dim to embedding dim. + Default: 4. + out_indices (list | tuple | int): Output from which stages. + Default: -1. + qv_bias (bool): Enable bias for qv if True. Default: True. + attn_drop_rate (float): The drop out rate for attention layer. + Default 0.0 + drop_path_rate (float): Stochastic depth rate. Default 0.0. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN') + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + patch_norm (bool): Whether to add a norm in PatchEmbed Block. + Default: False. + final_norm (bool): Whether to add a additional layer to normalize + final feature map. Default: False. + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + pretrained (str, optional): Model pretrained path. Default: None. + init_values (float): Initialize the values of BEiTAttention and FFN + with learnable scaling. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + img_size=224, + patch_size=16, + in_channels=3, + embed_dims=768, + num_layers=12, + num_heads=12, + mlp_ratio=4, + out_indices=-1, + qv_bias=True, + attn_drop_rate=0., + drop_path_rate=0., + norm_cfg=dict(type='LN'), + act_cfg=dict(type='GELU'), + patch_norm=False, + final_norm=False, + num_fcs=2, + norm_eval=False, + pretrained=None, + init_values=0.1, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + if isinstance(img_size, int): + img_size = to_2tuple(img_size) + elif isinstance(img_size, tuple): + if len(img_size) == 1: + img_size = to_2tuple(img_size[0]) + assert len(img_size) == 2, \ + f'The size of image should have length 1 or 2, ' \ + f'but got {len(img_size)}' + + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be set at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is not None: + raise TypeError('pretrained must be a str or None') + + self.in_channels = in_channels + self.img_size = img_size + self.patch_size = patch_size + self.norm_eval = norm_eval + self.pretrained = pretrained + self.num_layers = num_layers + self.embed_dims = embed_dims + self.num_heads = num_heads + self.mlp_ratio = mlp_ratio + self.attn_drop_rate = attn_drop_rate + self.drop_path_rate = drop_path_rate + self.num_fcs = num_fcs + self.qv_bias = qv_bias + self.act_cfg = act_cfg + self.norm_cfg = norm_cfg + self.patch_norm = patch_norm + self.init_values = init_values + self.window_size = (img_size[0] // patch_size, + img_size[1] // patch_size) + self.patch_shape = self.window_size + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dims)) + + self._build_patch_embedding() + self._build_layers() + + if isinstance(out_indices, int): + if out_indices == -1: + out_indices = num_layers - 1 + self.out_indices = [out_indices] + elif isinstance(out_indices, list) or isinstance(out_indices, tuple): + self.out_indices = out_indices + else: + raise TypeError('out_indices must be type of int, list or tuple') + + self.final_norm = final_norm + if final_norm: + self.norm1_name, norm1 = build_norm_layer( + norm_cfg, embed_dims, postfix=1) + self.add_module(self.norm1_name, norm1) + + def _build_patch_embedding(self): + """Build patch embedding layer.""" + self.patch_embed = PatchEmbed( + in_channels=self.in_channels, + embed_dims=self.embed_dims, + conv_type='Conv2d', + kernel_size=self.patch_size, + stride=self.patch_size, + padding=0, + norm_cfg=self.norm_cfg if self.patch_norm else None, + init_cfg=None) + + def _build_layers(self): + """Build transformer encoding layers.""" + + dpr = [ + x.item() + for x in torch.linspace(0, self.drop_path_rate, self.num_layers) + ] + self.layers = ModuleList() + for i in range(self.num_layers): + self.layers.append( + BEiTTransformerEncoderLayer( + embed_dims=self.embed_dims, + num_heads=self.num_heads, + feedforward_channels=self.mlp_ratio * self.embed_dims, + attn_drop_rate=self.attn_drop_rate, + drop_path_rate=dpr[i], + num_fcs=self.num_fcs, + bias='qv_bias' if self.qv_bias else False, + act_cfg=self.act_cfg, + norm_cfg=self.norm_cfg, + window_size=self.window_size, + init_values=self.init_values)) + + @property + def norm1(self): + return getattr(self, self.norm1_name) + + def _geometric_sequence_interpolation(self, src_size, dst_size, sequence, + num): + """Get new sequence via geometric sequence interpolation. + + Args: + src_size (int): Pos_embedding size in pre-trained model. + dst_size (int): Pos_embedding size in the current model. + sequence (tensor): The relative position bias of the pretrain + model after removing the extra tokens. + num (int): Number of attention heads. + Returns: + new_sequence (tensor): Geometric sequence interpolate the + pre-trained relative position bias to the size of + the current model. + """ + + def geometric_progression(a, r, n): + return a * (1.0 - r**n) / (1.0 - r) + + # Here is a binary function. + left, right = 1.01, 1.5 + while right - left > 1e-6: + q = (left + right) / 2.0 + gp = geometric_progression(1, q, src_size // 2) + if gp > dst_size // 2: + right = q + else: + left = q + # The position of each interpolated point is determined + # by the ratio obtained by dichotomy. + dis = [] + cur = 1 + for i in range(src_size // 2): + dis.append(cur) + cur += q**(i + 1) + r_ids = [-_ for _ in reversed(dis)] + x = r_ids + [0] + dis + y = r_ids + [0] + dis + t = dst_size // 2.0 + dx = np.arange(-t, t + 0.1, 1.0) + dy = np.arange(-t, t + 0.1, 1.0) + # Interpolation functions are being executed and called. + new_sequence = [] + for i in range(num): + z = sequence[:, i].view(src_size, src_size).float().numpy() + f = interpolate.interp2d(x, y, z, kind='cubic') + new_sequence.append( + torch.Tensor(f(dx, dy)).contiguous().view(-1, 1).to(sequence)) + new_sequence = torch.cat(new_sequence, dim=-1) + return new_sequence + + def resize_rel_pos_embed(self, checkpoint): + """Resize relative pos_embed weights. + + This function is modified from + https://github.com/microsoft/unilm/blob/master/beit/semantic_segmentation/mmcv_custom/checkpoint.py. # noqa: E501 + Copyright (c) Microsoft Corporation + Licensed under the MIT License + Args: + checkpoint (dict): Key and value of the pretrain model. + Returns: + state_dict (dict): Interpolate the relative pos_embed weights + in the pre-train model to the current model size. + """ + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + + all_keys = list(state_dict.keys()) + for key in all_keys: + if 'relative_position_index' in key: + state_dict.pop(key) + # In order to keep the center of pos_bias as consistent as + # possible after interpolation, and vice versa in the edge + # area, the geometric sequence interpolation method is adopted. + if 'relative_position_bias_table' in key: + rel_pos_bias = state_dict[key] + src_num_pos, num_attn_heads = rel_pos_bias.size() + dst_num_pos, _ = self.state_dict()[key].size() + dst_patch_shape = self.patch_shape + if dst_patch_shape[0] != dst_patch_shape[1]: + raise NotImplementedError() + # Count the number of extra tokens. + num_extra_tokens = dst_num_pos - ( + dst_patch_shape[0] * 2 - 1) * ( + dst_patch_shape[1] * 2 - 1) + src_size = int((src_num_pos - num_extra_tokens)**0.5) + dst_size = int((dst_num_pos - num_extra_tokens)**0.5) + if src_size != dst_size: + extra_tokens = rel_pos_bias[-num_extra_tokens:, :] + rel_pos_bias = rel_pos_bias[:-num_extra_tokens, :] + new_rel_pos_bias = self._geometric_sequence_interpolation( + src_size, dst_size, rel_pos_bias, num_attn_heads) + new_rel_pos_bias = torch.cat( + (new_rel_pos_bias, extra_tokens), dim=0) + state_dict[key] = new_rel_pos_bias + + return state_dict + + def init_weights(self): + + def _init_weights(m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + self.apply(_init_weights) + + if (isinstance(self.init_cfg, dict) + and self.init_cfg.get('type') == 'Pretrained'): + checkpoint = _load_checkpoint( + self.init_cfg['checkpoint'], logger=None, map_location='cpu') + state_dict = self.resize_rel_pos_embed(checkpoint) + self.load_state_dict(state_dict, False) + elif self.init_cfg is not None: + super().init_weights() + else: + # We only implement the 'jax_impl' initialization implemented at + # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py#L353 # noqa: E501 + # Copyright 2019 Ross Wightman + # Licensed under the Apache License, Version 2.0 (the "License") + trunc_normal_(self.cls_token, std=.02) + for n, m in self.named_modules(): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if m.bias is not None: + if 'ffn' in n: + nn.init.normal_(m.bias, mean=0., std=1e-6) + else: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv2d): + kaiming_init(m, mode='fan_in', bias=0.) + elif isinstance(m, (_BatchNorm, nn.GroupNorm, nn.LayerNorm)): + constant_init(m, val=1.0, bias=0.) + + def forward(self, inputs): + B = inputs.shape[0] + + x, hw_shape = self.patch_embed(inputs) + + # stole cls_tokens impl from Phil Wang, thanks + cls_tokens = self.cls_token.expand(B, -1, -1) + x = torch.cat((cls_tokens, x), dim=1) + + outs = [] + for i, layer in enumerate(self.layers): + x = layer(x) + if i == len(self.layers) - 1: + if self.final_norm: + x = self.norm1(x) + if i in self.out_indices: + # Remove class token and reshape token for decoder head + out = x[:, 1:] + B, _, C = out.shape + out = out.reshape(B, hw_shape[0], hw_shape[1], + C).permute(0, 3, 1, 2).contiguous() + outs.append(out) + + return tuple(outs) + + def train(self, mode=True): + super().train(mode) + if mode and self.norm_eval: + for m in self.modules(): + if isinstance(m, nn.LayerNorm): + m.eval() diff --git a/third-party/InterFormer/mmseg/models/backbones/bisenetv1.py b/third-party/InterFormer/mmseg/models/backbones/bisenetv1.py new file mode 100644 index 0000000000000000000000000000000000000000..ca58bf9c597836937bc384739ff77001b5402942 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/bisenetv1.py @@ -0,0 +1,332 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +class SpatialPath(BaseModule): + """Spatial Path to preserve the spatial size of the original input image + and encode affluent spatial information. + + Args: + in_channels(int): The number of channels of input + image. Default: 3. + num_channels (Tuple[int]): The number of channels of + each layers in Spatial Path. + Default: (64, 64, 64, 128). + Returns: + x (torch.Tensor): Feature map for Feature Fusion Module. + """ + + def __init__(self, + in_channels=3, + num_channels=(64, 64, 64, 128), + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert len(num_channels) == 4, 'Length of input channels \ + of Spatial Path must be 4!' + + self.layers = [] + for i in range(len(num_channels)): + layer_name = f'layer{i + 1}' + self.layers.append(layer_name) + if i == 0: + self.add_module( + layer_name, + ConvModule( + in_channels=in_channels, + out_channels=num_channels[i], + kernel_size=7, + stride=2, + padding=3, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + elif i == len(num_channels) - 1: + self.add_module( + layer_name, + ConvModule( + in_channels=num_channels[i - 1], + out_channels=num_channels[i], + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + else: + self.add_module( + layer_name, + ConvModule( + in_channels=num_channels[i - 1], + out_channels=num_channels[i], + kernel_size=3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + def forward(self, x): + for i, layer_name in enumerate(self.layers): + layer_stage = getattr(self, layer_name) + x = layer_stage(x) + return x + + +class AttentionRefinementModule(BaseModule): + """Attention Refinement Module (ARM) to refine the features of each stage. + + Args: + in_channels (int): The number of input channels. + out_channels (int): The number of output channels. + Returns: + x_out (torch.Tensor): Feature map of Attention Refinement Module. + """ + + def __init__(self, + in_channels, + out_channel, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.conv_layer = ConvModule( + in_channels=in_channels, + out_channels=out_channel, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.atten_conv_layer = nn.Sequential( + nn.AdaptiveAvgPool2d((1, 1)), + ConvModule( + in_channels=out_channel, + out_channels=out_channel, + kernel_size=1, + bias=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None), nn.Sigmoid()) + + def forward(self, x): + x = self.conv_layer(x) + x_atten = self.atten_conv_layer(x) + x_out = x * x_atten + return x_out + + +class ContextPath(BaseModule): + """Context Path to provide sufficient receptive field. + + Args: + backbone_cfg:(dict): Config of backbone of + Context Path. + context_channels (Tuple[int]): The number of channel numbers + of various modules in Context Path. + Default: (128, 256, 512). + align_corners (bool, optional): The align_corners argument of + resize operation. Default: False. + Returns: + x_16_up, x_32_up (torch.Tensor, torch.Tensor): Two feature maps + undergoing upsampling from 1/16 and 1/32 downsampling + feature maps. These two feature maps are used for Feature + Fusion Module and Auxiliary Head. + """ + + def __init__(self, + backbone_cfg, + context_channels=(128, 256, 512), + align_corners=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert len(context_channels) == 3, 'Length of input channels \ + of Context Path must be 3!' + + self.backbone = MODELS.build(backbone_cfg) + + self.align_corners = align_corners + self.arm16 = AttentionRefinementModule(context_channels[1], + context_channels[0]) + self.arm32 = AttentionRefinementModule(context_channels[2], + context_channels[0]) + self.conv_head32 = ConvModule( + in_channels=context_channels[0], + out_channels=context_channels[0], + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.conv_head16 = ConvModule( + in_channels=context_channels[0], + out_channels=context_channels[0], + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.gap_conv = nn.Sequential( + nn.AdaptiveAvgPool2d((1, 1)), + ConvModule( + in_channels=context_channels[2], + out_channels=context_channels[0], + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + def forward(self, x): + x_4, x_8, x_16, x_32 = self.backbone(x) + x_gap = self.gap_conv(x_32) + + x_32_arm = self.arm32(x_32) + x_32_sum = x_32_arm + x_gap + x_32_up = resize(input=x_32_sum, size=x_16.shape[2:], mode='nearest') + x_32_up = self.conv_head32(x_32_up) + + x_16_arm = self.arm16(x_16) + x_16_sum = x_16_arm + x_32_up + x_16_up = resize(input=x_16_sum, size=x_8.shape[2:], mode='nearest') + x_16_up = self.conv_head16(x_16_up) + + return x_16_up, x_32_up + + +class FeatureFusionModule(BaseModule): + """Feature Fusion Module to fuse low level output feature of Spatial Path + and high level output feature of Context Path. + + Args: + in_channels (int): The number of input channels. + out_channels (int): The number of output channels. + Returns: + x_out (torch.Tensor): Feature map of Feature Fusion Module. + """ + + def __init__(self, + in_channels, + out_channels, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.conv1 = ConvModule( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.gap = nn.AdaptiveAvgPool2d((1, 1)) + self.conv_atten = nn.Sequential( + ConvModule( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + padding=0, + bias=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg), nn.Sigmoid()) + + def forward(self, x_sp, x_cp): + x_concat = torch.cat([x_sp, x_cp], dim=1) + x_fuse = self.conv1(x_concat) + x_atten = self.gap(x_fuse) + # Note: No BN and more 1x1 conv in paper. + x_atten = self.conv_atten(x_atten) + x_atten = x_fuse * x_atten + x_out = x_atten + x_fuse + return x_out + + +@MODELS.register_module() +class BiSeNetV1(BaseModule): + """BiSeNetV1 backbone. + + This backbone is the implementation of `BiSeNet: Bilateral + Segmentation Network for Real-time Semantic + Segmentation `_. + + Args: + backbone_cfg:(dict): Config of backbone of + Context Path. + in_channels (int): The number of channels of input + image. Default: 3. + spatial_channels (Tuple[int]): Size of channel numbers of + various layers in Spatial Path. + Default: (64, 64, 64, 128). + context_channels (Tuple[int]): Size of channel numbers of + various modules in Context Path. + Default: (128, 256, 512). + out_indices (Tuple[int] | int, optional): Output from which stages. + Default: (0, 1, 2). + align_corners (bool, optional): The align_corners argument of + resize operation in Bilateral Guided Aggregation Layer. + Default: False. + out_channels(int): The number of channels of output. + It must be the same with `in_channels` of decode_head. + Default: 256. + """ + + def __init__(self, + backbone_cfg, + in_channels=3, + spatial_channels=(64, 64, 64, 128), + context_channels=(128, 256, 512), + out_indices=(0, 1, 2), + align_corners=False, + out_channels=256, + conv_cfg=None, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='ReLU'), + init_cfg=None): + + super().__init__(init_cfg=init_cfg) + assert len(spatial_channels) == 4, 'Length of input channels \ + of Spatial Path must be 4!' + + assert len(context_channels) == 3, 'Length of input channels \ + of Context Path must be 3!' + + self.out_indices = out_indices + self.align_corners = align_corners + self.context_path = ContextPath(backbone_cfg, context_channels, + self.align_corners) + self.spatial_path = SpatialPath(in_channels, spatial_channels) + self.ffm = FeatureFusionModule(context_channels[1], out_channels) + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + + def forward(self, x): + # stole refactoring code from Coin Cheung, thanks + x_context8, x_context16 = self.context_path(x) + x_spatial = self.spatial_path(x) + x_fuse = self.ffm(x_spatial, x_context8) + + outs = [x_fuse, x_context8, x_context16] + outs = [outs[i] for i in self.out_indices] + return tuple(outs) diff --git a/third-party/InterFormer/mmseg/models/backbones/bisenetv2.py b/third-party/InterFormer/mmseg/models/backbones/bisenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..32aa49822f7d0c3bd4839b3796a15689e1f4cbc0 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/bisenetv2.py @@ -0,0 +1,622 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import (ConvModule, DepthwiseSeparableConvModule, + build_activation_layer, build_norm_layer) +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +class DetailBranch(BaseModule): + """Detail Branch with wide channels and shallow layers to capture low-level + details and generate high-resolution feature representation. + + Args: + detail_channels (Tuple[int]): Size of channel numbers of each stage + in Detail Branch, in paper it has 3 stages. + Default: (64, 64, 128). + in_channels (int): Number of channels of input image. Default: 3. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + Returns: + x (torch.Tensor): Feature map of Detail Branch. + """ + + def __init__(self, + detail_channels=(64, 64, 128), + in_channels=3, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + detail_branch = [] + for i in range(len(detail_channels)): + if i == 0: + detail_branch.append( + nn.Sequential( + ConvModule( + in_channels=in_channels, + out_channels=detail_channels[i], + kernel_size=3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg), + ConvModule( + in_channels=detail_channels[i], + out_channels=detail_channels[i], + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg))) + else: + detail_branch.append( + nn.Sequential( + ConvModule( + in_channels=detail_channels[i - 1], + out_channels=detail_channels[i], + kernel_size=3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg), + ConvModule( + in_channels=detail_channels[i], + out_channels=detail_channels[i], + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg), + ConvModule( + in_channels=detail_channels[i], + out_channels=detail_channels[i], + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg))) + self.detail_branch = nn.ModuleList(detail_branch) + + def forward(self, x): + for stage in self.detail_branch: + x = stage(x) + return x + + +class StemBlock(BaseModule): + """Stem Block at the beginning of Semantic Branch. + + Args: + in_channels (int): Number of input channels. + Default: 3. + out_channels (int): Number of output channels. + Default: 16. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + Returns: + x (torch.Tensor): First feature map in Semantic Branch. + """ + + def __init__(self, + in_channels=3, + out_channels=16, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + self.conv_first = ConvModule( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.convs = nn.Sequential( + ConvModule( + in_channels=out_channels, + out_channels=out_channels // 2, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg), + ConvModule( + in_channels=out_channels // 2, + out_channels=out_channels, + kernel_size=3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.pool = nn.MaxPool2d( + kernel_size=3, stride=2, padding=1, ceil_mode=False) + self.fuse_last = ConvModule( + in_channels=out_channels * 2, + out_channels=out_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, x): + x = self.conv_first(x) + x_left = self.convs(x) + x_right = self.pool(x) + x = self.fuse_last(torch.cat([x_left, x_right], dim=1)) + return x + + +class GELayer(BaseModule): + """Gather-and-Expansion Layer. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + exp_ratio (int): Expansion ratio for middle channels. + Default: 6. + stride (int): Stride of GELayer. Default: 1 + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + Returns: + x (torch.Tensor): Intermediate feature map in + Semantic Branch. + """ + + def __init__(self, + in_channels, + out_channels, + exp_ratio=6, + stride=1, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + mid_channel = in_channels * exp_ratio + self.conv1 = ConvModule( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + if stride == 1: + self.dwconv = nn.Sequential( + # ReLU in ConvModule not shown in paper + ConvModule( + in_channels=in_channels, + out_channels=mid_channel, + kernel_size=3, + stride=stride, + padding=1, + groups=in_channels, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.shortcut = None + else: + self.dwconv = nn.Sequential( + ConvModule( + in_channels=in_channels, + out_channels=mid_channel, + kernel_size=3, + stride=stride, + padding=1, + groups=in_channels, + bias=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None), + # ReLU in ConvModule not shown in paper + ConvModule( + in_channels=mid_channel, + out_channels=mid_channel, + kernel_size=3, + stride=1, + padding=1, + groups=mid_channel, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg), + ) + self.shortcut = nn.Sequential( + DepthwiseSeparableConvModule( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + padding=1, + dw_norm_cfg=norm_cfg, + dw_act_cfg=None, + pw_norm_cfg=norm_cfg, + pw_act_cfg=None, + )) + + self.conv2 = nn.Sequential( + ConvModule( + in_channels=mid_channel, + out_channels=out_channels, + kernel_size=1, + stride=1, + padding=0, + bias=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None, + )) + + self.act = build_activation_layer(act_cfg) + + def forward(self, x): + identity = x + x = self.conv1(x) + x = self.dwconv(x) + x = self.conv2(x) + if self.shortcut is not None: + shortcut = self.shortcut(identity) + x = x + shortcut + else: + x = x + identity + x = self.act(x) + return x + + +class CEBlock(BaseModule): + """Context Embedding Block for large receptive filed in Semantic Branch. + + Args: + in_channels (int): Number of input channels. + Default: 3. + out_channels (int): Number of output channels. + Default: 16. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + Returns: + x (torch.Tensor): Last feature map in Semantic Branch. + """ + + def __init__(self, + in_channels=3, + out_channels=16, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.in_channels = in_channels + self.out_channels = out_channels + self.gap = nn.Sequential( + nn.AdaptiveAvgPool2d((1, 1)), + build_norm_layer(norm_cfg, self.in_channels)[1]) + self.conv_gap = ConvModule( + in_channels=self.in_channels, + out_channels=self.out_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + # Note: in paper here is naive conv2d, no bn-relu + self.conv_last = ConvModule( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, x): + identity = x + x = self.gap(x) + x = self.conv_gap(x) + x = identity + x + x = self.conv_last(x) + return x + + +class SemanticBranch(BaseModule): + """Semantic Branch which is lightweight with narrow channels and deep + layers to obtain high-level semantic context. + + Args: + semantic_channels(Tuple[int]): Size of channel numbers of + various stages in Semantic Branch. + Default: (16, 32, 64, 128). + in_channels (int): Number of channels of input image. Default: 3. + exp_ratio (int): Expansion ratio for middle channels. + Default: 6. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + Returns: + semantic_outs (List[torch.Tensor]): List of several feature maps + for auxiliary heads (Booster) and Bilateral + Guided Aggregation Layer. + """ + + def __init__(self, + semantic_channels=(16, 32, 64, 128), + in_channels=3, + exp_ratio=6, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.in_channels = in_channels + self.semantic_channels = semantic_channels + self.semantic_stages = [] + for i in range(len(semantic_channels)): + stage_name = f'stage{i + 1}' + self.semantic_stages.append(stage_name) + if i == 0: + self.add_module( + stage_name, + StemBlock(self.in_channels, semantic_channels[i])) + elif i == (len(semantic_channels) - 1): + self.add_module( + stage_name, + nn.Sequential( + GELayer(semantic_channels[i - 1], semantic_channels[i], + exp_ratio, 2), + GELayer(semantic_channels[i], semantic_channels[i], + exp_ratio, 1), + GELayer(semantic_channels[i], semantic_channels[i], + exp_ratio, 1), + GELayer(semantic_channels[i], semantic_channels[i], + exp_ratio, 1))) + else: + self.add_module( + stage_name, + nn.Sequential( + GELayer(semantic_channels[i - 1], semantic_channels[i], + exp_ratio, 2), + GELayer(semantic_channels[i], semantic_channels[i], + exp_ratio, 1))) + + self.add_module(f'stage{len(semantic_channels)}_CEBlock', + CEBlock(semantic_channels[-1], semantic_channels[-1])) + self.semantic_stages.append(f'stage{len(semantic_channels)}_CEBlock') + + def forward(self, x): + semantic_outs = [] + for stage_name in self.semantic_stages: + semantic_stage = getattr(self, stage_name) + x = semantic_stage(x) + semantic_outs.append(x) + return semantic_outs + + +class BGALayer(BaseModule): + """Bilateral Guided Aggregation Layer to fuse the complementary information + from both Detail Branch and Semantic Branch. + + Args: + out_channels (int): Number of output channels. + Default: 128. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + Returns: + output (torch.Tensor): Output feature map for Segment heads. + """ + + def __init__(self, + out_channels=128, + align_corners=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.out_channels = out_channels + self.align_corners = align_corners + self.detail_dwconv = nn.Sequential( + DepthwiseSeparableConvModule( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + dw_norm_cfg=norm_cfg, + dw_act_cfg=None, + pw_norm_cfg=None, + pw_act_cfg=None, + )) + self.detail_down = nn.Sequential( + ConvModule( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=3, + stride=2, + padding=1, + bias=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None), + nn.AvgPool2d(kernel_size=3, stride=2, padding=1, ceil_mode=False)) + self.semantic_conv = nn.Sequential( + ConvModule( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + bias=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None)) + self.semantic_dwconv = nn.Sequential( + DepthwiseSeparableConvModule( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + dw_norm_cfg=norm_cfg, + dw_act_cfg=None, + pw_norm_cfg=None, + pw_act_cfg=None, + )) + self.conv = ConvModule( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + inplace=True, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + ) + + def forward(self, x_d, x_s): + detail_dwconv = self.detail_dwconv(x_d) + detail_down = self.detail_down(x_d) + semantic_conv = self.semantic_conv(x_s) + semantic_dwconv = self.semantic_dwconv(x_s) + semantic_conv = resize( + input=semantic_conv, + size=detail_dwconv.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + fuse_1 = detail_dwconv * torch.sigmoid(semantic_conv) + fuse_2 = detail_down * torch.sigmoid(semantic_dwconv) + fuse_2 = resize( + input=fuse_2, + size=fuse_1.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + output = self.conv(fuse_1 + fuse_2) + return output + + +@MODELS.register_module() +class BiSeNetV2(BaseModule): + """BiSeNetV2: Bilateral Network with Guided Aggregation for + Real-time Semantic Segmentation. + + This backbone is the implementation of + `BiSeNetV2 `_. + + Args: + in_channels (int): Number of channel of input image. Default: 3. + detail_channels (Tuple[int], optional): Channels of each stage + in Detail Branch. Default: (64, 64, 128). + semantic_channels (Tuple[int], optional): Channels of each stage + in Semantic Branch. Default: (16, 32, 64, 128). + See Table 1 and Figure 3 of paper for more details. + semantic_expansion_ratio (int, optional): The expansion factor + expanding channel number of middle channels in Semantic Branch. + Default: 6. + bga_channels (int, optional): Number of middle channels in + Bilateral Guided Aggregation Layer. Default: 128. + out_indices (Tuple[int] | int, optional): Output from which stages. + Default: (0, 1, 2, 3, 4). + align_corners (bool, optional): The align_corners argument of + resize operation in Bilateral Guided Aggregation Layer. + Default: False. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels=3, + detail_channels=(64, 64, 128), + semantic_channels=(16, 32, 64, 128), + semantic_expansion_ratio=6, + bga_channels=128, + out_indices=(0, 1, 2, 3, 4), + align_corners=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + if init_cfg is None: + init_cfg = [ + dict(type='Kaiming', layer='Conv2d'), + dict( + type='Constant', val=1, layer=['_BatchNorm', 'GroupNorm']) + ] + super().__init__(init_cfg=init_cfg) + self.in_channels = in_channels + self.out_indices = out_indices + self.detail_channels = detail_channels + self.semantic_channels = semantic_channels + self.semantic_expansion_ratio = semantic_expansion_ratio + self.bga_channels = bga_channels + self.align_corners = align_corners + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + + self.detail = DetailBranch(self.detail_channels, self.in_channels) + self.semantic = SemanticBranch(self.semantic_channels, + self.in_channels, + self.semantic_expansion_ratio) + self.bga = BGALayer(self.bga_channels, self.align_corners) + + def forward(self, x): + # stole refactoring code from Coin Cheung, thanks + x_detail = self.detail(x) + x_semantic_lst = self.semantic(x) + x_head = self.bga(x_detail, x_semantic_lst[-1]) + outs = [x_head] + x_semantic_lst[:-1] + outs = [outs[i] for i in self.out_indices] + return tuple(outs) diff --git a/third-party/InterFormer/mmseg/models/backbones/cgnet.py b/third-party/InterFormer/mmseg/models/backbones/cgnet.py new file mode 100644 index 0000000000000000000000000000000000000000..b74b494f53466d1c608e50d088632aa952a5e534 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/cgnet.py @@ -0,0 +1,372 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch +import torch.nn as nn +import torch.utils.checkpoint as cp +from mmcv.cnn import ConvModule, build_conv_layer, build_norm_layer +from mmengine.model import BaseModule +from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm + +from mmseg.registry import MODELS + + +class GlobalContextExtractor(nn.Module): + """Global Context Extractor for CGNet. + + This class is employed to refine the joint feature of both local feature + and surrounding context. + + Args: + channel (int): Number of input feature channels. + reduction (int): Reductions for global context extractor. Default: 16. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + """ + + def __init__(self, channel, reduction=16, with_cp=False): + super().__init__() + self.channel = channel + self.reduction = reduction + assert reduction >= 1 and channel >= reduction + self.with_cp = with_cp + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.fc = nn.Sequential( + nn.Linear(channel, channel // reduction), nn.ReLU(inplace=True), + nn.Linear(channel // reduction, channel), nn.Sigmoid()) + + def forward(self, x): + + def _inner_forward(x): + num_batch, num_channel = x.size()[:2] + y = self.avg_pool(x).view(num_batch, num_channel) + y = self.fc(y).view(num_batch, num_channel, 1, 1) + return x * y + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + return out + + +class ContextGuidedBlock(nn.Module): + """Context Guided Block for CGNet. + + This class consists of four components: local feature extractor, + surrounding feature extractor, joint feature extractor and global + context extractor. + + Args: + in_channels (int): Number of input feature channels. + out_channels (int): Number of output feature channels. + dilation (int): Dilation rate for surrounding context extractor. + Default: 2. + reduction (int): Reduction for global context extractor. Default: 16. + skip_connect (bool): Add input to output or not. Default: True. + downsample (bool): Downsample the input to 1/2 or not. Default: False. + conv_cfg (dict): Config dict for convolution layer. + Default: None, which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN', requires_grad=True). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='PReLU'). + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + """ + + def __init__(self, + in_channels, + out_channels, + dilation=2, + reduction=16, + skip_connect=True, + downsample=False, + conv_cfg=None, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='PReLU'), + with_cp=False): + super().__init__() + self.with_cp = with_cp + self.downsample = downsample + + channels = out_channels if downsample else out_channels // 2 + if 'type' in act_cfg and act_cfg['type'] == 'PReLU': + act_cfg['num_parameters'] = channels + kernel_size = 3 if downsample else 1 + stride = 2 if downsample else 1 + padding = (kernel_size - 1) // 2 + + self.conv1x1 = ConvModule( + in_channels, + channels, + kernel_size, + stride, + padding, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + self.f_loc = build_conv_layer( + conv_cfg, + channels, + channels, + kernel_size=3, + padding=1, + groups=channels, + bias=False) + self.f_sur = build_conv_layer( + conv_cfg, + channels, + channels, + kernel_size=3, + padding=dilation, + groups=channels, + dilation=dilation, + bias=False) + + self.bn = build_norm_layer(norm_cfg, 2 * channels)[1] + self.activate = nn.PReLU(2 * channels) + + if downsample: + self.bottleneck = build_conv_layer( + conv_cfg, + 2 * channels, + out_channels, + kernel_size=1, + bias=False) + + self.skip_connect = skip_connect and not downsample + self.f_glo = GlobalContextExtractor(out_channels, reduction, with_cp) + + def forward(self, x): + + def _inner_forward(x): + out = self.conv1x1(x) + loc = self.f_loc(out) + sur = self.f_sur(out) + + joi_feat = torch.cat([loc, sur], 1) # the joint feature + joi_feat = self.bn(joi_feat) + joi_feat = self.activate(joi_feat) + if self.downsample: + joi_feat = self.bottleneck(joi_feat) # channel = out_channels + # f_glo is employed to refine the joint feature + out = self.f_glo(joi_feat) + + if self.skip_connect: + return x + out + else: + return out + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + return out + + +class InputInjection(nn.Module): + """Downsampling module for CGNet.""" + + def __init__(self, num_downsampling): + super().__init__() + self.pool = nn.ModuleList() + for i in range(num_downsampling): + self.pool.append(nn.AvgPool2d(3, stride=2, padding=1)) + + def forward(self, x): + for pool in self.pool: + x = pool(x) + return x + + +@MODELS.register_module() +class CGNet(BaseModule): + """CGNet backbone. + + This backbone is the implementation of `A Light-weight Context Guided + Network for Semantic Segmentation `_. + + Args: + in_channels (int): Number of input image channels. Normally 3. + num_channels (tuple[int]): Numbers of feature channels at each stages. + Default: (32, 64, 128). + num_blocks (tuple[int]): Numbers of CG blocks at stage 1 and stage 2. + Default: (3, 21). + dilations (tuple[int]): Dilation rate for surrounding context + extractors at stage 1 and stage 2. Default: (2, 4). + reductions (tuple[int]): Reductions for global context extractors at + stage 1 and stage 2. Default: (8, 16). + conv_cfg (dict): Config dict for convolution layer. + Default: None, which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN', requires_grad=True). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='PReLU'). + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + pretrained (str, optional): model pretrained path. Default: None + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None + """ + + def __init__(self, + in_channels=3, + num_channels=(32, 64, 128), + num_blocks=(3, 21), + dilations=(2, 4), + reductions=(8, 16), + conv_cfg=None, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='PReLU'), + norm_eval=False, + with_cp=False, + pretrained=None, + init_cfg=None): + + super().__init__(init_cfg) + + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be setting at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is a deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is None: + if init_cfg is None: + self.init_cfg = [ + dict(type='Kaiming', layer=['Conv2d', 'Linear']), + dict( + type='Constant', + val=1, + layer=['_BatchNorm', 'GroupNorm']), + dict(type='Constant', val=0, layer='PReLU') + ] + else: + raise TypeError('pretrained must be a str or None') + + self.in_channels = in_channels + self.num_channels = num_channels + assert isinstance(self.num_channels, tuple) and len( + self.num_channels) == 3 + self.num_blocks = num_blocks + assert isinstance(self.num_blocks, tuple) and len(self.num_blocks) == 2 + self.dilations = dilations + assert isinstance(self.dilations, tuple) and len(self.dilations) == 2 + self.reductions = reductions + assert isinstance(self.reductions, tuple) and len(self.reductions) == 2 + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + if 'type' in self.act_cfg and self.act_cfg['type'] == 'PReLU': + self.act_cfg['num_parameters'] = num_channels[0] + self.norm_eval = norm_eval + self.with_cp = with_cp + + cur_channels = in_channels + self.stem = nn.ModuleList() + for i in range(3): + self.stem.append( + ConvModule( + cur_channels, + num_channels[0], + 3, + 2 if i == 0 else 1, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + cur_channels = num_channels[0] + + self.inject_2x = InputInjection(1) # down-sample for Input, factor=2 + self.inject_4x = InputInjection(2) # down-sample for Input, factor=4 + + cur_channels += in_channels + self.norm_prelu_0 = nn.Sequential( + build_norm_layer(norm_cfg, cur_channels)[1], + nn.PReLU(cur_channels)) + + # stage 1 + self.level1 = nn.ModuleList() + for i in range(num_blocks[0]): + self.level1.append( + ContextGuidedBlock( + cur_channels if i == 0 else num_channels[1], + num_channels[1], + dilations[0], + reductions[0], + downsample=(i == 0), + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + with_cp=with_cp)) # CG block + + cur_channels = 2 * num_channels[1] + in_channels + self.norm_prelu_1 = nn.Sequential( + build_norm_layer(norm_cfg, cur_channels)[1], + nn.PReLU(cur_channels)) + + # stage 2 + self.level2 = nn.ModuleList() + for i in range(num_blocks[1]): + self.level2.append( + ContextGuidedBlock( + cur_channels if i == 0 else num_channels[2], + num_channels[2], + dilations[1], + reductions[1], + downsample=(i == 0), + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + with_cp=with_cp)) # CG block + + cur_channels = 2 * num_channels[2] + self.norm_prelu_2 = nn.Sequential( + build_norm_layer(norm_cfg, cur_channels)[1], + nn.PReLU(cur_channels)) + + def forward(self, x): + output = [] + + # stage 0 + inp_2x = self.inject_2x(x) + inp_4x = self.inject_4x(x) + for layer in self.stem: + x = layer(x) + x = self.norm_prelu_0(torch.cat([x, inp_2x], 1)) + output.append(x) + + # stage 1 + for i, layer in enumerate(self.level1): + x = layer(x) + if i == 0: + down1 = x + x = self.norm_prelu_1(torch.cat([x, down1, inp_4x], 1)) + output.append(x) + + # stage 2 + for i, layer in enumerate(self.level2): + x = layer(x) + if i == 0: + down2 = x + x = self.norm_prelu_2(torch.cat([down2, x], 1)) + output.append(x) + + return output + + def train(self, mode=True): + """Convert the model into training mode will keeping the normalization + layer freezed.""" + super().train(mode) + if mode and self.norm_eval: + for m in self.modules(): + # trick: eval have effect on BatchNorm only + if isinstance(m, _BatchNorm): + m.eval() diff --git a/third-party/InterFormer/mmseg/models/backbones/ddrnet.py b/third-party/InterFormer/mmseg/models/backbones/ddrnet.py new file mode 100644 index 0000000000000000000000000000000000000000..4508aade82b484abfcca593825649031db7cbdd0 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/ddrnet.py @@ -0,0 +1,222 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule, build_norm_layer +from mmengine.model import BaseModule + +from mmseg.models.utils import DAPPM, BasicBlock, Bottleneck, resize +from mmseg.registry import MODELS +from mmseg.utils import OptConfigType + + +@MODELS.register_module() +class DDRNet(BaseModule): + """DDRNet backbone. + + This backbone is the implementation of `Deep Dual-resolution Networks for + Real-time and Accurate Semantic Segmentation of Road Scenes + `_. + Modified from https://github.com/ydhongHIT/DDRNet. + + Args: + in_channels (int): Number of input image channels. Default: 3. + channels: (int): The base channels of DDRNet. Default: 32. + ppm_channels (int): The channels of PPM module. Default: 128. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + norm_cfg (dict): Config dict to build norm layer. + Default: dict(type='BN', requires_grad=True). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + init_cfg (dict, optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels: int = 3, + channels: int = 32, + ppm_channels: int = 128, + align_corners: bool = False, + norm_cfg: OptConfigType = dict(type='BN', requires_grad=True), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + + self.in_channels = in_channels + self.ppm_channels = ppm_channels + + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.align_corners = align_corners + + # stage 0-2 + self.stem = self._make_stem_layer(in_channels, channels, num_blocks=2) + self.relu = nn.ReLU() + + # low resolution(context) branch + self.context_branch_layers = nn.ModuleList() + for i in range(3): + self.context_branch_layers.append( + self._make_layer( + block=BasicBlock if i < 2 else Bottleneck, + inplanes=channels * 2**(i + 1), + planes=channels * 8 if i > 0 else channels * 4, + num_blocks=2 if i < 2 else 1, + stride=2)) + + # bilateral fusion + self.compression_1 = ConvModule( + channels * 4, + channels * 2, + kernel_size=1, + norm_cfg=self.norm_cfg, + act_cfg=None) + self.down_1 = ConvModule( + channels * 2, + channels * 4, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=None) + + self.compression_2 = ConvModule( + channels * 8, + channels * 2, + kernel_size=1, + norm_cfg=self.norm_cfg, + act_cfg=None) + self.down_2 = nn.Sequential( + ConvModule( + channels * 2, + channels * 4, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + ConvModule( + channels * 4, + channels * 8, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=None)) + + # high resolution(spatial) branch + self.spatial_branch_layers = nn.ModuleList() + for i in range(3): + self.spatial_branch_layers.append( + self._make_layer( + block=BasicBlock if i < 2 else Bottleneck, + inplanes=channels * 2, + planes=channels * 2, + num_blocks=2 if i < 2 else 1, + )) + + self.spp = DAPPM( + channels * 16, ppm_channels, channels * 4, num_scales=5) + + def _make_stem_layer(self, in_channels, channels, num_blocks): + layers = [ + ConvModule( + in_channels, + channels, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + ConvModule( + channels, + channels, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + ] + + layers.extend([ + self._make_layer(BasicBlock, channels, channels, num_blocks), + nn.ReLU(), + self._make_layer( + BasicBlock, channels, channels * 2, num_blocks, stride=2), + nn.ReLU(), + ]) + + return nn.Sequential(*layers) + + def _make_layer(self, block, inplanes, planes, num_blocks, stride=1): + downsample = None + if stride != 1 or inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d( + inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + bias=False), + build_norm_layer(self.norm_cfg, planes * block.expansion)[1]) + + layers = [ + block( + in_channels=inplanes, + channels=planes, + stride=stride, + downsample=downsample) + ] + inplanes = planes * block.expansion + for i in range(1, num_blocks): + layers.append( + block( + in_channels=inplanes, + channels=planes, + stride=1, + norm_cfg=self.norm_cfg, + act_cfg_out=None if i == num_blocks - 1 else self.act_cfg)) + + return nn.Sequential(*layers) + + def forward(self, x): + """Forward function.""" + out_size = (x.shape[-2] // 8, x.shape[-1] // 8) + + # stage 0-2 + x = self.stem(x) + + # stage3 + x_c = self.context_branch_layers[0](x) + x_s = self.spatial_branch_layers[0](x) + comp_c = self.compression_1(self.relu(x_c)) + x_c += self.down_1(self.relu(x_s)) + x_s += resize( + comp_c, + size=out_size, + mode='bilinear', + align_corners=self.align_corners) + if self.training: + temp_context = x_s.clone() + + # stage4 + x_c = self.context_branch_layers[1](self.relu(x_c)) + x_s = self.spatial_branch_layers[1](self.relu(x_s)) + comp_c = self.compression_2(self.relu(x_c)) + x_c += self.down_2(self.relu(x_s)) + x_s += resize( + comp_c, + size=out_size, + mode='bilinear', + align_corners=self.align_corners) + + # stage5 + x_s = self.spatial_branch_layers[2](self.relu(x_s)) + x_c = self.context_branch_layers[2](self.relu(x_c)) + x_c = self.spp(x_c) + x_c = resize( + x_c, + size=out_size, + mode='bilinear', + align_corners=self.align_corners) + + return (temp_context, x_s + x_c) if self.training else x_s + x_c diff --git a/third-party/InterFormer/mmseg/models/backbones/erfnet.py b/third-party/InterFormer/mmseg/models/backbones/erfnet.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5ec672a086b5d67568514140023ce402eef92f --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/erfnet.py @@ -0,0 +1,329 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import build_activation_layer, build_conv_layer, build_norm_layer +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +class DownsamplerBlock(BaseModule): + """Downsampler block of ERFNet. + + This module is a little different from basical ConvModule. + The features from Conv and MaxPool layers are + concatenated before BatchNorm. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + conv_cfg=None, + norm_cfg=dict(type='BN', eps=1e-3), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + + self.conv = build_conv_layer( + self.conv_cfg, + in_channels, + out_channels - in_channels, + kernel_size=3, + stride=2, + padding=1) + self.pool = nn.MaxPool2d(kernel_size=2, stride=2) + self.bn = build_norm_layer(self.norm_cfg, out_channels)[1] + self.act = build_activation_layer(self.act_cfg) + + def forward(self, input): + conv_out = self.conv(input) + pool_out = self.pool(input) + pool_out = resize( + input=pool_out, + size=conv_out.size()[2:], + mode='bilinear', + align_corners=False) + output = torch.cat([conv_out, pool_out], 1) + output = self.bn(output) + output = self.act(output) + return output + + +class NonBottleneck1d(BaseModule): + """Non-bottleneck block of ERFNet. + + Args: + channels (int): Number of channels in Non-bottleneck block. + drop_rate (float): Probability of an element to be zeroed. + Default 0. + dilation (int): Dilation rate for last two conv layers. + Default 1. + num_conv_layer (int): Number of 3x1 and 1x3 convolution layers. + Default 2. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + channels, + drop_rate=0, + dilation=1, + num_conv_layer=2, + conv_cfg=None, + norm_cfg=dict(type='BN', eps=1e-3), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.act = build_activation_layer(self.act_cfg) + + self.convs_layers = nn.ModuleList() + for conv_layer in range(num_conv_layer): + first_conv_padding = (1, 0) if conv_layer == 0 else (dilation, 0) + first_conv_dilation = 1 if conv_layer == 0 else (dilation, 1) + second_conv_padding = (0, 1) if conv_layer == 0 else (0, dilation) + second_conv_dilation = 1 if conv_layer == 0 else (1, dilation) + + self.convs_layers.append( + build_conv_layer( + self.conv_cfg, + channels, + channels, + kernel_size=(3, 1), + stride=1, + padding=first_conv_padding, + bias=True, + dilation=first_conv_dilation)) + self.convs_layers.append(self.act) + self.convs_layers.append( + build_conv_layer( + self.conv_cfg, + channels, + channels, + kernel_size=(1, 3), + stride=1, + padding=second_conv_padding, + bias=True, + dilation=second_conv_dilation)) + self.convs_layers.append( + build_norm_layer(self.norm_cfg, channels)[1]) + if conv_layer == 0: + self.convs_layers.append(self.act) + else: + self.convs_layers.append(nn.Dropout(p=drop_rate)) + + def forward(self, input): + output = input + for conv in self.convs_layers: + output = conv(output) + output = self.act(output + input) + return output + + +class UpsamplerBlock(BaseModule): + """Upsampler block of ERFNet. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + conv_cfg=None, + norm_cfg=dict(type='BN', eps=1e-3), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + + self.conv = nn.ConvTranspose2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=2, + padding=1, + output_padding=1, + bias=True) + self.bn = build_norm_layer(self.norm_cfg, out_channels)[1] + self.act = build_activation_layer(self.act_cfg) + + def forward(self, input): + output = self.conv(input) + output = self.bn(output) + output = self.act(output) + return output + + +@MODELS.register_module() +class ERFNet(BaseModule): + """ERFNet backbone. + + This backbone is the implementation of `ERFNet: Efficient Residual + Factorized ConvNet for Real-time SemanticSegmentation + `_. + + Args: + in_channels (int): The number of channels of input + image. Default: 3. + enc_downsample_channels (Tuple[int]): Size of channel + numbers of various Downsampler block in encoder. + Default: (16, 64, 128). + enc_stage_non_bottlenecks (Tuple[int]): Number of stages of + Non-bottleneck block in encoder. + Default: (5, 8). + enc_non_bottleneck_dilations (Tuple[int]): Dilation rate of each + stage of Non-bottleneck block of encoder. + Default: (2, 4, 8, 16). + enc_non_bottleneck_channels (Tuple[int]): Size of channel + numbers of various Non-bottleneck block in encoder. + Default: (64, 128). + dec_upsample_channels (Tuple[int]): Size of channel numbers of + various Deconvolution block in decoder. + Default: (64, 16). + dec_stages_non_bottleneck (Tuple[int]): Number of stages of + Non-bottleneck block in decoder. + Default: (2, 2). + dec_non_bottleneck_channels (Tuple[int]): Size of channel + numbers of various Non-bottleneck block in decoder. + Default: (64, 16). + drop_rate (float): Probability of an element to be zeroed. + Default 0.1. + """ + + def __init__(self, + in_channels=3, + enc_downsample_channels=(16, 64, 128), + enc_stage_non_bottlenecks=(5, 8), + enc_non_bottleneck_dilations=(2, 4, 8, 16), + enc_non_bottleneck_channels=(64, 128), + dec_upsample_channels=(64, 16), + dec_stages_non_bottleneck=(2, 2), + dec_non_bottleneck_channels=(64, 16), + dropout_ratio=0.1, + conv_cfg=None, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='ReLU'), + init_cfg=None): + + super().__init__(init_cfg=init_cfg) + assert len(enc_downsample_channels) \ + == len(dec_upsample_channels)+1, 'Number of downsample\ + block of encoder does not \ + match number of upsample block of decoder!' + assert len(enc_downsample_channels) \ + == len(enc_stage_non_bottlenecks)+1, 'Number of \ + downsample block of encoder does not match \ + number of Non-bottleneck block of encoder!' + assert len(enc_downsample_channels) \ + == len(enc_non_bottleneck_channels)+1, 'Number of \ + downsample block of encoder does not match \ + number of channels of Non-bottleneck block of encoder!' + assert enc_stage_non_bottlenecks[-1] \ + % len(enc_non_bottleneck_dilations) == 0, 'Number of \ + Non-bottleneck block of encoder does not match \ + number of Non-bottleneck block of encoder!' + assert len(dec_upsample_channels) \ + == len(dec_stages_non_bottleneck), 'Number of \ + upsample block of decoder does not match \ + number of Non-bottleneck block of decoder!' + assert len(dec_stages_non_bottleneck) \ + == len(dec_non_bottleneck_channels), 'Number of \ + Non-bottleneck block of decoder does not match \ + number of channels of Non-bottleneck block of decoder!' + + self.in_channels = in_channels + self.enc_downsample_channels = enc_downsample_channels + self.enc_stage_non_bottlenecks = enc_stage_non_bottlenecks + self.enc_non_bottleneck_dilations = enc_non_bottleneck_dilations + self.enc_non_bottleneck_channels = enc_non_bottleneck_channels + self.dec_upsample_channels = dec_upsample_channels + self.dec_stages_non_bottleneck = dec_stages_non_bottleneck + self.dec_non_bottleneck_channels = dec_non_bottleneck_channels + self.dropout_ratio = dropout_ratio + + self.encoder = nn.ModuleList() + self.decoder = nn.ModuleList() + + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + + self.encoder.append( + DownsamplerBlock(self.in_channels, enc_downsample_channels[0])) + + for i in range(len(enc_downsample_channels) - 1): + self.encoder.append( + DownsamplerBlock(enc_downsample_channels[i], + enc_downsample_channels[i + 1])) + # Last part of encoder is some dilated NonBottleneck1d blocks. + if i == len(enc_downsample_channels) - 2: + iteration_times = int(enc_stage_non_bottlenecks[-1] / + len(enc_non_bottleneck_dilations)) + for j in range(iteration_times): + for k in range(len(enc_non_bottleneck_dilations)): + self.encoder.append( + NonBottleneck1d(enc_downsample_channels[-1], + self.dropout_ratio, + enc_non_bottleneck_dilations[k])) + else: + for j in range(enc_stage_non_bottlenecks[i]): + self.encoder.append( + NonBottleneck1d(enc_downsample_channels[i + 1], + self.dropout_ratio)) + + for i in range(len(dec_upsample_channels)): + if i == 0: + self.decoder.append( + UpsamplerBlock(enc_downsample_channels[-1], + dec_non_bottleneck_channels[i])) + else: + self.decoder.append( + UpsamplerBlock(dec_non_bottleneck_channels[i - 1], + dec_non_bottleneck_channels[i])) + for j in range(dec_stages_non_bottleneck[i]): + self.decoder.append( + NonBottleneck1d(dec_non_bottleneck_channels[i])) + + def forward(self, x): + for enc in self.encoder: + x = enc(x) + for dec in self.decoder: + x = dec(x) + return [x] diff --git a/third-party/InterFormer/mmseg/models/backbones/fast_scnn.py b/third-party/InterFormer/mmseg/models/backbones/fast_scnn.py new file mode 100644 index 0000000000000000000000000000000000000000..6ff7a3191d2fee904c5200e0a526214a65f58b32 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/fast_scnn.py @@ -0,0 +1,408 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule +from mmengine.model import BaseModule + +from mmseg.models.decode_heads.psp_head import PPM +from mmseg.registry import MODELS +from ..utils import InvertedResidual, resize + + +class LearningToDownsample(nn.Module): + """Learning to downsample module. + + Args: + in_channels (int): Number of input channels. + dw_channels (tuple[int]): Number of output channels of the first and + the second depthwise conv (dwconv) layers. + out_channels (int): Number of output channels of the whole + 'learning to downsample' module. + conv_cfg (dict | None): Config of conv layers. Default: None + norm_cfg (dict | None): Config of norm layers. Default: + dict(type='BN') + act_cfg (dict): Config of activation layers. Default: + dict(type='ReLU') + dw_act_cfg (dict): In DepthwiseSeparableConvModule, activation config + of depthwise ConvModule. If it is 'default', it will be the same + as `act_cfg`. Default: None. + """ + + def __init__(self, + in_channels, + dw_channels, + out_channels, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + dw_act_cfg=None): + super().__init__() + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.dw_act_cfg = dw_act_cfg + dw_channels1 = dw_channels[0] + dw_channels2 = dw_channels[1] + + self.conv = ConvModule( + in_channels, + dw_channels1, + 3, + stride=2, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.dsconv1 = DepthwiseSeparableConvModule( + dw_channels1, + dw_channels2, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + dw_act_cfg=self.dw_act_cfg) + + self.dsconv2 = DepthwiseSeparableConvModule( + dw_channels2, + out_channels, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + dw_act_cfg=self.dw_act_cfg) + + def forward(self, x): + x = self.conv(x) + x = self.dsconv1(x) + x = self.dsconv2(x) + return x + + +class GlobalFeatureExtractor(nn.Module): + """Global feature extractor module. + + Args: + in_channels (int): Number of input channels of the GFE module. + Default: 64 + block_channels (tuple[int]): Tuple of ints. Each int specifies the + number of output channels of each Inverted Residual module. + Default: (64, 96, 128) + out_channels(int): Number of output channels of the GFE module. + Default: 128 + expand_ratio (int): Adjusts number of channels of the hidden layer + in InvertedResidual by this amount. + Default: 6 + num_blocks (tuple[int]): Tuple of ints. Each int specifies the + number of times each Inverted Residual module is repeated. + The repeated Inverted Residual modules are called a 'group'. + Default: (3, 3, 3) + strides (tuple[int]): Tuple of ints. Each int specifies + the downsampling factor of each 'group'. + Default: (2, 2, 1) + pool_scales (tuple[int]): Tuple of ints. Each int specifies + the parameter required in 'global average pooling' within PPM. + Default: (1, 2, 3, 6) + conv_cfg (dict | None): Config of conv layers. Default: None + norm_cfg (dict | None): Config of norm layers. Default: + dict(type='BN') + act_cfg (dict): Config of activation layers. Default: + dict(type='ReLU') + align_corners (bool): align_corners argument of F.interpolate. + Default: False + """ + + def __init__(self, + in_channels=64, + block_channels=(64, 96, 128), + out_channels=128, + expand_ratio=6, + num_blocks=(3, 3, 3), + strides=(2, 2, 1), + pool_scales=(1, 2, 3, 6), + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False): + super().__init__() + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + assert len(block_channels) == len(num_blocks) == 3 + self.bottleneck1 = self._make_layer(in_channels, block_channels[0], + num_blocks[0], strides[0], + expand_ratio) + self.bottleneck2 = self._make_layer(block_channels[0], + block_channels[1], num_blocks[1], + strides[1], expand_ratio) + self.bottleneck3 = self._make_layer(block_channels[1], + block_channels[2], num_blocks[2], + strides[2], expand_ratio) + self.ppm = PPM( + pool_scales, + block_channels[2], + block_channels[2] // 4, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=align_corners) + + self.out = ConvModule( + block_channels[2] * 2, + out_channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def _make_layer(self, + in_channels, + out_channels, + blocks, + stride=1, + expand_ratio=6): + layers = [ + InvertedResidual( + in_channels, + out_channels, + stride, + expand_ratio, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + ] + for i in range(1, blocks): + layers.append( + InvertedResidual( + out_channels, + out_channels, + 1, + expand_ratio, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + return nn.Sequential(*layers) + + def forward(self, x): + x = self.bottleneck1(x) + x = self.bottleneck2(x) + x = self.bottleneck3(x) + x = torch.cat([x, *self.ppm(x)], dim=1) + x = self.out(x) + return x + + +class FeatureFusionModule(nn.Module): + """Feature fusion module. + + Args: + higher_in_channels (int): Number of input channels of the + higher-resolution branch. + lower_in_channels (int): Number of input channels of the + lower-resolution branch. + out_channels (int): Number of output channels. + conv_cfg (dict | None): Config of conv layers. Default: None + norm_cfg (dict | None): Config of norm layers. Default: + dict(type='BN') + dwconv_act_cfg (dict): Config of activation layers in 3x3 conv. + Default: dict(type='ReLU'). + conv_act_cfg (dict): Config of activation layers in the two 1x1 conv. + Default: None. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + """ + + def __init__(self, + higher_in_channels, + lower_in_channels, + out_channels, + conv_cfg=None, + norm_cfg=dict(type='BN'), + dwconv_act_cfg=dict(type='ReLU'), + conv_act_cfg=None, + align_corners=False): + super().__init__() + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.dwconv_act_cfg = dwconv_act_cfg + self.conv_act_cfg = conv_act_cfg + self.align_corners = align_corners + self.dwconv = ConvModule( + lower_in_channels, + out_channels, + 3, + padding=1, + groups=out_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.dwconv_act_cfg) + self.conv_lower_res = ConvModule( + out_channels, + out_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.conv_act_cfg) + + self.conv_higher_res = ConvModule( + higher_in_channels, + out_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.conv_act_cfg) + + self.relu = nn.ReLU(True) + + def forward(self, higher_res_feature, lower_res_feature): + lower_res_feature = resize( + lower_res_feature, + size=higher_res_feature.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + lower_res_feature = self.dwconv(lower_res_feature) + lower_res_feature = self.conv_lower_res(lower_res_feature) + + higher_res_feature = self.conv_higher_res(higher_res_feature) + out = higher_res_feature + lower_res_feature + return self.relu(out) + + +@MODELS.register_module() +class FastSCNN(BaseModule): + """Fast-SCNN Backbone. + + This backbone is the implementation of `Fast-SCNN: Fast Semantic + Segmentation Network `_. + + Args: + in_channels (int): Number of input image channels. Default: 3. + downsample_dw_channels (tuple[int]): Number of output channels after + the first conv layer & the second conv layer in + Learning-To-Downsample (LTD) module. + Default: (32, 48). + global_in_channels (int): Number of input channels of + Global Feature Extractor(GFE). + Equal to number of output channels of LTD. + Default: 64. + global_block_channels (tuple[int]): Tuple of integers that describe + the output channels for each of the MobileNet-v2 bottleneck + residual blocks in GFE. + Default: (64, 96, 128). + global_block_strides (tuple[int]): Tuple of integers + that describe the strides (downsampling factors) for each of the + MobileNet-v2 bottleneck residual blocks in GFE. + Default: (2, 2, 1). + global_out_channels (int): Number of output channels of GFE. + Default: 128. + higher_in_channels (int): Number of input channels of the higher + resolution branch in FFM. + Equal to global_in_channels. + Default: 64. + lower_in_channels (int): Number of input channels of the lower + resolution branch in FFM. + Equal to global_out_channels. + Default: 128. + fusion_out_channels (int): Number of output channels of FFM. + Default: 128. + out_indices (tuple): Tuple of indices of list + [higher_res_features, lower_res_features, fusion_output]. + Often set to (0,1,2) to enable aux. heads. + Default: (0, 1, 2). + conv_cfg (dict | None): Config of conv layers. Default: None + norm_cfg (dict | None): Config of norm layers. Default: + dict(type='BN') + act_cfg (dict): Config of activation layers. Default: + dict(type='ReLU') + align_corners (bool): align_corners argument of F.interpolate. + Default: False + dw_act_cfg (dict): In DepthwiseSeparableConvModule, activation config + of depthwise ConvModule. If it is 'default', it will be the same + as `act_cfg`. Default: None. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None + """ + + def __init__(self, + in_channels=3, + downsample_dw_channels=(32, 48), + global_in_channels=64, + global_block_channels=(64, 96, 128), + global_block_strides=(2, 2, 1), + global_out_channels=128, + higher_in_channels=64, + lower_in_channels=128, + fusion_out_channels=128, + out_indices=(0, 1, 2), + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + dw_act_cfg=None, + init_cfg=None): + + super().__init__(init_cfg) + + if init_cfg is None: + self.init_cfg = [ + dict(type='Kaiming', layer='Conv2d'), + dict( + type='Constant', val=1, layer=['_BatchNorm', 'GroupNorm']) + ] + + if global_in_channels != higher_in_channels: + raise AssertionError('Global Input Channels must be the same \ + with Higher Input Channels!') + elif global_out_channels != lower_in_channels: + raise AssertionError('Global Output Channels must be the same \ + with Lower Input Channels!') + + self.in_channels = in_channels + self.downsample_dw_channels1 = downsample_dw_channels[0] + self.downsample_dw_channels2 = downsample_dw_channels[1] + self.global_in_channels = global_in_channels + self.global_block_channels = global_block_channels + self.global_block_strides = global_block_strides + self.global_out_channels = global_out_channels + self.higher_in_channels = higher_in_channels + self.lower_in_channels = lower_in_channels + self.fusion_out_channels = fusion_out_channels + self.out_indices = out_indices + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.align_corners = align_corners + self.learning_to_downsample = LearningToDownsample( + in_channels, + downsample_dw_channels, + global_in_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + dw_act_cfg=dw_act_cfg) + self.global_feature_extractor = GlobalFeatureExtractor( + global_in_channels, + global_block_channels, + global_out_channels, + strides=self.global_block_strides, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + self.feature_fusion = FeatureFusionModule( + higher_in_channels, + lower_in_channels, + fusion_out_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + dwconv_act_cfg=self.act_cfg, + align_corners=self.align_corners) + + def forward(self, x): + higher_res_features = self.learning_to_downsample(x) + lower_res_features = self.global_feature_extractor(higher_res_features) + fusion_output = self.feature_fusion(higher_res_features, + lower_res_features) + + outs = [higher_res_features, lower_res_features, fusion_output] + outs = [outs[i] for i in self.out_indices] + return tuple(outs) diff --git a/third-party/InterFormer/mmseg/models/backbones/hrnet.py b/third-party/InterFormer/mmseg/models/backbones/hrnet.py new file mode 100644 index 0000000000000000000000000000000000000000..2da755e731cfea911d47729f455c54c3d38a68e4 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/hrnet.py @@ -0,0 +1,642 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch.nn as nn +from mmcv.cnn import build_conv_layer, build_norm_layer +from mmengine.model import BaseModule, ModuleList, Sequential +from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm + +from mmseg.registry import MODELS +from ..utils import Upsample, resize +from .resnet import BasicBlock, Bottleneck + + +class HRModule(BaseModule): + """High-Resolution Module for HRNet. + + In this module, every branch has 4 BasicBlocks/Bottlenecks. Fusion/Exchange + is in this module. + """ + + def __init__(self, + num_branches, + blocks, + num_blocks, + in_channels, + num_channels, + multiscale_output=True, + with_cp=False, + conv_cfg=None, + norm_cfg=dict(type='BN', requires_grad=True), + block_init_cfg=None, + init_cfg=None): + super().__init__(init_cfg) + self.block_init_cfg = block_init_cfg + self._check_branches(num_branches, num_blocks, in_channels, + num_channels) + + self.in_channels = in_channels + self.num_branches = num_branches + + self.multiscale_output = multiscale_output + self.norm_cfg = norm_cfg + self.conv_cfg = conv_cfg + self.with_cp = with_cp + self.branches = self._make_branches(num_branches, blocks, num_blocks, + num_channels) + self.fuse_layers = self._make_fuse_layers() + self.relu = nn.ReLU(inplace=False) + + def _check_branches(self, num_branches, num_blocks, in_channels, + num_channels): + """Check branches configuration.""" + if num_branches != len(num_blocks): + error_msg = f'NUM_BRANCHES({num_branches}) <> NUM_BLOCKS(' \ + f'{len(num_blocks)})' + raise ValueError(error_msg) + + if num_branches != len(num_channels): + error_msg = f'NUM_BRANCHES({num_branches}) <> NUM_CHANNELS(' \ + f'{len(num_channels)})' + raise ValueError(error_msg) + + if num_branches != len(in_channels): + error_msg = f'NUM_BRANCHES({num_branches}) <> NUM_INCHANNELS(' \ + f'{len(in_channels)})' + raise ValueError(error_msg) + + def _make_one_branch(self, + branch_index, + block, + num_blocks, + num_channels, + stride=1): + """Build one branch.""" + downsample = None + if stride != 1 or \ + self.in_channels[branch_index] != \ + num_channels[branch_index] * block.expansion: + downsample = nn.Sequential( + build_conv_layer( + self.conv_cfg, + self.in_channels[branch_index], + num_channels[branch_index] * block.expansion, + kernel_size=1, + stride=stride, + bias=False), + build_norm_layer(self.norm_cfg, num_channels[branch_index] * + block.expansion)[1]) + + layers = [] + layers.append( + block( + self.in_channels[branch_index], + num_channels[branch_index], + stride, + downsample=downsample, + with_cp=self.with_cp, + norm_cfg=self.norm_cfg, + conv_cfg=self.conv_cfg, + init_cfg=self.block_init_cfg)) + self.in_channels[branch_index] = \ + num_channels[branch_index] * block.expansion + for i in range(1, num_blocks[branch_index]): + layers.append( + block( + self.in_channels[branch_index], + num_channels[branch_index], + with_cp=self.with_cp, + norm_cfg=self.norm_cfg, + conv_cfg=self.conv_cfg, + init_cfg=self.block_init_cfg)) + + return Sequential(*layers) + + def _make_branches(self, num_branches, block, num_blocks, num_channels): + """Build multiple branch.""" + branches = [] + + for i in range(num_branches): + branches.append( + self._make_one_branch(i, block, num_blocks, num_channels)) + + return ModuleList(branches) + + def _make_fuse_layers(self): + """Build fuse layer.""" + if self.num_branches == 1: + return None + + num_branches = self.num_branches + in_channels = self.in_channels + fuse_layers = [] + num_out_branches = num_branches if self.multiscale_output else 1 + for i in range(num_out_branches): + fuse_layer = [] + for j in range(num_branches): + if j > i: + fuse_layer.append( + nn.Sequential( + build_conv_layer( + self.conv_cfg, + in_channels[j], + in_channels[i], + kernel_size=1, + stride=1, + padding=0, + bias=False), + build_norm_layer(self.norm_cfg, in_channels[i])[1], + # we set align_corners=False for HRNet + Upsample( + scale_factor=2**(j - i), + mode='bilinear', + align_corners=False))) + elif j == i: + fuse_layer.append(None) + else: + conv_downsamples = [] + for k in range(i - j): + if k == i - j - 1: + conv_downsamples.append( + nn.Sequential( + build_conv_layer( + self.conv_cfg, + in_channels[j], + in_channels[i], + kernel_size=3, + stride=2, + padding=1, + bias=False), + build_norm_layer(self.norm_cfg, + in_channels[i])[1])) + else: + conv_downsamples.append( + nn.Sequential( + build_conv_layer( + self.conv_cfg, + in_channels[j], + in_channels[j], + kernel_size=3, + stride=2, + padding=1, + bias=False), + build_norm_layer(self.norm_cfg, + in_channels[j])[1], + nn.ReLU(inplace=False))) + fuse_layer.append(nn.Sequential(*conv_downsamples)) + fuse_layers.append(nn.ModuleList(fuse_layer)) + + return nn.ModuleList(fuse_layers) + + def forward(self, x): + """Forward function.""" + if self.num_branches == 1: + return [self.branches[0](x[0])] + + for i in range(self.num_branches): + x[i] = self.branches[i](x[i]) + + x_fuse = [] + for i in range(len(self.fuse_layers)): + y = 0 + for j in range(self.num_branches): + if i == j: + y += x[j] + elif j > i: + y = y + resize( + self.fuse_layers[i][j](x[j]), + size=x[i].shape[2:], + mode='bilinear', + align_corners=False) + else: + y += self.fuse_layers[i][j](x[j]) + x_fuse.append(self.relu(y)) + return x_fuse + + +@MODELS.register_module() +class HRNet(BaseModule): + """HRNet backbone. + + This backbone is the implementation of `High-Resolution Representations + for Labeling Pixels and Regions `_. + + Args: + extra (dict): Detailed configuration for each stage of HRNet. + There must be 4 stages, the configuration for each stage must have + 5 keys: + + - num_modules (int): The number of HRModule in this stage. + - num_branches (int): The number of branches in the HRModule. + - block (str): The type of convolution block. + - num_blocks (tuple): The number of blocks in each branch. + The length must be equal to num_branches. + - num_channels (tuple): The number of channels in each branch. + The length must be equal to num_branches. + in_channels (int): Number of input image channels. Normally 3. + conv_cfg (dict): Dictionary to construct and config conv layer. + Default: None. + norm_cfg (dict): Dictionary to construct and config norm layer. + Use `BN` by default. + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + frozen_stages (int): Stages to be frozen (stop grad and set eval mode). + -1 means not freezing any parameters. Default: -1. + zero_init_residual (bool): Whether to use zero init for last norm layer + in resblocks to let them behave as identity. Default: False. + multiscale_output (bool): Whether to output multi-level features + produced by multiple branches. If False, only the first level + feature will be output. Default: True. + pretrained (str, optional): Model pretrained path. Default: None. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + + Example: + >>> from mmseg.models import HRNet + >>> import torch + >>> extra = dict( + >>> stage1=dict( + >>> num_modules=1, + >>> num_branches=1, + >>> block='BOTTLENECK', + >>> num_blocks=(4, ), + >>> num_channels=(64, )), + >>> stage2=dict( + >>> num_modules=1, + >>> num_branches=2, + >>> block='BASIC', + >>> num_blocks=(4, 4), + >>> num_channels=(32, 64)), + >>> stage3=dict( + >>> num_modules=4, + >>> num_branches=3, + >>> block='BASIC', + >>> num_blocks=(4, 4, 4), + >>> num_channels=(32, 64, 128)), + >>> stage4=dict( + >>> num_modules=3, + >>> num_branches=4, + >>> block='BASIC', + >>> num_blocks=(4, 4, 4, 4), + >>> num_channels=(32, 64, 128, 256))) + >>> self = HRNet(extra, in_channels=1) + >>> self.eval() + >>> inputs = torch.rand(1, 1, 32, 32) + >>> level_outputs = self.forward(inputs) + >>> for level_out in level_outputs: + ... print(tuple(level_out.shape)) + (1, 32, 8, 8) + (1, 64, 4, 4) + (1, 128, 2, 2) + (1, 256, 1, 1) + """ + + blocks_dict = {'BASIC': BasicBlock, 'BOTTLENECK': Bottleneck} + + def __init__(self, + extra, + in_channels=3, + conv_cfg=None, + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=False, + with_cp=False, + frozen_stages=-1, + zero_init_residual=False, + multiscale_output=True, + pretrained=None, + init_cfg=None): + super().__init__(init_cfg) + + self.pretrained = pretrained + self.zero_init_residual = zero_init_residual + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be setting at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is None: + if init_cfg is None: + self.init_cfg = [ + dict(type='Kaiming', layer='Conv2d'), + dict( + type='Constant', + val=1, + layer=['_BatchNorm', 'GroupNorm']) + ] + else: + raise TypeError('pretrained must be a str or None') + + # Assert configurations of 4 stages are in extra + assert 'stage1' in extra and 'stage2' in extra \ + and 'stage3' in extra and 'stage4' in extra + # Assert whether the length of `num_blocks` and `num_channels` are + # equal to `num_branches` + for i in range(4): + cfg = extra[f'stage{i + 1}'] + assert len(cfg['num_blocks']) == cfg['num_branches'] and \ + len(cfg['num_channels']) == cfg['num_branches'] + + self.extra = extra + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.norm_eval = norm_eval + self.with_cp = with_cp + self.frozen_stages = frozen_stages + + # stem net + self.norm1_name, norm1 = build_norm_layer(self.norm_cfg, 64, postfix=1) + self.norm2_name, norm2 = build_norm_layer(self.norm_cfg, 64, postfix=2) + + self.conv1 = build_conv_layer( + self.conv_cfg, + in_channels, + 64, + kernel_size=3, + stride=2, + padding=1, + bias=False) + + self.add_module(self.norm1_name, norm1) + self.conv2 = build_conv_layer( + self.conv_cfg, + 64, + 64, + kernel_size=3, + stride=2, + padding=1, + bias=False) + + self.add_module(self.norm2_name, norm2) + self.relu = nn.ReLU(inplace=True) + + # stage 1 + self.stage1_cfg = self.extra['stage1'] + num_channels = self.stage1_cfg['num_channels'][0] + block_type = self.stage1_cfg['block'] + num_blocks = self.stage1_cfg['num_blocks'][0] + + block = self.blocks_dict[block_type] + stage1_out_channels = num_channels * block.expansion + self.layer1 = self._make_layer(block, 64, num_channels, num_blocks) + + # stage 2 + self.stage2_cfg = self.extra['stage2'] + num_channels = self.stage2_cfg['num_channels'] + block_type = self.stage2_cfg['block'] + + block = self.blocks_dict[block_type] + num_channels = [channel * block.expansion for channel in num_channels] + self.transition1 = self._make_transition_layer([stage1_out_channels], + num_channels) + self.stage2, pre_stage_channels = self._make_stage( + self.stage2_cfg, num_channels) + + # stage 3 + self.stage3_cfg = self.extra['stage3'] + num_channels = self.stage3_cfg['num_channels'] + block_type = self.stage3_cfg['block'] + + block = self.blocks_dict[block_type] + num_channels = [channel * block.expansion for channel in num_channels] + self.transition2 = self._make_transition_layer(pre_stage_channels, + num_channels) + self.stage3, pre_stage_channels = self._make_stage( + self.stage3_cfg, num_channels) + + # stage 4 + self.stage4_cfg = self.extra['stage4'] + num_channels = self.stage4_cfg['num_channels'] + block_type = self.stage4_cfg['block'] + + block = self.blocks_dict[block_type] + num_channels = [channel * block.expansion for channel in num_channels] + self.transition3 = self._make_transition_layer(pre_stage_channels, + num_channels) + self.stage4, pre_stage_channels = self._make_stage( + self.stage4_cfg, num_channels, multiscale_output=multiscale_output) + + self._freeze_stages() + + @property + def norm1(self): + """nn.Module: the normalization layer named "norm1" """ + return getattr(self, self.norm1_name) + + @property + def norm2(self): + """nn.Module: the normalization layer named "norm2" """ + return getattr(self, self.norm2_name) + + def _make_transition_layer(self, num_channels_pre_layer, + num_channels_cur_layer): + """Make transition layer.""" + num_branches_cur = len(num_channels_cur_layer) + num_branches_pre = len(num_channels_pre_layer) + + transition_layers = [] + for i in range(num_branches_cur): + if i < num_branches_pre: + if num_channels_cur_layer[i] != num_channels_pre_layer[i]: + transition_layers.append( + nn.Sequential( + build_conv_layer( + self.conv_cfg, + num_channels_pre_layer[i], + num_channels_cur_layer[i], + kernel_size=3, + stride=1, + padding=1, + bias=False), + build_norm_layer(self.norm_cfg, + num_channels_cur_layer[i])[1], + nn.ReLU(inplace=True))) + else: + transition_layers.append(None) + else: + conv_downsamples = [] + for j in range(i + 1 - num_branches_pre): + in_channels = num_channels_pre_layer[-1] + out_channels = num_channels_cur_layer[i] \ + if j == i - num_branches_pre else in_channels + conv_downsamples.append( + nn.Sequential( + build_conv_layer( + self.conv_cfg, + in_channels, + out_channels, + kernel_size=3, + stride=2, + padding=1, + bias=False), + build_norm_layer(self.norm_cfg, out_channels)[1], + nn.ReLU(inplace=True))) + transition_layers.append(nn.Sequential(*conv_downsamples)) + + return nn.ModuleList(transition_layers) + + def _make_layer(self, block, inplanes, planes, blocks, stride=1): + """Make each layer.""" + downsample = None + if stride != 1 or inplanes != planes * block.expansion: + downsample = nn.Sequential( + build_conv_layer( + self.conv_cfg, + inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + bias=False), + build_norm_layer(self.norm_cfg, planes * block.expansion)[1]) + + layers = [] + block_init_cfg = None + if self.pretrained is None and not hasattr( + self, 'init_cfg') and self.zero_init_residual: + if block is BasicBlock: + block_init_cfg = dict( + type='Constant', val=0, override=dict(name='norm2')) + elif block is Bottleneck: + block_init_cfg = dict( + type='Constant', val=0, override=dict(name='norm3')) + + layers.append( + block( + inplanes, + planes, + stride, + downsample=downsample, + with_cp=self.with_cp, + norm_cfg=self.norm_cfg, + conv_cfg=self.conv_cfg, + init_cfg=block_init_cfg)) + inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append( + block( + inplanes, + planes, + with_cp=self.with_cp, + norm_cfg=self.norm_cfg, + conv_cfg=self.conv_cfg, + init_cfg=block_init_cfg)) + + return Sequential(*layers) + + def _make_stage(self, layer_config, in_channels, multiscale_output=True): + """Make each stage.""" + num_modules = layer_config['num_modules'] + num_branches = layer_config['num_branches'] + num_blocks = layer_config['num_blocks'] + num_channels = layer_config['num_channels'] + block = self.blocks_dict[layer_config['block']] + + hr_modules = [] + block_init_cfg = None + if self.pretrained is None and not hasattr( + self, 'init_cfg') and self.zero_init_residual: + if block is BasicBlock: + block_init_cfg = dict( + type='Constant', val=0, override=dict(name='norm2')) + elif block is Bottleneck: + block_init_cfg = dict( + type='Constant', val=0, override=dict(name='norm3')) + + for i in range(num_modules): + # multi_scale_output is only used for the last module + if not multiscale_output and i == num_modules - 1: + reset_multiscale_output = False + else: + reset_multiscale_output = True + + hr_modules.append( + HRModule( + num_branches, + block, + num_blocks, + in_channels, + num_channels, + reset_multiscale_output, + with_cp=self.with_cp, + norm_cfg=self.norm_cfg, + conv_cfg=self.conv_cfg, + block_init_cfg=block_init_cfg)) + + return Sequential(*hr_modules), in_channels + + def _freeze_stages(self): + """Freeze stages param and norm stats.""" + if self.frozen_stages >= 0: + + self.norm1.eval() + self.norm2.eval() + for m in [self.conv1, self.norm1, self.conv2, self.norm2]: + for param in m.parameters(): + param.requires_grad = False + + for i in range(1, self.frozen_stages + 1): + if i == 1: + m = getattr(self, f'layer{i}') + t = getattr(self, f'transition{i}') + elif i == 4: + m = getattr(self, f'stage{i}') + else: + m = getattr(self, f'stage{i}') + t = getattr(self, f'transition{i}') + m.eval() + for param in m.parameters(): + param.requires_grad = False + t.eval() + for param in t.parameters(): + param.requires_grad = False + + def forward(self, x): + """Forward function.""" + + x = self.conv1(x) + x = self.norm1(x) + x = self.relu(x) + x = self.conv2(x) + x = self.norm2(x) + x = self.relu(x) + x = self.layer1(x) + + x_list = [] + for i in range(self.stage2_cfg['num_branches']): + if self.transition1[i] is not None: + x_list.append(self.transition1[i](x)) + else: + x_list.append(x) + y_list = self.stage2(x_list) + + x_list = [] + for i in range(self.stage3_cfg['num_branches']): + if self.transition2[i] is not None: + x_list.append(self.transition2[i](y_list[-1])) + else: + x_list.append(y_list[i]) + y_list = self.stage3(x_list) + + x_list = [] + for i in range(self.stage4_cfg['num_branches']): + if self.transition3[i] is not None: + x_list.append(self.transition3[i](y_list[-1])) + else: + x_list.append(y_list[i]) + y_list = self.stage4(x_list) + + return y_list + + def train(self, mode=True): + """Convert the model into training mode will keeping the normalization + layer freezed.""" + super().train(mode) + self._freeze_stages() + if mode and self.norm_eval: + for m in self.modules(): + # trick: eval have effect on BatchNorm only + if isinstance(m, _BatchNorm): + m.eval() diff --git a/third-party/InterFormer/mmseg/models/backbones/icnet.py b/third-party/InterFormer/mmseg/models/backbones/icnet.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff3448569c5a3ec82a12726767fcbb48b3870d2 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/icnet.py @@ -0,0 +1,166 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..decode_heads.psp_head import PPM +from ..utils import resize + + +@MODELS.register_module() +class ICNet(BaseModule): + """ICNet for Real-Time Semantic Segmentation on High-Resolution Images. + + This backbone is the implementation of + `ICNet `_. + + Args: + backbone_cfg (dict): Config dict to build backbone. Usually it is + ResNet but it can also be other backbones. + in_channels (int): The number of input image channels. Default: 3. + layer_channels (Sequence[int]): The numbers of feature channels at + layer 2 and layer 4 in ResNet. It can also be other backbones. + Default: (512, 2048). + light_branch_middle_channels (int): The number of channels of the + middle layer in light branch. Default: 32. + psp_out_channels (int): The number of channels of the output of PSP + module. Default: 512. + out_channels (Sequence[int]): The numbers of output feature channels + at each branches. Default: (64, 256, 256). + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module. Default: (1, 2, 3, 6). + conv_cfg (dict): Dictionary to construct and config conv layer. + Default: None. + norm_cfg (dict): Dictionary to construct and config norm layer. + Default: dict(type='BN'). + act_cfg (dict): Dictionary to construct and config act layer. + Default: dict(type='ReLU'). + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + backbone_cfg, + in_channels=3, + layer_channels=(512, 2048), + light_branch_middle_channels=32, + psp_out_channels=512, + out_channels=(64, 256, 256), + pool_scales=(1, 2, 3, 6), + conv_cfg=None, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='ReLU'), + align_corners=False, + init_cfg=None): + if backbone_cfg is None: + raise TypeError('backbone_cfg must be passed from config file!') + if init_cfg is None: + init_cfg = [ + dict(type='Kaiming', mode='fan_out', layer='Conv2d'), + dict(type='Constant', val=1, layer='_BatchNorm'), + dict(type='Normal', mean=0.01, layer='Linear') + ] + super().__init__(init_cfg=init_cfg) + self.align_corners = align_corners + self.backbone = MODELS.build(backbone_cfg) + + # Note: Default `ceil_mode` is false in nn.MaxPool2d, set + # `ceil_mode=True` to keep information in the corner of feature map. + self.backbone.maxpool = nn.MaxPool2d( + kernel_size=3, stride=2, padding=1, ceil_mode=True) + + self.psp_modules = PPM( + pool_scales=pool_scales, + in_channels=layer_channels[1], + channels=psp_out_channels, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + align_corners=align_corners) + + self.psp_bottleneck = ConvModule( + layer_channels[1] + len(pool_scales) * psp_out_channels, + psp_out_channels, + 3, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + self.conv_sub1 = nn.Sequential( + ConvModule( + in_channels=in_channels, + out_channels=light_branch_middle_channels, + kernel_size=3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg), + ConvModule( + in_channels=light_branch_middle_channels, + out_channels=light_branch_middle_channels, + kernel_size=3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg), + ConvModule( + in_channels=light_branch_middle_channels, + out_channels=out_channels[0], + kernel_size=3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg)) + + self.conv_sub2 = ConvModule( + layer_channels[0], + out_channels[1], + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg) + + self.conv_sub4 = ConvModule( + psp_out_channels, + out_channels[2], + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg) + + def forward(self, x): + output = [] + + # sub 1 + output.append(self.conv_sub1(x)) + + # sub 2 + x = resize( + x, + scale_factor=0.5, + mode='bilinear', + align_corners=self.align_corners) + x = self.backbone.stem(x) + x = self.backbone.maxpool(x) + x = self.backbone.layer1(x) + x = self.backbone.layer2(x) + output.append(self.conv_sub2(x)) + + # sub 4 + x = resize( + x, + scale_factor=0.5, + mode='bilinear', + align_corners=self.align_corners) + x = self.backbone.layer3(x) + x = self.backbone.layer4(x) + psp_outs = self.psp_modules(x) + [x] + psp_outs = torch.cat(psp_outs, dim=1) + x = self.psp_bottleneck(psp_outs) + + output.append(self.conv_sub4(x)) + + return output diff --git a/third-party/InterFormer/mmseg/models/backbones/mae.py b/third-party/InterFormer/mmseg/models/backbones/mae.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f243f0857b9aca5454e8c1410075bff9281285 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/mae.py @@ -0,0 +1,260 @@ +# Copyright (c) OpenMMLab. All rights reserved.import math +import math + +import torch +import torch.nn as nn +from mmengine.model import ModuleList +from mmengine.model.weight_init import (constant_init, kaiming_init, + trunc_normal_) +from mmengine.runner.checkpoint import _load_checkpoint +from torch.nn.modules.batchnorm import _BatchNorm + +from mmseg.registry import MODELS +from .beit import BEiT, BEiTAttention, BEiTTransformerEncoderLayer + + +class MAEAttention(BEiTAttention): + """Multi-head self-attention with relative position bias used in MAE. + + This module is different from ``BEiTAttention`` by initializing the + relative bias table with zeros. + """ + + def init_weights(self): + """Initialize relative position bias with zeros.""" + + # As MAE initializes relative position bias as zeros and this class + # inherited from BEiT which initializes relative position bias + # with `trunc_normal`, `init_weights` here does + # nothing and just passes directly + + pass + + +class MAETransformerEncoderLayer(BEiTTransformerEncoderLayer): + """Implements one encoder layer in Vision Transformer. + + This module is different from ``BEiTTransformerEncoderLayer`` by replacing + ``BEiTAttention`` with ``MAEAttention``. + """ + + def build_attn(self, attn_cfg): + self.attn = MAEAttention(**attn_cfg) + + +@MODELS.register_module() +class MAE(BEiT): + """VisionTransformer with support for patch. + + Args: + img_size (int | tuple): Input image size. Default: 224. + patch_size (int): The patch size. Default: 16. + in_channels (int): Number of input channels. Default: 3. + embed_dims (int): embedding dimension. Default: 768. + num_layers (int): depth of transformer. Default: 12. + num_heads (int): number of attention heads. Default: 12. + mlp_ratio (int): ratio of mlp hidden dim to embedding dim. + Default: 4. + out_indices (list | tuple | int): Output from which stages. + Default: -1. + attn_drop_rate (float): The drop out rate for attention layer. + Default 0.0 + drop_path_rate (float): stochastic depth rate. Default 0.0. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN') + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + patch_norm (bool): Whether to add a norm in PatchEmbed Block. + Default: False. + final_norm (bool): Whether to add a additional layer to normalize + final feature map. Default: False. + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + pretrained (str, optional): model pretrained path. Default: None. + init_values (float): Initialize the values of Attention and FFN + with learnable scaling. Defaults to 0.1. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + img_size=224, + patch_size=16, + in_channels=3, + embed_dims=768, + num_layers=12, + num_heads=12, + mlp_ratio=4, + out_indices=-1, + attn_drop_rate=0., + drop_path_rate=0., + norm_cfg=dict(type='LN'), + act_cfg=dict(type='GELU'), + patch_norm=False, + final_norm=False, + num_fcs=2, + norm_eval=False, + pretrained=None, + init_values=0.1, + init_cfg=None): + super().__init__( + img_size=img_size, + patch_size=patch_size, + in_channels=in_channels, + embed_dims=embed_dims, + num_layers=num_layers, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + out_indices=out_indices, + qv_bias=False, + attn_drop_rate=attn_drop_rate, + drop_path_rate=drop_path_rate, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + patch_norm=patch_norm, + final_norm=final_norm, + num_fcs=num_fcs, + norm_eval=norm_eval, + pretrained=pretrained, + init_values=init_values, + init_cfg=init_cfg) + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dims)) + + self.num_patches = self.patch_shape[0] * self.patch_shape[1] + self.pos_embed = nn.Parameter( + torch.zeros(1, self.num_patches + 1, embed_dims)) + + def _build_layers(self): + dpr = [ + x.item() + for x in torch.linspace(0, self.drop_path_rate, self.num_layers) + ] + self.layers = ModuleList() + for i in range(self.num_layers): + self.layers.append( + MAETransformerEncoderLayer( + embed_dims=self.embed_dims, + num_heads=self.num_heads, + feedforward_channels=self.mlp_ratio * self.embed_dims, + attn_drop_rate=self.attn_drop_rate, + drop_path_rate=dpr[i], + num_fcs=self.num_fcs, + bias=True, + act_cfg=self.act_cfg, + norm_cfg=self.norm_cfg, + window_size=self.patch_shape, + init_values=self.init_values)) + + def fix_init_weight(self): + """Rescale the initialization according to layer id. + + This function is copied from https://github.com/microsoft/unilm/blob/master/beit/modeling_pretrain.py. # noqa: E501 + Copyright (c) Microsoft Corporation + Licensed under the MIT License + """ + + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.layers): + rescale(layer.attn.proj.weight.data, layer_id + 1) + rescale(layer.ffn.layers[1].weight.data, layer_id + 1) + + def init_weights(self): + + def _init_weights(m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + self.apply(_init_weights) + self.fix_init_weight() + + if (isinstance(self.init_cfg, dict) + and self.init_cfg.get('type') == 'Pretrained'): + checkpoint = _load_checkpoint( + self.init_cfg['checkpoint'], logger=None, map_location='cpu') + state_dict = self.resize_rel_pos_embed(checkpoint) + state_dict = self.resize_abs_pos_embed(state_dict) + self.load_state_dict(state_dict, False) + elif self.init_cfg is not None: + super().init_weights() + else: + # We only implement the 'jax_impl' initialization implemented at + # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py#L353 # noqa: E501 + # Copyright 2019 Ross Wightman + # Licensed under the Apache License, Version 2.0 (the "License") + trunc_normal_(self.cls_token, std=.02) + for n, m in self.named_modules(): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if m.bias is not None: + if 'ffn' in n: + nn.init.normal_(m.bias, mean=0., std=1e-6) + else: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv2d): + kaiming_init(m, mode='fan_in', bias=0.) + elif isinstance(m, (_BatchNorm, nn.GroupNorm, nn.LayerNorm)): + constant_init(m, val=1.0, bias=0.) + + def resize_abs_pos_embed(self, state_dict): + if 'pos_embed' in state_dict: + pos_embed_checkpoint = state_dict['pos_embed'] + embedding_size = pos_embed_checkpoint.shape[-1] + num_extra_tokens = self.pos_embed.shape[-2] - self.num_patches + # height (== width) for the checkpoint position embedding + orig_size = int( + (pos_embed_checkpoint.shape[-2] - num_extra_tokens)**0.5) + # height (== width) for the new position embedding + new_size = int(self.num_patches**0.5) + # class_token and dist_token are kept unchanged + if orig_size != new_size: + extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] + # only the position tokens are interpolated + pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, + embedding_size).permute( + 0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, + size=(new_size, new_size), + mode='bicubic', + align_corners=False) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) + state_dict['pos_embed'] = new_pos_embed + return state_dict + + def forward(self, inputs): + B = inputs.shape[0] + + x, hw_shape = self.patch_embed(inputs) + + # stole cls_tokens impl from Phil Wang, thanks + cls_tokens = self.cls_token.expand(B, -1, -1) + x = torch.cat((cls_tokens, x), dim=1) + x = x + self.pos_embed + + outs = [] + for i, layer in enumerate(self.layers): + x = layer(x) + if i == len(self.layers) - 1: + if self.final_norm: + x = self.norm1(x) + if i in self.out_indices: + out = x[:, 1:] + B, _, C = out.shape + out = out.reshape(B, hw_shape[0], hw_shape[1], + C).permute(0, 3, 1, 2).contiguous() + outs.append(out) + + return tuple(outs) diff --git a/third-party/InterFormer/mmseg/models/backbones/mit.py b/third-party/InterFormer/mmseg/models/backbones/mit.py new file mode 100644 index 0000000000000000000000000000000000000000..66556bdfca2b0bcb180afd23c2923c68b9ff3a69 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/mit.py @@ -0,0 +1,450 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +import warnings + +import torch +import torch.nn as nn +import torch.utils.checkpoint as cp +from mmcv.cnn import Conv2d, build_activation_layer, build_norm_layer +from mmcv.cnn.bricks.drop import build_dropout +from mmcv.cnn.bricks.transformer import MultiheadAttention +from mmengine.model import BaseModule, ModuleList, Sequential +from mmengine.model.weight_init import (constant_init, normal_init, + trunc_normal_init) + +from mmseg.registry import MODELS +from ..utils import PatchEmbed, nchw_to_nlc, nlc_to_nchw + + +class MixFFN(BaseModule): + """An implementation of MixFFN of Segformer. + + The differences between MixFFN & FFN: + 1. Use 1X1 Conv to replace Linear layer. + 2. Introduce 3X3 Conv to encode positional information. + Args: + embed_dims (int): The feature dimension. Same as + `MultiheadAttention`. Defaults: 256. + feedforward_channels (int): The hidden dimension of FFNs. + Defaults: 1024. + act_cfg (dict, optional): The activation config for FFNs. + Default: dict(type='ReLU') + ffn_drop (float, optional): Probability of an element to be + zeroed in FFN. Default 0.0. + dropout_layer (obj:`ConfigDict`): The dropout_layer used + when adding the shortcut. + init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization. + Default: None. + """ + + def __init__(self, + embed_dims, + feedforward_channels, + act_cfg=dict(type='GELU'), + ffn_drop=0., + dropout_layer=None, + init_cfg=None): + super().__init__(init_cfg) + + self.embed_dims = embed_dims + self.feedforward_channels = feedforward_channels + self.act_cfg = act_cfg + self.activate = build_activation_layer(act_cfg) + + in_channels = embed_dims + fc1 = Conv2d( + in_channels=in_channels, + out_channels=feedforward_channels, + kernel_size=1, + stride=1, + bias=True) + # 3x3 depth wise conv to provide positional encode information + pe_conv = Conv2d( + in_channels=feedforward_channels, + out_channels=feedforward_channels, + kernel_size=3, + stride=1, + padding=(3 - 1) // 2, + bias=True, + groups=feedforward_channels) + fc2 = Conv2d( + in_channels=feedforward_channels, + out_channels=in_channels, + kernel_size=1, + stride=1, + bias=True) + drop = nn.Dropout(ffn_drop) + layers = [fc1, pe_conv, self.activate, drop, fc2, drop] + self.layers = Sequential(*layers) + self.dropout_layer = build_dropout( + dropout_layer) if dropout_layer else torch.nn.Identity() + + def forward(self, x, hw_shape, identity=None): + out = nlc_to_nchw(x, hw_shape) + out = self.layers(out) + out = nchw_to_nlc(out) + if identity is None: + identity = x + return identity + self.dropout_layer(out) + + +class EfficientMultiheadAttention(MultiheadAttention): + """An implementation of Efficient Multi-head Attention of Segformer. + + This module is modified from MultiheadAttention which is a module from + mmcv.cnn.bricks.transformer. + Args: + embed_dims (int): The embedding dimension. + num_heads (int): Parallel attention heads. + attn_drop (float): A Dropout layer on attn_output_weights. + Default: 0.0. + proj_drop (float): A Dropout layer after `nn.MultiheadAttention`. + Default: 0.0. + dropout_layer (obj:`ConfigDict`): The dropout_layer used + when adding the shortcut. Default: None. + init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization. + Default: None. + batch_first (bool): Key, Query and Value are shape of + (batch, n, embed_dim) + or (n, batch, embed_dim). Default: False. + qkv_bias (bool): enable bias for qkv if True. Default True. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + sr_ratio (int): The ratio of spatial reduction of Efficient Multi-head + Attention of Segformer. Default: 1. + """ + + def __init__(self, + embed_dims, + num_heads, + attn_drop=0., + proj_drop=0., + dropout_layer=None, + init_cfg=None, + batch_first=True, + qkv_bias=False, + norm_cfg=dict(type='LN'), + sr_ratio=1): + super().__init__( + embed_dims, + num_heads, + attn_drop, + proj_drop, + dropout_layer=dropout_layer, + init_cfg=init_cfg, + batch_first=batch_first, + bias=qkv_bias) + + self.sr_ratio = sr_ratio + if sr_ratio > 1: + self.sr = Conv2d( + in_channels=embed_dims, + out_channels=embed_dims, + kernel_size=sr_ratio, + stride=sr_ratio) + # The ret[0] of build_norm_layer is norm name. + self.norm = build_norm_layer(norm_cfg, embed_dims)[1] + + # handle the BC-breaking from https://github.com/open-mmlab/mmcv/pull/1418 # noqa + from mmseg import digit_version, mmcv_version + if mmcv_version < digit_version('1.3.17'): + warnings.warn('The legacy version of forward function in' + 'EfficientMultiheadAttention is deprecated in' + 'mmcv>=1.3.17 and will no longer support in the' + 'future. Please upgrade your mmcv.') + self.forward = self.legacy_forward + + def forward(self, x, hw_shape, identity=None): + + x_q = x + if self.sr_ratio > 1: + x_kv = nlc_to_nchw(x, hw_shape) + x_kv = self.sr(x_kv) + x_kv = nchw_to_nlc(x_kv) + x_kv = self.norm(x_kv) + else: + x_kv = x + + if identity is None: + identity = x_q + + # Because the dataflow('key', 'query', 'value') of + # ``torch.nn.MultiheadAttention`` is (num_query, batch, + # embed_dims), We should adjust the shape of dataflow from + # batch_first (batch, num_query, embed_dims) to num_query_first + # (num_query ,batch, embed_dims), and recover ``attn_output`` + # from num_query_first to batch_first. + if self.batch_first: + x_q = x_q.transpose(0, 1) + x_kv = x_kv.transpose(0, 1) + + out = self.attn(query=x_q, key=x_kv, value=x_kv)[0] + + if self.batch_first: + out = out.transpose(0, 1) + + return identity + self.dropout_layer(self.proj_drop(out)) + + def legacy_forward(self, x, hw_shape, identity=None): + """multi head attention forward in mmcv version < 1.3.17.""" + + x_q = x + if self.sr_ratio > 1: + x_kv = nlc_to_nchw(x, hw_shape) + x_kv = self.sr(x_kv) + x_kv = nchw_to_nlc(x_kv) + x_kv = self.norm(x_kv) + else: + x_kv = x + + if identity is None: + identity = x_q + + # `need_weights=True` will let nn.MultiHeadAttention + # `return attn_output, attn_output_weights.sum(dim=1) / num_heads` + # The `attn_output_weights.sum(dim=1)` may cause cuda error. So, we set + # `need_weights=False` to ignore `attn_output_weights.sum(dim=1)`. + # This issue - `https://github.com/pytorch/pytorch/issues/37583` report + # the error that large scale tensor sum operation may cause cuda error. + out = self.attn(query=x_q, key=x_kv, value=x_kv, need_weights=False)[0] + + return identity + self.dropout_layer(self.proj_drop(out)) + + +class TransformerEncoderLayer(BaseModule): + """Implements one encoder layer in Segformer. + + Args: + embed_dims (int): The feature dimension. + num_heads (int): Parallel attention heads. + feedforward_channels (int): The hidden dimension for FFNs. + drop_rate (float): Probability of an element to be zeroed. + after the feed forward layer. Default 0.0. + attn_drop_rate (float): The drop out rate for attention layer. + Default 0.0. + drop_path_rate (float): stochastic depth rate. Default 0.0. + qkv_bias (bool): enable bias for qkv if True. + Default: True. + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + batch_first (bool): Key, Query and Value are shape of + (batch, n, embed_dim) + or (n, batch, embed_dim). Default: False. + init_cfg (dict, optional): Initialization config dict. + Default:None. + sr_ratio (int): The ratio of spatial reduction of Efficient Multi-head + Attention of Segformer. Default: 1. + with_cp (bool): Use checkpoint or not. Using checkpoint will save + some memory while slowing down the training speed. Default: False. + """ + + def __init__(self, + embed_dims, + num_heads, + feedforward_channels, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + qkv_bias=True, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + batch_first=True, + sr_ratio=1, + with_cp=False): + super().__init__() + + # The ret[0] of build_norm_layer is norm name. + self.norm1 = build_norm_layer(norm_cfg, embed_dims)[1] + + self.attn = EfficientMultiheadAttention( + embed_dims=embed_dims, + num_heads=num_heads, + attn_drop=attn_drop_rate, + proj_drop=drop_rate, + dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), + batch_first=batch_first, + qkv_bias=qkv_bias, + norm_cfg=norm_cfg, + sr_ratio=sr_ratio) + + # The ret[0] of build_norm_layer is norm name. + self.norm2 = build_norm_layer(norm_cfg, embed_dims)[1] + + self.ffn = MixFFN( + embed_dims=embed_dims, + feedforward_channels=feedforward_channels, + ffn_drop=drop_rate, + dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), + act_cfg=act_cfg) + + self.with_cp = with_cp + + def forward(self, x, hw_shape): + + def _inner_forward(x): + x = self.attn(self.norm1(x), hw_shape, identity=x) + x = self.ffn(self.norm2(x), hw_shape, identity=x) + return x + + if self.with_cp and x.requires_grad: + x = cp.checkpoint(_inner_forward, x) + else: + x = _inner_forward(x) + return x + + +@MODELS.register_module() +class MixVisionTransformer(BaseModule): + """The backbone of Segformer. + + This backbone is the implementation of `SegFormer: Simple and + Efficient Design for Semantic Segmentation with + Transformers `_. + Args: + in_channels (int): Number of input channels. Default: 3. + embed_dims (int): Embedding dimension. Default: 768. + num_stags (int): The num of stages. Default: 4. + num_layers (Sequence[int]): The layer number of each transformer encode + layer. Default: [3, 4, 6, 3]. + num_heads (Sequence[int]): The attention heads of each transformer + encode layer. Default: [1, 2, 4, 8]. + patch_sizes (Sequence[int]): The patch_size of each overlapped patch + embedding. Default: [7, 3, 3, 3]. + strides (Sequence[int]): The stride of each overlapped patch embedding. + Default: [4, 2, 2, 2]. + sr_ratios (Sequence[int]): The spatial reduction rate of each + transformer encode layer. Default: [8, 4, 2, 1]. + out_indices (Sequence[int] | int): Output from which stages. + Default: (0, 1, 2, 3). + mlp_ratio (int): ratio of mlp hidden dim to embedding dim. + Default: 4. + qkv_bias (bool): Enable bias for qkv if True. Default: True. + drop_rate (float): Probability of an element to be zeroed. + Default 0.0 + attn_drop_rate (float): The drop out rate for attention layer. + Default 0.0 + drop_path_rate (float): stochastic depth rate. Default 0.0 + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN') + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + pretrained (str, optional): model pretrained path. Default: None. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + with_cp (bool): Use checkpoint or not. Using checkpoint will save + some memory while slowing down the training speed. Default: False. + """ + + def __init__(self, + in_channels=3, + embed_dims=64, + num_stages=4, + num_layers=[3, 4, 6, 3], + num_heads=[1, 2, 4, 8], + patch_sizes=[7, 3, 3, 3], + strides=[4, 2, 2, 2], + sr_ratios=[8, 4, 2, 1], + out_indices=(0, 1, 2, 3), + mlp_ratio=4, + qkv_bias=True, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN', eps=1e-6), + pretrained=None, + init_cfg=None, + with_cp=False): + super().__init__(init_cfg=init_cfg) + + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be set at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is not None: + raise TypeError('pretrained must be a str or None') + + self.embed_dims = embed_dims + self.num_stages = num_stages + self.num_layers = num_layers + self.num_heads = num_heads + self.patch_sizes = patch_sizes + self.strides = strides + self.sr_ratios = sr_ratios + self.with_cp = with_cp + assert num_stages == len(num_layers) == len(num_heads) \ + == len(patch_sizes) == len(strides) == len(sr_ratios) + + self.out_indices = out_indices + assert max(out_indices) < self.num_stages + + # transformer encoder + dpr = [ + x.item() + for x in torch.linspace(0, drop_path_rate, sum(num_layers)) + ] # stochastic num_layer decay rule + + cur = 0 + self.layers = ModuleList() + for i, num_layer in enumerate(num_layers): + embed_dims_i = embed_dims * num_heads[i] + patch_embed = PatchEmbed( + in_channels=in_channels, + embed_dims=embed_dims_i, + kernel_size=patch_sizes[i], + stride=strides[i], + padding=patch_sizes[i] // 2, + norm_cfg=norm_cfg) + layer = ModuleList([ + TransformerEncoderLayer( + embed_dims=embed_dims_i, + num_heads=num_heads[i], + feedforward_channels=mlp_ratio * embed_dims_i, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=dpr[cur + idx], + qkv_bias=qkv_bias, + act_cfg=act_cfg, + norm_cfg=norm_cfg, + with_cp=with_cp, + sr_ratio=sr_ratios[i]) for idx in range(num_layer) + ]) + in_channels = embed_dims_i + # The ret[0] of build_norm_layer is norm name. + norm = build_norm_layer(norm_cfg, embed_dims_i)[1] + self.layers.append(ModuleList([patch_embed, layer, norm])) + cur += num_layer + + def init_weights(self): + if self.init_cfg is None: + for m in self.modules(): + if isinstance(m, nn.Linear): + trunc_normal_init(m, std=.02, bias=0.) + elif isinstance(m, nn.LayerNorm): + constant_init(m, val=1.0, bias=0.) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[ + 1] * m.out_channels + fan_out //= m.groups + normal_init( + m, mean=0, std=math.sqrt(2.0 / fan_out), bias=0) + else: + super().init_weights() + + def forward(self, x): + outs = [] + + for i, layer in enumerate(self.layers): + x, hw_shape = layer[0](x) + for block in layer[1]: + x = block(x, hw_shape) + x = layer[2](x) + x = nlc_to_nchw(x, hw_shape) + if i in self.out_indices: + outs.append(x) + + return outs diff --git a/third-party/InterFormer/mmseg/models/backbones/mobilenet_v2.py b/third-party/InterFormer/mmseg/models/backbones/mobilenet_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..1c21b5df97dade148136e8b0e6b039512f9e03f9 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/mobilenet_v2.py @@ -0,0 +1,197 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule +from torch.nn.modules.batchnorm import _BatchNorm + +from mmseg.registry import MODELS +from ..utils import InvertedResidual, make_divisible + + +@MODELS.register_module() +class MobileNetV2(BaseModule): + """MobileNetV2 backbone. + + This backbone is the implementation of + `MobileNetV2: Inverted Residuals and Linear Bottlenecks + `_. + + Args: + widen_factor (float): Width multiplier, multiply number of + channels in each layer by this amount. Default: 1.0. + strides (Sequence[int], optional): Strides of the first block of each + layer. If not specified, default config in ``arch_setting`` will + be used. + dilations (Sequence[int]): Dilation of each layer. + out_indices (None or Sequence[int]): Output from which stages. + Default: (7, ). + frozen_stages (int): Stages to be frozen (all param fixed). + Default: -1, which means not freezing any parameters. + conv_cfg (dict): Config dict for convolution layer. + Default: None, which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU6'). + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + pretrained (str, optional): model pretrained path. Default: None + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None + """ + + # Parameters to build layers. 3 parameters are needed to construct a + # layer, from left to right: expand_ratio, channel, num_blocks. + arch_settings = [[1, 16, 1], [6, 24, 2], [6, 32, 3], [6, 64, 4], + [6, 96, 3], [6, 160, 3], [6, 320, 1]] + + def __init__(self, + widen_factor=1., + strides=(1, 2, 2, 2, 1, 2, 1), + dilations=(1, 1, 1, 1, 1, 1, 1), + out_indices=(1, 2, 4, 6), + frozen_stages=-1, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU6'), + norm_eval=False, + with_cp=False, + pretrained=None, + init_cfg=None): + super().__init__(init_cfg) + + self.pretrained = pretrained + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be setting at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is a deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is None: + if init_cfg is None: + self.init_cfg = [ + dict(type='Kaiming', layer='Conv2d'), + dict( + type='Constant', + val=1, + layer=['_BatchNorm', 'GroupNorm']) + ] + else: + raise TypeError('pretrained must be a str or None') + + self.widen_factor = widen_factor + self.strides = strides + self.dilations = dilations + assert len(strides) == len(dilations) == len(self.arch_settings) + self.out_indices = out_indices + for index in out_indices: + if index not in range(0, 7): + raise ValueError('the item in out_indices must in ' + f'range(0, 7). But received {index}') + + if frozen_stages not in range(-1, 7): + raise ValueError('frozen_stages must be in range(-1, 7). ' + f'But received {frozen_stages}') + self.out_indices = out_indices + self.frozen_stages = frozen_stages + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.norm_eval = norm_eval + self.with_cp = with_cp + + self.in_channels = make_divisible(32 * widen_factor, 8) + + self.conv1 = ConvModule( + in_channels=3, + out_channels=self.in_channels, + kernel_size=3, + stride=2, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.layers = [] + + for i, layer_cfg in enumerate(self.arch_settings): + expand_ratio, channel, num_blocks = layer_cfg + stride = self.strides[i] + dilation = self.dilations[i] + out_channels = make_divisible(channel * widen_factor, 8) + inverted_res_layer = self.make_layer( + out_channels=out_channels, + num_blocks=num_blocks, + stride=stride, + dilation=dilation, + expand_ratio=expand_ratio) + layer_name = f'layer{i + 1}' + self.add_module(layer_name, inverted_res_layer) + self.layers.append(layer_name) + + def make_layer(self, out_channels, num_blocks, stride, dilation, + expand_ratio): + """Stack InvertedResidual blocks to build a layer for MobileNetV2. + + Args: + out_channels (int): out_channels of block. + num_blocks (int): Number of blocks. + stride (int): Stride of the first block. + dilation (int): Dilation of the first block. + expand_ratio (int): Expand the number of channels of the + hidden layer in InvertedResidual by this ratio. + """ + layers = [] + for i in range(num_blocks): + layers.append( + InvertedResidual( + self.in_channels, + out_channels, + stride if i == 0 else 1, + expand_ratio=expand_ratio, + dilation=dilation if i == 0 else 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + with_cp=self.with_cp)) + self.in_channels = out_channels + + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1(x) + + outs = [] + for i, layer_name in enumerate(self.layers): + layer = getattr(self, layer_name) + x = layer(x) + if i in self.out_indices: + outs.append(x) + + if len(outs) == 1: + return outs[0] + else: + return tuple(outs) + + def _freeze_stages(self): + if self.frozen_stages >= 0: + for param in self.conv1.parameters(): + param.requires_grad = False + for i in range(1, self.frozen_stages + 1): + layer = getattr(self, f'layer{i}') + layer.eval() + for param in layer.parameters(): + param.requires_grad = False + + def train(self, mode=True): + super().train(mode) + self._freeze_stages() + if mode and self.norm_eval: + for m in self.modules(): + if isinstance(m, _BatchNorm): + m.eval() diff --git a/third-party/InterFormer/mmseg/models/backbones/mobilenet_v3.py b/third-party/InterFormer/mmseg/models/backbones/mobilenet_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..1efb6e097472d53a5269e52a39ff2cae48e834db --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/mobilenet_v3.py @@ -0,0 +1,267 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +from mmcv.cnn import ConvModule +from mmcv.cnn.bricks import Conv2dAdaptivePadding +from mmengine.model import BaseModule +from mmengine.utils import is_tuple_of +from torch.nn.modules.batchnorm import _BatchNorm + +from mmseg.registry import MODELS +from ..utils import InvertedResidualV3 as InvertedResidual + + +@MODELS.register_module() +class MobileNetV3(BaseModule): + """MobileNetV3 backbone. + + This backbone is the improved implementation of `Searching for MobileNetV3 + `_. + + Args: + arch (str): Architecture of mobilnetv3, from {'small', 'large'}. + Default: 'small'. + conv_cfg (dict): Config dict for convolution layer. + Default: None, which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + out_indices (tuple[int]): Output from which layer. + Default: (0, 1, 12). + frozen_stages (int): Stages to be frozen (all param fixed). + Default: -1, which means not freezing any parameters. + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + with_cp (bool): Use checkpoint or not. Using checkpoint will save + some memory while slowing down the training speed. + Default: False. + pretrained (str, optional): model pretrained path. Default: None + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None + """ + # Parameters to build each block: + # [kernel size, mid channels, out channels, with_se, act type, stride] + arch_settings = { + 'small': [[3, 16, 16, True, 'ReLU', 2], # block0 layer1 os=4 + [3, 72, 24, False, 'ReLU', 2], # block1 layer2 os=8 + [3, 88, 24, False, 'ReLU', 1], + [5, 96, 40, True, 'HSwish', 2], # block2 layer4 os=16 + [5, 240, 40, True, 'HSwish', 1], + [5, 240, 40, True, 'HSwish', 1], + [5, 120, 48, True, 'HSwish', 1], # block3 layer7 os=16 + [5, 144, 48, True, 'HSwish', 1], + [5, 288, 96, True, 'HSwish', 2], # block4 layer9 os=32 + [5, 576, 96, True, 'HSwish', 1], + [5, 576, 96, True, 'HSwish', 1]], + 'large': [[3, 16, 16, False, 'ReLU', 1], # block0 layer1 os=2 + [3, 64, 24, False, 'ReLU', 2], # block1 layer2 os=4 + [3, 72, 24, False, 'ReLU', 1], + [5, 72, 40, True, 'ReLU', 2], # block2 layer4 os=8 + [5, 120, 40, True, 'ReLU', 1], + [5, 120, 40, True, 'ReLU', 1], + [3, 240, 80, False, 'HSwish', 2], # block3 layer7 os=16 + [3, 200, 80, False, 'HSwish', 1], + [3, 184, 80, False, 'HSwish', 1], + [3, 184, 80, False, 'HSwish', 1], + [3, 480, 112, True, 'HSwish', 1], # block4 layer11 os=16 + [3, 672, 112, True, 'HSwish', 1], + [5, 672, 160, True, 'HSwish', 2], # block5 layer13 os=32 + [5, 960, 160, True, 'HSwish', 1], + [5, 960, 160, True, 'HSwish', 1]] + } # yapf: disable + + def __init__(self, + arch='small', + conv_cfg=None, + norm_cfg=dict(type='BN'), + out_indices=(0, 1, 12), + frozen_stages=-1, + reduction_factor=1, + norm_eval=False, + with_cp=False, + pretrained=None, + init_cfg=None): + super().__init__(init_cfg) + + self.pretrained = pretrained + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be setting at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is a deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is None: + if init_cfg is None: + self.init_cfg = [ + dict(type='Kaiming', layer='Conv2d'), + dict( + type='Constant', + val=1, + layer=['_BatchNorm', 'GroupNorm']) + ] + else: + raise TypeError('pretrained must be a str or None') + + assert arch in self.arch_settings + assert isinstance(reduction_factor, int) and reduction_factor > 0 + assert is_tuple_of(out_indices, int) + for index in out_indices: + if index not in range(0, len(self.arch_settings[arch]) + 2): + raise ValueError( + 'the item in out_indices must in ' + f'range(0, {len(self.arch_settings[arch])+2}). ' + f'But received {index}') + + if frozen_stages not in range(-1, len(self.arch_settings[arch]) + 2): + raise ValueError('frozen_stages must be in range(-1, ' + f'{len(self.arch_settings[arch])+2}). ' + f'But received {frozen_stages}') + self.arch = arch + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.out_indices = out_indices + self.frozen_stages = frozen_stages + self.reduction_factor = reduction_factor + self.norm_eval = norm_eval + self.with_cp = with_cp + self.layers = self._make_layer() + + def _make_layer(self): + layers = [] + + # build the first layer (layer0) + in_channels = 16 + layer = ConvModule( + in_channels=3, + out_channels=in_channels, + kernel_size=3, + stride=2, + padding=1, + conv_cfg=dict(type='Conv2dAdaptivePadding'), + norm_cfg=self.norm_cfg, + act_cfg=dict(type='HSwish')) + self.add_module('layer0', layer) + layers.append('layer0') + + layer_setting = self.arch_settings[self.arch] + for i, params in enumerate(layer_setting): + (kernel_size, mid_channels, out_channels, with_se, act, + stride) = params + + if self.arch == 'large' and i >= 12 or self.arch == 'small' and \ + i >= 8: + mid_channels = mid_channels // self.reduction_factor + out_channels = out_channels // self.reduction_factor + + if with_se: + se_cfg = dict( + channels=mid_channels, + ratio=4, + act_cfg=(dict(type='ReLU'), + dict(type='HSigmoid', bias=3.0, divisor=6.0))) + else: + se_cfg = None + + layer = InvertedResidual( + in_channels=in_channels, + out_channels=out_channels, + mid_channels=mid_channels, + kernel_size=kernel_size, + stride=stride, + se_cfg=se_cfg, + with_expand_conv=(in_channels != mid_channels), + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=dict(type=act), + with_cp=self.with_cp) + in_channels = out_channels + layer_name = f'layer{i + 1}' + self.add_module(layer_name, layer) + layers.append(layer_name) + + # build the last layer + # block5 layer12 os=32 for small model + # block6 layer16 os=32 for large model + layer = ConvModule( + in_channels=in_channels, + out_channels=576 if self.arch == 'small' else 960, + kernel_size=1, + stride=1, + dilation=4, + padding=0, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=dict(type='HSwish')) + layer_name = f'layer{len(layer_setting) + 1}' + self.add_module(layer_name, layer) + layers.append(layer_name) + + # next, convert backbone MobileNetV3 to a semantic segmentation version + if self.arch == 'small': + self.layer4.depthwise_conv.conv.stride = (1, 1) + self.layer9.depthwise_conv.conv.stride = (1, 1) + for i in range(4, len(layers)): + layer = getattr(self, layers[i]) + if isinstance(layer, InvertedResidual): + modified_module = layer.depthwise_conv.conv + else: + modified_module = layer.conv + + if i < 9: + modified_module.dilation = (2, 2) + pad = 2 + else: + modified_module.dilation = (4, 4) + pad = 4 + + if not isinstance(modified_module, Conv2dAdaptivePadding): + # Adjust padding + pad *= (modified_module.kernel_size[0] - 1) // 2 + modified_module.padding = (pad, pad) + else: + self.layer7.depthwise_conv.conv.stride = (1, 1) + self.layer13.depthwise_conv.conv.stride = (1, 1) + for i in range(7, len(layers)): + layer = getattr(self, layers[i]) + if isinstance(layer, InvertedResidual): + modified_module = layer.depthwise_conv.conv + else: + modified_module = layer.conv + + if i < 13: + modified_module.dilation = (2, 2) + pad = 2 + else: + modified_module.dilation = (4, 4) + pad = 4 + + if not isinstance(modified_module, Conv2dAdaptivePadding): + # Adjust padding + pad *= (modified_module.kernel_size[0] - 1) // 2 + modified_module.padding = (pad, pad) + + return layers + + def forward(self, x): + outs = [] + for i, layer_name in enumerate(self.layers): + layer = getattr(self, layer_name) + x = layer(x) + if i in self.out_indices: + outs.append(x) + return outs + + def _freeze_stages(self): + for i in range(self.frozen_stages + 1): + layer = getattr(self, f'layer{i}') + layer.eval() + for param in layer.parameters(): + param.requires_grad = False + + def train(self, mode=True): + super().train(mode) + self._freeze_stages() + if mode and self.norm_eval: + for m in self.modules(): + if isinstance(m, _BatchNorm): + m.eval() diff --git a/third-party/InterFormer/mmseg/models/backbones/mscan.py b/third-party/InterFormer/mmseg/models/backbones/mscan.py new file mode 100644 index 0000000000000000000000000000000000000000..7150cb7a1c13d11dcdcc6fbbc72931154853929e --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/mscan.py @@ -0,0 +1,467 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Originally from https://github.com/visual-attention-network/segnext +# Licensed under the Apache License, Version 2.0 (the "License") +import math +import warnings + +import torch +import torch.nn as nn +from mmcv.cnn import build_activation_layer, build_norm_layer +from mmcv.cnn.bricks import DropPath +from mmengine.model import BaseModule +from mmengine.model.weight_init import (constant_init, normal_init, + trunc_normal_init) + +from mmseg.registry import MODELS + + +class Mlp(BaseModule): + """Multi Layer Perceptron (MLP) Module. + + Args: + in_features (int): The dimension of input features. + hidden_features (int): The dimension of hidden features. + Defaults: None. + out_features (int): The dimension of output features. + Defaults: None. + act_cfg (dict): Config dict for activation layer in block. + Default: dict(type='GELU'). + drop (float): The number of dropout rate in MLP block. + Defaults: 0.0. + """ + + def __init__(self, + in_features, + hidden_features=None, + out_features=None, + act_cfg=dict(type='GELU'), + drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Conv2d(in_features, hidden_features, 1) + self.dwconv = nn.Conv2d( + hidden_features, + hidden_features, + 3, + 1, + 1, + bias=True, + groups=hidden_features) + self.act = build_activation_layer(act_cfg) + self.fc2 = nn.Conv2d(hidden_features, out_features, 1) + self.drop = nn.Dropout(drop) + + def forward(self, x): + """Forward function.""" + + x = self.fc1(x) + + x = self.dwconv(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + + return x + + +class StemConv(BaseModule): + """Stem Block at the beginning of Semantic Branch. + + Args: + in_channels (int): The dimension of input channels. + out_channels (int): The dimension of output channels. + act_cfg (dict): Config dict for activation layer in block. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Defaults: dict(type='SyncBN', requires_grad=True). + """ + + def __init__(self, + in_channels, + out_channels, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='SyncBN', requires_grad=True)): + super().__init__() + + self.proj = nn.Sequential( + nn.Conv2d( + in_channels, + out_channels // 2, + kernel_size=(3, 3), + stride=(2, 2), + padding=(1, 1)), + build_norm_layer(norm_cfg, out_channels // 2)[1], + build_activation_layer(act_cfg), + nn.Conv2d( + out_channels // 2, + out_channels, + kernel_size=(3, 3), + stride=(2, 2), + padding=(1, 1)), + build_norm_layer(norm_cfg, out_channels)[1], + ) + + def forward(self, x): + """Forward function.""" + + x = self.proj(x) + _, _, H, W = x.size() + x = x.flatten(2).transpose(1, 2) + return x, H, W + + +class MSCAAttention(BaseModule): + """Attention Module in Multi-Scale Convolutional Attention Module (MSCA). + + Args: + channels (int): The dimension of channels. + kernel_sizes (list): The size of attention + kernel. Defaults: [5, [1, 7], [1, 11], [1, 21]]. + paddings (list): The number of + corresponding padding value in attention module. + Defaults: [2, [0, 3], [0, 5], [0, 10]]. + """ + + def __init__(self, + channels, + kernel_sizes=[5, [1, 7], [1, 11], [1, 21]], + paddings=[2, [0, 3], [0, 5], [0, 10]]): + super().__init__() + self.conv0 = nn.Conv2d( + channels, + channels, + kernel_size=kernel_sizes[0], + padding=paddings[0], + groups=channels) + for i, (kernel_size, + padding) in enumerate(zip(kernel_sizes[1:], paddings[1:])): + kernel_size_ = [kernel_size, kernel_size[::-1]] + padding_ = [padding, padding[::-1]] + conv_name = [f'conv{i}_1', f'conv{i}_2'] + for i_kernel, i_pad, i_conv in zip(kernel_size_, padding_, + conv_name): + self.add_module( + i_conv, + nn.Conv2d( + channels, + channels, + tuple(i_kernel), + padding=i_pad, + groups=channels)) + self.conv3 = nn.Conv2d(channels, channels, 1) + + def forward(self, x): + """Forward function.""" + + u = x.clone() + + attn = self.conv0(x) + + # Multi-Scale Feature extraction + attn_0 = self.conv0_1(attn) + attn_0 = self.conv0_2(attn_0) + + attn_1 = self.conv1_1(attn) + attn_1 = self.conv1_2(attn_1) + + attn_2 = self.conv2_1(attn) + attn_2 = self.conv2_2(attn_2) + + attn = attn + attn_0 + attn_1 + attn_2 + # Channel Mixing + attn = self.conv3(attn) + + # Convolutional Attention + x = attn * u + + return x + + +class MSCASpatialAttention(BaseModule): + """Spatial Attention Module in Multi-Scale Convolutional Attention Module + (MSCA). + + Args: + in_channels (int): The dimension of channels. + attention_kernel_sizes (list): The size of attention + kernel. Defaults: [5, [1, 7], [1, 11], [1, 21]]. + attention_kernel_paddings (list): The number of + corresponding padding value in attention module. + Defaults: [2, [0, 3], [0, 5], [0, 10]]. + act_cfg (dict): Config dict for activation layer in block. + Default: dict(type='GELU'). + """ + + def __init__(self, + in_channels, + attention_kernel_sizes=[5, [1, 7], [1, 11], [1, 21]], + attention_kernel_paddings=[2, [0, 3], [0, 5], [0, 10]], + act_cfg=dict(type='GELU')): + super().__init__() + self.proj_1 = nn.Conv2d(in_channels, in_channels, 1) + self.activation = build_activation_layer(act_cfg) + self.spatial_gating_unit = MSCAAttention(in_channels, + attention_kernel_sizes, + attention_kernel_paddings) + self.proj_2 = nn.Conv2d(in_channels, in_channels, 1) + + def forward(self, x): + """Forward function.""" + + shorcut = x.clone() + x = self.proj_1(x) + x = self.activation(x) + x = self.spatial_gating_unit(x) + x = self.proj_2(x) + x = x + shorcut + return x + + +class MSCABlock(BaseModule): + """Basic Multi-Scale Convolutional Attention Block. It leverage the large- + kernel attention (LKA) mechanism to build both channel and spatial + attention. In each branch, it uses two depth-wise strip convolutions to + approximate standard depth-wise convolutions with large kernels. The kernel + size for each branch is set to 7, 11, and 21, respectively. + + Args: + channels (int): The dimension of channels. + attention_kernel_sizes (list): The size of attention + kernel. Defaults: [5, [1, 7], [1, 11], [1, 21]]. + attention_kernel_paddings (list): The number of + corresponding padding value in attention module. + Defaults: [2, [0, 3], [0, 5], [0, 10]]. + mlp_ratio (float): The ratio of multiple input dimension to + calculate hidden feature in MLP layer. Defaults: 4.0. + drop (float): The number of dropout rate in MLP block. + Defaults: 0.0. + drop_path (float): The ratio of drop paths. + Defaults: 0.0. + act_cfg (dict): Config dict for activation layer in block. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Defaults: dict(type='SyncBN', requires_grad=True). + """ + + def __init__(self, + channels, + attention_kernel_sizes=[5, [1, 7], [1, 11], [1, 21]], + attention_kernel_paddings=[2, [0, 3], [0, 5], [0, 10]], + mlp_ratio=4., + drop=0., + drop_path=0., + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='SyncBN', requires_grad=True)): + super().__init__() + self.norm1 = build_norm_layer(norm_cfg, channels)[1] + self.attn = MSCASpatialAttention(channels, attention_kernel_sizes, + attention_kernel_paddings, act_cfg) + self.drop_path = DropPath( + drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = build_norm_layer(norm_cfg, channels)[1] + mlp_hidden_channels = int(channels * mlp_ratio) + self.mlp = Mlp( + in_features=channels, + hidden_features=mlp_hidden_channels, + act_cfg=act_cfg, + drop=drop) + layer_scale_init_value = 1e-2 + self.layer_scale_1 = nn.Parameter( + layer_scale_init_value * torch.ones(channels), requires_grad=True) + self.layer_scale_2 = nn.Parameter( + layer_scale_init_value * torch.ones(channels), requires_grad=True) + + def forward(self, x, H, W): + """Forward function.""" + + B, N, C = x.shape + x = x.permute(0, 2, 1).view(B, C, H, W) + x = x + self.drop_path( + self.layer_scale_1.unsqueeze(-1).unsqueeze(-1) * + self.attn(self.norm1(x))) + x = x + self.drop_path( + self.layer_scale_2.unsqueeze(-1).unsqueeze(-1) * + self.mlp(self.norm2(x))) + x = x.view(B, C, N).permute(0, 2, 1) + return x + + +class OverlapPatchEmbed(BaseModule): + """Image to Patch Embedding. + + Args: + patch_size (int): The patch size. + Defaults: 7. + stride (int): Stride of the convolutional layer. + Default: 4. + in_channels (int): The number of input channels. + Defaults: 3. + embed_dims (int): The dimensions of embedding. + Defaults: 768. + norm_cfg (dict): Config dict for normalization layer. + Defaults: dict(type='SyncBN', requires_grad=True). + """ + + def __init__(self, + patch_size=7, + stride=4, + in_channels=3, + embed_dim=768, + norm_cfg=dict(type='SyncBN', requires_grad=True)): + super().__init__() + + self.proj = nn.Conv2d( + in_channels, + embed_dim, + kernel_size=patch_size, + stride=stride, + padding=patch_size // 2) + self.norm = build_norm_layer(norm_cfg, embed_dim)[1] + + def forward(self, x): + """Forward function.""" + + x = self.proj(x) + _, _, H, W = x.shape + x = self.norm(x) + + x = x.flatten(2).transpose(1, 2) + + return x, H, W + + +@MODELS.register_module() +class MSCAN(BaseModule): + """SegNeXt Multi-Scale Convolutional Attention Network (MCSAN) backbone. + + This backbone is the implementation of `SegNeXt: Rethinking + Convolutional Attention Design for Semantic + Segmentation `_. + Inspiration from https://github.com/visual-attention-network/segnext. + + Args: + in_channels (int): The number of input channels. Defaults: 3. + embed_dims (list[int]): Embedding dimension. + Defaults: [64, 128, 256, 512]. + mlp_ratios (list[int]): Ratio of mlp hidden dim to embedding dim. + Defaults: [4, 4, 4, 4]. + drop_rate (float): Dropout rate. Defaults: 0. + drop_path_rate (float): Stochastic depth rate. Defaults: 0. + depths (list[int]): Depths of each Swin Transformer stage. + Default: [3, 4, 6, 3]. + num_stages (int): MSCAN stages. Default: 4. + attention_kernel_sizes (list): Size of attention kernel in + Attention Module (Figure 2(b) of original paper). + Defaults: [5, [1, 7], [1, 11], [1, 21]]. + attention_kernel_paddings (list): Size of attention paddings + in Attention Module (Figure 2(b) of original paper). + Defaults: [2, [0, 3], [0, 5], [0, 10]]. + norm_cfg (dict): Config of norm layers. + Defaults: dict(type='SyncBN', requires_grad=True). + pretrained (str, optional): model pretrained path. + Default: None. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels=3, + embed_dims=[64, 128, 256, 512], + mlp_ratios=[4, 4, 4, 4], + drop_rate=0., + drop_path_rate=0., + depths=[3, 4, 6, 3], + num_stages=4, + attention_kernel_sizes=[5, [1, 7], [1, 11], [1, 21]], + attention_kernel_paddings=[2, [0, 3], [0, 5], [0, 10]], + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='SyncBN', requires_grad=True), + pretrained=None, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be set at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is not None: + raise TypeError('pretrained must be a str or None') + + self.depths = depths + self.num_stages = num_stages + + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) + ] # stochastic depth decay rule + cur = 0 + + for i in range(num_stages): + if i == 0: + patch_embed = StemConv(3, embed_dims[0], norm_cfg=norm_cfg) + else: + patch_embed = OverlapPatchEmbed( + patch_size=7 if i == 0 else 3, + stride=4 if i == 0 else 2, + in_channels=in_channels if i == 0 else embed_dims[i - 1], + embed_dim=embed_dims[i], + norm_cfg=norm_cfg) + + block = nn.ModuleList([ + MSCABlock( + channels=embed_dims[i], + attention_kernel_sizes=attention_kernel_sizes, + attention_kernel_paddings=attention_kernel_paddings, + mlp_ratio=mlp_ratios[i], + drop=drop_rate, + drop_path=dpr[cur + j], + act_cfg=act_cfg, + norm_cfg=norm_cfg) for j in range(depths[i]) + ]) + norm = nn.LayerNorm(embed_dims[i]) + cur += depths[i] + + setattr(self, f'patch_embed{i + 1}', patch_embed) + setattr(self, f'block{i + 1}', block) + setattr(self, f'norm{i + 1}', norm) + + def init_weights(self): + """Initialize modules of MSCAN.""" + + print('init cfg', self.init_cfg) + if self.init_cfg is None: + for m in self.modules(): + if isinstance(m, nn.Linear): + trunc_normal_init(m, std=.02, bias=0.) + elif isinstance(m, nn.LayerNorm): + constant_init(m, val=1.0, bias=0.) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[ + 1] * m.out_channels + fan_out //= m.groups + normal_init( + m, mean=0, std=math.sqrt(2.0 / fan_out), bias=0) + else: + super().init_weights() + + def forward(self, x): + """Forward function.""" + + B = x.shape[0] + outs = [] + + for i in range(self.num_stages): + patch_embed = getattr(self, f'patch_embed{i + 1}') + block = getattr(self, f'block{i + 1}') + norm = getattr(self, f'norm{i + 1}') + x, H, W = patch_embed(x) + for blk in block: + x = blk(x, H, W) + x = norm(x) + x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() + outs.append(x) + + return outs diff --git a/third-party/InterFormer/mmseg/models/backbones/pidnet.py b/third-party/InterFormer/mmseg/models/backbones/pidnet.py new file mode 100644 index 0000000000000000000000000000000000000000..0b711a373701c0771c5c5997bbb8e5b345d70924 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/pidnet.py @@ -0,0 +1,522 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule +from mmengine.runner import CheckpointLoader +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import OptConfigType +from ..utils import DAPPM, PAPPM, BasicBlock, Bottleneck + + +class PagFM(BaseModule): + """Pixel-attention-guided fusion module. + + Args: + in_channels (int): The number of input channels. + channels (int): The number of channels. + after_relu (bool): Whether to use ReLU before attention. + Default: False. + with_channel (bool): Whether to use channel attention. + Default: False. + upsample_mode (str): The mode of upsample. Default: 'bilinear'. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(typ='ReLU', inplace=True). + init_cfg (dict): Config dict for initialization. Default: None. + """ + + def __init__(self, + in_channels: int, + channels: int, + after_relu: bool = False, + with_channel: bool = False, + upsample_mode: str = 'bilinear', + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(typ='ReLU', inplace=True), + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + self.after_relu = after_relu + self.with_channel = with_channel + self.upsample_mode = upsample_mode + self.f_i = ConvModule( + in_channels, channels, 1, norm_cfg=norm_cfg, act_cfg=None) + self.f_p = ConvModule( + in_channels, channels, 1, norm_cfg=norm_cfg, act_cfg=None) + if with_channel: + self.up = ConvModule( + channels, in_channels, 1, norm_cfg=norm_cfg, act_cfg=None) + if after_relu: + self.relu = MODELS.build(act_cfg) + + def forward(self, x_p: Tensor, x_i: Tensor) -> Tensor: + """Forward function. + + Args: + x_p (Tensor): The featrue map from P branch. + x_i (Tensor): The featrue map from I branch. + + Returns: + Tensor: The feature map with pixel-attention-guided fusion. + """ + if self.after_relu: + x_p = self.relu(x_p) + x_i = self.relu(x_i) + + f_i = self.f_i(x_i) + f_i = F.interpolate( + f_i, + size=x_p.shape[2:], + mode=self.upsample_mode, + align_corners=False) + + f_p = self.f_p(x_p) + + if self.with_channel: + sigma = torch.sigmoid(self.up(f_p * f_i)) + else: + sigma = torch.sigmoid(torch.sum(f_p * f_i, dim=1).unsqueeze(1)) + + x_i = F.interpolate( + x_i, + size=x_p.shape[2:], + mode=self.upsample_mode, + align_corners=False) + + out = sigma * x_i + (1 - sigma) * x_p + return out + + +class Bag(BaseModule): + """Boundary-attention-guided fusion module. + + Args: + in_channels (int): The number of input channels. + out_channels (int): The number of output channels. + kernel_size (int): The kernel size of the convolution. Default: 3. + padding (int): The padding of the convolution. Default: 1. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + conv_cfg (dict): Config dict for convolution layer. + Default: dict(order=('norm', 'act', 'conv')). + init_cfg (dict): Config dict for initialization. Default: None. + """ + + def __init__(self, + in_channels: int, + out_channels: int, + kernel_size: int = 3, + padding: int = 1, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + conv_cfg: OptConfigType = dict(order=('norm', 'act', 'conv')), + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + + self.conv = ConvModule( + in_channels, + out_channels, + kernel_size, + padding=padding, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + + def forward(self, x_p: Tensor, x_i: Tensor, x_d: Tensor) -> Tensor: + """Forward function. + + Args: + x_p (Tensor): The featrue map from P branch. + x_i (Tensor): The featrue map from I branch. + x_d (Tensor): The featrue map from D branch. + + Returns: + Tensor: The feature map with boundary-attention-guided fusion. + """ + sigma = torch.sigmoid(x_d) + return self.conv(sigma * x_p + (1 - sigma) * x_i) + + +class LightBag(BaseModule): + """Light Boundary-attention-guided fusion module. + + Args: + in_channels (int): The number of input channels. + out_channels (int): The number of output channels. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. Default: None. + init_cfg (dict): Config dict for initialization. Default: None. + """ + + def __init__(self, + in_channels: int, + out_channels: int, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = None, + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + self.f_p = ConvModule( + in_channels, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.f_i = ConvModule( + in_channels, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, x_p: Tensor, x_i: Tensor, x_d: Tensor) -> Tensor: + """Forward function. + Args: + x_p (Tensor): The featrue map from P branch. + x_i (Tensor): The featrue map from I branch. + x_d (Tensor): The featrue map from D branch. + + Returns: + Tensor: The feature map with light boundary-attention-guided + fusion. + """ + sigma = torch.sigmoid(x_d) + + f_p = self.f_p((1 - sigma) * x_i + x_p) + f_i = self.f_i(x_i + sigma * x_p) + + return f_p + f_i + + +@MODELS.register_module() +class PIDNet(BaseModule): + """PIDNet backbone. + + This backbone is the implementation of `PIDNet: A Real-time Semantic + Segmentation Network Inspired from PID Controller + `_. + Modified from https://github.com/XuJiacong/PIDNet. + + Licensed under the MIT License. + + Args: + in_channels (int): The number of input channels. Default: 3. + channels (int): The number of channels in the stem layer. Default: 64. + ppm_channels (int): The number of channels in the PPM layer. + Default: 96. + num_stem_blocks (int): The number of blocks in the stem layer. + Default: 2. + num_branch_blocks (int): The number of blocks in the branch layer. + Default: 3. + align_corners (bool): The align_corners argument of F.interpolate. + Default: False. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + init_cfg (dict): Config dict for initialization. Default: None. + """ + + def __init__(self, + in_channels: int = 3, + channels: int = 64, + ppm_channels: int = 96, + num_stem_blocks: int = 2, + num_branch_blocks: int = 3, + align_corners: bool = False, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + init_cfg: OptConfigType = None, + **kwargs): + super().__init__(init_cfg) + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.align_corners = align_corners + + # stem layer + self.stem = self._make_stem_layer(in_channels, channels, + num_stem_blocks) + self.relu = nn.ReLU() + + # I Branch + self.i_branch_layers = nn.ModuleList() + for i in range(3): + self.i_branch_layers.append( + self._make_layer( + block=BasicBlock if i < 2 else Bottleneck, + in_channels=channels * 2**(i + 1), + channels=channels * 8 if i > 0 else channels * 4, + num_blocks=num_branch_blocks if i < 2 else 2, + stride=2)) + + # P Branch + self.p_branch_layers = nn.ModuleList() + for i in range(3): + self.p_branch_layers.append( + self._make_layer( + block=BasicBlock if i < 2 else Bottleneck, + in_channels=channels * 2, + channels=channels * 2, + num_blocks=num_stem_blocks if i < 2 else 1)) + self.compression_1 = ConvModule( + channels * 4, + channels * 2, + kernel_size=1, + bias=False, + norm_cfg=norm_cfg, + act_cfg=None) + self.compression_2 = ConvModule( + channels * 8, + channels * 2, + kernel_size=1, + bias=False, + norm_cfg=norm_cfg, + act_cfg=None) + self.pag_1 = PagFM(channels * 2, channels) + self.pag_2 = PagFM(channels * 2, channels) + + # D Branch + if num_stem_blocks == 2: + self.d_branch_layers = nn.ModuleList([ + self._make_single_layer(BasicBlock, channels * 2, channels), + self._make_layer(Bottleneck, channels, channels, 1) + ]) + channel_expand = 1 + spp_module = PAPPM + dfm_module = LightBag + act_cfg_dfm = None + else: + self.d_branch_layers = nn.ModuleList([ + self._make_single_layer(BasicBlock, channels * 2, + channels * 2), + self._make_single_layer(BasicBlock, channels * 2, channels * 2) + ]) + channel_expand = 2 + spp_module = DAPPM + dfm_module = Bag + act_cfg_dfm = act_cfg + + self.diff_1 = ConvModule( + channels * 4, + channels * channel_expand, + kernel_size=3, + padding=1, + bias=False, + norm_cfg=norm_cfg, + act_cfg=None) + self.diff_2 = ConvModule( + channels * 8, + channels * 2, + kernel_size=3, + padding=1, + bias=False, + norm_cfg=norm_cfg, + act_cfg=None) + + self.spp = spp_module( + channels * 16, ppm_channels, channels * 4, num_scales=5) + self.dfm = dfm_module( + channels * 4, channels * 4, norm_cfg=norm_cfg, act_cfg=act_cfg_dfm) + + self.d_branch_layers.append( + self._make_layer(Bottleneck, channels * 2, channels * 2, 1)) + + def _make_stem_layer(self, in_channels: int, channels: int, + num_blocks: int) -> nn.Sequential: + """Make stem layer. + + Args: + in_channels (int): Number of input channels. + channels (int): Number of output channels. + num_blocks (int): Number of blocks. + + Returns: + nn.Sequential: The stem layer. + """ + + layers = [ + ConvModule( + in_channels, + channels, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + ConvModule( + channels, + channels, + kernel_size=3, + stride=2, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + ] + + layers.append( + self._make_layer(BasicBlock, channels, channels, num_blocks)) + layers.append(nn.ReLU()) + layers.append( + self._make_layer( + BasicBlock, channels, channels * 2, num_blocks, stride=2)) + layers.append(nn.ReLU()) + + return nn.Sequential(*layers) + + def _make_layer(self, + block: BasicBlock, + in_channels: int, + channels: int, + num_blocks: int, + stride: int = 1) -> nn.Sequential: + """Make layer for PIDNet backbone. + Args: + block (BasicBlock): Basic block. + in_channels (int): Number of input channels. + channels (int): Number of output channels. + num_blocks (int): Number of blocks. + stride (int): Stride of the first block. Default: 1. + + Returns: + nn.Sequential: The Branch Layer. + """ + downsample = None + if stride != 1 or in_channels != channels * block.expansion: + downsample = ConvModule( + in_channels, + channels * block.expansion, + kernel_size=1, + stride=stride, + norm_cfg=self.norm_cfg, + act_cfg=None) + + layers = [block(in_channels, channels, stride, downsample)] + in_channels = channels * block.expansion + for i in range(1, num_blocks): + layers.append( + block( + in_channels, + channels, + stride=1, + act_cfg_out=None if i == num_blocks - 1 else self.act_cfg)) + return nn.Sequential(*layers) + + def _make_single_layer(self, + block: Union[BasicBlock, Bottleneck], + in_channels: int, + channels: int, + stride: int = 1) -> nn.Module: + """Make single layer for PIDNet backbone. + Args: + block (BasicBlock or Bottleneck): Basic block or Bottleneck. + in_channels (int): Number of input channels. + channels (int): Number of output channels. + stride (int): Stride of the first block. Default: 1. + + Returns: + nn.Module + """ + + downsample = None + if stride != 1 or in_channels != channels * block.expansion: + downsample = ConvModule( + in_channels, + channels * block.expansion, + kernel_size=1, + stride=stride, + norm_cfg=self.norm_cfg, + act_cfg=None) + return block( + in_channels, channels, stride, downsample, act_cfg_out=None) + + def init_weights(self): + """Initialize the weights in backbone. + + Since the D branch is not initialized by the pre-trained model, we + initialize it with the same method as the ResNet. + """ + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu') + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + if self.init_cfg is not None: + assert 'checkpoint' in self.init_cfg, f'Only support ' \ + f'specify `Pretrained` in ' \ + f'`init_cfg` in ' \ + f'{self.__class__.__name__} ' + ckpt = CheckpointLoader.load_checkpoint( + self.init_cfg['checkpoint'], map_location='cpu') + self.load_state_dict(ckpt, strict=False) + + def forward(self, x: Tensor) -> Union[Tensor, Tuple[Tensor]]: + """Forward function. + + Args: + x (Tensor): Input tensor with shape (B, C, H, W). + + Returns: + Tensor or tuple[Tensor]: If self.training is True, return + tuple[Tensor], else return Tensor. + """ + w_out = x.shape[-1] // 8 + h_out = x.shape[-2] // 8 + + # stage 0-2 + x = self.stem(x) + + # stage 3 + x_i = self.relu(self.i_branch_layers[0](x)) + x_p = self.p_branch_layers[0](x) + x_d = self.d_branch_layers[0](x) + + comp_i = self.compression_1(x_i) + x_p = self.pag_1(x_p, comp_i) + diff_i = self.diff_1(x_i) + x_d += F.interpolate( + diff_i, + size=[h_out, w_out], + mode='bilinear', + align_corners=self.align_corners) + if self.training: + temp_p = x_p.clone() + + # stage 4 + x_i = self.relu(self.i_branch_layers[1](x_i)) + x_p = self.p_branch_layers[1](self.relu(x_p)) + x_d = self.d_branch_layers[1](self.relu(x_d)) + + comp_i = self.compression_2(x_i) + x_p = self.pag_2(x_p, comp_i) + diff_i = self.diff_2(x_i) + x_d += F.interpolate( + diff_i, + size=[h_out, w_out], + mode='bilinear', + align_corners=self.align_corners) + if self.training: + temp_d = x_d.clone() + + # stage 5 + x_i = self.i_branch_layers[2](x_i) + x_p = self.p_branch_layers[2](self.relu(x_p)) + x_d = self.d_branch_layers[2](self.relu(x_d)) + + x_i = self.spp(x_i) + x_i = F.interpolate( + x_i, + size=[h_out, w_out], + mode='bilinear', + align_corners=self.align_corners) + out = self.dfm(x_p, x_i, x_d) + return (temp_p, out, temp_d) if self.training else out diff --git a/third-party/InterFormer/mmseg/models/backbones/resnest.py b/third-party/InterFormer/mmseg/models/backbones/resnest.py new file mode 100644 index 0000000000000000000000000000000000000000..3cc380b4460915f476ffc1febcfc145a94fc7c7a --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/resnest.py @@ -0,0 +1,318 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as cp +from mmcv.cnn import build_conv_layer, build_norm_layer + +from mmseg.registry import MODELS +from ..utils import ResLayer +from .resnet import Bottleneck as _Bottleneck +from .resnet import ResNetV1d + + +class RSoftmax(nn.Module): + """Radix Softmax module in ``SplitAttentionConv2d``. + + Args: + radix (int): Radix of input. + groups (int): Groups of input. + """ + + def __init__(self, radix, groups): + super().__init__() + self.radix = radix + self.groups = groups + + def forward(self, x): + batch = x.size(0) + if self.radix > 1: + x = x.view(batch, self.groups, self.radix, -1).transpose(1, 2) + x = F.softmax(x, dim=1) + x = x.reshape(batch, -1) + else: + x = torch.sigmoid(x) + return x + + +class SplitAttentionConv2d(nn.Module): + """Split-Attention Conv2d in ResNeSt. + + Args: + in_channels (int): Same as nn.Conv2d. + out_channels (int): Same as nn.Conv2d. + kernel_size (int | tuple[int]): Same as nn.Conv2d. + stride (int | tuple[int]): Same as nn.Conv2d. + padding (int | tuple[int]): Same as nn.Conv2d. + dilation (int | tuple[int]): Same as nn.Conv2d. + groups (int): Same as nn.Conv2d. + radix (int): Radix of SpltAtConv2d. Default: 2 + reduction_factor (int): Reduction factor of inter_channels. Default: 4. + conv_cfg (dict): Config dict for convolution layer. Default: None, + which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. Default: None. + dcn (dict): Config dict for DCN. Default: None. + """ + + def __init__(self, + in_channels, + channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + radix=2, + reduction_factor=4, + conv_cfg=None, + norm_cfg=dict(type='BN'), + dcn=None): + super().__init__() + inter_channels = max(in_channels * radix // reduction_factor, 32) + self.radix = radix + self.groups = groups + self.channels = channels + self.with_dcn = dcn is not None + self.dcn = dcn + fallback_on_stride = False + if self.with_dcn: + fallback_on_stride = self.dcn.pop('fallback_on_stride', False) + if self.with_dcn and not fallback_on_stride: + assert conv_cfg is None, 'conv_cfg must be None for DCN' + conv_cfg = dcn + self.conv = build_conv_layer( + conv_cfg, + in_channels, + channels * radix, + kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups * radix, + bias=False) + self.norm0_name, norm0 = build_norm_layer( + norm_cfg, channels * radix, postfix=0) + self.add_module(self.norm0_name, norm0) + self.relu = nn.ReLU(inplace=True) + self.fc1 = build_conv_layer( + None, channels, inter_channels, 1, groups=self.groups) + self.norm1_name, norm1 = build_norm_layer( + norm_cfg, inter_channels, postfix=1) + self.add_module(self.norm1_name, norm1) + self.fc2 = build_conv_layer( + None, inter_channels, channels * radix, 1, groups=self.groups) + self.rsoftmax = RSoftmax(radix, groups) + + @property + def norm0(self): + """nn.Module: the normalization layer named "norm0" """ + return getattr(self, self.norm0_name) + + @property + def norm1(self): + """nn.Module: the normalization layer named "norm1" """ + return getattr(self, self.norm1_name) + + def forward(self, x): + x = self.conv(x) + x = self.norm0(x) + x = self.relu(x) + + batch, rchannel = x.shape[:2] + batch = x.size(0) + if self.radix > 1: + splits = x.view(batch, self.radix, -1, *x.shape[2:]) + gap = splits.sum(dim=1) + else: + gap = x + gap = F.adaptive_avg_pool2d(gap, 1) + gap = self.fc1(gap) + + gap = self.norm1(gap) + gap = self.relu(gap) + + atten = self.fc2(gap) + atten = self.rsoftmax(atten).view(batch, -1, 1, 1) + + if self.radix > 1: + attens = atten.view(batch, self.radix, -1, *atten.shape[2:]) + out = torch.sum(attens * splits, dim=1) + else: + out = atten * x + return out.contiguous() + + +class Bottleneck(_Bottleneck): + """Bottleneck block for ResNeSt. + + Args: + inplane (int): Input planes of this block. + planes (int): Middle planes of this block. + groups (int): Groups of conv2. + width_per_group (int): Width per group of conv2. 64x4d indicates + ``groups=64, width_per_group=4`` and 32x8d indicates + ``groups=32, width_per_group=8``. + radix (int): Radix of SpltAtConv2d. Default: 2 + reduction_factor (int): Reduction factor of inter_channels in + SplitAttentionConv2d. Default: 4. + avg_down_stride (bool): Whether to use average pool for stride in + Bottleneck. Default: True. + kwargs (dict): Key word arguments for base class. + """ + expansion = 4 + + def __init__(self, + inplanes, + planes, + groups=1, + base_width=4, + base_channels=64, + radix=2, + reduction_factor=4, + avg_down_stride=True, + **kwargs): + """Bottleneck block for ResNeSt.""" + super().__init__(inplanes, planes, **kwargs) + + if groups == 1: + width = self.planes + else: + width = math.floor(self.planes * + (base_width / base_channels)) * groups + + self.avg_down_stride = avg_down_stride and self.conv2_stride > 1 + + self.norm1_name, norm1 = build_norm_layer( + self.norm_cfg, width, postfix=1) + self.norm3_name, norm3 = build_norm_layer( + self.norm_cfg, self.planes * self.expansion, postfix=3) + + self.conv1 = build_conv_layer( + self.conv_cfg, + self.inplanes, + width, + kernel_size=1, + stride=self.conv1_stride, + bias=False) + self.add_module(self.norm1_name, norm1) + self.with_modulated_dcn = False + self.conv2 = SplitAttentionConv2d( + width, + width, + kernel_size=3, + stride=1 if self.avg_down_stride else self.conv2_stride, + padding=self.dilation, + dilation=self.dilation, + groups=groups, + radix=radix, + reduction_factor=reduction_factor, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + dcn=self.dcn) + delattr(self, self.norm2_name) + + if self.avg_down_stride: + self.avd_layer = nn.AvgPool2d(3, self.conv2_stride, padding=1) + + self.conv3 = build_conv_layer( + self.conv_cfg, + width, + self.planes * self.expansion, + kernel_size=1, + bias=False) + self.add_module(self.norm3_name, norm3) + + def forward(self, x): + + def _inner_forward(x): + identity = x + + out = self.conv1(x) + out = self.norm1(out) + out = self.relu(out) + + if self.with_plugins: + out = self.forward_plugin(out, self.after_conv1_plugin_names) + + out = self.conv2(out) + + if self.avg_down_stride: + out = self.avd_layer(out) + + if self.with_plugins: + out = self.forward_plugin(out, self.after_conv2_plugin_names) + + out = self.conv3(out) + out = self.norm3(out) + + if self.with_plugins: + out = self.forward_plugin(out, self.after_conv3_plugin_names) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + + return out + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + out = self.relu(out) + + return out + + +@MODELS.register_module() +class ResNeSt(ResNetV1d): + """ResNeSt backbone. + + This backbone is the implementation of `ResNeSt: + Split-Attention Networks `_. + + Args: + groups (int): Number of groups of Bottleneck. Default: 1 + base_width (int): Base width of Bottleneck. Default: 4 + radix (int): Radix of SpltAtConv2d. Default: 2 + reduction_factor (int): Reduction factor of inter_channels in + SplitAttentionConv2d. Default: 4. + avg_down_stride (bool): Whether to use average pool for stride in + Bottleneck. Default: True. + kwargs (dict): Keyword arguments for ResNet. + """ + + arch_settings = { + 50: (Bottleneck, (3, 4, 6, 3)), + 101: (Bottleneck, (3, 4, 23, 3)), + 152: (Bottleneck, (3, 8, 36, 3)), + 200: (Bottleneck, (3, 24, 36, 3)) + } + + def __init__(self, + groups=1, + base_width=4, + radix=2, + reduction_factor=4, + avg_down_stride=True, + **kwargs): + self.groups = groups + self.base_width = base_width + self.radix = radix + self.reduction_factor = reduction_factor + self.avg_down_stride = avg_down_stride + super().__init__(**kwargs) + + def make_res_layer(self, **kwargs): + """Pack all blocks in a stage into a ``ResLayer``.""" + return ResLayer( + groups=self.groups, + base_width=self.base_width, + base_channels=self.base_channels, + radix=self.radix, + reduction_factor=self.reduction_factor, + avg_down_stride=self.avg_down_stride, + **kwargs) diff --git a/third-party/InterFormer/mmseg/models/backbones/resnet.py b/third-party/InterFormer/mmseg/models/backbones/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..9226c90d85c938e76f322e58643ee9d7b17ba27b --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/resnet.py @@ -0,0 +1,712 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch.nn as nn +import torch.utils.checkpoint as cp +from mmcv.cnn import build_conv_layer, build_norm_layer, build_plugin_layer +from mmengine.model import BaseModule +from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm + +from mmseg.registry import MODELS +from ..utils import ResLayer + + +class BasicBlock(BaseModule): + """Basic block for ResNet.""" + + expansion = 1 + + def __init__(self, + inplanes, + planes, + stride=1, + dilation=1, + downsample=None, + style='pytorch', + with_cp=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + dcn=None, + plugins=None, + init_cfg=None): + super().__init__(init_cfg) + assert dcn is None, 'Not implemented yet.' + assert plugins is None, 'Not implemented yet.' + + self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1) + self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2) + + self.conv1 = build_conv_layer( + conv_cfg, + inplanes, + planes, + 3, + stride=stride, + padding=dilation, + dilation=dilation, + bias=False) + self.add_module(self.norm1_name, norm1) + self.conv2 = build_conv_layer( + conv_cfg, planes, planes, 3, padding=1, bias=False) + self.add_module(self.norm2_name, norm2) + + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + self.dilation = dilation + self.with_cp = with_cp + + @property + def norm1(self): + """nn.Module: normalization layer after the first convolution layer""" + return getattr(self, self.norm1_name) + + @property + def norm2(self): + """nn.Module: normalization layer after the second convolution layer""" + return getattr(self, self.norm2_name) + + def forward(self, x): + """Forward function.""" + + def _inner_forward(x): + identity = x + + out = self.conv1(x) + out = self.norm1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.norm2(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + + return out + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + out = self.relu(out) + + return out + + +class Bottleneck(BaseModule): + """Bottleneck block for ResNet. + + If style is "pytorch", the stride-two layer is the 3x3 conv layer, if it is + "caffe", the stride-two layer is the first 1x1 conv layer. + """ + + expansion = 4 + + def __init__(self, + inplanes, + planes, + stride=1, + dilation=1, + downsample=None, + style='pytorch', + with_cp=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + dcn=None, + plugins=None, + init_cfg=None): + super().__init__(init_cfg) + assert style in ['pytorch', 'caffe'] + assert dcn is None or isinstance(dcn, dict) + assert plugins is None or isinstance(plugins, list) + if plugins is not None: + allowed_position = ['after_conv1', 'after_conv2', 'after_conv3'] + assert all(p['position'] in allowed_position for p in plugins) + + self.inplanes = inplanes + self.planes = planes + self.stride = stride + self.dilation = dilation + self.style = style + self.with_cp = with_cp + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.dcn = dcn + self.with_dcn = dcn is not None + self.plugins = plugins + self.with_plugins = plugins is not None + + if self.with_plugins: + # collect plugins for conv1/conv2/conv3 + self.after_conv1_plugins = [ + plugin['cfg'] for plugin in plugins + if plugin['position'] == 'after_conv1' + ] + self.after_conv2_plugins = [ + plugin['cfg'] for plugin in plugins + if plugin['position'] == 'after_conv2' + ] + self.after_conv3_plugins = [ + plugin['cfg'] for plugin in plugins + if plugin['position'] == 'after_conv3' + ] + + if self.style == 'pytorch': + self.conv1_stride = 1 + self.conv2_stride = stride + else: + self.conv1_stride = stride + self.conv2_stride = 1 + + self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1) + self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2) + self.norm3_name, norm3 = build_norm_layer( + norm_cfg, planes * self.expansion, postfix=3) + + self.conv1 = build_conv_layer( + conv_cfg, + inplanes, + planes, + kernel_size=1, + stride=self.conv1_stride, + bias=False) + self.add_module(self.norm1_name, norm1) + fallback_on_stride = False + if self.with_dcn: + fallback_on_stride = dcn.pop('fallback_on_stride', False) + if not self.with_dcn or fallback_on_stride: + self.conv2 = build_conv_layer( + conv_cfg, + planes, + planes, + kernel_size=3, + stride=self.conv2_stride, + padding=dilation, + dilation=dilation, + bias=False) + else: + assert self.conv_cfg is None, 'conv_cfg must be None for DCN' + self.conv2 = build_conv_layer( + dcn, + planes, + planes, + kernel_size=3, + stride=self.conv2_stride, + padding=dilation, + dilation=dilation, + bias=False) + + self.add_module(self.norm2_name, norm2) + self.conv3 = build_conv_layer( + conv_cfg, + planes, + planes * self.expansion, + kernel_size=1, + bias=False) + self.add_module(self.norm3_name, norm3) + + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + + if self.with_plugins: + self.after_conv1_plugin_names = self.make_block_plugins( + planes, self.after_conv1_plugins) + self.after_conv2_plugin_names = self.make_block_plugins( + planes, self.after_conv2_plugins) + self.after_conv3_plugin_names = self.make_block_plugins( + planes * self.expansion, self.after_conv3_plugins) + + def make_block_plugins(self, in_channels, plugins): + """make plugins for block. + + Args: + in_channels (int): Input channels of plugin. + plugins (list[dict]): List of plugins cfg to build. + + Returns: + list[str]: List of the names of plugin. + """ + assert isinstance(plugins, list) + plugin_names = [] + for plugin in plugins: + plugin = plugin.copy() + name, layer = build_plugin_layer( + plugin, + in_channels=in_channels, + postfix=plugin.pop('postfix', '')) + assert not hasattr(self, name), f'duplicate plugin {name}' + self.add_module(name, layer) + plugin_names.append(name) + return plugin_names + + def forward_plugin(self, x, plugin_names): + """Forward function for plugins.""" + out = x + for name in plugin_names: + out = getattr(self, name)(x) + return out + + @property + def norm1(self): + """nn.Module: normalization layer after the first convolution layer""" + return getattr(self, self.norm1_name) + + @property + def norm2(self): + """nn.Module: normalization layer after the second convolution layer""" + return getattr(self, self.norm2_name) + + @property + def norm3(self): + """nn.Module: normalization layer after the third convolution layer""" + return getattr(self, self.norm3_name) + + def forward(self, x): + """Forward function.""" + + def _inner_forward(x): + identity = x + + out = self.conv1(x) + out = self.norm1(out) + out = self.relu(out) + + if self.with_plugins: + out = self.forward_plugin(out, self.after_conv1_plugin_names) + + out = self.conv2(out) + out = self.norm2(out) + out = self.relu(out) + + if self.with_plugins: + out = self.forward_plugin(out, self.after_conv2_plugin_names) + + out = self.conv3(out) + out = self.norm3(out) + + if self.with_plugins: + out = self.forward_plugin(out, self.after_conv3_plugin_names) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + + return out + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + out = self.relu(out) + + return out + + +@MODELS.register_module() +class ResNet(BaseModule): + """ResNet backbone. + + This backbone is the improved implementation of `Deep Residual Learning + for Image Recognition `_. + + Args: + depth (int): Depth of resnet, from {18, 34, 50, 101, 152}. + in_channels (int): Number of input image channels. Default: 3. + stem_channels (int): Number of stem channels. Default: 64. + base_channels (int): Number of base channels of res layer. Default: 64. + num_stages (int): Resnet stages, normally 4. Default: 4. + strides (Sequence[int]): Strides of the first block of each stage. + Default: (1, 2, 2, 2). + dilations (Sequence[int]): Dilation of each stage. + Default: (1, 1, 1, 1). + out_indices (Sequence[int]): Output from which stages. + Default: (0, 1, 2, 3). + style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two + layer is the 3x3 conv layer, otherwise the stride-two layer is + the first 1x1 conv layer. Default: 'pytorch'. + deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv. + Default: False. + avg_down (bool): Use AvgPool instead of stride conv when + downsampling in the bottleneck. Default: False. + frozen_stages (int): Stages to be frozen (stop grad and set eval mode). + -1 means not freezing any parameters. Default: -1. + conv_cfg (dict | None): Dictionary to construct and config conv layer. + When conv_cfg is None, cfg will be set to dict(type='Conv2d'). + Default: None. + norm_cfg (dict): Dictionary to construct and config norm layer. + Default: dict(type='BN', requires_grad=True). + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + dcn (dict | None): Dictionary to construct and config DCN conv layer. + When dcn is not None, conv_cfg must be None. Default: None. + stage_with_dcn (Sequence[bool]): Whether to set DCN conv for each + stage. The length of stage_with_dcn is equal to num_stages. + Default: (False, False, False, False). + plugins (list[dict]): List of plugins for stages, each dict contains: + + - cfg (dict, required): Cfg dict to build plugin. + + - position (str, required): Position inside block to insert plugin, + options: 'after_conv1', 'after_conv2', 'after_conv3'. + + - stages (tuple[bool], optional): Stages to apply plugin, length + should be same as 'num_stages'. + Default: None. + multi_grid (Sequence[int]|None): Multi grid dilation rates of last + stage. Default: None. + contract_dilation (bool): Whether contract first dilation of each layer + Default: False. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + zero_init_residual (bool): Whether to use zero init for last norm layer + in resblocks to let them behave as identity. Default: True. + pretrained (str, optional): model pretrained path. Default: None. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + + Example: + >>> from mmseg.models import ResNet + >>> import torch + >>> self = ResNet(depth=18) + >>> self.eval() + >>> inputs = torch.rand(1, 3, 32, 32) + >>> level_outputs = self.forward(inputs) + >>> for level_out in level_outputs: + ... print(tuple(level_out.shape)) + (1, 64, 8, 8) + (1, 128, 4, 4) + (1, 256, 2, 2) + (1, 512, 1, 1) + """ + + arch_settings = { + 18: (BasicBlock, (2, 2, 2, 2)), + 34: (BasicBlock, (3, 4, 6, 3)), + 50: (Bottleneck, (3, 4, 6, 3)), + 101: (Bottleneck, (3, 4, 23, 3)), + 152: (Bottleneck, (3, 8, 36, 3)) + } + + def __init__(self, + depth, + in_channels=3, + stem_channels=64, + base_channels=64, + num_stages=4, + strides=(1, 2, 2, 2), + dilations=(1, 1, 1, 1), + out_indices=(0, 1, 2, 3), + style='pytorch', + deep_stem=False, + avg_down=False, + frozen_stages=-1, + conv_cfg=None, + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=False, + dcn=None, + stage_with_dcn=(False, False, False, False), + plugins=None, + multi_grid=None, + contract_dilation=False, + with_cp=False, + zero_init_residual=True, + pretrained=None, + init_cfg=None): + super().__init__(init_cfg) + if depth not in self.arch_settings: + raise KeyError(f'invalid depth {depth} for resnet') + + self.pretrained = pretrained + self.zero_init_residual = zero_init_residual + block_init_cfg = None + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be setting at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is a deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is None: + if init_cfg is None: + self.init_cfg = [ + dict(type='Kaiming', layer='Conv2d'), + dict( + type='Constant', + val=1, + layer=['_BatchNorm', 'GroupNorm']) + ] + block = self.arch_settings[depth][0] + if self.zero_init_residual: + if block is BasicBlock: + block_init_cfg = dict( + type='Constant', + val=0, + override=dict(name='norm2')) + elif block is Bottleneck: + block_init_cfg = dict( + type='Constant', + val=0, + override=dict(name='norm3')) + else: + raise TypeError('pretrained must be a str or None') + + self.depth = depth + self.stem_channels = stem_channels + self.base_channels = base_channels + self.num_stages = num_stages + assert num_stages >= 1 and num_stages <= 4 + self.strides = strides + self.dilations = dilations + assert len(strides) == len(dilations) == num_stages + self.out_indices = out_indices + assert max(out_indices) < num_stages + self.style = style + self.deep_stem = deep_stem + self.avg_down = avg_down + self.frozen_stages = frozen_stages + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.with_cp = with_cp + self.norm_eval = norm_eval + self.dcn = dcn + self.stage_with_dcn = stage_with_dcn + if dcn is not None: + assert len(stage_with_dcn) == num_stages + self.plugins = plugins + self.multi_grid = multi_grid + self.contract_dilation = contract_dilation + self.block, stage_blocks = self.arch_settings[depth] + self.stage_blocks = stage_blocks[:num_stages] + self.inplanes = stem_channels + + self._make_stem_layer(in_channels, stem_channels) + + self.res_layers = [] + for i, num_blocks in enumerate(self.stage_blocks): + stride = strides[i] + dilation = dilations[i] + dcn = self.dcn if self.stage_with_dcn[i] else None + if plugins is not None: + stage_plugins = self.make_stage_plugins(plugins, i) + else: + stage_plugins = None + # multi grid is applied to last layer only + stage_multi_grid = multi_grid if i == len( + self.stage_blocks) - 1 else None + planes = base_channels * 2**i + res_layer = self.make_res_layer( + block=self.block, + inplanes=self.inplanes, + planes=planes, + num_blocks=num_blocks, + stride=stride, + dilation=dilation, + style=self.style, + avg_down=self.avg_down, + with_cp=with_cp, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + dcn=dcn, + plugins=stage_plugins, + multi_grid=stage_multi_grid, + contract_dilation=contract_dilation, + init_cfg=block_init_cfg) + self.inplanes = planes * self.block.expansion + layer_name = f'layer{i+1}' + self.add_module(layer_name, res_layer) + self.res_layers.append(layer_name) + + self._freeze_stages() + + self.feat_dim = self.block.expansion * base_channels * 2**( + len(self.stage_blocks) - 1) + + def make_stage_plugins(self, plugins, stage_idx): + """make plugins for ResNet 'stage_idx'th stage . + + Currently we support to insert 'context_block', + 'empirical_attention_block', 'nonlocal_block' into the backbone like + ResNet/ResNeXt. They could be inserted after conv1/conv2/conv3 of + Bottleneck. + + An example of plugins format could be : + >>> plugins=[ + ... dict(cfg=dict(type='xxx', arg1='xxx'), + ... stages=(False, True, True, True), + ... position='after_conv2'), + ... dict(cfg=dict(type='yyy'), + ... stages=(True, True, True, True), + ... position='after_conv3'), + ... dict(cfg=dict(type='zzz', postfix='1'), + ... stages=(True, True, True, True), + ... position='after_conv3'), + ... dict(cfg=dict(type='zzz', postfix='2'), + ... stages=(True, True, True, True), + ... position='after_conv3') + ... ] + >>> self = ResNet(depth=18) + >>> stage_plugins = self.make_stage_plugins(plugins, 0) + >>> assert len(stage_plugins) == 3 + + Suppose 'stage_idx=0', the structure of blocks in the stage would be: + conv1-> conv2->conv3->yyy->zzz1->zzz2 + Suppose 'stage_idx=1', the structure of blocks in the stage would be: + conv1-> conv2->xxx->conv3->yyy->zzz1->zzz2 + + If stages is missing, the plugin would be applied to all stages. + + Args: + plugins (list[dict]): List of plugins cfg to build. The postfix is + required if multiple same type plugins are inserted. + stage_idx (int): Index of stage to build + + Returns: + list[dict]: Plugins for current stage + """ + stage_plugins = [] + for plugin in plugins: + plugin = plugin.copy() + stages = plugin.pop('stages', None) + assert stages is None or len(stages) == self.num_stages + # whether to insert plugin into current stage + if stages is None or stages[stage_idx]: + stage_plugins.append(plugin) + + return stage_plugins + + def make_res_layer(self, **kwargs): + """Pack all blocks in a stage into a ``ResLayer``.""" + return ResLayer(**kwargs) + + @property + def norm1(self): + """nn.Module: the normalization layer named "norm1" """ + return getattr(self, self.norm1_name) + + def _make_stem_layer(self, in_channels, stem_channels): + """Make stem layer for ResNet.""" + if self.deep_stem: + self.stem = nn.Sequential( + build_conv_layer( + self.conv_cfg, + in_channels, + stem_channels // 2, + kernel_size=3, + stride=2, + padding=1, + bias=False), + build_norm_layer(self.norm_cfg, stem_channels // 2)[1], + nn.ReLU(inplace=True), + build_conv_layer( + self.conv_cfg, + stem_channels // 2, + stem_channels // 2, + kernel_size=3, + stride=1, + padding=1, + bias=False), + build_norm_layer(self.norm_cfg, stem_channels // 2)[1], + nn.ReLU(inplace=True), + build_conv_layer( + self.conv_cfg, + stem_channels // 2, + stem_channels, + kernel_size=3, + stride=1, + padding=1, + bias=False), + build_norm_layer(self.norm_cfg, stem_channels)[1], + nn.ReLU(inplace=True)) + else: + self.conv1 = build_conv_layer( + self.conv_cfg, + in_channels, + stem_channels, + kernel_size=7, + stride=2, + padding=3, + bias=False) + self.norm1_name, norm1 = build_norm_layer( + self.norm_cfg, stem_channels, postfix=1) + self.add_module(self.norm1_name, norm1) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + + def _freeze_stages(self): + """Freeze stages param and norm stats.""" + if self.frozen_stages >= 0: + if self.deep_stem: + self.stem.eval() + for param in self.stem.parameters(): + param.requires_grad = False + else: + self.norm1.eval() + for m in [self.conv1, self.norm1]: + for param in m.parameters(): + param.requires_grad = False + + for i in range(1, self.frozen_stages + 1): + m = getattr(self, f'layer{i}') + m.eval() + for param in m.parameters(): + param.requires_grad = False + + def forward(self, x): + """Forward function.""" + if self.deep_stem: + x = self.stem(x) + else: + x = self.conv1(x) + x = self.norm1(x) + x = self.relu(x) + x = self.maxpool(x) + outs = [] + for i, layer_name in enumerate(self.res_layers): + res_layer = getattr(self, layer_name) + x = res_layer(x) + if i in self.out_indices: + outs.append(x) + return tuple(outs) + + def train(self, mode=True): + """Convert the model into training mode while keep normalization layer + freezed.""" + super().train(mode) + self._freeze_stages() + if mode and self.norm_eval: + for m in self.modules(): + # trick: eval have effect on BatchNorm only + if isinstance(m, _BatchNorm): + m.eval() + + +@MODELS.register_module() +class ResNetV1c(ResNet): + """ResNetV1c variant described in [1]_. + + Compared with default ResNet(ResNetV1b), ResNetV1c replaces the 7x7 conv in + the input stem with three 3x3 convs. For more details please refer to `Bag + of Tricks for Image Classification with Convolutional Neural Networks + `_. + """ + + def __init__(self, **kwargs): + super().__init__(deep_stem=True, avg_down=False, **kwargs) + + +@MODELS.register_module() +class ResNetV1d(ResNet): + """ResNetV1d variant described in [1]_. + + Compared with default ResNet(ResNetV1b), ResNetV1d replaces the 7x7 conv in + the input stem with three 3x3 convs. And in the downsampling block, a 2x2 + avg_pool with stride 2 is added before conv, whose stride is changed to 1. + """ + + def __init__(self, **kwargs): + super().__init__(deep_stem=True, avg_down=True, **kwargs) diff --git a/third-party/InterFormer/mmseg/models/backbones/resnext.py b/third-party/InterFormer/mmseg/models/backbones/resnext.py new file mode 100644 index 0000000000000000000000000000000000000000..67a244a12f61b78ee12e89e8b45868781208614c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/resnext.py @@ -0,0 +1,150 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math + +from mmcv.cnn import build_conv_layer, build_norm_layer + +from mmseg.registry import MODELS +from ..utils import ResLayer +from .resnet import Bottleneck as _Bottleneck +from .resnet import ResNet + + +class Bottleneck(_Bottleneck): + """Bottleneck block for ResNeXt. + + If style is "pytorch", the stride-two layer is the 3x3 conv layer, if it is + "caffe", the stride-two layer is the first 1x1 conv layer. + """ + + def __init__(self, + inplanes, + planes, + groups=1, + base_width=4, + base_channels=64, + **kwargs): + super().__init__(inplanes, planes, **kwargs) + + if groups == 1: + width = self.planes + else: + width = math.floor(self.planes * + (base_width / base_channels)) * groups + + self.norm1_name, norm1 = build_norm_layer( + self.norm_cfg, width, postfix=1) + self.norm2_name, norm2 = build_norm_layer( + self.norm_cfg, width, postfix=2) + self.norm3_name, norm3 = build_norm_layer( + self.norm_cfg, self.planes * self.expansion, postfix=3) + + self.conv1 = build_conv_layer( + self.conv_cfg, + self.inplanes, + width, + kernel_size=1, + stride=self.conv1_stride, + bias=False) + self.add_module(self.norm1_name, norm1) + fallback_on_stride = False + self.with_modulated_dcn = False + if self.with_dcn: + fallback_on_stride = self.dcn.pop('fallback_on_stride', False) + if not self.with_dcn or fallback_on_stride: + self.conv2 = build_conv_layer( + self.conv_cfg, + width, + width, + kernel_size=3, + stride=self.conv2_stride, + padding=self.dilation, + dilation=self.dilation, + groups=groups, + bias=False) + else: + assert self.conv_cfg is None, 'conv_cfg must be None for DCN' + self.conv2 = build_conv_layer( + self.dcn, + width, + width, + kernel_size=3, + stride=self.conv2_stride, + padding=self.dilation, + dilation=self.dilation, + groups=groups, + bias=False) + + self.add_module(self.norm2_name, norm2) + self.conv3 = build_conv_layer( + self.conv_cfg, + width, + self.planes * self.expansion, + kernel_size=1, + bias=False) + self.add_module(self.norm3_name, norm3) + + +@MODELS.register_module() +class ResNeXt(ResNet): + """ResNeXt backbone. + + This backbone is the implementation of `Aggregated + Residual Transformations for Deep Neural + Networks `_. + + Args: + depth (int): Depth of resnet, from {18, 34, 50, 101, 152}. + in_channels (int): Number of input image channels. Normally 3. + num_stages (int): Resnet stages, normally 4. + groups (int): Group of resnext. + base_width (int): Base width of resnext. + strides (Sequence[int]): Strides of the first block of each stage. + dilations (Sequence[int]): Dilation of each stage. + out_indices (Sequence[int]): Output from which stages. + style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two + layer is the 3x3 conv layer, otherwise the stride-two layer is + the first 1x1 conv layer. + frozen_stages (int): Stages to be frozen (all param fixed). -1 means + not freezing any parameters. + norm_cfg (dict): dictionary to construct and config norm layer. + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. + zero_init_residual (bool): whether to use zero init for last norm layer + in resblocks to let them behave as identity. + + Example: + >>> from mmseg.models import ResNeXt + >>> import torch + >>> self = ResNeXt(depth=50) + >>> self.eval() + >>> inputs = torch.rand(1, 3, 32, 32) + >>> level_outputs = self.forward(inputs) + >>> for level_out in level_outputs: + ... print(tuple(level_out.shape)) + (1, 256, 8, 8) + (1, 512, 4, 4) + (1, 1024, 2, 2) + (1, 2048, 1, 1) + """ + + arch_settings = { + 50: (Bottleneck, (3, 4, 6, 3)), + 101: (Bottleneck, (3, 4, 23, 3)), + 152: (Bottleneck, (3, 8, 36, 3)) + } + + def __init__(self, groups=1, base_width=4, **kwargs): + self.groups = groups + self.base_width = base_width + super().__init__(**kwargs) + + def make_res_layer(self, **kwargs): + """Pack all blocks in a stage into a ``ResLayer``""" + return ResLayer( + groups=self.groups, + base_width=self.base_width, + base_channels=self.base_channels, + **kwargs) diff --git a/third-party/InterFormer/mmseg/models/backbones/stdc.py b/third-party/InterFormer/mmseg/models/backbones/stdc.py new file mode 100644 index 0000000000000000000000000000000000000000..758a3c92e07dc8d2051f670adf00d163019d758c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/stdc.py @@ -0,0 +1,422 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from https://github.com/MichaelFan01/STDC-Seg.""" +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule, ModuleList, Sequential + +from mmseg.registry import MODELS +from ..utils import resize +from .bisenetv1 import AttentionRefinementModule + + +class STDCModule(BaseModule): + """STDCModule. + + Args: + in_channels (int): The number of input channels. + out_channels (int): The number of output channels before scaling. + stride (int): The number of stride for the first conv layer. + norm_cfg (dict): Config dict for normalization layer. Default: None. + act_cfg (dict): The activation config for conv layers. + num_convs (int): Numbers of conv layers. + fusion_type (str): Type of fusion operation. Default: 'add'. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + stride, + norm_cfg=None, + act_cfg=None, + num_convs=4, + fusion_type='add', + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert num_convs > 1 + assert fusion_type in ['add', 'cat'] + self.stride = stride + self.with_downsample = True if self.stride == 2 else False + self.fusion_type = fusion_type + + self.layers = ModuleList() + conv_0 = ConvModule( + in_channels, out_channels // 2, kernel_size=1, norm_cfg=norm_cfg) + + if self.with_downsample: + self.downsample = ConvModule( + out_channels // 2, + out_channels // 2, + kernel_size=3, + stride=2, + padding=1, + groups=out_channels // 2, + norm_cfg=norm_cfg, + act_cfg=None) + + if self.fusion_type == 'add': + self.layers.append(nn.Sequential(conv_0, self.downsample)) + self.skip = Sequential( + ConvModule( + in_channels, + in_channels, + kernel_size=3, + stride=2, + padding=1, + groups=in_channels, + norm_cfg=norm_cfg, + act_cfg=None), + ConvModule( + in_channels, + out_channels, + 1, + norm_cfg=norm_cfg, + act_cfg=None)) + else: + self.layers.append(conv_0) + self.skip = nn.AvgPool2d(kernel_size=3, stride=2, padding=1) + else: + self.layers.append(conv_0) + + for i in range(1, num_convs): + out_factor = 2**(i + 1) if i != num_convs - 1 else 2**i + self.layers.append( + ConvModule( + out_channels // 2**i, + out_channels // out_factor, + kernel_size=3, + stride=1, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + def forward(self, inputs): + if self.fusion_type == 'add': + out = self.forward_add(inputs) + else: + out = self.forward_cat(inputs) + return out + + def forward_add(self, inputs): + layer_outputs = [] + x = inputs.clone() + for layer in self.layers: + x = layer(x) + layer_outputs.append(x) + if self.with_downsample: + inputs = self.skip(inputs) + + return torch.cat(layer_outputs, dim=1) + inputs + + def forward_cat(self, inputs): + x0 = self.layers[0](inputs) + layer_outputs = [x0] + for i, layer in enumerate(self.layers[1:]): + if i == 0: + if self.with_downsample: + x = layer(self.downsample(x0)) + else: + x = layer(x0) + else: + x = layer(x) + layer_outputs.append(x) + if self.with_downsample: + layer_outputs[0] = self.skip(x0) + return torch.cat(layer_outputs, dim=1) + + +class FeatureFusionModule(BaseModule): + """Feature Fusion Module. This module is different from FeatureFusionModule + in BiSeNetV1. It uses two ConvModules in `self.attention` whose inter + channel number is calculated by given `scale_factor`, while + FeatureFusionModule in BiSeNetV1 only uses one ConvModule in + `self.conv_atten`. + + Args: + in_channels (int): The number of input channels. + out_channels (int): The number of output channels. + scale_factor (int): The number of channel scale factor. + Default: 4. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): The activation config for conv layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + scale_factor=4, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + channels = out_channels // scale_factor + self.conv0 = ConvModule( + in_channels, out_channels, 1, norm_cfg=norm_cfg, act_cfg=act_cfg) + self.attention = nn.Sequential( + nn.AdaptiveAvgPool2d((1, 1)), + ConvModule( + out_channels, + channels, + 1, + norm_cfg=None, + bias=False, + act_cfg=act_cfg), + ConvModule( + channels, + out_channels, + 1, + norm_cfg=None, + bias=False, + act_cfg=None), nn.Sigmoid()) + + def forward(self, spatial_inputs, context_inputs): + inputs = torch.cat([spatial_inputs, context_inputs], dim=1) + x = self.conv0(inputs) + attn = self.attention(x) + x_attn = x * attn + return x_attn + x + + +@MODELS.register_module() +class STDCNet(BaseModule): + """This backbone is the implementation of `Rethinking BiSeNet For Real-time + Semantic Segmentation `_. + + Args: + stdc_type (int): The type of backbone structure, + `STDCNet1` and`STDCNet2` denotes two main backbones in paper, + whose FLOPs is 813M and 1446M, respectively. + in_channels (int): The num of input_channels. + channels (tuple[int]): The output channels for each stage. + bottleneck_type (str): The type of STDC Module type, the value must + be 'add' or 'cat'. + norm_cfg (dict): Config dict for normalization layer. + act_cfg (dict): The activation config for conv layers. + num_convs (int): Numbers of conv layer at each STDC Module. + Default: 4. + with_final_conv (bool): Whether add a conv layer at the Module output. + Default: True. + pretrained (str, optional): Model pretrained path. Default: None. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + + Example: + >>> import torch + >>> stdc_type = 'STDCNet1' + >>> in_channels = 3 + >>> channels = (32, 64, 256, 512, 1024) + >>> bottleneck_type = 'cat' + >>> inputs = torch.rand(1, 3, 1024, 2048) + >>> self = STDCNet(stdc_type, in_channels, + ... channels, bottleneck_type).eval() + >>> outputs = self.forward(inputs) + >>> for i in range(len(outputs)): + ... print(f'outputs[{i}].shape = {outputs[i].shape}') + outputs[0].shape = torch.Size([1, 256, 128, 256]) + outputs[1].shape = torch.Size([1, 512, 64, 128]) + outputs[2].shape = torch.Size([1, 1024, 32, 64]) + """ + + arch_settings = { + 'STDCNet1': [(2, 1), (2, 1), (2, 1)], + 'STDCNet2': [(2, 1, 1, 1), (2, 1, 1, 1, 1), (2, 1, 1)] + } + + def __init__(self, + stdc_type, + in_channels, + channels, + bottleneck_type, + norm_cfg, + act_cfg, + num_convs=4, + with_final_conv=False, + pretrained=None, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert stdc_type in self.arch_settings, \ + f'invalid structure {stdc_type} for STDCNet.' + assert bottleneck_type in ['add', 'cat'],\ + f'bottleneck_type must be `add` or `cat`, got {bottleneck_type}' + + assert len(channels) == 5,\ + f'invalid channels length {len(channels)} for STDCNet.' + + self.in_channels = in_channels + self.channels = channels + self.stage_strides = self.arch_settings[stdc_type] + self.prtrained = pretrained + self.num_convs = num_convs + self.with_final_conv = with_final_conv + + self.stages = ModuleList([ + ConvModule( + self.in_channels, + self.channels[0], + kernel_size=3, + stride=2, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg), + ConvModule( + self.channels[0], + self.channels[1], + kernel_size=3, + stride=2, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + ]) + # `self.num_shallow_features` is the number of shallow modules in + # `STDCNet`, which is noted as `Stage1` and `Stage2` in original paper. + # They are both not used for following modules like Attention + # Refinement Module and Feature Fusion Module. + # Thus they would be cut from `outs`. Please refer to Figure 4 + # of original paper for more details. + self.num_shallow_features = len(self.stages) + + for strides in self.stage_strides: + idx = len(self.stages) - 1 + self.stages.append( + self._make_stage(self.channels[idx], self.channels[idx + 1], + strides, norm_cfg, act_cfg, bottleneck_type)) + # After appending, `self.stages` is a ModuleList including several + # shallow modules and STDCModules. + # (len(self.stages) == + # self.num_shallow_features + len(self.stage_strides)) + if self.with_final_conv: + self.final_conv = ConvModule( + self.channels[-1], + max(1024, self.channels[-1]), + 1, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def _make_stage(self, in_channels, out_channels, strides, norm_cfg, + act_cfg, bottleneck_type): + layers = [] + for i, stride in enumerate(strides): + layers.append( + STDCModule( + in_channels if i == 0 else out_channels, + out_channels, + stride, + norm_cfg, + act_cfg, + num_convs=self.num_convs, + fusion_type=bottleneck_type)) + return Sequential(*layers) + + def forward(self, x): + outs = [] + for stage in self.stages: + x = stage(x) + outs.append(x) + if self.with_final_conv: + outs[-1] = self.final_conv(outs[-1]) + outs = outs[self.num_shallow_features:] + return tuple(outs) + + +@MODELS.register_module() +class STDCContextPathNet(BaseModule): + """STDCNet with Context Path. The `outs` below is a list of three feature + maps from deep to shallow, whose height and width is from small to big, + respectively. The biggest feature map of `outs` is outputted for + `STDCHead`, where Detail Loss would be calculated by Detail Ground-truth. + The other two feature maps are used for Attention Refinement Module, + respectively. Besides, the biggest feature map of `outs` and the last + output of Attention Refinement Module are concatenated for Feature Fusion + Module. Then, this fusion feature map `feat_fuse` would be outputted for + `decode_head`. More details please refer to Figure 4 of original paper. + + Args: + backbone_cfg (dict): Config dict for stdc backbone. + last_in_channels (tuple(int)), The number of channels of last + two feature maps from stdc backbone. Default: (1024, 512). + out_channels (int): The channels of output feature maps. + Default: 128. + ffm_cfg (dict): Config dict for Feature Fusion Module. Default: + `dict(in_channels=512, out_channels=256, scale_factor=4)`. + upsample_mode (str): Algorithm used for upsampling: + ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` | + ``'trilinear'``. Default: ``'nearest'``. + align_corners (str): align_corners argument of F.interpolate. It + must be `None` if upsample_mode is ``'nearest'``. Default: None. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + + Return: + outputs (tuple): The tuple of list of output feature map for + auxiliary heads and decoder head. + """ + + def __init__(self, + backbone_cfg, + last_in_channels=(1024, 512), + out_channels=128, + ffm_cfg=dict( + in_channels=512, out_channels=256, scale_factor=4), + upsample_mode='nearest', + align_corners=None, + norm_cfg=dict(type='BN'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.backbone = MODELS.build(backbone_cfg) + self.arms = ModuleList() + self.convs = ModuleList() + for channels in last_in_channels: + self.arms.append(AttentionRefinementModule(channels, out_channels)) + self.convs.append( + ConvModule( + out_channels, + out_channels, + 3, + padding=1, + norm_cfg=norm_cfg)) + self.conv_avg = ConvModule( + last_in_channels[0], out_channels, 1, norm_cfg=norm_cfg) + + self.ffm = FeatureFusionModule(**ffm_cfg) + + self.upsample_mode = upsample_mode + self.align_corners = align_corners + + def forward(self, x): + outs = list(self.backbone(x)) + avg = F.adaptive_avg_pool2d(outs[-1], 1) + avg_feat = self.conv_avg(avg) + + feature_up = resize( + avg_feat, + size=outs[-1].shape[2:], + mode=self.upsample_mode, + align_corners=self.align_corners) + arms_out = [] + for i in range(len(self.arms)): + x_arm = self.arms[i](outs[len(outs) - 1 - i]) + feature_up + feature_up = resize( + x_arm, + size=outs[len(outs) - 1 - i - 1].shape[2:], + mode=self.upsample_mode, + align_corners=self.align_corners) + feature_up = self.convs[i](feature_up) + arms_out.append(feature_up) + + feat_fuse = self.ffm(outs[0], arms_out[1]) + + # The `outputs` has four feature maps. + # `outs[0]` is outputted for `STDCHead` auxiliary head. + # Two feature maps of `arms_out` are outputted for auxiliary head. + # `feat_fuse` is outputted for decoder head. + outputs = [outs[0]] + list(arms_out) + [feat_fuse] + return tuple(outputs) diff --git a/third-party/InterFormer/mmseg/models/backbones/swin.py b/third-party/InterFormer/mmseg/models/backbones/swin.py new file mode 100644 index 0000000000000000000000000000000000000000..67b28a96e15fe81e8213d67518d664383a4fd255 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/swin.py @@ -0,0 +1,757 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings +from collections import OrderedDict +from copy import deepcopy + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as cp +from mmcv.cnn import build_norm_layer +from mmcv.cnn.bricks.transformer import FFN, build_dropout +from mmengine.logging import print_log +from mmengine.model import BaseModule, ModuleList +from mmengine.model.weight_init import (constant_init, trunc_normal_, + trunc_normal_init) +from mmengine.runner import CheckpointLoader +from mmengine.utils import to_2tuple + +from mmseg.registry import MODELS +from ..utils.embed import PatchEmbed, PatchMerging + + +class WindowMSA(BaseModule): + """Window based multi-head self-attention (W-MSA) module with relative + position bias. + + Args: + embed_dims (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (tuple[int]): The height and width of the window. + qkv_bias (bool, optional): If True, add a learnable bias to q, k, v. + Default: True. + qk_scale (float | None, optional): Override default qk scale of + head_dim ** -0.5 if set. Default: None. + attn_drop_rate (float, optional): Dropout ratio of attention weight. + Default: 0.0 + proj_drop_rate (float, optional): Dropout ratio of output. Default: 0. + init_cfg (dict | None, optional): The Config for initialization. + Default: None. + """ + + def __init__(self, + embed_dims, + num_heads, + window_size, + qkv_bias=True, + qk_scale=None, + attn_drop_rate=0., + proj_drop_rate=0., + init_cfg=None): + + super().__init__(init_cfg=init_cfg) + self.embed_dims = embed_dims + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_embed_dims = embed_dims // num_heads + self.scale = qk_scale or head_embed_dims**-0.5 + + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), + num_heads)) # 2*Wh-1 * 2*Ww-1, nH + + # About 2x faster than original impl + Wh, Ww = self.window_size + rel_index_coords = self.double_step_seq(2 * Ww - 1, Wh, 1, Ww) + rel_position_index = rel_index_coords + rel_index_coords.T + rel_position_index = rel_position_index.flip(1).contiguous() + self.register_buffer('relative_position_index', rel_position_index) + + self.qkv = nn.Linear(embed_dims, embed_dims * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop_rate) + self.proj = nn.Linear(embed_dims, embed_dims) + self.proj_drop = nn.Dropout(proj_drop_rate) + + self.softmax = nn.Softmax(dim=-1) + + def init_weights(self): + trunc_normal_(self.relative_position_bias_table, std=0.02) + + def forward(self, x, mask=None): + """ + Args: + + x (tensor): input features with shape of (num_windows*B, N, C) + mask (tensor | None, Optional): mask with shape of (num_windows, + Wh*Ww, Wh*Ww), value should be between (-inf, 0]. + """ + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, + C // self.num_heads).permute(2, 0, 3, 1, 4) + # make torchscript happy (cannot use tensor as tuple) + q, k, v = qkv[0], qkv[1], qkv[2] + + q = q * self.scale + attn = (q @ k.transpose(-2, -1)) + + relative_position_bias = self.relative_position_bias_table[ + self.relative_position_index.view(-1)].view( + self.window_size[0] * self.window_size[1], + self.window_size[0] * self.window_size[1], + -1) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute( + 2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0) + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B // nW, nW, self.num_heads, N, + N) + mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, self.num_heads, N, N) + attn = self.softmax(attn) + + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + @staticmethod + def double_step_seq(step1, len1, step2, len2): + seq1 = torch.arange(0, step1 * len1, step1) + seq2 = torch.arange(0, step2 * len2, step2) + return (seq1[:, None] + seq2[None, :]).reshape(1, -1) + + +class ShiftWindowMSA(BaseModule): + """Shifted Window Multihead Self-Attention Module. + + Args: + embed_dims (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (int): The height and width of the window. + shift_size (int, optional): The shift step of each window towards + right-bottom. If zero, act as regular window-msa. Defaults to 0. + qkv_bias (bool, optional): If True, add a learnable bias to q, k, v. + Default: True + qk_scale (float | None, optional): Override default qk scale of + head_dim ** -0.5 if set. Defaults: None. + attn_drop_rate (float, optional): Dropout ratio of attention weight. + Defaults: 0. + proj_drop_rate (float, optional): Dropout ratio of output. + Defaults: 0. + dropout_layer (dict, optional): The dropout_layer used before output. + Defaults: dict(type='DropPath', drop_prob=0.). + init_cfg (dict, optional): The extra config for initialization. + Default: None. + """ + + def __init__(self, + embed_dims, + num_heads, + window_size, + shift_size=0, + qkv_bias=True, + qk_scale=None, + attn_drop_rate=0, + proj_drop_rate=0, + dropout_layer=dict(type='DropPath', drop_prob=0.), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + self.window_size = window_size + self.shift_size = shift_size + assert 0 <= self.shift_size < self.window_size + + self.w_msa = WindowMSA( + embed_dims=embed_dims, + num_heads=num_heads, + window_size=to_2tuple(window_size), + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop_rate=attn_drop_rate, + proj_drop_rate=proj_drop_rate, + init_cfg=None) + + self.drop = build_dropout(dropout_layer) + + def forward(self, query, hw_shape): + B, L, C = query.shape + H, W = hw_shape + assert L == H * W, 'input feature has wrong size' + query = query.view(B, H, W, C) + + # pad feature maps to multiples of window size + pad_r = (self.window_size - W % self.window_size) % self.window_size + pad_b = (self.window_size - H % self.window_size) % self.window_size + query = F.pad(query, (0, 0, 0, pad_r, 0, pad_b)) + H_pad, W_pad = query.shape[1], query.shape[2] + + # cyclic shift + if self.shift_size > 0: + shifted_query = torch.roll( + query, + shifts=(-self.shift_size, -self.shift_size), + dims=(1, 2)) + + # calculate attention mask for SW-MSA + img_mask = torch.zeros((1, H_pad, W_pad, 1), device=query.device) + h_slices = (slice(0, -self.window_size), + slice(-self.window_size, + -self.shift_size), slice(-self.shift_size, None)) + w_slices = (slice(0, -self.window_size), + slice(-self.window_size, + -self.shift_size), slice(-self.shift_size, None)) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + # nW, window_size, window_size, 1 + mask_windows = self.window_partition(img_mask) + mask_windows = mask_windows.view( + -1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, + float(-100.0)).masked_fill( + attn_mask == 0, float(0.0)) + else: + shifted_query = query + attn_mask = None + + # nW*B, window_size, window_size, C + query_windows = self.window_partition(shifted_query) + # nW*B, window_size*window_size, C + query_windows = query_windows.view(-1, self.window_size**2, C) + + # W-MSA/SW-MSA (nW*B, window_size*window_size, C) + attn_windows = self.w_msa(query_windows, mask=attn_mask) + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, + self.window_size, C) + + # B H' W' C + shifted_x = self.window_reverse(attn_windows, H_pad, W_pad) + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll( + shifted_x, + shifts=(self.shift_size, self.shift_size), + dims=(1, 2)) + else: + x = shifted_x + + if pad_r > 0 or pad_b: + x = x[:, :H, :W, :].contiguous() + + x = x.view(B, H * W, C) + + x = self.drop(x) + return x + + def window_reverse(self, windows, H, W): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + H (int): Height of image + W (int): Width of image + Returns: + x: (B, H, W, C) + """ + window_size = self.window_size + B = int(windows.shape[0] / (H * W / window_size / window_size)) + x = windows.view(B, H // window_size, W // window_size, window_size, + window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + def window_partition(self, x): + """ + Args: + x: (B, H, W, C) + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + window_size = self.window_size + x = x.view(B, H // window_size, window_size, W // window_size, + window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous() + windows = windows.view(-1, window_size, window_size, C) + return windows + + +class SwinBlock(BaseModule): + """" + Args: + embed_dims (int): The feature dimension. + num_heads (int): Parallel attention heads. + feedforward_channels (int): The hidden dimension for FFNs. + window_size (int, optional): The local window scale. Default: 7. + shift (bool, optional): whether to shift window or not. Default False. + qkv_bias (bool, optional): enable bias for qkv if True. Default: True. + qk_scale (float | None, optional): Override default qk scale of + head_dim ** -0.5 if set. Default: None. + drop_rate (float, optional): Dropout rate. Default: 0. + attn_drop_rate (float, optional): Attention dropout rate. Default: 0. + drop_path_rate (float, optional): Stochastic depth rate. Default: 0. + act_cfg (dict, optional): The config dict of activation function. + Default: dict(type='GELU'). + norm_cfg (dict, optional): The config dict of normalization. + Default: dict(type='LN'). + with_cp (bool, optional): Use checkpoint or not. Using checkpoint + will save some memory while slowing down the training speed. + Default: False. + init_cfg (dict | list | None, optional): The init config. + Default: None. + """ + + def __init__(self, + embed_dims, + num_heads, + feedforward_channels, + window_size=7, + shift=False, + qkv_bias=True, + qk_scale=None, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + with_cp=False, + init_cfg=None): + + super().__init__(init_cfg=init_cfg) + + self.with_cp = with_cp + + self.norm1 = build_norm_layer(norm_cfg, embed_dims)[1] + self.attn = ShiftWindowMSA( + embed_dims=embed_dims, + num_heads=num_heads, + window_size=window_size, + shift_size=window_size // 2 if shift else 0, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop_rate=attn_drop_rate, + proj_drop_rate=drop_rate, + dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), + init_cfg=None) + + self.norm2 = build_norm_layer(norm_cfg, embed_dims)[1] + self.ffn = FFN( + embed_dims=embed_dims, + feedforward_channels=feedforward_channels, + num_fcs=2, + ffn_drop=drop_rate, + dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), + act_cfg=act_cfg, + add_identity=True, + init_cfg=None) + + def forward(self, x, hw_shape): + + def _inner_forward(x): + identity = x + x = self.norm1(x) + x = self.attn(x, hw_shape) + + x = x + identity + + identity = x + x = self.norm2(x) + x = self.ffn(x, identity=identity) + + return x + + if self.with_cp and x.requires_grad: + x = cp.checkpoint(_inner_forward, x) + else: + x = _inner_forward(x) + + return x + + +class SwinBlockSequence(BaseModule): + """Implements one stage in Swin Transformer. + + Args: + embed_dims (int): The feature dimension. + num_heads (int): Parallel attention heads. + feedforward_channels (int): The hidden dimension for FFNs. + depth (int): The number of blocks in this stage. + window_size (int, optional): The local window scale. Default: 7. + qkv_bias (bool, optional): enable bias for qkv if True. Default: True. + qk_scale (float | None, optional): Override default qk scale of + head_dim ** -0.5 if set. Default: None. + drop_rate (float, optional): Dropout rate. Default: 0. + attn_drop_rate (float, optional): Attention dropout rate. Default: 0. + drop_path_rate (float | list[float], optional): Stochastic depth + rate. Default: 0. + downsample (BaseModule | None, optional): The downsample operation + module. Default: None. + act_cfg (dict, optional): The config dict of activation function. + Default: dict(type='GELU'). + norm_cfg (dict, optional): The config dict of normalization. + Default: dict(type='LN'). + with_cp (bool, optional): Use checkpoint or not. Using checkpoint + will save some memory while slowing down the training speed. + Default: False. + init_cfg (dict | list | None, optional): The init config. + Default: None. + """ + + def __init__(self, + embed_dims, + num_heads, + feedforward_channels, + depth, + window_size=7, + qkv_bias=True, + qk_scale=None, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + downsample=None, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + with_cp=False, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + if isinstance(drop_path_rate, list): + drop_path_rates = drop_path_rate + assert len(drop_path_rates) == depth + else: + drop_path_rates = [deepcopy(drop_path_rate) for _ in range(depth)] + + self.blocks = ModuleList() + for i in range(depth): + block = SwinBlock( + embed_dims=embed_dims, + num_heads=num_heads, + feedforward_channels=feedforward_channels, + window_size=window_size, + shift=False if i % 2 == 0 else True, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=drop_path_rates[i], + act_cfg=act_cfg, + norm_cfg=norm_cfg, + with_cp=with_cp, + init_cfg=None) + self.blocks.append(block) + + self.downsample = downsample + + def forward(self, x, hw_shape): + for block in self.blocks: + x = block(x, hw_shape) + + if self.downsample: + x_down, down_hw_shape = self.downsample(x, hw_shape) + return x_down, down_hw_shape, x, hw_shape + else: + return x, hw_shape, x, hw_shape + + +@MODELS.register_module() +class SwinTransformer(BaseModule): + """Swin Transformer backbone. + + This backbone is the implementation of `Swin Transformer: + Hierarchical Vision Transformer using Shifted + Windows `_. + Inspiration from https://github.com/microsoft/Swin-Transformer. + + Args: + pretrain_img_size (int | tuple[int]): The size of input image when + pretrain. Defaults: 224. + in_channels (int): The num of input channels. + Defaults: 3. + embed_dims (int): The feature dimension. Default: 96. + patch_size (int | tuple[int]): Patch size. Default: 4. + window_size (int): Window size. Default: 7. + mlp_ratio (int | float): Ratio of mlp hidden dim to embedding dim. + Default: 4. + depths (tuple[int]): Depths of each Swin Transformer stage. + Default: (2, 2, 6, 2). + num_heads (tuple[int]): Parallel attention heads of each Swin + Transformer stage. Default: (3, 6, 12, 24). + strides (tuple[int]): The patch merging or patch embedding stride of + each Swin Transformer stage. (In swin, we set kernel size equal to + stride.) Default: (4, 2, 2, 2). + out_indices (tuple[int]): Output from which stages. + Default: (0, 1, 2, 3). + qkv_bias (bool, optional): If True, add a learnable bias to query, key, + value. Default: True + qk_scale (float | None, optional): Override default qk scale of + head_dim ** -0.5 if set. Default: None. + patch_norm (bool): If add a norm layer for patch embed and patch + merging. Default: True. + drop_rate (float): Dropout rate. Defaults: 0. + attn_drop_rate (float): Attention dropout rate. Default: 0. + drop_path_rate (float): Stochastic depth rate. Defaults: 0.1. + use_abs_pos_embed (bool): If True, add absolute position embedding to + the patch embedding. Defaults: False. + act_cfg (dict): Config dict for activation layer. + Default: dict(type='LN'). + norm_cfg (dict): Config dict for normalization layer at + output of backone. Defaults: dict(type='LN'). + with_cp (bool, optional): Use checkpoint or not. Using checkpoint + will save some memory while slowing down the training speed. + Default: False. + pretrained (str, optional): model pretrained path. Default: None. + frozen_stages (int): Stages to be frozen (stop grad and set eval mode). + -1 means not freezing any parameters. + init_cfg (dict, optional): The Config for initialization. + Defaults to None. + """ + + def __init__(self, + pretrain_img_size=224, + in_channels=3, + embed_dims=96, + patch_size=4, + window_size=7, + mlp_ratio=4, + depths=(2, 2, 6, 2), + num_heads=(3, 6, 12, 24), + strides=(4, 2, 2, 2), + out_indices=(0, 1, 2, 3), + qkv_bias=True, + qk_scale=None, + patch_norm=True, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0.1, + use_abs_pos_embed=False, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + with_cp=False, + pretrained=None, + frozen_stages=-1, + init_cfg=None): + self.frozen_stages = frozen_stages + + if isinstance(pretrain_img_size, int): + pretrain_img_size = to_2tuple(pretrain_img_size) + elif isinstance(pretrain_img_size, tuple): + if len(pretrain_img_size) == 1: + pretrain_img_size = to_2tuple(pretrain_img_size[0]) + assert len(pretrain_img_size) == 2, \ + f'The size of image should have length 1 or 2, ' \ + f'but got {len(pretrain_img_size)}' + + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be specified at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is deprecated, ' + 'please use "init_cfg" instead') + init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is None: + init_cfg = init_cfg + else: + raise TypeError('pretrained must be a str or None') + + super().__init__(init_cfg=init_cfg) + + num_layers = len(depths) + self.out_indices = out_indices + self.use_abs_pos_embed = use_abs_pos_embed + + assert strides[0] == patch_size, 'Use non-overlapping patch embed.' + + self.patch_embed = PatchEmbed( + in_channels=in_channels, + embed_dims=embed_dims, + conv_type='Conv2d', + kernel_size=patch_size, + stride=strides[0], + padding='corner', + norm_cfg=norm_cfg if patch_norm else None, + init_cfg=None) + + if self.use_abs_pos_embed: + patch_row = pretrain_img_size[0] // patch_size + patch_col = pretrain_img_size[1] // patch_size + num_patches = patch_row * patch_col + self.absolute_pos_embed = nn.Parameter( + torch.zeros((1, num_patches, embed_dims))) + + self.drop_after_pos = nn.Dropout(p=drop_rate) + + # set stochastic depth decay rule + total_depth = sum(depths) + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, total_depth) + ] + + self.stages = ModuleList() + in_channels = embed_dims + for i in range(num_layers): + if i < num_layers - 1: + downsample = PatchMerging( + in_channels=in_channels, + out_channels=2 * in_channels, + stride=strides[i + 1], + norm_cfg=norm_cfg if patch_norm else None, + init_cfg=None) + else: + downsample = None + + stage = SwinBlockSequence( + embed_dims=in_channels, + num_heads=num_heads[i], + feedforward_channels=int(mlp_ratio * in_channels), + depth=depths[i], + window_size=window_size, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=dpr[sum(depths[:i]):sum(depths[:i + 1])], + downsample=downsample, + act_cfg=act_cfg, + norm_cfg=norm_cfg, + with_cp=with_cp, + init_cfg=None) + self.stages.append(stage) + if downsample: + in_channels = downsample.out_channels + + self.num_features = [int(embed_dims * 2**i) for i in range(num_layers)] + # Add a norm layer for each output + for i in out_indices: + layer = build_norm_layer(norm_cfg, self.num_features[i])[1] + layer_name = f'norm{i}' + self.add_module(layer_name, layer) + + def train(self, mode=True): + """Convert the model into training mode while keep layers freezed.""" + super().train(mode) + self._freeze_stages() + + def _freeze_stages(self): + if self.frozen_stages >= 0: + self.patch_embed.eval() + for param in self.patch_embed.parameters(): + param.requires_grad = False + if self.use_abs_pos_embed: + self.absolute_pos_embed.requires_grad = False + self.drop_after_pos.eval() + + for i in range(1, self.frozen_stages + 1): + + if (i - 1) in self.out_indices: + norm_layer = getattr(self, f'norm{i-1}') + norm_layer.eval() + for param in norm_layer.parameters(): + param.requires_grad = False + + m = self.stages[i - 1] + m.eval() + for param in m.parameters(): + param.requires_grad = False + + def init_weights(self): + if self.init_cfg is None: + print_log(f'No pre-trained weights for ' + f'{self.__class__.__name__}, ' + f'training start from scratch') + if self.use_abs_pos_embed: + trunc_normal_(self.absolute_pos_embed, std=0.02) + for m in self.modules(): + if isinstance(m, nn.Linear): + trunc_normal_init(m, std=.02, bias=0.) + elif isinstance(m, nn.LayerNorm): + constant_init(m, val=1.0, bias=0.) + else: + assert 'checkpoint' in self.init_cfg, f'Only support ' \ + f'specify `Pretrained` in ' \ + f'`init_cfg` in ' \ + f'{self.__class__.__name__} ' + ckpt = CheckpointLoader.load_checkpoint( + self.init_cfg['checkpoint'], logger=None, map_location='cpu') + if 'state_dict' in ckpt: + _state_dict = ckpt['state_dict'] + elif 'model' in ckpt: + _state_dict = ckpt['model'] + else: + _state_dict = ckpt + + state_dict = OrderedDict() + for k, v in _state_dict.items(): + if k.startswith('backbone.'): + state_dict[k[9:]] = v + else: + state_dict[k] = v + + # strip prefix of state_dict + if list(state_dict.keys())[0].startswith('module.'): + state_dict = {k[7:]: v for k, v in state_dict.items()} + + # reshape absolute position embedding + if state_dict.get('absolute_pos_embed') is not None: + absolute_pos_embed = state_dict['absolute_pos_embed'] + N1, L, C1 = absolute_pos_embed.size() + N2, C2, H, W = self.absolute_pos_embed.size() + if N1 != N2 or C1 != C2 or L != H * W: + print_log('Error in loading absolute_pos_embed, pass') + else: + state_dict['absolute_pos_embed'] = absolute_pos_embed.view( + N2, H, W, C2).permute(0, 3, 1, 2).contiguous() + + # interpolate position bias table if needed + relative_position_bias_table_keys = [ + k for k in state_dict.keys() + if 'relative_position_bias_table' in k + ] + for table_key in relative_position_bias_table_keys: + table_pretrained = state_dict[table_key] + if table_key in self.state_dict(): + table_current = self.state_dict()[table_key] + L1, nH1 = table_pretrained.size() + L2, nH2 = table_current.size() + if nH1 != nH2: + print_log(f'Error in loading {table_key}, pass') + elif L1 != L2: + S1 = int(L1**0.5) + S2 = int(L2**0.5) + table_pretrained_resized = F.interpolate( + table_pretrained.permute(1, 0).reshape( + 1, nH1, S1, S1), + size=(S2, S2), + mode='bicubic') + state_dict[table_key] = table_pretrained_resized.view( + nH2, L2).permute(1, 0).contiguous() + + # load state_dict + self.load_state_dict(state_dict, strict=False) + + def forward(self, x): + x, hw_shape = self.patch_embed(x) + + if self.use_abs_pos_embed: + x = x + self.absolute_pos_embed + x = self.drop_after_pos(x) + + outs = [] + for i, stage in enumerate(self.stages): + x, hw_shape, out, out_hw_shape = stage(x, hw_shape) + if i in self.out_indices: + norm_layer = getattr(self, f'norm{i}') + out = norm_layer(out) + out = out.view(-1, *out_hw_shape, + self.num_features[i]).permute(0, 3, 1, + 2).contiguous() + outs.append(out) + + return outs diff --git a/third-party/InterFormer/mmseg/models/backbones/timm_backbone.py b/third-party/InterFormer/mmseg/models/backbones/timm_backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..1eef302bddeac3cee71412bcb481b68b796e515f --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/timm_backbone.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +try: + import timm +except ImportError: + timm = None + +from mmengine.model import BaseModule +from mmengine.registry import MODELS as MMENGINE_MODELS + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class TIMMBackbone(BaseModule): + """Wrapper to use backbones from timm library. More details can be found in + `timm `_ . + + Args: + model_name (str): Name of timm model to instantiate. + pretrained (bool): Load pretrained weights if True. + checkpoint_path (str): Path of checkpoint to load after + model is initialized. + in_channels (int): Number of input image channels. Default: 3. + init_cfg (dict, optional): Initialization config dict + **kwargs: Other timm & model specific arguments. + """ + + def __init__( + self, + model_name, + features_only=True, + pretrained=True, + checkpoint_path='', + in_channels=3, + init_cfg=None, + **kwargs, + ): + if timm is None: + raise RuntimeError('timm is not installed') + super().__init__(init_cfg) + if 'norm_layer' in kwargs: + kwargs['norm_layer'] = MMENGINE_MODELS.get(kwargs['norm_layer']) + self.timm_model = timm.create_model( + model_name=model_name, + features_only=features_only, + pretrained=pretrained, + in_chans=in_channels, + checkpoint_path=checkpoint_path, + **kwargs, + ) + + # Make unused parameters None + self.timm_model.global_pool = None + self.timm_model.fc = None + self.timm_model.classifier = None + + # Hack to use pretrained weights from timm + if pretrained or checkpoint_path: + self._is_init = True + + def forward(self, x): + features = self.timm_model(x) + return features diff --git a/third-party/InterFormer/mmseg/models/backbones/twins.py b/third-party/InterFormer/mmseg/models/backbones/twins.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a6eea795cf53bee6b52ece80d5d90ecc969970 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/twins.py @@ -0,0 +1,588 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +import warnings + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import build_norm_layer +from mmcv.cnn.bricks.drop import build_dropout +from mmcv.cnn.bricks.transformer import FFN +from mmengine.model import BaseModule, ModuleList +from mmengine.model.weight_init import (constant_init, normal_init, + trunc_normal_init) +from torch.nn.modules.batchnorm import _BatchNorm + +from mmseg.models.backbones.mit import EfficientMultiheadAttention +from mmseg.registry import MODELS +from ..utils.embed import PatchEmbed + + +class GlobalSubsampledAttention(EfficientMultiheadAttention): + """Global Sub-sampled Attention (Spatial Reduction Attention) + + This module is modified from EfficientMultiheadAttention, + which is a module from mmseg.models.backbones.mit.py. + Specifically, there is no difference between + `GlobalSubsampledAttention` and `EfficientMultiheadAttention`, + `GlobalSubsampledAttention` is built as a brand new class + because it is renamed as `Global sub-sampled attention (GSA)` + in paper. + + + Args: + embed_dims (int): The embedding dimension. + num_heads (int): Parallel attention heads. + attn_drop (float): A Dropout layer on attn_output_weights. + Default: 0.0. + proj_drop (float): A Dropout layer after `nn.MultiheadAttention`. + Default: 0.0. + dropout_layer (obj:`ConfigDict`): The dropout_layer used + when adding the shortcut. Default: None. + batch_first (bool): Key, Query and Value are shape of + (batch, n, embed_dims) + or (n, batch, embed_dims). Default: False. + qkv_bias (bool): enable bias for qkv if True. Default: True. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + sr_ratio (int): The ratio of spatial reduction of GSA of PCPVT. + Default: 1. + init_cfg (dict, optional): The Config for initialization. + Defaults to None. + """ + + def __init__(self, + embed_dims, + num_heads, + attn_drop=0., + proj_drop=0., + dropout_layer=None, + batch_first=True, + qkv_bias=True, + norm_cfg=dict(type='LN'), + sr_ratio=1, + init_cfg=None): + super().__init__( + embed_dims, + num_heads, + attn_drop=attn_drop, + proj_drop=proj_drop, + dropout_layer=dropout_layer, + batch_first=batch_first, + qkv_bias=qkv_bias, + norm_cfg=norm_cfg, + sr_ratio=sr_ratio, + init_cfg=init_cfg) + + +class GSAEncoderLayer(BaseModule): + """Implements one encoder layer with GSA. + + Args: + embed_dims (int): The feature dimension. + num_heads (int): Parallel attention heads. + feedforward_channels (int): The hidden dimension for FFNs. + drop_rate (float): Probability of an element to be zeroed + after the feed forward layer. Default: 0.0. + attn_drop_rate (float): The drop out rate for attention layer. + Default: 0.0. + drop_path_rate (float): Stochastic depth rate. Default 0.0. + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + qkv_bias (bool): Enable bias for qkv if True. Default: True + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + sr_ratio (float): Kernel_size of conv in Attention modules. Default: 1. + init_cfg (dict, optional): The Config for initialization. + Defaults to None. + """ + + def __init__(self, + embed_dims, + num_heads, + feedforward_channels, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + num_fcs=2, + qkv_bias=True, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + sr_ratio=1., + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + self.norm1 = build_norm_layer(norm_cfg, embed_dims, postfix=1)[1] + self.attn = GlobalSubsampledAttention( + embed_dims=embed_dims, + num_heads=num_heads, + attn_drop=attn_drop_rate, + proj_drop=drop_rate, + dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), + qkv_bias=qkv_bias, + norm_cfg=norm_cfg, + sr_ratio=sr_ratio) + + self.norm2 = build_norm_layer(norm_cfg, embed_dims, postfix=2)[1] + self.ffn = FFN( + embed_dims=embed_dims, + feedforward_channels=feedforward_channels, + num_fcs=num_fcs, + ffn_drop=drop_rate, + dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), + act_cfg=act_cfg, + add_identity=False) + + self.drop_path = build_dropout( + dict(type='DropPath', drop_prob=drop_path_rate) + ) if drop_path_rate > 0. else nn.Identity() + + def forward(self, x, hw_shape): + x = x + self.drop_path(self.attn(self.norm1(x), hw_shape, identity=0.)) + x = x + self.drop_path(self.ffn(self.norm2(x))) + return x + + +class LocallyGroupedSelfAttention(BaseModule): + """Locally-grouped Self Attention (LSA) module. + + Args: + embed_dims (int): Number of input channels. + num_heads (int): Number of attention heads. Default: 8 + qkv_bias (bool, optional): If True, add a learnable bias to q, k, v. + Default: False. + qk_scale (float | None, optional): Override default qk scale of + head_dim ** -0.5 if set. Default: None. + attn_drop_rate (float, optional): Dropout ratio of attention weight. + Default: 0.0 + proj_drop_rate (float, optional): Dropout ratio of output. Default: 0. + window_size(int): Window size of LSA. Default: 1. + init_cfg (dict, optional): The Config for initialization. + Defaults to None. + """ + + def __init__(self, + embed_dims, + num_heads=8, + qkv_bias=False, + qk_scale=None, + attn_drop_rate=0., + proj_drop_rate=0., + window_size=1, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + assert embed_dims % num_heads == 0, f'dim {embed_dims} should be ' \ + f'divided by num_heads ' \ + f'{num_heads}.' + self.embed_dims = embed_dims + self.num_heads = num_heads + head_dim = embed_dims // num_heads + self.scale = qk_scale or head_dim**-0.5 + + self.qkv = nn.Linear(embed_dims, embed_dims * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop_rate) + self.proj = nn.Linear(embed_dims, embed_dims) + self.proj_drop = nn.Dropout(proj_drop_rate) + self.window_size = window_size + + def forward(self, x, hw_shape): + b, n, c = x.shape + h, w = hw_shape + x = x.view(b, h, w, c) + + # pad feature maps to multiples of Local-groups + pad_l = pad_t = 0 + pad_r = (self.window_size - w % self.window_size) % self.window_size + pad_b = (self.window_size - h % self.window_size) % self.window_size + x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) + + # calculate attention mask for LSA + Hp, Wp = x.shape[1:-1] + _h, _w = Hp // self.window_size, Wp // self.window_size + mask = torch.zeros((1, Hp, Wp), device=x.device) + mask[:, -pad_b:, :].fill_(1) + mask[:, :, -pad_r:].fill_(1) + + # [B, _h, _w, window_size, window_size, C] + x = x.reshape(b, _h, self.window_size, _w, self.window_size, + c).transpose(2, 3) + mask = mask.reshape(1, _h, self.window_size, _w, + self.window_size).transpose(2, 3).reshape( + 1, _h * _w, + self.window_size * self.window_size) + # [1, _h*_w, window_size*window_size, window_size*window_size] + attn_mask = mask.unsqueeze(2) - mask.unsqueeze(3) + attn_mask = attn_mask.masked_fill(attn_mask != 0, + float(-1000.0)).masked_fill( + attn_mask == 0, float(0.0)) + + # [3, B, _w*_h, nhead, window_size*window_size, dim] + qkv = self.qkv(x).reshape(b, _h * _w, + self.window_size * self.window_size, 3, + self.num_heads, c // self.num_heads).permute( + 3, 0, 1, 4, 2, 5) + q, k, v = qkv[0], qkv[1], qkv[2] + # [B, _h*_w, n_head, window_size*window_size, window_size*window_size] + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn + attn_mask.unsqueeze(2) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + attn = (attn @ v).transpose(2, 3).reshape(b, _h, _w, self.window_size, + self.window_size, c) + x = attn.transpose(2, 3).reshape(b, _h * self.window_size, + _w * self.window_size, c) + if pad_r > 0 or pad_b > 0: + x = x[:, :h, :w, :].contiguous() + + x = x.reshape(b, n, c) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class LSAEncoderLayer(BaseModule): + """Implements one encoder layer in Twins-SVT. + + Args: + embed_dims (int): The feature dimension. + num_heads (int): Parallel attention heads. + feedforward_channels (int): The hidden dimension for FFNs. + drop_rate (float): Probability of an element to be zeroed + after the feed forward layer. Default: 0.0. + attn_drop_rate (float, optional): Dropout ratio of attention weight. + Default: 0.0 + drop_path_rate (float): Stochastic depth rate. Default 0.0. + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + qkv_bias (bool): Enable bias for qkv if True. Default: True + qk_scale (float | None, optional): Override default qk scale of + head_dim ** -0.5 if set. Default: None. + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + window_size (int): Window size of LSA. Default: 1. + init_cfg (dict, optional): The Config for initialization. + Defaults to None. + """ + + def __init__(self, + embed_dims, + num_heads, + feedforward_channels, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + num_fcs=2, + qkv_bias=True, + qk_scale=None, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + window_size=1, + init_cfg=None): + + super().__init__(init_cfg=init_cfg) + + self.norm1 = build_norm_layer(norm_cfg, embed_dims, postfix=1)[1] + self.attn = LocallyGroupedSelfAttention(embed_dims, num_heads, + qkv_bias, qk_scale, + attn_drop_rate, drop_rate, + window_size) + + self.norm2 = build_norm_layer(norm_cfg, embed_dims, postfix=2)[1] + self.ffn = FFN( + embed_dims=embed_dims, + feedforward_channels=feedforward_channels, + num_fcs=num_fcs, + ffn_drop=drop_rate, + dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), + act_cfg=act_cfg, + add_identity=False) + + self.drop_path = build_dropout( + dict(type='DropPath', drop_prob=drop_path_rate) + ) if drop_path_rate > 0. else nn.Identity() + + def forward(self, x, hw_shape): + x = x + self.drop_path(self.attn(self.norm1(x), hw_shape)) + x = x + self.drop_path(self.ffn(self.norm2(x))) + return x + + +class ConditionalPositionEncoding(BaseModule): + """The Conditional Position Encoding (CPE) module. + + The CPE is the implementation of 'Conditional Positional Encodings + for Vision Transformers '_. + + Args: + in_channels (int): Number of input channels. + embed_dims (int): The feature dimension. Default: 768. + stride (int): Stride of conv layer. Default: 1. + """ + + def __init__(self, in_channels, embed_dims=768, stride=1, init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.proj = nn.Conv2d( + in_channels, + embed_dims, + kernel_size=3, + stride=stride, + padding=1, + bias=True, + groups=embed_dims) + self.stride = stride + + def forward(self, x, hw_shape): + b, n, c = x.shape + h, w = hw_shape + feat_token = x + cnn_feat = feat_token.transpose(1, 2).view(b, c, h, w) + if self.stride == 1: + x = self.proj(cnn_feat) + cnn_feat + else: + x = self.proj(cnn_feat) + x = x.flatten(2).transpose(1, 2) + return x + + +@MODELS.register_module() +class PCPVT(BaseModule): + """The backbone of Twins-PCPVT. + + This backbone is the implementation of `Twins: Revisiting the Design + of Spatial Attention in Vision Transformers + `_. + + Args: + in_channels (int): Number of input channels. Default: 3. + embed_dims (list): Embedding dimension. Default: [64, 128, 256, 512]. + patch_sizes (list): The patch sizes. Default: [4, 2, 2, 2]. + strides (list): The strides. Default: [4, 2, 2, 2]. + num_heads (int): Number of attention heads. Default: [1, 2, 4, 8]. + mlp_ratios (int): Ratio of mlp hidden dim to embedding dim. + Default: [4, 4, 4, 4]. + out_indices (tuple[int]): Output from which stages. + Default: (0, 1, 2, 3). + qkv_bias (bool): Enable bias for qkv if True. Default: False. + drop_rate (float): Probability of an element to be zeroed. + Default 0. + attn_drop_rate (float): The drop out rate for attention layer. + Default 0.0 + drop_path_rate (float): Stochastic depth rate. Default 0.0 + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN') + depths (list): Depths of each stage. Default [3, 4, 6, 3] + sr_ratios (list): Kernel_size of conv in each Attn module in + Transformer encoder layer. Default: [8, 4, 2, 1]. + norm_after_stage(bool): Add extra norm. Default False. + init_cfg (dict, optional): The Config for initialization. + Defaults to None. + """ + + def __init__(self, + in_channels=3, + embed_dims=[64, 128, 256, 512], + patch_sizes=[4, 2, 2, 2], + strides=[4, 2, 2, 2], + num_heads=[1, 2, 4, 8], + mlp_ratios=[4, 4, 4, 4], + out_indices=(0, 1, 2, 3), + qkv_bias=False, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + norm_cfg=dict(type='LN'), + depths=[3, 4, 6, 3], + sr_ratios=[8, 4, 2, 1], + norm_after_stage=False, + pretrained=None, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be set at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is not None: + raise TypeError('pretrained must be a str or None') + self.depths = depths + + # patch_embed + self.patch_embeds = ModuleList() + self.position_encoding_drops = ModuleList() + self.layers = ModuleList() + + for i in range(len(depths)): + self.patch_embeds.append( + PatchEmbed( + in_channels=in_channels if i == 0 else embed_dims[i - 1], + embed_dims=embed_dims[i], + conv_type='Conv2d', + kernel_size=patch_sizes[i], + stride=strides[i], + padding='corner', + norm_cfg=norm_cfg)) + + self.position_encoding_drops.append(nn.Dropout(p=drop_rate)) + + self.position_encodings = ModuleList([ + ConditionalPositionEncoding(embed_dim, embed_dim) + for embed_dim in embed_dims + ]) + + # transformer encoder + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) + ] # stochastic depth decay rule + cur = 0 + + for k in range(len(depths)): + _block = ModuleList([ + GSAEncoderLayer( + embed_dims=embed_dims[k], + num_heads=num_heads[k], + feedforward_channels=mlp_ratios[k] * embed_dims[k], + attn_drop_rate=attn_drop_rate, + drop_rate=drop_rate, + drop_path_rate=dpr[cur + i], + num_fcs=2, + qkv_bias=qkv_bias, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + sr_ratio=sr_ratios[k]) for i in range(depths[k]) + ]) + self.layers.append(_block) + cur += depths[k] + + self.norm_name, norm = build_norm_layer( + norm_cfg, embed_dims[-1], postfix=1) + + self.out_indices = out_indices + self.norm_after_stage = norm_after_stage + if self.norm_after_stage: + self.norm_list = ModuleList() + for dim in embed_dims: + self.norm_list.append(build_norm_layer(norm_cfg, dim)[1]) + + def init_weights(self): + if self.init_cfg is not None: + super().init_weights() + else: + for m in self.modules(): + if isinstance(m, nn.Linear): + trunc_normal_init(m, std=.02, bias=0.) + elif isinstance(m, (_BatchNorm, nn.GroupNorm, nn.LayerNorm)): + constant_init(m, val=1.0, bias=0.) + elif isinstance(m, nn.Conv2d): + fan_out = m.kernel_size[0] * m.kernel_size[ + 1] * m.out_channels + fan_out //= m.groups + normal_init( + m, mean=0, std=math.sqrt(2.0 / fan_out), bias=0) + + def forward(self, x): + outputs = list() + + b = x.shape[0] + + for i in range(len(self.depths)): + x, hw_shape = self.patch_embeds[i](x) + h, w = hw_shape + x = self.position_encoding_drops[i](x) + for j, blk in enumerate(self.layers[i]): + x = blk(x, hw_shape) + if j == 0: + x = self.position_encodings[i](x, hw_shape) + if self.norm_after_stage: + x = self.norm_list[i](x) + x = x.reshape(b, h, w, -1).permute(0, 3, 1, 2).contiguous() + + if i in self.out_indices: + outputs.append(x) + + return tuple(outputs) + + +@MODELS.register_module() +class SVT(PCPVT): + """The backbone of Twins-SVT. + + This backbone is the implementation of `Twins: Revisiting the Design + of Spatial Attention in Vision Transformers + `_. + + Args: + in_channels (int): Number of input channels. Default: 3. + embed_dims (list): Embedding dimension. Default: [64, 128, 256, 512]. + patch_sizes (list): The patch sizes. Default: [4, 2, 2, 2]. + strides (list): The strides. Default: [4, 2, 2, 2]. + num_heads (int): Number of attention heads. Default: [1, 2, 4]. + mlp_ratios (int): Ratio of mlp hidden dim to embedding dim. + Default: [4, 4, 4]. + out_indices (tuple[int]): Output from which stages. + Default: (0, 1, 2, 3). + qkv_bias (bool): Enable bias for qkv if True. Default: False. + drop_rate (float): Dropout rate. Default 0. + attn_drop_rate (float): Dropout ratio of attention weight. + Default 0.0 + drop_path_rate (float): Stochastic depth rate. Default 0.2. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN') + depths (list): Depths of each stage. Default [4, 4, 4]. + sr_ratios (list): Kernel_size of conv in each Attn module in + Transformer encoder layer. Default: [4, 2, 1]. + windiow_sizes (list): Window size of LSA. Default: [7, 7, 7], + input_features_slice(bool): Input features need slice. Default: False. + norm_after_stage(bool): Add extra norm. Default False. + strides (list): Strides in patch-Embedding modules. Default: (2, 2, 2) + init_cfg (dict, optional): The Config for initialization. + Defaults to None. + """ + + def __init__(self, + in_channels=3, + embed_dims=[64, 128, 256], + patch_sizes=[4, 2, 2, 2], + strides=[4, 2, 2, 2], + num_heads=[1, 2, 4], + mlp_ratios=[4, 4, 4], + out_indices=(0, 1, 2, 3), + qkv_bias=False, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0.2, + norm_cfg=dict(type='LN'), + depths=[4, 4, 4], + sr_ratios=[4, 2, 1], + windiow_sizes=[7, 7, 7], + norm_after_stage=True, + pretrained=None, + init_cfg=None): + super().__init__(in_channels, embed_dims, patch_sizes, strides, + num_heads, mlp_ratios, out_indices, qkv_bias, + drop_rate, attn_drop_rate, drop_path_rate, norm_cfg, + depths, sr_ratios, norm_after_stage, pretrained, + init_cfg) + # transformer encoder + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) + ] # stochastic depth decay rule + + for k in range(len(depths)): + for i in range(depths[k]): + if i % 2 == 0: + self.layers[k][i] = \ + LSAEncoderLayer( + embed_dims=embed_dims[k], + num_heads=num_heads[k], + feedforward_channels=mlp_ratios[k] * embed_dims[k], + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=dpr[sum(depths[:k])+i], + qkv_bias=qkv_bias, + window_size=windiow_sizes[k]) diff --git a/third-party/InterFormer/mmseg/models/backbones/unet.py b/third-party/InterFormer/mmseg/models/backbones/unet.py new file mode 100644 index 0000000000000000000000000000000000000000..545921db8e14668e454f5834f9a1618fe0c04ffe --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/unet.py @@ -0,0 +1,436 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch.nn as nn +import torch.utils.checkpoint as cp +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer +from mmengine.model import BaseModule +from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm + +from mmseg.registry import MODELS +from ..utils import UpConvBlock, Upsample + + +class BasicConvBlock(nn.Module): + """Basic convolutional block for UNet. + + This module consists of several plain convolutional layers. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + num_convs (int): Number of convolutional layers. Default: 2. + stride (int): Whether use stride convolution to downsample + the input feature map. If stride=2, it only uses stride convolution + in the first convolutional layer to downsample the input feature + map. Options are 1 or 2. Default: 1. + dilation (int): Whether use dilated convolution to expand the + receptive field. Set dilation rate of each convolutional layer and + the dilation rate of the first convolutional layer is always 1. + Default: 1. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + conv_cfg (dict | None): Config dict for convolution layer. + Default: None. + norm_cfg (dict | None): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict | None): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU'). + dcn (bool): Use deformable convolution in convolutional layer or not. + Default: None. + plugins (dict): plugins for convolutional layers. Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + num_convs=2, + stride=1, + dilation=1, + with_cp=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + dcn=None, + plugins=None): + super().__init__() + assert dcn is None, 'Not implemented yet.' + assert plugins is None, 'Not implemented yet.' + + self.with_cp = with_cp + convs = [] + for i in range(num_convs): + convs.append( + ConvModule( + in_channels=in_channels if i == 0 else out_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride if i == 0 else 1, + dilation=1 if i == 0 else dilation, + padding=1 if i == 0 else dilation, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + self.convs = nn.Sequential(*convs) + + def forward(self, x): + """Forward function.""" + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(self.convs, x) + else: + out = self.convs(x) + return out + + +@MODELS.register_module() +class DeconvModule(nn.Module): + """Deconvolution upsample module in decoder for UNet (2X upsample). + + This module uses deconvolution to upsample feature map in the decoder + of UNet. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + norm_cfg (dict | None): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict | None): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU'). + kernel_size (int): Kernel size of the convolutional layer. Default: 4. + """ + + def __init__(self, + in_channels, + out_channels, + with_cp=False, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + *, + kernel_size=4, + scale_factor=2): + super().__init__() + + assert (kernel_size - scale_factor >= 0) and\ + (kernel_size - scale_factor) % 2 == 0,\ + f'kernel_size should be greater than or equal to scale_factor '\ + f'and (kernel_size - scale_factor) should be even numbers, '\ + f'while the kernel size is {kernel_size} and scale_factor is '\ + f'{scale_factor}.' + + stride = scale_factor + padding = (kernel_size - scale_factor) // 2 + self.with_cp = with_cp + deconv = nn.ConvTranspose2d( + in_channels, + out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding) + + norm_name, norm = build_norm_layer(norm_cfg, out_channels) + activate = build_activation_layer(act_cfg) + self.deconv_upsamping = nn.Sequential(deconv, norm, activate) + + def forward(self, x): + """Forward function.""" + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(self.deconv_upsamping, x) + else: + out = self.deconv_upsamping(x) + return out + + +@MODELS.register_module() +class InterpConv(nn.Module): + """Interpolation upsample module in decoder for UNet. + + This module uses interpolation to upsample feature map in the decoder + of UNet. It consists of one interpolation upsample layer and one + convolutional layer. It can be one interpolation upsample layer followed + by one convolutional layer (conv_first=False) or one convolutional layer + followed by one interpolation upsample layer (conv_first=True). + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + norm_cfg (dict | None): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict | None): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU'). + conv_cfg (dict | None): Config dict for convolution layer. + Default: None. + conv_first (bool): Whether convolutional layer or interpolation + upsample layer first. Default: False. It means interpolation + upsample layer followed by one convolutional layer. + kernel_size (int): Kernel size of the convolutional layer. Default: 1. + stride (int): Stride of the convolutional layer. Default: 1. + padding (int): Padding of the convolutional layer. Default: 1. + upsample_cfg (dict): Interpolation config of the upsample layer. + Default: dict( + scale_factor=2, mode='bilinear', align_corners=False). + """ + + def __init__(self, + in_channels, + out_channels, + with_cp=False, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + *, + conv_cfg=None, + conv_first=False, + kernel_size=1, + stride=1, + padding=0, + upsample_cfg=dict( + scale_factor=2, mode='bilinear', align_corners=False)): + super().__init__() + + self.with_cp = with_cp + conv = ConvModule( + in_channels, + out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + upsample = Upsample(**upsample_cfg) + if conv_first: + self.interp_upsample = nn.Sequential(conv, upsample) + else: + self.interp_upsample = nn.Sequential(upsample, conv) + + def forward(self, x): + """Forward function.""" + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(self.interp_upsample, x) + else: + out = self.interp_upsample(x) + return out + + +@MODELS.register_module() +class UNet(BaseModule): + """UNet backbone. + + This backbone is the implementation of `U-Net: Convolutional Networks + for Biomedical Image Segmentation `_. + + Args: + in_channels (int): Number of input image channels. Default" 3. + base_channels (int): Number of base channels of each stage. + The output channels of the first stage. Default: 64. + num_stages (int): Number of stages in encoder, normally 5. Default: 5. + strides (Sequence[int 1 | 2]): Strides of each stage in encoder. + len(strides) is equal to num_stages. Normally the stride of the + first stage in encoder is 1. If strides[i]=2, it uses stride + convolution to downsample in the correspondence encoder stage. + Default: (1, 1, 1, 1, 1). + enc_num_convs (Sequence[int]): Number of convolutional layers in the + convolution block of the correspondence encoder stage. + Default: (2, 2, 2, 2, 2). + dec_num_convs (Sequence[int]): Number of convolutional layers in the + convolution block of the correspondence decoder stage. + Default: (2, 2, 2, 2). + downsamples (Sequence[int]): Whether use MaxPool to downsample the + feature map after the first stage of encoder + (stages: [1, num_stages)). If the correspondence encoder stage use + stride convolution (strides[i]=2), it will never use MaxPool to + downsample, even downsamples[i-1]=True. + Default: (True, True, True, True). + enc_dilations (Sequence[int]): Dilation rate of each stage in encoder. + Default: (1, 1, 1, 1, 1). + dec_dilations (Sequence[int]): Dilation rate of each stage in decoder. + Default: (1, 1, 1, 1). + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + conv_cfg (dict | None): Config dict for convolution layer. + Default: None. + norm_cfg (dict | None): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict | None): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU'). + upsample_cfg (dict): The upsample config of the upsample module in + decoder. Default: dict(type='InterpConv'). + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + dcn (bool): Use deformable convolution in convolutional layer or not. + Default: None. + plugins (dict): plugins for convolutional layers. Default: None. + pretrained (str, optional): model pretrained path. Default: None + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None + + Notice: + The input image size should be divisible by the whole downsample rate + of the encoder. More detail of the whole downsample rate can be found + in UNet._check_input_divisible. + """ + + def __init__(self, + in_channels=3, + base_channels=64, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1), + with_cp=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + upsample_cfg=dict(type='InterpConv'), + norm_eval=False, + dcn=None, + plugins=None, + pretrained=None, + init_cfg=None): + super().__init__(init_cfg) + + self.pretrained = pretrained + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be setting at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is a deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is None: + if init_cfg is None: + self.init_cfg = [ + dict(type='Kaiming', layer='Conv2d'), + dict( + type='Constant', + val=1, + layer=['_BatchNorm', 'GroupNorm']) + ] + else: + raise TypeError('pretrained must be a str or None') + + assert dcn is None, 'Not implemented yet.' + assert plugins is None, 'Not implemented yet.' + assert len(strides) == num_stages, \ + 'The length of strides should be equal to num_stages, '\ + f'while the strides is {strides}, the length of '\ + f'strides is {len(strides)}, and the num_stages is '\ + f'{num_stages}.' + assert len(enc_num_convs) == num_stages, \ + 'The length of enc_num_convs should be equal to num_stages, '\ + f'while the enc_num_convs is {enc_num_convs}, the length of '\ + f'enc_num_convs is {len(enc_num_convs)}, and the num_stages is '\ + f'{num_stages}.' + assert len(dec_num_convs) == (num_stages-1), \ + 'The length of dec_num_convs should be equal to (num_stages-1), '\ + f'while the dec_num_convs is {dec_num_convs}, the length of '\ + f'dec_num_convs is {len(dec_num_convs)}, and the num_stages is '\ + f'{num_stages}.' + assert len(downsamples) == (num_stages-1), \ + 'The length of downsamples should be equal to (num_stages-1), '\ + f'while the downsamples is {downsamples}, the length of '\ + f'downsamples is {len(downsamples)}, and the num_stages is '\ + f'{num_stages}.' + assert len(enc_dilations) == num_stages, \ + 'The length of enc_dilations should be equal to num_stages, '\ + f'while the enc_dilations is {enc_dilations}, the length of '\ + f'enc_dilations is {len(enc_dilations)}, and the num_stages is '\ + f'{num_stages}.' + assert len(dec_dilations) == (num_stages-1), \ + 'The length of dec_dilations should be equal to (num_stages-1), '\ + f'while the dec_dilations is {dec_dilations}, the length of '\ + f'dec_dilations is {len(dec_dilations)}, and the num_stages is '\ + f'{num_stages}.' + self.num_stages = num_stages + self.strides = strides + self.downsamples = downsamples + self.norm_eval = norm_eval + self.base_channels = base_channels + + self.encoder = nn.ModuleList() + self.decoder = nn.ModuleList() + + for i in range(num_stages): + enc_conv_block = [] + if i != 0: + if strides[i] == 1 and downsamples[i - 1]: + enc_conv_block.append(nn.MaxPool2d(kernel_size=2)) + upsample = (strides[i] != 1 or downsamples[i - 1]) + self.decoder.append( + UpConvBlock( + conv_block=BasicConvBlock, + in_channels=base_channels * 2**i, + skip_channels=base_channels * 2**(i - 1), + out_channels=base_channels * 2**(i - 1), + num_convs=dec_num_convs[i - 1], + stride=1, + dilation=dec_dilations[i - 1], + with_cp=with_cp, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + upsample_cfg=upsample_cfg if upsample else None, + dcn=None, + plugins=None)) + + enc_conv_block.append( + BasicConvBlock( + in_channels=in_channels, + out_channels=base_channels * 2**i, + num_convs=enc_num_convs[i], + stride=strides[i], + dilation=enc_dilations[i], + with_cp=with_cp, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + dcn=None, + plugins=None)) + self.encoder.append(nn.Sequential(*enc_conv_block)) + in_channels = base_channels * 2**i + + def forward(self, x): + self._check_input_divisible(x) + enc_outs = [] + for enc in self.encoder: + x = enc(x) + enc_outs.append(x) + dec_outs = [x] + for i in reversed(range(len(self.decoder))): + x = self.decoder[i](enc_outs[i], x) + dec_outs.append(x) + + return dec_outs + + def train(self, mode=True): + """Convert the model into training mode while keep normalization layer + freezed.""" + super().train(mode) + if mode and self.norm_eval: + for m in self.modules(): + # trick: eval have effect on BatchNorm only + if isinstance(m, _BatchNorm): + m.eval() + + def _check_input_divisible(self, x): + h, w = x.shape[-2:] + whole_downsample_rate = 1 + for i in range(1, self.num_stages): + if self.strides[i] == 2 or self.downsamples[i - 1]: + whole_downsample_rate *= 2 + assert (h % whole_downsample_rate == 0) \ + and (w % whole_downsample_rate == 0),\ + f'The input image size {(h, w)} should be divisible by the whole '\ + f'downsample rate {whole_downsample_rate}, when num_stages is '\ + f'{self.num_stages}, strides is {self.strides}, and downsamples '\ + f'is {self.downsamples}.' diff --git a/third-party/InterFormer/mmseg/models/backbones/vit.py b/third-party/InterFormer/mmseg/models/backbones/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..dd0f688fcc46680b13904a26f14269b3d19d6ce3 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/vit.py @@ -0,0 +1,501 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +import warnings + +import torch +import torch.nn as nn +import torch.utils.checkpoint as cp +from mmcv.cnn import build_norm_layer +from mmcv.cnn.bricks.transformer import FFN, MultiheadAttention +from mmengine.logging import print_log +from mmengine.model import BaseModule, ModuleList +from mmengine.model.weight_init import (constant_init, kaiming_init, + trunc_normal_) +from mmengine.runner.checkpoint import CheckpointLoader, load_state_dict +from torch.nn.modules.batchnorm import _BatchNorm +from torch.nn.modules.utils import _pair as to_2tuple + +from mmseg.registry import MODELS +from ..utils import PatchEmbed, resize + + +class TransformerEncoderLayer(BaseModule): + """Implements one encoder layer in Vision Transformer. + + Args: + embed_dims (int): The feature dimension. + num_heads (int): Parallel attention heads. + feedforward_channels (int): The hidden dimension for FFNs. + drop_rate (float): Probability of an element to be zeroed + after the feed forward layer. Default: 0.0. + attn_drop_rate (float): The drop out rate for attention layer. + Default: 0.0. + drop_path_rate (float): stochastic depth rate. Default 0.0. + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + qkv_bias (bool): enable bias for qkv if True. Default: True + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + batch_first (bool): Key, Query and Value are shape of + (batch, n, embed_dim) + or (n, batch, embed_dim). Default: True. + with_cp (bool): Use checkpoint or not. Using checkpoint will save + some memory while slowing down the training speed. Default: False. + """ + + def __init__(self, + embed_dims, + num_heads, + feedforward_channels, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + num_fcs=2, + qkv_bias=True, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + batch_first=True, + attn_cfg=dict(), + ffn_cfg=dict(), + with_cp=False): + super().__init__() + + self.norm1_name, norm1 = build_norm_layer( + norm_cfg, embed_dims, postfix=1) + self.add_module(self.norm1_name, norm1) + + attn_cfg.update( + dict( + embed_dims=embed_dims, + num_heads=num_heads, + attn_drop=attn_drop_rate, + proj_drop=drop_rate, + batch_first=batch_first, + bias=qkv_bias)) + + self.build_attn(attn_cfg) + + self.norm2_name, norm2 = build_norm_layer( + norm_cfg, embed_dims, postfix=2) + self.add_module(self.norm2_name, norm2) + + ffn_cfg.update( + dict( + embed_dims=embed_dims, + feedforward_channels=feedforward_channels, + num_fcs=num_fcs, + ffn_drop=drop_rate, + dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate) + if drop_path_rate > 0 else None, + act_cfg=act_cfg)) + self.build_ffn(ffn_cfg) + self.with_cp = with_cp + + def build_attn(self, attn_cfg): + self.attn = MultiheadAttention(**attn_cfg) + + def build_ffn(self, ffn_cfg): + self.ffn = FFN(**ffn_cfg) + + @property + def norm1(self): + return getattr(self, self.norm1_name) + + @property + def norm2(self): + return getattr(self, self.norm2_name) + + def forward(self, x): + + def _inner_forward(x): + x = self.attn(self.norm1(x), identity=x) + x = self.ffn(self.norm2(x), identity=x) + return x + + if self.with_cp and x.requires_grad: + x = cp.checkpoint(_inner_forward, x) + else: + x = _inner_forward(x) + return x + + +@MODELS.register_module() +class VisionTransformer(BaseModule): + """Vision Transformer. + + This backbone is the implementation of `An Image is Worth 16x16 Words: + Transformers for Image Recognition at + Scale `_. + + Args: + img_size (int | tuple): Input image size. Default: 224. + patch_size (int): The patch size. Default: 16. + patch_pad (str | int | None): The padding method in patch embedding. + Default: 'corner'. + in_channels (int): Number of input channels. Default: 3. + embed_dims (int): embedding dimension. Default: 768. + num_layers (int): depth of transformer. Default: 12. + num_heads (int): number of attention heads. Default: 12. + mlp_ratio (int): ratio of mlp hidden dim to embedding dim. + Default: 4. + out_origin (bool): Whether to output the original input embedding. + Default: False + out_indices (list | tuple | int): Output from which stages. + Default: -1. + qkv_bias (bool): enable bias for qkv if True. Default: True. + drop_rate (float): Probability of an element to be zeroed. + Default 0.0 + attn_drop_rate (float): The drop out rate for attention layer. + Default 0.0 + drop_path_rate (float): stochastic depth rate. Default 0.0 + with_cls_token (bool): Whether concatenating class token into image + tokens as transformer input. Default: True. + output_cls_token (bool): Whether output the cls_token. If set True, + `with_cls_token` must be True. Default: False. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN') + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + patch_bias (dict): Whether use bias in convolution of PatchEmbed Block. + Default: True. + patch_norm (bool): Whether to add a norm in PatchEmbed Block. + Default: False. + pre_norm (bool): Whether to add a norm before Transformer Layers. + Default: False. + final_norm (bool): Whether to add a additional layer to normalize + final feature map. Default: False. + interpolate_mode (str): Select the interpolate mode for position + embeding vector resize. Default: bicubic. + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + norm_eval (bool): Whether to set norm layers to eval mode, namely, + freeze running stats (mean and var). Note: Effect on Batch Norm + and its variants only. Default: False. + with_cp (bool): Use checkpoint or not. Using checkpoint will save + some memory while slowing down the training speed. Default: False. + frozen_exclude (List): List of parameters that are not to be frozen. + Default: ["all"], "all" means there are no frozen parameters. + pretrained (str, optional): model pretrained path. Default: None. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + img_size=224, + patch_size=16, + patch_pad='corner', + in_channels=3, + embed_dims=768, + num_layers=12, + num_heads=12, + mlp_ratio=4, + out_origin=False, + out_indices=-1, + qkv_bias=True, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0., + with_cls_token=True, + output_cls_token=False, + norm_cfg=dict(type='LN'), + act_cfg=dict(type='GELU'), + patch_norm=False, + patch_bias=False, + pre_norm=False, + final_norm=False, + interpolate_mode='bicubic', + num_fcs=2, + norm_eval=False, + with_cp=False, + frozen_exclude=['all'], + pretrained=None, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + if isinstance(img_size, int): + img_size = to_2tuple(img_size) + elif isinstance(img_size, tuple): + if len(img_size) == 1: + img_size = to_2tuple(img_size[0]) + assert len(img_size) == 2, \ + f'The size of image should have length 1 or 2, ' \ + f'but got {len(img_size)}' + + if output_cls_token: + assert with_cls_token is True, f'with_cls_token must be True if' \ + f'set output_cls_token to True, but got {with_cls_token}' + + assert not (init_cfg and pretrained), \ + 'init_cfg and pretrained cannot be set at the same time' + if isinstance(pretrained, str): + warnings.warn('DeprecationWarning: pretrained is deprecated, ' + 'please use "init_cfg" instead') + self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) + elif pretrained is not None: + raise TypeError('pretrained must be a str or None') + + self.img_size = img_size + self.patch_size = patch_size + self.interpolate_mode = interpolate_mode + self.norm_eval = norm_eval + self.with_cp = with_cp + self.pretrained = pretrained + self.out_origin = out_origin + self.frozen_exclude = frozen_exclude + + self.patch_embed = PatchEmbed( + in_channels=in_channels, + embed_dims=embed_dims, + conv_type='Conv2d', + kernel_size=patch_size, + stride=patch_size, + padding=patch_pad, + bias=patch_bias, + norm_cfg=norm_cfg if patch_norm else None, + init_cfg=None, + ) + + num_patches = (img_size[0] // patch_size) * \ + (img_size[1] // patch_size) + + self.with_cls_token = with_cls_token + self.output_cls_token = output_cls_token + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dims)) + self.pos_embed = nn.Parameter( + torch.zeros(1, num_patches + 1, embed_dims)) + self.drop_after_pos = nn.Dropout(p=drop_rate) + self.pre_norm = pre_norm + + if self.pre_norm: + self.pre_ln_name, pre_ln = build_norm_layer( + norm_cfg, embed_dims, postfix='_pre') + self.add_module(self.pre_ln_name, pre_ln) + + if isinstance(out_indices, int): + if out_indices == -1: + out_indices = num_layers - 1 + self.out_indices = [out_indices] + elif isinstance(out_indices, list) or isinstance(out_indices, tuple): + self.out_indices = out_indices + else: + raise TypeError('out_indices must be type of int, list or tuple') + + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, num_layers) + ] # stochastic depth decay rule + + self.layers = ModuleList() + for i in range(num_layers): + self.layers.append( + TransformerEncoderLayer( + embed_dims=embed_dims, + num_heads=num_heads, + feedforward_channels=mlp_ratio * embed_dims, + attn_drop_rate=attn_drop_rate, + drop_rate=drop_rate, + drop_path_rate=dpr[i], + num_fcs=num_fcs, + qkv_bias=qkv_bias, + act_cfg=act_cfg, + norm_cfg=norm_cfg, + with_cp=with_cp, + batch_first=True)) + + self.final_norm = final_norm + if final_norm: + self.norm1_name, norm1 = build_norm_layer( + norm_cfg, embed_dims, postfix=1) + self.add_module(self.norm1_name, norm1) + + self._freeze() + + @property + def pre_ln(self): + return getattr(self, self.pre_ln_name) + + @property + def norm1(self): + return getattr(self, self.norm1_name) + + def init_weights(self): + if isinstance(self.init_cfg, dict) and \ + self.init_cfg.get('type') in ['Pretrained', 'Pretrained_Part']: + checkpoint = CheckpointLoader.load_checkpoint( + self.init_cfg['checkpoint'], logger=None, map_location='cpu') + + if self.init_cfg.get('type') == 'Pretrained': + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + + elif self.init_cfg.get('type') == 'Pretrained_Part': + state_dict = checkpoint.copy() + para_prefix = 'image_encoder' + prefix_len = len(para_prefix) + 1 + for k, v in checkpoint.items(): + state_dict.pop(k) + if para_prefix in k: + state_dict[k[prefix_len:]] = v + + if 'pos_embed' in state_dict.keys(): + if self.pos_embed.shape != state_dict['pos_embed'].shape: + print_log(msg=f'Resize the pos_embed shape from ' + f'{state_dict["pos_embed"].shape} to ' + f'{self.pos_embed.shape}') + h, w = self.img_size + pos_size = int( + math.sqrt(state_dict['pos_embed'].shape[1] - 1)) + state_dict['pos_embed'] = self.resize_pos_embed( + state_dict['pos_embed'], + (h // self.patch_size, w // self.patch_size), + (pos_size, pos_size), self.interpolate_mode) + + load_state_dict(self, state_dict, strict=False, logger=None) + elif self.init_cfg is not None: + super().init_weights() + else: + # We only implement the 'jax_impl' initialization implemented at + # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py#L353 # noqa: E501 + trunc_normal_(self.pos_embed, std=.02) + trunc_normal_(self.cls_token, std=.02) + for n, m in self.named_modules(): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if m.bias is not None: + if 'ffn' in n: + nn.init.normal_(m.bias, mean=0., std=1e-6) + else: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv2d): + kaiming_init(m, mode='fan_in', bias=0.) + elif isinstance(m, (_BatchNorm, nn.GroupNorm, nn.LayerNorm)): + constant_init(m, val=1.0, bias=0.) + + def _freeze(self): + if 'all' in self.frozen_exclude: + return + for name, param in self.named_parameters(): + if not any([exclude in name for exclude in self.frozen_exclude]): + param.requires_grad = False + + def _pos_embeding(self, patched_img, hw_shape, pos_embed): + """Positioning embeding method. + + Resize the pos_embed, if the input image size doesn't match + the training size. + Args: + patched_img (torch.Tensor): The patched image, it should be + shape of [B, L1, C]. + hw_shape (tuple): The downsampled image resolution. + pos_embed (torch.Tensor): The pos_embed weighs, it should be + shape of [B, L2, c]. + Return: + torch.Tensor: The pos encoded image feature. + """ + assert patched_img.ndim == 3 and pos_embed.ndim == 3, \ + 'the shapes of patched_img and pos_embed must be [B, L, C]' + x_len, pos_len = patched_img.shape[1], pos_embed.shape[1] + if x_len != pos_len: + if pos_len == (self.img_size[0] // self.patch_size) * ( + self.img_size[1] // self.patch_size) + 1: + pos_h = self.img_size[0] // self.patch_size + pos_w = self.img_size[1] // self.patch_size + else: + raise ValueError( + 'Unexpected shape of pos_embed, got {}.'.format( + pos_embed.shape)) + pos_embed = self.resize_pos_embed(pos_embed, hw_shape, + (pos_h, pos_w), + self.interpolate_mode) + return self.drop_after_pos(patched_img + pos_embed) + + @staticmethod + def resize_pos_embed(pos_embed, input_shpae, pos_shape, mode): + """Resize pos_embed weights. + + Resize pos_embed using bicubic interpolate method. + Args: + pos_embed (torch.Tensor): Position embedding weights. + input_shpae (tuple): Tuple for (downsampled input image height, + downsampled input image width). + pos_shape (tuple): The resolution of downsampled origin training + image. + mode (str): Algorithm used for upsampling: + ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` | + ``'trilinear'``. Default: ``'nearest'`` + Return: + torch.Tensor: The resized pos_embed of shape [B, L_new, C] + """ + assert pos_embed.ndim == 3, 'shape of pos_embed must be [B, L, C]' + pos_h, pos_w = pos_shape + cls_token_weight = pos_embed[:, 0] + pos_embed_weight = pos_embed[:, (-1 * pos_h * pos_w):] + pos_embed_weight = pos_embed_weight.reshape( + 1, pos_h, pos_w, pos_embed.shape[2]).permute(0, 3, 1, 2) + pos_embed_weight = resize( + pos_embed_weight, size=input_shpae, align_corners=False, mode=mode) + cls_token_weight = cls_token_weight.unsqueeze(1) + pos_embed_weight = torch.flatten(pos_embed_weight, 2).transpose(1, 2) + pos_embed = torch.cat((cls_token_weight, pos_embed_weight), dim=1) + return pos_embed + + def forward(self, inputs): + B = inputs.shape[0] + + x, hw_shape = self.patch_embed(inputs) + + # stole cls_tokens impl from Phil Wang, thanks + cls_tokens = self.cls_token.expand(B, -1, -1) + x = torch.cat((cls_tokens, x), dim=1) + x = self._pos_embeding(x, hw_shape, self.pos_embed) + + if not self.with_cls_token: + # Remove class token for transformer encoder input + x = x[:, 1:] + + if self.pre_norm: + x = self.pre_ln(x) + + outs = [] + if self.out_origin: + if self.with_cls_token: + # Remove class token and reshape token for decoder head + out = x[:, 1:] + else: + out = x + B, _, C = out.shape + out = out.reshape(B, hw_shape[0], hw_shape[1], + C).permute(0, 3, 1, 2).contiguous() + if self.output_cls_token: + out = [out, x[:, 0]] + outs.append(out) + + for i, layer in enumerate(self.layers): + x = layer(x) + if i == len(self.layers) - 1: + if self.final_norm: + x = self.norm1(x) + if i in self.out_indices: + if self.with_cls_token: + # Remove class token and reshape token for decoder head + out = x[:, 1:] + else: + out = x + B, _, C = out.shape + out = out.reshape(B, hw_shape[0], hw_shape[1], + C).permute(0, 3, 1, 2).contiguous() + if self.output_cls_token: + out = [out, x[:, 0]] + outs.append(out) + + return tuple(outs) + + def train(self, mode=True): + super().train(mode) + if mode and self.norm_eval: + for m in self.modules(): + if isinstance(m, nn.LayerNorm): + m.eval() diff --git a/third-party/InterFormer/mmseg/models/backbones/vpd.py b/third-party/InterFormer/mmseg/models/backbones/vpd.py new file mode 100644 index 0000000000000000000000000000000000000000..e0536d31c64f82fb66117d9ebd2161d5f2df57bd --- /dev/null +++ b/third-party/InterFormer/mmseg/models/backbones/vpd.py @@ -0,0 +1,395 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# ------------------------------------------------------------------------------ +# Adapted from https://github.com/wl-zhao/VPD/blob/main/vpd/models.py +# Original licence: MIT License +# ------------------------------------------------------------------------------ + +import math +from typing import List, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.model import BaseModule +from mmengine.runner import CheckpointLoader, load_checkpoint + +from mmseg.registry import MODELS +from mmseg.utils import ConfigType, OptConfigType + +try: + from ldm.modules.diffusionmodules.util import timestep_embedding + from ldm.util import instantiate_from_config + has_ldm = True +except ImportError: + has_ldm = False + + +def register_attention_control(model, controller): + """Registers a control function to manage attention within a model. + + Args: + model: The model to which attention is to be registered. + controller: The control function responsible for managing attention. + """ + + def ca_forward(self, place_in_unet): + """Custom forward method for attention. + + Args: + self: Reference to the current object. + place_in_unet: The location in UNet (down/mid/up). + + Returns: + The modified forward method. + """ + + def forward(x, context=None, mask=None): + h = self.heads + is_cross = context is not None + context = context or x # if context is None, use x + + q, k, v = self.to_q(x), self.to_k(context), self.to_v(context) + q, k, v = ( + tensor.view(tensor.shape[0] * h, tensor.shape[1], + tensor.shape[2] // h) for tensor in [q, k, v]) + + sim = torch.matmul(q, k.transpose(-2, -1)) * self.scale + + if mask is not None: + mask = mask.flatten(1).unsqueeze(1).repeat(h, 1, 1) + max_neg_value = -torch.finfo(sim.dtype).max + sim.masked_fill_(~mask, max_neg_value) + + attn = sim.softmax(dim=-1) + attn_mean = attn.view(h, attn.shape[0] // h, + *attn.shape[1:]).mean(0) + controller(attn_mean, is_cross, place_in_unet) + + out = torch.matmul(attn, v) + out = out.view(out.shape[0] // h, out.shape[1], out.shape[2] * h) + return self.to_out(out) + + return forward + + def register_recr(net_, count, place_in_unet): + """Recursive function to register the custom forward method to all + CrossAttention layers. + + Args: + net_: The network layer currently being processed. + count: The current count of layers processed. + place_in_unet: The location in UNet (down/mid/up). + + Returns: + The updated count of layers processed. + """ + if net_.__class__.__name__ == 'CrossAttention': + net_.forward = ca_forward(net_, place_in_unet) + return count + 1 + if hasattr(net_, 'children'): + return sum( + register_recr(child, 0, place_in_unet) + for child in net_.children()) + return count + + cross_att_count = sum( + register_recr(net[1], 0, place) for net, place in [ + (child, 'down') if 'input_blocks' in name else ( + child, 'up') if 'output_blocks' in name else + (child, + 'mid') if 'middle_block' in name else (None, None) # Default case + for name, child in model.diffusion_model.named_children() + ] if net is not None) + + controller.num_att_layers = cross_att_count + + +class AttentionStore: + """A class for storing attention information in the UNet model. + + Attributes: + base_size (int): Base size for storing attention information. + max_size (int): Maximum size for storing attention information. + """ + + def __init__(self, base_size=64, max_size=None): + """Initialize AttentionStore with default or custom sizes.""" + self.reset() + self.base_size = base_size + self.max_size = max_size or (base_size // 2) + self.num_att_layers = -1 + + @staticmethod + def get_empty_store(): + """Returns an empty store for holding attention values.""" + return { + key: [] + for key in [ + 'down_cross', 'mid_cross', 'up_cross', 'down_self', 'mid_self', + 'up_self' + ] + } + + def reset(self): + """Resets the step and attention stores to their initial states.""" + self.cur_step = 0 + self.cur_att_layer = 0 + self.step_store = self.get_empty_store() + self.attention_store = {} + + def forward(self, attn, is_cross: bool, place_in_unet: str): + """Processes a single forward step, storing the attention. + + Args: + attn: The attention tensor. + is_cross (bool): Whether it's cross attention. + place_in_unet (str): The location in UNet (down/mid/up). + + Returns: + The unmodified attention tensor. + """ + key = f"{place_in_unet}_{'cross' if is_cross else 'self'}" + if attn.shape[1] <= (self.max_size)**2: + self.step_store[key].append(attn) + return attn + + def between_steps(self): + """Processes and stores attention information between steps.""" + if not self.attention_store: + self.attention_store = self.step_store + else: + for key in self.attention_store: + self.attention_store[key] = [ + stored + step for stored, step in zip( + self.attention_store[key], self.step_store[key]) + ] + self.step_store = self.get_empty_store() + + def get_average_attention(self): + """Calculates and returns the average attention across all steps.""" + return { + key: [item for item in self.step_store[key]] + for key in self.step_store + } + + def __call__(self, attn, is_cross: bool, place_in_unet: str): + """Allows the class instance to be callable.""" + return self.forward(attn, is_cross, place_in_unet) + + @property + def num_uncond_att_layers(self): + """Returns the number of unconditional attention layers (default is + 0).""" + return 0 + + def step_callback(self, x_t): + """A placeholder for a step callback. + + Returns the input unchanged. + """ + return x_t + + +class UNetWrapper(nn.Module): + """A wrapper for UNet with optional attention mechanisms. + + Args: + unet (nn.Module): The UNet model to wrap + use_attn (bool): Whether to use attention. Defaults to True + base_size (int): Base size for the attention store. Defaults to 512 + max_attn_size (int, optional): Maximum size for the attention store. + Defaults to None + attn_selector (str): The types of attention to use. + Defaults to 'up_cross+down_cross' + """ + + def __init__(self, + unet, + use_attn=True, + base_size=512, + max_attn_size=None, + attn_selector='up_cross+down_cross'): + super().__init__() + + assert has_ldm, 'To use UNetWrapper, please install required ' \ + 'packages via `pip install -r requirements/optional.txt`.' + + self.unet = unet + self.attention_store = AttentionStore( + base_size=base_size // 8, max_size=max_attn_size) + self.attn_selector = attn_selector.split('+') + self.use_attn = use_attn + self.init_sizes(base_size) + if self.use_attn: + register_attention_control(unet, self.attention_store) + + def init_sizes(self, base_size): + """Initialize sizes based on the base size.""" + self.size16 = base_size // 32 + self.size32 = base_size // 16 + self.size64 = base_size // 8 + + def forward(self, x, timesteps=None, context=None, y=None, **kwargs): + """Forward pass through the model.""" + diffusion_model = self.unet.diffusion_model + if self.use_attn: + self.attention_store.reset() + hs, emb, out_list = self._unet_forward(x, timesteps, context, y, + diffusion_model) + if self.use_attn: + self._append_attn_to_output(out_list) + return out_list[::-1] + + def _unet_forward(self, x, timesteps, context, y, diffusion_model): + hs = [] + t_emb = timestep_embedding( + timesteps, diffusion_model.model_channels, repeat_only=False) + emb = diffusion_model.time_embed(t_emb) + h = x.type(diffusion_model.dtype) + for module in diffusion_model.input_blocks: + h = module(h, emb, context) + hs.append(h) + h = diffusion_model.middle_block(h, emb, context) + out_list = [] + for i_out, module in enumerate(diffusion_model.output_blocks): + h = torch.cat([h, hs.pop()], dim=1) + h = module(h, emb, context) + if i_out in [1, 4, 7]: + out_list.append(h) + h = h.type(x.dtype) + out_list.append(h) + return hs, emb, out_list + + def _append_attn_to_output(self, out_list): + avg_attn = self.attention_store.get_average_attention() + attns = {self.size16: [], self.size32: [], self.size64: []} + for k in self.attn_selector: + for up_attn in avg_attn[k]: + size = int(math.sqrt(up_attn.shape[1])) + up_attn = up_attn.transpose(-1, -2).reshape( + *up_attn.shape[:2], size, -1) + attns[size].append(up_attn) + attn16 = torch.stack(attns[self.size16]).mean(0) + attn32 = torch.stack(attns[self.size32]).mean(0) + attn64 = torch.stack(attns[self.size64]).mean(0) if len( + attns[self.size64]) > 0 else None + out_list[1] = torch.cat([out_list[1], attn16], dim=1) + out_list[2] = torch.cat([out_list[2], attn32], dim=1) + if attn64 is not None: + out_list[3] = torch.cat([out_list[3], attn64], dim=1) + + +class TextAdapter(nn.Module): + """A PyTorch Module that serves as a text adapter. + + This module takes text embeddings and adjusts them based on a scaling + factor gamma. + """ + + def __init__(self, text_dim=768): + super().__init__() + self.fc = nn.Sequential( + nn.Linear(text_dim, text_dim), nn.GELU(), + nn.Linear(text_dim, text_dim)) + + def forward(self, texts, gamma): + texts_after = self.fc(texts) + texts = texts + gamma * texts_after + return texts + + +@MODELS.register_module() +class VPD(BaseModule): + """VPD (Visual Perception Diffusion) model. + + .. _`VPD`: https://arxiv.org/abs/2303.02153 + + Args: + diffusion_cfg (dict): Configuration for diffusion model. + class_embed_path (str): Path for class embeddings. + unet_cfg (dict, optional): Configuration for U-Net. + gamma (float, optional): Gamma for text adaptation. Defaults to 1e-4. + class_embed_select (bool, optional): If True, enables class embedding + selection. Defaults to False. + pad_shape (Optional[Union[int, List[int]]], optional): Padding shape. + Defaults to None. + pad_val (Union[int, List[int]], optional): Padding value. + Defaults to 0. + init_cfg (dict, optional): Configuration for network initialization. + """ + + def __init__(self, + diffusion_cfg: ConfigType, + class_embed_path: str, + unet_cfg: OptConfigType = dict(), + gamma: float = 1e-4, + class_embed_select=False, + pad_shape: Optional[Union[int, List[int]]] = None, + pad_val: Union[int, List[int]] = 0, + init_cfg: OptConfigType = None): + + super().__init__(init_cfg=init_cfg) + + assert has_ldm, 'To use VPD model, please install required packages' \ + ' via `pip install -r requirements/optional.txt`.' + + if pad_shape is not None: + if not isinstance(pad_shape, (list, tuple)): + pad_shape = (pad_shape, pad_shape) + + self.pad_shape = pad_shape + self.pad_val = pad_val + + # diffusion model + diffusion_checkpoint = diffusion_cfg.pop('checkpoint', None) + sd_model = instantiate_from_config(diffusion_cfg) + if diffusion_checkpoint is not None: + load_checkpoint(sd_model, diffusion_checkpoint, strict=False) + + self.encoder_vq = sd_model.first_stage_model + self.unet = UNetWrapper(sd_model.model, **unet_cfg) + + # class embeddings & text adapter + class_embeddings = CheckpointLoader.load_checkpoint(class_embed_path) + text_dim = class_embeddings.size(-1) + self.text_adapter = TextAdapter(text_dim=text_dim) + self.class_embed_select = class_embed_select + if class_embed_select: + class_embeddings = torch.cat( + (class_embeddings, class_embeddings.mean(dim=0, + keepdims=True)), + dim=0) + self.register_buffer('class_embeddings', class_embeddings) + self.gamma = nn.Parameter(torch.ones(text_dim) * gamma) + + def forward(self, x): + """Extract features from images.""" + + # calculate cross-attn map + if self.class_embed_select: + if isinstance(x, (tuple, list)): + x, class_ids = x[:2] + class_ids = class_ids.tolist() + else: + class_ids = [-1] * x.size(0) + class_embeddings = self.class_embeddings[class_ids] + c_crossattn = self.text_adapter(class_embeddings, self.gamma) + c_crossattn = c_crossattn.unsqueeze(1) + else: + class_embeddings = self.class_embeddings + c_crossattn = self.text_adapter(class_embeddings, self.gamma) + c_crossattn = c_crossattn.unsqueeze(0).repeat(x.size(0), 1, 1) + + # pad to required input shape for pretrained diffusion model + if self.pad_shape is not None: + pad_width = max(0, self.pad_shape[1] - x.shape[-1]) + pad_height = max(0, self.pad_shape[0] - x.shape[-2]) + x = F.pad(x, (0, pad_width, 0, pad_height), value=self.pad_val) + + # forward the denoising model + with torch.no_grad(): + latents = self.encoder_vq.encode(x).mode().detach() + t = torch.ones((x.shape[0], ), device=x.device).long() + outs = self.unet(latents, t, context=c_crossattn) + + return outs diff --git a/third-party/InterFormer/mmseg/models/builder.py b/third-party/InterFormer/mmseg/models/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..081c646b49b8ff1ea6c42d1ea4e24e63cdf6b43a --- /dev/null +++ b/third-party/InterFormer/mmseg/models/builder.py @@ -0,0 +1,52 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +from mmseg.registry import MODELS + +BACKBONES = MODELS +NECKS = MODELS +HEADS = MODELS +LOSSES = MODELS +SEGMENTORS = MODELS + + +def build_backbone(cfg): + """Build backbone.""" + warnings.warn('``build_backbone`` would be deprecated soon, please use ' + '``mmseg.registry.MODELS.build()`` ') + return BACKBONES.build(cfg) + + +def build_neck(cfg): + """Build neck.""" + warnings.warn('``build_neck`` would be deprecated soon, please use ' + '``mmseg.registry.MODELS.build()`` ') + return NECKS.build(cfg) + + +def build_head(cfg): + """Build head.""" + warnings.warn('``build_head`` would be deprecated soon, please use ' + '``mmseg.registry.MODELS.build()`` ') + return HEADS.build(cfg) + + +def build_loss(cfg): + """Build loss.""" + warnings.warn('``build_loss`` would be deprecated soon, please use ' + '``mmseg.registry.MODELS.build()`` ') + return LOSSES.build(cfg) + + +def build_segmentor(cfg, train_cfg=None, test_cfg=None): + """Build segmentor.""" + if train_cfg is not None or test_cfg is not None: + warnings.warn( + 'train_cfg and test_cfg is deprecated, ' + 'please specify them in model', UserWarning) + assert cfg.get('train_cfg') is None or train_cfg is None, \ + 'train_cfg specified in both outer field and model field ' + assert cfg.get('test_cfg') is None or test_cfg is None, \ + 'test_cfg specified in both outer field and model field ' + return SEGMENTORS.build( + cfg, default_args=dict(train_cfg=train_cfg, test_cfg=test_cfg)) diff --git a/third-party/InterFormer/mmseg/models/data_preprocessor.py b/third-party/InterFormer/mmseg/models/data_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..8d32bc647b7d48183590408e36ec42ea36aea91c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/data_preprocessor.py @@ -0,0 +1,151 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from numbers import Number +from typing import Any, Dict, List, Optional, Sequence + +import torch +from mmengine.model import BaseDataPreprocessor + +from mmseg.registry import MODELS +from mmseg.utils import stack_batch + + +@MODELS.register_module() +class SegDataPreProcessor(BaseDataPreprocessor): + """Image pre-processor for segmentation tasks. + + Comparing with the :class:`mmengine.ImgDataPreprocessor`, + + 1. It won't do normalization if ``mean`` is not specified. + 2. It does normalization and color space conversion after stacking batch. + 3. It supports batch augmentations like mixup and cutmix. + + + It provides the data pre-processing as follows + + - Collate and move data to the target device. + - Pad inputs to the input size with defined ``pad_val``, and pad seg map + with defined ``seg_pad_val``. + - Stack inputs to batch_inputs. + - Convert inputs from bgr to rgb if the shape of input is (3, H, W). + - Normalize image with defined std and mean. + - Do batch augmentations like Mixup and Cutmix during training. + + Args: + mean (Sequence[Number], optional): The pixel mean of R, G, B channels. + Defaults to None. + std (Sequence[Number], optional): The pixel standard deviation of + R, G, B channels. Defaults to None. + size (tuple, optional): Fixed padding size. + size_divisor (int, optional): The divisor of padded size. + pad_val (float, optional): Padding value. Default: 0. + seg_pad_val (float, optional): Padding value of segmentation map. + Default: 255. + padding_mode (str): Type of padding. Default: constant. + - constant: pads with a constant value, this value is specified + with pad_val. + bgr_to_rgb (bool): whether to convert image from BGR to RGB. + Defaults to False. + rgb_to_bgr (bool): whether to convert image from RGB to RGB. + Defaults to False. + batch_augments (list[dict], optional): Batch-level augmentations + test_cfg (dict, optional): The padding size config in testing, if not + specify, will use `size` and `size_divisor` params as default. + Defaults to None, only supports keys `size` or `size_divisor`. + """ + + def __init__( + self, + mean: Sequence[Number] = None, + std: Sequence[Number] = None, + size: Optional[tuple] = None, + size_divisor: Optional[int] = None, + pad_val: Number = 0, + seg_pad_val: Number = 255, + bgr_to_rgb: bool = False, + rgb_to_bgr: bool = False, + batch_augments: Optional[List[dict]] = None, + test_cfg: dict = None, + ): + super().__init__() + self.size = size + self.size_divisor = size_divisor + self.pad_val = pad_val + self.seg_pad_val = seg_pad_val + + assert not (bgr_to_rgb and rgb_to_bgr), ( + '`bgr2rgb` and `rgb2bgr` cannot be set to True at the same time') + self.channel_conversion = rgb_to_bgr or bgr_to_rgb + + if mean is not None: + assert std is not None, 'To enable the normalization in ' \ + 'preprocessing, please specify both ' \ + '`mean` and `std`.' + # Enable the normalization in preprocessing. + self._enable_normalize = True + self.register_buffer('mean', + torch.tensor(mean).view(-1, 1, 1), False) + self.register_buffer('std', + torch.tensor(std).view(-1, 1, 1), False) + else: + self._enable_normalize = False + + # TODO: support batch augmentations. + self.batch_augments = batch_augments + + # Support different padding methods in testing + self.test_cfg = test_cfg + + def forward(self, data: dict, training: bool = False) -> Dict[str, Any]: + """Perform normalization、padding and bgr2rgb conversion based on + ``BaseDataPreprocessor``. + + Args: + data (dict): data sampled from dataloader. + training (bool): Whether to enable training time augmentation. + + Returns: + Dict: Data in the same format as the model input. + """ + data = self.cast_data(data) # type: ignore + inputs = data['inputs'] + data_samples = data.get('data_samples', None) + # TODO: whether normalize should be after stack_batch + if self.channel_conversion and inputs[0].size(0) == 3: + inputs = [_input[[2, 1, 0], ...] for _input in inputs] + + inputs = [_input.float() for _input in inputs] + if self._enable_normalize: + inputs = [(_input - self.mean) / self.std for _input in inputs] + + if training: + assert data_samples is not None, ('During training, ', + '`data_samples` must be define.') + inputs, data_samples = stack_batch( + inputs=inputs, + data_samples=data_samples, + size=self.size, + size_divisor=self.size_divisor, + pad_val=self.pad_val, + seg_pad_val=self.seg_pad_val) + + if self.batch_augments is not None: + inputs, data_samples = self.batch_augments( + inputs, data_samples) + else: + img_size = inputs[0].shape[1:] + assert all(input_.shape[1:] == img_size for input_ in inputs), \ + 'The image size in a batch should be the same.' + # pad images when testing + if self.test_cfg: + inputs, padded_samples = stack_batch( + inputs=inputs, + size=self.test_cfg.get('size', None), + size_divisor=self.test_cfg.get('size_divisor', None), + pad_val=self.pad_val, + seg_pad_val=self.seg_pad_val) + for data_sample, pad_info in zip(data_samples, padded_samples): + data_sample.set_metainfo({**pad_info}) + else: + inputs = torch.stack(inputs, dim=0) + + return dict(inputs=inputs, data_samples=data_samples) diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__init__.py b/third-party/InterFormer/mmseg/models/decode_heads/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5198380ac25c29c39d325f38c095283c0223c91c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/__init__.py @@ -0,0 +1,50 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .ann_head import ANNHead +from .apc_head import APCHead +from .aspp_head import ASPPHead +from .cc_head import CCHead +from .da_head import DAHead +from .ddr_head import DDRHead +from .dm_head import DMHead +from .dnl_head import DNLHead +from .dpt_head import DPTHead +from .ema_head import EMAHead +from .enc_head import EncHead +from .fcn_head import FCNHead +from .fpn_head import FPNHead +from .gc_head import GCHead +from .ham_head import LightHamHead +from .isa_head import ISAHead +from .knet_head import IterativeDecodeHead, KernelUpdateHead, KernelUpdator +from .lraspp_head import LRASPPHead +from .mask2former_head import Mask2FormerHead +from .maskformer_head import MaskFormerHead +from .nl_head import NLHead +from .ocr_head import OCRHead +from .pid_head import PIDHead +from .point_head import PointHead +from .psa_head import PSAHead +from .psp_head import PSPHead +from .san_head import SideAdapterCLIPHead +from .segformer_head import SegformerHead +from .segmenter_mask_head import SegmenterMaskTransformerHead +from .sep_aspp_head import DepthwiseSeparableASPPHead +from .sep_fcn_head import DepthwiseSeparableFCNHead +from .setr_mla_head import SETRMLAHead +from .setr_up_head import SETRUPHead +from .stdc_head import STDCHead +from .uper_head import UPerHead +from .vpd_depth_head import VPDDepthHead +from .interformer_decoder import InterFormerDecoder + +__all__ = [ + 'FCNHead', 'PSPHead', 'ASPPHead', 'PSAHead', 'NLHead', 'GCHead', 'CCHead', + 'UPerHead', 'DepthwiseSeparableASPPHead', 'ANNHead', 'DAHead', 'OCRHead', + 'EncHead', 'DepthwiseSeparableFCNHead', 'FPNHead', 'EMAHead', 'DNLHead', + 'PointHead', 'APCHead', 'DMHead', 'LRASPPHead', 'SETRUPHead', + 'SETRMLAHead', 'DPTHead', 'SETRMLAHead', 'SegmenterMaskTransformerHead', + 'SegformerHead', 'ISAHead', 'STDCHead', 'IterativeDecodeHead', + 'KernelUpdateHead', 'KernelUpdator', 'MaskFormerHead', 'Mask2FormerHead', + 'LightHamHead', 'PIDHead', 'DDRHead', 'VPDDepthHead', 'SideAdapterCLIPHead', + 'InterFormerDecoder' +] diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02b7944359ce478a825a7ce8e241929ae46e8e53 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ann_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ann_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ef321e88293ad3b47b0faa9ce19cd7c447e1560 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ann_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/apc_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/apc_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0a4add4ea0fe7f4756715ca651a3cb194fda025 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/apc_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/aspp_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/aspp_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af9bfc9951ecf0fae4bcde50ee67fdd5c06a9fa1 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/aspp_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/cascade_decode_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/cascade_decode_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..574b3fc84fa63831ccce50f29dbb0e9f76ee0ac7 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/cascade_decode_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/cc_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/cc_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d85e082769821d6c5df363ad17935466f75a55b9 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/cc_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/da_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/da_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..658e4a8d5538cd12d3a582cb00e209816ff7a2f7 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/da_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ddr_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ddr_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5368d90c95321cfa8b254524392f35e202da3907 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ddr_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/decode_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/decode_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf79e6d152b5c8bf41c692559669ee2dc1f4ca27 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/decode_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dm_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dm_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bb2774a1bccc09d0d7eb81b9d6fec36c6c02593 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dm_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dnl_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dnl_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7379f657484b1b20a4c0d0dafc282efdb2defad Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dnl_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dpt_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dpt_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..987fd7475abfabac983b056f76d1c726f37a1716 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/dpt_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ema_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ema_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86dc26a2c1322ccab5966e9d2ea808cfb11fdc94 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ema_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/enc_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/enc_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8e9733b453bf4b2a69aadae217299a3e281f62b Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/enc_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/fcn_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/fcn_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f20bb2871c912566f295059259ab8986d843907c Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/fcn_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/fpn_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/fpn_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f39a1df92d8e5fe869b91acdf71bb0c7bd22cba0 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/fpn_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/gc_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/gc_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc0ec73a35f309556ecb0dbe7b263126a8fe2e0f Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/gc_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ham_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ham_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0130b49214ff9a388659da212e8bc62a8babe2ad Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ham_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/interformer_decoder.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/interformer_decoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9d26b44562d395b2e45c7049b3c4ea7774dfd9f Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/interformer_decoder.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/isa_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/isa_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49ab8157e90a31561f064c157ebf92422e542e1a Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/isa_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/knet_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/knet_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e48ab6116abc789c57bf2d33151ed5d02614cedf Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/knet_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/lraspp_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/lraspp_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f0e43658680b74bdf6d2436cbf1e659511d74ce Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/lraspp_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/mask2former_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/mask2former_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7bd5834dc27d3bb4c9565d31d0282e618642ad9 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/mask2former_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/maskformer_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/maskformer_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9136ed72ba9240f9b5acccdfb591e23add188560 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/maskformer_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/nl_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/nl_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6bb0cec0edb7c951f9647f3f71d50a9891e0fc9 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/nl_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ocr_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ocr_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..106d591c9c49a9caf346f77ceeaf39cc024dd81d Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/ocr_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/pid_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/pid_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90f620861ad8a53faf02c67c79c9df924900ea10 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/pid_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/point_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/point_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..255116cdbda3cef66090c808f76d8991757aafbf Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/point_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/psa_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/psa_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1bc0dd8cd5e66293671b8baf5c1b0f52a476e65 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/psa_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/psp_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/psp_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..987fc2aba402d7935dec0891755b00572928fa32 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/psp_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/san_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/san_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dd0a96390bb6e92587d23a021811e08b3052538 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/san_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/segformer_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/segformer_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a765063699b1dc13784b8d1f0f103e02d3f4051 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/segformer_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/segmenter_mask_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/segmenter_mask_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..723ae8dc3c70345707a76d508fef188af209a9c5 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/segmenter_mask_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/sep_aspp_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/sep_aspp_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5072485de90d66f6afbad4c2408f445065af50d3 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/sep_aspp_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/sep_fcn_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/sep_fcn_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..425cc7f066bed9904fbd087b92557a3413edc579 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/sep_fcn_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/setr_mla_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/setr_mla_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ad9290bf1fec71ee3a1d058f21e6e7c4be44671 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/setr_mla_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/setr_up_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/setr_up_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3205f4a014bee7012d447175b5c5648d20e51978 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/setr_up_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/stdc_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/stdc_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdc74d4452aaed8dd9ac352049ca301032c7dace Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/stdc_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/uper_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/uper_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69e763fba490b4043353a91c5c2862b758971579 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/uper_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-38.pyc b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db81d8a691f748bda36b511279eecf0ecb389b7a Binary files /dev/null and b/third-party/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/decode_heads/ann_head.py b/third-party/InterFormer/mmseg/models/decode_heads/ann_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2b40ef5aa1da0bc2473597fedca5b3f33973beb0 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/ann_head.py @@ -0,0 +1,245 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import SelfAttentionBlock as _SelfAttentionBlock +from .decode_head import BaseDecodeHead + + +class PPMConcat(nn.ModuleList): + """Pyramid Pooling Module that only concat the features of each layer. + + Args: + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module. + """ + + def __init__(self, pool_scales=(1, 3, 6, 8)): + super().__init__( + [nn.AdaptiveAvgPool2d(pool_scale) for pool_scale in pool_scales]) + + def forward(self, feats): + """Forward function.""" + ppm_outs = [] + for ppm in self: + ppm_out = ppm(feats) + ppm_outs.append(ppm_out.view(*feats.shape[:2], -1)) + concat_outs = torch.cat(ppm_outs, dim=2) + return concat_outs + + +class SelfAttentionBlock(_SelfAttentionBlock): + """Make a ANN used SelfAttentionBlock. + + Args: + low_in_channels (int): Input channels of lower level feature, + which is the key feature for self-attention. + high_in_channels (int): Input channels of higher level feature, + which is the query feature for self-attention. + channels (int): Output channels of key/query transform. + out_channels (int): Output channels. + share_key_query (bool): Whether share projection weight between key + and query projection. + query_scale (int): The scale of query feature map. + key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module of key feature. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict|None): Config of activation layers. + """ + + def __init__(self, low_in_channels, high_in_channels, channels, + out_channels, share_key_query, query_scale, key_pool_scales, + conv_cfg, norm_cfg, act_cfg): + key_psp = PPMConcat(key_pool_scales) + if query_scale > 1: + query_downsample = nn.MaxPool2d(kernel_size=query_scale) + else: + query_downsample = None + super().__init__( + key_in_channels=low_in_channels, + query_in_channels=high_in_channels, + channels=channels, + out_channels=out_channels, + share_key_query=share_key_query, + query_downsample=query_downsample, + key_downsample=key_psp, + key_query_num_convs=1, + key_query_norm=True, + value_out_num_convs=1, + value_out_norm=False, + matmul_norm=True, + with_out=True, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + +class AFNB(nn.Module): + """Asymmetric Fusion Non-local Block(AFNB) + + Args: + low_in_channels (int): Input channels of lower level feature, + which is the key feature for self-attention. + high_in_channels (int): Input channels of higher level feature, + which is the query feature for self-attention. + channels (int): Output channels of key/query transform. + out_channels (int): Output channels. + and query projection. + query_scales (tuple[int]): The scales of query feature map. + Default: (1,) + key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module of key feature. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict|None): Config of activation layers. + """ + + def __init__(self, low_in_channels, high_in_channels, channels, + out_channels, query_scales, key_pool_scales, conv_cfg, + norm_cfg, act_cfg): + super().__init__() + self.stages = nn.ModuleList() + for query_scale in query_scales: + self.stages.append( + SelfAttentionBlock( + low_in_channels=low_in_channels, + high_in_channels=high_in_channels, + channels=channels, + out_channels=out_channels, + share_key_query=False, + query_scale=query_scale, + key_pool_scales=key_pool_scales, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.bottleneck = ConvModule( + out_channels + high_in_channels, + out_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None) + + def forward(self, low_feats, high_feats): + """Forward function.""" + priors = [stage(high_feats, low_feats) for stage in self.stages] + context = torch.stack(priors, dim=0).sum(dim=0) + output = self.bottleneck(torch.cat([context, high_feats], 1)) + return output + + +class APNB(nn.Module): + """Asymmetric Pyramid Non-local Block (APNB) + + Args: + in_channels (int): Input channels of key/query feature, + which is the key feature for self-attention. + channels (int): Output channels of key/query transform. + out_channels (int): Output channels. + query_scales (tuple[int]): The scales of query feature map. + Default: (1,) + key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module of key feature. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict|None): Config of activation layers. + """ + + def __init__(self, in_channels, channels, out_channels, query_scales, + key_pool_scales, conv_cfg, norm_cfg, act_cfg): + super().__init__() + self.stages = nn.ModuleList() + for query_scale in query_scales: + self.stages.append( + SelfAttentionBlock( + low_in_channels=in_channels, + high_in_channels=in_channels, + channels=channels, + out_channels=out_channels, + share_key_query=True, + query_scale=query_scale, + key_pool_scales=key_pool_scales, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.bottleneck = ConvModule( + 2 * in_channels, + out_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, feats): + """Forward function.""" + priors = [stage(feats, feats) for stage in self.stages] + context = torch.stack(priors, dim=0).sum(dim=0) + output = self.bottleneck(torch.cat([context, feats], 1)) + return output + + +@MODELS.register_module() +class ANNHead(BaseDecodeHead): + """Asymmetric Non-local Neural Networks for Semantic Segmentation. + + This head is the implementation of `ANNNet + `_. + + Args: + project_channels (int): Projection channels for Nonlocal. + query_scales (tuple[int]): The scales of query feature map. + Default: (1,) + key_pool_scales (tuple[int]): The pooling scales of key feature map. + Default: (1, 3, 6, 8). + """ + + def __init__(self, + project_channels, + query_scales=(1, ), + key_pool_scales=(1, 3, 6, 8), + **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + assert len(self.in_channels) == 2 + low_in_channels, high_in_channels = self.in_channels + self.project_channels = project_channels + self.fusion = AFNB( + low_in_channels=low_in_channels, + high_in_channels=high_in_channels, + out_channels=high_in_channels, + channels=project_channels, + query_scales=query_scales, + key_pool_scales=key_pool_scales, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.bottleneck = ConvModule( + high_in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.context = APNB( + in_channels=self.channels, + out_channels=self.channels, + channels=project_channels, + query_scales=query_scales, + key_pool_scales=key_pool_scales, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + low_feats, high_feats = self._transform_inputs(inputs) + output = self.fusion(low_feats, high_feats) + output = self.dropout(output) + output = self.bottleneck(output) + output = self.context(output) + output = self.cls_seg(output) + + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/apc_head.py b/third-party/InterFormer/mmseg/models/decode_heads/apc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..728f39659c63680944306fddc9e33b7c9172c1ba --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/apc_head.py @@ -0,0 +1,159 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class ACM(nn.Module): + """Adaptive Context Module used in APCNet. + + Args: + pool_scale (int): Pooling scale used in Adaptive Context + Module to extract region features. + fusion (bool): Add one conv to fuse residual feature. + in_channels (int): Input channels. + channels (int): Channels after modules, before conv_seg. + conv_cfg (dict | None): Config of conv layers. + norm_cfg (dict | None): Config of norm layers. + act_cfg (dict): Config of activation layers. + """ + + def __init__(self, pool_scale, fusion, in_channels, channels, conv_cfg, + norm_cfg, act_cfg): + super().__init__() + self.pool_scale = pool_scale + self.fusion = fusion + self.in_channels = in_channels + self.channels = channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.pooled_redu_conv = ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.input_redu_conv = ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.global_info = ConvModule( + self.channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.gla = nn.Conv2d(self.channels, self.pool_scale**2, 1, 1, 0) + + self.residual_conv = ConvModule( + self.channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + if self.fusion: + self.fusion_conv = ConvModule( + self.channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, x): + """Forward function.""" + pooled_x = F.adaptive_avg_pool2d(x, self.pool_scale) + # [batch_size, channels, h, w] + x = self.input_redu_conv(x) + # [batch_size, channels, pool_scale, pool_scale] + pooled_x = self.pooled_redu_conv(pooled_x) + batch_size = x.size(0) + # [batch_size, pool_scale * pool_scale, channels] + pooled_x = pooled_x.view(batch_size, self.channels, + -1).permute(0, 2, 1).contiguous() + # [batch_size, h * w, pool_scale * pool_scale] + affinity_matrix = self.gla(x + resize( + self.global_info(F.adaptive_avg_pool2d(x, 1)), size=x.shape[2:]) + ).permute(0, 2, 3, 1).reshape( + batch_size, -1, self.pool_scale**2) + affinity_matrix = F.sigmoid(affinity_matrix) + # [batch_size, h * w, channels] + z_out = torch.matmul(affinity_matrix, pooled_x) + # [batch_size, channels, h * w] + z_out = z_out.permute(0, 2, 1).contiguous() + # [batch_size, channels, h, w] + z_out = z_out.view(batch_size, self.channels, x.size(2), x.size(3)) + z_out = self.residual_conv(z_out) + z_out = F.relu(z_out + x) + if self.fusion: + z_out = self.fusion_conv(z_out) + + return z_out + + +@MODELS.register_module() +class APCHead(BaseDecodeHead): + """Adaptive Pyramid Context Network for Semantic Segmentation. + + This head is the implementation of + `APCNet `_. + + Args: + pool_scales (tuple[int]): Pooling scales used in Adaptive Context + Module. Default: (1, 2, 3, 6). + fusion (bool): Add one conv to fuse residual feature. + """ + + def __init__(self, pool_scales=(1, 2, 3, 6), fusion=True, **kwargs): + super().__init__(**kwargs) + assert isinstance(pool_scales, (list, tuple)) + self.pool_scales = pool_scales + self.fusion = fusion + acm_modules = [] + for pool_scale in self.pool_scales: + acm_modules.append( + ACM(pool_scale, + self.fusion, + self.in_channels, + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + self.acm_modules = nn.ModuleList(acm_modules) + self.bottleneck = ConvModule( + self.in_channels + len(pool_scales) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + acm_outs = [x] + for acm_module in self.acm_modules: + acm_outs.append(acm_module(x)) + acm_outs = torch.cat(acm_outs, dim=1) + output = self.bottleneck(acm_outs) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/aspp_head.py b/third-party/InterFormer/mmseg/models/decode_heads/aspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7185d7de58d35ef17e5d54e0e75b045e8724c4 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/aspp_head.py @@ -0,0 +1,122 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class ASPPModule(nn.ModuleList): + """Atrous Spatial Pyramid Pooling (ASPP) Module. + + Args: + dilations (tuple[int]): Dilation rate of each layer. + in_channels (int): Input channels. + channels (int): Channels after modules, before conv_seg. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict): Config of activation layers. + """ + + def __init__(self, dilations, in_channels, channels, conv_cfg, norm_cfg, + act_cfg): + super().__init__() + self.dilations = dilations + self.in_channels = in_channels + self.channels = channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + for dilation in dilations: + self.append( + ConvModule( + self.in_channels, + self.channels, + 1 if dilation == 1 else 3, + dilation=dilation, + padding=0 if dilation == 1 else dilation, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + + def forward(self, x): + """Forward function.""" + aspp_outs = [] + for aspp_module in self: + aspp_outs.append(aspp_module(x)) + + return aspp_outs + + +@MODELS.register_module() +class ASPPHead(BaseDecodeHead): + """Rethinking Atrous Convolution for Semantic Image Segmentation. + + This head is the implementation of `DeepLabV3 + `_. + + Args: + dilations (tuple[int]): Dilation rates for ASPP module. + Default: (1, 6, 12, 18). + """ + + def __init__(self, dilations=(1, 6, 12, 18), **kwargs): + super().__init__(**kwargs) + assert isinstance(dilations, (list, tuple)) + self.dilations = dilations + self.image_pool = nn.Sequential( + nn.AdaptiveAvgPool2d(1), + ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + self.aspp_modules = ASPPModule( + dilations, + self.in_channels, + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.bottleneck = ConvModule( + (len(dilations) + 1) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def _forward_feature(self, inputs): + """Forward function for feature maps before classifying each pixel with + ``self.cls_seg`` fc. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + feats (Tensor): A tensor of shape (batch_size, self.channels, + H, W) which is feature map for last layer of decoder head. + """ + x = self._transform_inputs(inputs) + aspp_outs = [ + resize( + self.image_pool(x), + size=x.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + ] + aspp_outs.extend(self.aspp_modules(x)) + aspp_outs = torch.cat(aspp_outs, dim=1) + feats = self.bottleneck(aspp_outs) + return feats + + def forward(self, inputs): + """Forward function.""" + output = self._forward_feature(inputs) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/cascade_decode_head.py b/third-party/InterFormer/mmseg/models/decode_heads/cascade_decode_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2bcb9302235e3881696dff6657e3e7fb12609b --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/cascade_decode_head.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from abc import ABCMeta, abstractmethod +from typing import List + +from torch import Tensor + +from mmseg.utils import ConfigType +from .decode_head import BaseDecodeHead + + +class BaseCascadeDecodeHead(BaseDecodeHead, metaclass=ABCMeta): + """Base class for cascade decode head used in + :class:`CascadeEncoderDecoder.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + @abstractmethod + def forward(self, inputs, prev_output): + """Placeholder of forward function.""" + pass + + def loss(self, inputs: List[Tensor], prev_output: Tensor, + batch_data_samples: List[dict], train_cfg: ConfigType) -> Tensor: + """Forward function for training. + + Args: + inputs (List[Tensor]): List of multi-level img features. + prev_output (Tensor): The output of previous decode head. + batch_data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_sem_seg`. + train_cfg (dict): The training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + seg_logits = self.forward(inputs, prev_output) + losses = self.loss_by_feat(seg_logits, batch_data_samples) + + return losses + + def predict(self, inputs: List[Tensor], prev_output: Tensor, + batch_img_metas: List[dict], tese_cfg: ConfigType): + """Forward function for testing. + + Args: + inputs (List[Tensor]): List of multi-level img features. + prev_output (Tensor): The output of previous decode head. + batch_img_metas (dict): List Image info where each dict may also + contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + test_cfg (dict): The testing config. + + Returns: + Tensor: Output segmentation map. + """ + seg_logits = self.forward(inputs, prev_output) + + return self.predict_by_feat(seg_logits, batch_img_metas) diff --git a/third-party/InterFormer/mmseg/models/decode_heads/cc_head.py b/third-party/InterFormer/mmseg/models/decode_heads/cc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e9075a2648d77f6bca6bb29f3e7db52a329f7afb --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/cc_head.py @@ -0,0 +1,43 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + +try: + from mmcv.ops import CrissCrossAttention +except ModuleNotFoundError: + CrissCrossAttention = None + + +@MODELS.register_module() +class CCHead(FCNHead): + """CCNet: Criss-Cross Attention for Semantic Segmentation. + + This head is the implementation of `CCNet + `_. + + Args: + recurrence (int): Number of recurrence of Criss Cross Attention + module. Default: 2. + """ + + def __init__(self, recurrence=2, **kwargs): + if CrissCrossAttention is None: + raise RuntimeError('Please install mmcv-full for ' + 'CrissCrossAttention ops') + super().__init__(num_convs=2, **kwargs) + self.recurrence = recurrence + self.cca = CrissCrossAttention(self.channels) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + output = self.convs[0](x) + for _ in range(self.recurrence): + output = self.cca(output) + output = self.convs[1](output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/da_head.py b/third-party/InterFormer/mmseg/models/decode_heads/da_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d87214365d2f8695b60ccab0c1850669ff8dd295 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/da_head.py @@ -0,0 +1,184 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +import torch.nn.functional as F +from mmcv.cnn import ConvModule, Scale +from torch import Tensor, nn + +from mmseg.registry import MODELS +from mmseg.utils import SampleList, add_prefix +from ..utils import SelfAttentionBlock as _SelfAttentionBlock +from .decode_head import BaseDecodeHead + + +class PAM(_SelfAttentionBlock): + """Position Attention Module (PAM) + + Args: + in_channels (int): Input channels of key/query feature. + channels (int): Output channels of key/query transform. + """ + + def __init__(self, in_channels, channels): + super().__init__( + key_in_channels=in_channels, + query_in_channels=in_channels, + channels=channels, + out_channels=in_channels, + share_key_query=False, + query_downsample=None, + key_downsample=None, + key_query_num_convs=1, + key_query_norm=False, + value_out_num_convs=1, + value_out_norm=False, + matmul_norm=False, + with_out=False, + conv_cfg=None, + norm_cfg=None, + act_cfg=None) + + self.gamma = Scale(0) + + def forward(self, x): + """Forward function.""" + out = super().forward(x, x) + + out = self.gamma(out) + x + return out + + +class CAM(nn.Module): + """Channel Attention Module (CAM)""" + + def __init__(self): + super().__init__() + self.gamma = Scale(0) + + def forward(self, x): + """Forward function.""" + batch_size, channels, height, width = x.size() + proj_query = x.view(batch_size, channels, -1) + proj_key = x.view(batch_size, channels, -1).permute(0, 2, 1) + energy = torch.bmm(proj_query, proj_key) + energy_new = torch.max( + energy, -1, keepdim=True)[0].expand_as(energy) - energy + attention = F.softmax(energy_new, dim=-1) + proj_value = x.view(batch_size, channels, -1) + + out = torch.bmm(attention, proj_value) + out = out.view(batch_size, channels, height, width) + + out = self.gamma(out) + x + return out + + +@MODELS.register_module() +class DAHead(BaseDecodeHead): + """Dual Attention Network for Scene Segmentation. + + This head is the implementation of `DANet + `_. + + Args: + pam_channels (int): The channels of Position Attention Module(PAM). + """ + + def __init__(self, pam_channels, **kwargs): + super().__init__(**kwargs) + self.pam_channels = pam_channels + self.pam_in_conv = ConvModule( + self.in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.pam = PAM(self.channels, pam_channels) + self.pam_out_conv = ConvModule( + self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.pam_conv_seg = nn.Conv2d( + self.channels, self.num_classes, kernel_size=1) + + self.cam_in_conv = ConvModule( + self.in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.cam = CAM() + self.cam_out_conv = ConvModule( + self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.cam_conv_seg = nn.Conv2d( + self.channels, self.num_classes, kernel_size=1) + + def pam_cls_seg(self, feat): + """PAM feature classification.""" + if self.dropout is not None: + feat = self.dropout(feat) + output = self.pam_conv_seg(feat) + return output + + def cam_cls_seg(self, feat): + """CAM feature classification.""" + if self.dropout is not None: + feat = self.dropout(feat) + output = self.cam_conv_seg(feat) + return output + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + pam_feat = self.pam_in_conv(x) + pam_feat = self.pam(pam_feat) + pam_feat = self.pam_out_conv(pam_feat) + pam_out = self.pam_cls_seg(pam_feat) + + cam_feat = self.cam_in_conv(x) + cam_feat = self.cam(cam_feat) + cam_feat = self.cam_out_conv(cam_feat) + cam_out = self.cam_cls_seg(cam_feat) + + feat_sum = pam_feat + cam_feat + pam_cam_out = self.cls_seg(feat_sum) + + return pam_cam_out, pam_out, cam_out + + def predict(self, inputs, batch_img_metas: List[dict], test_cfg, + **kwargs) -> List[Tensor]: + """Forward function for testing, only ``pam_cam`` is used.""" + seg_logits = self.forward(inputs)[0] + return self.predict_by_feat(seg_logits, batch_img_metas, **kwargs) + + def loss_by_feat(self, seg_logit: Tuple[Tensor], + batch_data_samples: SampleList, **kwargs) -> dict: + """Compute ``pam_cam``, ``pam``, ``cam`` loss.""" + pam_cam_seg_logit, pam_seg_logit, cam_seg_logit = seg_logit + loss = dict() + loss.update( + add_prefix( + super().loss_by_feat(pam_cam_seg_logit, batch_data_samples), + 'pam_cam')) + loss.update( + add_prefix(super().loss_by_feat(pam_seg_logit, batch_data_samples), + 'pam')) + loss.update( + add_prefix(super().loss_by_feat(cam_seg_logit, batch_data_samples), + 'cam')) + return loss diff --git a/third-party/InterFormer/mmseg/models/decode_heads/ddr_head.py b/third-party/InterFormer/mmseg/models/decode_heads/ddr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ba26d6503c09d7efb3ca6664c7baf59c9e6e3ce9 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/ddr_head.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Tuple, Union + +import torch.nn as nn +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer +from torch import Tensor + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.models.losses import accuracy +from mmseg.models.utils import resize +from mmseg.registry import MODELS +from mmseg.utils import OptConfigType, SampleList + + +@MODELS.register_module() +class DDRHead(BaseDecodeHead): + """Decode head for DDRNet. + + Args: + in_channels (int): Number of input channels. + channels (int): Number of output channels. + num_classes (int): Number of classes. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict, optional): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + """ + + def __init__(self, + in_channels: int, + channels: int, + num_classes: int, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + **kwargs): + super().__init__( + in_channels, + channels, + num_classes=num_classes, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **kwargs) + + self.head = self._make_base_head(self.in_channels, self.channels) + self.aux_head = self._make_base_head(self.in_channels // 2, + self.channels) + self.aux_cls_seg = nn.Conv2d( + self.channels, self.out_channels, kernel_size=1) + + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu') + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def forward( + self, + inputs: Union[Tensor, + Tuple[Tensor]]) -> Union[Tensor, Tuple[Tensor]]: + if self.training: + c3_feat, c5_feat = inputs + x_c = self.head(c5_feat) + x_c = self.cls_seg(x_c) + x_s = self.aux_head(c3_feat) + x_s = self.aux_cls_seg(x_s) + + return x_c, x_s + else: + x_c = self.head(inputs) + x_c = self.cls_seg(x_c) + return x_c + + def _make_base_head(self, in_channels: int, + channels: int) -> nn.Sequential: + layers = [ + ConvModule( + in_channels, + channels, + kernel_size=3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + order=('norm', 'act', 'conv')), + build_norm_layer(self.norm_cfg, channels)[1], + build_activation_layer(self.act_cfg), + ] + + return nn.Sequential(*layers) + + def loss_by_feat(self, seg_logits: Tuple[Tensor], + batch_data_samples: SampleList) -> dict: + loss = dict() + context_logit, spatial_logit = seg_logits + seg_label = self._stack_batch_gt(batch_data_samples) + + context_logit = resize( + context_logit, + size=seg_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + spatial_logit = resize( + spatial_logit, + size=seg_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + seg_label = seg_label.squeeze(1) + + loss['loss_context'] = self.loss_decode[0](context_logit, seg_label) + loss['loss_spatial'] = self.loss_decode[1](spatial_logit, seg_label) + loss['acc_seg'] = accuracy( + context_logit, seg_label, ignore_index=self.ignore_index) + + return loss diff --git a/third-party/InterFormer/mmseg/models/decode_heads/decode_head.py b/third-party/InterFormer/mmseg/models/decode_heads/decode_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fd53afe22d9350482e84c989d3d87e4e07d1ee6b --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/decode_head.py @@ -0,0 +1,366 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings +from abc import ABCMeta, abstractmethod +from typing import List, Tuple + +import torch +import torch.nn as nn +from mmengine.model import BaseModule +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures import build_pixel_sampler +from mmseg.utils import ConfigType, SampleList +from ..losses import accuracy +from ..utils import resize + + +class BaseDecodeHead(BaseModule, metaclass=ABCMeta): + """Base class for BaseDecodeHead. + + 1. The ``init_weights`` method is used to initialize decode_head's + model parameters. After segmentor initialization, ``init_weights`` + is triggered when ``segmentor.init_weights()`` is called externally. + + 2. The ``loss`` method is used to calculate the loss of decode_head, + which includes two steps: (1) the decode_head model performs forward + propagation to obtain the feature maps (2) The ``loss_by_feat`` method + is called based on the feature maps to calculate the loss. + + .. code:: text + + loss(): forward() -> loss_by_feat() + + 3. The ``predict`` method is used to predict segmentation results, + which includes two steps: (1) the decode_head model performs forward + propagation to obtain the feature maps (2) The ``predict_by_feat`` method + is called based on the feature maps to predict segmentation results + including post-processing. + + .. code:: text + + predict(): forward() -> predict_by_feat() + + Args: + in_channels (int|Sequence[int]): Input channels. + channels (int): Channels after modules, before conv_seg. + num_classes (int): Number of classes. + out_channels (int): Output channels of conv_seg. Default: None. + threshold (float): Threshold for binary segmentation in the case of + `num_classes==1`. Default: None. + dropout_ratio (float): Ratio of dropout layer. Default: 0.1. + conv_cfg (dict|None): Config of conv layers. Default: None. + norm_cfg (dict|None): Config of norm layers. Default: None. + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU') + in_index (int|Sequence[int]): Input feature index. Default: -1 + input_transform (str|None): Transformation type of input features. + Options: 'resize_concat', 'multiple_select', None. + 'resize_concat': Multiple feature maps will be resize to the + same size as first one and than concat together. + Usually used in FCN head of HRNet. + 'multiple_select': Multiple feature maps will be bundle into + a list and passed into decode head. + None: Only one select feature map is allowed. + Default: None. + loss_decode (dict | Sequence[dict]): Config of decode loss. + The `loss_name` is property of corresponding loss function which + could be shown in training log. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_ce'. + e.g. dict(type='CrossEntropyLoss'), + [dict(type='CrossEntropyLoss', loss_name='loss_ce'), + dict(type='DiceLoss', loss_name='loss_dice')] + Default: dict(type='CrossEntropyLoss'). + ignore_index (int | None): The label index to be ignored. When using + masked BCE loss, ignore_index should be set to None. Default: 255. + sampler (dict|None): The config of segmentation map sampler. + Default: None. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + init_cfg (dict or list[dict], optional): Initialization config dict. + """ + + def __init__(self, + in_channels, + channels, + *, + num_classes, + out_channels=None, + threshold=None, + dropout_ratio=0.1, + conv_cfg=None, + norm_cfg=None, + act_cfg=dict(type='ReLU'), + in_index=-1, + input_transform=None, + loss_decode=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + ignore_index=255, + sampler=None, + align_corners=False, + init_cfg=dict( + type='Normal', std=0.01, override=dict(name='conv_seg'))): + super().__init__(init_cfg) + self._init_inputs(in_channels, in_index, input_transform) + self.channels = channels + self.dropout_ratio = dropout_ratio + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.in_index = in_index + + self.ignore_index = ignore_index + self.align_corners = align_corners + + if out_channels is None: + if num_classes == 2: + warnings.warn('For binary segmentation, we suggest using' + '`out_channels = 1` to define the output' + 'channels of segmentor, and use `threshold`' + 'to convert `seg_logits` into a prediction' + 'applying a threshold') + out_channels = num_classes + + if out_channels != num_classes and out_channels != 1: + raise ValueError( + 'out_channels should be equal to num_classes,' + 'except binary segmentation set out_channels == 1 and' + f'num_classes == 2, but got out_channels={out_channels}' + f'and num_classes={num_classes}') + + if out_channels == 1 and threshold is None: + threshold = 0.3 + warnings.warn('threshold is not defined for binary, and defaults' + 'to 0.3') + self.num_classes = num_classes + self.out_channels = out_channels + self.threshold = threshold + + if isinstance(loss_decode, dict): + self.loss_decode = MODELS.build(loss_decode) + elif isinstance(loss_decode, (list, tuple)): + self.loss_decode = nn.ModuleList() + for loss in loss_decode: + self.loss_decode.append(MODELS.build(loss)) + else: + raise TypeError(f'loss_decode must be a dict or sequence of dict,\ + but got {type(loss_decode)}') + + if sampler is not None: + self.sampler = build_pixel_sampler(sampler, context=self) + else: + self.sampler = None + + self.conv_seg = nn.Conv2d(channels, self.out_channels, kernel_size=1) + if dropout_ratio > 0: + self.dropout = nn.Dropout2d(dropout_ratio) + else: + self.dropout = None + + def extra_repr(self): + """Extra repr.""" + s = f'input_transform={self.input_transform}, ' \ + f'ignore_index={self.ignore_index}, ' \ + f'align_corners={self.align_corners}' + return s + + def _init_inputs(self, in_channels, in_index, input_transform): + """Check and initialize input transforms. + + The in_channels, in_index and input_transform must match. + Specifically, when input_transform is None, only single feature map + will be selected. So in_channels and in_index must be of type int. + When input_transform + + Args: + in_channels (int|Sequence[int]): Input channels. + in_index (int|Sequence[int]): Input feature index. + input_transform (str|None): Transformation type of input features. + Options: 'resize_concat', 'multiple_select', None. + 'resize_concat': Multiple feature maps will be resize to the + same size as first one and than concat together. + Usually used in FCN head of HRNet. + 'multiple_select': Multiple feature maps will be bundle into + a list and passed into decode head. + None: Only one select feature map is allowed. + """ + + if input_transform is not None: + assert input_transform in ['resize_concat', 'multiple_select'] + self.input_transform = input_transform + self.in_index = in_index + if input_transform is not None: + assert isinstance(in_channels, (list, tuple)) + assert isinstance(in_index, (list, tuple)) + assert len(in_channels) == len(in_index) + if input_transform == 'resize_concat': + self.in_channels = sum(in_channels) + else: + self.in_channels = in_channels + else: + assert isinstance(in_channels, int) + assert isinstance(in_index, int) + self.in_channels = in_channels + + def _transform_inputs(self, inputs): + """Transform inputs for decoder. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + Tensor: The transformed inputs + """ + + if self.input_transform == 'resize_concat': + inputs = [inputs[i] for i in self.in_index] + upsampled_inputs = [ + resize( + input=x, + size=inputs[0].shape[2:], + mode='bilinear', + align_corners=self.align_corners) for x in inputs + ] + inputs = torch.cat(upsampled_inputs, dim=1) + elif self.input_transform == 'multiple_select': + inputs = [inputs[i] for i in self.in_index] + else: + inputs = inputs[self.in_index] + + return inputs + + @abstractmethod + def forward(self, inputs): + """Placeholder of forward function.""" + pass + + def cls_seg(self, feat): + """Classify each pixel.""" + if self.dropout is not None: + feat = self.dropout(feat) + output = self.conv_seg(feat) + return output + + def loss(self, inputs: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + """Forward function for training. + + Args: + inputs (Tuple[Tensor]): List of multi-level img features. + batch_data_samples (list[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `img_metas` or `gt_semantic_seg`. + train_cfg (dict): The training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + seg_logits = self.forward(inputs) + losses = self.loss_by_feat(seg_logits, batch_data_samples) + return losses + + def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tensor: + """Forward function for prediction. + + Args: + inputs (Tuple[Tensor]): List of multi-level img features. + batch_img_metas (dict): List Image info where each dict may also + contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + test_cfg (dict): The testing config. + + Returns: + Tensor: Outputs segmentation logits map. + """ + seg_logits = self.forward(inputs) + + return self.predict_by_feat(seg_logits, batch_img_metas) + + def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tensor: + gt_semantic_segs = [ + data_sample.gt_sem_seg.data for data_sample in batch_data_samples + ] + return torch.stack(gt_semantic_segs, dim=0) + + def loss_by_feat(self, seg_logits: Tensor, + batch_data_samples: SampleList) -> dict: + """Compute segmentation loss. + + Args: + seg_logits (Tensor): The output from decode head forward function. + batch_data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_sem_seg`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + + seg_label = self._stack_batch_gt(batch_data_samples) + loss = dict() + seg_logits = resize( + input=seg_logits, + size=seg_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + if self.sampler is not None: + seg_weight = self.sampler.sample(seg_logits, seg_label) + else: + seg_weight = None + seg_label = seg_label.squeeze(1) + + if not isinstance(self.loss_decode, nn.ModuleList): + losses_decode = [self.loss_decode] + else: + losses_decode = self.loss_decode + for loss_decode in losses_decode: + if loss_decode.loss_name not in loss: + loss[loss_decode.loss_name] = loss_decode( + seg_logits, + seg_label, + weight=seg_weight, + ignore_index=self.ignore_index) + else: + loss[loss_decode.loss_name] += loss_decode( + seg_logits, + seg_label, + weight=seg_weight, + ignore_index=self.ignore_index) + + loss['acc_seg'] = accuracy( + seg_logits, seg_label, ignore_index=self.ignore_index) + return loss + + def predict_by_feat(self, seg_logits: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Transform a batch of output seg_logits to the input shape. + + Args: + seg_logits (Tensor): The output from decode head forward function. + batch_img_metas (list[dict]): Meta information of each image, e.g., + image size, scaling factor, etc. + + Returns: + Tensor: Outputs segmentation logits map. + """ + + if isinstance(batch_img_metas[0]['img_shape'], torch.Size): + # slide inference + size = batch_img_metas[0]['img_shape'] + elif 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'][:2] + else: + size = batch_img_metas[0]['img_shape'] + + seg_logits = resize( + input=seg_logits, + size=size, + mode='bilinear', + align_corners=self.align_corners) + return seg_logits diff --git a/third-party/InterFormer/mmseg/models/decode_heads/dm_head.py b/third-party/InterFormer/mmseg/models/decode_heads/dm_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7694abd8ac3a470d543c580bd97adceb5b647f7c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/dm_head.py @@ -0,0 +1,141 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer + +from mmseg.registry import MODELS +from .decode_head import BaseDecodeHead + + +class DCM(nn.Module): + """Dynamic Convolutional Module used in DMNet. + + Args: + filter_size (int): The filter size of generated convolution kernel + used in Dynamic Convolutional Module. + fusion (bool): Add one conv to fuse DCM output feature. + in_channels (int): Input channels. + channels (int): Channels after modules, before conv_seg. + conv_cfg (dict | None): Config of conv layers. + norm_cfg (dict | None): Config of norm layers. + act_cfg (dict): Config of activation layers. + """ + + def __init__(self, filter_size, fusion, in_channels, channels, conv_cfg, + norm_cfg, act_cfg): + super().__init__() + self.filter_size = filter_size + self.fusion = fusion + self.in_channels = in_channels + self.channels = channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.filter_gen_conv = nn.Conv2d(self.in_channels, self.channels, 1, 1, + 0) + + self.input_redu_conv = ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + if self.norm_cfg is not None: + self.norm = build_norm_layer(self.norm_cfg, self.channels)[1] + else: + self.norm = None + self.activate = build_activation_layer(self.act_cfg) + + if self.fusion: + self.fusion_conv = ConvModule( + self.channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, x): + """Forward function.""" + generated_filter = self.filter_gen_conv( + F.adaptive_avg_pool2d(x, self.filter_size)) + x = self.input_redu_conv(x) + b, c, h, w = x.shape + # [1, b * c, h, w], c = self.channels + x = x.view(1, b * c, h, w) + # [b * c, 1, filter_size, filter_size] + generated_filter = generated_filter.view(b * c, 1, self.filter_size, + self.filter_size) + pad = (self.filter_size - 1) // 2 + if (self.filter_size - 1) % 2 == 0: + p2d = (pad, pad, pad, pad) + else: + p2d = (pad + 1, pad, pad + 1, pad) + x = F.pad(input=x, pad=p2d, mode='constant', value=0) + # [1, b * c, h, w] + output = F.conv2d(input=x, weight=generated_filter, groups=b * c) + # [b, c, h, w] + output = output.view(b, c, h, w) + if self.norm is not None: + output = self.norm(output) + output = self.activate(output) + + if self.fusion: + output = self.fusion_conv(output) + + return output + + +@MODELS.register_module() +class DMHead(BaseDecodeHead): + """Dynamic Multi-scale Filters for Semantic Segmentation. + + This head is the implementation of + `DMNet `_. + + Args: + filter_sizes (tuple[int]): The size of generated convolutional filters + used in Dynamic Convolutional Module. Default: (1, 3, 5, 7). + fusion (bool): Add one conv to fuse DCM output feature. + """ + + def __init__(self, filter_sizes=(1, 3, 5, 7), fusion=False, **kwargs): + super().__init__(**kwargs) + assert isinstance(filter_sizes, (list, tuple)) + self.filter_sizes = filter_sizes + self.fusion = fusion + dcm_modules = [] + for filter_size in self.filter_sizes: + dcm_modules.append( + DCM(filter_size, + self.fusion, + self.in_channels, + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + self.dcm_modules = nn.ModuleList(dcm_modules) + self.bottleneck = ConvModule( + self.in_channels + len(filter_sizes) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + dcm_outs = [x] + for dcm_module in self.dcm_modules: + dcm_outs.append(dcm_module(x)) + dcm_outs = torch.cat(dcm_outs, dim=1) + output = self.bottleneck(dcm_outs) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/dnl_head.py b/third-party/InterFormer/mmseg/models/decode_heads/dnl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..248c11814108d02e88fa7e0cada061b3366e33ff --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/dnl_head.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import NonLocal2d +from torch import nn + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + + +class DisentangledNonLocal2d(NonLocal2d): + """Disentangled Non-Local Blocks. + + Args: + temperature (float): Temperature to adjust attention. Default: 0.05 + """ + + def __init__(self, *arg, temperature, **kwargs): + super().__init__(*arg, **kwargs) + self.temperature = temperature + self.conv_mask = nn.Conv2d(self.in_channels, 1, kernel_size=1) + + def embedded_gaussian(self, theta_x, phi_x): + """Embedded gaussian with temperature.""" + + # NonLocal2d pairwise_weight: [N, HxW, HxW] + pairwise_weight = torch.matmul(theta_x, phi_x) + if self.use_scale: + # theta_x.shape[-1] is `self.inter_channels` + pairwise_weight /= torch.tensor( + theta_x.shape[-1], + dtype=torch.float, + device=pairwise_weight.device)**torch.tensor( + 0.5, device=pairwise_weight.device) + pairwise_weight /= torch.tensor( + self.temperature, device=pairwise_weight.device) + pairwise_weight = pairwise_weight.softmax(dim=-1) + return pairwise_weight + + def forward(self, x): + # x: [N, C, H, W] + n = x.size(0) + + # g_x: [N, HxW, C] + g_x = self.g(x).view(n, self.inter_channels, -1) + g_x = g_x.permute(0, 2, 1) + + # theta_x: [N, HxW, C], phi_x: [N, C, HxW] + if self.mode == 'gaussian': + theta_x = x.view(n, self.in_channels, -1) + theta_x = theta_x.permute(0, 2, 1) + if self.sub_sample: + phi_x = self.phi(x).view(n, self.in_channels, -1) + else: + phi_x = x.view(n, self.in_channels, -1) + elif self.mode == 'concatenation': + theta_x = self.theta(x).view(n, self.inter_channels, -1, 1) + phi_x = self.phi(x).view(n, self.inter_channels, 1, -1) + else: + theta_x = self.theta(x).view(n, self.inter_channels, -1) + theta_x = theta_x.permute(0, 2, 1) + phi_x = self.phi(x).view(n, self.inter_channels, -1) + + # subtract mean + theta_x -= theta_x.mean(dim=-2, keepdim=True) + phi_x -= phi_x.mean(dim=-1, keepdim=True) + + pairwise_func = getattr(self, self.mode) + # pairwise_weight: [N, HxW, HxW] + pairwise_weight = pairwise_func(theta_x, phi_x) + + # y: [N, HxW, C] + y = torch.matmul(pairwise_weight, g_x) + # y: [N, C, H, W] + y = y.permute(0, 2, 1).contiguous().reshape(n, self.inter_channels, + *x.size()[2:]) + + # unary_mask: [N, 1, HxW] + unary_mask = self.conv_mask(x) + unary_mask = unary_mask.view(n, 1, -1) + unary_mask = unary_mask.softmax(dim=-1) + # unary_x: [N, 1, C] + unary_x = torch.matmul(unary_mask, g_x) + # unary_x: [N, C, 1, 1] + unary_x = unary_x.permute(0, 2, 1).contiguous().reshape( + n, self.inter_channels, 1, 1) + + output = x + self.conv_out(y + unary_x) + + return output + + +@MODELS.register_module() +class DNLHead(FCNHead): + """Disentangled Non-Local Neural Networks. + + This head is the implementation of `DNLNet + `_. + + Args: + reduction (int): Reduction factor of projection transform. Default: 2. + use_scale (bool): Whether to scale pairwise_weight by + sqrt(1/inter_channels). Default: False. + mode (str): The nonlocal mode. Options are 'embedded_gaussian', + 'dot_product'. Default: 'embedded_gaussian.'. + temperature (float): Temperature to adjust attention. Default: 0.05 + """ + + def __init__(self, + reduction=2, + use_scale=True, + mode='embedded_gaussian', + temperature=0.05, + **kwargs): + super().__init__(num_convs=2, **kwargs) + self.reduction = reduction + self.use_scale = use_scale + self.mode = mode + self.temperature = temperature + self.dnl_block = DisentangledNonLocal2d( + in_channels=self.channels, + reduction=self.reduction, + use_scale=self.use_scale, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + mode=self.mode, + temperature=self.temperature) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + output = self.convs[0](x) + output = self.dnl_block(output) + output = self.convs[1](output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/dpt_head.py b/third-party/InterFormer/mmseg/models/decode_heads/dpt_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d2cfd89daa4df48601e930cfd158dcf3c9a6a837 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/dpt_head.py @@ -0,0 +1,294 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, Linear, build_activation_layer +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class ReassembleBlocks(BaseModule): + """ViTPostProcessBlock, process cls_token in ViT backbone output and + rearrange the feature vector to feature map. + + Args: + in_channels (int): ViT feature channels. Default: 768. + out_channels (List): output channels of each stage. + Default: [96, 192, 384, 768]. + readout_type (str): Type of readout operation. Default: 'ignore'. + patch_size (int): The patch size. Default: 16. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + def __init__(self, + in_channels=768, + out_channels=[96, 192, 384, 768], + readout_type='ignore', + patch_size=16, + init_cfg=None): + super().__init__(init_cfg) + + assert readout_type in ['ignore', 'add', 'project'] + self.readout_type = readout_type + self.patch_size = patch_size + + self.projects = nn.ModuleList([ + ConvModule( + in_channels=in_channels, + out_channels=out_channel, + kernel_size=1, + act_cfg=None, + ) for out_channel in out_channels + ]) + + self.resize_layers = nn.ModuleList([ + nn.ConvTranspose2d( + in_channels=out_channels[0], + out_channels=out_channels[0], + kernel_size=4, + stride=4, + padding=0), + nn.ConvTranspose2d( + in_channels=out_channels[1], + out_channels=out_channels[1], + kernel_size=2, + stride=2, + padding=0), + nn.Identity(), + nn.Conv2d( + in_channels=out_channels[3], + out_channels=out_channels[3], + kernel_size=3, + stride=2, + padding=1) + ]) + if self.readout_type == 'project': + self.readout_projects = nn.ModuleList() + for _ in range(len(self.projects)): + self.readout_projects.append( + nn.Sequential( + Linear(2 * in_channels, in_channels), + build_activation_layer(dict(type='GELU')))) + + def forward(self, inputs): + assert isinstance(inputs, list) + out = [] + for i, x in enumerate(inputs): + assert len(x) == 2 + x, cls_token = x[0], x[1] + feature_shape = x.shape + if self.readout_type == 'project': + x = x.flatten(2).permute((0, 2, 1)) + readout = cls_token.unsqueeze(1).expand_as(x) + x = self.readout_projects[i](torch.cat((x, readout), -1)) + x = x.permute(0, 2, 1).reshape(feature_shape) + elif self.readout_type == 'add': + x = x.flatten(2) + cls_token.unsqueeze(-1) + x = x.reshape(feature_shape) + else: + pass + x = self.projects[i](x) + x = self.resize_layers[i](x) + out.append(x) + return out + + +class PreActResidualConvUnit(BaseModule): + """ResidualConvUnit, pre-activate residual unit. + + Args: + in_channels (int): number of channels in the input feature map. + act_cfg (dict): dictionary to construct and config activation layer. + norm_cfg (dict): dictionary to construct and config norm layer. + stride (int): stride of the first block. Default: 1 + dilation (int): dilation rate for convs layers. Default: 1. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + def __init__(self, + in_channels, + act_cfg, + norm_cfg, + stride=1, + dilation=1, + init_cfg=None): + super().__init__(init_cfg) + + self.conv1 = ConvModule( + in_channels, + in_channels, + 3, + stride=stride, + padding=dilation, + dilation=dilation, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + bias=False, + order=('act', 'conv', 'norm')) + + self.conv2 = ConvModule( + in_channels, + in_channels, + 3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + bias=False, + order=('act', 'conv', 'norm')) + + def forward(self, inputs): + inputs_ = inputs.clone() + x = self.conv1(inputs) + x = self.conv2(x) + return x + inputs_ + + +class FeatureFusionBlock(BaseModule): + """FeatureFusionBlock, merge feature map from different stages. + + Args: + in_channels (int): Input channels. + act_cfg (dict): The activation config for ResidualConvUnit. + norm_cfg (dict): Config dict for normalization layer. + expand (bool): Whether expand the channels in post process block. + Default: False. + align_corners (bool): align_corner setting for bilinear upsample. + Default: True. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + def __init__(self, + in_channels, + act_cfg, + norm_cfg, + expand=False, + align_corners=True, + init_cfg=None): + super().__init__(init_cfg) + + self.in_channels = in_channels + self.expand = expand + self.align_corners = align_corners + + self.out_channels = in_channels + if self.expand: + self.out_channels = in_channels // 2 + + self.project = ConvModule( + self.in_channels, + self.out_channels, + kernel_size=1, + act_cfg=None, + bias=True) + + self.res_conv_unit1 = PreActResidualConvUnit( + in_channels=self.in_channels, act_cfg=act_cfg, norm_cfg=norm_cfg) + self.res_conv_unit2 = PreActResidualConvUnit( + in_channels=self.in_channels, act_cfg=act_cfg, norm_cfg=norm_cfg) + + def forward(self, *inputs): + x = inputs[0] + if len(inputs) == 2: + if x.shape != inputs[1].shape: + res = resize( + inputs[1], + size=(x.shape[2], x.shape[3]), + mode='bilinear', + align_corners=False) + else: + res = inputs[1] + x = x + self.res_conv_unit1(res) + x = self.res_conv_unit2(x) + x = resize( + x, + scale_factor=2, + mode='bilinear', + align_corners=self.align_corners) + x = self.project(x) + return x + + +@MODELS.register_module() +class DPTHead(BaseDecodeHead): + """Vision Transformers for Dense Prediction. + + This head is implemented of `DPT `_. + + Args: + embed_dims (int): The embed dimension of the ViT backbone. + Default: 768. + post_process_channels (List): Out channels of post process conv + layers. Default: [96, 192, 384, 768]. + readout_type (str): Type of readout operation. Default: 'ignore'. + patch_size (int): The patch size. Default: 16. + expand_channels (bool): Whether expand the channels in post process + block. Default: False. + act_cfg (dict): The activation config for residual conv unit. + Default dict(type='ReLU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + """ + + def __init__(self, + embed_dims=768, + post_process_channels=[96, 192, 384, 768], + readout_type='ignore', + patch_size=16, + expand_channels=False, + act_cfg=dict(type='ReLU'), + norm_cfg=dict(type='BN'), + **kwargs): + super().__init__(**kwargs) + + self.in_channels = self.in_channels + self.expand_channels = expand_channels + self.reassemble_blocks = ReassembleBlocks(embed_dims, + post_process_channels, + readout_type, patch_size) + + self.post_process_channels = [ + channel * math.pow(2, i) if expand_channels else channel + for i, channel in enumerate(post_process_channels) + ] + self.convs = nn.ModuleList() + for channel in self.post_process_channels: + self.convs.append( + ConvModule( + channel, + self.channels, + kernel_size=3, + padding=1, + act_cfg=None, + bias=False)) + self.fusion_blocks = nn.ModuleList() + for _ in range(len(self.convs)): + self.fusion_blocks.append( + FeatureFusionBlock(self.channels, act_cfg, norm_cfg)) + self.fusion_blocks[0].res_conv_unit1 = None + self.project = ConvModule( + self.channels, + self.channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg) + self.num_fusion_blocks = len(self.fusion_blocks) + self.num_reassemble_blocks = len(self.reassemble_blocks.resize_layers) + self.num_post_process_channels = len(self.post_process_channels) + assert self.num_fusion_blocks == self.num_reassemble_blocks + assert self.num_reassemble_blocks == self.num_post_process_channels + + def forward(self, inputs): + assert len(inputs) == self.num_reassemble_blocks + x = self._transform_inputs(inputs) + x = self.reassemble_blocks(x) + x = [self.convs[i](feature) for i, feature in enumerate(x)] + out = self.fusion_blocks[0](x[-1]) + for i in range(1, len(self.fusion_blocks)): + out = self.fusion_blocks[i](out, x[-(i + 1)]) + out = self.project(out) + out = self.cls_seg(out) + return out diff --git a/third-party/InterFormer/mmseg/models/decode_heads/ema_head.py b/third-party/InterFormer/mmseg/models/decode_heads/ema_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8dbb0c29b9b533dad962e48d71ae055f20aa07 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/ema_head.py @@ -0,0 +1,169 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from .decode_head import BaseDecodeHead + + +def reduce_mean(tensor): + """Reduce mean when distributed training.""" + if not (dist.is_available() and dist.is_initialized()): + return tensor + tensor = tensor.clone() + dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM) + return tensor + + +class EMAModule(nn.Module): + """Expectation Maximization Attention Module used in EMANet. + + Args: + channels (int): Channels of the whole module. + num_bases (int): Number of bases. + num_stages (int): Number of the EM iterations. + """ + + def __init__(self, channels, num_bases, num_stages, momentum): + super().__init__() + assert num_stages >= 1, 'num_stages must be at least 1!' + self.num_bases = num_bases + self.num_stages = num_stages + self.momentum = momentum + + bases = torch.zeros(1, channels, self.num_bases) + bases.normal_(0, math.sqrt(2. / self.num_bases)) + # [1, channels, num_bases] + bases = F.normalize(bases, dim=1, p=2) + self.register_buffer('bases', bases) + + def forward(self, feats): + """Forward function.""" + batch_size, channels, height, width = feats.size() + # [batch_size, channels, height*width] + feats = feats.view(batch_size, channels, height * width) + # [batch_size, channels, num_bases] + bases = self.bases.repeat(batch_size, 1, 1) + + with torch.no_grad(): + for i in range(self.num_stages): + # [batch_size, height*width, num_bases] + attention = torch.einsum('bcn,bck->bnk', feats, bases) + attention = F.softmax(attention, dim=2) + # l1 norm + attention_normed = F.normalize(attention, dim=1, p=1) + # [batch_size, channels, num_bases] + bases = torch.einsum('bcn,bnk->bck', feats, attention_normed) + # l2 norm + bases = F.normalize(bases, dim=1, p=2) + + feats_recon = torch.einsum('bck,bnk->bcn', bases, attention) + feats_recon = feats_recon.view(batch_size, channels, height, width) + + if self.training: + bases = bases.mean(dim=0, keepdim=True) + bases = reduce_mean(bases) + # l2 norm + bases = F.normalize(bases, dim=1, p=2) + self.bases = (1 - + self.momentum) * self.bases + self.momentum * bases + + return feats_recon + + +@MODELS.register_module() +class EMAHead(BaseDecodeHead): + """Expectation Maximization Attention Networks for Semantic Segmentation. + + This head is the implementation of `EMANet + `_. + + Args: + ema_channels (int): EMA module channels + num_bases (int): Number of bases. + num_stages (int): Number of the EM iterations. + concat_input (bool): Whether concat the input and output of convs + before classification layer. Default: True + momentum (float): Momentum to update the base. Default: 0.1. + """ + + def __init__(self, + ema_channels, + num_bases, + num_stages, + concat_input=True, + momentum=0.1, + **kwargs): + super().__init__(**kwargs) + self.ema_channels = ema_channels + self.num_bases = num_bases + self.num_stages = num_stages + self.concat_input = concat_input + self.momentum = momentum + self.ema_module = EMAModule(self.ema_channels, self.num_bases, + self.num_stages, self.momentum) + + self.ema_in_conv = ConvModule( + self.in_channels, + self.ema_channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + # project (0, inf) -> (-inf, inf) + self.ema_mid_conv = ConvModule( + self.ema_channels, + self.ema_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=None, + act_cfg=None) + for param in self.ema_mid_conv.parameters(): + param.requires_grad = False + + self.ema_out_conv = ConvModule( + self.ema_channels, + self.ema_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=None) + self.bottleneck = ConvModule( + self.ema_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + if self.concat_input: + self.conv_cat = ConvModule( + self.in_channels + self.channels, + self.channels, + kernel_size=3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + feats = self.ema_in_conv(x) + identity = feats + feats = self.ema_mid_conv(feats) + recon = self.ema_module(feats) + recon = F.relu(recon, inplace=True) + recon = self.ema_out_conv(recon) + output = F.relu(identity + recon, inplace=True) + output = self.bottleneck(output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/enc_head.py b/third-party/InterFormer/mmseg/models/decode_heads/enc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2bba73b3010b31cd39547b79bd507073f14bdb32 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/enc_head.py @@ -0,0 +1,196 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule, build_norm_layer +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import ConfigType, SampleList +from ..utils import Encoding, resize +from .decode_head import BaseDecodeHead + + +class EncModule(nn.Module): + """Encoding Module used in EncNet. + + Args: + in_channels (int): Input channels. + num_codes (int): Number of code words. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict): Config of activation layers. + """ + + def __init__(self, in_channels, num_codes, conv_cfg, norm_cfg, act_cfg): + super().__init__() + self.encoding_project = ConvModule( + in_channels, + in_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + # TODO: resolve this hack + # change to 1d + if norm_cfg is not None: + encoding_norm_cfg = norm_cfg.copy() + if encoding_norm_cfg['type'] in ['BN', 'IN']: + encoding_norm_cfg['type'] += '1d' + else: + encoding_norm_cfg['type'] = encoding_norm_cfg['type'].replace( + '2d', '1d') + else: + # fallback to BN1d + encoding_norm_cfg = dict(type='BN1d') + self.encoding = nn.Sequential( + Encoding(channels=in_channels, num_codes=num_codes), + build_norm_layer(encoding_norm_cfg, num_codes)[1], + nn.ReLU(inplace=True)) + self.fc = nn.Sequential( + nn.Linear(in_channels, in_channels), nn.Sigmoid()) + + def forward(self, x): + """Forward function.""" + encoding_projection = self.encoding_project(x) + encoding_feat = self.encoding(encoding_projection).mean(dim=1) + batch_size, channels, _, _ = x.size() + gamma = self.fc(encoding_feat) + y = gamma.view(batch_size, channels, 1, 1) + output = F.relu_(x + x * y) + return encoding_feat, output + + +@MODELS.register_module() +class EncHead(BaseDecodeHead): + """Context Encoding for Semantic Segmentation. + + This head is the implementation of `EncNet + `_. + + Args: + num_codes (int): Number of code words. Default: 32. + use_se_loss (bool): Whether use Semantic Encoding Loss (SE-loss) to + regularize the training. Default: True. + add_lateral (bool): Whether use lateral connection to fuse features. + Default: False. + loss_se_decode (dict): Config of decode loss. + Default: dict(type='CrossEntropyLoss', use_sigmoid=True). + """ + + def __init__(self, + num_codes=32, + use_se_loss=True, + add_lateral=False, + loss_se_decode=dict( + type='CrossEntropyLoss', + use_sigmoid=True, + loss_weight=0.2), + **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + self.use_se_loss = use_se_loss + self.add_lateral = add_lateral + self.num_codes = num_codes + self.bottleneck = ConvModule( + self.in_channels[-1], + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + if add_lateral: + self.lateral_convs = nn.ModuleList() + for in_channels in self.in_channels[:-1]: # skip the last one + self.lateral_convs.append( + ConvModule( + in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + self.fusion = ConvModule( + len(self.in_channels) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.enc_module = EncModule( + self.channels, + num_codes=num_codes, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + if self.use_se_loss: + self.loss_se_decode = MODELS.build(loss_se_decode) + self.se_layer = nn.Linear(self.channels, self.num_classes) + + def forward(self, inputs): + """Forward function.""" + inputs = self._transform_inputs(inputs) + feat = self.bottleneck(inputs[-1]) + if self.add_lateral: + laterals = [ + resize( + lateral_conv(inputs[i]), + size=feat.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + for i, lateral_conv in enumerate(self.lateral_convs) + ] + feat = self.fusion(torch.cat([feat, *laterals], 1)) + encode_feat, output = self.enc_module(feat) + output = self.cls_seg(output) + if self.use_se_loss: + se_output = self.se_layer(encode_feat) + return output, se_output + else: + return output + + def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType): + """Forward function for testing, ignore se_loss.""" + if self.use_se_loss: + seg_logits = self.forward(inputs)[0] + else: + seg_logits = self.forward(inputs) + return self.predict_by_feat(seg_logits, batch_img_metas) + + @staticmethod + def _convert_to_onehot_labels(seg_label, num_classes): + """Convert segmentation label to onehot. + + Args: + seg_label (Tensor): Segmentation label of shape (N, H, W). + num_classes (int): Number of classes. + + Returns: + Tensor: Onehot labels of shape (N, num_classes). + """ + + batch_size = seg_label.size(0) + onehot_labels = seg_label.new_zeros((batch_size, num_classes)) + for i in range(batch_size): + hist = seg_label[i].float().histc( + bins=num_classes, min=0, max=num_classes - 1) + onehot_labels[i] = hist > 0 + return onehot_labels + + def loss_by_feat(self, seg_logit: Tuple[Tensor], + batch_data_samples: SampleList, **kwargs) -> dict: + """Compute segmentation and semantic encoding loss.""" + seg_logit, se_seg_logit = seg_logit + loss = dict() + loss.update(super().loss_by_feat(seg_logit, batch_data_samples)) + + seg_label = self._stack_batch_gt(batch_data_samples) + se_loss = self.loss_se_decode( + se_seg_logit, + self._convert_to_onehot_labels(seg_label, self.num_classes)) + loss['loss_se'] = se_loss + return loss diff --git a/third-party/InterFormer/mmseg/models/decode_heads/fcn_head.py b/third-party/InterFormer/mmseg/models/decode_heads/fcn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..341801888368d307da6b926a2c89f72b6b06476d --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/fcn_head.py @@ -0,0 +1,96 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class FCNHead(BaseDecodeHead): + """Fully Convolution Networks for Semantic Segmentation. + + This head is implemented of `FCNNet `_. + + Args: + num_convs (int): Number of convs in the head. Default: 2. + kernel_size (int): The kernel size for convs in the head. Default: 3. + concat_input (bool): Whether concat the input and output of convs + before classification layer. + dilation (int): The dilation rate for convs in the head. Default: 1. + """ + + def __init__(self, + num_convs=2, + kernel_size=3, + concat_input=True, + dilation=1, + **kwargs): + assert num_convs >= 0 and dilation > 0 and isinstance(dilation, int) + self.num_convs = num_convs + self.concat_input = concat_input + self.kernel_size = kernel_size + super().__init__(**kwargs) + if num_convs == 0: + assert self.in_channels == self.channels + + conv_padding = (kernel_size // 2) * dilation + convs = [] + convs.append( + ConvModule( + self.in_channels, + self.channels, + kernel_size=kernel_size, + padding=conv_padding, + dilation=dilation, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + for i in range(num_convs - 1): + convs.append( + ConvModule( + self.channels, + self.channels, + kernel_size=kernel_size, + padding=conv_padding, + dilation=dilation, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + if num_convs == 0: + self.convs = nn.Identity() + else: + self.convs = nn.Sequential(*convs) + if self.concat_input: + self.conv_cat = ConvModule( + self.in_channels + self.channels, + self.channels, + kernel_size=kernel_size, + padding=kernel_size // 2, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def _forward_feature(self, inputs): + """Forward function for feature maps before classifying each pixel with + ``self.cls_seg`` fc. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + feats (Tensor): A tensor of shape (batch_size, self.channels, + H, W) which is feature map for last layer of decoder head. + """ + x = self._transform_inputs(inputs) + feats = self.convs(x) + if self.concat_input: + feats = self.conv_cat(torch.cat([x, feats], dim=1)) + return feats + + def forward(self, inputs): + """Forward function.""" + output = self._forward_feature(inputs) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/fpn_head.py b/third-party/InterFormer/mmseg/models/decode_heads/fpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..25f481fe81c5f4f0aa37903aaf135dc63c930bf8 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/fpn_head.py @@ -0,0 +1,68 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import Upsample, resize +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class FPNHead(BaseDecodeHead): + """Panoptic Feature Pyramid Networks. + + This head is the implementation of `Semantic FPN + `_. + + Args: + feature_strides (tuple[int]): The strides for input feature maps. + stack_lateral. All strides suppose to be power of 2. The first + one is of largest resolution. + """ + + def __init__(self, feature_strides, **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + assert len(feature_strides) == len(self.in_channels) + assert min(feature_strides) == feature_strides[0] + self.feature_strides = feature_strides + + self.scale_heads = nn.ModuleList() + for i in range(len(feature_strides)): + head_length = max( + 1, + int(np.log2(feature_strides[i]) - np.log2(feature_strides[0]))) + scale_head = [] + for k in range(head_length): + scale_head.append( + ConvModule( + self.in_channels[i] if k == 0 else self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + if feature_strides[i] != feature_strides[0]: + scale_head.append( + Upsample( + scale_factor=2, + mode='bilinear', + align_corners=self.align_corners)) + self.scale_heads.append(nn.Sequential(*scale_head)) + + def forward(self, inputs): + + x = self._transform_inputs(inputs) + + output = self.scale_heads[0](x[0]) + for i in range(1, len(self.feature_strides)): + # non inplace + output = output + resize( + self.scale_heads[i](x[i]), + size=output.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/gc_head.py b/third-party/InterFormer/mmseg/models/decode_heads/gc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..14f0ef021c1143d493e17f347f1f4da1145470b8 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/gc_head.py @@ -0,0 +1,48 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import ContextBlock + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + + +@MODELS.register_module() +class GCHead(FCNHead): + """GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond. + + This head is the implementation of `GCNet + `_. + + Args: + ratio (float): Multiplier of channels ratio. Default: 1/4. + pooling_type (str): The pooling type of context aggregation. + Options are 'att', 'avg'. Default: 'avg'. + fusion_types (tuple[str]): The fusion type for feature fusion. + Options are 'channel_add', 'channel_mul'. Default: ('channel_add',) + """ + + def __init__(self, + ratio=1 / 4., + pooling_type='att', + fusion_types=('channel_add', ), + **kwargs): + super().__init__(num_convs=2, **kwargs) + self.ratio = ratio + self.pooling_type = pooling_type + self.fusion_types = fusion_types + self.gc_block = ContextBlock( + in_channels=self.channels, + ratio=self.ratio, + pooling_type=self.pooling_type, + fusion_types=self.fusion_types) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + output = self.convs[0](x) + output = self.gc_block(output) + output = self.convs[1](output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/ham_head.py b/third-party/InterFormer/mmseg/models/decode_heads/ham_head.py new file mode 100644 index 0000000000000000000000000000000000000000..073d8011b05dc8c5e8d48cc8b77484a27f7b2100 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/ham_head.py @@ -0,0 +1,255 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Originally from https://github.com/visual-attention-network/segnext +# Licensed under the Apache License, Version 2.0 (the "License") +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.device import get_device + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class Matrix_Decomposition_2D_Base(nn.Module): + """Base class of 2D Matrix Decomposition. + + Args: + MD_S (int): The number of spatial coefficient in + Matrix Decomposition, it may be used for calculation + of the number of latent dimension D in Matrix + Decomposition. Defaults: 1. + MD_R (int): The number of latent dimension R in + Matrix Decomposition. Defaults: 64. + train_steps (int): The number of iteration steps in + Multiplicative Update (MU) rule to solve Non-negative + Matrix Factorization (NMF) in training. Defaults: 6. + eval_steps (int): The number of iteration steps in + Multiplicative Update (MU) rule to solve Non-negative + Matrix Factorization (NMF) in evaluation. Defaults: 7. + inv_t (int): Inverted multiple number to make coefficient + smaller in softmax. Defaults: 100. + rand_init (bool): Whether to initialize randomly. + Defaults: True. + """ + + def __init__(self, + MD_S=1, + MD_R=64, + train_steps=6, + eval_steps=7, + inv_t=100, + rand_init=True): + super().__init__() + + self.S = MD_S + self.R = MD_R + + self.train_steps = train_steps + self.eval_steps = eval_steps + + self.inv_t = inv_t + + self.rand_init = rand_init + + def _build_bases(self, B, S, D, R, device=None): + raise NotImplementedError + + def local_step(self, x, bases, coef): + raise NotImplementedError + + def local_inference(self, x, bases): + # (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R) + coef = torch.bmm(x.transpose(1, 2), bases) + coef = F.softmax(self.inv_t * coef, dim=-1) + + steps = self.train_steps if self.training else self.eval_steps + for _ in range(steps): + bases, coef = self.local_step(x, bases, coef) + + return bases, coef + + def compute_coef(self, x, bases, coef): + raise NotImplementedError + + def forward(self, x, return_bases=False): + """Forward Function.""" + B, C, H, W = x.shape + + # (B, C, H, W) -> (B * S, D, N) + D = C // self.S + N = H * W + x = x.view(B * self.S, D, N) + if not self.rand_init and not hasattr(self, 'bases'): + bases = self._build_bases(1, self.S, D, self.R, device=x.device) + self.register_buffer('bases', bases) + + # (S, D, R) -> (B * S, D, R) + if self.rand_init: + bases = self._build_bases(B, self.S, D, self.R, device=x.device) + else: + bases = self.bases.repeat(B, 1, 1) + + bases, coef = self.local_inference(x, bases) + + # (B * S, N, R) + coef = self.compute_coef(x, bases, coef) + + # (B * S, D, R) @ (B * S, N, R)^T -> (B * S, D, N) + x = torch.bmm(bases, coef.transpose(1, 2)) + + # (B * S, D, N) -> (B, C, H, W) + x = x.view(B, C, H, W) + + return x + + +class NMF2D(Matrix_Decomposition_2D_Base): + """Non-negative Matrix Factorization (NMF) module. + + It is inherited from ``Matrix_Decomposition_2D_Base`` module. + """ + + def __init__(self, args=dict()): + super().__init__(**args) + + self.inv_t = 1 + + def _build_bases(self, B, S, D, R, device=None): + """Build bases in initialization.""" + if device is None: + device = get_device() + bases = torch.rand((B * S, D, R)).to(device) + bases = F.normalize(bases, dim=1) + + return bases + + def local_step(self, x, bases, coef): + """Local step in iteration to renew bases and coefficient.""" + # (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R) + numerator = torch.bmm(x.transpose(1, 2), bases) + # (B * S, N, R) @ [(B * S, D, R)^T @ (B * S, D, R)] -> (B * S, N, R) + denominator = coef.bmm(bases.transpose(1, 2).bmm(bases)) + # Multiplicative Update + coef = coef * numerator / (denominator + 1e-6) + + # (B * S, D, N) @ (B * S, N, R) -> (B * S, D, R) + numerator = torch.bmm(x, coef) + # (B * S, D, R) @ [(B * S, N, R)^T @ (B * S, N, R)] -> (B * S, D, R) + denominator = bases.bmm(coef.transpose(1, 2).bmm(coef)) + # Multiplicative Update + bases = bases * numerator / (denominator + 1e-6) + + return bases, coef + + def compute_coef(self, x, bases, coef): + """Compute coefficient.""" + # (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R) + numerator = torch.bmm(x.transpose(1, 2), bases) + # (B * S, N, R) @ (B * S, D, R)^T @ (B * S, D, R) -> (B * S, N, R) + denominator = coef.bmm(bases.transpose(1, 2).bmm(bases)) + # multiplication update + coef = coef * numerator / (denominator + 1e-6) + + return coef + + +class Hamburger(nn.Module): + """Hamburger Module. It consists of one slice of "ham" (matrix + decomposition) and two slices of "bread" (linear transformation). + + Args: + ham_channels (int): Input and output channels of feature. + ham_kwargs (dict): Config of matrix decomposition module. + norm_cfg (dict | None): Config of norm layers. + """ + + def __init__(self, + ham_channels=512, + ham_kwargs=dict(), + norm_cfg=None, + **kwargs): + super().__init__() + + self.ham_in = ConvModule( + ham_channels, ham_channels, 1, norm_cfg=None, act_cfg=None) + + self.ham = NMF2D(ham_kwargs) + + self.ham_out = ConvModule( + ham_channels, ham_channels, 1, norm_cfg=norm_cfg, act_cfg=None) + + def forward(self, x): + enjoy = self.ham_in(x) + enjoy = F.relu(enjoy, inplace=True) + enjoy = self.ham(enjoy) + enjoy = self.ham_out(enjoy) + ham = F.relu(x + enjoy, inplace=True) + + return ham + + +@MODELS.register_module() +class LightHamHead(BaseDecodeHead): + """SegNeXt decode head. + + This decode head is the implementation of `SegNeXt: Rethinking + Convolutional Attention Design for Semantic + Segmentation `_. + Inspiration from https://github.com/visual-attention-network/segnext. + + Specifically, LightHamHead is inspired by HamNet from + `Is Attention Better Than Matrix Decomposition? + `. + + Args: + ham_channels (int): input channels for Hamburger. + Defaults: 512. + ham_kwargs (int): kwagrs for Ham. Defaults: dict(). + """ + + def __init__(self, ham_channels=512, ham_kwargs=dict(), **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + self.ham_channels = ham_channels + + self.squeeze = ConvModule( + sum(self.in_channels), + self.ham_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.hamburger = Hamburger(ham_channels, ham_kwargs, **kwargs) + + self.align = ConvModule( + self.ham_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + inputs = self._transform_inputs(inputs) + + inputs = [ + resize( + level, + size=inputs[0].shape[2:], + mode='bilinear', + align_corners=self.align_corners) for level in inputs + ] + + inputs = torch.cat(inputs, dim=1) + # apply a conv block to squeeze feature map + x = self.squeeze(inputs) + # apply hamburger module + x = self.hamburger(x) + + # apply a conv block to align feature map + output = self.align(x) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/interformer_decoder.py b/third-party/InterFormer/mmseg/models/decode_heads/interformer_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..ba58bb96d90376325ea57b7159237ad0cf8808dc --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/interformer_decoder.py @@ -0,0 +1,921 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple, Dict + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.model import BaseModule +from typing import Optional +import numpy as np +import cv2 +from PIL import Image + +try: + from mmdet.models.dense_heads import \ + Mask2FormerHead as MMDET_Mask2FormerHead +except ModuleNotFoundError: + MMDET_Mask2FormerHead = BaseModule + +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures.seg_data_sample import SegDataSample +from mmseg.utils import ConfigType, SampleList + +# moving from parent classes +from mmseg.utils import OptConfigType, OptMultiConfig +import copy +from mmdet.models.layers import Mask2FormerTransformerDecoder, SinePositionalEncoding +from mmseg.registry import TASK_UTILS +from mmengine.model import ModuleList, caffe2_xavier_init +from mmcv.cnn import Conv2d +from .decode_head import BaseDecodeHead +from mmdet.models.utils import multi_apply, get_uncertain_point_coords_with_randomness +from mmcv.ops import point_sample +from mmdet.utils import reduce_mean, InstanceList +from typing import Union + + +class UNetDecoder(nn.Module): + def __init__(self, in_channels_list, out_channels): + super(UNetDecoder, self).__init__() + + self.upconv1 = nn.ConvTranspose2d(in_channels_list[3], in_channels_list[2], kernel_size=2, stride=2) + self.conv1 = nn.Conv2d(in_channels_list[2] * 2, in_channels_list[2], kernel_size=3, padding=1) + + self.upconv2 = nn.ConvTranspose2d(in_channels_list[2], in_channels_list[1], kernel_size=2, stride=2) + self.conv2 = nn.Conv2d(in_channels_list[1] * 2, in_channels_list[1], kernel_size=3, padding=1) + + self.upconv3 = nn.ConvTranspose2d(in_channels_list[1], in_channels_list[0], kernel_size=2, stride=2) + self.conv3 = nn.Conv2d(in_channels_list[0] * 2, out_channels, kernel_size=3, padding=1) + + def forward(self, features): + x1 = features[3] + x2 = self.upconv1(x1) + x2 = torch.cat((x2, features[2]), dim=1) # Concatenate + x2 = self.conv1(x2) + + x3 = self.upconv2(x2) + x3 = torch.cat((x3, features[1]), dim=1) # Concatenate + x3 = self.conv2(x3) + + x4 = self.upconv3(x3) + x4 = torch.cat((x4, features[0]), dim=1) # Concatenate + x4 = self.conv3(x4) + + return x4, [x1,x2,x3] + +def _get_activation_fn(activation): + """Return an activation function given a string""" + if activation == "relu": + return F.relu + if activation == "gelu": + return F.gelu + if activation == "glu": + return F.glu + raise RuntimeError(F"activation should be relu/gelu, not {activation}.") + +class CrossAttentionLayer(nn.Module): + + def __init__(self, d_model=256, nhead=8, dropout=0.0, + activation="relu"): + super().__init__() + self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) + + self.norm = nn.LayerNorm(d_model) + self.dropout = nn.Dropout(dropout) + + self.activation = _get_activation_fn(activation) + + self._reset_parameters() + + def _reset_parameters(self): + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + + def with_pos_embed(self, tensor, pos: Optional[Tensor]): + return tensor if pos is None else tensor + pos + + def forward_pre(self, tgt, memory, + memory_mask: Optional[Tensor] = None, + memory_key_padding_mask: Optional[Tensor] = None, + pos: Optional[Tensor] = None, + query_pos: Optional[Tensor] = None): + tgt2 = self.norm(tgt) + tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos), + key=self.with_pos_embed(memory, pos), + value=memory, attn_mask=memory_mask, + key_padding_mask=memory_key_padding_mask)[0] + tgt = tgt + self.dropout(tgt2) + + return tgt + + def forward(self, tgt, memory, + memory_mask: Optional[Tensor] = None, + memory_key_padding_mask: Optional[Tensor] = None, + pos: Optional[Tensor] = None, + query_pos: Optional[Tensor] = None): + + return self.forward_pre(tgt, memory, memory_mask, + memory_key_padding_mask, pos, query_pos) + +class Attention(nn.Module): + def __init__(self, dim=256, heads=8): + super().__init__() + self.heads = heads + head_dim = dim // heads + self.scale = head_dim ** -0.5 + self.attn = None + + self.qkv = nn.Linear(dim, dim * 3) + self.proj = nn.Linear(dim, dim) + + + @property + def unwrapped(self): + return self + + def forward(self, x, mask=None): + B, N, C = x.shape + qkv = ( + self.qkv(x) + .reshape(B, N, 3, self.heads, C // self.heads) + .permute(2, 0, 3, 1, 4) + ) + q, k, v = ( + qkv[0], + qkv[1], + qkv[2], + ) + + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + + return x, attn + +def select_top_k_features_from_regional_similarity(feature_A: torch.Tensor, feature_B: torch.Tensor, k: int = 5): + + if feature_A.shape[1] != feature_B.shape[1]: + raise ValueError("Not match") + + batch_size, channels, h_A, w_A = feature_A.shape + _, _, h_B, w_B = feature_B.shape + + if h_B != 2 * h_A or w_B != 2 * w_A: + raise ValueError("2x times Error") + + b_top_left = feature_B[:, :, :h_A, :w_A] + b_top_right = feature_B[:, :, :h_A, w_A:] + b_bottom_left = feature_B[:, :, h_A:, :w_A] + b_bottom_right = feature_B[:, :, h_A:, w_A:] + + b_sub_regions = [b_top_left, b_top_right, b_bottom_left, b_bottom_right] + + pixelwise_similarities_list = [] + for b_sub in b_sub_regions: + + cosine_sim_map = F.cosine_similarity(feature_A, b_sub, dim=1) + pixelwise_similarities_list.append(cosine_sim_map) + + + sim_map_top = torch.cat([pixelwise_similarities_list[0], pixelwise_similarities_list[1]], dim=2) # [B, H_A, 2*W_A] = [B, H_A, W_B] + sim_map_bottom = torch.cat([pixelwise_similarities_list[2], pixelwise_similarities_list[3]], dim=2) # [B, H_A, 2*W_A] = [B, H_A, W_B] + + total_similarity_map = torch.cat([sim_map_top, sim_map_bottom], dim=1) # [B, 2*H_A, W_B] = [B, H_B, W_B] + + final_selected_features = [] + + for b_idx in range(batch_size): + + batch_similarity = total_similarity_map[b_idx].flatten() + + _, top_k_indices_flat = torch.topk(batch_similarity, k=k, largest=True, sorted=True) + + current_batch_top_k_features = [] + for k_idx in range(k): + flat_idx = top_k_indices_flat[k_idx].item() + + h_coord = flat_idx // w_B + w_coord = flat_idx % w_B + + selected_feature = feature_B[b_idx, :, h_coord, w_coord].unsqueeze(-1).unsqueeze(-1) + current_batch_top_k_features.append(selected_feature) + + all_batches_top_k_flat_indices = [] + for b_idx in range(batch_size): + batch_similarity = total_similarity_map[b_idx].flatten() + _, top_k_indices_flat = torch.topk(batch_similarity, k=k, largest=True, sorted=True) + all_batches_top_k_flat_indices.append(top_k_indices_flat) + + final_selected_features_list = [] + + for k_val_idx in range(k): + features_for_this_k_across_batches = [] + for b_idx in range(batch_size): + flat_idx = all_batches_top_k_flat_indices[b_idx][k_val_idx].item() + h_coord = flat_idx // w_B + w_coord = flat_idx % w_B + + selected_feature = feature_B[b_idx, :, h_coord, w_coord].unsqueeze(-1).unsqueeze(-1) + features_for_this_k_across_batches.append(selected_feature) + + final_selected_features_list.append(torch.stack(features_for_this_k_across_batches, dim=0)) + + return final_selected_features_list + + +@MODELS.register_module() +class InterFormerDecoder(BaseDecodeHead): + + + def __init__(self, + in_channels: List[int], + feat_channels: int, + out_channels: int, + num_queries: int = 100, + num_transformer_feat_level: int = 3, + pixel_decoder: ConfigType = ..., + enforce_decoder_input_project: bool = False, + transformer_decoder: ConfigType = ..., + positional_encoding: ConfigType = dict( + num_feats=128, normalize=True), + loss_cls: ConfigType = dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=2.0, + reduction='mean', + class_weight=[1.0] * 133 + [0.1]), + loss_mask: ConfigType = dict( + type='CrossEntropyLoss', + use_sigmoid=True, + reduction='mean', + loss_weight=5.0), + loss_dice: ConfigType = dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + reduction='mean', + naive_dice=True, + eps=1.0, + loss_weight=5.0), + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + init_cfg: OptMultiConfig = None, + num_classes=10, + align_corners=False, + ignore_index=255, + **kwargs): + super().__init__(in_channels=3,channels=out_channels,num_classes=num_classes) + + self.num_classes = num_classes + self.align_corners = align_corners + self.out_channels = num_classes + self.ignore_index = ignore_index + + feat_channels = feat_channels + + + self.num_queries = num_queries + self.num_transformer_feat_level = num_transformer_feat_level + self.num_heads = transformer_decoder.layer_cfg.cross_attn_cfg.num_heads + self.num_transformer_decoder_layers = transformer_decoder.num_layers + + assert pixel_decoder.encoder.layer_cfg. \ + self_attn_cfg.num_levels == num_transformer_feat_level + pixel_decoder_ = copy.deepcopy(pixel_decoder) + pixel_decoder_.update( + in_channels=in_channels, + feat_channels=feat_channels, + out_channels=out_channels) + self.pixel_decoder = MODELS.build(pixel_decoder_) + self.transformer_decoder = Mask2FormerTransformerDecoder( + **transformer_decoder) + self.decoder_embed_dims = self.transformer_decoder.embed_dims + self.decoder_input_projs = ModuleList() + # from low resolution to high resolution + for _ in range(num_transformer_feat_level): + if (self.decoder_embed_dims != feat_channels + or enforce_decoder_input_project): + self.decoder_input_projs.append( + Conv2d( + feat_channels, self.decoder_embed_dims, kernel_size=1)) + else: + self.decoder_input_projs.append(nn.Identity()) + self.decoder_positional_encoding = SinePositionalEncoding( + **positional_encoding) + self.query_embed = nn.Embedding(self.num_queries, feat_channels) #position + self.query_feat = nn.Embedding(self.num_queries, feat_channels) #content + # from low resolution to high resolution + self.level_embed = nn.Embedding(self.num_transformer_feat_level, + feat_channels) + + self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1) + self.mask_embed = nn.Sequential( + nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True), + nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True), + nn.Linear(feat_channels, out_channels)) + + + self.mlp = nn.Sequential(nn.Linear(112*112, 256), nn.ReLU(inplace=True), + nn.Linear(256,128), nn.ReLU(inplace=True), + nn.Linear(128,5),nn.ReLU(inplace=True)) + + self.test_cfg = test_cfg + self.train_cfg = train_cfg + if train_cfg: + self.assigner = TASK_UTILS.build(self.train_cfg['assigner']) + self.sampler = TASK_UTILS.build( + self.train_cfg['sampler'], default_args=dict(context=self)) + self.num_points = self.train_cfg.get('num_points', 12544) + self.oversample_ratio = self.train_cfg.get('oversample_ratio', 3.0) + self.importance_sample_ratio = self.train_cfg.get( + 'importance_sample_ratio', 0.75) + + + self.class_weight = loss_cls.class_weight + self.loss_cls = MODELS.build(loss_cls) + self.loss_mask = MODELS.build(loss_mask) + self.loss_dice = MODELS.build(loss_dice) + + + self.cbdecoder = UNetDecoder(in_channels_list=[128, 256, 512, 1024], out_channels=1) + self.proj_cb = ModuleList() + channels = [1024,512,256] + for i in range(num_transformer_feat_level): + self.proj_cb.append( + Conv2d( + channels[i], self.decoder_embed_dims, kernel_size=1)) + self.cross_attn_cb = CrossAttentionLayer() + self.self_attn_cb = Attention() + self.norm_cb = nn.LayerNorm(256) + + def _seg_data_to_instance_data(self, batch_data_samples: SampleList): + + batch_img_metas = [] + batch_gt_instances = [] + + for data_sample in batch_data_samples: + batch_img_metas.append(data_sample.metainfo) + gt_sem_seg = data_sample.gt_sem_seg.data + classes = torch.unique( + gt_sem_seg, + sorted=False, + return_inverse=False, + return_counts=False) + + gt_labels = classes[classes != self.ignore_index] + + masks = [] + for class_id in gt_labels: + masks.append(gt_sem_seg == class_id) + + if len(masks) == 0: + gt_masks = torch.zeros( + (0, gt_sem_seg.shape[-2], + gt_sem_seg.shape[-1])).to(gt_sem_seg).long() + else: + gt_masks = torch.stack(masks).squeeze(1).long() + + instance_data = InstanceData(labels=gt_labels, masks=gt_masks) + batch_gt_instances.append(instance_data) + return batch_gt_instances, batch_img_metas + + def compute_loss_for_cb(self, cb_pred, batch_data_samples): + # add supervision for cb prediction + gt_cbs = [] + for data_sample in batch_data_samples: + img_path = data_sample.metainfo['img_path'] + filename = img_path.split('.')[0].split('/')[-1] + cb_gt_path = '/mnt/nvme1/suyuejiao/egohos_split_data/train/label_contact_first/'+filename+'.png' + cb_gt_np = np.array(Image.open(cb_gt_path).resize((448, 448))) + gt_cbs.append(torch.from_numpy(cb_gt_np).to(cb_pred)) + + gt_cbs = torch.stack(gt_cbs).squeeze(1).float() + + criterion = nn.BCEWithLogitsLoss() + loss = criterion(cb_pred.squeeze(1), gt_cbs) + return loss + + + + def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + + batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data( + batch_data_samples) + + all_cls_scores, all_mask_preds, cb_pred = self.forward(x, batch_data_samples) + + # add loss for cb prediction + loss_cb = self.compute_loss_for_cb(cb_pred,batch_data_samples) + + # loss + losses = self.loss_by_feat(all_cls_scores, all_mask_preds, + batch_gt_instances, batch_img_metas) + losses['cb']=loss_cb + + # adding the consistency loss + mask_cls_results = all_cls_scores[-1] + mask_pred_results = all_mask_preds[-1] + if 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'] + else: + size = batch_img_metas[0]['img_shape'] + # upsample mask + mask_pred_results = F.interpolate( + mask_pred_results, size=size, mode='bilinear', align_corners=False) + cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1] + mask_pred = mask_pred_results.sigmoid() + seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred) + pred_results_index = torch.argmax(seg_logits,dim=1) + + left_hand_pred = torch.zeros(pred_results_index.shape) + left_hand_pred[pred_results_index==1] = 1 + + threshold_left = 150 + if left_hand_pred.sum() >= threshold_left: + index_left = 1 + else: + index_left = 0 + + right_hand_pred = torch.zeros(pred_results_index.shape) + right_hand_pred[pred_results_index==2] = 1 + + threshold_right = threshold_left + if right_hand_pred.sum() >= threshold_right: + index_right = 1 + else: + index_right = 0 + + if index_left == 0 or index_right == 0: + index_two = 0 + else: + index_two = 1 + + left_object_pred = torch.zeros(pred_results_index.shape) + left_object_pred[pred_results_index==3] = 1 + right_object_pred = torch.zeros(pred_results_index.shape) + right_object_pred[pred_results_index==4] = 1 + two_object_pred = torch.zeros(pred_results_index.shape) + two_object_pred[pred_results_index==5] = 1 + loss_left = (1-index_left)*(left_object_pred.sum()-left_object_pred.sum()*index_left) + loss_right = (1-index_right)*(right_object_pred.sum()-right_object_pred.sum()*index_right) + loss_two = (1-index_two)*(two_object_pred.sum()-two_object_pred.sum()*index_two) + consistency_loss = loss_left + loss_right + loss_two + + losses['consistency'] = consistency_loss + + return losses + + def loss_by_feat(self, all_cls_scores: Tensor, all_mask_preds: Tensor, + batch_gt_instances: List[InstanceData], + batch_img_metas: List[dict]) -> Dict[str, Tensor]: + + num_dec_layers = len(all_cls_scores) + batch_gt_instances_list = [ + batch_gt_instances for _ in range(num_dec_layers) + ] + img_metas_list = [batch_img_metas for _ in range(num_dec_layers)] + losses_cls, losses_mask, losses_dice = multi_apply( + self._loss_by_feat_single, all_cls_scores, all_mask_preds, + batch_gt_instances_list, img_metas_list) + + loss_dict = dict() + # loss from the last decoder layer + loss_dict['loss_cls'] = losses_cls[-1] + loss_dict['loss_mask'] = losses_mask[-1] + loss_dict['loss_dice'] = losses_dice[-1] + # loss from other decoder layers + num_dec_layer = 0 + for loss_cls_i, loss_mask_i, loss_dice_i in zip( + losses_cls[:-1], losses_mask[:-1], losses_dice[:-1]): + loss_dict[f'd{num_dec_layer}.loss_cls'] = loss_cls_i + loss_dict[f'd{num_dec_layer}.loss_mask'] = loss_mask_i + loss_dict[f'd{num_dec_layer}.loss_dice'] = loss_dice_i + num_dec_layer += 1 + return loss_dict + + def _loss_by_feat_single(self, cls_scores: Tensor, mask_preds: Tensor, + batch_gt_instances: List[InstanceData], + batch_img_metas: List[dict]) -> Tuple[Tensor]: + """Loss function for outputs from a single decoder layer. + + Args: + cls_scores (Tensor): Mask score logits from a single decoder layer + for all images. Shape (batch_size, num_queries, + cls_out_channels). Note `cls_out_channels` should includes + background. + mask_preds (Tensor): Mask logits for a pixel decoder for all + images. Shape (batch_size, num_queries, h, w). + batch_gt_instances (list[obj:`InstanceData`]): each contains + ``labels`` and ``masks``. + batch_img_metas (list[dict]): List of image meta information. + + Returns: + tuple[Tensor]: Loss components for outputs from a single \ + decoder layer. + """ + num_imgs = cls_scores.size(0) + cls_scores_list = [cls_scores[i] for i in range(num_imgs)] + mask_preds_list = [mask_preds[i] for i in range(num_imgs)] + (labels_list, label_weights_list, mask_targets_list, mask_weights_list, + avg_factor) = self.get_targets(cls_scores_list, mask_preds_list, + batch_gt_instances, batch_img_metas) + + labels = torch.stack(labels_list, dim=0) + + label_weights = torch.stack(label_weights_list, dim=0) + + mask_targets = torch.cat(mask_targets_list, dim=0) + + mask_weights = torch.stack(mask_weights_list, dim=0) + + cls_scores = cls_scores.flatten(0, 1) + labels = labels.flatten(0, 1) + label_weights = label_weights.flatten(0, 1) + + class_weight = cls_scores.new_tensor(self.class_weight) + loss_cls = self.loss_cls( + cls_scores, + labels, + label_weights, + avg_factor=class_weight[labels].sum()) + + num_total_masks = reduce_mean(cls_scores.new_tensor([avg_factor])) + num_total_masks = max(num_total_masks, 1) + + # extract positive ones + # shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w) + mask_preds = mask_preds[mask_weights > 0] + + if mask_targets.shape[0] == 0: + # zero match + loss_dice = mask_preds.sum() + loss_mask = mask_preds.sum() + return loss_cls, loss_mask, loss_dice + + with torch.no_grad(): + points_coords = get_uncertain_point_coords_with_randomness( + mask_preds.unsqueeze(1), None, self.num_points, + self.oversample_ratio, self.importance_sample_ratio) + # shape (num_total_gts, h, w) -> (num_total_gts, num_points) + mask_point_targets = point_sample( + mask_targets.unsqueeze(1).float(), points_coords).squeeze(1) + # shape (num_queries, h, w) -> (num_queries, num_points) + mask_point_preds = point_sample( + mask_preds.unsqueeze(1), points_coords).squeeze(1) + + # dice loss + loss_dice = self.loss_dice( + mask_point_preds, mask_point_targets, avg_factor=num_total_masks) + + # mask loss + # shape (num_queries, num_points) -> (num_queries * num_points, ) + mask_point_preds = mask_point_preds.reshape(-1) + # shape (num_total_gts, num_points) -> (num_total_gts * num_points, ) + mask_point_targets = mask_point_targets.reshape(-1) + loss_mask = self.loss_mask( + mask_point_preds, + mask_point_targets, + avg_factor=num_total_masks * self.num_points) + + return loss_cls, loss_mask, loss_dice + + def get_targets( + self, + cls_scores_list: List[Tensor], + mask_preds_list: List[Tensor], + batch_gt_instances: InstanceList, + batch_img_metas: List[dict], + return_sampling_results: bool = False + ) -> Tuple[List[Union[Tensor, int]]]: + """Compute classification and mask targets for all images for a decoder + layer. + + Args: + cls_scores_list (list[Tensor]): Mask score logits from a single + decoder layer for all images. Each with shape (num_queries, + cls_out_channels). + mask_preds_list (list[Tensor]): Mask logits from a single decoder + layer for all images. Each with shape (num_queries, h, w). + batch_gt_instances (list[obj:`InstanceData`]): each contains + ``labels`` and ``masks``. + batch_img_metas (list[dict]): List of image meta information. + return_sampling_results (bool): Whether to return the sampling + results. Defaults to False. + + Returns: + tuple: a tuple containing the following targets. + + - labels_list (list[Tensor]): Labels of all images.\ + Each with shape (num_queries, ). + - label_weights_list (list[Tensor]): Label weights\ + of all images. Each with shape (num_queries, ). + - mask_targets_list (list[Tensor]): Mask targets of\ + all images. Each with shape (num_queries, h, w). + - mask_weights_list (list[Tensor]): Mask weights of\ + all images. Each with shape (num_queries, ). + - avg_factor (int): Average factor that is used to average\ + the loss. When using sampling method, avg_factor is + usually the sum of positive and negative priors. When + using `MaskPseudoSampler`, `avg_factor` is usually equal + to the number of positive priors. + + additional_returns: This function enables user-defined returns from + `self._get_targets_single`. These returns are currently refined + to properties at each feature map (i.e. having HxW dimension). + The results will be concatenated after the end. + """ + results = multi_apply(self._get_targets_single, cls_scores_list, + mask_preds_list, batch_gt_instances, + batch_img_metas) + (labels_list, label_weights_list, mask_targets_list, mask_weights_list, + pos_inds_list, neg_inds_list, sampling_results_list) = results[:7] + rest_results = list(results[7:]) + + avg_factor = sum( + [results.avg_factor for results in sampling_results_list]) + + res = (labels_list, label_weights_list, mask_targets_list, + mask_weights_list, avg_factor) + if return_sampling_results: + res = res + (sampling_results_list) + + return res + tuple(rest_results) + + def _get_targets_single(self, cls_score: Tensor, mask_pred: Tensor, + gt_instances: InstanceData, + img_meta: dict) -> Tuple[Tensor]: + """Compute classification and mask targets for one image. + + Args: + cls_score (Tensor): Mask score logits from a single decoder layer + for one image. Shape (num_queries, cls_out_channels). + mask_pred (Tensor): Mask logits for a single decoder layer for one + image. Shape (num_queries, h, w). + gt_instances (:obj:`InstanceData`): It contains ``labels`` and + ``masks``. + img_meta (dict): Image informtation. + + Returns: + tuple[Tensor]: A tuple containing the following for one image. + + - labels (Tensor): Labels of each image. \ + shape (num_queries, ). + - label_weights (Tensor): Label weights of each image. \ + shape (num_queries, ). + - mask_targets (Tensor): Mask targets of each image. \ + shape (num_queries, h, w). + - mask_weights (Tensor): Mask weights of each image. \ + shape (num_queries, ). + - pos_inds (Tensor): Sampled positive indices for each \ + image. + - neg_inds (Tensor): Sampled negative indices for each \ + image. + - sampling_result (:obj:`SamplingResult`): Sampling results. + """ + gt_labels = gt_instances.labels + gt_masks = gt_instances.masks + # sample points + num_queries = cls_score.shape[0] + num_gts = gt_labels.shape[0] + + point_coords = torch.rand((1, self.num_points, 2), + device=cls_score.device) + # shape (num_queries, num_points) + mask_points_pred = point_sample( + mask_pred.unsqueeze(1), point_coords.repeat(num_queries, 1, + 1)).squeeze(1) + # shape (num_gts, num_points) + gt_points_masks = point_sample( + gt_masks.unsqueeze(1).float(), point_coords.repeat(num_gts, 1, + 1)).squeeze(1) + + sampled_gt_instances = InstanceData( + labels=gt_labels, masks=gt_points_masks) + sampled_pred_instances = InstanceData( + scores=cls_score, masks=mask_points_pred) + # assign and sample + assign_result = self.assigner.assign( + pred_instances=sampled_pred_instances, + gt_instances=sampled_gt_instances, + img_meta=img_meta) + pred_instances = InstanceData(scores=cls_score, masks=mask_pred) + sampling_result = self.sampler.sample( + assign_result=assign_result, + pred_instances=pred_instances, + gt_instances=gt_instances) + pos_inds = sampling_result.pos_inds + neg_inds = sampling_result.neg_inds + + # label target + labels = gt_labels.new_full((self.num_queries, ), + self.num_classes, + dtype=torch.long) + labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds] + label_weights = gt_labels.new_ones((self.num_queries, )) + + # mask target + mask_targets = gt_masks[sampling_result.pos_assigned_gt_inds] + mask_weights = mask_pred.new_zeros((self.num_queries, )) + mask_weights[pos_inds] = 1.0 + + return (labels, label_weights, mask_targets, mask_weights, pos_inds, + neg_inds, sampling_result) + + def _forward_head(self, decoder_out: Tensor, mask_feature: Tensor, + attn_mask_target_size: Tuple[int, int]) -> Tuple[Tensor]: + """Forward for head part which is called after every decoder layer. + + Args: + decoder_out (Tensor): in shape (batch_size, num_queries, c). + mask_feature (Tensor): in shape (batch_size, c, h, w). + attn_mask_target_size (tuple[int, int]): target attention + mask size. + + Returns: + tuple: A tuple contain three elements. + + - cls_pred (Tensor): Classification scores in shape \ + (batch_size, num_queries, cls_out_channels). \ + Note `cls_out_channels` should includes background. + - mask_pred (Tensor): Mask scores in shape \ + (batch_size, num_queries,h, w). + - attn_mask (Tensor): Attention mask in shape \ + (batch_size * num_heads, num_queries, h, w). + """ + + decoder_out = self.transformer_decoder.post_norm(decoder_out) + # shape (batch_size,num_queries, c) + cls_pred = self.cls_embed(decoder_out) + # shape (batch_size,num_queries, num_classes) + mask_embed = self.mask_embed(decoder_out) + # shape ( batch_size, num_queries, c) + mask_pred = torch.einsum('bqc,bchw->bqhw', mask_embed, mask_feature) + attn_mask = F.interpolate( + mask_pred, + attn_mask_target_size, + mode='bilinear', + align_corners=False) + # shape (num_queries, batch_size, h, w) -> + # (batch_size * num_head, num_queries, h, w) + attn_mask = attn_mask.flatten(2).unsqueeze(1).repeat( + (1, self.num_heads, 1, 1)).flatten(0, 1) + attn_mask = attn_mask.sigmoid() < 0.5 + attn_mask = attn_mask.detach() + + return cls_pred, mask_pred, attn_mask + + def forward(self, x: List[Tensor], + batch_data_samples: SampleList) -> Tuple[List[Tensor]]: + """Forward function. + + Args: + x (list[Tensor]): Multi scale Features from the + upstream network, each is a 4D-tensor. + batch_data_samples (List[:obj:`DetDataSample`]): The Data + Samples. It usually includes information such as + `gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`. + + Returns: + tuple[list[Tensor]]: A tuple contains two elements. + + - cls_pred_list (list[Tensor)]: Classification logits \ + for each decoder layer. Each is a 3D-tensor with shape \ + (batch_size, num_queries, cls_out_channels). \ + Note `cls_out_channels` should includes background. + - mask_pred_list (list[Tensor]): Mask logits for each \ + decoder layer. Each with shape (batch_size, num_queries, \ + h, w). + """ + batch_size = x[0].shape[0] + + mask_features, multi_scale_memorys = self.pixel_decoder(x) + + + # add decoder for CB prediction + cb_feat, cb_multi_sclae_features = self.cbdecoder(x) + cb_pred = F.interpolate( + cb_feat, size=(448,448), mode='bilinear', align_corners=False) + + + decoder_inputs = [] + decoder_positional_encodings = [] + for i in range(self.num_transformer_feat_level): + decoder_input = self.decoder_input_projs[i](multi_scale_memorys[i]) + # shape (batch_size, c, h, w) -> (batch_size, h*w, c) + decoder_input = decoder_input.flatten(2).permute(0, 2, 1) + level_embed = self.level_embed.weight[i].view(1, 1, -1) + decoder_input = decoder_input + level_embed + # shape (batch_size, c, h, w) -> (batch_size, h*w, c) + + + cb_feat_align_channel = self.proj_cb[i](cb_multi_sclae_features[i]) + + cb_feat_align_channel = cb_feat_align_channel.flatten(2).permute(0, 2, 1) + + cb_cross_attn = self.cross_attn_cb(cb_feat_align_channel, decoder_input) + cb_cross_attn = cb_cross_attn + cb_feat_align_channel + cb_cross_attn = self.norm_cb(cb_cross_attn) + cb_attn, A = self.self_attn_cb(cb_cross_attn) + + cb_attn = cb_cross_attn + cb_attn + cb_attn = self.norm_cb(cb_attn) + decoder_input = decoder_input+cb_attn + + mask = decoder_input.new_zeros( + (batch_size, ) + multi_scale_memorys[i].shape[-2:], + dtype=torch.bool) + decoder_positional_encoding = self.decoder_positional_encoding(mask) + decoder_positional_encoding = decoder_positional_encoding.flatten( + 2).permute(0, 2, 1) + + decoder_inputs.append(decoder_input) + decoder_positional_encodings.append(decoder_positional_encoding) + + + + selected_q = select_top_k_features_from_regional_similarity(cb_multi_sclae_features[2], mask_features) + # Each item is [B, C, 1, 1]. squeeze() drops B when B==1 and breaks cat(dim=2). + _selected_q = [feat.reshape(feat.shape[0], feat.shape[1], 1) for feat in selected_q] + selected_q = torch.cat(_selected_q, dim=2) + selected_q = selected_q.permute(0, 2, 1) + + + query_feat = self.query_feat.weight.unsqueeze(0).repeat((batch_size, 1, 1)) + query_embed = self.query_embed.weight.unsqueeze(0).repeat((batch_size, 1, 1)) + query_feat = query_feat + selected_q + + cls_pred_list = [] + mask_pred_list = [] + cls_pred, mask_pred, attn_mask = self._forward_head( + query_feat, mask_features, multi_scale_memorys[0].shape[-2:]) + cls_pred_list.append(cls_pred) + mask_pred_list.append(mask_pred) + + for i in range(self.num_transformer_decoder_layers): + level_idx = i % self.num_transformer_feat_level + # if a mask is all True(all background), then set it all False. + mask_sum = (attn_mask.sum(-1) != attn_mask.shape[-1]).unsqueeze(-1) + attn_mask = attn_mask & mask_sum + # cross_attn + self_attn + layer = self.transformer_decoder.layers[i] + query_feat = layer( + query=query_feat, + key=decoder_inputs[level_idx], + value=decoder_inputs[level_idx], + query_pos=query_embed, + key_pos=decoder_positional_encodings[level_idx], + cross_attn_mask=attn_mask, + query_key_padding_mask=None, + # here we do not apply masking on padded region + key_padding_mask=None) + + cls_pred, mask_pred, attn_mask = self._forward_head( + query_feat, mask_features, multi_scale_memorys[(i + 1) % self.num_transformer_feat_level].shape[-2:]) + + + + cls_pred_list.append(cls_pred) + mask_pred_list.append(mask_pred) + + return cls_pred_list, mask_pred_list, cb_pred + + def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tuple[Tensor]: + """Test without augmentaton. + + Args: + x (tuple[Tensor]): Multi-level features from the + upstream network, each is a 4D-tensor. + batch_img_metas (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + test_cfg (ConfigType): Test config. + + Returns: + Tensor: A tensor of segmentation mask. + """ + batch_data_samples = [ + SegDataSample(metainfo=metainfo) for metainfo in batch_img_metas + ] + + all_cls_scores, all_mask_preds, _ = self.forward(x, batch_data_samples) + mask_cls_results = all_cls_scores[-1] + mask_pred_results = all_mask_preds[-1] + if 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'] + else: + size = batch_img_metas[0]['img_shape'] + # upsample mask + mask_pred_results = F.interpolate( + mask_pred_results, size=size, mode='bilinear', align_corners=False) + cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1] + mask_pred = mask_pred_results.sigmoid() + seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred) + return seg_logits diff --git a/third-party/InterFormer/mmseg/models/decode_heads/isa_head.py b/third-party/InterFormer/mmseg/models/decode_heads/isa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..355f215f39007d0153c2fdb3b22a40e7f11a01e3 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/isa_head.py @@ -0,0 +1,143 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math + +import torch +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import SelfAttentionBlock as _SelfAttentionBlock +from .decode_head import BaseDecodeHead + + +class SelfAttentionBlock(_SelfAttentionBlock): + """Self-Attention Module. + + Args: + in_channels (int): Input channels of key/query feature. + channels (int): Output channels of key/query transform. + conv_cfg (dict | None): Config of conv layers. + norm_cfg (dict | None): Config of norm layers. + act_cfg (dict | None): Config of activation layers. + """ + + def __init__(self, in_channels, channels, conv_cfg, norm_cfg, act_cfg): + super().__init__( + key_in_channels=in_channels, + query_in_channels=in_channels, + channels=channels, + out_channels=in_channels, + share_key_query=False, + query_downsample=None, + key_downsample=None, + key_query_num_convs=2, + key_query_norm=True, + value_out_num_convs=1, + value_out_norm=False, + matmul_norm=True, + with_out=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + self.output_project = self.build_project( + in_channels, + in_channels, + num_convs=1, + use_conv_module=True, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, x): + """Forward function.""" + context = super().forward(x, x) + return self.output_project(context) + + +@MODELS.register_module() +class ISAHead(BaseDecodeHead): + """Interlaced Sparse Self-Attention for Semantic Segmentation. + + This head is the implementation of `ISA + `_. + + Args: + isa_channels (int): The channels of ISA Module. + down_factor (tuple[int]): The local group size of ISA. + """ + + def __init__(self, isa_channels, down_factor=(8, 8), **kwargs): + super().__init__(**kwargs) + self.down_factor = down_factor + + self.in_conv = ConvModule( + self.in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.global_relation = SelfAttentionBlock( + self.channels, + isa_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.local_relation = SelfAttentionBlock( + self.channels, + isa_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.out_conv = ConvModule( + self.channels * 2, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x_ = self._transform_inputs(inputs) + x = self.in_conv(x_) + residual = x + + n, c, h, w = x.size() + loc_h, loc_w = self.down_factor # size of local group in H- and W-axes + glb_h, glb_w = math.ceil(h / loc_h), math.ceil(w / loc_w) + pad_h, pad_w = glb_h * loc_h - h, glb_w * loc_w - w + if pad_h > 0 or pad_w > 0: # pad if the size is not divisible + padding = (pad_w // 2, pad_w - pad_w // 2, pad_h // 2, + pad_h - pad_h // 2) + x = F.pad(x, padding) + + # global relation + x = x.view(n, c, glb_h, loc_h, glb_w, loc_w) + # do permutation to gather global group + x = x.permute(0, 3, 5, 1, 2, 4) # (n, loc_h, loc_w, c, glb_h, glb_w) + x = x.reshape(-1, c, glb_h, glb_w) + # apply attention within each global group + x = self.global_relation(x) # (n * loc_h * loc_w, c, glb_h, glb_w) + + # local relation + x = x.view(n, loc_h, loc_w, c, glb_h, glb_w) + # do permutation to gather local group + x = x.permute(0, 4, 5, 3, 1, 2) # (n, glb_h, glb_w, c, loc_h, loc_w) + x = x.reshape(-1, c, loc_h, loc_w) + # apply attention within each local group + x = self.local_relation(x) # (n * glb_h * glb_w, c, loc_h, loc_w) + + # permute each pixel back to its original position + x = x.view(n, glb_h, glb_w, c, loc_h, loc_w) + x = x.permute(0, 3, 1, 4, 2, 5) # (n, c, glb_h, loc_h, glb_w, loc_w) + x = x.reshape(n, c, glb_h * loc_h, glb_w * loc_w) + if pad_h > 0 or pad_w > 0: # remove padding + x = x[:, :, pad_h // 2:pad_h // 2 + h, pad_w // 2:pad_w // 2 + w] + + x = self.out_conv(torch.cat([x, residual], dim=1)) + out = self.cls_seg(x) + + return out diff --git a/third-party/InterFormer/mmseg/models/decode_heads/knet_head.py b/third-party/InterFormer/mmseg/models/decode_heads/knet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..82d3a2807685cdc896c881095f46fd50a450018e --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/knet_head.py @@ -0,0 +1,461 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer +from mmcv.cnn.bricks.transformer import (FFN, MultiheadAttention, + build_transformer_layer) +from mmengine.logging import print_log +from torch import Tensor + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.registry import MODELS +from mmseg.utils import SampleList + + +@MODELS.register_module() +class KernelUpdator(nn.Module): + """Dynamic Kernel Updator in Kernel Update Head. + + Args: + in_channels (int): The number of channels of input feature map. + Default: 256. + feat_channels (int): The number of middle-stage channels in + the kernel updator. Default: 64. + out_channels (int): The number of output channels. + gate_sigmoid (bool): Whether use sigmoid function in gate + mechanism. Default: True. + gate_norm_act (bool): Whether add normalization and activation + layer in gate mechanism. Default: False. + activate_out: Whether add activation after gate mechanism. + Default: False. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='LN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + """ + + def __init__( + self, + in_channels=256, + feat_channels=64, + out_channels=None, + gate_sigmoid=True, + gate_norm_act=False, + activate_out=False, + norm_cfg=dict(type='LN'), + act_cfg=dict(type='ReLU', inplace=True), + ): + super().__init__() + self.in_channels = in_channels + self.feat_channels = feat_channels + self.out_channels_raw = out_channels + self.gate_sigmoid = gate_sigmoid + self.gate_norm_act = gate_norm_act + self.activate_out = activate_out + self.act_cfg = act_cfg + self.norm_cfg = norm_cfg + self.out_channels = out_channels if out_channels else in_channels + + self.num_params_in = self.feat_channels + self.num_params_out = self.feat_channels + self.dynamic_layer = nn.Linear( + self.in_channels, self.num_params_in + self.num_params_out) + self.input_layer = nn.Linear(self.in_channels, + self.num_params_in + self.num_params_out, + 1) + self.input_gate = nn.Linear(self.in_channels, self.feat_channels, 1) + self.update_gate = nn.Linear(self.in_channels, self.feat_channels, 1) + if self.gate_norm_act: + self.gate_norm = build_norm_layer(norm_cfg, self.feat_channels)[1] + + self.norm_in = build_norm_layer(norm_cfg, self.feat_channels)[1] + self.norm_out = build_norm_layer(norm_cfg, self.feat_channels)[1] + self.input_norm_in = build_norm_layer(norm_cfg, self.feat_channels)[1] + self.input_norm_out = build_norm_layer(norm_cfg, self.feat_channels)[1] + + self.activation = build_activation_layer(act_cfg) + + self.fc_layer = nn.Linear(self.feat_channels, self.out_channels, 1) + self.fc_norm = build_norm_layer(norm_cfg, self.out_channels)[1] + + def forward(self, update_feature, input_feature): + """Forward function of KernelUpdator. + + Args: + update_feature (torch.Tensor): Feature map assembled from + each group. It would be reshaped with last dimension + shape: `self.in_channels`. + input_feature (torch.Tensor): Intermediate feature + with shape: (N, num_classes, conv_kernel_size**2, channels). + Returns: + Tensor: The output tensor of shape (N*C1/C2, K*K, C2), where N is + the number of classes, C1 and C2 are the feature map channels of + KernelUpdateHead and KernelUpdator, respectively. + """ + + update_feature = update_feature.reshape(-1, self.in_channels) + num_proposals = update_feature.size(0) + # dynamic_layer works for + # phi_1 and psi_3 in Eq.(4) and (5) of K-Net paper + parameters = self.dynamic_layer(update_feature) + param_in = parameters[:, :self.num_params_in].view( + -1, self.feat_channels) + param_out = parameters[:, -self.num_params_out:].view( + -1, self.feat_channels) + + # input_layer works for + # phi_2 and psi_4 in Eq.(4) and (5) of K-Net paper + input_feats = self.input_layer( + input_feature.reshape(num_proposals, -1, self.feat_channels)) + input_in = input_feats[..., :self.num_params_in] + input_out = input_feats[..., -self.num_params_out:] + + # `gate_feats` is F^G in K-Net paper + gate_feats = input_in * param_in.unsqueeze(-2) + if self.gate_norm_act: + gate_feats = self.activation(self.gate_norm(gate_feats)) + + input_gate = self.input_norm_in(self.input_gate(gate_feats)) + update_gate = self.norm_in(self.update_gate(gate_feats)) + if self.gate_sigmoid: + input_gate = input_gate.sigmoid() + update_gate = update_gate.sigmoid() + param_out = self.norm_out(param_out) + input_out = self.input_norm_out(input_out) + + if self.activate_out: + param_out = self.activation(param_out) + input_out = self.activation(input_out) + + # Gate mechanism. Eq.(5) in original paper. + # param_out has shape (batch_size, feat_channels, out_channels) + features = update_gate * param_out.unsqueeze( + -2) + input_gate * input_out + + features = self.fc_layer(features) + features = self.fc_norm(features) + features = self.activation(features) + + return features + + +@MODELS.register_module() +class KernelUpdateHead(nn.Module): + """Kernel Update Head in K-Net. + + Args: + num_classes (int): Number of classes. Default: 150. + num_ffn_fcs (int): The number of fully-connected layers in + FFNs. Default: 2. + num_heads (int): The number of parallel attention heads. + Default: 8. + num_mask_fcs (int): The number of fully connected layers for + mask prediction. Default: 3. + feedforward_channels (int): The hidden dimension of FFNs. + Defaults: 2048. + in_channels (int): The number of channels of input feature map. + Default: 256. + out_channels (int): The number of output channels. + Default: 256. + dropout (float): The Probability of an element to be + zeroed in MultiheadAttention and FFN. Default 0.0. + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + ffn_act_cfg (dict): Config of activation layers in FFN. + Default: dict(type='ReLU'). + conv_kernel_size (int): The kernel size of convolution in + Kernel Update Head for dynamic kernel updation. + Default: 1. + feat_transform_cfg (dict | None): Config of feature transform. + Default: None. + kernel_init (bool): Whether initiate mask kernel in mask head. + Default: False. + with_ffn (bool): Whether add FFN in kernel update head. + Default: True. + feat_gather_stride (int): Stride of convolution in feature transform. + Default: 1. + mask_transform_stride (int): Stride of mask transform. + Default: 1. + kernel_updator_cfg (dict): Config of kernel updator. + Default: dict( + type='DynamicConv', + in_channels=256, + feat_channels=64, + out_channels=256, + act_cfg=dict(type='ReLU', inplace=True), + norm_cfg=dict(type='LN')). + """ + + def __init__(self, + num_classes=150, + num_ffn_fcs=2, + num_heads=8, + num_mask_fcs=3, + feedforward_channels=2048, + in_channels=256, + out_channels=256, + dropout=0.0, + act_cfg=dict(type='ReLU', inplace=True), + ffn_act_cfg=dict(type='ReLU', inplace=True), + conv_kernel_size=1, + feat_transform_cfg=None, + kernel_init=False, + with_ffn=True, + feat_gather_stride=1, + mask_transform_stride=1, + kernel_updator_cfg=dict( + type='DynamicConv', + in_channels=256, + feat_channels=64, + out_channels=256, + act_cfg=dict(type='ReLU', inplace=True), + norm_cfg=dict(type='LN'))): + super().__init__() + self.num_classes = num_classes + self.in_channels = in_channels + self.out_channels = out_channels + self.fp16_enabled = False + self.dropout = dropout + self.num_heads = num_heads + self.kernel_init = kernel_init + self.with_ffn = with_ffn + self.conv_kernel_size = conv_kernel_size + self.feat_gather_stride = feat_gather_stride + self.mask_transform_stride = mask_transform_stride + + self.attention = MultiheadAttention(in_channels * conv_kernel_size**2, + num_heads, dropout) + self.attention_norm = build_norm_layer( + dict(type='LN'), in_channels * conv_kernel_size**2)[1] + self.kernel_update_conv = build_transformer_layer(kernel_updator_cfg) + + if feat_transform_cfg is not None: + kernel_size = feat_transform_cfg.pop('kernel_size', 1) + transform_channels = in_channels + self.feat_transform = ConvModule( + transform_channels, + in_channels, + kernel_size, + stride=feat_gather_stride, + padding=int(feat_gather_stride // 2), + **feat_transform_cfg) + else: + self.feat_transform = None + + if self.with_ffn: + self.ffn = FFN( + in_channels, + feedforward_channels, + num_ffn_fcs, + act_cfg=ffn_act_cfg, + dropout=dropout) + self.ffn_norm = build_norm_layer(dict(type='LN'), in_channels)[1] + + self.mask_fcs = nn.ModuleList() + for _ in range(num_mask_fcs): + self.mask_fcs.append( + nn.Linear(in_channels, in_channels, bias=False)) + self.mask_fcs.append( + build_norm_layer(dict(type='LN'), in_channels)[1]) + self.mask_fcs.append(build_activation_layer(act_cfg)) + + self.fc_mask = nn.Linear(in_channels, out_channels) + + def init_weights(self): + """Use xavier initialization for all weight parameter and set + classification head bias as a specific value when use focal loss.""" + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + else: + # adopt the default initialization for + # the weight and bias of the layer norm + pass + if self.kernel_init: + print_log( + 'mask kernel in mask head is normal initialized by std 0.01') + nn.init.normal_(self.fc_mask.weight, mean=0, std=0.01) + + def forward(self, x, proposal_feat, mask_preds, mask_shape=None): + """Forward function of Dynamic Instance Interactive Head. + + Args: + x (Tensor): Feature map from FPN with shape + (batch_size, feature_dimensions, H , W). + proposal_feat (Tensor): Intermediate feature get from + diihead in last stage, has shape + (batch_size, num_proposals, feature_dimensions) + mask_preds (Tensor): mask prediction from the former stage in shape + (batch_size, num_proposals, H, W). + + Returns: + Tuple: The first tensor is predicted mask with shape + (N, num_classes, H, W), the second tensor is dynamic kernel + with shape (N, num_classes, channels, K, K). + """ + N, num_proposals = proposal_feat.shape[:2] + if self.feat_transform is not None: + x = self.feat_transform(x) + + C, H, W = x.shape[-3:] + + mask_h, mask_w = mask_preds.shape[-2:] + if mask_h != H or mask_w != W: + gather_mask = F.interpolate( + mask_preds, (H, W), align_corners=False, mode='bilinear') + else: + gather_mask = mask_preds + + sigmoid_masks = gather_mask.softmax(dim=1) + + # Group Feature Assembling. Eq.(3) in original paper. + # einsum is faster than bmm by 30% + x_feat = torch.einsum('bnhw,bchw->bnc', sigmoid_masks, x) + + # obj_feat in shape [B, N, C, K, K] -> [B, N, C, K*K] -> [B, N, K*K, C] + proposal_feat = proposal_feat.reshape(N, num_proposals, + self.in_channels, + -1).permute(0, 1, 3, 2) + obj_feat = self.kernel_update_conv(x_feat, proposal_feat) + + # [B, N, K*K, C] -> [B, N, K*K*C] -> [N, B, K*K*C] + obj_feat = obj_feat.reshape(N, num_proposals, -1).permute(1, 0, 2) + obj_feat = self.attention_norm(self.attention(obj_feat)) + # [N, B, K*K*C] -> [B, N, K*K*C] + obj_feat = obj_feat.permute(1, 0, 2) + + # obj_feat in shape [B, N, K*K*C] -> [B, N, K*K, C] + obj_feat = obj_feat.reshape(N, num_proposals, -1, self.in_channels) + + # FFN + if self.with_ffn: + obj_feat = self.ffn_norm(self.ffn(obj_feat)) + + mask_feat = obj_feat + + for reg_layer in self.mask_fcs: + mask_feat = reg_layer(mask_feat) + + # [B, N, K*K, C] -> [B, N, C, K*K] + mask_feat = self.fc_mask(mask_feat).permute(0, 1, 3, 2) + + if (self.mask_transform_stride == 2 and self.feat_gather_stride == 1): + mask_x = F.interpolate( + x, scale_factor=0.5, mode='bilinear', align_corners=False) + H, W = mask_x.shape[-2:] + else: + mask_x = x + # group conv is 5x faster than unfold and uses about 1/5 memory + # Group conv vs. unfold vs. concat batch, 2.9ms :13.5ms :3.8ms + # Group conv vs. unfold vs. concat batch, 278 : 1420 : 369 + # but in real training group conv is slower than concat batch + # so we keep using concat batch. + # fold_x = F.unfold( + # mask_x, + # self.conv_kernel_size, + # padding=int(self.conv_kernel_size // 2)) + # mask_feat = mask_feat.reshape(N, num_proposals, -1) + # new_mask_preds = torch.einsum('bnc,bcl->bnl', mask_feat, fold_x) + # [B, N, C, K*K] -> [B*N, C, K, K] + mask_feat = mask_feat.reshape(N, num_proposals, C, + self.conv_kernel_size, + self.conv_kernel_size) + # [B, C, H, W] -> [1, B*C, H, W] + new_mask_preds = [] + for i in range(N): + new_mask_preds.append( + F.conv2d( + mask_x[i:i + 1], + mask_feat[i], + padding=int(self.conv_kernel_size // 2))) + + new_mask_preds = torch.cat(new_mask_preds, dim=0) + new_mask_preds = new_mask_preds.reshape(N, num_proposals, H, W) + if self.mask_transform_stride == 2: + new_mask_preds = F.interpolate( + new_mask_preds, + scale_factor=2, + mode='bilinear', + align_corners=False) + + if mask_shape is not None and mask_shape[0] != H: + new_mask_preds = F.interpolate( + new_mask_preds, + mask_shape, + align_corners=False, + mode='bilinear') + + return new_mask_preds, obj_feat.permute(0, 1, 3, 2).reshape( + N, num_proposals, self.in_channels, self.conv_kernel_size, + self.conv_kernel_size) + + +@MODELS.register_module() +class IterativeDecodeHead(BaseDecodeHead): + """K-Net: Towards Unified Image Segmentation. + + This head is the implementation of + `K-Net: `_. + + Args: + num_stages (int): The number of stages (kernel update heads) + in IterativeDecodeHead. Default: 3. + kernel_generate_head:(dict): Config of kernel generate head which + generate mask predictions, dynamic kernels and class predictions + for next kernel update heads. + kernel_update_head (dict): Config of kernel update head which refine + dynamic kernels and class predictions iteratively. + + """ + + def __init__(self, num_stages, kernel_generate_head, kernel_update_head, + **kwargs): + # ``IterativeDecodeHead`` would skip initialization of + # ``BaseDecodeHead`` which would be called when building + # ``self.kernel_generate_head``. + super(BaseDecodeHead, self).__init__(**kwargs) + assert num_stages == len(kernel_update_head) + self.num_stages = num_stages + self.kernel_generate_head = MODELS.build(kernel_generate_head) + self.kernel_update_head = nn.ModuleList() + self.align_corners = self.kernel_generate_head.align_corners + self.num_classes = self.kernel_generate_head.num_classes + self.input_transform = self.kernel_generate_head.input_transform + self.ignore_index = self.kernel_generate_head.ignore_index + self.out_channels = self.num_classes + + for head_cfg in kernel_update_head: + self.kernel_update_head.append(MODELS.build(head_cfg)) + + def forward(self, inputs): + """Forward function.""" + feats = self.kernel_generate_head._forward_feature(inputs) + sem_seg = self.kernel_generate_head.cls_seg(feats) + seg_kernels = self.kernel_generate_head.conv_seg.weight.clone() + seg_kernels = seg_kernels[None].expand( + feats.size(0), *seg_kernels.size()) + + stage_segs = [sem_seg] + for i in range(self.num_stages): + sem_seg, seg_kernels = self.kernel_update_head[i](feats, + seg_kernels, + sem_seg) + stage_segs.append(sem_seg) + if self.training: + return stage_segs + # only return the prediction of the last stage during testing + return stage_segs[-1] + + def loss_by_feat(self, seg_logits: List[Tensor], + batch_data_samples: SampleList, **kwargs) -> dict: + losses = dict() + for i, logit in enumerate(seg_logits): + loss = self.kernel_generate_head.loss_by_feat( + logit, batch_data_samples) + for k, v in loss.items(): + losses[f'{k}.s{i}'] = v + + return losses diff --git a/third-party/InterFormer/mmseg/models/decode_heads/lraspp_head.py b/third-party/InterFormer/mmseg/models/decode_heads/lraspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2465f27522e6ff106fcdf94a46aab42881260a --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/lraspp_head.py @@ -0,0 +1,91 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.utils import is_tuple_of + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class LRASPPHead(BaseDecodeHead): + """Lite R-ASPP (LRASPP) head is proposed in Searching for MobileNetV3. + + This head is the improved implementation of `Searching for MobileNetV3 + `_. + + Args: + branch_channels (tuple[int]): The number of output channels in every + each branch. Default: (32, 64). + """ + + def __init__(self, branch_channels=(32, 64), **kwargs): + super().__init__(**kwargs) + if self.input_transform != 'multiple_select': + raise ValueError('in Lite R-ASPP (LRASPP) head, input_transform ' + f'must be \'multiple_select\'. But received ' + f'\'{self.input_transform}\'') + assert is_tuple_of(branch_channels, int) + assert len(branch_channels) == len(self.in_channels) - 1 + self.branch_channels = branch_channels + + self.convs = nn.Sequential() + self.conv_ups = nn.Sequential() + for i in range(len(branch_channels)): + self.convs.add_module( + f'conv{i}', + nn.Conv2d( + self.in_channels[i], branch_channels[i], 1, bias=False)) + self.conv_ups.add_module( + f'conv_up{i}', + ConvModule( + self.channels + branch_channels[i], + self.channels, + 1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + bias=False)) + + self.conv_up_input = nn.Conv2d(self.channels, self.channels, 1) + + self.aspp_conv = ConvModule( + self.in_channels[-1], + self.channels, + 1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + bias=False) + self.image_pool = nn.Sequential( + nn.AvgPool2d(kernel_size=49, stride=(16, 20)), + ConvModule( + self.in_channels[2], + self.channels, + 1, + act_cfg=dict(type='Sigmoid'), + bias=False)) + + def forward(self, inputs): + """Forward function.""" + inputs = self._transform_inputs(inputs) + + x = inputs[-1] + + x = self.aspp_conv(x) * resize( + self.image_pool(x), + size=x.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + x = self.conv_up_input(x) + + for i in range(len(self.branch_channels) - 1, -1, -1): + x = resize( + x, + size=inputs[i].size()[2:], + mode='bilinear', + align_corners=self.align_corners) + x = torch.cat([x, self.convs[i](inputs[i])], 1) + x = self.conv_ups[i](x) + + return self.cls_seg(x) diff --git a/third-party/InterFormer/mmseg/models/decode_heads/mask2former_head.py b/third-party/InterFormer/mmseg/models/decode_heads/mask2former_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0135af0645830f5cf98595318c4bb20220e64b0b --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/mask2former_head.py @@ -0,0 +1,163 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.model import BaseModule + +try: + from mmdet.models.dense_heads import \ + Mask2FormerHead as MMDET_Mask2FormerHead +except ModuleNotFoundError: + MMDET_Mask2FormerHead = BaseModule + +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures.seg_data_sample import SegDataSample +from mmseg.utils import ConfigType, SampleList + + +@MODELS.register_module() +class Mask2FormerHead(MMDET_Mask2FormerHead): + """Implements the Mask2Former head. + + See `Mask2Former: Masked-attention Mask Transformer for Universal Image + Segmentation `_ for details. + + Args: + num_classes (int): Number of classes. Default: 150. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + ignore_index (int): The label index to be ignored. Default: 255. + """ + + def __init__(self, + num_classes, + align_corners=False, + ignore_index=255, + **kwargs): + super().__init__(**kwargs) + + self.num_classes = num_classes + self.align_corners = align_corners + self.out_channels = num_classes + self.ignore_index = ignore_index + + feat_channels = kwargs['feat_channels'] + self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1) + + def _seg_data_to_instance_data(self, batch_data_samples: SampleList): + """Perform forward propagation to convert paradigm from MMSegmentation + to MMDetection to ensure ``MMDET_Mask2FormerHead`` could be called + normally. Specifically, ``batch_gt_instances`` would be added. + + Args: + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + + Returns: + tuple[Tensor]: A tuple contains two lists. + + - batch_gt_instances (list[:obj:`InstanceData`]): Batch of + gt_instance. It usually includes ``labels``, each is + unique ground truth label id of images, with + shape (num_gt, ) and ``masks``, each is ground truth + masks of each instances of a image, shape (num_gt, h, w). + - batch_img_metas (list[dict]): List of image meta information. + """ + batch_img_metas = [] + batch_gt_instances = [] + + for data_sample in batch_data_samples: + batch_img_metas.append(data_sample.metainfo) + gt_sem_seg = data_sample.gt_sem_seg.data + classes = torch.unique( + gt_sem_seg, + sorted=False, + return_inverse=False, + return_counts=False) + + # remove ignored region + gt_labels = classes[classes != self.ignore_index] + + masks = [] + for class_id in gt_labels: + masks.append(gt_sem_seg == class_id) + + if len(masks) == 0: + gt_masks = torch.zeros( + (0, gt_sem_seg.shape[-2], + gt_sem_seg.shape[-1])).to(gt_sem_seg).long() + else: + gt_masks = torch.stack(masks).squeeze(1).long() + + instance_data = InstanceData(labels=gt_labels, masks=gt_masks) + batch_gt_instances.append(instance_data) + return batch_gt_instances, batch_img_metas + + def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + """Perform forward propagation and loss calculation of the decoder head + on the features of the upstream network. + + Args: + x (tuple[Tensor]): Multi-level features from the upstream + network, each is a 4D-tensor. + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + train_cfg (ConfigType): Training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components. + """ + # batch SegDataSample to InstanceDataSample + batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data( + batch_data_samples) + + # forward + all_cls_scores, all_mask_preds = self(x, batch_data_samples) + + # loss + losses = self.loss_by_feat(all_cls_scores, all_mask_preds, + batch_gt_instances, batch_img_metas) + + return losses + + def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tuple[Tensor]: + """Test without augmentaton. + + Args: + x (tuple[Tensor]): Multi-level features from the + upstream network, each is a 4D-tensor. + batch_img_metas (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + test_cfg (ConfigType): Test config. + + Returns: + Tensor: A tensor of segmentation mask. + """ + batch_data_samples = [ + SegDataSample(metainfo=metainfo) for metainfo in batch_img_metas + ] + + all_cls_scores, all_mask_preds = self(x, batch_data_samples) + mask_cls_results = all_cls_scores[-1] + mask_pred_results = all_mask_preds[-1] + if 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'] + else: + size = batch_img_metas[0]['img_shape'] + # upsample mask + mask_pred_results = F.interpolate( + mask_pred_results, size=size, mode='bilinear', align_corners=False) + cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1] + mask_pred = mask_pred_results.sigmoid() + seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred) + return seg_logits diff --git a/third-party/InterFormer/mmseg/models/decode_heads/maskformer_head.py b/third-party/InterFormer/mmseg/models/decode_heads/maskformer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6e61a7f63a33a508955a866e57c139ce8c40e0f6 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/maskformer_head.py @@ -0,0 +1,174 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.model import BaseModule + +try: + from mmdet.models.dense_heads import MaskFormerHead as MMDET_MaskFormerHead +except ModuleNotFoundError: + MMDET_MaskFormerHead = BaseModule + +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures.seg_data_sample import SegDataSample +from mmseg.utils import ConfigType, SampleList + + +@MODELS.register_module() +class MaskFormerHead(MMDET_MaskFormerHead): + """Implements the MaskFormer head. + + See `Per-Pixel Classification is Not All You Need for Semantic Segmentation + `_ for details. + + Args: + num_classes (int): Number of classes. Default: 150. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + ignore_index (int): The label index to be ignored. Default: 255. + """ + + def __init__(self, + num_classes: int = 150, + align_corners: bool = False, + ignore_index: int = 255, + **kwargs) -> None: + super().__init__(**kwargs) + + self.out_channels = kwargs['out_channels'] + self.align_corners = True + self.num_classes = num_classes + self.align_corners = align_corners + self.out_channels = num_classes + self.ignore_index = ignore_index + + feat_channels = kwargs['feat_channels'] + self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1) + + def _seg_data_to_instance_data(self, batch_data_samples: SampleList): + """Perform forward propagation to convert paradigm from MMSegmentation + to MMDetection to ensure ``MMDET_MaskFormerHead`` could be called + normally. Specifically, ``batch_gt_instances`` would be added. + + Args: + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + + Returns: + tuple[Tensor]: A tuple contains two lists. + + - batch_gt_instances (list[:obj:`InstanceData`]): Batch of + gt_instance. It usually includes ``labels``, each is + unique ground truth label id of images, with + shape (num_gt, ) and ``masks``, each is ground truth + masks of each instances of a image, shape (num_gt, h, w). + - batch_img_metas (list[dict]): List of image meta information. + """ + batch_img_metas = [] + batch_gt_instances = [] + for data_sample in batch_data_samples: + # Add `batch_input_shape` in metainfo of data_sample, which would + # be used in MaskFormerHead of MMDetection. + metainfo = data_sample.metainfo + metainfo['batch_input_shape'] = metainfo['img_shape'] + data_sample.set_metainfo(metainfo) + batch_img_metas.append(data_sample.metainfo) + gt_sem_seg = data_sample.gt_sem_seg.data + classes = torch.unique( + gt_sem_seg, + sorted=False, + return_inverse=False, + return_counts=False) + + # remove ignored region + gt_labels = classes[classes != self.ignore_index] + + masks = [] + for class_id in gt_labels: + masks.append(gt_sem_seg == class_id) + + if len(masks) == 0: + gt_masks = torch.zeros((0, gt_sem_seg.shape[-2], + gt_sem_seg.shape[-1])).to(gt_sem_seg) + else: + gt_masks = torch.stack(masks).squeeze(1) + + instance_data = InstanceData( + labels=gt_labels, masks=gt_masks.long()) + batch_gt_instances.append(instance_data) + return batch_gt_instances, batch_img_metas + + def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + """Perform forward propagation and loss calculation of the decoder head + on the features of the upstream network. + + Args: + x (tuple[Tensor]): Multi-level features from the upstream + network, each is a 4D-tensor. + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + train_cfg (ConfigType): Training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components. + """ + # batch SegDataSample to InstanceDataSample + batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data( + batch_data_samples) + + # forward + all_cls_scores, all_mask_preds = self(x, batch_data_samples) + + # loss + losses = self.loss_by_feat(all_cls_scores, all_mask_preds, + batch_gt_instances, batch_img_metas) + + return losses + + def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tuple[Tensor]: + """Test without augmentaton. + + Args: + x (tuple[Tensor]): Multi-level features from the + upstream network, each is a 4D-tensor. + batch_img_metas (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + test_cfg (ConfigType): Test config. + + Returns: + Tensor: A tensor of segmentation mask. + """ + + batch_data_samples = [] + for metainfo in batch_img_metas: + metainfo['batch_input_shape'] = metainfo['img_shape'] + batch_data_samples.append(SegDataSample(metainfo=metainfo)) + # Forward function of MaskFormerHead from MMDetection needs + # 'batch_data_samples' as inputs, which is image shape actually. + all_cls_scores, all_mask_preds = self(x, batch_data_samples) + mask_cls_results = all_cls_scores[-1] + mask_pred_results = all_mask_preds[-1] + + # upsample masks + img_shape = batch_img_metas[0]['batch_input_shape'] + mask_pred_results = F.interpolate( + mask_pred_results, + size=img_shape, + mode='bilinear', + align_corners=False) + + # semantic inference + cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1] + mask_pred = mask_pred_results.sigmoid() + seg_logits = torch.einsum('bqc,bqhw->bchw', cls_score, mask_pred) + return seg_logits diff --git a/third-party/InterFormer/mmseg/models/decode_heads/nl_head.py b/third-party/InterFormer/mmseg/models/decode_heads/nl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffcc2a2f081127f109deb0ad5bd1be0d6f50493 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/nl_head.py @@ -0,0 +1,50 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import NonLocal2d + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + + +@MODELS.register_module() +class NLHead(FCNHead): + """Non-local Neural Networks. + + This head is the implementation of `NLNet + `_. + + Args: + reduction (int): Reduction factor of projection transform. Default: 2. + use_scale (bool): Whether to scale pairwise_weight by + sqrt(1/inter_channels). Default: True. + mode (str): The nonlocal mode. Options are 'embedded_gaussian', + 'dot_product'. Default: 'embedded_gaussian.'. + """ + + def __init__(self, + reduction=2, + use_scale=True, + mode='embedded_gaussian', + **kwargs): + super().__init__(num_convs=2, **kwargs) + self.reduction = reduction + self.use_scale = use_scale + self.mode = mode + self.nl_block = NonLocal2d( + in_channels=self.channels, + reduction=self.reduction, + use_scale=self.use_scale, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + mode=self.mode) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + output = self.convs[0](x) + output = self.nl_block(output) + output = self.convs[1](output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/ocr_head.py b/third-party/InterFormer/mmseg/models/decode_heads/ocr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9afe37bebd6c16ff184dc482ae358eb7ae9a093a --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/ocr_head.py @@ -0,0 +1,127 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import SelfAttentionBlock as _SelfAttentionBlock +from ..utils import resize +from .cascade_decode_head import BaseCascadeDecodeHead + + +class SpatialGatherModule(nn.Module): + """Aggregate the context features according to the initial predicted + probability distribution. + + Employ the soft-weighted method to aggregate the context. + """ + + def __init__(self, scale): + super().__init__() + self.scale = scale + + def forward(self, feats, probs): + """Forward function.""" + batch_size, num_classes, height, width = probs.size() + channels = feats.size(1) + probs = probs.view(batch_size, num_classes, -1) + feats = feats.view(batch_size, channels, -1) + # [batch_size, height*width, num_classes] + feats = feats.permute(0, 2, 1) + # [batch_size, channels, height*width] + probs = F.softmax(self.scale * probs, dim=2) + # [batch_size, channels, num_classes] + ocr_context = torch.matmul(probs, feats) + ocr_context = ocr_context.permute(0, 2, 1).contiguous().unsqueeze(3) + return ocr_context + + +class ObjectAttentionBlock(_SelfAttentionBlock): + """Make a OCR used SelfAttentionBlock.""" + + def __init__(self, in_channels, channels, scale, conv_cfg, norm_cfg, + act_cfg): + if scale > 1: + query_downsample = nn.MaxPool2d(kernel_size=scale) + else: + query_downsample = None + super().__init__( + key_in_channels=in_channels, + query_in_channels=in_channels, + channels=channels, + out_channels=in_channels, + share_key_query=False, + query_downsample=query_downsample, + key_downsample=None, + key_query_num_convs=2, + key_query_norm=True, + value_out_num_convs=1, + value_out_norm=True, + matmul_norm=True, + with_out=True, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.bottleneck = ConvModule( + in_channels * 2, + in_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, query_feats, key_feats): + """Forward function.""" + context = super().forward(query_feats, key_feats) + output = self.bottleneck(torch.cat([context, query_feats], dim=1)) + if self.query_downsample is not None: + output = resize(query_feats) + + return output + + +@MODELS.register_module() +class OCRHead(BaseCascadeDecodeHead): + """Object-Contextual Representations for Semantic Segmentation. + + This head is the implementation of `OCRNet + `_. + + Args: + ocr_channels (int): The intermediate channels of OCR block. + scale (int): The scale of probability map in SpatialGatherModule in + Default: 1. + """ + + def __init__(self, ocr_channels, scale=1, **kwargs): + super().__init__(**kwargs) + self.ocr_channels = ocr_channels + self.scale = scale + self.object_context_block = ObjectAttentionBlock( + self.channels, + self.ocr_channels, + self.scale, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.spatial_gather_module = SpatialGatherModule(self.scale) + + self.bottleneck = ConvModule( + self.in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs, prev_output): + """Forward function.""" + x = self._transform_inputs(inputs) + feats = self.bottleneck(x) + context = self.spatial_gather_module(feats, prev_output) + object_context = self.object_context_block(feats, context) + output = self.cls_seg(object_context) + + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/pid_head.py b/third-party/InterFormer/mmseg/models/decode_heads/pid_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c092cb32d07c279c1d6a45d2e02baccb8e5ffa33 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/pid_head.py @@ -0,0 +1,183 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional, Tuple, Union + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer +from mmengine.model import BaseModule +from torch import Tensor + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.models.losses import accuracy +from mmseg.models.utils import resize +from mmseg.registry import MODELS +from mmseg.utils import OptConfigType, SampleList + + +class BasePIDHead(BaseModule): + """Base class for PID head. + + Args: + in_channels (int): Number of input channels. + channels (int): Number of output channels. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + init_cfg (dict or list[dict], optional): Init config dict. + Default: None. + """ + + def __init__(self, + in_channels: int, + channels: int, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + self.conv = ConvModule( + in_channels, + channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + order=('norm', 'act', 'conv')) + _, self.norm = build_norm_layer(norm_cfg, num_features=channels) + self.act = build_activation_layer(act_cfg) + + def forward(self, x: Tensor, cls_seg: Optional[nn.Module]) -> Tensor: + """Forward function. + Args: + x (Tensor): Input tensor. + cls_seg (nn.Module, optional): The classification head. + + Returns: + Tensor: Output tensor. + """ + x = self.conv(x) + x = self.norm(x) + x = self.act(x) + if cls_seg is not None: + x = cls_seg(x) + return x + + +@MODELS.register_module() +class PIDHead(BaseDecodeHead): + """Decode head for PIDNet. + + Args: + in_channels (int): Number of input channels. + channels (int): Number of output channels. + num_classes (int): Number of classes. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + """ + + def __init__(self, + in_channels: int, + channels: int, + num_classes: int, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + **kwargs): + super().__init__( + in_channels, + channels, + num_classes=num_classes, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **kwargs) + self.i_head = BasePIDHead(in_channels, channels, norm_cfg, act_cfg) + self.p_head = BasePIDHead(in_channels // 2, channels, norm_cfg, + act_cfg) + self.d_head = BasePIDHead( + in_channels // 2, + in_channels // 4, + norm_cfg, + ) + self.p_cls_seg = nn.Conv2d(channels, self.out_channels, kernel_size=1) + self.d_cls_seg = nn.Conv2d(in_channels // 4, 1, kernel_size=1) + + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu') + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def forward( + self, + inputs: Union[Tensor, + Tuple[Tensor]]) -> Union[Tensor, Tuple[Tensor]]: + """Forward function. + Args: + inputs (Tensor | tuple[Tensor]): Input tensor or tuple of + Tensor. When training, the input is a tuple of three tensors, + (p_feat, i_feat, d_feat), and the output is a tuple of three + tensors, (p_seg_logit, i_seg_logit, d_seg_logit). + When inference, only the head of integral branch is used, and + input is a tensor of integral feature map, and the output is + the segmentation logit. + + Returns: + Tensor | tuple[Tensor]: Output tensor or tuple of tensors. + """ + if self.training: + x_p, x_i, x_d = inputs + x_p = self.p_head(x_p, self.p_cls_seg) + x_i = self.i_head(x_i, self.cls_seg) + x_d = self.d_head(x_d, self.d_cls_seg) + return x_p, x_i, x_d + else: + return self.i_head(inputs, self.cls_seg) + + def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tuple[Tensor]: + gt_semantic_segs = [ + data_sample.gt_sem_seg.data for data_sample in batch_data_samples + ] + gt_edge_segs = [ + data_sample.gt_edge_map.data for data_sample in batch_data_samples + ] + gt_sem_segs = torch.stack(gt_semantic_segs, dim=0) + gt_edge_segs = torch.stack(gt_edge_segs, dim=0) + return gt_sem_segs, gt_edge_segs + + def loss_by_feat(self, seg_logits: Tuple[Tensor], + batch_data_samples: SampleList) -> dict: + loss = dict() + p_logit, i_logit, d_logit = seg_logits + sem_label, bd_label = self._stack_batch_gt(batch_data_samples) + p_logit = resize( + input=p_logit, + size=sem_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + i_logit = resize( + input=i_logit, + size=sem_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + d_logit = resize( + input=d_logit, + size=bd_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + sem_label = sem_label.squeeze(1) + bd_label = bd_label.squeeze(1) + loss['loss_sem_p'] = self.loss_decode[0]( + p_logit, sem_label, ignore_index=self.ignore_index) + loss['loss_sem_i'] = self.loss_decode[1](i_logit, sem_label) + loss['loss_bd'] = self.loss_decode[2](d_logit, bd_label) + filler = torch.ones_like(sem_label) * self.ignore_index + sem_bd_label = torch.where( + torch.sigmoid(d_logit[:, 0, :, :]) > 0.8, sem_label, filler) + loss['loss_sem_bd'] = self.loss_decode[3](i_logit, sem_bd_label) + loss['acc_seg'] = accuracy( + i_logit, sem_label, ignore_index=self.ignore_index) + return loss diff --git a/third-party/InterFormer/mmseg/models/decode_heads/point_head.py b/third-party/InterFormer/mmseg/models/decode_heads/point_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e433d66249a4690cea3e33e95ec54d58ee3a07 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/point_head.py @@ -0,0 +1,367 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend/point_head/point_head.py # noqa + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +try: + from mmcv.ops import point_sample +except ModuleNotFoundError: + point_sample = None + +from typing import List + +from mmseg.registry import MODELS +from mmseg.utils import SampleList +from ..losses import accuracy +from ..utils import resize +from .cascade_decode_head import BaseCascadeDecodeHead + + +def calculate_uncertainty(seg_logits): + """Estimate uncertainty based on seg logits. + + For each location of the prediction ``seg_logits`` we estimate + uncertainty as the difference between top first and top second + predicted logits. + + Args: + seg_logits (Tensor): Semantic segmentation logits, + shape (batch_size, num_classes, height, width). + + Returns: + scores (Tensor): T uncertainty scores with the most uncertain + locations having the highest uncertainty score, shape ( + batch_size, 1, height, width) + """ + top2_scores = torch.topk(seg_logits, k=2, dim=1)[0] + return (top2_scores[:, 1] - top2_scores[:, 0]).unsqueeze(1) + + +@MODELS.register_module() +class PointHead(BaseCascadeDecodeHead): + """A mask point head use in PointRend. + + This head is implemented of `PointRend: Image Segmentation as + Rendering `_. + ``PointHead`` use shared multi-layer perceptron (equivalent to + nn.Conv1d) to predict the logit of input points. The fine-grained feature + and coarse feature will be concatenate together for predication. + + Args: + num_fcs (int): Number of fc layers in the head. Default: 3. + in_channels (int): Number of input channels. Default: 256. + fc_channels (int): Number of fc channels. Default: 256. + num_classes (int): Number of classes for logits. Default: 80. + class_agnostic (bool): Whether use class agnostic classification. + If so, the output channels of logits will be 1. Default: False. + coarse_pred_each_layer (bool): Whether concatenate coarse feature with + the output of each fc layer. Default: True. + conv_cfg (dict|None): Dictionary to construct and config conv layer. + Default: dict(type='Conv1d')) + norm_cfg (dict|None): Dictionary to construct and config norm layer. + Default: None. + loss_point (dict): Dictionary to construct and config loss layer of + point head. Default: dict(type='CrossEntropyLoss', use_mask=True, + loss_weight=1.0). + """ + + def __init__(self, + num_fcs=3, + coarse_pred_each_layer=True, + conv_cfg=dict(type='Conv1d'), + norm_cfg=None, + act_cfg=dict(type='ReLU', inplace=False), + **kwargs): + super().__init__( + input_transform='multiple_select', + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + init_cfg=dict( + type='Normal', std=0.01, override=dict(name='fc_seg')), + **kwargs) + if point_sample is None: + raise RuntimeError('Please install mmcv-full for ' + 'point_sample ops') + + self.num_fcs = num_fcs + self.coarse_pred_each_layer = coarse_pred_each_layer + + fc_in_channels = sum(self.in_channels) + self.num_classes + fc_channels = self.channels + self.fcs = nn.ModuleList() + for k in range(num_fcs): + fc = ConvModule( + fc_in_channels, + fc_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.fcs.append(fc) + fc_in_channels = fc_channels + fc_in_channels += self.num_classes if self.coarse_pred_each_layer \ + else 0 + self.fc_seg = nn.Conv1d( + fc_in_channels, + self.num_classes, + kernel_size=1, + stride=1, + padding=0) + if self.dropout_ratio > 0: + self.dropout = nn.Dropout(self.dropout_ratio) + delattr(self, 'conv_seg') + + def cls_seg(self, feat): + """Classify each pixel with fc.""" + if self.dropout is not None: + feat = self.dropout(feat) + output = self.fc_seg(feat) + return output + + def forward(self, fine_grained_point_feats, coarse_point_feats): + x = torch.cat([fine_grained_point_feats, coarse_point_feats], dim=1) + for fc in self.fcs: + x = fc(x) + if self.coarse_pred_each_layer: + x = torch.cat((x, coarse_point_feats), dim=1) + return self.cls_seg(x) + + def _get_fine_grained_point_feats(self, x, points): + """Sample from fine grained features. + + Args: + x (list[Tensor]): Feature pyramid from by neck or backbone. + points (Tensor): Point coordinates, shape (batch_size, + num_points, 2). + + Returns: + fine_grained_feats (Tensor): Sampled fine grained feature, + shape (batch_size, sum(channels of x), num_points). + """ + + fine_grained_feats_list = [ + point_sample(_, points, align_corners=self.align_corners) + for _ in x + ] + if len(fine_grained_feats_list) > 1: + fine_grained_feats = torch.cat(fine_grained_feats_list, dim=1) + else: + fine_grained_feats = fine_grained_feats_list[0] + + return fine_grained_feats + + def _get_coarse_point_feats(self, prev_output, points): + """Sample from fine grained features. + + Args: + prev_output (list[Tensor]): Prediction of previous decode head. + points (Tensor): Point coordinates, shape (batch_size, + num_points, 2). + + Returns: + coarse_feats (Tensor): Sampled coarse feature, shape (batch_size, + num_classes, num_points). + """ + + coarse_feats = point_sample( + prev_output, points, align_corners=self.align_corners) + + return coarse_feats + + def loss(self, inputs, prev_output, batch_data_samples: SampleList, + train_cfg, **kwargs): + """Forward function for training. + Args: + inputs (list[Tensor]): List of multi-level img features. + prev_output (Tensor): The output of previous decode head. + batch_data_samples (list[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `img_metas` or `gt_semantic_seg`. + train_cfg (dict): The training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + x = self._transform_inputs(inputs) + with torch.no_grad(): + points = self.get_points_train( + prev_output, calculate_uncertainty, cfg=train_cfg) + fine_grained_point_feats = self._get_fine_grained_point_feats( + x, points) + coarse_point_feats = self._get_coarse_point_feats(prev_output, points) + point_logits = self.forward(fine_grained_point_feats, + coarse_point_feats) + + losses = self.loss_by_feat(point_logits, points, batch_data_samples) + + return losses + + def predict(self, inputs, prev_output, batch_img_metas: List[dict], + test_cfg, **kwargs): + """Forward function for testing. + + Args: + inputs (list[Tensor]): List of multi-level img features. + prev_output (Tensor): The output of previous decode head. + img_metas (list[dict]): List of image info dict where each dict + has: 'img_shape', 'scale_factor', 'flip', and may also contain + 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:Collect`. + test_cfg (dict): The testing config. + + Returns: + Tensor: Output segmentation map. + """ + + x = self._transform_inputs(inputs) + refined_seg_logits = prev_output.clone() + for _ in range(test_cfg.subdivision_steps): + refined_seg_logits = resize( + refined_seg_logits, + scale_factor=test_cfg.scale_factor, + mode='bilinear', + align_corners=self.align_corners) + batch_size, channels, height, width = refined_seg_logits.shape + point_indices, points = self.get_points_test( + refined_seg_logits, calculate_uncertainty, cfg=test_cfg) + fine_grained_point_feats = self._get_fine_grained_point_feats( + x, points) + coarse_point_feats = self._get_coarse_point_feats( + prev_output, points) + point_logits = self.forward(fine_grained_point_feats, + coarse_point_feats) + + point_indices = point_indices.unsqueeze(1).expand(-1, channels, -1) + refined_seg_logits = refined_seg_logits.reshape( + batch_size, channels, height * width) + refined_seg_logits = refined_seg_logits.scatter_( + 2, point_indices, point_logits) + refined_seg_logits = refined_seg_logits.view( + batch_size, channels, height, width) + + return self.predict_by_feat(refined_seg_logits, batch_img_metas, + **kwargs) + + def loss_by_feat(self, point_logits, points, batch_data_samples, **kwargs): + """Compute segmentation loss.""" + gt_semantic_seg = self._stack_batch_gt(batch_data_samples) + point_label = point_sample( + gt_semantic_seg.float(), + points, + mode='nearest', + align_corners=self.align_corners) + point_label = point_label.squeeze(1).long() + + loss = dict() + if not isinstance(self.loss_decode, nn.ModuleList): + losses_decode = [self.loss_decode] + else: + losses_decode = self.loss_decode + for loss_module in losses_decode: + loss['point' + loss_module.loss_name] = loss_module( + point_logits, point_label, ignore_index=self.ignore_index) + + loss['acc_point'] = accuracy( + point_logits, point_label, ignore_index=self.ignore_index) + return loss + + def get_points_train(self, seg_logits, uncertainty_func, cfg): + """Sample points for training. + + Sample points in [0, 1] x [0, 1] coordinate space based on their + uncertainty. The uncertainties are calculated for each point using + 'uncertainty_func' function that takes point's logit prediction as + input. + + Args: + seg_logits (Tensor): Semantic segmentation logits, shape ( + batch_size, num_classes, height, width). + uncertainty_func (func): uncertainty calculation function. + cfg (dict): Training config of point head. + + Returns: + point_coords (Tensor): A tensor of shape (batch_size, num_points, + 2) that contains the coordinates of ``num_points`` sampled + points. + """ + num_points = cfg.num_points + oversample_ratio = cfg.oversample_ratio + importance_sample_ratio = cfg.importance_sample_ratio + assert oversample_ratio >= 1 + assert 0 <= importance_sample_ratio <= 1 + batch_size = seg_logits.shape[0] + num_sampled = int(num_points * oversample_ratio) + point_coords = torch.rand( + batch_size, num_sampled, 2, device=seg_logits.device) + point_logits = point_sample(seg_logits, point_coords) + # It is crucial to calculate uncertainty based on the sampled + # prediction value for the points. Calculating uncertainties of the + # coarse predictions first and sampling them for points leads to + # incorrect results. To illustrate this: assume uncertainty func( + # logits)=-abs(logits), a sampled point between two coarse + # predictions with -1 and 1 logits has 0 logits, and therefore 0 + # uncertainty value. However, if we calculate uncertainties for the + # coarse predictions first, both will have -1 uncertainty, + # and sampled point will get -1 uncertainty. + point_uncertainties = uncertainty_func(point_logits) + num_uncertain_points = int(importance_sample_ratio * num_points) + num_random_points = num_points - num_uncertain_points + idx = torch.topk( + point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1] + shift = num_sampled * torch.arange( + batch_size, dtype=torch.long, device=seg_logits.device) + idx += shift[:, None] + point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view( + batch_size, num_uncertain_points, 2) + if num_random_points > 0: + rand_point_coords = torch.rand( + batch_size, num_random_points, 2, device=seg_logits.device) + point_coords = torch.cat((point_coords, rand_point_coords), dim=1) + return point_coords + + def get_points_test(self, seg_logits, uncertainty_func, cfg): + """Sample points for testing. + + Find ``num_points`` most uncertain points from ``uncertainty_map``. + + Args: + seg_logits (Tensor): A tensor of shape (batch_size, num_classes, + height, width) for class-specific or class-agnostic prediction. + uncertainty_func (func): uncertainty calculation function. + cfg (dict): Testing config of point head. + + Returns: + point_indices (Tensor): A tensor of shape (batch_size, num_points) + that contains indices from [0, height x width) of the most + uncertain points. + point_coords (Tensor): A tensor of shape (batch_size, num_points, + 2) that contains [0, 1] x [0, 1] normalized coordinates of the + most uncertain points from the ``height x width`` grid . + """ + + num_points = cfg.subdivision_num_points + uncertainty_map = uncertainty_func(seg_logits) + batch_size, _, height, width = uncertainty_map.shape + h_step = 1.0 / height + w_step = 1.0 / width + + uncertainty_map = uncertainty_map.view(batch_size, height * width) + num_points = min(height * width, num_points) + point_indices = uncertainty_map.topk(num_points, dim=1)[1] + point_coords = torch.zeros( + batch_size, + num_points, + 2, + dtype=torch.float, + device=seg_logits.device) + point_coords[:, :, 0] = w_step / 2.0 + (point_indices % + width).float() * w_step + point_coords[:, :, 1] = h_step / 2.0 + (point_indices // + width).float() * h_step + return point_indices, point_coords diff --git a/third-party/InterFormer/mmseg/models/decode_heads/psa_head.py b/third-party/InterFormer/mmseg/models/decode_heads/psa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..13ee5c58a569bb46612625b85685cd61b7e9df3e --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/psa_head.py @@ -0,0 +1,197 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + +try: + from mmcv.ops import PSAMask +except ModuleNotFoundError: + PSAMask = None + + +@MODELS.register_module() +class PSAHead(BaseDecodeHead): + """Point-wise Spatial Attention Network for Scene Parsing. + + This head is the implementation of `PSANet + `_. + + Args: + mask_size (tuple[int]): The PSA mask size. It usually equals input + size. + psa_type (str): The type of psa module. Options are 'collect', + 'distribute', 'bi-direction'. Default: 'bi-direction' + compact (bool): Whether use compact map for 'collect' mode. + Default: True. + shrink_factor (int): The downsample factors of psa mask. Default: 2. + normalization_factor (float): The normalize factor of attention. + psa_softmax (bool): Whether use softmax for attention. + """ + + def __init__(self, + mask_size, + psa_type='bi-direction', + compact=False, + shrink_factor=2, + normalization_factor=1.0, + psa_softmax=True, + **kwargs): + if PSAMask is None: + raise RuntimeError('Please install mmcv-full for PSAMask ops') + super().__init__(**kwargs) + assert psa_type in ['collect', 'distribute', 'bi-direction'] + self.psa_type = psa_type + self.compact = compact + self.shrink_factor = shrink_factor + self.mask_size = mask_size + mask_h, mask_w = mask_size + self.psa_softmax = psa_softmax + if normalization_factor is None: + normalization_factor = mask_h * mask_w + self.normalization_factor = normalization_factor + + self.reduce = ConvModule( + self.in_channels, + self.channels, + kernel_size=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.attention = nn.Sequential( + ConvModule( + self.channels, + self.channels, + kernel_size=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + nn.Conv2d( + self.channels, mask_h * mask_w, kernel_size=1, bias=False)) + if psa_type == 'bi-direction': + self.reduce_p = ConvModule( + self.in_channels, + self.channels, + kernel_size=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.attention_p = nn.Sequential( + ConvModule( + self.channels, + self.channels, + kernel_size=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + nn.Conv2d( + self.channels, mask_h * mask_w, kernel_size=1, bias=False)) + self.psamask_collect = PSAMask('collect', mask_size) + self.psamask_distribute = PSAMask('distribute', mask_size) + else: + self.psamask = PSAMask(psa_type, mask_size) + self.proj = ConvModule( + self.channels * (2 if psa_type == 'bi-direction' else 1), + self.in_channels, + kernel_size=1, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.bottleneck = ConvModule( + self.in_channels * 2, + self.channels, + kernel_size=3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + identity = x + align_corners = self.align_corners + if self.psa_type in ['collect', 'distribute']: + out = self.reduce(x) + n, c, h, w = out.size() + if self.shrink_factor != 1: + if h % self.shrink_factor and w % self.shrink_factor: + h = (h - 1) // self.shrink_factor + 1 + w = (w - 1) // self.shrink_factor + 1 + align_corners = True + else: + h = h // self.shrink_factor + w = w // self.shrink_factor + align_corners = False + out = resize( + out, + size=(h, w), + mode='bilinear', + align_corners=align_corners) + y = self.attention(out) + if self.compact: + if self.psa_type == 'collect': + y = y.view(n, h * w, + h * w).transpose(1, 2).view(n, h * w, h, w) + else: + y = self.psamask(y) + if self.psa_softmax: + y = F.softmax(y, dim=1) + out = torch.bmm( + out.view(n, c, h * w), y.view(n, h * w, h * w)).view( + n, c, h, w) * (1.0 / self.normalization_factor) + else: + x_col = self.reduce(x) + x_dis = self.reduce_p(x) + n, c, h, w = x_col.size() + if self.shrink_factor != 1: + if h % self.shrink_factor and w % self.shrink_factor: + h = (h - 1) // self.shrink_factor + 1 + w = (w - 1) // self.shrink_factor + 1 + align_corners = True + else: + h = h // self.shrink_factor + w = w // self.shrink_factor + align_corners = False + x_col = resize( + x_col, + size=(h, w), + mode='bilinear', + align_corners=align_corners) + x_dis = resize( + x_dis, + size=(h, w), + mode='bilinear', + align_corners=align_corners) + y_col = self.attention(x_col) + y_dis = self.attention_p(x_dis) + if self.compact: + y_dis = y_dis.view(n, h * w, + h * w).transpose(1, 2).view(n, h * w, h, w) + else: + y_col = self.psamask_collect(y_col) + y_dis = self.psamask_distribute(y_dis) + if self.psa_softmax: + y_col = F.softmax(y_col, dim=1) + y_dis = F.softmax(y_dis, dim=1) + x_col = torch.bmm( + x_col.view(n, c, h * w), y_col.view(n, h * w, h * w)).view( + n, c, h, w) * (1.0 / self.normalization_factor) + x_dis = torch.bmm( + x_dis.view(n, c, h * w), y_dis.view(n, h * w, h * w)).view( + n, c, h, w) * (1.0 / self.normalization_factor) + out = torch.cat([x_col, x_dis], 1) + out = self.proj(out) + out = resize( + out, + size=identity.shape[2:], + mode='bilinear', + align_corners=align_corners) + out = self.bottleneck(torch.cat((identity, out), dim=1)) + out = self.cls_seg(out) + return out diff --git a/third-party/InterFormer/mmseg/models/decode_heads/psp_head.py b/third-party/InterFormer/mmseg/models/decode_heads/psp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a40ec41dec281e53815e9753ee2ba1a5da76bd05 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/psp_head.py @@ -0,0 +1,117 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class PPM(nn.ModuleList): + """Pooling Pyramid Module used in PSPNet. + + Args: + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module. + in_channels (int): Input channels. + channels (int): Channels after modules, before conv_seg. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict): Config of activation layers. + align_corners (bool): align_corners argument of F.interpolate. + """ + + def __init__(self, pool_scales, in_channels, channels, conv_cfg, norm_cfg, + act_cfg, align_corners, **kwargs): + super().__init__() + self.pool_scales = pool_scales + self.align_corners = align_corners + self.in_channels = in_channels + self.channels = channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + for pool_scale in pool_scales: + self.append( + nn.Sequential( + nn.AdaptiveAvgPool2d(pool_scale), + ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + **kwargs))) + + def forward(self, x): + """Forward function.""" + ppm_outs = [] + for ppm in self: + ppm_out = ppm(x) + upsampled_ppm_out = resize( + ppm_out, + size=x.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + ppm_outs.append(upsampled_ppm_out) + return ppm_outs + + +@MODELS.register_module() +class PSPHead(BaseDecodeHead): + """Pyramid Scene Parsing Network. + + This head is the implementation of + `PSPNet `_. + + Args: + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module. Default: (1, 2, 3, 6). + """ + + def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): + super().__init__(**kwargs) + assert isinstance(pool_scales, (list, tuple)) + self.pool_scales = pool_scales + self.psp_modules = PPM( + self.pool_scales, + self.in_channels, + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + self.bottleneck = ConvModule( + self.in_channels + len(pool_scales) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def _forward_feature(self, inputs): + """Forward function for feature maps before classifying each pixel with + ``self.cls_seg`` fc. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + feats (Tensor): A tensor of shape (batch_size, self.channels, + H, W) which is feature map for last layer of decoder head. + """ + x = self._transform_inputs(inputs) + psp_outs = [x] + psp_outs.extend(self.psp_modules(x)) + psp_outs = torch.cat(psp_outs, dim=1) + feats = self.bottleneck(psp_outs) + return feats + + def forward(self, inputs): + """Forward function.""" + output = self._forward_feature(inputs) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/san_head.py b/third-party/InterFormer/mmseg/models/decode_heads/san_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d20da801924080efeee30a246331af2e2e5df352 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/san_head.py @@ -0,0 +1,736 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from functools import partial +from typing import Dict, List, Tuple + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, build_norm_layer +from mmcv.cnn.bricks.transformer import BaseTransformerLayer +from mmcv.ops import point_sample +from mmengine.dist import all_reduce +from mmengine.model.weight_init import (caffe2_xavier_init, normal_init, + trunc_normal_) +from mmengine.runner.checkpoint import CheckpointLoader, load_state_dict +from mmengine.structures import InstanceData +from torch import Tensor +from torch.nn import functional as F + +from mmseg.models.backbones.vit import TransformerEncoderLayer +from mmseg.registry import MODELS +from mmseg.utils import (ConfigType, MatchMasks, SampleList, + seg_data_to_instance_data) +from ..utils import (MLP, LayerNorm2d, PatchEmbed, cross_attn_layer, + get_uncertain_point_coords_with_randomness, resize) +from .decode_head import BaseDecodeHead + + +class MLPMaskDecoder(nn.Module): + """Module for decoding query and visual features with MLP layers to + generate the attention biases and the mask proposals.""" + + def __init__( + self, + *, + in_channels: int, + total_heads: int = 1, + total_layers: int = 1, + embed_channels: int = 256, + mlp_channels: int = 256, + mlp_num_layers: int = 3, + rescale_attn_bias: bool = False, + ): + super().__init__() + self.total_heads = total_heads + self.total_layers = total_layers + + dense_affine_func = partial(nn.Conv2d, kernel_size=1) + # Query Branch + self.query_mlp = MLP(in_channels, mlp_channels, embed_channels, + mlp_num_layers) + # Pixel Branch + self.pix_mlp = MLP( + in_channels, + mlp_channels, + embed_channels, + mlp_num_layers, + affine_func=dense_affine_func, + ) + # Attention Bias Branch + self.attn_mlp = MLP( + in_channels, + mlp_channels, + embed_channels * self.total_heads * self.total_layers, + mlp_num_layers, + affine_func=dense_affine_func, + ) + if rescale_attn_bias: + self.bias_scaling = nn.Linear(1, 1) + else: + self.bias_scaling = nn.Identity() + + def forward(self, query: torch.Tensor, + x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: + """Forward function. + Args: + query (Tensor): Query Tokens [B,N,C]. + x (Tensor): Visual features [B,C,H,W] + + Return: + mask_preds (Tensor): Mask proposals. + attn_bias (List[Tensor]): List of attention bias. + """ + query = self.query_mlp(query) + pix = self.pix_mlp(x) + b, c, h, w = pix.shape + # preidict mask + mask_preds = torch.einsum('bqc,bchw->bqhw', query, pix) + # generate attn bias + attn = self.attn_mlp(x) + attn = attn.reshape(b, self.total_layers, self.total_heads, c, h, w) + attn_bias = torch.einsum('bqc,blnchw->blnqhw', query, attn) + attn_bias = self.bias_scaling(attn_bias[..., None]).squeeze(-1) + attn_bias = attn_bias.chunk(self.total_layers, dim=1) + attn_bias = [attn.squeeze(1) for attn in attn_bias] + return mask_preds, attn_bias + + +class SideAdapterNetwork(nn.Module): + """Side Adapter Network for predicting mask proposals and attention bias. + + Args: + in_channels (int): Number of input channels. Default: 3. + clip_channels (int): Number of channels of visual features. + Default: 768. + embed_dims (int): embedding dimension. Default: 240. + patch_size (int): The patch size. Default: 16. + patch_bias (bool): Whether use bias in patch embedding. + Default: True. + num_queries (int): Number of queries for mask proposals. + Default: 100. + fusion_index (List[int]): The layer number of the encode + transformer to fuse with the CLIP feature. + Default: [0, 1, 2, 3]. + cfg_encoder (ConfigType): Configs for the encode layers. + cfg_decoder (ConfigType): Configs for the decode layers. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + """ + + def __init__( + self, + in_channels: int = 3, + clip_channels: int = 768, + embed_dims: int = 240, + patch_size: int = 16, + patch_bias: bool = True, + num_queries: int = 100, + fusion_index: list = [0, 1, 2, 3], + cfg_encoder: ConfigType = ..., + cfg_decoder: ConfigType = ..., + norm_cfg: dict = dict(type='LN'), + ): + super().__init__() + + self.patch_embed = PatchEmbed( + in_channels=in_channels, + embed_dims=embed_dims, + conv_type='Conv2d', + kernel_size=patch_size, + stride=patch_size, + padding=0, + input_size=(640, 640), + bias=patch_bias, + norm_cfg=None, + init_cfg=None, + ) + ori_h, ori_w = self.patch_embed.init_out_size + num_patches = ori_h * ori_w + self.pos_embed = nn.Parameter( + torch.randn(1, num_patches, embed_dims) * .02) + self.query_pos_embed = nn.Parameter( + torch.zeros(1, num_queries, embed_dims)) + self.query_embed = nn.Parameter( + torch.zeros(1, num_queries, embed_dims)) + encode_layers = [] + for i in range(cfg_encoder.num_encode_layer): + encode_layers.append( + TransformerEncoderLayer( + embed_dims=embed_dims, + num_heads=cfg_encoder.num_heads, + feedforward_channels=cfg_encoder.mlp_ratio * embed_dims, + norm_cfg=norm_cfg)) + self.encode_layers = nn.ModuleList(encode_layers) + conv_clips = [] + for i in range(len(fusion_index)): + conv_clips.append( + nn.Sequential( + LayerNorm2d(clip_channels), + ConvModule( + clip_channels, + embed_dims, + kernel_size=1, + norm_cfg=None, + act_cfg=None))) + self.conv_clips = nn.ModuleList(conv_clips) + self.fusion_index = fusion_index + self.mask_decoder = MLPMaskDecoder( + in_channels=embed_dims, + total_heads=cfg_decoder.num_heads, + total_layers=cfg_decoder.num_layers, + embed_channels=cfg_decoder.embed_channels, + mlp_channels=cfg_decoder.mlp_channels, + mlp_num_layers=cfg_decoder.num_mlp, + rescale_attn_bias=cfg_decoder.rescale) + + def init_weights(self): + trunc_normal_(self.pos_embed, std=0.02) + nn.init.normal_(self.query_embed, std=0.02) + nn.init.normal_(self.query_pos_embed, std=0.02) + for i in range(len(self.conv_clips)): + caffe2_xavier_init(self.conv_clips[i][1].conv) + + def fuse_clip(self, fused_index: int, x: torch.Tensor, + clip_feature: torch.Tensor, hwshape: Tuple[int, + int], L: int): + """Fuse CLIP feature and visual tokens.""" + fused_clip = (resize( + self.conv_clips[fused_index](clip_feature.contiguous()), + size=hwshape, + mode='bilinear', + align_corners=False)).permute(0, 2, 3, 1).reshape(x[:, -L:, + ...].shape) + x = torch.cat([x[:, :-L, ...], x[:, -L:, ...] + fused_clip], dim=1) + return x + + def encode_feature(self, image: torch.Tensor, + clip_features: List[torch.Tensor], + deep_supervision_idxs: List[int]) -> List[List]: + """Encode images by a lightweight vision transformer.""" + assert len(self.fusion_index) == len(clip_features) + x, hwshape = self.patch_embed(image) + ori_h, ori_w = self.patch_embed.init_out_size + pos_embed = self.pos_embed + if self.pos_embed.shape[1] != x.shape[1]: + # resize the position embedding + pos_embed = ( + resize( + self.pos_embed.reshape(1, ori_h, ori_w, + -1).permute(0, 3, 1, 2), + size=hwshape, + mode='bicubic', + align_corners=False, + ).flatten(2).permute(0, 2, 1)) + pos_embed = torch.cat([ + self.query_pos_embed.expand(pos_embed.shape[0], -1, -1), pos_embed + ], + dim=1) + x = torch.cat([self.query_embed.expand(x.shape[0], -1, -1), x], dim=1) + x = x + pos_embed + L = hwshape[0] * hwshape[1] + fused_index = 0 + if self.fusion_index[fused_index] == 0: + x = self.fuse_clip(fused_index, x, clip_features[0][0], hwshape, L) + fused_index += 1 + outs = [] + for index, block in enumerate(self.encode_layers, start=1): + x = block(x) + if index < len(self.fusion_index + ) and index == self.fusion_index[fused_index]: + x = self.fuse_clip(fused_index, x, + clip_features[fused_index][0], hwshape, L) + fused_index += 1 + x_query = x[:, :-L, ...] + x_feat = x[:, -L:, ...].permute(0, 2, 1)\ + .reshape(x.shape[0], x.shape[-1], hwshape[0], hwshape[1]) + + if index in deep_supervision_idxs or index == len( + self.encode_layers): + outs.append({'query': x_query, 'x': x_feat}) + + if index < len(self.encode_layers): + x = x + pos_embed + return outs + + def decode_feature(self, features): + mask_embeds = [] + attn_biases = [] + for feature in features: + mask_embed, attn_bias = self.mask_decoder(**feature) + mask_embeds.append(mask_embed) + attn_biases.append(attn_bias) + return mask_embeds, attn_biases + + def forward( + self, image: torch.Tensor, clip_features: List[torch.Tensor], + deep_supervision_idxs: List[int] + ) -> Tuple[List[torch.Tensor], List[List[torch.Tensor]]]: + """Forward function.""" + features = self.encode_feature(image, clip_features, + deep_supervision_idxs) + mask_embeds, attn_biases = self.decode_feature(features) + return mask_embeds, attn_biases + + +class RecWithAttnbias(nn.Module): + """Mask recognition module by applying the attention biases to rest deeper + CLIP layers. + + Args: + sos_token_format (str): The format of sos token. It should be + chosen from ["cls_token", "learnable_token", "pos_embedding"]. + Default: 'cls_token'. + sos_token_num (int): Number of sos token. It should be equal to + the number of quries. Default: 100. + num_layers (int): Number of rest CLIP layers for mask recognition. + Default: 3. + cross_attn (bool): Whether use cross attention to update sos token. + Default: False. + embed_dims (int): The feature dimension of CLIP layers. + Default: 768. + num_heads (int): Parallel attention heads of CLIP layers. + Default: 768. + mlp_ratio (int): Ratio of mlp hidden dim to embedding dim. + Default: 4. + qkv_bias (bool): Whether to use bias in multihead-attention. + Default: True. + out_dims (int): Number of channels of the output mask proposals. + It should be equal to the out_dims of text_encoder. + Default: 512. + final_norm (True): Whether use norm layer for sos token. + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + frozen_exclude (List): List of parameters that are not to be frozen. + """ + + def __init__(self, + sos_token_format: str = 'cls_token', + sos_token_num: int = 100, + num_layers: int = 3, + cross_attn: bool = False, + embed_dims: int = 768, + num_heads: int = 12, + mlp_ratio: int = 4, + num_fcs: int = 2, + qkv_bias: bool = True, + out_dims: int = 512, + final_norm: bool = True, + act_cfg: dict = dict(type='GELU'), + norm_cfg: dict = dict(type='LN'), + frozen_exclude: List = []): + super().__init__() + + assert sos_token_format in [ + 'cls_token', 'learnable_token', 'pos_embedding' + ] + self.sos_token_format = sos_token_format + self.sos_token_num = sos_token_num + self.frozen_exclude = frozen_exclude + self.cross_attn = cross_attn + self.num_layers = num_layers + self.num_heads = num_heads + if sos_token_format in ['learnable_token', 'pos_embedding']: + self.sos_token = nn.Parameter( + torch.randn(sos_token_num, 1, self.proj.shape[0])) + self.frozen.append('sos_token') + + layers = [] + for i in range(num_layers): + layers.append( + BaseTransformerLayer( + attn_cfgs=dict( + type='MultiheadAttention', + embed_dims=embed_dims, + num_heads=num_heads, + batch_first=False, + bias=qkv_bias), + ffn_cfgs=dict( + type='FFN', + embed_dims=embed_dims, + feedforward_channels=mlp_ratio * embed_dims, + act_cfg=act_cfg), + operation_order=('norm', 'self_attn', 'norm', 'ffn'))) + self.layers = nn.ModuleList(layers) + + self.ln_post = build_norm_layer(norm_cfg, embed_dims)[1] + self.proj = nn.Linear(embed_dims, out_dims, bias=False) + + self.final_norm = final_norm + self._freeze() + + def init_weights(self, rec_state_dict): + if hasattr(self, 'sos_token'): + normal_init(self.sos_token, std=0.02) + if rec_state_dict is not None: + load_state_dict(self, rec_state_dict, strict=False, logger=None) + else: + super().init_weights() + + def _freeze(self): + if 'all' in self.frozen_exclude: + return + for name, param in self.named_parameters(): + if not any([exclude in name for exclude in self.frozen_exclude]): + param.requires_grad = False + + def _build_attn_biases(self, attn_biases, target_shape): + formatted_attn_biases = [] + for attn_bias in attn_biases: + # convert it to proper format: N*num_head,L,L + # attn_bias: [N, num_head/1, num_sos,H,W] + n, num_head, num_sos, h, w = attn_bias.shape + # reshape and downsample + attn_bias = F.adaptive_max_pool2d( + attn_bias.reshape(n, num_head * num_sos, h, w), + output_size=target_shape) + attn_bias = attn_bias.reshape(n, num_head, num_sos, *target_shape) + + true_num_head = self.num_heads + assert (num_head == 1 or num_head + == true_num_head), f'num_head={num_head} is not supported.' + if num_head == 1: + attn_bias = attn_bias.repeat(1, true_num_head, 1, 1, 1) + attn_bias = attn_bias.reshape(n * true_num_head, num_sos, -1) + L = attn_bias.shape[-1] + if self.cross_attn: + # [n*num_head, num_sos, L] + formatted_attn_biases.append(attn_bias) + else: + # [n*num_head, num_sos+1+L, num_sos+1+L] + new_attn_bias = attn_bias.new_zeros(num_sos + 1 + L, + num_sos + 1 + L) + new_attn_bias[:, :num_sos] = -100 + new_attn_bias[torch.arange(num_sos), torch.arange(num_sos)] = 0 + new_attn_bias[:num_sos, num_sos] = -100 + new_attn_bias = ( + new_attn_bias[None, ...].expand(n * true_num_head, -1, + -1).clone()) + new_attn_bias[..., :num_sos, -L:] = attn_bias + formatted_attn_biases.append(new_attn_bias) + + if len(formatted_attn_biases) == 1: + formatted_attn_biases = [ + formatted_attn_biases[0] for _ in range(self.num_layers) + ] + return formatted_attn_biases + + def forward(self, bias: List[Tensor], feature: List[Tensor]): + """Forward function to recognize the category of masks + Args: + bias (List[Tensor]): Attention bias for transformer layers + feature (List[Tensor]): Output of the image encoder, + including cls_token and img_feature. + """ + cls_token = feature[1].unsqueeze(0) + img_feature = feature[0] + b, c, h, w = img_feature.shape + # construct clip shadow features + x = torch.cat( + [cls_token, + img_feature.reshape(b, c, -1).permute(2, 0, 1)]) + + # construct sos token + if self.sos_token_format == 'cls_token': + sos_token = cls_token.repeat(self.sos_token_num, 1, 1) + elif self.sos_token_format == 'learnable_token': + sos_token = self.sos_token.expand(-1, b, -1) + elif self.sos_token_format == 'pos_embedding': + sos_token = self.sos_token.expand(-1, b, -1) + cls_token + + # construct attn bias + attn_biases = self._build_attn_biases(bias, target_shape=(h, w)) + + if self.cross_attn: + for i, block in enumerate(self.layers): + if self.cross_attn: + sos_token = cross_attn_layer( + block, + sos_token, + x[1:, ], + attn_biases[i], + ) + if i < len(self.layers) - 1: + x = block(x) + else: + x = torch.cat([sos_token, x], dim=0) + for i, block in enumerate(self.layers): + x = block(x, attn_masks=[attn_biases[i]]) + sos_token = x[:self.sos_token_num] + + sos_token = sos_token.permute(1, 0, 2) # LND -> NLD + sos_token = self.ln_post(sos_token) + sos_token = self.proj(sos_token) + if self.final_norm: + sos_token = F.normalize(sos_token, dim=-1) + return sos_token + + +@MODELS.register_module() +class SideAdapterCLIPHead(BaseDecodeHead): + """Side Adapter Network (SAN) for open-vocabulary semantic segmentation + with pre-trained vision-language model. + + This decode head is the implementation of `Side Adapter Network + for Open-Vocabulary Semantic Segmentation` + . + Modified from https://github.com/MendelXu/SAN/blob/main/san/model/side_adapter/side_adapter.py # noqa:E501 + Copyright (c) 2023 MendelXu. + Licensed under the MIT License + + Args: + num_classes (int): the number of classes. + san_cfg (ConfigType): Configs for SideAdapterNetwork module + maskgen_cfg (ConfigType): Configs for RecWithAttnbias module + """ + + def __init__(self, num_classes: int, san_cfg: ConfigType, + maskgen_cfg: ConfigType, deep_supervision_idxs: List[int], + train_cfg: ConfigType, **kwargs): + super().__init__( + in_channels=san_cfg.in_channels, + channels=san_cfg.embed_dims, + num_classes=num_classes, + **kwargs) + assert san_cfg.num_queries == maskgen_cfg.sos_token_num, \ + 'num_queries in san_cfg should be equal to sos_token_num ' \ + 'in maskgen_cfg' + del self.conv_seg + self.side_adapter_network = SideAdapterNetwork(**san_cfg) + self.rec_with_attnbias = RecWithAttnbias(**maskgen_cfg) + self.deep_supervision_idxs = deep_supervision_idxs + self.train_cfg = train_cfg + if train_cfg: + self.match_masks = MatchMasks( + num_points=train_cfg.num_points, + num_queries=san_cfg.num_queries, + num_classes=num_classes, + assigner=train_cfg.assigner) + + def init_weights(self): + + rec_state_dict = None + if isinstance(self.init_cfg, dict) and \ + self.init_cfg.get('type') == 'Pretrained_Part': + checkpoint = CheckpointLoader.load_checkpoint( + self.init_cfg['checkpoint'], logger=None, map_location='cpu') + + rec_state_dict = checkpoint.copy() + para_prefix = 'decode_head.rec_with_attnbias' + prefix_len = len(para_prefix) + 1 + for k, v in checkpoint.items(): + rec_state_dict.pop(k) + if para_prefix in k: + rec_state_dict[k[prefix_len:]] = v + + self.side_adapter_network.init_weights() + self.rec_with_attnbias.init_weights(rec_state_dict) + + def forward(self, inputs: Tuple[Tensor], + deep_supervision_idxs) -> Tuple[List]: + """Forward function. + + Args: + inputs (Tuple[Tensor]): A triplet including images, + list of multi-level visual features from image encoder and + class embeddings from text_encoder. + + Returns: + mask_props (List[Tensor]): Mask proposals predicted by SAN. + mask_logits (List[Tensor]): Class logits of mask proposals. + """ + imgs, clip_feature, class_embeds = inputs + # predict mask proposals and attention bias + mask_props, attn_biases = self.side_adapter_network( + imgs, clip_feature, deep_supervision_idxs) + + # mask recognition with attention bias + mask_embeds = [ + self.rec_with_attnbias(att_bias, clip_feature[-1]) + for att_bias in attn_biases + ] + # Obtain class prediction of masks by comparing the similarity + # between the image token and the text embedding of class names. + mask_logits = [ + torch.einsum('bqc,nc->bqn', mask_embed, class_embeds) + for mask_embed in mask_embeds + ] + return mask_props, mask_logits + + def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tensor: + """Forward function for prediction. + + Args: + inputs (Tuple[Tensor]): Images, visual features from image encoder + and class embedding from text encoder. + batch_img_metas (dict): List Image info where each dict may also + contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + test_cfg (dict): The testing config. + + Returns: + Tensor: Outputs segmentation logits map. + """ + mask_props, mask_logits = self.forward(inputs, []) + + return self.predict_by_feat([mask_props[-1], mask_logits[-1]], + batch_img_metas) + + def predict_by_feat(self, seg_logits: List[Tensor], + batch_img_metas: List[dict]) -> Tensor: + """1. Transform a batch of mask proposals to the input shape. + 2. Generate segmentation map with mask proposals and class logits. + """ + mask_pred = seg_logits[0] + cls_score = seg_logits[1] + if isinstance(batch_img_metas[0]['img_shape'], torch.Size): + # slide inference + size = batch_img_metas[0]['img_shape'] + elif 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'][:2] + else: + size = batch_img_metas[0]['img_shape'] + # upsample mask + mask_pred = F.interpolate( + mask_pred, size=size, mode='bilinear', align_corners=False) + + mask_cls = F.softmax(cls_score, dim=-1)[..., :-1] + mask_pred = mask_pred.sigmoid() + seg_logits = torch.einsum('bqc,bqhw->bchw', mask_cls, mask_pred) + return seg_logits + + def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + """Perform forward propagation and loss calculation of the decoder head + on the features of the upstream network. + + Args: + x (tuple[Tensor]): Multi-level features from the upstream + network, each is a 4D-tensor. + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + train_cfg (ConfigType): Training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components. + """ + # batch SegDataSample to InstanceDataSample + batch_gt_instances = seg_data_to_instance_data(self.ignore_index, + batch_data_samples) + + # forward + all_mask_props, all_mask_logits = self.forward( + x, self.deep_supervision_idxs) + + # loss + losses = self.loss_by_feat(all_mask_logits, all_mask_props, + batch_gt_instances) + + return losses + + def loss_by_feat( + self, all_cls_scores: Tensor, all_mask_preds: Tensor, + batch_gt_instances: List[InstanceData]) -> Dict[str, Tensor]: + """Loss function. + + Args: + all_cls_scores (Tensor): Classification scores for all decoder + layers with shape (num_decoder, batch_size, num_queries, + cls_out_channels). Note `cls_out_channels` should includes + background. + all_mask_preds (Tensor): Mask scores for all decoder layers with + shape (num_decoder, batch_size, num_queries, h, w). + batch_gt_instances (list[obj:`InstanceData`]): each contains + ``labels`` and ``masks``. + + Returns: + dict[str, Tensor]: A dictionary of loss components. + """ + num_dec_layers = len(all_cls_scores) + batch_gt_instances_list = [ + batch_gt_instances for _ in range(num_dec_layers) + ] + + losses = [] + for i in range(num_dec_layers): + cls_scores = all_cls_scores[i] + mask_preds = all_mask_preds[i] + # matching N mask predictions to K category labels + (labels, mask_targets, mask_weights, + avg_factor) = self.match_masks.get_targets( + cls_scores, mask_preds, batch_gt_instances_list[i]) + cls_scores = cls_scores.flatten(0, 1) + labels = labels.flatten(0, 1) + num_total_masks = cls_scores.new_tensor([avg_factor], + dtype=torch.float) + all_reduce(num_total_masks, op='mean') + num_total_masks = max(num_total_masks, 1) + + # extract positive ones + # shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w) + mask_preds = mask_preds[mask_weights > 0] + + if mask_targets.shape[0] != 0: + with torch.no_grad(): + points_coords = get_uncertain_point_coords_with_randomness( + mask_preds.unsqueeze(1), None, + self.train_cfg.num_points, + self.train_cfg.oversample_ratio, + self.train_cfg.importance_sample_ratio) + # shape (num_total_gts, h, w) + # -> (num_total_gts, num_points) + mask_point_targets = point_sample( + mask_targets.unsqueeze(1).float(), + points_coords).squeeze(1) + # shape (num_queries, h, w) -> (num_queries, num_points) + mask_point_preds = point_sample( + mask_preds.unsqueeze(1), points_coords).squeeze(1) + + if not isinstance(self.loss_decode, nn.ModuleList): + losses_decode = [self.loss_decode] + else: + losses_decode = self.loss_decode + loss = dict() + for loss_decode in losses_decode: + if 'loss_cls' in loss_decode.loss_name: + if loss_decode.loss_name == 'loss_cls_ce': + loss[loss_decode.loss_name] = loss_decode( + cls_scores, labels) + else: + assert False, "Only support 'CrossEntropyLoss' in" \ + ' classification loss' + + elif 'loss_mask' in loss_decode.loss_name: + if mask_targets.shape[0] == 0: + loss[loss_decode.loss_name] = mask_preds.sum() + elif loss_decode.loss_name == 'loss_mask_ce': + loss[loss_decode.loss_name] = loss_decode( + mask_point_preds, + mask_point_targets, + avg_factor=num_total_masks * + self.train_cfg.num_points) + elif loss_decode.loss_name == 'loss_mask_dice': + loss[loss_decode.loss_name] = loss_decode( + mask_point_preds, + mask_point_targets, + avg_factor=num_total_masks) + else: + assert False, "Only support 'CrossEntropyLoss' and" \ + " 'DiceLoss' in mask loss" + else: + assert False, "Only support for 'loss_cls' and 'loss_mask'" + + losses.append(loss) + + loss_dict = dict() + # loss from the last decoder layer + loss_dict.update(losses[-1]) + # loss from other decoder layers + for i, loss in enumerate(losses[:-1]): + for k, v in loss.items(): + loss_dict[f'd{self.deep_supervision_idxs[i]}.{k}'] = v + return loss_dict diff --git a/third-party/InterFormer/mmseg/models/decode_heads/segformer_head.py b/third-party/InterFormer/mmseg/models/decode_heads/segformer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f9eb0b320b4e7b892e0540cea5ba5ea7054f8008 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/segformer_head.py @@ -0,0 +1,66 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.registry import MODELS +from ..utils import resize + + +@MODELS.register_module() +class SegformerHead(BaseDecodeHead): + """The all mlp Head of segformer. + + This head is the implementation of + `Segformer ` _. + + Args: + interpolate_mode: The interpolate mode of MLP head upsample operation. + Default: 'bilinear'. + """ + + def __init__(self, interpolate_mode='bilinear', **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + + self.interpolate_mode = interpolate_mode + num_inputs = len(self.in_channels) + + assert num_inputs == len(self.in_index) + + self.convs = nn.ModuleList() + for i in range(num_inputs): + self.convs.append( + ConvModule( + in_channels=self.in_channels[i], + out_channels=self.channels, + kernel_size=1, + stride=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + + self.fusion_conv = ConvModule( + in_channels=self.channels * num_inputs, + out_channels=self.channels, + kernel_size=1, + norm_cfg=self.norm_cfg) + + def forward(self, inputs): + # Receive 4 stage backbone feature map: 1/4, 1/8, 1/16, 1/32 + inputs = self._transform_inputs(inputs) + outs = [] + for idx in range(len(inputs)): + x = inputs[idx] + conv = self.convs[idx] + outs.append( + resize( + input=conv(x), + size=inputs[0].shape[2:], + mode=self.interpolate_mode, + align_corners=self.align_corners)) + + out = self.fusion_conv(torch.cat(outs, dim=1)) + + out = self.cls_seg(out) + + return out diff --git a/third-party/InterFormer/mmseg/models/decode_heads/segmenter_mask_head.py b/third-party/InterFormer/mmseg/models/decode_heads/segmenter_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..85d27735ba8015772324177716b5e8d5f357295c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/segmenter_mask_head.py @@ -0,0 +1,132 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import build_norm_layer +from mmengine.model import ModuleList +from mmengine.model.weight_init import (constant_init, trunc_normal_, + trunc_normal_init) + +from mmseg.models.backbones.vit import TransformerEncoderLayer +from mmseg.registry import MODELS +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class SegmenterMaskTransformerHead(BaseDecodeHead): + """Segmenter: Transformer for Semantic Segmentation. + + This head is the implementation of + `Segmenter: `_. + + Args: + backbone_cfg:(dict): Config of backbone of + Context Path. + in_channels (int): The number of channels of input image. + num_layers (int): The depth of transformer. + num_heads (int): The number of attention heads. + embed_dims (int): The number of embedding dimension. + mlp_ratio (int): ratio of mlp hidden dim to embedding dim. + Default: 4. + drop_path_rate (float): stochastic depth rate. Default 0.1. + drop_rate (float): Probability of an element to be zeroed. + Default 0.0 + attn_drop_rate (float): The drop out rate for attention layer. + Default 0.0 + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + qkv_bias (bool): Enable bias for qkv if True. Default: True. + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN') + init_std (float): The value of std in weight initialization. + Default: 0.02. + """ + + def __init__( + self, + in_channels, + num_layers, + num_heads, + embed_dims, + mlp_ratio=4, + drop_path_rate=0.1, + drop_rate=0.0, + attn_drop_rate=0.0, + num_fcs=2, + qkv_bias=True, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + init_std=0.02, + **kwargs, + ): + super().__init__(in_channels=in_channels, **kwargs) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_layers)] + self.layers = ModuleList() + for i in range(num_layers): + self.layers.append( + TransformerEncoderLayer( + embed_dims=embed_dims, + num_heads=num_heads, + feedforward_channels=mlp_ratio * embed_dims, + attn_drop_rate=attn_drop_rate, + drop_rate=drop_rate, + drop_path_rate=dpr[i], + num_fcs=num_fcs, + qkv_bias=qkv_bias, + act_cfg=act_cfg, + norm_cfg=norm_cfg, + batch_first=True, + )) + + self.dec_proj = nn.Linear(in_channels, embed_dims) + + self.cls_emb = nn.Parameter( + torch.randn(1, self.num_classes, embed_dims)) + self.patch_proj = nn.Linear(embed_dims, embed_dims, bias=False) + self.classes_proj = nn.Linear(embed_dims, embed_dims, bias=False) + + self.decoder_norm = build_norm_layer( + norm_cfg, embed_dims, postfix=1)[1] + self.mask_norm = build_norm_layer( + norm_cfg, self.num_classes, postfix=2)[1] + + self.init_std = init_std + + delattr(self, 'conv_seg') + + def init_weights(self): + trunc_normal_(self.cls_emb, std=self.init_std) + trunc_normal_init(self.patch_proj, std=self.init_std) + trunc_normal_init(self.classes_proj, std=self.init_std) + for n, m in self.named_modules(): + if isinstance(m, nn.Linear): + trunc_normal_init(m, std=self.init_std, bias=0) + elif isinstance(m, nn.LayerNorm): + constant_init(m, val=1.0, bias=0.0) + + def forward(self, inputs): + x = self._transform_inputs(inputs) + b, c, h, w = x.shape + x = x.permute(0, 2, 3, 1).contiguous().view(b, -1, c) + + x = self.dec_proj(x) + cls_emb = self.cls_emb.expand(x.size(0), -1, -1) + x = torch.cat((x, cls_emb), 1) + for layer in self.layers: + x = layer(x) + x = self.decoder_norm(x) + + patches = self.patch_proj(x[:, :-self.num_classes]) + cls_seg_feat = self.classes_proj(x[:, -self.num_classes:]) + + patches = F.normalize(patches, dim=2, p=2) + cls_seg_feat = F.normalize(cls_seg_feat, dim=2, p=2) + + masks = patches @ cls_seg_feat.transpose(1, 2) + masks = self.mask_norm(masks) + masks = masks.permute(0, 2, 1).contiguous().view(b, -1, h, w) + + return masks diff --git a/third-party/InterFormer/mmseg/models/decode_heads/sep_aspp_head.py b/third-party/InterFormer/mmseg/models/decode_heads/sep_aspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9dba68c9ecc6909e47da4f2da6169d529910355d --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/sep_aspp_head.py @@ -0,0 +1,102 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .aspp_head import ASPPHead, ASPPModule + + +class DepthwiseSeparableASPPModule(ASPPModule): + """Atrous Spatial Pyramid Pooling (ASPP) Module with depthwise separable + conv.""" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + for i, dilation in enumerate(self.dilations): + if dilation > 1: + self[i] = DepthwiseSeparableConvModule( + self.in_channels, + self.channels, + 3, + dilation=dilation, + padding=dilation, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + +@MODELS.register_module() +class DepthwiseSeparableASPPHead(ASPPHead): + """Encoder-Decoder with Atrous Separable Convolution for Semantic Image + Segmentation. + + This head is the implementation of `DeepLabV3+ + `_. + + Args: + c1_in_channels (int): The input channels of c1 decoder. If is 0, + the no decoder will be used. + c1_channels (int): The intermediate channels of c1 decoder. + """ + + def __init__(self, c1_in_channels, c1_channels, **kwargs): + super().__init__(**kwargs) + assert c1_in_channels >= 0 + self.aspp_modules = DepthwiseSeparableASPPModule( + dilations=self.dilations, + in_channels=self.in_channels, + channels=self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + if c1_in_channels > 0: + self.c1_bottleneck = ConvModule( + c1_in_channels, + c1_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + else: + self.c1_bottleneck = None + self.sep_bottleneck = nn.Sequential( + DepthwiseSeparableConvModule( + self.channels + c1_channels, + self.channels, + 3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + DepthwiseSeparableConvModule( + self.channels, + self.channels, + 3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + aspp_outs = [ + resize( + self.image_pool(x), + size=x.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + ] + aspp_outs.extend(self.aspp_modules(x)) + aspp_outs = torch.cat(aspp_outs, dim=1) + output = self.bottleneck(aspp_outs) + if self.c1_bottleneck is not None: + c1_output = self.c1_bottleneck(inputs[0]) + output = resize( + input=output, + size=c1_output.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + output = torch.cat([output, c1_output], dim=1) + output = self.sep_bottleneck(output) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/sep_fcn_head.py b/third-party/InterFormer/mmseg/models/decode_heads/sep_fcn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..3b15983bceaeff48534bbceedfdf1c434a8d1d1f --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/sep_fcn_head.py @@ -0,0 +1,60 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.cnn import DepthwiseSeparableConvModule + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + + +@MODELS.register_module() +class DepthwiseSeparableFCNHead(FCNHead): + """Depthwise-Separable Fully Convolutional Network for Semantic + Segmentation. + + This head is implemented according to `Fast-SCNN: Fast Semantic + Segmentation Network `_. + + Args: + in_channels(int): Number of output channels of FFM. + channels(int): Number of middle-stage channels in the decode head. + concat_input(bool): Whether to concatenate original decode input into + the result of several consecutive convolution layers. + Default: True. + num_classes(int): Used to determine the dimension of + final prediction tensor. + in_index(int): Correspond with 'out_indices' in FastSCNN backbone. + norm_cfg (dict | None): Config of norm layers. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + loss_decode(dict): Config of loss type and some + relevant additional options. + dw_act_cfg (dict):Activation config of depthwise ConvModule. If it is + 'default', it will be the same as `act_cfg`. Default: None. + """ + + def __init__(self, dw_act_cfg=None, **kwargs): + super().__init__(**kwargs) + self.convs[0] = DepthwiseSeparableConvModule( + self.in_channels, + self.channels, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + norm_cfg=self.norm_cfg, + dw_act_cfg=dw_act_cfg) + + for i in range(1, self.num_convs): + self.convs[i] = DepthwiseSeparableConvModule( + self.channels, + self.channels, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + norm_cfg=self.norm_cfg, + dw_act_cfg=dw_act_cfg) + + if self.concat_input: + self.conv_cat = DepthwiseSeparableConvModule( + self.in_channels + self.channels, + self.channels, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + norm_cfg=self.norm_cfg, + dw_act_cfg=dw_act_cfg) diff --git a/third-party/InterFormer/mmseg/models/decode_heads/setr_mla_head.py b/third-party/InterFormer/mmseg/models/decode_heads/setr_mla_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1975991a60cc720650b880060efe10753f213131 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/setr_mla_head.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import Upsample +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class SETRMLAHead(BaseDecodeHead): + """Multi level feature aggretation head of SETR. + + MLA head of `SETR `_. + + Args: + mlahead_channels (int): Channels of conv-conv-4x of multi-level feature + aggregation. Default: 128. + up_scale (int): The scale factor of interpolate. Default:4. + """ + + def __init__(self, mla_channels=128, up_scale=4, **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + self.mla_channels = mla_channels + + num_inputs = len(self.in_channels) + + # Refer to self.cls_seg settings of BaseDecodeHead + assert self.channels == num_inputs * mla_channels + + self.up_convs = nn.ModuleList() + for i in range(num_inputs): + self.up_convs.append( + nn.Sequential( + ConvModule( + in_channels=self.in_channels[i], + out_channels=mla_channels, + kernel_size=3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + ConvModule( + in_channels=mla_channels, + out_channels=mla_channels, + kernel_size=3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + Upsample( + scale_factor=up_scale, + mode='bilinear', + align_corners=self.align_corners))) + + def forward(self, inputs): + inputs = self._transform_inputs(inputs) + outs = [] + for x, up_conv in zip(inputs, self.up_convs): + outs.append(up_conv(x)) + out = torch.cat(outs, dim=1) + out = self.cls_seg(out) + return out diff --git a/third-party/InterFormer/mmseg/models/decode_heads/setr_up_head.py b/third-party/InterFormer/mmseg/models/decode_heads/setr_up_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9c796d8161088c2d7effe17f5ba71e43ff62e50c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/setr_up_head.py @@ -0,0 +1,81 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule, build_norm_layer + +from mmseg.registry import MODELS +from ..utils import Upsample +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class SETRUPHead(BaseDecodeHead): + """Naive upsampling head and Progressive upsampling head of SETR. + + Naive or PUP head of `SETR `_. + + Args: + norm_layer (dict): Config dict for input normalization. + Default: norm_layer=dict(type='LN', eps=1e-6, requires_grad=True). + num_convs (int): Number of decoder convolutions. Default: 1. + up_scale (int): The scale factor of interpolate. Default:4. + kernel_size (int): The kernel size of convolution when decoding + feature information from backbone. Default: 3. + init_cfg (dict | list[dict] | None): Initialization config dict. + Default: dict( + type='Constant', val=1.0, bias=0, layer='LayerNorm'). + """ + + def __init__(self, + norm_layer=dict(type='LN', eps=1e-6, requires_grad=True), + num_convs=1, + up_scale=4, + kernel_size=3, + init_cfg=[ + dict(type='Constant', val=1.0, bias=0, layer='LayerNorm'), + dict( + type='Normal', + std=0.01, + override=dict(name='conv_seg')) + ], + **kwargs): + + assert kernel_size in [1, 3], 'kernel_size must be 1 or 3.' + + super().__init__(init_cfg=init_cfg, **kwargs) + + assert isinstance(self.in_channels, int) + + _, self.norm = build_norm_layer(norm_layer, self.in_channels) + + self.up_convs = nn.ModuleList() + in_channels = self.in_channels + out_channels = self.channels + for _ in range(num_convs): + self.up_convs.append( + nn.Sequential( + ConvModule( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=1, + padding=int(kernel_size - 1) // 2, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + Upsample( + scale_factor=up_scale, + mode='bilinear', + align_corners=self.align_corners))) + in_channels = out_channels + + def forward(self, x): + x = self._transform_inputs(x) + + n, c, h, w = x.shape + x = x.reshape(n, c, h * w).transpose(2, 1).contiguous() + x = self.norm(x) + x = x.transpose(1, 2).reshape(n, c, h, w).contiguous() + + for up_conv in self.up_convs: + x = up_conv(x) + out = self.cls_seg(x) + return out diff --git a/third-party/InterFormer/mmseg/models/decode_heads/stdc_head.py b/third-party/InterFormer/mmseg/models/decode_heads/stdc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1c1c21e3083fcb5098d2458e44538c0cf5b8f0e4 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/stdc_head.py @@ -0,0 +1,97 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn.functional as F +from mmengine.structures import PixelData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample +from mmseg.utils import SampleList +from .fcn_head import FCNHead + + +@MODELS.register_module() +class STDCHead(FCNHead): + """This head is the implementation of `Rethinking BiSeNet For Real-time + Semantic Segmentation `_. + + Args: + boundary_threshold (float): The threshold of calculating boundary. + Default: 0.1. + """ + + def __init__(self, boundary_threshold=0.1, **kwargs): + super().__init__(**kwargs) + self.boundary_threshold = boundary_threshold + # Using register buffer to make laplacian kernel on the same + # device of `seg_label`. + self.register_buffer( + 'laplacian_kernel', + torch.tensor([-1, -1, -1, -1, 8, -1, -1, -1, -1], + dtype=torch.float32, + requires_grad=False).reshape((1, 1, 3, 3))) + self.fusion_kernel = torch.nn.Parameter( + torch.tensor([[6. / 10], [3. / 10], [1. / 10]], + dtype=torch.float32).reshape(1, 3, 1, 1), + requires_grad=False) + + def loss_by_feat(self, seg_logits: Tensor, + batch_data_samples: SampleList) -> dict: + """Compute Detail Aggregation Loss.""" + # Note: The paper claims `fusion_kernel` is a trainable 1x1 conv + # parameters. However, it is a constant in original repo and other + # codebase because it would not be added into computation graph + # after threshold operation. + seg_label = self._stack_batch_gt(batch_data_samples).to( + self.laplacian_kernel) + boundary_targets = F.conv2d( + seg_label, self.laplacian_kernel, padding=1) + boundary_targets = boundary_targets.clamp(min=0) + boundary_targets[boundary_targets > self.boundary_threshold] = 1 + boundary_targets[boundary_targets <= self.boundary_threshold] = 0 + + boundary_targets_x2 = F.conv2d( + seg_label, self.laplacian_kernel, stride=2, padding=1) + boundary_targets_x2 = boundary_targets_x2.clamp(min=0) + + boundary_targets_x4 = F.conv2d( + seg_label, self.laplacian_kernel, stride=4, padding=1) + boundary_targets_x4 = boundary_targets_x4.clamp(min=0) + + boundary_targets_x4_up = F.interpolate( + boundary_targets_x4, boundary_targets.shape[2:], mode='nearest') + boundary_targets_x2_up = F.interpolate( + boundary_targets_x2, boundary_targets.shape[2:], mode='nearest') + + boundary_targets_x2_up[ + boundary_targets_x2_up > self.boundary_threshold] = 1 + boundary_targets_x2_up[ + boundary_targets_x2_up <= self.boundary_threshold] = 0 + + boundary_targets_x4_up[ + boundary_targets_x4_up > self.boundary_threshold] = 1 + boundary_targets_x4_up[ + boundary_targets_x4_up <= self.boundary_threshold] = 0 + + boundary_targets_pyramids = torch.stack( + (boundary_targets, boundary_targets_x2_up, boundary_targets_x4_up), + dim=1) + + boundary_targets_pyramids = boundary_targets_pyramids.squeeze(2) + boudary_targets_pyramid = F.conv2d(boundary_targets_pyramids, + self.fusion_kernel) + + boudary_targets_pyramid[ + boudary_targets_pyramid > self.boundary_threshold] = 1 + boudary_targets_pyramid[ + boudary_targets_pyramid <= self.boundary_threshold] = 0 + + seg_labels = boudary_targets_pyramid.long() + batch_sample_list = [] + for label in seg_labels: + seg_data_sample = SegDataSample() + seg_data_sample.gt_sem_seg = PixelData(data=label) + batch_sample_list.append(seg_data_sample) + + loss = super().loss_by_feat(seg_logits, batch_sample_list) + return loss diff --git a/third-party/InterFormer/mmseg/models/decode_heads/uper_head.py b/third-party/InterFormer/mmseg/models/decode_heads/uper_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ccc3173c0f1193e89ad48861aa7b5ee3b329cc --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/uper_head.py @@ -0,0 +1,139 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead +from .psp_head import PPM + + +@MODELS.register_module() +class UPerHead(BaseDecodeHead): + """Unified Perceptual Parsing for Scene Understanding. + + This head is the implementation of `UPerNet + `_. + + Args: + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module applied on the last feature. Default: (1, 2, 3, 6). + """ + + def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + # PSP Module + self.psp_modules = PPM( + pool_scales, + self.in_channels[-1], + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + self.bottleneck = ConvModule( + self.in_channels[-1] + len(pool_scales) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + # FPN Module + self.lateral_convs = nn.ModuleList() + self.fpn_convs = nn.ModuleList() + for in_channels in self.in_channels[:-1]: # skip the top layer + l_conv = ConvModule( + in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + inplace=False) + fpn_conv = ConvModule( + self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + inplace=False) + self.lateral_convs.append(l_conv) + self.fpn_convs.append(fpn_conv) + + self.fpn_bottleneck = ConvModule( + len(self.in_channels) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def psp_forward(self, inputs): + """Forward function of PSP module.""" + x = inputs[-1] + psp_outs = [x] + psp_outs.extend(self.psp_modules(x)) + psp_outs = torch.cat(psp_outs, dim=1) + output = self.bottleneck(psp_outs) + + return output + + def _forward_feature(self, inputs): + """Forward function for feature maps before classifying each pixel with + ``self.cls_seg`` fc. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + feats (Tensor): A tensor of shape (batch_size, self.channels, + H, W) which is feature map for last layer of decoder head. + """ + inputs = self._transform_inputs(inputs) + + # build laterals + laterals = [ + lateral_conv(inputs[i]) + for i, lateral_conv in enumerate(self.lateral_convs) + ] + + laterals.append(self.psp_forward(inputs)) + + # build top-down path + used_backbone_levels = len(laterals) + for i in range(used_backbone_levels - 1, 0, -1): + prev_shape = laterals[i - 1].shape[2:] + laterals[i - 1] = laterals[i - 1] + resize( + laterals[i], + size=prev_shape, + mode='bilinear', + align_corners=self.align_corners) + + # build outputs + fpn_outs = [ + self.fpn_convs[i](laterals[i]) + for i in range(used_backbone_levels - 1) + ] + # append psp feature + fpn_outs.append(laterals[-1]) + + for i in range(used_backbone_levels - 1, 0, -1): + fpn_outs[i] = resize( + fpn_outs[i], + size=fpn_outs[0].shape[2:], + mode='bilinear', + align_corners=self.align_corners) + fpn_outs = torch.cat(fpn_outs, dim=1) + feats = self.fpn_bottleneck(fpn_outs) + return feats + + def forward(self, inputs): + """Forward function.""" + output = self._forward_feature(inputs) + output = self.cls_seg(output) + return output diff --git a/third-party/InterFormer/mmseg/models/decode_heads/vpd_depth_head.py b/third-party/InterFormer/mmseg/models/decode_heads/vpd_depth_head.py new file mode 100644 index 0000000000000000000000000000000000000000..65bdfbd8d9065c158f4f6a147cd8c06ae1dfd961 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/decode_heads/vpd_depth_head.py @@ -0,0 +1,253 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Dict, List, Optional, Sequence, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import build_conv_layer, build_norm_layer, build_upsample_layer +from mmengine.model import BaseModule +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import SampleList +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class VPDDepthDecoder(BaseModule): + """VPD Depth Decoder class. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + num_deconv_layers (int): Number of deconvolution layers. + num_deconv_filters (List[int]): List of output channels for + deconvolution layers. + init_cfg (Optional[Union[Dict, List[Dict]]], optional): Configuration + for weight initialization. Defaults to Normal for Conv2d and + ConvTranspose2d layers. + """ + + def __init__(self, + in_channels: int, + out_channels: int, + num_deconv_layers: int, + num_deconv_filters: List[int], + init_cfg: Optional[Union[Dict, List[Dict]]] = dict( + type='Normal', + std=0.001, + layer=['Conv2d', 'ConvTranspose2d'])): + super().__init__(init_cfg=init_cfg) + self.in_channels = in_channels + + self.deconv_layers = self._make_deconv_layer( + num_deconv_layers, + num_deconv_filters, + ) + + conv_layers = [] + conv_layers.append( + build_conv_layer( + dict(type='Conv2d'), + in_channels=num_deconv_filters[-1], + out_channels=out_channels, + kernel_size=3, + stride=1, + padding=1)) + conv_layers.append(build_norm_layer(dict(type='BN'), out_channels)[1]) + conv_layers.append(nn.ReLU(inplace=True)) + self.conv_layers = nn.Sequential(*conv_layers) + + self.up_sample = nn.Upsample( + scale_factor=2, mode='bilinear', align_corners=False) + + def forward(self, x): + """Forward pass through the decoder network.""" + out = self.deconv_layers(x) + out = self.conv_layers(out) + + out = self.up_sample(out) + out = self.up_sample(out) + + return out + + def _make_deconv_layer(self, num_layers, num_deconv_filters): + """Make deconv layers.""" + + layers = [] + in_channels = self.in_channels + for i in range(num_layers): + + num_channels = num_deconv_filters[i] + layers.append( + build_upsample_layer( + dict(type='deconv'), + in_channels=in_channels, + out_channels=num_channels, + kernel_size=2, + stride=2, + padding=0, + output_padding=0, + bias=False)) + layers.append(nn.BatchNorm2d(num_channels)) + layers.append(nn.ReLU(inplace=True)) + in_channels = num_channels + + return nn.Sequential(*layers) + + +@MODELS.register_module() +class VPDDepthHead(BaseDecodeHead): + """Depth Prediction Head for VPD. + + .. _`VPD`: https://arxiv.org/abs/2303.02153 + + Args: + max_depth (float): Maximum depth value. Defaults to 10.0. + in_channels (Sequence[int]): Number of input channels for each + convolutional layer. + embed_dim (int): Dimension of embedding. Defaults to 192. + feature_dim (int): Dimension of aggregated feature. Defaults to 1536. + num_deconv_layers (int): Number of deconvolution layers in the + decoder. Defaults to 3. + num_deconv_filters (Sequence[int]): Number of filters for each deconv + layer. Defaults to (32, 32, 32). + fmap_border (Union[int, Sequence[int]]): Feature map border for + cropping. Defaults to 0. + align_corners (bool): Flag for align_corners in interpolation. + Defaults to False. + loss_decode (dict): Configurations for the loss function. Defaults to + dict(type='SiLogLoss'). + init_cfg (dict): Initialization configurations. Defaults to + dict(type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']). + """ + + num_classes = 1 + out_channels = 1 + input_transform = None + + def __init__( + self, + max_depth: float = 10.0, + in_channels: Sequence[int] = [320, 640, 1280, 1280], + embed_dim: int = 192, + feature_dim: int = 1536, + num_deconv_layers: int = 3, + num_deconv_filters: Sequence[int] = (32, 32, 32), + fmap_border: Union[int, Sequence[int]] = 0, + align_corners: bool = False, + loss_decode: dict = dict(type='SiLogLoss'), + init_cfg=dict( + type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']), + ): + + super(BaseDecodeHead, self).__init__(init_cfg=init_cfg) + + # initialize parameters + self.in_channels = in_channels + self.max_depth = max_depth + self.align_corners = align_corners + + # feature map border + if isinstance(fmap_border, int): + fmap_border = (fmap_border, fmap_border) + self.fmap_border = fmap_border + + # define network layers + self.conv1 = nn.Sequential( + nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1), + nn.GroupNorm(16, in_channels[0]), + nn.ReLU(), + nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1), + ) + self.conv2 = nn.Conv2d( + in_channels[1], in_channels[1], 3, stride=2, padding=1) + + self.conv_aggregation = nn.Sequential( + nn.Conv2d(sum(in_channels), feature_dim, 1), + nn.GroupNorm(16, feature_dim), + nn.ReLU(), + ) + + self.decoder = VPDDepthDecoder( + in_channels=embed_dim * 8, + out_channels=embed_dim, + num_deconv_layers=num_deconv_layers, + num_deconv_filters=num_deconv_filters) + + self.depth_pred_layer = nn.Sequential( + nn.Conv2d( + embed_dim, embed_dim, kernel_size=3, stride=1, padding=1), + nn.ReLU(inplace=False), + nn.Conv2d(embed_dim, 1, kernel_size=3, stride=1, padding=1)) + + # build loss + if isinstance(loss_decode, dict): + self.loss_decode = MODELS.build(loss_decode) + elif isinstance(loss_decode, (list, tuple)): + self.loss_decode = nn.ModuleList() + for loss in loss_decode: + self.loss_decode.append(MODELS.build(loss)) + else: + raise TypeError(f'loss_decode must be a dict or sequence of dict,\ + but got {type(loss_decode)}') + + def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tensor: + gt_depth_maps = [ + data_sample.gt_depth_map.data for data_sample in batch_data_samples + ] + return torch.stack(gt_depth_maps, dim=0) + + def forward(self, x): + x = [ + x[0], x[1], + torch.cat([x[2], F.interpolate(x[3], scale_factor=2)], dim=1) + ] + x = torch.cat([self.conv1(x[0]), self.conv2(x[1]), x[2]], dim=1) + x = self.conv_aggregation(x) + + x = x[:, :, :x.size(2) - self.fmap_border[0], :x.size(3) - + self.fmap_border[1]].contiguous() + x = self.decoder(x) + out = self.depth_pred_layer(x) + + depth = torch.sigmoid(out) * self.max_depth + + return depth + + def loss_by_feat(self, pred_depth_map: Tensor, + batch_data_samples: SampleList) -> dict: + """Compute depth estimation loss. + + Args: + pred_depth_map (Tensor): The output from decode head forward + function. + batch_data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_dpeth_map`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + + gt_depth_map = self._stack_batch_gt(batch_data_samples) + loss = dict() + pred_depth_map = resize( + input=pred_depth_map, + size=gt_depth_map.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + + if not isinstance(self.loss_decode, nn.ModuleList): + losses_decode = [self.loss_decode] + else: + losses_decode = self.loss_decode + for loss_decode in losses_decode: + if loss_decode.loss_name not in loss: + loss[loss_decode.loss_name] = loss_decode( + pred_depth_map, gt_depth_map) + else: + loss[loss_decode.loss_name] += loss_decode( + pred_depth_map, gt_depth_map) + + return loss diff --git a/third-party/InterFormer/mmseg/models/losses/__init__.py b/third-party/InterFormer/mmseg/models/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0467cb3ad89b8c0c57f7f8eb58cbc2e23f50cdb4 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/__init__.py @@ -0,0 +1,21 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .accuracy import Accuracy, accuracy +from .boundary_loss import BoundaryLoss +from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy, + cross_entropy, mask_cross_entropy) +from .dice_loss import DiceLoss +from .focal_loss import FocalLoss +from .huasdorff_distance_loss import HuasdorffDisstanceLoss +from .lovasz_loss import LovaszLoss +from .ohem_cross_entropy_loss import OhemCrossEntropy +from .silog_loss import SiLogLoss +from .tversky_loss import TverskyLoss +from .utils import reduce_loss, weight_reduce_loss, weighted_loss + +__all__ = [ + 'accuracy', 'Accuracy', 'cross_entropy', 'binary_cross_entropy', + 'mask_cross_entropy', 'CrossEntropyLoss', 'reduce_loss', + 'weight_reduce_loss', 'weighted_loss', 'LovaszLoss', 'DiceLoss', + 'FocalLoss', 'TverskyLoss', 'OhemCrossEntropy', 'BoundaryLoss', + 'HuasdorffDisstanceLoss', 'SiLogLoss' +] diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9747958dcb80baf3b7dab5e05f87601c9a645cb8 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b66404b08692387d697d4b570eb174eda171344 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c01349750b5c17a1c8998489f7d2f6973ba8f5b5 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dbb82becb90555a78cb29662914bc1fcc5aacdc Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..670d78baabba0922ccd4be1c6080abcbe7705f4b Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45e15bcf89da1ac014dbeada7173f849cb2c3720 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8764f89761a9ee1d51f755d110e724000353a0e Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..152f51884868b4af45a66fcada4fd9f10cdb08d3 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baeaabd07115760f4ec9fe6c983e7dd475074b10 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b24dc174fc5e53de646f61aa358cf417633305a Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3de70327a491b57dd7f45d2529f8d0866279247e Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-38.pyc b/third-party/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85496dc9205702f97131a23afb783cfd3f4db774 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/losses/accuracy.py b/third-party/InterFormer/mmseg/models/losses/accuracy.py new file mode 100644 index 0000000000000000000000000000000000000000..1d9e2d7701088adadd5b6bb71c718c986b87a066 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/accuracy.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn + + +def accuracy(pred, target, topk=1, thresh=None, ignore_index=None): + """Calculate accuracy according to the prediction and target. + + Args: + pred (torch.Tensor): The model prediction, shape (N, num_class, ...) + target (torch.Tensor): The target of each prediction, shape (N, , ...) + ignore_index (int | None): The label index to be ignored. Default: None + topk (int | tuple[int], optional): If the predictions in ``topk`` + matches the target, the predictions will be regarded as + correct ones. Defaults to 1. + thresh (float, optional): If not None, predictions with scores under + this threshold are considered incorrect. Default to None. + + Returns: + float | tuple[float]: If the input ``topk`` is a single integer, + the function will return a single float as accuracy. If + ``topk`` is a tuple containing multiple integers, the + function will return a tuple containing accuracies of + each ``topk`` number. + """ + assert isinstance(topk, (int, tuple)) + if isinstance(topk, int): + topk = (topk, ) + return_single = True + else: + return_single = False + + maxk = max(topk) + if pred.size(0) == 0: + accu = [pred.new_tensor(0.) for i in range(len(topk))] + return accu[0] if return_single else accu + assert pred.ndim == target.ndim + 1 + assert pred.size(0) == target.size(0) + assert maxk <= pred.size(1), \ + f'maxk {maxk} exceeds pred dimension {pred.size(1)}' + pred_value, pred_label = pred.topk(maxk, dim=1) + # transpose to shape (maxk, N, ...) + pred_label = pred_label.transpose(0, 1) + correct = pred_label.eq(target.unsqueeze(0).expand_as(pred_label)) + if thresh is not None: + # Only prediction values larger than thresh are counted as correct + correct = correct & (pred_value > thresh).t() + if ignore_index is not None: + correct = correct[:, target != ignore_index] + res = [] + eps = torch.finfo(torch.float32).eps + for k in topk: + # Avoid causing ZeroDivisionError when all pixels + # of an image are ignored + correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) + eps + if ignore_index is not None: + total_num = target[target != ignore_index].numel() + eps + else: + total_num = target.numel() + eps + res.append(correct_k.mul_(100.0 / total_num)) + return res[0] if return_single else res + + +class Accuracy(nn.Module): + """Accuracy calculation module.""" + + def __init__(self, topk=(1, ), thresh=None, ignore_index=None): + """Module to calculate the accuracy. + + Args: + topk (tuple, optional): The criterion used to calculate the + accuracy. Defaults to (1,). + thresh (float, optional): If not None, predictions with scores + under this threshold are considered incorrect. Default to None. + """ + super().__init__() + self.topk = topk + self.thresh = thresh + self.ignore_index = ignore_index + + def forward(self, pred, target): + """Forward function to calculate accuracy. + + Args: + pred (torch.Tensor): Prediction of models. + target (torch.Tensor): Target for each prediction. + + Returns: + tuple[float]: The accuracies under different topk criterions. + """ + return accuracy(pred, target, self.topk, self.thresh, + self.ignore_index) diff --git a/third-party/InterFormer/mmseg/models/losses/boundary_loss.py b/third-party/InterFormer/mmseg/models/losses/boundary_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..e86b850d87e1d26be8cbb700758dae8dead82c58 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/boundary_loss.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class BoundaryLoss(nn.Module): + """Boundary loss. + + This function is modified from + `PIDNet `_. # noqa + Licensed under the MIT License. + + + Args: + loss_weight (float): Weight of the loss. Defaults to 1.0. + loss_name (str): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_boundary'. + """ + + def __init__(self, + loss_weight: float = 1.0, + loss_name: str = 'loss_boundary'): + super().__init__() + self.loss_weight = loss_weight + self.loss_name_ = loss_name + + def forward(self, bd_pre: Tensor, bd_gt: Tensor) -> Tensor: + """Forward function. + Args: + bd_pre (Tensor): Predictions of the boundary head. + bd_gt (Tensor): Ground truth of the boundary. + + Returns: + Tensor: Loss tensor. + """ + log_p = bd_pre.permute(0, 2, 3, 1).contiguous().view(1, -1) + target_t = bd_gt.view(1, -1).float() + + pos_index = (target_t == 1) + neg_index = (target_t == 0) + + weight = torch.zeros_like(log_p) + pos_num = pos_index.sum() + neg_num = neg_index.sum() + sum_num = pos_num + neg_num + weight[pos_index] = neg_num * 1.0 / sum_num + weight[neg_index] = pos_num * 1.0 / sum_num + + loss = F.binary_cross_entropy_with_logits( + log_p, target_t, weight, reduction='mean') + + return self.loss_weight * loss + + @property + def loss_name(self): + return self.loss_name_ diff --git a/third-party/InterFormer/mmseg/models/losses/cross_entropy_loss.py b/third-party/InterFormer/mmseg/models/losses/cross_entropy_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..988fb789c11eca9d002b2c02f227450d704aeaef --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/cross_entropy_loss.py @@ -0,0 +1,311 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from mmseg.registry import MODELS +from .utils import get_class_weight, weight_reduce_loss + + +def cross_entropy(pred, + label, + weight=None, + class_weight=None, + reduction='mean', + avg_factor=None, + ignore_index=-100, + avg_non_ignore=False): + """cross_entropy. The wrapper function for :func:`F.cross_entropy` + + Args: + pred (torch.Tensor): The prediction with shape (N, 1). + label (torch.Tensor): The learning label of the prediction. + weight (torch.Tensor, optional): Sample-wise loss weight. + Default: None. + class_weight (list[float], optional): The weight for each class. + Default: None. + reduction (str, optional): The method used to reduce the loss. + Options are 'none', 'mean' and 'sum'. Default: 'mean'. + avg_factor (int, optional): Average factor that is used to average + the loss. Default: None. + ignore_index (int): Specifies a target value that is ignored and + does not contribute to the input gradients. When + ``avg_non_ignore `` is ``True``, and the ``reduction`` is + ``''mean''``, the loss is averaged over non-ignored targets. + Defaults: -100. + avg_non_ignore (bool): The flag decides to whether the loss is + only averaged over non-ignored targets. Default: False. + `New in version 0.23.0.` + """ + + # class_weight is a manual rescaling weight given to each class. + # If given, has to be a Tensor of size C element-wise losses + loss = F.cross_entropy( + pred, + label, + weight=class_weight, + reduction='none', + ignore_index=ignore_index) + + # apply weights and do the reduction + # average loss over non-ignored elements + # pytorch's official cross_entropy average loss over non-ignored elements + # refer to https://github.com/pytorch/pytorch/blob/56b43f4fec1f76953f15a627694d4bba34588969/torch/nn/functional.py#L2660 # noqa + if (avg_factor is None) and reduction == 'mean': + if class_weight is None: + if avg_non_ignore: + avg_factor = label.numel() - (label + == ignore_index).sum().item() + else: + avg_factor = label.numel() + + else: + # the average factor should take the class weights into account + label_weights = torch.stack([class_weight[cls] for cls in label + ]).to(device=class_weight.device) + + if avg_non_ignore: + label_weights[label == ignore_index] = 0 + avg_factor = label_weights.sum() + + if weight is not None: + weight = weight.float() + loss = weight_reduce_loss( + loss, weight=weight, reduction=reduction, avg_factor=avg_factor) + + return loss + + +def _expand_onehot_labels(labels, label_weights, target_shape, ignore_index): + """Expand onehot labels to match the size of prediction.""" + bin_labels = labels.new_zeros(target_shape) + valid_mask = (labels >= 0) & (labels != ignore_index) + inds = torch.nonzero(valid_mask, as_tuple=True) + + if inds[0].numel() > 0: + if labels.dim() == 3: + bin_labels[inds[0], labels[valid_mask], inds[1], inds[2]] = 1 + else: + bin_labels[inds[0], labels[valid_mask]] = 1 + + valid_mask = valid_mask.unsqueeze(1).expand(target_shape).float() + + if label_weights is None: + bin_label_weights = valid_mask + else: + bin_label_weights = label_weights.unsqueeze(1).expand(target_shape) + bin_label_weights = bin_label_weights * valid_mask + + return bin_labels, bin_label_weights, valid_mask + + +def binary_cross_entropy(pred, + label, + weight=None, + reduction='mean', + avg_factor=None, + class_weight=None, + ignore_index=-100, + avg_non_ignore=False, + **kwargs): + """Calculate the binary CrossEntropy loss. + + Args: + pred (torch.Tensor): The prediction with shape (N, 1). + label (torch.Tensor): The learning label of the prediction. + Note: In bce loss, label < 0 is invalid. + weight (torch.Tensor, optional): Sample-wise loss weight. + reduction (str, optional): The method used to reduce the loss. + Options are "none", "mean" and "sum". + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + class_weight (list[float], optional): The weight for each class. + ignore_index (int): The label index to be ignored. Default: -100. + avg_non_ignore (bool): The flag decides to whether the loss is + only averaged over non-ignored targets. Default: False. + `New in version 0.23.0.` + + Returns: + torch.Tensor: The calculated loss + """ + if pred.size(1) == 1: + # For binary class segmentation, the shape of pred is + # [N, 1, H, W] and that of label is [N, H, W]. + # As the ignore_index often set as 255, so the + # binary class label check should mask out + # ignore_index + assert label[label != ignore_index].max() <= 1, \ + 'For pred with shape [N, 1, H, W], its label must have at ' \ + 'most 2 classes' + pred = pred.squeeze(1) + if pred.dim() != label.dim(): + assert (pred.dim() == 2 and label.dim() == 1) or ( + pred.dim() == 4 and label.dim() == 3), \ + 'Only pred shape [N, C], label shape [N] or pred shape [N, C, ' \ + 'H, W], label shape [N, H, W] are supported' + # `weight` returned from `_expand_onehot_labels` + # has been treated for valid (non-ignore) pixels + label, weight, valid_mask = _expand_onehot_labels( + label, weight, pred.shape, ignore_index) + else: + # should mask out the ignored elements + valid_mask = ((label >= 0) & (label != ignore_index)).float() + if weight is not None: + weight = weight * valid_mask + else: + weight = valid_mask + # average loss over non-ignored and valid elements + if reduction == 'mean' and avg_factor is None and avg_non_ignore: + avg_factor = valid_mask.sum().item() + + loss = F.binary_cross_entropy_with_logits( + pred, label.float(), pos_weight=class_weight, reduction='none') + # do the reduction for the weighted loss + loss = weight_reduce_loss( + loss, weight, reduction=reduction, avg_factor=avg_factor) + + return loss + + +def mask_cross_entropy(pred, + target, + label, + reduction='mean', + avg_factor=None, + class_weight=None, + ignore_index=None, + **kwargs): + """Calculate the CrossEntropy loss for masks. + + Args: + pred (torch.Tensor): The prediction with shape (N, C), C is the number + of classes. + target (torch.Tensor): The learning label of the prediction. + label (torch.Tensor): ``label`` indicates the class label of the mask' + corresponding object. This will be used to select the mask in the + of the class which the object belongs to when the mask prediction + if not class-agnostic. + reduction (str, optional): The method used to reduce the loss. + Options are "none", "mean" and "sum". + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + class_weight (list[float], optional): The weight for each class. + ignore_index (None): Placeholder, to be consistent with other loss. + Default: None. + + Returns: + torch.Tensor: The calculated loss + """ + assert ignore_index is None, 'BCE loss does not support ignore_index' + # TODO: handle these two reserved arguments + assert reduction == 'mean' and avg_factor is None + num_rois = pred.size()[0] + inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device) + pred_slice = pred[inds, label].squeeze(1) + return F.binary_cross_entropy_with_logits( + pred_slice, target, weight=class_weight, reduction='mean')[None] + + +@MODELS.register_module() +class CrossEntropyLoss(nn.Module): + """CrossEntropyLoss. + + Args: + use_sigmoid (bool, optional): Whether the prediction uses sigmoid + of softmax. Defaults to False. + use_mask (bool, optional): Whether to use mask cross entropy loss. + Defaults to False. + reduction (str, optional): . Defaults to 'mean'. + Options are "none", "mean" and "sum". + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_weight (float, optional): Weight of the loss. Defaults to 1.0. + loss_name (str, optional): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_ce'. + avg_non_ignore (bool): The flag decides to whether the loss is + only averaged over non-ignored targets. Default: False. + `New in version 0.23.0.` + """ + + def __init__(self, + use_sigmoid=False, + use_mask=False, + reduction='mean', + class_weight=None, + loss_weight=1.0, + loss_name='loss_ce', + avg_non_ignore=False): + super().__init__() + assert (use_sigmoid is False) or (use_mask is False) + self.use_sigmoid = use_sigmoid + self.use_mask = use_mask + self.reduction = reduction + self.loss_weight = loss_weight + self.class_weight = get_class_weight(class_weight) + self.avg_non_ignore = avg_non_ignore + if not self.avg_non_ignore and self.reduction == 'mean': + warnings.warn( + 'Default ``avg_non_ignore`` is False, if you would like to ' + 'ignore the certain label and average loss over non-ignore ' + 'labels, which is the same with PyTorch official ' + 'cross_entropy, set ``avg_non_ignore=True``.') + + if self.use_sigmoid: + self.cls_criterion = binary_cross_entropy + elif self.use_mask: + self.cls_criterion = mask_cross_entropy + else: + self.cls_criterion = cross_entropy + self._loss_name = loss_name + + def extra_repr(self): + """Extra repr.""" + s = f'avg_non_ignore={self.avg_non_ignore}' + return s + + def forward(self, + cls_score, + label, + weight=None, + avg_factor=None, + reduction_override=None, + ignore_index=-100, + **kwargs): + """Forward function.""" + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.class_weight is not None: + class_weight = cls_score.new_tensor(self.class_weight) + else: + class_weight = None + # Note: for BCE loss, label < 0 is invalid. + loss_cls = self.loss_weight * self.cls_criterion( + cls_score, + label, + weight, + class_weight=class_weight, + reduction=reduction, + avg_factor=avg_factor, + avg_non_ignore=self.avg_non_ignore, + ignore_index=ignore_index, + **kwargs) + return loss_cls + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/third-party/InterFormer/mmseg/models/losses/dice_loss.py b/third-party/InterFormer/mmseg/models/losses/dice_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2ffdba8daf867032b6d7b4e0d70a9b7a0c50fe --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/dice_loss.py @@ -0,0 +1,202 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Union + +import torch +import torch.nn as nn + +from mmseg.registry import MODELS +from .utils import weight_reduce_loss + + +def _expand_onehot_labels_dice(pred: torch.Tensor, + target: torch.Tensor) -> torch.Tensor: + """Expand onehot labels to match the size of prediction. + + Args: + pred (torch.Tensor): The prediction, has a shape (N, num_class, H, W). + target (torch.Tensor): The learning label of the prediction, + has a shape (N, H, W). + + Returns: + torch.Tensor: The target after one-hot encoding, + has a shape (N, num_class, H, W). + """ + num_classes = pred.shape[1] + one_hot_target = torch.clamp(target, min=0, max=num_classes) + one_hot_target = torch.nn.functional.one_hot(one_hot_target, + num_classes + 1) + one_hot_target = one_hot_target[..., :num_classes].permute(0, 3, 1, 2) + return one_hot_target + + +def dice_loss(pred: torch.Tensor, + target: torch.Tensor, + weight: Union[torch.Tensor, None], + eps: float = 1e-3, + reduction: Union[str, None] = 'mean', + naive_dice: Union[bool, None] = False, + avg_factor: Union[int, None] = None, + ignore_index: Union[int, None] = 255) -> float: + """Calculate dice loss, there are two forms of dice loss is supported: + + - the one proposed in `V-Net: Fully Convolutional Neural + Networks for Volumetric Medical Image Segmentation + `_. + - the dice loss in which the power of the number in the + denominator is the first power instead of the second + power. + + Args: + pred (torch.Tensor): The prediction, has a shape (n, *) + target (torch.Tensor): The learning label of the prediction, + shape (n, *), same shape of pred. + weight (torch.Tensor, optional): The weight of loss for each + prediction, has a shape (n,). Defaults to None. + eps (float): Avoid dividing by zero. Default: 1e-3. + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. + Options are "none", "mean" and "sum". + naive_dice (bool, optional): If false, use the dice + loss defined in the V-Net paper, otherwise, use the + naive dice loss in which the power of the number in the + denominator is the first power instead of the second + power.Defaults to False. + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + ignore_index (int, optional): The label index to be ignored. + Defaults to 255. + """ + if ignore_index is not None: + num_classes = pred.shape[1] + pred = pred[:, torch.arange(num_classes) != ignore_index, :, :] + target = target[:, torch.arange(num_classes) != ignore_index, :, :] + assert pred.shape[1] != 0 # if the ignored index is the only class + input = pred.flatten(1) + target = target.flatten(1).float() + a = torch.sum(input * target, 1) + if naive_dice: + b = torch.sum(input, 1) + c = torch.sum(target, 1) + d = (2 * a + eps) / (b + c + eps) + else: + b = torch.sum(input * input, 1) + eps + c = torch.sum(target * target, 1) + eps + d = (2 * a) / (b + c) + + loss = 1 - d + if weight is not None: + assert weight.ndim == loss.ndim + assert len(weight) == len(pred) + loss = weight_reduce_loss(loss, weight, reduction, avg_factor) + return loss + + +@MODELS.register_module() +class DiceLoss(nn.Module): + + def __init__(self, + use_sigmoid=True, + activate=True, + reduction='mean', + naive_dice=False, + loss_weight=1.0, + ignore_index=255, + eps=1e-3, + loss_name='loss_dice'): + """Compute dice loss. + + Args: + use_sigmoid (bool, optional): Whether to the prediction is + used for sigmoid or softmax. Defaults to True. + activate (bool): Whether to activate the predictions inside, + this will disable the inside sigmoid operation. + Defaults to True. + reduction (str, optional): The method used + to reduce the loss. Options are "none", + "mean" and "sum". Defaults to 'mean'. + naive_dice (bool, optional): If false, use the dice + loss defined in the V-Net paper, otherwise, use the + naive dice loss in which the power of the number in the + denominator is the first power instead of the second + power. Defaults to False. + loss_weight (float, optional): Weight of loss. Defaults to 1.0. + ignore_index (int, optional): The label index to be ignored. + Default: 255. + eps (float): Avoid dividing by zero. Defaults to 1e-3. + loss_name (str, optional): Name of the loss item. If you want this + loss item to be included into the backward graph, `loss_` must + be the prefix of the name. Defaults to 'loss_dice'. + """ + + super().__init__() + self.use_sigmoid = use_sigmoid + self.reduction = reduction + self.naive_dice = naive_dice + self.loss_weight = loss_weight + self.eps = eps + self.activate = activate + self.ignore_index = ignore_index + self._loss_name = loss_name + + def forward(self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None, + ignore_index=255, + **kwargs): + """Forward function. + + Args: + pred (torch.Tensor): The prediction, has a shape (n, *). + target (torch.Tensor): The label of the prediction, + shape (n, *), same shape of pred. + weight (torch.Tensor, optional): The weight of loss for each + prediction, has a shape (n,). Defaults to None. + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + reduction_override (str, optional): The reduction method used to + override the original reduction method of the loss. + Options are "none", "mean" and "sum". + + Returns: + torch.Tensor: The calculated loss + """ + one_hot_target = target + if (pred.shape != target.shape): + one_hot_target = _expand_onehot_labels_dice(pred, target) + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.activate: + if self.use_sigmoid: + pred = pred.sigmoid() + elif pred.shape[1] != 1: + # softmax does not work when there is only 1 class + pred = pred.softmax(dim=1) + loss = self.loss_weight * dice_loss( + pred, + one_hot_target, + weight, + eps=self.eps, + reduction=reduction, + naive_dice=self.naive_dice, + avg_factor=avg_factor, + ignore_index=self.ignore_index) + + return loss + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/third-party/InterFormer/mmseg/models/losses/focal_loss.py b/third-party/InterFormer/mmseg/models/losses/focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..6507ed7a9112993733ac25bc095da0b571e14363 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/focal_loss.py @@ -0,0 +1,337 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Modified from https://github.com/open-mmlab/mmdetection +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.ops import sigmoid_focal_loss as _sigmoid_focal_loss + +from mmseg.registry import MODELS +from .utils import weight_reduce_loss + + +# This method is used when cuda is not available +def py_sigmoid_focal_loss(pred, + target, + one_hot_target=None, + weight=None, + gamma=2.0, + alpha=0.5, + class_weight=None, + valid_mask=None, + reduction='mean', + avg_factor=None): + """PyTorch version of `Focal Loss `_. + + Args: + pred (torch.Tensor): The prediction with shape (N, C), C is the + number of classes + target (torch.Tensor): The learning label of the prediction with + shape (N, C) + one_hot_target (None): Placeholder. It should be None. + weight (torch.Tensor, optional): Sample-wise loss weight. + gamma (float, optional): The gamma for calculating the modulating + factor. Defaults to 2.0. + alpha (float | list[float], optional): A balanced form for Focal Loss. + Defaults to 0.5. + class_weight (list[float], optional): Weight of each class. + Defaults to None. + valid_mask (torch.Tensor, optional): A mask uses 1 to mark the valid + samples and uses 0 to mark the ignored samples. Default: None. + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + """ + if isinstance(alpha, list): + alpha = pred.new_tensor(alpha) + pred_sigmoid = pred.sigmoid() + target = target.type_as(pred) + one_minus_pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target) + focal_weight = (alpha * target + (1 - alpha) * + (1 - target)) * one_minus_pt.pow(gamma) + + loss = F.binary_cross_entropy_with_logits( + pred, target, reduction='none') * focal_weight + final_weight = torch.ones(1, pred.size(1)).type_as(loss) + if weight is not None: + if weight.shape != loss.shape and weight.size(0) == loss.size(0): + # For most cases, weight is of shape (N, ), + # which means it does not have the second axis num_class + weight = weight.view(-1, 1) + assert weight.dim() == loss.dim() + final_weight = final_weight * weight + if class_weight is not None: + final_weight = final_weight * pred.new_tensor(class_weight) + if valid_mask is not None: + final_weight = final_weight * valid_mask + loss = weight_reduce_loss(loss, final_weight, reduction, avg_factor) + return loss + + +def sigmoid_focal_loss(pred, + target, + one_hot_target, + weight=None, + gamma=2.0, + alpha=0.5, + class_weight=None, + valid_mask=None, + reduction='mean', + avg_factor=None): + r"""A wrapper of cuda version `Focal Loss + `_. + Args: + pred (torch.Tensor): The prediction with shape (N, C), C is the number + of classes. + target (torch.Tensor): The learning label of the prediction. It's shape + should be (N, ) + one_hot_target (torch.Tensor): The learning label with shape (N, C) + weight (torch.Tensor, optional): Sample-wise loss weight. + gamma (float, optional): The gamma for calculating the modulating + factor. Defaults to 2.0. + alpha (float | list[float], optional): A balanced form for Focal Loss. + Defaults to 0.5. + class_weight (list[float], optional): Weight of each class. + Defaults to None. + valid_mask (torch.Tensor, optional): A mask uses 1 to mark the valid + samples and uses 0 to mark the ignored samples. Default: None. + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. Options are "none", "mean" and "sum". + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + """ + # Function.apply does not accept keyword arguments, so the decorator + # "weighted_loss" is not applicable + final_weight = torch.ones(1, pred.size(1)).type_as(pred) + if isinstance(alpha, list): + # _sigmoid_focal_loss doesn't accept alpha of list type. Therefore, if + # a list is given, we set the input alpha as 0.5. This means setting + # equal weight for foreground class and background class. By + # multiplying the loss by 2, the effect of setting alpha as 0.5 is + # undone. The alpha of type list is used to regulate the loss in the + # post-processing process. + loss = _sigmoid_focal_loss(pred.contiguous(), target.contiguous(), + gamma, 0.5, None, 'none') * 2 + alpha = pred.new_tensor(alpha) + final_weight = final_weight * ( + alpha * one_hot_target + (1 - alpha) * (1 - one_hot_target)) + else: + loss = _sigmoid_focal_loss(pred.contiguous(), target.contiguous(), + gamma, alpha, None, 'none') + if weight is not None: + if weight.shape != loss.shape and weight.size(0) == loss.size(0): + # For most cases, weight is of shape (N, ), + # which means it does not have the second axis num_class + weight = weight.view(-1, 1) + assert weight.dim() == loss.dim() + final_weight = final_weight * weight + if class_weight is not None: + final_weight = final_weight * pred.new_tensor(class_weight) + if valid_mask is not None: + final_weight = final_weight * valid_mask + loss = weight_reduce_loss(loss, final_weight, reduction, avg_factor) + return loss + + +@MODELS.register_module() +class FocalLoss(nn.Module): + + def __init__(self, + use_sigmoid=True, + gamma=2.0, + alpha=0.5, + reduction='mean', + class_weight=None, + loss_weight=1.0, + loss_name='loss_focal'): + """`Focal Loss `_ + Args: + use_sigmoid (bool, optional): Whether to the prediction is + used for sigmoid or softmax. Defaults to True. + gamma (float, optional): The gamma for calculating the modulating + factor. Defaults to 2.0. + alpha (float | list[float], optional): A balanced form for Focal + Loss. Defaults to 0.5. When a list is provided, the length + of the list should be equal to the number of classes. + Please be careful that this parameter is not the + class-wise weight but the weight of a binary classification + problem. This binary classification problem regards the + pixels which belong to one class as the foreground + and the other pixels as the background, each element in + the list is the weight of the corresponding foreground class. + The value of alpha or each element of alpha should be a float + in the interval [0, 1]. If you want to specify the class-wise + weight, please use `class_weight` parameter. + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. Options are "none", "mean" and + "sum". + class_weight (list[float], optional): Weight of each class. + Defaults to None. + loss_weight (float, optional): Weight of loss. Defaults to 1.0. + loss_name (str, optional): Name of the loss item. If you want this + loss item to be included into the backward graph, `loss_` must + be the prefix of the name. Defaults to 'loss_focal'. + """ + super().__init__() + assert use_sigmoid is True, \ + 'AssertionError: Only sigmoid focal loss supported now.' + assert reduction in ('none', 'mean', 'sum'), \ + "AssertionError: reduction should be 'none', 'mean' or " \ + "'sum'" + assert isinstance(alpha, (float, list)), \ + 'AssertionError: alpha should be of type float' + assert isinstance(gamma, float), \ + 'AssertionError: gamma should be of type float' + assert isinstance(loss_weight, float), \ + 'AssertionError: loss_weight should be of type float' + assert isinstance(loss_name, str), \ + 'AssertionError: loss_name should be of type str' + assert isinstance(class_weight, list) or class_weight is None, \ + 'AssertionError: class_weight must be None or of type list' + self.use_sigmoid = use_sigmoid + self.gamma = gamma + self.alpha = alpha + self.reduction = reduction + self.class_weight = class_weight + self.loss_weight = loss_weight + self._loss_name = loss_name + + def forward(self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None, + ignore_index=255, + **kwargs): + """Forward function. + + Args: + pred (torch.Tensor): The prediction with shape + (N, C) where C = number of classes, or + (N, C, d_1, d_2, ..., d_K) with K≥1 in the + case of K-dimensional loss. + target (torch.Tensor): The ground truth. If containing class + indices, shape (N) where each value is 0≤targets[i]≤C−1, + or (N, d_1, d_2, ..., d_K) with K≥1 in the case of + K-dimensional loss. If containing class probabilities, + same shape as the input. + weight (torch.Tensor, optional): The weight of loss for each + prediction. Defaults to None. + avg_factor (int, optional): Average factor that is used to + average the loss. Defaults to None. + reduction_override (str, optional): The reduction method used + to override the original reduction method of the loss. + Options are "none", "mean" and "sum". + ignore_index (int, optional): The label index to be ignored. + Default: 255 + Returns: + torch.Tensor: The calculated loss + """ + assert isinstance(ignore_index, int), \ + 'ignore_index must be of type int' + assert reduction_override in (None, 'none', 'mean', 'sum'), \ + "AssertionError: reduction should be 'none', 'mean' or " \ + "'sum'" + assert pred.shape == target.shape or \ + (pred.size(0) == target.size(0) and + pred.shape[2:] == target.shape[1:]), \ + "The shape of pred doesn't match the shape of target" + + original_shape = pred.shape + + # [B, C, d_1, d_2, ..., d_k] -> [C, B, d_1, d_2, ..., d_k] + pred = pred.transpose(0, 1) + # [C, B, d_1, d_2, ..., d_k] -> [C, N] + pred = pred.reshape(pred.size(0), -1) + # [C, N] -> [N, C] + pred = pred.transpose(0, 1).contiguous() + + if original_shape == target.shape: + # target with shape [B, C, d_1, d_2, ...] + # transform it's shape into [N, C] + # [B, C, d_1, d_2, ...] -> [C, B, d_1, d_2, ..., d_k] + target = target.transpose(0, 1) + # [C, B, d_1, d_2, ..., d_k] -> [C, N] + target = target.reshape(target.size(0), -1) + # [C, N] -> [N, C] + target = target.transpose(0, 1).contiguous() + else: + # target with shape [B, d_1, d_2, ...] + # transform it's shape into [N, ] + target = target.view(-1).contiguous() + valid_mask = (target != ignore_index).view(-1, 1) + # avoid raising error when using F.one_hot() + target = torch.where(target == ignore_index, target.new_tensor(0), + target) + + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.use_sigmoid: + num_classes = pred.size(1) + if torch.cuda.is_available() and pred.is_cuda: + if target.dim() == 1: + one_hot_target = F.one_hot( + target, num_classes=num_classes + 1) + if num_classes == 1: + one_hot_target = one_hot_target[:, 1] + target = 1 - target + else: + one_hot_target = one_hot_target[:, :num_classes] + else: + one_hot_target = target + target = target.argmax(dim=1) + valid_mask = (target != ignore_index).view(-1, 1) + calculate_loss_func = sigmoid_focal_loss + else: + one_hot_target = None + if target.dim() == 1: + target = F.one_hot(target, num_classes=num_classes + 1) + if num_classes == 1: + target = target[:, 1] + else: + target = target[:, num_classes] + else: + valid_mask = (target.argmax(dim=1) != ignore_index).view( + -1, 1) + calculate_loss_func = py_sigmoid_focal_loss + + loss_cls = self.loss_weight * calculate_loss_func( + pred, + target, + one_hot_target, + weight, + gamma=self.gamma, + alpha=self.alpha, + class_weight=self.class_weight, + valid_mask=valid_mask, + reduction=reduction, + avg_factor=avg_factor) + + if reduction == 'none': + # [N, C] -> [C, N] + loss_cls = loss_cls.transpose(0, 1) + # [C, N] -> [C, B, d1, d2, ...] + # original_shape: [B, C, d1, d2, ...] + loss_cls = loss_cls.reshape(original_shape[1], + original_shape[0], + *original_shape[2:]) + # [C, B, d1, d2, ...] -> [B, C, d1, d2, ...] + loss_cls = loss_cls.transpose(0, 1).contiguous() + else: + raise NotImplementedError + return loss_cls + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/third-party/InterFormer/mmseg/models/losses/huasdorff_distance_loss.py b/third-party/InterFormer/mmseg/models/losses/huasdorff_distance_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..d950ba728f8d419ea2b291e2159b926aca44038c --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/huasdorff_distance_loss.py @@ -0,0 +1,160 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from https://github.com/JunMa11/SegWithDistMap/blob/ +master/code/train_LA_HD.py (Apache-2.0 License)""" +import torch +import torch.nn as nn +import torch.nn.functional as F +from scipy.ndimage import distance_transform_edt as distance +from torch import Tensor + +from mmseg.registry import MODELS +from .utils import get_class_weight, weighted_loss + + +def compute_dtm(img_gt: Tensor, pred: Tensor) -> Tensor: + """ + compute the distance transform map of foreground in mask + Args: + img_gt: Ground truth of the image, (b, h, w) + pred: Predictions of the segmentation head after softmax, (b, c, h, w) + + Returns: + output: the foreground Distance Map (SDM) + dtm(x) = 0; x in segmentation boundary + inf|x-y|; x in segmentation + """ + + fg_dtm = torch.zeros_like(pred) + out_shape = pred.shape + for b in range(out_shape[0]): # batch size + for c in range(1, out_shape[1]): # default 0 channel is background + posmask = img_gt[b].byte() + if posmask.any(): + posdis = distance(posmask) + fg_dtm[b][c] = torch.from_numpy(posdis) + + return fg_dtm + + +@weighted_loss +def hd_loss(seg_soft: Tensor, + gt: Tensor, + seg_dtm: Tensor, + gt_dtm: Tensor, + class_weight=None, + ignore_index=255) -> Tensor: + """ + compute huasdorff distance loss for segmentation + Args: + seg_soft: softmax results, shape=(b,c,x,y) + gt: ground truth, shape=(b,x,y) + seg_dtm: segmentation distance transform map, shape=(b,c,x,y) + gt_dtm: ground truth distance transform map, shape=(b,c,x,y) + + Returns: + output: hd_loss + """ + assert seg_soft.shape[0] == gt.shape[0] + total_loss = 0 + num_class = seg_soft.shape[1] + if class_weight is not None: + assert class_weight.ndim == num_class + for i in range(1, num_class): + if i != ignore_index: + delta_s = (seg_soft[:, i, ...] - gt.float())**2 + s_dtm = seg_dtm[:, i, ...]**2 + g_dtm = gt_dtm[:, i, ...]**2 + dtm = s_dtm + g_dtm + multiplied = torch.einsum('bxy, bxy->bxy', delta_s, dtm) + hd_loss = multiplied.mean() + if class_weight is not None: + hd_loss *= class_weight[i] + total_loss += hd_loss + + return total_loss / num_class + + +@MODELS.register_module() +class HuasdorffDisstanceLoss(nn.Module): + """HuasdorffDisstanceLoss. This loss is proposed in `How Distance Transform + Maps Boost Segmentation CNNs: An Empirical Study. + + `_. + Args: + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_weight (float): Weight of the loss. Defaults to 1.0. + ignore_index (int | None): The label index to be ignored. Default: 255. + loss_name (str): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_boundary'. + """ + + def __init__(self, + reduction='mean', + class_weight=None, + loss_weight=1.0, + ignore_index=255, + loss_name='loss_huasdorff_disstance', + **kwargs): + super().__init__() + self.reduction = reduction + self.loss_weight = loss_weight + self.class_weight = get_class_weight(class_weight) + self._loss_name = loss_name + self.ignore_index = ignore_index + + def forward(self, + pred: Tensor, + target: Tensor, + avg_factor=None, + reduction_override=None, + **kwargs) -> Tensor: + """Forward function. + + Args: + pred (Tensor): Predictions of the segmentation head. (B, C, H, W) + target (Tensor): Ground truth of the image. (B, H, W) + avg_factor (int, optional): Average factor that is used to + average the loss. Defaults to None. + reduction_override (str, optional): The reduction method used + to override the original reduction method of the loss. + Options are "none", "mean" and "sum". + Returns: + Tensor: Loss tensor. + """ + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.class_weight is not None: + class_weight = pred.new_tensor(self.class_weight) + else: + class_weight = None + + pred_soft = F.softmax(pred, dim=1) + valid_mask = (target != self.ignore_index).long() + target = target * valid_mask + + with torch.no_grad(): + gt_dtm = compute_dtm(target.cpu(), pred_soft) + gt_dtm = gt_dtm.float() + seg_dtm2 = compute_dtm( + pred_soft.argmax(dim=1, keepdim=False).cpu(), pred_soft) + seg_dtm2 = seg_dtm2.float() + + loss_hd = self.loss_weight * hd_loss( + pred_soft, + target, + seg_dtm=seg_dtm2, + gt_dtm=gt_dtm, + reduction=reduction, + avg_factor=avg_factor, + class_weight=class_weight, + ignore_index=self.ignore_index) + return loss_hd + + @property + def loss_name(self): + return self._loss_name diff --git a/third-party/InterFormer/mmseg/models/losses/kldiv_loss.py b/third-party/InterFormer/mmseg/models/losses/kldiv_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..496ef9713f085a36d46837ac0b51d4cb9f956fce --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/kldiv_loss.py @@ -0,0 +1,99 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class KLDivLoss(nn.Module): + + def __init__(self, + temperature: float = 1.0, + reduction: str = 'mean', + loss_name: str = 'loss_kld'): + """Kullback-Leibler divergence Loss. + + + + Args: + temperature (float, optional): Temperature param + reduction (str, optional): The method to reduce the loss into a + scalar. Default is "mean". Options are "none", "sum", + and "mean" + """ + + assert isinstance(temperature, (float, int)), \ + 'Expected temperature to be' \ + f'float or int, but got {temperature.__class__.__name__} instead' + assert temperature != 0., 'Temperature must not be zero' + + assert reduction in ['mean', 'none', 'sum'], \ + 'Reduction must be one of the options ("mean", ' \ + f'"sum", "none"), but got {reduction}' + + super().__init__() + self.temperature = temperature + self.reduction = reduction + self._loss_name = loss_name + + def forward(self, input: torch.Tensor, target: torch.Tensor): + """Forward function. Calculate KL divergence Loss. + + Args: + input (Tensor): Logit tensor, + the data type is float32 or float64. + The shape is (N, C) where N is batchsize and C is number of + channels. + If there more than 2 dimensions, shape is (N, C, D1, D2, ... + Dk), k>= 1 + target (Tensor): Logit tensor, + the data type is float32 or float64. + input and target must be with the same shape. + + Returns: + (Tensor): Reduced loss. + """ + assert isinstance(input, torch.Tensor), 'Expected input to' \ + f'be Tensor, but got {input.__class__.__name__} instead' + assert isinstance(target, torch.Tensor), 'Expected target to' \ + f'be Tensor, but got {target.__class__.__name__} instead' + + assert input.shape == target.shape, 'Input and target ' \ + 'must have same shape,' \ + f'but got shapes {input.shape} and {target.shape}' + + input = F.softmax(input / self.temperature, dim=1) + target = F.softmax(target / self.temperature, dim=1) + + loss = F.kl_div(input, target, reduction='none', log_target=False) + loss = loss * self.temperature**2 + + batch_size = input.shape[0] + + if self.reduction == 'sum': + # Change view to calculate instance-wise sum + loss = loss.view(batch_size, -1) + return torch.sum(loss, dim=1) + + elif self.reduction == 'mean': + # Change view to calculate instance-wise mean + loss = loss.view(batch_size, -1) + return torch.mean(loss, dim=1) + + return loss + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/third-party/InterFormer/mmseg/models/losses/lovasz_loss.py b/third-party/InterFormer/mmseg/models/losses/lovasz_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..b47f9d8a15330a45d0d2d25f3c18d9386e2b335e --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/lovasz_loss.py @@ -0,0 +1,323 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytor +ch/lovasz_losses.py Lovasz-Softmax and Jaccard hinge loss in PyTorch Maxim +Berman 2018 ESAT-PSI KU Leuven (MIT License)""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.utils import is_list_of + +from mmseg.registry import MODELS +from .utils import get_class_weight, weight_reduce_loss + + +def lovasz_grad(gt_sorted): + """Computes gradient of the Lovasz extension w.r.t sorted errors. + + See Alg. 1 in paper. + """ + p = len(gt_sorted) + gts = gt_sorted.sum() + intersection = gts - gt_sorted.float().cumsum(0) + union = gts + (1 - gt_sorted).float().cumsum(0) + jaccard = 1. - intersection / union + if p > 1: # cover 1-pixel case + jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] + return jaccard + + +def flatten_binary_logits(logits, labels, ignore_index=None): + """Flattens predictions in the batch (binary case) Remove labels equal to + 'ignore_index'.""" + logits = logits.view(-1) + labels = labels.view(-1) + if ignore_index is None: + return logits, labels + valid = (labels != ignore_index) + vlogits = logits[valid] + vlabels = labels[valid] + return vlogits, vlabels + + +def flatten_probs(probs, labels, ignore_index=None): + """Flattens predictions in the batch.""" + if probs.dim() == 3: + # assumes output of a sigmoid layer + B, H, W = probs.size() + probs = probs.view(B, 1, H, W) + B, C, H, W = probs.size() + probs = probs.permute(0, 2, 3, 1).contiguous().view(-1, C) # B*H*W, C=P,C + labels = labels.view(-1) + if ignore_index is None: + return probs, labels + valid = (labels != ignore_index) + vprobs = probs[valid.nonzero().squeeze()] + vlabels = labels[valid] + return vprobs, vlabels + + +def lovasz_hinge_flat(logits, labels): + """Binary Lovasz hinge loss. + + Args: + logits (torch.Tensor): [P], logits at each prediction + (between -infty and +infty). + labels (torch.Tensor): [P], binary ground truth labels (0 or 1). + + Returns: + torch.Tensor: The calculated loss. + """ + if len(labels) == 0: + # only void pixels, the gradients should be 0 + return logits.sum() * 0. + signs = 2. * labels.float() - 1. + errors = (1. - logits * signs) + errors_sorted, perm = torch.sort(errors, dim=0, descending=True) + perm = perm.data + gt_sorted = labels[perm] + grad = lovasz_grad(gt_sorted) + loss = torch.dot(F.relu(errors_sorted), grad) + return loss + + +def lovasz_hinge(logits, + labels, + classes='present', + per_image=False, + class_weight=None, + reduction='mean', + avg_factor=None, + ignore_index=255): + """Binary Lovasz hinge loss. + + Args: + logits (torch.Tensor): [B, H, W], logits at each pixel + (between -infty and +infty). + labels (torch.Tensor): [B, H, W], binary ground truth masks (0 or 1). + classes (str | list[int], optional): Placeholder, to be consistent with + other loss. Default: None. + per_image (bool, optional): If per_image is True, compute the loss per + image instead of per batch. Default: False. + class_weight (list[float], optional): Placeholder, to be consistent + with other loss. Default: None. + reduction (str, optional): The method used to reduce the loss. Options + are "none", "mean" and "sum". This parameter only works when + per_image is True. Default: 'mean'. + avg_factor (int, optional): Average factor that is used to average + the loss. This parameter only works when per_image is True. + Default: None. + ignore_index (int | None): The label index to be ignored. Default: 255. + + Returns: + torch.Tensor: The calculated loss. + """ + if per_image: + loss = [ + lovasz_hinge_flat(*flatten_binary_logits( + logit.unsqueeze(0), label.unsqueeze(0), ignore_index)) + for logit, label in zip(logits, labels) + ] + loss = weight_reduce_loss( + torch.stack(loss), None, reduction, avg_factor) + else: + loss = lovasz_hinge_flat( + *flatten_binary_logits(logits, labels, ignore_index)) + return loss + + +def lovasz_softmax_flat(probs, labels, classes='present', class_weight=None): + """Multi-class Lovasz-Softmax loss. + + Args: + probs (torch.Tensor): [P, C], class probabilities at each prediction + (between 0 and 1). + labels (torch.Tensor): [P], ground truth labels (between 0 and C - 1). + classes (str | list[int], optional): Classes chosen to calculate loss. + 'all' for all classes, 'present' for classes present in labels, or + a list of classes to average. Default: 'present'. + class_weight (list[float], optional): The weight for each class. + Default: None. + + Returns: + torch.Tensor: The calculated loss. + """ + if probs.numel() == 0: + # only void pixels, the gradients should be 0 + return probs * 0. + C = probs.size(1) + losses = [] + class_to_sum = list(range(C)) if classes in ['all', 'present'] else classes + for c in class_to_sum: + fg = (labels == c).float() # foreground for class c + if (classes == 'present' and fg.sum() == 0): + continue + if C == 1: + if len(classes) > 1: + raise ValueError('Sigmoid output possible only with 1 class') + class_pred = probs[:, 0] + else: + class_pred = probs[:, c] + errors = (fg - class_pred).abs() + errors_sorted, perm = torch.sort(errors, 0, descending=True) + perm = perm.data + fg_sorted = fg[perm] + loss = torch.dot(errors_sorted, lovasz_grad(fg_sorted)) + if class_weight is not None: + loss *= class_weight[c] + losses.append(loss) + return torch.stack(losses).mean() + + +def lovasz_softmax(probs, + labels, + classes='present', + per_image=False, + class_weight=None, + reduction='mean', + avg_factor=None, + ignore_index=255): + """Multi-class Lovasz-Softmax loss. + + Args: + probs (torch.Tensor): [B, C, H, W], class probabilities at each + prediction (between 0 and 1). + labels (torch.Tensor): [B, H, W], ground truth labels (between 0 and + C - 1). + classes (str | list[int], optional): Classes chosen to calculate loss. + 'all' for all classes, 'present' for classes present in labels, or + a list of classes to average. Default: 'present'. + per_image (bool, optional): If per_image is True, compute the loss per + image instead of per batch. Default: False. + class_weight (list[float], optional): The weight for each class. + Default: None. + reduction (str, optional): The method used to reduce the loss. Options + are "none", "mean" and "sum". This parameter only works when + per_image is True. Default: 'mean'. + avg_factor (int, optional): Average factor that is used to average + the loss. This parameter only works when per_image is True. + Default: None. + ignore_index (int | None): The label index to be ignored. Default: 255. + + Returns: + torch.Tensor: The calculated loss. + """ + + if per_image: + loss = [ + lovasz_softmax_flat( + *flatten_probs( + prob.unsqueeze(0), label.unsqueeze(0), ignore_index), + classes=classes, + class_weight=class_weight) + for prob, label in zip(probs, labels) + ] + loss = weight_reduce_loss( + torch.stack(loss), None, reduction, avg_factor) + else: + loss = lovasz_softmax_flat( + *flatten_probs(probs, labels, ignore_index), + classes=classes, + class_weight=class_weight) + return loss + + +@MODELS.register_module() +class LovaszLoss(nn.Module): + """LovaszLoss. + + This loss is proposed in `The Lovasz-Softmax loss: A tractable surrogate + for the optimization of the intersection-over-union measure in neural + networks `_. + + Args: + loss_type (str, optional): Binary or multi-class loss. + Default: 'multi_class'. Options are "binary" and "multi_class". + classes (str | list[int], optional): Classes chosen to calculate loss. + 'all' for all classes, 'present' for classes present in labels, or + a list of classes to average. Default: 'present'. + per_image (bool, optional): If per_image is True, compute the loss per + image instead of per batch. Default: False. + reduction (str, optional): The method used to reduce the loss. Options + are "none", "mean" and "sum". This parameter only works when + per_image is True. Default: 'mean'. + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_weight (float, optional): Weight of the loss. Defaults to 1.0. + loss_name (str, optional): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_lovasz'. + """ + + def __init__(self, + loss_type='multi_class', + classes='present', + per_image=False, + reduction='mean', + class_weight=None, + loss_weight=1.0, + loss_name='loss_lovasz'): + super().__init__() + assert loss_type in ('binary', 'multi_class'), "loss_type should be \ + 'binary' or 'multi_class'." + + if loss_type == 'binary': + self.cls_criterion = lovasz_hinge + else: + self.cls_criterion = lovasz_softmax + assert classes in ('all', 'present') or is_list_of(classes, int) + if not per_image: + assert reduction == 'none', "reduction should be 'none' when \ + per_image is False." + + self.classes = classes + self.per_image = per_image + self.reduction = reduction + self.loss_weight = loss_weight + self.class_weight = get_class_weight(class_weight) + self._loss_name = loss_name + + def forward(self, + cls_score, + label, + weight=None, + avg_factor=None, + reduction_override=None, + **kwargs): + """Forward function.""" + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.class_weight is not None: + class_weight = cls_score.new_tensor(self.class_weight) + else: + class_weight = None + + # if multi-class loss, transform logits to probs + if self.cls_criterion == lovasz_softmax: + cls_score = F.softmax(cls_score, dim=1) + + loss_cls = self.loss_weight * self.cls_criterion( + cls_score, + label, + self.classes, + self.per_image, + class_weight=class_weight, + reduction=reduction, + avg_factor=avg_factor, + **kwargs) + return loss_cls + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/third-party/InterFormer/mmseg/models/losses/ohem_cross_entropy_loss.py b/third-party/InterFormer/mmseg/models/losses/ohem_cross_entropy_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a519b4d84e1dbf86ebc7ad07372ddbdfb0ff3d13 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/ohem_cross_entropy_loss.py @@ -0,0 +1,94 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional, Union + +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class OhemCrossEntropy(nn.Module): + """OhemCrossEntropy loss. + + This func is modified from + `PIDNet `_. # noqa + + Licensed under the MIT License. + + Args: + ignore_label (int): Labels to ignore when computing the loss. + Default: 255 + thresh (float, optional): The threshold for hard example selection. + Below which, are prediction with low confidence. If not + specified, the hard examples will be pixels of top ``min_kept`` + loss. Default: 0.7. + min_kept (int, optional): The minimum number of predictions to keep. + Default: 100000. + loss_weight (float): Weight of the loss. Defaults to 1.0. + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_name (str): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_boundary'. + """ + + def __init__(self, + ignore_label: int = 255, + thres: float = 0.7, + min_kept: int = 100000, + loss_weight: float = 1.0, + class_weight: Optional[Union[List[float], str]] = None, + loss_name: str = 'loss_ohem'): + super().__init__() + self.thresh = thres + self.min_kept = max(1, min_kept) + self.ignore_label = ignore_label + self.loss_weight = loss_weight + self.loss_name_ = loss_name + self.class_weight = class_weight + + def forward(self, score: Tensor, target: Tensor) -> Tensor: + """Forward function. + Args: + score (Tensor): Predictions of the segmentation head. + target (Tensor): Ground truth of the image. + + Returns: + Tensor: Loss tensor. + """ + # score: (N, C, H, W) + pred = F.softmax(score, dim=1) + if self.class_weight is not None: + class_weight = score.new_tensor(self.class_weight) + else: + class_weight = None + + pixel_losses = F.cross_entropy( + score, + target, + weight=class_weight, + ignore_index=self.ignore_label, + reduction='none').contiguous().view(-1) # (N*H*W) + mask = target.contiguous().view(-1) != self.ignore_label # (N*H*W) + + tmp_target = target.clone() # (N, H, W) + tmp_target[tmp_target == self.ignore_label] = 0 + # pred: (N, C, H, W) -> (N*H*W, C) + pred = pred.gather(1, tmp_target.unsqueeze(1)) + # pred: (N*H*W, C) -> (N*H*W), ind: (N*H*W) + pred, ind = pred.contiguous().view(-1, )[mask].contiguous().sort() + if pred.numel() > 0: + min_value = pred[min(self.min_kept, pred.numel() - 1)] + else: + return score.new_tensor(0.0) + threshold = max(min_value, self.thresh) + + pixel_losses = pixel_losses[mask][ind] + pixel_losses = pixel_losses[pred < threshold] + return self.loss_weight * pixel_losses.mean() + + @property + def loss_name(self): + return self.loss_name_ diff --git a/third-party/InterFormer/mmseg/models/losses/silog_loss.py b/third-party/InterFormer/mmseg/models/losses/silog_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc07aac424a9308bce33e00c621369ac555f4ba --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/silog_loss.py @@ -0,0 +1,122 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor + +from mmseg.registry import MODELS +from .utils import weight_reduce_loss + + +def silog_loss(pred: Tensor, + target: Tensor, + weight: Optional[Tensor] = None, + eps: float = 1e-4, + reduction: Union[str, None] = 'mean', + avg_factor: Optional[int] = None) -> Tensor: + """Computes the Scale-Invariant Logarithmic (SI-Log) loss between + prediction and target. + + Args: + pred (Tensor): Predicted output. + target (Tensor): Ground truth. + weight (Optional[Tensor]): Optional weight to apply on the loss. + eps (float): Epsilon value to avoid division and log(0). + reduction (Union[str, None]): Specifies the reduction to apply to the + output: 'mean', 'sum' or None. + avg_factor (Optional[int]): Optional average factor for the loss. + + Returns: + Tensor: The calculated SI-Log loss. + """ + pred, target = pred.flatten(1), target.flatten(1) + valid_mask = (target > eps).detach().float() + + diff_log = torch.log(target.clamp(min=eps)) - torch.log( + pred.clamp(min=eps)) + + valid_mask = (target > eps).detach() & (~torch.isnan(diff_log)) + diff_log[~valid_mask] = 0.0 + valid_mask = valid_mask.float() + + diff_log_sq_mean = (diff_log.pow(2) * valid_mask).sum( + dim=1) / valid_mask.sum(dim=1).clamp(min=eps) + diff_log_mean = (diff_log * valid_mask).sum(dim=1) / valid_mask.sum( + dim=1).clamp(min=eps) + + loss = torch.sqrt(diff_log_sq_mean - 0.5 * diff_log_mean.pow(2)) + + if weight is not None: + weight = weight.float() + + loss = weight_reduce_loss(loss, weight, reduction, avg_factor) + return loss + + +@MODELS.register_module() +class SiLogLoss(nn.Module): + """Compute SiLog loss. + + Args: + reduction (str, optional): The method used + to reduce the loss. Options are "none", + "mean" and "sum". Defaults to 'mean'. + loss_weight (float, optional): Weight of loss. Defaults to 1.0. + eps (float): Avoid dividing by zero. Defaults to 1e-3. + loss_name (str, optional): Name of the loss item. If you want this + loss item to be included into the backward graph, `loss_` must + be the prefix of the name. Defaults to 'loss_silog'. + """ + + def __init__(self, + reduction='mean', + loss_weight=1.0, + eps=1e-6, + loss_name='loss_silog'): + super().__init__() + self.reduction = reduction + self.loss_weight = loss_weight + self.eps = eps + self._loss_name = loss_name + + def forward( + self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None, + ): + + assert pred.shape == target.shape, 'the shapes of pred ' \ + f'({pred.shape}) and target ({target.shape}) are mismatch' + + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + + loss = self.loss_weight * silog_loss( + pred, + target, + weight, + eps=self.eps, + reduction=reduction, + avg_factor=avg_factor, + ) + + return loss + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/third-party/InterFormer/mmseg/models/losses/tversky_loss.py b/third-party/InterFormer/mmseg/models/losses/tversky_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..bfca1af6669e3ac328492da11758a084999ef906 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/tversky_loss.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from +https://github.com/JunMa11/SegLoss/blob/master/losses_pytorch/dice_loss.py#L333 +(Apache-2.0 License)""" +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ..builder import LOSSES +from .utils import get_class_weight, weighted_loss + + +@weighted_loss +def tversky_loss(pred, + target, + valid_mask, + alpha=0.3, + beta=0.7, + smooth=1, + class_weight=None, + ignore_index=255): + assert pred.shape[0] == target.shape[0] + total_loss = 0 + num_classes = pred.shape[1] + for i in range(num_classes): + if i != ignore_index: + tversky_loss = binary_tversky_loss( + pred[:, i], + target[..., i], + valid_mask=valid_mask, + alpha=alpha, + beta=beta, + smooth=smooth) + if class_weight is not None: + tversky_loss *= class_weight[i] + total_loss += tversky_loss + return total_loss / num_classes + + +@weighted_loss +def binary_tversky_loss(pred, + target, + valid_mask, + alpha=0.3, + beta=0.7, + smooth=1): + assert pred.shape[0] == target.shape[0] + pred = pred.reshape(pred.shape[0], -1) + target = target.reshape(target.shape[0], -1) + valid_mask = valid_mask.reshape(valid_mask.shape[0], -1) + + TP = torch.sum(torch.mul(pred, target) * valid_mask, dim=1) + FP = torch.sum(torch.mul(pred, 1 - target) * valid_mask, dim=1) + FN = torch.sum(torch.mul(1 - pred, target) * valid_mask, dim=1) + tversky = (TP + smooth) / (TP + alpha * FP + beta * FN + smooth) + + return 1 - tversky + + +@LOSSES.register_module() +class TverskyLoss(nn.Module): + """TverskyLoss. This loss is proposed in `Tversky loss function for image + segmentation using 3D fully convolutional deep networks. + + `_. + Args: + smooth (float): A float number to smooth loss, and avoid NaN error. + Default: 1. + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_weight (float, optional): Weight of the loss. Default to 1.0. + ignore_index (int | None): The label index to be ignored. Default: 255. + alpha(float, in [0, 1]): + The coefficient of false positives. Default: 0.3. + beta (float, in [0, 1]): + The coefficient of false negatives. Default: 0.7. + Note: alpha + beta = 1. + loss_name (str, optional): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_tversky'. + """ + + def __init__(self, + smooth=1, + class_weight=None, + loss_weight=1.0, + ignore_index=255, + alpha=0.3, + beta=0.7, + loss_name='loss_tversky'): + super().__init__() + self.smooth = smooth + self.class_weight = get_class_weight(class_weight) + self.loss_weight = loss_weight + self.ignore_index = ignore_index + assert (alpha + beta == 1.0), 'Sum of alpha and beta but be 1.0!' + self.alpha = alpha + self.beta = beta + self._loss_name = loss_name + + def forward(self, pred, target, **kwargs): + if self.class_weight is not None: + class_weight = pred.new_tensor(self.class_weight) + else: + class_weight = None + + pred = F.softmax(pred, dim=1) + num_classes = pred.shape[1] + one_hot_target = F.one_hot( + torch.clamp(target.long(), 0, num_classes - 1), + num_classes=num_classes) + valid_mask = (target != self.ignore_index).long() + + loss = self.loss_weight * tversky_loss( + pred, + one_hot_target, + valid_mask=valid_mask, + alpha=self.alpha, + beta=self.beta, + smooth=self.smooth, + class_weight=class_weight, + ignore_index=self.ignore_index) + return loss + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/third-party/InterFormer/mmseg/models/losses/utils.py b/third-party/InterFormer/mmseg/models/losses/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..047803473316ff5fc58de2b8e35ef0087bc3b624 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/losses/utils.py @@ -0,0 +1,129 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import functools + +import numpy as np +import torch +import torch.nn.functional as F +from mmengine.fileio import load + + +def get_class_weight(class_weight): + """Get class weight for loss function. + + Args: + class_weight (list[float] | str | None): If class_weight is a str, + take it as a file name and read from it. + """ + if isinstance(class_weight, str): + # take it as a file path + if class_weight.endswith('.npy'): + class_weight = np.load(class_weight) + else: + # pkl, json or yaml + class_weight = load(class_weight) + + return class_weight + + +def reduce_loss(loss, reduction) -> torch.Tensor: + """Reduce loss as specified. + + Args: + loss (Tensor): Elementwise loss tensor. + reduction (str): Options are "none", "mean" and "sum". + + Return: + Tensor: Reduced loss tensor. + """ + reduction_enum = F._Reduction.get_enum(reduction) + # none: 0, elementwise_mean:1, sum: 2 + if reduction_enum == 0: + return loss + elif reduction_enum == 1: + return loss.mean() + elif reduction_enum == 2: + return loss.sum() + + +def weight_reduce_loss(loss, + weight=None, + reduction='mean', + avg_factor=None) -> torch.Tensor: + """Apply element-wise weight and reduce loss. + + Args: + loss (Tensor): Element-wise loss. + weight (Tensor): Element-wise weights. + reduction (str): Same as built-in losses of PyTorch. + avg_factor (float): Average factor when computing the mean of losses. + + Returns: + Tensor: Processed loss values. + """ + # if weight is specified, apply element-wise weight + if weight is not None: + assert weight.dim() == loss.dim() + if weight.dim() > 1: + assert weight.size(1) == 1 or weight.size(1) == loss.size(1) + loss = loss * weight + + # if avg_factor is not specified, just reduce the loss + if avg_factor is None: + loss = reduce_loss(loss, reduction) + else: + # if reduction is mean, then average the loss by avg_factor + if reduction == 'mean': + # Avoid causing ZeroDivisionError when avg_factor is 0.0, + # i.e., all labels of an image belong to ignore index. + eps = torch.finfo(torch.float32).eps + loss = loss.sum() / (avg_factor + eps) + # if reduction is 'none', then do nothing, otherwise raise an error + elif reduction != 'none': + raise ValueError('avg_factor can not be used with reduction="sum"') + return loss + + +def weighted_loss(loss_func): + """Create a weighted version of a given loss function. + + To use this decorator, the loss function must have the signature like + `loss_func(pred, target, **kwargs)`. The function only needs to compute + element-wise loss without any reduction. This decorator will add weight + and reduction arguments to the function. The decorated function will have + the signature like `loss_func(pred, target, weight=None, reduction='mean', + avg_factor=None, **kwargs)`. + + :Example: + + >>> import torch + >>> @weighted_loss + >>> def l1_loss(pred, target): + >>> return (pred - target).abs() + + >>> pred = torch.Tensor([0, 2, 3]) + >>> target = torch.Tensor([1, 1, 1]) + >>> weight = torch.Tensor([1, 0, 1]) + + >>> l1_loss(pred, target) + tensor(1.3333) + >>> l1_loss(pred, target, weight) + tensor(1.) + >>> l1_loss(pred, target, reduction='none') + tensor([1., 1., 2.]) + >>> l1_loss(pred, target, weight, avg_factor=2) + tensor(1.5000) + """ + + @functools.wraps(loss_func) + def wrapper(pred, + target, + weight=None, + reduction='mean', + avg_factor=None, + **kwargs): + # get element-wise loss + loss = loss_func(pred, target, **kwargs) + loss = weight_reduce_loss(loss, weight, reduction, avg_factor) + return loss + + return wrapper diff --git a/third-party/InterFormer/mmseg/models/necks/__init__.py b/third-party/InterFormer/mmseg/models/necks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff03186a92b78f942e79cff9eec9f5e2784c359a --- /dev/null +++ b/third-party/InterFormer/mmseg/models/necks/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .featurepyramid import Feature2Pyramid +from .fpn import FPN +from .ic_neck import ICNeck +from .jpu import JPU +from .mla_neck import MLANeck +from .multilevel_neck import MultiLevelNeck + +__all__ = [ + 'FPN', 'MultiLevelNeck', 'MLANeck', 'ICNeck', 'JPU', 'Feature2Pyramid' +] diff --git a/third-party/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3477f13a4fd7dea15251eb0f87e71689dc64b1b Binary files /dev/null and b/third-party/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-38.pyc b/third-party/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3911d3224fdbe86e4afac9bee50ede3770778a59 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-38.pyc b/third-party/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26df1d6f086136dff02f64bb7fc7ea8e5298e126 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-38.pyc b/third-party/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12f6aa6ff0ac3865b437f0a0c70bb8b76124bb65 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-38.pyc b/third-party/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..962b026cb6e62c03280e84e15468e43e6f9d7692 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-38.pyc b/third-party/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bb1909329e2bc0bffc27abcd2c47e590c6f4726 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-38.pyc b/third-party/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3660261060da21771eed6d9564684e741de634a2 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/necks/featurepyramid.py b/third-party/InterFormer/mmseg/models/necks/featurepyramid.py new file mode 100644 index 0000000000000000000000000000000000000000..dc1250d39dafcf78880aa282bcba4215520ad94e --- /dev/null +++ b/third-party/InterFormer/mmseg/models/necks/featurepyramid.py @@ -0,0 +1,67 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import build_norm_layer + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class Feature2Pyramid(nn.Module): + """Feature2Pyramid. + + A neck structure connect ViT backbone and decoder_heads. + + Args: + embed_dims (int): Embedding dimension. + rescales (list[float]): Different sampling multiples were + used to obtain pyramid features. Default: [4, 2, 1, 0.5]. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='SyncBN', requires_grad=True). + """ + + def __init__(self, + embed_dim, + rescales=[4, 2, 1, 0.5], + norm_cfg=dict(type='SyncBN', requires_grad=True)): + super().__init__() + self.rescales = rescales + self.upsample_4x = None + for k in self.rescales: + if k == 4: + self.upsample_4x = nn.Sequential( + nn.ConvTranspose2d( + embed_dim, embed_dim, kernel_size=2, stride=2), + build_norm_layer(norm_cfg, embed_dim)[1], + nn.GELU(), + nn.ConvTranspose2d( + embed_dim, embed_dim, kernel_size=2, stride=2), + ) + elif k == 2: + self.upsample_2x = nn.Sequential( + nn.ConvTranspose2d( + embed_dim, embed_dim, kernel_size=2, stride=2)) + elif k == 1: + self.identity = nn.Identity() + elif k == 0.5: + self.downsample_2x = nn.MaxPool2d(kernel_size=2, stride=2) + elif k == 0.25: + self.downsample_4x = nn.MaxPool2d(kernel_size=4, stride=4) + else: + raise KeyError(f'invalid {k} for feature2pyramid') + + def forward(self, inputs): + assert len(inputs) == len(self.rescales) + outputs = [] + if self.upsample_4x is not None: + ops = [ + self.upsample_4x, self.upsample_2x, self.identity, + self.downsample_2x + ] + else: + ops = [ + self.upsample_2x, self.identity, self.downsample_2x, + self.downsample_4x + ] + for i in range(len(inputs)): + outputs.append(ops[i](inputs[i])) + return tuple(outputs) diff --git a/third-party/InterFormer/mmseg/models/necks/fpn.py b/third-party/InterFormer/mmseg/models/necks/fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..ddab74c00a262a89031fda44824c5de0e2e9a362 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/necks/fpn.py @@ -0,0 +1,212 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +@MODELS.register_module() +class FPN(BaseModule): + """Feature Pyramid Network. + + This neck is the implementation of `Feature Pyramid Networks for Object + Detection `_. + + Args: + in_channels (list[int]): Number of input channels per scale. + out_channels (int): Number of output channels (used at each scale). + num_outs (int): Number of output scales. + start_level (int): Index of the start input backbone level used to + build the feature pyramid. Default: 0. + end_level (int): Index of the end input backbone level (exclusive) to + build the feature pyramid. Default: -1, which means the last level. + add_extra_convs (bool | str): If bool, it decides whether to add conv + layers on top of the original feature maps. Default to False. + If True, its actual mode is specified by `extra_convs_on_inputs`. + If str, it specifies the source feature map of the extra convs. + Only the following options are allowed + + - 'on_input': Last feat map of neck inputs (i.e. backbone feature). + - 'on_lateral': Last feature map after lateral convs. + - 'on_output': The last output feature map after fpn convs. + extra_convs_on_inputs (bool, deprecated): Whether to apply extra convs + on the original feature from the backbone. If True, + it is equivalent to `add_extra_convs='on_input'`. If False, it is + equivalent to set `add_extra_convs='on_output'`. Default to True. + relu_before_extra_convs (bool): Whether to apply relu before the extra + conv. Default: False. + no_norm_on_lateral (bool): Whether to apply norm on lateral. + Default: False. + conv_cfg (dict): Config dict for convolution layer. Default: None. + norm_cfg (dict): Config dict for normalization layer. Default: None. + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: None. + upsample_cfg (dict): Config dict for interpolate layer. + Default: dict(mode='nearest'). + init_cfg (dict or list[dict], optional): Initialization config dict. + + Example: + >>> import torch + >>> in_channels = [2, 3, 5, 7] + >>> scales = [340, 170, 84, 43] + >>> inputs = [torch.rand(1, c, s, s) + ... for c, s in zip(in_channels, scales)] + >>> self = FPN(in_channels, 11, len(in_channels)).eval() + >>> outputs = self.forward(inputs) + >>> for i in range(len(outputs)): + ... print(f'outputs[{i}].shape = {outputs[i].shape}') + outputs[0].shape = torch.Size([1, 11, 340, 340]) + outputs[1].shape = torch.Size([1, 11, 170, 170]) + outputs[2].shape = torch.Size([1, 11, 84, 84]) + outputs[3].shape = torch.Size([1, 11, 43, 43]) + """ + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False, + extra_convs_on_inputs=False, + relu_before_extra_convs=False, + no_norm_on_lateral=False, + conv_cfg=None, + norm_cfg=None, + act_cfg=None, + upsample_cfg=dict(mode='nearest'), + init_cfg=dict( + type='Xavier', layer='Conv2d', distribution='uniform')): + super().__init__(init_cfg) + assert isinstance(in_channels, list) + self.in_channels = in_channels + self.out_channels = out_channels + self.num_ins = len(in_channels) + self.num_outs = num_outs + self.relu_before_extra_convs = relu_before_extra_convs + self.no_norm_on_lateral = no_norm_on_lateral + self.fp16_enabled = False + self.upsample_cfg = upsample_cfg.copy() + + if end_level == -1: + self.backbone_end_level = self.num_ins + assert num_outs >= self.num_ins - start_level + else: + # if end_level < inputs, no extra level is allowed + self.backbone_end_level = end_level + assert end_level <= len(in_channels) + assert num_outs == end_level - start_level + self.start_level = start_level + self.end_level = end_level + self.add_extra_convs = add_extra_convs + assert isinstance(add_extra_convs, (str, bool)) + if isinstance(add_extra_convs, str): + # Extra_convs_source choices: 'on_input', 'on_lateral', 'on_output' + assert add_extra_convs in ('on_input', 'on_lateral', 'on_output') + elif add_extra_convs: # True + if extra_convs_on_inputs: + # For compatibility with previous release + # TODO: deprecate `extra_convs_on_inputs` + self.add_extra_convs = 'on_input' + else: + self.add_extra_convs = 'on_output' + + self.lateral_convs = nn.ModuleList() + self.fpn_convs = nn.ModuleList() + + for i in range(self.start_level, self.backbone_end_level): + l_conv = ConvModule( + in_channels[i], + out_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg if not self.no_norm_on_lateral else None, + act_cfg=act_cfg, + inplace=False) + fpn_conv = ConvModule( + out_channels, + out_channels, + 3, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + inplace=False) + + self.lateral_convs.append(l_conv) + self.fpn_convs.append(fpn_conv) + + # add extra conv layers (e.g., RetinaNet) + extra_levels = num_outs - self.backbone_end_level + self.start_level + if self.add_extra_convs and extra_levels >= 1: + for i in range(extra_levels): + if i == 0 and self.add_extra_convs == 'on_input': + in_channels = self.in_channels[self.backbone_end_level - 1] + else: + in_channels = out_channels + extra_fpn_conv = ConvModule( + in_channels, + out_channels, + 3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + inplace=False) + self.fpn_convs.append(extra_fpn_conv) + + def forward(self, inputs): + assert len(inputs) == len(self.in_channels) + + # build laterals + laterals = [ + lateral_conv(inputs[i + self.start_level]) + for i, lateral_conv in enumerate(self.lateral_convs) + ] + + # build top-down path + used_backbone_levels = len(laterals) + for i in range(used_backbone_levels - 1, 0, -1): + # In some cases, fixing `scale factor` (e.g. 2) is preferred, but + # it cannot co-exist with `size` in `F.interpolate`. + if 'scale_factor' in self.upsample_cfg: + laterals[i - 1] = laterals[i - 1] + resize( + laterals[i], **self.upsample_cfg) + else: + prev_shape = laterals[i - 1].shape[2:] + laterals[i - 1] = laterals[i - 1] + resize( + laterals[i], size=prev_shape, **self.upsample_cfg) + + # build outputs + # part 1: from original levels + outs = [ + self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels) + ] + # part 2: add extra levels + if self.num_outs > len(outs): + # use max pool to get more levels on top of outputs + # (e.g., Faster R-CNN, Mask R-CNN) + if not self.add_extra_convs: + for i in range(self.num_outs - used_backbone_levels): + outs.append(F.max_pool2d(outs[-1], 1, stride=2)) + # add conv layers on top of original feature maps (RetinaNet) + else: + if self.add_extra_convs == 'on_input': + extra_source = inputs[self.backbone_end_level - 1] + elif self.add_extra_convs == 'on_lateral': + extra_source = laterals[-1] + elif self.add_extra_convs == 'on_output': + extra_source = outs[-1] + else: + raise NotImplementedError + outs.append(self.fpn_convs[used_backbone_levels](extra_source)) + for i in range(used_backbone_levels + 1, self.num_outs): + if self.relu_before_extra_convs: + outs.append(self.fpn_convs[i](F.relu(outs[-1]))) + else: + outs.append(self.fpn_convs[i](outs[-1])) + return tuple(outs) diff --git a/third-party/InterFormer/mmseg/models/necks/ic_neck.py b/third-party/InterFormer/mmseg/models/necks/ic_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..9763541e0980cb0ec53a342b656e64c99d87ed7e --- /dev/null +++ b/third-party/InterFormer/mmseg/models/necks/ic_neck.py @@ -0,0 +1,148 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +class CascadeFeatureFusion(BaseModule): + """Cascade Feature Fusion Unit in ICNet. + + Args: + low_channels (int): The number of input channels for + low resolution feature map. + high_channels (int): The number of input channels for + high resolution feature map. + out_channels (int): The number of output channels. + conv_cfg (dict): Dictionary to construct and config conv layer. + Default: None. + norm_cfg (dict): Dictionary to construct and config norm layer. + Default: dict(type='BN'). + act_cfg (dict): Dictionary to construct and config act layer. + Default: dict(type='ReLU'). + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + + Returns: + x (Tensor): The output tensor of shape (N, out_channels, H, W). + x_low (Tensor): The output tensor of shape (N, out_channels, H, W) + for Cascade Label Guidance in auxiliary heads. + """ + + def __init__(self, + low_channels, + high_channels, + out_channels, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.align_corners = align_corners + self.conv_low = ConvModule( + low_channels, + out_channels, + 3, + padding=2, + dilation=2, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.conv_high = ConvModule( + high_channels, + out_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, x_low, x_high): + x_low = resize( + x_low, + size=x_high.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + # Note: Different from original paper, `x_low` is underwent + # `self.conv_low` rather than another 1x1 conv classifier + # before being used for auxiliary head. + x_low = self.conv_low(x_low) + x_high = self.conv_high(x_high) + x = x_low + x_high + x = F.relu(x, inplace=True) + return x, x_low + + +@MODELS.register_module() +class ICNeck(BaseModule): + """ICNet for Real-Time Semantic Segmentation on High-Resolution Images. + + This head is the implementation of `ICHead + `_. + + Args: + in_channels (int): The number of input image channels. Default: 3. + out_channels (int): The numbers of output feature channels. + Default: 128. + conv_cfg (dict): Dictionary to construct and config conv layer. + Default: None. + norm_cfg (dict): Dictionary to construct and config norm layer. + Default: dict(type='BN'). + act_cfg (dict): Dictionary to construct and config act layer. + Default: dict(type='ReLU'). + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels=(64, 256, 256), + out_channels=128, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert len(in_channels) == 3, 'Length of input channels \ + must be 3!' + + self.in_channels = in_channels + self.out_channels = out_channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.align_corners = align_corners + self.cff_24 = CascadeFeatureFusion( + self.in_channels[2], + self.in_channels[1], + self.out_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + + self.cff_12 = CascadeFeatureFusion( + self.out_channels, + self.in_channels[0], + self.out_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + + def forward(self, inputs): + assert len(inputs) == 3, 'Length of input feature \ + maps must be 3!' + + x_sub1, x_sub2, x_sub4 = inputs + x_cff_24, x_24 = self.cff_24(x_sub4, x_sub2) + x_cff_12, x_12 = self.cff_12(x_cff_24, x_sub1) + # Note: `x_cff_12` is used for decode_head, + # `x_24` and `x_12` are used for auxiliary head. + return x_24, x_12, x_cff_12 diff --git a/third-party/InterFormer/mmseg/models/necks/jpu.py b/third-party/InterFormer/mmseg/models/necks/jpu.py new file mode 100644 index 0000000000000000000000000000000000000000..3ea0fe2183377d3e3c1a87ca8a0df909b123cdfa --- /dev/null +++ b/third-party/InterFormer/mmseg/models/necks/jpu.py @@ -0,0 +1,131 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +@MODELS.register_module() +class JPU(BaseModule): + """FastFCN: Rethinking Dilated Convolution in the Backbone + for Semantic Segmentation. + + This Joint Pyramid Upsampling (JPU) neck is the implementation of + `FastFCN `_. + + Args: + in_channels (Tuple[int], optional): The number of input channels + for each convolution operations before upsampling. + Default: (512, 1024, 2048). + mid_channels (int): The number of output channels of JPU. + Default: 512. + start_level (int): Index of the start input backbone level used to + build the feature pyramid. Default: 0. + end_level (int): Index of the end input backbone level (exclusive) to + build the feature pyramid. Default: -1, which means the last level. + dilations (tuple[int]): Dilation rate of each Depthwise + Separable ConvModule. Default: (1, 2, 4, 8). + align_corners (bool, optional): The align_corners argument of + resize operation. Default: False. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels=(512, 1024, 2048), + mid_channels=512, + start_level=0, + end_level=-1, + dilations=(1, 2, 4, 8), + align_corners=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert isinstance(in_channels, tuple) + assert isinstance(dilations, tuple) + self.in_channels = in_channels + self.mid_channels = mid_channels + self.start_level = start_level + self.num_ins = len(in_channels) + if end_level == -1: + self.backbone_end_level = self.num_ins + else: + self.backbone_end_level = end_level + assert end_level <= len(in_channels) + + self.dilations = dilations + self.align_corners = align_corners + + self.conv_layers = nn.ModuleList() + self.dilation_layers = nn.ModuleList() + for i in range(self.start_level, self.backbone_end_level): + conv_layer = nn.Sequential( + ConvModule( + self.in_channels[i], + self.mid_channels, + kernel_size=3, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.conv_layers.append(conv_layer) + for i in range(len(dilations)): + dilation_layer = nn.Sequential( + DepthwiseSeparableConvModule( + in_channels=(self.backbone_end_level - self.start_level) * + self.mid_channels, + out_channels=self.mid_channels, + kernel_size=3, + stride=1, + padding=dilations[i], + dilation=dilations[i], + dw_norm_cfg=norm_cfg, + dw_act_cfg=None, + pw_norm_cfg=norm_cfg, + pw_act_cfg=act_cfg)) + self.dilation_layers.append(dilation_layer) + + def forward(self, inputs): + """Forward function.""" + assert len(inputs) == len(self.in_channels), 'Length of inputs must \ + be the same with self.in_channels!' + + feats = [ + self.conv_layers[i - self.start_level](inputs[i]) + for i in range(self.start_level, self.backbone_end_level) + ] + + h, w = feats[0].shape[2:] + for i in range(1, len(feats)): + feats[i] = resize( + feats[i], + size=(h, w), + mode='bilinear', + align_corners=self.align_corners) + + feat = torch.cat(feats, dim=1) + concat_feat = torch.cat([ + self.dilation_layers[i](feat) for i in range(len(self.dilations)) + ], + dim=1) + + outs = [] + + # Default: outs[2] is the output of JPU for decoder head, outs[1] is + # the feature map from backbone for auxiliary head. Additionally, + # outs[0] can also be used for auxiliary head. + for i in range(self.start_level, self.backbone_end_level - 1): + outs.append(inputs[i]) + outs.append(concat_feat) + return tuple(outs) diff --git a/third-party/InterFormer/mmseg/models/necks/mla_neck.py b/third-party/InterFormer/mmseg/models/necks/mla_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..db250aefbfa45beaa98855be79ddc7f5e7276cca --- /dev/null +++ b/third-party/InterFormer/mmseg/models/necks/mla_neck.py @@ -0,0 +1,118 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule, build_norm_layer + +from mmseg.registry import MODELS + + +class MLAModule(nn.Module): + + def __init__(self, + in_channels=[1024, 1024, 1024, 1024], + out_channels=256, + norm_cfg=None, + act_cfg=None): + super().__init__() + self.channel_proj = nn.ModuleList() + for i in range(len(in_channels)): + self.channel_proj.append( + ConvModule( + in_channels=in_channels[i], + out_channels=out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.feat_extract = nn.ModuleList() + for i in range(len(in_channels)): + self.feat_extract.append( + ConvModule( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + def forward(self, inputs): + + # feat_list -> [p2, p3, p4, p5] + feat_list = [] + for x, conv in zip(inputs, self.channel_proj): + feat_list.append(conv(x)) + + # feat_list -> [p5, p4, p3, p2] + # mid_list -> [m5, m4, m3, m2] + feat_list = feat_list[::-1] + mid_list = [] + for feat in feat_list: + if len(mid_list) == 0: + mid_list.append(feat) + else: + mid_list.append(mid_list[-1] + feat) + + # mid_list -> [m5, m4, m3, m2] + # out_list -> [o2, o3, o4, o5] + out_list = [] + for mid, conv in zip(mid_list, self.feat_extract): + out_list.append(conv(mid)) + + return tuple(out_list) + + +@MODELS.register_module() +class MLANeck(nn.Module): + """Multi-level Feature Aggregation. + + This neck is `The Multi-level Feature Aggregation construction of + SETR `_. + + + Args: + in_channels (List[int]): Number of input channels per scale. + out_channels (int): Number of output channels (used at each scale). + norm_layer (dict): Config dict for input normalization. + Default: norm_layer=dict(type='LN', eps=1e-6, requires_grad=True). + norm_cfg (dict): Config dict for normalization layer. Default: None. + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + norm_layer=dict(type='LN', eps=1e-6, requires_grad=True), + norm_cfg=None, + act_cfg=None): + super().__init__() + assert isinstance(in_channels, list) + self.in_channels = in_channels + self.out_channels = out_channels + + # In order to build general vision transformer backbone, we have to + # move MLA to neck. + self.norm = nn.ModuleList([ + build_norm_layer(norm_layer, in_channels[i])[1] + for i in range(len(in_channels)) + ]) + + self.mla = MLAModule( + in_channels=in_channels, + out_channels=out_channels, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, inputs): + assert len(inputs) == len(self.in_channels) + + # Convert from nchw to nlc + outs = [] + for i in range(len(inputs)): + x = inputs[i] + n, c, h, w = x.shape + x = x.reshape(n, c, h * w).transpose(2, 1).contiguous() + x = self.norm[i](x) + x = x.transpose(1, 2).reshape(n, c, h, w).contiguous() + outs.append(x) + + outs = self.mla(outs) + return tuple(outs) diff --git a/third-party/InterFormer/mmseg/models/necks/multilevel_neck.py b/third-party/InterFormer/mmseg/models/necks/multilevel_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..c997125f24791b1c01248c60a27fa37a986c6c82 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/necks/multilevel_neck.py @@ -0,0 +1,79 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model.weight_init import xavier_init + +from mmseg.registry import MODELS +from ..utils import resize + + +@MODELS.register_module() +class MultiLevelNeck(nn.Module): + """MultiLevelNeck. + + A neck structure connect vit backbone and decoder_heads. + + Args: + in_channels (List[int]): Number of input channels per scale. + out_channels (int): Number of output channels (used at each scale). + scales (List[float]): Scale factors for each input feature map. + Default: [0.5, 1, 2, 4] + norm_cfg (dict): Config dict for normalization layer. Default: None. + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + scales=[0.5, 1, 2, 4], + norm_cfg=None, + act_cfg=None): + super().__init__() + assert isinstance(in_channels, list) + self.in_channels = in_channels + self.out_channels = out_channels + self.scales = scales + self.num_outs = len(scales) + self.lateral_convs = nn.ModuleList() + self.convs = nn.ModuleList() + for in_channel in in_channels: + self.lateral_convs.append( + ConvModule( + in_channel, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + for _ in range(self.num_outs): + self.convs.append( + ConvModule( + out_channels, + out_channels, + kernel_size=3, + padding=1, + stride=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + # default init_weights for conv(msra) and norm in ConvModule + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + xavier_init(m, distribution='uniform') + + def forward(self, inputs): + assert len(inputs) == len(self.in_channels) + inputs = [ + lateral_conv(inputs[i]) + for i, lateral_conv in enumerate(self.lateral_convs) + ] + # for len(inputs) not equal to self.num_outs + if len(inputs) == 1: + inputs = [inputs[0] for _ in range(self.num_outs)] + outs = [] + for i in range(self.num_outs): + x_resize = resize( + inputs[i], scale_factor=self.scales[i], mode='bilinear') + outs.append(self.convs[i](x_resize)) + return tuple(outs) diff --git a/third-party/InterFormer/mmseg/models/segmentors/__init__.py b/third-party/InterFormer/mmseg/models/segmentors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59b012f41725d26d099b8f890630d1dc04019ba5 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/segmentors/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .base import BaseSegmentor +from .cascade_encoder_decoder import CascadeEncoderDecoder +from .depth_estimator import DepthEstimator +from .encoder_decoder import EncoderDecoder +from .multimodal_encoder_decoder import MultimodalEncoderDecoder +from .seg_tta import SegTTAModel + +__all__ = [ + 'BaseSegmentor', 'EncoderDecoder', 'CascadeEncoderDecoder', 'SegTTAModel', + 'MultimodalEncoderDecoder', 'DepthEstimator' +] diff --git a/third-party/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be9b139301597c27ae4b445eaa42165bcca8bee1 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-38.pyc b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40d1eea4451079037481043d6d6cab931ec54bcc Binary files /dev/null and b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-38.pyc b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed6a18bc9a4ea83c927f42f670b3136150ae8f51 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-38.pyc b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4237a96807892538f8fe4ac9bd61c8009e78c67 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-38.pyc b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..756aa4bde3201ce29986519ee17412337a9f2de7 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-38.pyc b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b087ddf5bd4df9b38aaf3ecb1d088a2f4c411d8 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-38.pyc b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7852561d351729941b62078d90a2fae7af7f0bb8 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/segmentors/base.py b/third-party/InterFormer/mmseg/models/segmentors/base.py new file mode 100644 index 0000000000000000000000000000000000000000..17a0bb2b33e57684bccaaf892af69bcba69dd773 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/segmentors/base.py @@ -0,0 +1,200 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from abc import ABCMeta, abstractmethod +from typing import List, Tuple + +from mmengine.model import BaseModel +from mmengine.structures import PixelData +from torch import Tensor + +from mmseg.structures import SegDataSample +from mmseg.utils import (ForwardResults, OptConfigType, OptMultiConfig, + OptSampleList, SampleList) +from ..utils import resize + + +class BaseSegmentor(BaseModel, metaclass=ABCMeta): + """Base class for segmentors. + + Args: + data_preprocessor (dict, optional): Model preprocessing config + for processing the input data. it usually includes + ``to_rgb``, ``pad_size_divisor``, ``pad_val``, + ``mean`` and ``std``. Default to None. + init_cfg (dict, optional): the config to control the + initialization. Default to None. + """ + + def __init__(self, + data_preprocessor: OptConfigType = None, + init_cfg: OptMultiConfig = None): + super().__init__( + data_preprocessor=data_preprocessor, init_cfg=init_cfg) + + @property + def with_neck(self) -> bool: + """bool: whether the segmentor has neck""" + return hasattr(self, 'neck') and self.neck is not None + + @property + def with_auxiliary_head(self) -> bool: + """bool: whether the segmentor has auxiliary head""" + return hasattr(self, + 'auxiliary_head') and self.auxiliary_head is not None + + @property + def with_decode_head(self) -> bool: + """bool: whether the segmentor has decode head""" + return hasattr(self, 'decode_head') and self.decode_head is not None + + @abstractmethod + def extract_feat(self, inputs: Tensor) -> bool: + """Placeholder for extract features from images.""" + pass + + @abstractmethod + def encode_decode(self, inputs: Tensor, batch_data_samples: SampleList): + """Placeholder for encode images with backbone and decode into a + semantic segmentation map of the same size as input.""" + pass + + def forward(self, + inputs: Tensor, + data_samples: OptSampleList = None, + mode: str = 'tensor') -> ForwardResults: + """The unified entry for a forward process in both training and test. + + The method should accept three modes: "tensor", "predict" and "loss": + + - "tensor": Forward the whole network and return tensor or tuple of + tensor without any post-processing, same as a common nn.Module. + - "predict": Forward and return the predictions, which are fully + processed to a list of :obj:`SegDataSample`. + - "loss": Forward and return a dict of losses according to the given + inputs and data samples. + + Note that this method doesn't handle neither back propagation nor + optimizer updating, which are done in the :meth:`train_step`. + + Args: + inputs (torch.Tensor): The input tensor with shape (N, C, ...) in + general. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_sem_seg`. Default to None. + mode (str): Return what kind of value. Defaults to 'tensor'. + + Returns: + The return type depends on ``mode``. + + - If ``mode="tensor"``, return a tensor or a tuple of tensor. + - If ``mode="predict"``, return a list of :obj:`DetDataSample`. + - If ``mode="loss"``, return a dict of tensor. + """ + if mode == 'loss': + return self.loss(inputs, data_samples) + elif mode == 'predict': + return self.predict(inputs, data_samples) + elif mode == 'tensor': + return self._forward(inputs, data_samples) + else: + raise RuntimeError(f'Invalid mode "{mode}". ' + 'Only supports loss, predict and tensor mode') + + @abstractmethod + def loss(self, inputs: Tensor, data_samples: SampleList) -> dict: + """Calculate losses from a batch of inputs and data samples.""" + pass + + @abstractmethod + def predict(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """Predict results from a batch of inputs and data samples with post- + processing.""" + pass + + @abstractmethod + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tuple[List[Tensor]]: + """Network forward process. + + Usually includes backbone, neck and head forward without any post- + processing. + """ + pass + + def postprocess_result(self, + seg_logits: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """ Convert results list to `SegDataSample`. + Args: + seg_logits (Tensor): The segmentation results, seg_logits from + model of each input image. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_sem_seg`. Default to None. + Returns: + list[:obj:`SegDataSample`]: Segmentation results of the + input images. Each SegDataSample usually contain: + + - ``pred_sem_seg``(PixelData): Prediction of semantic segmentation. + - ``seg_logits``(PixelData): Predicted logits of semantic + segmentation before normalization. + """ + batch_size, C, H, W = seg_logits.shape + + if data_samples is None: + data_samples = [SegDataSample() for _ in range(batch_size)] + only_prediction = True + else: + only_prediction = False + + for i in range(batch_size): + if not only_prediction: + img_meta = data_samples[i].metainfo + # remove padding area + if 'img_padding_size' not in img_meta: + padding_size = img_meta.get('padding_size', [0] * 4) + else: + padding_size = img_meta['img_padding_size'] + padding_left, padding_right, padding_top, padding_bottom =\ + padding_size + # i_seg_logits shape is 1, C, H, W after remove padding + i_seg_logits = seg_logits[i:i + 1, :, + padding_top:H - padding_bottom, + padding_left:W - padding_right] + + flip = img_meta.get('flip', None) + if flip: + flip_direction = img_meta.get('flip_direction', None) + assert flip_direction in ['horizontal', 'vertical'] + if flip_direction == 'horizontal': + i_seg_logits = i_seg_logits.flip(dims=(3, )) + else: + i_seg_logits = i_seg_logits.flip(dims=(2, )) + + # resize as original shape + i_seg_logits = resize( + i_seg_logits, + size=img_meta['ori_shape'], + mode='bilinear', + align_corners=self.align_corners, + warning=False).squeeze(0) + else: + i_seg_logits = seg_logits[i] + + if C > 1: + i_seg_pred = i_seg_logits.argmax(dim=0, keepdim=True) + else: + i_seg_logits = i_seg_logits.sigmoid() + i_seg_pred = (i_seg_logits > + self.decode_head.threshold).to(i_seg_logits) + data_samples[i].set_data({ + 'seg_logits': + PixelData(**{'data': i_seg_logits}), + 'pred_sem_seg': + PixelData(**{'data': i_seg_pred}) + }) + + return data_samples diff --git a/third-party/InterFormer/mmseg/models/segmentors/cascade_encoder_decoder.py b/third-party/InterFormer/mmseg/models/segmentors/cascade_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..0184a3533a18cbe96a28bbb645c3e73bbffcdeee --- /dev/null +++ b/third-party/InterFormer/mmseg/models/segmentors/cascade_encoder_decoder.py @@ -0,0 +1,138 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional + +from torch import Tensor, nn + +from mmseg.registry import MODELS +from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, + OptSampleList, SampleList, add_prefix) +from .encoder_decoder import EncoderDecoder + + +@MODELS.register_module() +class CascadeEncoderDecoder(EncoderDecoder): + """Cascade Encoder Decoder segmentors. + + CascadeEncoderDecoder almost the same as EncoderDecoder, while decoders of + CascadeEncoderDecoder are cascaded. The output of previous decoder_head + will be the input of next decoder_head. + + Args: + + num_stages (int): How many stages will be cascaded. + backbone (ConfigType): The config for the backnone of segmentor. + decode_head (ConfigType): The config for the decode head of segmentor. + neck (OptConfigType): The config for the neck of segmentor. + Defaults to None. + auxiliary_head (OptConfigType): The config for the auxiliary head of + segmentor. Defaults to None. + train_cfg (OptConfigType): The config for training. Defaults to None. + test_cfg (OptConfigType): The config for testing. Defaults to None. + data_preprocessor (dict, optional): The pre-process config of + :class:`BaseDataPreprocessor`. + pretrained (str, optional): The path for pretrained model. + Defaults to None. + init_cfg (dict, optional): The weight initialized config for + :class:`BaseModule`. + """ + + def __init__(self, + num_stages: int, + backbone: ConfigType, + decode_head: ConfigType, + neck: OptConfigType = None, + auxiliary_head: OptConfigType = None, + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + data_preprocessor: OptConfigType = None, + pretrained: Optional[str] = None, + init_cfg: OptMultiConfig = None): + self.num_stages = num_stages + super().__init__( + backbone=backbone, + decode_head=decode_head, + neck=neck, + auxiliary_head=auxiliary_head, + train_cfg=train_cfg, + test_cfg=test_cfg, + data_preprocessor=data_preprocessor, + pretrained=pretrained, + init_cfg=init_cfg) + + def _init_decode_head(self, decode_head: ConfigType) -> None: + """Initialize ``decode_head``""" + assert isinstance(decode_head, list) + assert len(decode_head) == self.num_stages + self.decode_head = nn.ModuleList() + for i in range(self.num_stages): + self.decode_head.append(MODELS.build(decode_head[i])) + self.align_corners = self.decode_head[-1].align_corners + self.num_classes = self.decode_head[-1].num_classes + self.out_channels = self.decode_head[-1].out_channels + + def encode_decode(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Encode images with backbone and decode into a semantic segmentation + map of the same size as input.""" + x = self.extract_feat(inputs) + out = self.decode_head[0].forward(x) + for i in range(1, self.num_stages - 1): + out = self.decode_head[i].forward(x, out) + seg_logits_list = self.decode_head[-1].predict(x, out, batch_img_metas, + self.test_cfg) + + return seg_logits_list + + def _decode_head_forward_train(self, inputs: Tensor, + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for decode head in + training.""" + losses = dict() + + loss_decode = self.decode_head[0].loss(inputs, data_samples, + self.train_cfg) + + losses.update(add_prefix(loss_decode, 'decode_0')) + # get batch_img_metas + batch_size = len(data_samples) + batch_img_metas = [] + for batch_index in range(batch_size): + metainfo = data_samples[batch_index].metainfo + batch_img_metas.append(metainfo) + + for i in range(1, self.num_stages): + # forward test again, maybe unnecessary for most methods. + if i == 1: + prev_outputs = self.decode_head[0].forward(inputs) + else: + prev_outputs = self.decode_head[i - 1].forward( + inputs, prev_outputs) + loss_decode = self.decode_head[i].loss(inputs, prev_outputs, + data_samples, + self.train_cfg) + losses.update(add_prefix(loss_decode, f'decode_{i}')) + + return losses + + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tensor: + """Network forward process. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_semantic_seg`. + + Returns: + Tensor: Forward output of model without any post-processes. + """ + x = self.extract_feat(inputs) + + out = self.decode_head[0].forward(x) + for i in range(1, self.num_stages): + # TODO support PointRend tensor mode + out = self.decode_head[i].forward(x, out) + + return out diff --git a/third-party/InterFormer/mmseg/models/segmentors/depth_estimator.py b/third-party/InterFormer/mmseg/models/segmentors/depth_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..1020637e737a3c72ba6a48f2d1228717470ba862 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/segmentors/depth_estimator.py @@ -0,0 +1,392 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import logging +from typing import List, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.logging import print_log +from mmengine.structures import PixelData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample +from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, + OptSampleList, SampleList, add_prefix) +from ..utils import resize +from .encoder_decoder import EncoderDecoder + + +@MODELS.register_module() +class DepthEstimator(EncoderDecoder): + """Encoder Decoder depth estimator. + + EncoderDecoder typically consists of backbone, decode_head, auxiliary_head. + Note that auxiliary_head is only used for deep supervision during training, + which could be dumped during inference. + + 1. The ``loss`` method is used to calculate the loss of model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2) Call the decode head loss function to forward decode head model and + calculate losses. + + .. code:: text + + loss(): extract_feat() -> _decode_head_forward_train() -> _auxiliary_head_forward_train (optional) + _decode_head_forward_train(): decode_head.loss() + _auxiliary_head_forward_train(): auxiliary_head.loss (optional) + + 2. The ``predict`` method is used to predict depth estimation results, + which includes two steps: (1) Run inference function to obtain the list of + depth (2) Call post-processing function to obtain list of + ``SegDataSample`` including ``pred_depth_map``. + + .. code:: text + + predict(): inference() -> postprocess_result() + inference(): whole_inference()/slide_inference() + whole_inference()/slide_inference(): encoder_decoder() + encoder_decoder(): extract_feat() -> decode_head.predict() + + 3. The ``_forward`` method is used to output the tensor by running the model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2)Call the decode head forward function to forward decode head model. + + .. code:: text + + _forward(): extract_feat() -> _decode_head.forward() + + Args: + + backbone (ConfigType): The config for the backnone of depth estimator. + decode_head (ConfigType): The config for the decode head of depth estimator. + neck (OptConfigType): The config for the neck of depth estimator. + Defaults to None. + auxiliary_head (OptConfigType): The config for the auxiliary head of + depth estimator. Defaults to None. + train_cfg (OptConfigType): The config for training. Defaults to None. + test_cfg (OptConfigType): The config for testing. Defaults to None. + data_preprocessor (dict, optional): The pre-process config of + :class:`BaseDataPreprocessor`. + pretrained (str, optional): The path for pretrained model. + Defaults to None. + init_cfg (dict, optional): The weight initialized config for + :class:`BaseModule`. + """ # noqa: E501 + + def __init__(self, + backbone: ConfigType, + decode_head: ConfigType, + neck: OptConfigType = None, + auxiliary_head: OptConfigType = None, + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + data_preprocessor: OptConfigType = None, + pretrained: Optional[str] = None, + init_cfg: OptMultiConfig = None): + super().__init__( + backbone=backbone, + decode_head=decode_head, + neck=neck, + auxiliary_head=auxiliary_head, + train_cfg=train_cfg, + test_cfg=test_cfg, + data_preprocessor=data_preprocessor, + pretrained=pretrained, + init_cfg=init_cfg) + + def extract_feat(self, + inputs: Tensor, + batch_img_metas: Optional[List[dict]] = None) -> Tensor: + """Extract features from images.""" + + if getattr(self.backbone, 'class_embed_select', False) and \ + isinstance(batch_img_metas, list) and \ + 'category_id' in batch_img_metas[0]: + cat_ids = [meta['category_id'] for meta in batch_img_metas] + cat_ids = torch.tensor(cat_ids).to(inputs.device) + inputs = (inputs, cat_ids) + + x = self.backbone(inputs) + if self.with_neck: + x = self.neck(x) + return x + + def encode_decode(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Encode images with backbone and decode into a depth map of the same + size as input.""" + x = self.extract_feat(inputs, batch_img_metas) + depth = self.decode_head.predict(x, batch_img_metas, self.test_cfg) + + return depth + + def _decode_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for decode head in + training.""" + losses = dict() + loss_decode = self.decode_head.loss(inputs, data_samples, + self.train_cfg) + + losses.update(add_prefix(loss_decode, 'decode')) + return losses + + def _auxiliary_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for auxiliary head in + training.""" + losses = dict() + if isinstance(self.auxiliary_head, nn.ModuleList): + for idx, aux_head in enumerate(self.auxiliary_head): + loss_aux = aux_head.loss(inputs, data_samples, self.train_cfg) + losses.update(add_prefix(loss_aux, f'aux_{idx}')) + else: + loss_aux = self.auxiliary_head.loss(inputs, data_samples, + self.train_cfg) + losses.update(add_prefix(loss_aux, 'aux')) + + return losses + + def loss(self, inputs: Tensor, data_samples: SampleList) -> dict: + """Calculate losses from a batch of inputs and data samples. + + Args: + inputs (Tensor): Input images. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_depth_map`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + if data_samples is not None: + batch_img_metas = [ + data_sample.metainfo for data_sample in data_samples + ] + else: + batch_img_metas = [ + dict( + ori_shape=inputs.shape[2:], + img_shape=inputs.shape[2:], + pad_shape=inputs.shape[2:], + padding_size=[0, 0, 0, 0]) + ] * inputs.shape[0] + + x = self.extract_feat(inputs, batch_img_metas) + + losses = dict() + + loss_decode = self._decode_head_forward_train(x, data_samples) + losses.update(loss_decode) + + if self.with_auxiliary_head: + loss_aux = self._auxiliary_head_forward_train(x, data_samples) + losses.update(loss_aux) + + return losses + + def predict(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """Predict results from a batch of inputs and data samples with post- + processing. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`], optional): The seg data + samples. It usually includes information such as `metainfo` + and `gt_depth_map`. + + Returns: + list[:obj:`SegDataSample`]: Depth estimation results of the + input images. Each SegDataSample usually contain: + + - ``pred_depth_max``(PixelData): Prediction of depth estimation. + """ + if data_samples is not None: + batch_img_metas = [ + data_sample.metainfo for data_sample in data_samples + ] + else: + batch_img_metas = [ + dict( + ori_shape=inputs.shape[2:], + img_shape=inputs.shape[2:], + pad_shape=inputs.shape[2:], + padding_size=[0, 0, 0, 0]) + ] * inputs.shape[0] + + depth = self.inference(inputs, batch_img_metas) + + return self.postprocess_result(depth, data_samples) + + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tensor: + """Network forward process. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_depth_map`. + + Returns: + Tensor: Forward output of model without any post-processes. + """ + x = self.extract_feat(inputs) + return self.decode_head.forward(x) + + def slide_flip_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference by sliding-window with overlap and flip. + + If h_crop > h_img or w_crop > w_img, the small patch will be used to + decode without padding. + + Args: + inputs (tensor): the tensor should have a shape NxCxHxW, + which contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The depth estimation results. + """ + + h_stride, w_stride = self.test_cfg.stride + h_crop, w_crop = self.test_cfg.crop_size + batch_size, _, h_img, w_img = inputs.size() + out_channels = self.out_channels + h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1 + w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1 + preds = inputs.new_zeros((batch_size, out_channels, h_img, w_img)) + count_mat = inputs.new_zeros((batch_size, 1, h_img, w_img)) + for h_idx in range(h_grids): + for w_idx in range(w_grids): + y1 = h_idx * h_stride + x1 = w_idx * w_stride + y2 = min(y1 + h_crop, h_img) + x2 = min(x1 + w_crop, w_img) + y1 = max(y2 - h_crop, 0) + x1 = max(x2 - w_crop, 0) + crop_img = inputs[:, :, y1:y2, x1:x2] + # change the image shape to patch shape + batch_img_metas[0]['img_shape'] = crop_img.shape[2:] + # the output of encode_decode is depth tensor map + # with shape [N, C, H, W] + crop_depth_map = self.encode_decode(crop_img, batch_img_metas) + + # average out the original and flipped prediction + crop_depth_map_flip = self.encode_decode( + crop_img.flip(dims=(3, )), batch_img_metas) + crop_depth_map_flip = crop_depth_map_flip.flip(dims=(3, )) + crop_depth_map = (crop_depth_map + crop_depth_map_flip) / 2.0 + + preds += F.pad(crop_depth_map, + (int(x1), int(preds.shape[3] - x2), int(y1), + int(preds.shape[2] - y2))) + + count_mat[:, :, y1:y2, x1:x2] += 1 + assert (count_mat == 0).sum() == 0 + depth = preds / count_mat + + return depth + + def inference(self, inputs: Tensor, batch_img_metas: List[dict]) -> Tensor: + """Inference with slide/whole style. + + Args: + inputs (Tensor): The input image of shape (N, 3, H, W). + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', 'pad_shape', and 'padding_size'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The depth estimation results. + """ + assert self.test_cfg.get('mode', 'whole') in ['slide', 'whole', + 'slide_flip'], \ + f'Only "slide", "slide_flip" or "whole" test mode are ' \ + f'supported, but got {self.test_cfg["mode"]}.' + ori_shape = batch_img_metas[0]['ori_shape'] + if not all(_['ori_shape'] == ori_shape for _ in batch_img_metas): + print_log( + 'Image shapes are different in the batch.', + logger='current', + level=logging.WARN) + if self.test_cfg.mode == 'slide': + depth_map = self.slide_inference(inputs, batch_img_metas) + if self.test_cfg.mode == 'slide_flip': + depth_map = self.slide_flip_inference(inputs, batch_img_metas) + else: + depth_map = self.whole_inference(inputs, batch_img_metas) + + return depth_map + + def postprocess_result(self, + depth: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """ Convert results list to `SegDataSample`. + Args: + depth (Tensor): The depth estimation results. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_depth_map`. Default to None. + Returns: + list[:obj:`SegDataSample`]: Depth estomation results of the + input images. Each SegDataSample usually contain: + + - ``pred_depth_map``(PixelData): Prediction of depth estimation. + """ + batch_size, C, H, W = depth.shape + + if data_samples is None: + data_samples = [SegDataSample() for _ in range(batch_size)] + only_prediction = True + else: + only_prediction = False + + for i in range(batch_size): + if not only_prediction: + img_meta = data_samples[i].metainfo + # remove padding area + if 'img_padding_size' not in img_meta: + padding_size = img_meta.get('padding_size', [0] * 4) + else: + padding_size = img_meta['img_padding_size'] + padding_left, padding_right, padding_top, padding_bottom =\ + padding_size + # i_depth shape is 1, C, H, W after remove padding + i_depth = depth[i:i + 1, :, padding_top:H - padding_bottom, + padding_left:W - padding_right] + + flip = img_meta.get('flip', None) + if flip: + flip_direction = img_meta.get('flip_direction', None) + assert flip_direction in ['horizontal', 'vertical'] + if flip_direction == 'horizontal': + i_depth = i_depth.flip(dims=(3, )) + else: + i_depth = i_depth.flip(dims=(2, )) + + # resize as original shape + i_depth = resize( + i_depth, + size=img_meta['ori_shape'], + mode='bilinear', + align_corners=self.align_corners, + warning=False).squeeze(0) + else: + i_depth = depth[i] + + data_samples[i].set_data( + {'pred_depth_map': PixelData(**{'data': i_depth})}) + + return data_samples diff --git a/third-party/InterFormer/mmseg/models/segmentors/encoder_decoder.py b/third-party/InterFormer/mmseg/models/segmentors/encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4050e0b736f98c17629a93e2f70be1d7e84fbb --- /dev/null +++ b/third-party/InterFormer/mmseg/models/segmentors/encoder_decoder.py @@ -0,0 +1,364 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import logging +from typing import List, Optional + +import torch.nn as nn +import torch.nn.functional as F +from mmengine.logging import print_log +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, + OptSampleList, SampleList, add_prefix) +from .base import BaseSegmentor + + +@MODELS.register_module() +class EncoderDecoder(BaseSegmentor): + """Encoder Decoder segmentors. + + EncoderDecoder typically consists of backbone, decode_head, auxiliary_head. + Note that auxiliary_head is only used for deep supervision during training, + which could be dumped during inference. + + 1. The ``loss`` method is used to calculate the loss of model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2) Call the decode head loss function to forward decode head model and + calculate losses. + + .. code:: text + + loss(): extract_feat() -> _decode_head_forward_train() -> _auxiliary_head_forward_train (optional) + _decode_head_forward_train(): decode_head.loss() + _auxiliary_head_forward_train(): auxiliary_head.loss (optional) + + 2. The ``predict`` method is used to predict segmentation results, + which includes two steps: (1) Run inference function to obtain the list of + seg_logits (2) Call post-processing function to obtain list of + ``SegDataSample`` including ``pred_sem_seg`` and ``seg_logits``. + + .. code:: text + + predict(): inference() -> postprocess_result() + infercen(): whole_inference()/slide_inference() + whole_inference()/slide_inference(): encoder_decoder() + encoder_decoder(): extract_feat() -> decode_head.predict() + + 3. The ``_forward`` method is used to output the tensor by running the model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2)Call the decode head forward function to forward decode head model. + + .. code:: text + + _forward(): extract_feat() -> _decode_head.forward() + + Args: + + backbone (ConfigType): The config for the backnone of segmentor. + decode_head (ConfigType): The config for the decode head of segmentor. + neck (OptConfigType): The config for the neck of segmentor. + Defaults to None. + auxiliary_head (OptConfigType): The config for the auxiliary head of + segmentor. Defaults to None. + train_cfg (OptConfigType): The config for training. Defaults to None. + test_cfg (OptConfigType): The config for testing. Defaults to None. + data_preprocessor (dict, optional): The pre-process config of + :class:`BaseDataPreprocessor`. + pretrained (str, optional): The path for pretrained model. + Defaults to None. + init_cfg (dict, optional): The weight initialized config for + :class:`BaseModule`. + """ # noqa: E501 + + def __init__(self, + backbone: ConfigType, + decode_head: ConfigType, + neck: OptConfigType = None, + auxiliary_head: OptConfigType = None, + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + data_preprocessor: OptConfigType = None, + pretrained: Optional[str] = None, + init_cfg: OptMultiConfig = None): + super().__init__( + data_preprocessor=data_preprocessor, init_cfg=init_cfg) + if pretrained is not None: + assert backbone.get('pretrained') is None, \ + 'both backbone and segmentor set pretrained weight' + backbone.pretrained = pretrained + self.backbone = MODELS.build(backbone) + if neck is not None: + self.neck = MODELS.build(neck) + self._init_decode_head(decode_head) + self._init_auxiliary_head(auxiliary_head) + + self.train_cfg = train_cfg + self.test_cfg = test_cfg + + assert self.with_decode_head + + def _init_decode_head(self, decode_head: ConfigType) -> None: + """Initialize ``decode_head``""" + self.decode_head = MODELS.build(decode_head) + self.align_corners = self.decode_head.align_corners + self.num_classes = self.decode_head.num_classes + self.out_channels = self.decode_head.out_channels + + def _init_auxiliary_head(self, auxiliary_head: ConfigType) -> None: + """Initialize ``auxiliary_head``""" + if auxiliary_head is not None: + if isinstance(auxiliary_head, list): + self.auxiliary_head = nn.ModuleList() + for head_cfg in auxiliary_head: + self.auxiliary_head.append(MODELS.build(head_cfg)) + else: + self.auxiliary_head = MODELS.build(auxiliary_head) + + def extract_feat(self, inputs: Tensor) -> List[Tensor]: + """Extract features from images.""" + x = self.backbone(inputs) + if self.with_neck: + x = self.neck(x) + return x + + def encode_decode(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Encode images with backbone and decode into a semantic segmentation + map of the same size as input.""" + x = self.extract_feat(inputs) + seg_logits = self.decode_head.predict(x, batch_img_metas, + self.test_cfg) + + return seg_logits + + def _decode_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for decode head in + training.""" + losses = dict() + loss_decode = self.decode_head.loss(inputs, data_samples, + self.train_cfg) + + losses.update(add_prefix(loss_decode, 'decode')) + return losses + + def _auxiliary_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for auxiliary head in + training.""" + losses = dict() + if isinstance(self.auxiliary_head, nn.ModuleList): + for idx, aux_head in enumerate(self.auxiliary_head): + loss_aux = aux_head.loss(inputs, data_samples, self.train_cfg) + losses.update(add_prefix(loss_aux, f'aux_{idx}')) + else: + loss_aux = self.auxiliary_head.loss(inputs, data_samples, + self.train_cfg) + losses.update(add_prefix(loss_aux, 'aux')) + + return losses + + def loss(self, inputs: Tensor, data_samples: SampleList) -> dict: + """Calculate losses from a batch of inputs and data samples. + + Args: + inputs (Tensor): Input images. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_sem_seg`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + + x = self.extract_feat(inputs) + + losses = dict() + + loss_decode = self._decode_head_forward_train(x, data_samples) + losses.update(loss_decode) + + if self.with_auxiliary_head: + loss_aux = self._auxiliary_head_forward_train(x, data_samples) + losses.update(loss_aux) + + return losses + + def predict(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """Predict results from a batch of inputs and data samples with post- + processing. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`], optional): The seg data + samples. It usually includes information such as `metainfo` + and `gt_sem_seg`. + + Returns: + list[:obj:`SegDataSample`]: Segmentation results of the + input images. Each SegDataSample usually contain: + + - ``pred_sem_seg``(PixelData): Prediction of semantic segmentation. + - ``seg_logits``(PixelData): Predicted logits of semantic + segmentation before normalization. + """ + if data_samples is not None: + batch_img_metas = [ + data_sample.metainfo for data_sample in data_samples + ] + else: + batch_img_metas = [ + dict( + ori_shape=inputs.shape[2:], + img_shape=inputs.shape[2:], + pad_shape=inputs.shape[2:], + padding_size=[0, 0, 0, 0]) + ] * inputs.shape[0] + + seg_logits = self.inference(inputs, batch_img_metas) + + return self.postprocess_result(seg_logits, data_samples) + + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tensor: + """Network forward process. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_sem_seg`. + + Returns: + Tensor: Forward output of model without any post-processes. + """ + x = self.extract_feat(inputs) + return self.decode_head.forward(x) + + def slide_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference by sliding-window with overlap. + + If h_crop > h_img or w_crop > w_img, the small patch will be used to + decode without padding. + + Args: + inputs (tensor): the tensor should have a shape NxCxHxW, + which contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + h_stride, w_stride = self.test_cfg.stride + h_crop, w_crop = self.test_cfg.crop_size + batch_size, _, h_img, w_img = inputs.size() + out_channels = self.out_channels + h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1 + w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1 + preds = inputs.new_zeros((batch_size, out_channels, h_img, w_img)) + count_mat = inputs.new_zeros((batch_size, 1, h_img, w_img)) + for h_idx in range(h_grids): + for w_idx in range(w_grids): + y1 = h_idx * h_stride + x1 = w_idx * w_stride + y2 = min(y1 + h_crop, h_img) + x2 = min(x1 + w_crop, w_img) + y1 = max(y2 - h_crop, 0) + x1 = max(x2 - w_crop, 0) + crop_img = inputs[:, :, y1:y2, x1:x2] + # change the image shape to patch shape + batch_img_metas[0]['img_shape'] = crop_img.shape[2:] + # the output of encode_decode is seg logits tensor map + # with shape [N, C, H, W] + crop_seg_logit = self.encode_decode(crop_img, batch_img_metas) + preds += F.pad(crop_seg_logit, + (int(x1), int(preds.shape[3] - x2), int(y1), + int(preds.shape[2] - y2))) + + count_mat[:, :, y1:y2, x1:x2] += 1 + assert (count_mat == 0).sum() == 0 + seg_logits = preds / count_mat + + return seg_logits + + def whole_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference with full image. + + Args: + inputs (Tensor): The tensor should have a shape NxCxHxW, which + contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + seg_logits = self.encode_decode(inputs, batch_img_metas) + + return seg_logits + + def inference(self, inputs: Tensor, batch_img_metas: List[dict]) -> Tensor: + """Inference with slide/whole style. + + Args: + inputs (Tensor): The input image of shape (N, 3, H, W). + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', 'pad_shape', and 'padding_size'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + assert self.test_cfg.get('mode', 'whole') in ['slide', 'whole'], \ + f'Only "slide" or "whole" test mode are supported, but got ' \ + f'{self.test_cfg["mode"]}.' + ori_shape = batch_img_metas[0]['ori_shape'] + if not all(_['ori_shape'] == ori_shape for _ in batch_img_metas): + print_log( + 'Image shapes are different in the batch.', + logger='current', + level=logging.WARN) + if self.test_cfg.mode == 'slide': + seg_logit = self.slide_inference(inputs, batch_img_metas) + else: + seg_logit = self.whole_inference(inputs, batch_img_metas) + + return seg_logit + + def aug_test(self, inputs, batch_img_metas, rescale=True): + """Test with augmentations. + + Only rescale=True is supported. + """ + # aug_test rescale all imgs back to ori_shape for now + assert rescale + # to save memory, we get augmented seg logit inplace + seg_logit = self.inference(inputs[0], batch_img_metas[0], rescale) + for i in range(1, len(inputs)): + cur_seg_logit = self.inference(inputs[i], batch_img_metas[i], + rescale) + seg_logit += cur_seg_logit + seg_logit /= len(inputs) + seg_pred = seg_logit.argmax(dim=1) + # unravel batch dim + seg_pred = list(seg_pred) + return seg_pred diff --git a/third-party/InterFormer/mmseg/models/segmentors/multimodal_encoder_decoder.py b/third-party/InterFormer/mmseg/models/segmentors/multimodal_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..75aa8b9b17688cb5f54da08f9300af82b3339967 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/segmentors/multimodal_encoder_decoder.py @@ -0,0 +1,350 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional + +import torch.nn.functional as F +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, + OptSampleList, SampleList, add_prefix) +from .base import BaseSegmentor + + +@MODELS.register_module() +class MultimodalEncoderDecoder(BaseSegmentor): + """Multimodal Encoder-Decoder segmentors. + + Multimodal segmentation architecture is used for open-vocabulary + semantic segmentation with combining the visual and language + pretrain models. It consists of a image_encoder (backbone) to extract + visual feature, a text encoder to extract text feature, and a decode + head to generate semantic maps. + Note that the deep supervision during training is implemented in decode head. + + 1. The ``loss`` method is used to calculate the loss of model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2) Call the decode head loss function to forward decode head model and + calculate losses. + + .. code:: text + + loss(): extract_feat() -> _decode_head_forward_train() + _decode_head_forward_train(): decode_head.loss() + + 2. The ``predict`` method is used to predict segmentation results, + which includes two steps: (1) Run inference function to obtain the list of + seg_logits (2) Call post-processing function to obtain list of + ``SegDataSampel`` including ``pred_sem_seg`` and ``seg_logits``. + + .. code:: text + + predict(): inference() -> postprocess_result() + inference(): whole_inference()/slide_inference() + whole_inference()/slide_inference(): encoder_decoder() + encoder_decoder(): extract_feat() -> decode_head.predict() + + 3. The ``_forward`` method is used to output the tensor by running the model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2)Call the decode head forward function to forward decode head model. + + .. code:: text + + _forward(): extract_feat() -> _decode_head.forward() + + Args: + + image_encoder (ConfigType): The config for the visual encoder of segmentor. + text_encoder ((ConfigType): The config for the text encoder of segmentor. + decode_head (ConfigType): The config for the decode head of segmentor. + train_cfg (OptConfigType): The config for training. Defaults to None. + test_cfg (OptConfigType): The config for testing. Defaults to None. + data_preprocessor (dict, optional): The pre-process config of + :class:`BaseDataPreprocessor`. + pretrained (str, optional): The path for pretrained model. + Defaults to None. + asymetric_input (bool): whether to use different size of input for image encoder + and decode head. Defaults to False. + encoder_resolution (float): resize scale of input images for image encoder. + Defaults to None. + init_cfg (dict, optional): The weight initialized config for + :class:`BaseModule`. + """ # noqa: E501 + + def __init__(self, + image_encoder: ConfigType, + text_encoder: ConfigType, + decode_head: ConfigType, + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + data_preprocessor: OptConfigType = None, + pretrained: Optional[str] = None, + asymetric_input: bool = True, + encoder_resolution: float = None, + init_cfg: OptMultiConfig = None): + super().__init__( + data_preprocessor=data_preprocessor, init_cfg=init_cfg) + if pretrained is not None: + image_encoder.init_cfg = dict( + type='Pretrained_Part', checkpoint=pretrained) + text_encoder.init_cfg = dict( + type='Pretrained_Part', checkpoint=pretrained) + decode_head.init_cfg = dict( + type='Pretrained_Part', checkpoint=pretrained) + + if asymetric_input: + assert encoder_resolution is not None, \ + 'if asymetric_input set True, ' \ + 'clip_resolution must be a certain value' + self.asymetric_input = asymetric_input + self.encoder_resolution = encoder_resolution + self.image_encoder = MODELS.build(image_encoder) + self.text_encoder = MODELS.build(text_encoder) + self._init_decode_head(decode_head) + + self.train_cfg = train_cfg + self.test_cfg = test_cfg + + assert self.with_decode_head + + def _init_decode_head(self, decode_head: ConfigType) -> None: + """Initialize ``decode_head``""" + self.decode_head = MODELS.build(decode_head) + self.align_corners = self.decode_head.align_corners + self.num_classes = self.decode_head.num_classes + self.out_channels = self.decode_head.out_channels + + def extract_feat(self, inputs: Tensor) -> List[Tensor]: + """Extract visual features from images.""" + x = self.image_encoder(inputs) + return x + + def encode_decode(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Encode the name of classes with text_encoder and encode images with + image_encoder. + + Then decode the class embedding and visual feature into a semantic + segmentation map of the same size as input. + """ + classifier_embeds = self.text_encoder() + clip_inputs = inputs + if self.asymetric_input: + clip_inputs = F.interpolate( + inputs, scale_factor=self.encoder_resolution, mode='bilinear') + x = self.image_encoder(clip_inputs) + seg_logits = self.decode_head.predict([inputs, x, classifier_embeds], + batch_img_metas, self.test_cfg) + + return seg_logits + + def _decode_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for decode head in + training.""" + losses = dict() + loss_decode = self.decode_head.loss(inputs, data_samples, + self.train_cfg) + + losses.update(add_prefix(loss_decode, 'decode')) + return losses + + def loss(self, inputs: Tensor, data_samples: SampleList) -> dict: + """Calculate losses from a batch of inputs and data samples. + + Args: + inputs (Tensor): Input images. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_sem_seg`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + classifier_embeds = self.text_encoder() + clip_inputs = inputs + if self.asymetric_input: + clip_inputs = F.interpolate( + inputs, scale_factor=self.encoder_resolution, mode='bilinear') + x = self.image_encoder(clip_inputs) + + losses = dict() + + loss_decode = self._decode_head_forward_train( + [inputs, x, classifier_embeds], data_samples) + losses.update(loss_decode) + + return losses + + def predict(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """Predict results from a batch of inputs and data samples with post- + processing. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`], optional): The seg data + samples. It usually includes information such as `metainfo` + and `gt_sem_seg`. + + Returns: + list[:obj:`SegDataSample`]: Segmentation results of the + input images. Each SegDataSample usually contain: + + - ``pred_sem_seg``(PixelData): Prediction of semantic segmentation. + - ``seg_logits``(PixelData): Predicted logits of semantic + segmentation before normalization. + """ + if data_samples is not None: + batch_img_metas = [ + data_sample.metainfo for data_sample in data_samples + ] + else: + batch_img_metas = [ + dict( + ori_shape=inputs.shape[2:], + img_shape=inputs.shape[2:], + pad_shape=inputs.shape[2:], + padding_size=[0, 0, 0, 0]) + ] * inputs.shape[0] + + seg_logits = self.inference(inputs, batch_img_metas) + + return self.postprocess_result(seg_logits, data_samples) + + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tensor: + """Network forward process. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_sem_seg`. + + Returns: + Tensor: Forward output of model without any post-processes. + """ + x = self.extract_feat(inputs) + return self.decode_head.forward(x) + + def slide_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference by sliding-window with overlap. + + If h_crop > h_img or w_crop > w_img, the small patch will be used to + decode without padding. + + Args: + inputs (tensor): the tensor should have a shape NxCxHxW, + which contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + h_stride, w_stride = self.test_cfg.stride + h_crop, w_crop = self.test_cfg.crop_size + batch_size, _, h_img, w_img = inputs.size() + out_channels = self.out_channels + h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1 + w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1 + preds = inputs.new_zeros((batch_size, out_channels, h_img, w_img)) + count_mat = inputs.new_zeros((batch_size, 1, h_img, w_img)) + for h_idx in range(h_grids): + for w_idx in range(w_grids): + y1 = h_idx * h_stride + x1 = w_idx * w_stride + y2 = min(y1 + h_crop, h_img) + x2 = min(x1 + w_crop, w_img) + y1 = max(y2 - h_crop, 0) + x1 = max(x2 - w_crop, 0) + crop_img = inputs[:, :, y1:y2, x1:x2] + # change the image shape to patch shape + batch_img_metas[0]['img_shape'] = crop_img.shape[2:] + # the output of encode_decode is seg logits tensor map + # with shape [N, C, H, W] + crop_seg_logit = self.encode_decode(crop_img, batch_img_metas) + preds += F.pad(crop_seg_logit, + (int(x1), int(preds.shape[3] - x2), int(y1), + int(preds.shape[2] - y2))) + + count_mat[:, :, y1:y2, x1:x2] += 1 + assert (count_mat == 0).sum() == 0 + seg_logits = preds / count_mat + + return seg_logits + + def whole_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference with full image. + + Args: + inputs (Tensor): The tensor should have a shape NxCxHxW, which + contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + seg_logits = self.encode_decode(inputs, batch_img_metas) + + return seg_logits + + def inference(self, inputs: Tensor, batch_img_metas: List[dict]) -> Tensor: + """Inference with slide/whole style. + + Args: + inputs (Tensor): The input image of shape (N, 3, H, W). + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', 'pad_shape', and 'padding_size'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + assert self.test_cfg.mode in ['slide', 'whole'] + ori_shape = batch_img_metas[0]['ori_shape'] + assert all(_['ori_shape'] == ori_shape for _ in batch_img_metas) + if self.test_cfg.mode == 'slide': + seg_logit = self.slide_inference(inputs, batch_img_metas) + else: + seg_logit = self.whole_inference(inputs, batch_img_metas) + + return seg_logit + + def aug_test(self, inputs, batch_img_metas, rescale=True): + """Test with augmentations. + + Only rescale=True is supported. + """ + # aug_test rescale all imgs back to ori_shape for now + assert rescale + # to save memory, we get augmented seg logit inplace + seg_logit = self.inference(inputs[0], batch_img_metas[0], rescale) + for i in range(1, len(inputs)): + cur_seg_logit = self.inference(inputs[i], batch_img_metas[i], + rescale) + seg_logit += cur_seg_logit + seg_logit /= len(inputs) + seg_pred = seg_logit.argmax(dim=1) + # unravel batch dim + seg_pred = list(seg_pred) + return seg_pred diff --git a/third-party/InterFormer/mmseg/models/segmentors/seg_tta.py b/third-party/InterFormer/mmseg/models/segmentors/seg_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..63ef61d223a572dec4fc3e43e1550b98cd2e7302 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/segmentors/seg_tta.py @@ -0,0 +1,47 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List + +import torch +from mmengine.model import BaseTTAModel +from mmengine.structures import PixelData + +from mmseg.registry import MODELS +from mmseg.utils import SampleList + + +@MODELS.register_module() +class SegTTAModel(BaseTTAModel): + + def merge_preds(self, data_samples_list: List[SampleList]) -> SampleList: + """Merge predictions of enhanced data to one prediction. + + Args: + data_samples_list (List[SampleList]): List of predictions + of all enhanced data. + + Returns: + SampleList: Merged prediction. + """ + predictions = [] + for data_samples in data_samples_list: + seg_logits = data_samples[0].seg_logits.data + logits = torch.zeros(seg_logits.shape).to(seg_logits) + for data_sample in data_samples: + seg_logit = data_sample.seg_logits.data + if self.module.out_channels > 1: + logits += seg_logit.softmax(dim=0) + else: + logits += seg_logit.sigmoid() + logits /= len(data_samples) + if self.module.out_channels == 1: + seg_pred = (logits > self.module.decode_head.threshold + ).to(logits).squeeze(1) + else: + seg_pred = logits.argmax(dim=0) + data_sample.set_data({'pred_sem_seg': PixelData(data=seg_pred)}) + if hasattr(data_samples[0], 'gt_sem_seg'): + data_sample.set_data( + {'gt_sem_seg': data_samples[0].gt_sem_seg}) + data_sample.set_metainfo({'img_path': data_samples[0].img_path}) + predictions.append(data_sample) + return predictions diff --git a/third-party/InterFormer/mmseg/models/text_encoder/__init__.py b/third-party/InterFormer/mmseg/models/text_encoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..199856d9d79800cbcd9aa7b77223a6528c6b7e0a --- /dev/null +++ b/third-party/InterFormer/mmseg/models/text_encoder/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .clip_text_encoder import CLIPTextEncoder + +__all__ = ['CLIPTextEncoder'] diff --git a/third-party/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d45675ab07ea223d98813767e15d7f69148c3c9a Binary files /dev/null and b/third-party/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-38.pyc b/third-party/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20c61a4eb99ed5dab10a4534a1c5fdeaf40b1953 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/text_encoder/clip_text_encoder.py b/third-party/InterFormer/mmseg/models/text_encoder/clip_text_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..1a18b86395ebcf0443e9aab05f4454acada98990 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/text_encoder/clip_text_encoder.py @@ -0,0 +1,229 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List + +import numpy as np +import torch +import torch.nn as nn +from mmcv.cnn import build_norm_layer +from mmcv.cnn.bricks.transformer import BaseTransformerLayer +from mmengine.model import BaseModule, ModuleList +from mmengine.runner.checkpoint import CheckpointLoader, load_state_dict +from torch.nn import functional as F + +from mmseg.registry import MODELS +from mmseg.utils import get_classes, get_predefined_templates, tokenizer + + +@MODELS.register_module() +class CLIPTextEncoder(BaseModule): + """A text encoder with transformer architecture to encode the label text. + + Modified from https://github.com/MendelXu/SAN/blob/main/san/model/clip_utils/classifier.py # noqa:E501 + Copyright (c) 2023 MendelXu. + Licensed under the MIT License + + Args: + dataset_name: (str|None): The name of the dataset to which + the data belongs. + vocabulary: (List[str]|None): The list of class names. Default: None. + templates: (List[str]|None): The prompt template used for labels. + Default: None. + total_vocab_size: (int): Number of all words used by the pre-trained + model. Default: 49408 (CLIP). + context_length: (int): The max length of prompt text. + Default: 77 (CLIP). + embed_dims: (int): Width of transformer model. Default: 512. + num_layers: (int): Depth of transformer. Default: 12, + num_heads: (int): Number of attention heads in transformer. + Default: 8, + mlp_ratio: (int) Ratio of mlp hidden dim to embedding dim in + transformer. Default: 4, + output_dims: (int) Dim of output text embeddings. Default: 512, + cache_feature: (bool) Whether to save class embeddings in cache. + Default: True, + cat_bg: (bool) Whether to add background embedding. Default: True. + norm_cfg (dict|None): Config for norm layer. Default: dict(type='LN') + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + dataset_name: str = None, + vocabulary: List[str] = None, + templates: str = 'vild', + total_vocab_size: int = 49408, + context_length: int = 77, + embed_dims: int = 512, + num_layers: int = 12, + num_heads: int = 8, + mlp_ratio: int = 4, + output_dims: int = 512, + cache_feature: bool = True, + cat_bg: bool = True, + norm_cfg: dict = dict(type='LN'), + init_cfg: dict = None): + super().__init__(init_cfg) + if isinstance(templates, List): + self.templates = templates + else: + self.templates = get_predefined_templates(templates) + + assert dataset_name is not None or vocabulary is not None, \ + "text_encoder required either 'dataset_name' or 'vocabulary'" + assert dataset_name is None or vocabulary is None, \ + "there is conflict between 'dataset_name' and 'vocabulary'" + self.dataset_name = dataset_name + self.vocabulary = vocabulary + self.num_pos = context_length + self.token_embedding = nn.Embedding(total_vocab_size, embed_dims) + self.positional_embedding = nn.Parameter( + torch.empty(context_length, embed_dims)) + self.text_projection = nn.Parameter( + torch.empty(embed_dims, output_dims)) + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + self.transformer = ModuleList() + self.register_buffer( + 'attn_mask', self.build_attention_mask(), persistent=False) + for i in range(num_layers): + self.transformer.append( + BaseTransformerLayer( + attn_cfgs=dict( + type='MultiheadAttention', + embed_dims=embed_dims, + num_heads=num_heads, + batch_first=False, + bias=True), + ffn_cfgs=dict( + type='FFN', + embed_dims=embed_dims, + feedforward_channels=mlp_ratio * embed_dims, + act_cfg=dict(type='QuickGELU')), + operation_order=('norm', 'self_attn', 'norm', 'ffn'))) + self.ln_final = build_norm_layer( + norm_cfg, embed_dims, postfix='_final')[1] + + self.cache_feature = cache_feature + if self.cache_feature: + self.cache = {} + + self._freeze() + + self.cat_bg = cat_bg + if self.cat_bg: + self.bg_embed = nn.Parameter( + torch.randn(1, self.text_projection.shape[1])) + + @property + def ln_final(self): + return getattr(self, self.final_name) + + def build_attention_mask(self): + """lazily create causal attention mask, with full attention between the + tokens. + + pytorch uses additive attention mask; fill with -inf + """ + mask = torch.empty(self.num_pos, self.num_pos) + mask.fill_(float('-inf')) + mask.triu_(1) # zero out the lower diagonal + return mask + + def _freeze(self): + for param in self.parameters(): + param.requires_grad = False + + def init_weights(self): + if self.cat_bg: + nn.init.normal_( + self.bg_embed, + std=self.bg_embed.shape[1]**-0.5, + ) + if isinstance(self.init_cfg, dict) and \ + self.init_cfg.get('type') == 'Pretrained_Part': + checkpoint = CheckpointLoader.load_checkpoint( + self.init_cfg['checkpoint'], logger=None, map_location='cpu') + + state_dict = checkpoint.copy() + para_prefix = 'text_encoder' + prefix_len = len(para_prefix) + 1 + for k, v in checkpoint.items(): + state_dict.pop(k) + if para_prefix in k: + state_dict[k[prefix_len:]] = v + + load_state_dict(self, state_dict, strict=False, logger=None) + + else: + super().init_weights() + + @torch.no_grad() + def encode_text(self, text, normalize=False): + """encode class token.""" + + embed_device = self.token_embedding.weight.device + x = self.token_embedding( + text.to(embed_device)) # [batch_size, n_ctx, d_model] + x = x + self.positional_embedding + x = x.permute(1, 0, 2) # NLD -> LND + for block in self.transformer: + x = block(query=x, attn_masks=self.attn_mask) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) # [batch_size, n_ctx, transformer.width] + # take features from the eot embedding + # (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), + text.argmax(dim=-1)] @ self.text_projection + return F.normalize(x, dim=-1) if normalize else x + + def template_encode(self, vocabulary): + """Prompt engineering.""" + text_embed_bucket = [] + for template in self.templates: + text_inputs = tokenizer.tokenize( + [template.format(noun) for noun in vocabulary]) + text_embed = self.encode_text(text_inputs, normalize=True) + text_embed_bucket.append(text_embed) + text_embed = torch.stack(text_embed_bucket).mean(dim=0) + text_embed = text_embed / text_embed.norm(dim=-1, keepdim=True) + return text_embed + + def forward(self): + """Forward function.""" + if self.dataset_name is None: # encoding vocabulary directly + class_names = self.vocabulary + if self.cache_feature: + new_classes = [ + word for word in class_names if word not in self.cache + ] + if len(new_classes) > 0: + class_embeds = self.template_encode(new_classes) + self.cache.update(dict(zip(new_classes, class_embeds))) + class_embeds = torch.stack( + [self.cache[word] for word in class_names]) + else: + class_embeds = self.template_encode(class_names) + + else: # encoding the classes of the dataset + class_names = get_classes(self.dataset_name) + if class_names[0] == 'background': + class_names = class_names[1:] + if self.cache_feature: + if self.dataset_name not in self.cache: + class_embeds = self.template_encode(class_names) + self.cache[self.dataset_name] = class_embeds + else: + class_embeds = self.cache[self.dataset_name] + else: + class_embeds = self.template_encode(class_names) + + if self.cat_bg: + class_embeds = torch.cat([class_embeds, self.bg_embed]) + class_embeds = F.normalize(class_embeds, p=2, dim=-1) + return self.logit_scale.exp() * class_embeds + + +@MODELS.register_module() +class QuickGELU(nn.Module): + # From https://github.com/openai/CLIP/blob/main/clip/model.py + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) diff --git a/third-party/InterFormer/mmseg/models/utils/__init__.py b/third-party/InterFormer/mmseg/models/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c0751b17c02de14e9bf1bfc02230d507a143e9c0 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .basic_block import BasicBlock, Bottleneck +from .embed import PatchEmbed +from .encoding import Encoding +from .inverted_residual import InvertedResidual, InvertedResidualV3 +from .make_divisible import make_divisible +from .point_sample import get_uncertain_point_coords_with_randomness +from .ppm import DAPPM, PAPPM +from .res_layer import ResLayer +from .se_layer import SELayer +from .self_attention_block import SelfAttentionBlock +from .shape_convert import (nchw2nlc2nchw, nchw_to_nlc, nlc2nchw2nlc, + nlc_to_nchw) +from .up_conv_block import UpConvBlock + +# isort: off +from .wrappers import Upsample, resize +from .san_layers import MLP, LayerNorm2d, cross_attn_layer + +__all__ = [ + 'ResLayer', 'SelfAttentionBlock', 'make_divisible', 'InvertedResidual', + 'UpConvBlock', 'InvertedResidualV3', 'SELayer', 'PatchEmbed', + 'nchw_to_nlc', 'nlc_to_nchw', 'nchw2nlc2nchw', 'nlc2nchw2nlc', 'Encoding', + 'Upsample', 'resize', 'DAPPM', 'PAPPM', 'BasicBlock', 'Bottleneck', + 'cross_attn_layer', 'LayerNorm2d', 'MLP', + 'get_uncertain_point_coords_with_randomness' +] diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f127211d782727026bdd292869f47fe4a555afc1 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e7d9c35cac58976f8d5de1b2d3ad423cffd4c2c Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f1b5e266c93036b1ca322826248024f0f24fe7 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cd1b8d0079942ac8cfd0eac815ec013296d6da6 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..048b27a4679f70790d19dcff7de2ea2534c0d0d2 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97239b8f895a3fe460bef08258e1009f187d98f4 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1036cbfd38a82e3a128a990ead6d29ea285dd689 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9febdd2c7de1a188acf4353efbca6ca25023cca2 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c5591569c849de73bf63ed0b91a2a2d4a5737f Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d47f77bfe3cd902af6223db682ee9c225d199b76 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe59de13b5ad7adb7dcd6faade1fd614b7d578cd Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd8d7808911b26771d2612551f11d4bee2b07b81 Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..770835513d3eaaa51b67c32b852873cd6188e93f Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..510fe17e48b0c130e52368b010bb373fbf44757e Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-38.pyc b/third-party/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6113f3fbdb3e38912999583d1b91e8c606ca954e Binary files /dev/null and b/third-party/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/models/utils/basic_block.py b/third-party/InterFormer/mmseg/models/utils/basic_block.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1ad8146dd200c5f1e543adf22ada654ee196a4 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/basic_block.py @@ -0,0 +1,143 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional + +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import OptConfigType + + +class BasicBlock(BaseModule): + """Basic block from `ResNet `_. + + Args: + in_channels (int): Input channels. + channels (int): Output channels. + stride (int): Stride of the first block. Default: 1. + downsample (nn.Module, optional): Downsample operation on identity. + Default: None. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict, optional): Config dict for activation layer in + ConvModule. Default: dict(type='ReLU', inplace=True). + act_cfg_out (dict, optional): Config dict for activation layer at the + last of the block. Default: None. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + expansion = 1 + + def __init__(self, + in_channels: int, + channels: int, + stride: int = 1, + downsample: nn.Module = None, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + act_cfg_out: OptConfigType = dict(type='ReLU', inplace=True), + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + self.conv1 = ConvModule( + in_channels, + channels, + kernel_size=3, + stride=stride, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.conv2 = ConvModule( + channels, + channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=None) + self.downsample = downsample + if act_cfg_out: + self.act = MODELS.build(act_cfg_out) + + def forward(self, x: Tensor) -> Tensor: + residual = x + out = self.conv1(x) + out = self.conv2(out) + + if self.downsample: + residual = self.downsample(x) + + out += residual + + if hasattr(self, 'act'): + out = self.act(out) + + return out + + +class Bottleneck(BaseModule): + """Bottleneck block from `ResNet `_. + + Args: + in_channels (int): Input channels. + channels (int): Output channels. + stride (int): Stride of the first block. Default: 1. + downsample (nn.Module, optional): Downsample operation on identity. + Default: None. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict, optional): Config dict for activation layer in + ConvModule. Default: dict(type='ReLU', inplace=True). + act_cfg_out (dict, optional): Config dict for activation layer at + the last of the block. Default: None. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + expansion = 2 + + def __init__(self, + in_channels: int, + channels: int, + stride: int = 1, + downsample: Optional[nn.Module] = None, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + act_cfg_out: OptConfigType = None, + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + self.conv1 = ConvModule( + in_channels, channels, 1, norm_cfg=norm_cfg, act_cfg=act_cfg) + self.conv2 = ConvModule( + channels, + channels, + 3, + stride, + 1, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.conv3 = ConvModule( + channels, + channels * self.expansion, + 1, + norm_cfg=norm_cfg, + act_cfg=None) + if act_cfg_out: + self.act = MODELS.build(act_cfg_out) + self.downsample = downsample + + def forward(self, x: Tensor) -> Tensor: + residual = x + + out = self.conv1(x) + out = self.conv2(out) + out = self.conv3(out) + + if self.downsample: + residual = self.downsample(x) + + out += residual + + if hasattr(self, 'act'): + out = self.act(out) + + return out diff --git a/third-party/InterFormer/mmseg/models/utils/embed.py b/third-party/InterFormer/mmseg/models/utils/embed.py new file mode 100644 index 0000000000000000000000000000000000000000..aef0a40b0a87bb6616db96fe2c72c19cc6f5b366 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/embed.py @@ -0,0 +1,330 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +from typing import Sequence + +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import build_conv_layer, build_norm_layer +from mmengine.model import BaseModule +from mmengine.utils import to_2tuple + + +class AdaptivePadding(nn.Module): + """Applies padding to input (if needed) so that input can get fully covered + by filter you specified. It support two modes "same" and "corner". The + "same" mode is same with "SAME" padding mode in TensorFlow, pad zero around + input. The "corner" mode would pad zero to bottom right. + + Args: + kernel_size (int | tuple): Size of the kernel: + stride (int | tuple): Stride of the filter. Default: 1: + dilation (int | tuple): Spacing between kernel elements. + Default: 1. + padding (str): Support "same" and "corner", "corner" mode + would pad zero to bottom right, and "same" mode would + pad zero around input. Default: "corner". + Example: + >>> kernel_size = 16 + >>> stride = 16 + >>> dilation = 1 + >>> input = torch.rand(1, 1, 15, 17) + >>> adap_pad = AdaptivePadding( + >>> kernel_size=kernel_size, + >>> stride=stride, + >>> dilation=dilation, + >>> padding="corner") + >>> out = adap_pad(input) + >>> assert (out.shape[2], out.shape[3]) == (16, 32) + >>> input = torch.rand(1, 1, 16, 17) + >>> out = adap_pad(input) + >>> assert (out.shape[2], out.shape[3]) == (16, 32) + """ + + def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'): + + super().__init__() + + assert padding in ('same', 'corner') + + kernel_size = to_2tuple(kernel_size) + stride = to_2tuple(stride) + dilation = to_2tuple(dilation) + + self.padding = padding + self.kernel_size = kernel_size + self.stride = stride + self.dilation = dilation + + def get_pad_shape(self, input_shape): + input_h, input_w = input_shape + kernel_h, kernel_w = self.kernel_size + stride_h, stride_w = self.stride + output_h = math.ceil(input_h / stride_h) + output_w = math.ceil(input_w / stride_w) + pad_h = max((output_h - 1) * stride_h + + (kernel_h - 1) * self.dilation[0] + 1 - input_h, 0) + pad_w = max((output_w - 1) * stride_w + + (kernel_w - 1) * self.dilation[1] + 1 - input_w, 0) + return pad_h, pad_w + + def forward(self, x): + pad_h, pad_w = self.get_pad_shape(x.size()[-2:]) + if pad_h > 0 or pad_w > 0: + if self.padding == 'corner': + x = F.pad(x, [0, pad_w, 0, pad_h]) + elif self.padding == 'same': + x = F.pad(x, [ + pad_w // 2, pad_w - pad_w // 2, pad_h // 2, + pad_h - pad_h // 2 + ]) + return x + + +class PatchEmbed(BaseModule): + """Image to Patch Embedding. + + We use a conv layer to implement PatchEmbed. + + Args: + in_channels (int): The num of input channels. Default: 3 + embed_dims (int): The dimensions of embedding. Default: 768 + conv_type (str): The config dict for embedding + conv layer type selection. Default: "Conv2d". + kernel_size (int): The kernel_size of embedding conv. Default: 16. + stride (int, optional): The slide stride of embedding conv. + Default: None (Would be set as `kernel_size`). + padding (int | tuple | string ): The padding length of + embedding conv. When it is a string, it means the mode + of adaptive padding, support "same" and "corner" now. + Default: "corner". + dilation (int): The dilation rate of embedding conv. Default: 1. + bias (bool): Bias of embed conv. Default: True. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: None. + input_size (int | tuple | None): The size of input, which will be + used to calculate the out size. Only work when `dynamic_size` + is False. Default: None. + init_cfg (`mmengine.ConfigDict`, optional): The Config for + initialization. Default: None. + """ + + def __init__(self, + in_channels=3, + embed_dims=768, + conv_type='Conv2d', + kernel_size=16, + stride=None, + padding='corner', + dilation=1, + bias=True, + norm_cfg=None, + input_size=None, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + self.embed_dims = embed_dims + if stride is None: + stride = kernel_size + + kernel_size = to_2tuple(kernel_size) + stride = to_2tuple(stride) + dilation = to_2tuple(dilation) + + if isinstance(padding, str): + self.adap_padding = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + # disable the padding of conv + padding = 0 + else: + self.adap_padding = None + padding = to_2tuple(padding) + + self.projection = build_conv_layer( + dict(type=conv_type), + in_channels=in_channels, + out_channels=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + if norm_cfg is not None: + self.norm = build_norm_layer(norm_cfg, embed_dims)[1] + else: + self.norm = None + + if input_size: + input_size = to_2tuple(input_size) + # `init_out_size` would be used outside to + # calculate the num_patches + # when `use_abs_pos_embed` outside + self.init_input_size = input_size + if self.adap_padding: + pad_h, pad_w = self.adap_padding.get_pad_shape(input_size) + input_h, input_w = input_size + input_h = input_h + pad_h + input_w = input_w + pad_w + input_size = (input_h, input_w) + + # https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html + h_out = (input_size[0] + 2 * padding[0] - dilation[0] * + (kernel_size[0] - 1) - 1) // stride[0] + 1 + w_out = (input_size[1] + 2 * padding[1] - dilation[1] * + (kernel_size[1] - 1) - 1) // stride[1] + 1 + self.init_out_size = (h_out, w_out) + else: + self.init_input_size = None + self.init_out_size = None + + def forward(self, x): + """ + Args: + x (Tensor): Has shape (B, C, H, W). In most case, C is 3. + + Returns: + tuple: Contains merged results and its spatial shape. + + - x (Tensor): Has shape (B, out_h * out_w, embed_dims) + - out_size (tuple[int]): Spatial shape of x, arrange as + (out_h, out_w). + """ + + if self.adap_padding: + x = self.adap_padding(x) + + x = self.projection(x) + out_size = (x.shape[2], x.shape[3]) + x = x.flatten(2).transpose(1, 2) + if self.norm is not None: + x = self.norm(x) + return x, out_size + + +class PatchMerging(BaseModule): + """Merge patch feature map. + + This layer groups feature map by kernel_size, and applies norm and linear + layers to the grouped feature map. Our implementation uses `nn.Unfold` to + merge patch, which is about 25% faster than original implementation. + Instead, we need to modify pretrained models for compatibility. + + Args: + in_channels (int): The num of input channels. + out_channels (int): The num of output channels. + kernel_size (int | tuple, optional): the kernel size in the unfold + layer. Defaults to 2. + stride (int | tuple, optional): the stride of the sliding blocks in the + unfold layer. Default: None. (Would be set as `kernel_size`) + padding (int | tuple | string ): The padding length of + embedding conv. When it is a string, it means the mode + of adaptive padding, support "same" and "corner" now. + Default: "corner". + dilation (int | tuple, optional): dilation parameter in the unfold + layer. Default: 1. + bias (bool, optional): Whether to add bias in linear layer or not. + Defaults: False. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: dict(type='LN'). + init_cfg (dict, optional): The extra config for initialization. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + kernel_size=2, + stride=None, + padding='corner', + dilation=1, + bias=False, + norm_cfg=dict(type='LN'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.in_channels = in_channels + self.out_channels = out_channels + if stride: + stride = stride + else: + stride = kernel_size + + kernel_size = to_2tuple(kernel_size) + stride = to_2tuple(stride) + dilation = to_2tuple(dilation) + + if isinstance(padding, str): + self.adap_padding = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + # disable the padding of unfold + padding = 0 + else: + self.adap_padding = None + + padding = to_2tuple(padding) + self.sampler = nn.Unfold( + kernel_size=kernel_size, + dilation=dilation, + padding=padding, + stride=stride) + + sample_dim = kernel_size[0] * kernel_size[1] * in_channels + + if norm_cfg is not None: + self.norm = build_norm_layer(norm_cfg, sample_dim)[1] + else: + self.norm = None + + self.reduction = nn.Linear(sample_dim, out_channels, bias=bias) + + def forward(self, x, input_size): + """ + Args: + x (Tensor): Has shape (B, H*W, C_in). + input_size (tuple[int]): The spatial shape of x, arrange as (H, W). + Default: None. + + Returns: + tuple: Contains merged results and its spatial shape. + + - x (Tensor): Has shape (B, Merged_H * Merged_W, C_out) + - out_size (tuple[int]): Spatial shape of x, arrange as + (Merged_H, Merged_W). + """ + B, L, C = x.shape + assert isinstance(input_size, Sequence), f'Expect ' \ + f'input_size is ' \ + f'`Sequence` ' \ + f'but get {input_size}' + + H, W = input_size + assert L == H * W, 'input feature has wrong size' + + x = x.view(B, H, W, C).permute([0, 3, 1, 2]) # B, C, H, W + # Use nn.Unfold to merge patch. About 25% faster than original method, + # but need to modify pretrained model for compatibility + + if self.adap_padding: + x = self.adap_padding(x) + H, W = x.shape[-2:] + + x = self.sampler(x) + # if kernel_size=2 and stride=2, x should has shape (B, 4*C, H/2*W/2) + + out_h = (H + 2 * self.sampler.padding[0] - self.sampler.dilation[0] * + (self.sampler.kernel_size[0] - 1) - + 1) // self.sampler.stride[0] + 1 + out_w = (W + 2 * self.sampler.padding[1] - self.sampler.dilation[1] * + (self.sampler.kernel_size[1] - 1) - + 1) // self.sampler.stride[1] + 1 + + output_size = (out_h, out_w) + x = x.transpose(1, 2) # B, H/2*W/2, 4*C + x = self.norm(x) if self.norm else x + x = self.reduction(x) + return x, output_size diff --git a/third-party/InterFormer/mmseg/models/utils/encoding.py b/third-party/InterFormer/mmseg/models/utils/encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4f0574fbc1957cf8da591a0e4befd6d8a125d3 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/encoding.py @@ -0,0 +1,75 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from torch import nn +from torch.nn import functional as F + + +class Encoding(nn.Module): + """Encoding Layer: a learnable residual encoder. + + Input is of shape (batch_size, channels, height, width). + Output is of shape (batch_size, num_codes, channels). + + Args: + channels: dimension of the features or feature channels + num_codes: number of code words + """ + + def __init__(self, channels, num_codes): + super().__init__() + # init codewords and smoothing factor + self.channels, self.num_codes = channels, num_codes + std = 1. / ((num_codes * channels)**0.5) + # [num_codes, channels] + self.codewords = nn.Parameter( + torch.empty(num_codes, channels, + dtype=torch.float).uniform_(-std, std), + requires_grad=True) + # [num_codes] + self.scale = nn.Parameter( + torch.empty(num_codes, dtype=torch.float).uniform_(-1, 0), + requires_grad=True) + + @staticmethod + def scaled_l2(x, codewords, scale): + num_codes, channels = codewords.size() + batch_size = x.size(0) + reshaped_scale = scale.view((1, 1, num_codes)) + expanded_x = x.unsqueeze(2).expand( + (batch_size, x.size(1), num_codes, channels)) + reshaped_codewords = codewords.view((1, 1, num_codes, channels)) + + scaled_l2_norm = reshaped_scale * ( + expanded_x - reshaped_codewords).pow(2).sum(dim=3) + return scaled_l2_norm + + @staticmethod + def aggregate(assignment_weights, x, codewords): + num_codes, channels = codewords.size() + reshaped_codewords = codewords.view((1, 1, num_codes, channels)) + batch_size = x.size(0) + + expanded_x = x.unsqueeze(2).expand( + (batch_size, x.size(1), num_codes, channels)) + encoded_feat = (assignment_weights.unsqueeze(3) * + (expanded_x - reshaped_codewords)).sum(dim=1) + return encoded_feat + + def forward(self, x): + assert x.dim() == 4 and x.size(1) == self.channels + # [batch_size, channels, height, width] + batch_size = x.size(0) + # [batch_size, height x width, channels] + x = x.view(batch_size, self.channels, -1).transpose(1, 2).contiguous() + # assignment_weights: [batch_size, channels, num_codes] + assignment_weights = F.softmax( + self.scaled_l2(x, self.codewords, self.scale), dim=2) + # aggregate + encoded_feat = self.aggregate(assignment_weights, x, self.codewords) + return encoded_feat + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(Nx{self.channels}xHxW =>Nx{self.num_codes}' \ + f'x{self.channels})' + return repr_str diff --git a/third-party/InterFormer/mmseg/models/utils/inverted_residual.py b/third-party/InterFormer/mmseg/models/utils/inverted_residual.py new file mode 100644 index 0000000000000000000000000000000000000000..56190b3bfe7cc8fe98bf34c3812db18dd34a8f02 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/inverted_residual.py @@ -0,0 +1,213 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.cnn import ConvModule +from torch import nn +from torch.utils import checkpoint as cp + +from .se_layer import SELayer + + +class InvertedResidual(nn.Module): + """InvertedResidual block for MobileNetV2. + + Args: + in_channels (int): The input channels of the InvertedResidual block. + out_channels (int): The output channels of the InvertedResidual block. + stride (int): Stride of the middle (first) 3x3 convolution. + expand_ratio (int): Adjusts number of channels of the hidden layer + in InvertedResidual by this amount. + dilation (int): Dilation rate of depthwise conv. Default: 1 + conv_cfg (dict): Config dict for convolution layer. + Default: None, which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU6'). + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + + Returns: + Tensor: The output tensor. + """ + + def __init__(self, + in_channels, + out_channels, + stride, + expand_ratio, + dilation=1, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU6'), + with_cp=False, + **kwargs): + super().__init__() + self.stride = stride + assert stride in [1, 2], f'stride must in [1, 2]. ' \ + f'But received {stride}.' + self.with_cp = with_cp + self.use_res_connect = self.stride == 1 and in_channels == out_channels + hidden_dim = int(round(in_channels * expand_ratio)) + + layers = [] + if expand_ratio != 1: + layers.append( + ConvModule( + in_channels=in_channels, + out_channels=hidden_dim, + kernel_size=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **kwargs)) + layers.extend([ + ConvModule( + in_channels=hidden_dim, + out_channels=hidden_dim, + kernel_size=3, + stride=stride, + padding=dilation, + dilation=dilation, + groups=hidden_dim, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **kwargs), + ConvModule( + in_channels=hidden_dim, + out_channels=out_channels, + kernel_size=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None, + **kwargs) + ]) + self.conv = nn.Sequential(*layers) + + def forward(self, x): + + def _inner_forward(x): + if self.use_res_connect: + return x + self.conv(x) + else: + return self.conv(x) + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + return out + + +class InvertedResidualV3(nn.Module): + """Inverted Residual Block for MobileNetV3. + + Args: + in_channels (int): The input channels of this Module. + out_channels (int): The output channels of this Module. + mid_channels (int): The input channels of the depthwise convolution. + kernel_size (int): The kernel size of the depthwise convolution. + Default: 3. + stride (int): The stride of the depthwise convolution. Default: 1. + se_cfg (dict): Config dict for se layer. Default: None, which means no + se layer. + with_expand_conv (bool): Use expand conv or not. If set False, + mid_channels must be the same with in_channels. Default: True. + conv_cfg (dict): Config dict for convolution layer. Default: None, + which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU'). + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + + Returns: + Tensor: The output tensor. + """ + + def __init__(self, + in_channels, + out_channels, + mid_channels, + kernel_size=3, + stride=1, + se_cfg=None, + with_expand_conv=True, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + with_cp=False): + super().__init__() + self.with_res_shortcut = (stride == 1 and in_channels == out_channels) + assert stride in [1, 2] + self.with_cp = with_cp + self.with_se = se_cfg is not None + self.with_expand_conv = with_expand_conv + + if self.with_se: + assert isinstance(se_cfg, dict) + if not self.with_expand_conv: + assert mid_channels == in_channels + + if self.with_expand_conv: + self.expand_conv = ConvModule( + in_channels=in_channels, + out_channels=mid_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.depthwise_conv = ConvModule( + in_channels=mid_channels, + out_channels=mid_channels, + kernel_size=kernel_size, + stride=stride, + padding=kernel_size // 2, + groups=mid_channels, + conv_cfg=dict( + type='Conv2dAdaptivePadding') if stride == 2 else conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + if self.with_se: + self.se = SELayer(**se_cfg) + + self.linear_conv = ConvModule( + in_channels=mid_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None) + + def forward(self, x): + + def _inner_forward(x): + out = x + + if self.with_expand_conv: + out = self.expand_conv(out) + + out = self.depthwise_conv(out) + + if self.with_se: + out = self.se(out) + + out = self.linear_conv(out) + + if self.with_res_shortcut: + return x + out + else: + return out + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + return out diff --git a/third-party/InterFormer/mmseg/models/utils/make_divisible.py b/third-party/InterFormer/mmseg/models/utils/make_divisible.py new file mode 100644 index 0000000000000000000000000000000000000000..ed42c2eeea2a6aed03a0be5516b8d1ef1139e486 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/make_divisible.py @@ -0,0 +1,28 @@ +# Copyright (c) OpenMMLab. All rights reserved. +def make_divisible(value, divisor, min_value=None, min_ratio=0.9): + """Make divisible function. + + This function rounds the channel number to the nearest value that can be + divisible by the divisor. It is taken from the original tf repo. It ensures + that all layers have a channel number that is divisible by divisor. It can + be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py # noqa + + Args: + value (int): The original channel number. + divisor (int): The divisor to fully divide the channel number. + min_value (int): The minimum value of the output channel. + Default: None, means that the minimum value equal to the divisor. + min_ratio (float): The minimum ratio of the rounded channel number to + the original channel number. Default: 0.9. + + Returns: + int: The modified output channel number. + """ + + if min_value is None: + min_value = divisor + new_value = max(min_value, int(value + divisor / 2) // divisor * divisor) + # Make sure that round down does not go down by more than (1-min_ratio). + if new_value < min_ratio * value: + new_value += divisor + return new_value diff --git a/third-party/InterFormer/mmseg/models/utils/point_sample.py b/third-party/InterFormer/mmseg/models/utils/point_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..1afc957f3da7d1dc030c21d40311c768c6952ea4 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/point_sample.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.ops import point_sample +from torch import Tensor + + +def get_uncertainty(mask_preds: Tensor, labels: Tensor) -> Tensor: + """Estimate uncertainty based on pred logits. + + We estimate uncertainty as L1 distance between 0.0 and the logits + prediction in 'mask_preds' for the foreground class in `classes`. + + Args: + mask_preds (Tensor): mask predication logits, shape (num_rois, + num_classes, mask_height, mask_width). + + labels (Tensor): Either predicted or ground truth label for + each predicted mask, of length num_rois. + + Returns: + scores (Tensor): Uncertainty scores with the most uncertain + locations having the highest uncertainty score, + shape (num_rois, 1, mask_height, mask_width) + """ + if mask_preds.shape[1] == 1: + gt_class_logits = mask_preds.clone() + else: + inds = torch.arange(mask_preds.shape[0], device=mask_preds.device) + gt_class_logits = mask_preds[inds, labels].unsqueeze(1) + return -torch.abs(gt_class_logits) + + +def get_uncertain_point_coords_with_randomness( + mask_preds: Tensor, labels: Tensor, num_points: int, + oversample_ratio: float, importance_sample_ratio: float) -> Tensor: + """Get ``num_points`` most uncertain points with random points during + train. + + Sample points in [0, 1] x [0, 1] coordinate space based on their + uncertainty. The uncertainties are calculated for each point using + 'get_uncertainty()' function that takes point's logit prediction as + input. + + Args: + mask_preds (Tensor): A tensor of shape (num_rois, num_classes, + mask_height, mask_width) for class-specific or class-agnostic + prediction. + labels (Tensor): The ground truth class for each instance. + num_points (int): The number of points to sample. + oversample_ratio (float): Oversampling parameter. + importance_sample_ratio (float): Ratio of points that are sampled + via importnace sampling. + + Returns: + point_coords (Tensor): A tensor of shape (num_rois, num_points, 2) + that contains the coordinates sampled points. + """ + assert oversample_ratio >= 1 + assert 0 <= importance_sample_ratio <= 1 + batch_size = mask_preds.shape[0] + num_sampled = int(num_points * oversample_ratio) + point_coords = torch.rand( + batch_size, num_sampled, 2, device=mask_preds.device) + point_logits = point_sample(mask_preds, point_coords) + # It is crucial to calculate uncertainty based on the sampled + # prediction value for the points. Calculating uncertainties of the + # coarse predictions first and sampling them for points leads to + # incorrect results. To illustrate this: assume uncertainty func( + # logits)=-abs(logits), a sampled point between two coarse + # predictions with -1 and 1 logits has 0 logits, and therefore 0 + # uncertainty value. However, if we calculate uncertainties for the + # coarse predictions first, both will have -1 uncertainty, + # and sampled point will get -1 uncertainty. + point_uncertainties = get_uncertainty(point_logits, labels) + num_uncertain_points = int(importance_sample_ratio * num_points) + num_random_points = num_points - num_uncertain_points + idx = torch.topk( + point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1] + shift = num_sampled * torch.arange( + batch_size, dtype=torch.long, device=mask_preds.device) + idx += shift[:, None] + point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view( + batch_size, num_uncertain_points, 2) + if num_random_points > 0: + rand_roi_coords = torch.rand( + batch_size, num_random_points, 2, device=mask_preds.device) + point_coords = torch.cat((point_coords, rand_roi_coords), dim=1) + return point_coords diff --git a/third-party/InterFormer/mmseg/models/utils/ppm.py b/third-party/InterFormer/mmseg/models/utils/ppm.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe6ff26fae6869b989cecde96af3ceff1a37b38 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/ppm.py @@ -0,0 +1,193 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Dict, List + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule, ModuleList, Sequential +from torch import Tensor + + +class DAPPM(BaseModule): + """DAPPM module in `DDRNet `_. + + Args: + in_channels (int): Input channels. + branch_channels (int): Branch channels. + out_channels (int): Output channels. + num_scales (int): Number of scales. + kernel_sizes (list[int]): Kernel sizes of each scale. + strides (list[int]): Strides of each scale. + paddings (list[int]): Paddings of each scale. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU', inplace=True). + conv_cfg (dict): Config dict for convolution layer in ConvModule. + Default: dict(order=('norm', 'act', 'conv'), bias=False). + upsample_mode (str): Upsample mode. Default: 'bilinear'. + """ + + def __init__(self, + in_channels: int, + branch_channels: int, + out_channels: int, + num_scales: int, + kernel_sizes: List[int] = [5, 9, 17], + strides: List[int] = [2, 4, 8], + paddings: List[int] = [2, 4, 8], + norm_cfg: Dict = dict(type='BN', momentum=0.1), + act_cfg: Dict = dict(type='ReLU', inplace=True), + conv_cfg: Dict = dict( + order=('norm', 'act', 'conv'), bias=False), + upsample_mode: str = 'bilinear'): + super().__init__() + + self.num_scales = num_scales + self.unsample_mode = upsample_mode + self.in_channels = in_channels + self.branch_channels = branch_channels + self.out_channels = out_channels + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.conv_cfg = conv_cfg + + self.scales = ModuleList([ + ConvModule( + in_channels, + branch_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + ]) + for i in range(1, num_scales - 1): + self.scales.append( + Sequential(*[ + nn.AvgPool2d( + kernel_size=kernel_sizes[i - 1], + stride=strides[i - 1], + padding=paddings[i - 1]), + ConvModule( + in_channels, + branch_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + ])) + self.scales.append( + Sequential(*[ + nn.AdaptiveAvgPool2d((1, 1)), + ConvModule( + in_channels, + branch_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + ])) + self.processes = ModuleList() + for i in range(num_scales - 1): + self.processes.append( + ConvModule( + branch_channels, + branch_channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg)) + + self.compression = ConvModule( + branch_channels * num_scales, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + + self.shortcut = ConvModule( + in_channels, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + + def forward(self, inputs: Tensor): + feats = [] + feats.append(self.scales[0](inputs)) + + for i in range(1, self.num_scales): + feat_up = F.interpolate( + self.scales[i](inputs), + size=inputs.shape[2:], + mode=self.unsample_mode) + feats.append(self.processes[i - 1](feat_up + feats[i - 1])) + + return self.compression(torch.cat(feats, + dim=1)) + self.shortcut(inputs) + + +class PAPPM(DAPPM): + """PAPPM module in `PIDNet `_. + + Args: + in_channels (int): Input channels. + branch_channels (int): Branch channels. + out_channels (int): Output channels. + num_scales (int): Number of scales. + kernel_sizes (list[int]): Kernel sizes of each scale. + strides (list[int]): Strides of each scale. + paddings (list[int]): Paddings of each scale. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN', momentum=0.1). + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU', inplace=True). + conv_cfg (dict): Config dict for convolution layer in ConvModule. + Default: dict(order=('norm', 'act', 'conv'), bias=False). + upsample_mode (str): Upsample mode. Default: 'bilinear'. + """ + + def __init__(self, + in_channels: int, + branch_channels: int, + out_channels: int, + num_scales: int, + kernel_sizes: List[int] = [5, 9, 17], + strides: List[int] = [2, 4, 8], + paddings: List[int] = [2, 4, 8], + norm_cfg: Dict = dict(type='BN', momentum=0.1), + act_cfg: Dict = dict(type='ReLU', inplace=True), + conv_cfg: Dict = dict( + order=('norm', 'act', 'conv'), bias=False), + upsample_mode: str = 'bilinear'): + super().__init__(in_channels, branch_channels, out_channels, + num_scales, kernel_sizes, strides, paddings, norm_cfg, + act_cfg, conv_cfg, upsample_mode) + + self.processes = ConvModule( + self.branch_channels * (self.num_scales - 1), + self.branch_channels * (self.num_scales - 1), + kernel_size=3, + padding=1, + groups=self.num_scales - 1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + **self.conv_cfg) + + def forward(self, inputs: Tensor): + x_ = self.scales[0](inputs) + feats = [] + for i in range(1, self.num_scales): + feat_up = F.interpolate( + self.scales[i](inputs), + size=inputs.shape[2:], + mode=self.unsample_mode, + align_corners=False) + feats.append(feat_up + x_) + scale_out = self.processes(torch.cat(feats, dim=1)) + return self.compression(torch.cat([x_, scale_out], + dim=1)) + self.shortcut(inputs) diff --git a/third-party/InterFormer/mmseg/models/utils/res_layer.py b/third-party/InterFormer/mmseg/models/utils/res_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd7a6f75a168f2f7e3c61f82d309b1cf0d502bc --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/res_layer.py @@ -0,0 +1,96 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.cnn import build_conv_layer, build_norm_layer +from mmengine.model import Sequential +from torch import nn as nn + + +class ResLayer(Sequential): + """ResLayer to build ResNet style backbone. + + Args: + block (nn.Module): block used to build ResLayer. + inplanes (int): inplanes of block. + planes (int): planes of block. + num_blocks (int): number of blocks. + stride (int): stride of the first block. Default: 1 + avg_down (bool): Use AvgPool instead of stride conv when + downsampling in the bottleneck. Default: False + conv_cfg (dict): dictionary to construct and config conv layer. + Default: None + norm_cfg (dict): dictionary to construct and config norm layer. + Default: dict(type='BN') + multi_grid (int | None): Multi grid dilation rates of last + stage. Default: None + contract_dilation (bool): Whether contract first dilation of each layer + Default: False + """ + + def __init__(self, + block, + inplanes, + planes, + num_blocks, + stride=1, + dilation=1, + avg_down=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + multi_grid=None, + contract_dilation=False, + **kwargs): + self.block = block + + downsample = None + if stride != 1 or inplanes != planes * block.expansion: + downsample = [] + conv_stride = stride + if avg_down: + conv_stride = 1 + downsample.append( + nn.AvgPool2d( + kernel_size=stride, + stride=stride, + ceil_mode=True, + count_include_pad=False)) + downsample.extend([ + build_conv_layer( + conv_cfg, + inplanes, + planes * block.expansion, + kernel_size=1, + stride=conv_stride, + bias=False), + build_norm_layer(norm_cfg, planes * block.expansion)[1] + ]) + downsample = nn.Sequential(*downsample) + + layers = [] + if multi_grid is None: + if dilation > 1 and contract_dilation: + first_dilation = dilation // 2 + else: + first_dilation = dilation + else: + first_dilation = multi_grid[0] + layers.append( + block( + inplanes=inplanes, + planes=planes, + stride=stride, + dilation=first_dilation, + downsample=downsample, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + **kwargs)) + inplanes = planes * block.expansion + for i in range(1, num_blocks): + layers.append( + block( + inplanes=inplanes, + planes=planes, + stride=1, + dilation=dilation if multi_grid is None else multi_grid[i], + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + **kwargs)) + super().__init__(*layers) diff --git a/third-party/InterFormer/mmseg/models/utils/san_layers.py b/third-party/InterFormer/mmseg/models/utils/san_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..2267686daf62658c5dc81408e0a399c43aee83aa --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/san_layers.py @@ -0,0 +1,418 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Modified from https://github.com/MendelXu/SAN/blob/main/san/model/attn_helper.py # noqa: E501 +# Copyright (c) 2023 MendelXu. +# Licensed under the MIT License + +import warnings +from typing import Optional + +import torch +from mmcv.cnn.bricks.transformer import BaseTransformerLayer +from torch import Tensor, nn +from torch.nn import functional as F + + +def cross_attn_with_self_bias( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim_to_check: int, + num_heads: int, + in_proj_weight: Tensor, + in_proj_bias: Tensor, + bias_k: Optional[Tensor], + bias_v: Optional[Tensor], + add_zero_attn: bool, + dropout_p: float, + out_proj_weight: Tensor, + out_proj_bias: Tensor, + training: bool = True, + key_padding_mask: Optional[Tensor] = None, + need_weights: bool = True, + attn_mask: Optional[Tensor] = None, + use_separate_proj_weight: bool = False, + q_proj_weight: Optional[Tensor] = None, + k_proj_weight: Optional[Tensor] = None, + v_proj_weight: Optional[Tensor] = None, + static_k: Optional[Tensor] = None, + static_v: Optional[Tensor] = None, +): + """Forward function of multi-head attention. Modified from + multi_head_attention_forward in + https://github.com/pytorch/pytorch/blob/main/torch/nn/functional.py. + + Args: + query, key, value: map a query and a set of key-value pairs to an output. + See "Attention Is All You Need" for more details. + embed_dim_to_check: total dimension of the model. + num_heads: parallel attention heads. + in_proj_weight, in_proj_bias: input projection weight and bias. + bias_k, bias_v: bias of the key and value sequences to be added at dim=0. + add_zero_attn: add a new batch of zeros to the key and + value sequences at dim=1. + dropout_p: probability of an element to be zeroed. + out_proj_weight, out_proj_bias: the output projection weight and bias. + training: apply dropout if is ``True``. + key_padding_mask: if provided, specified padding elements in the key will + be ignored by the attention. This is an binary mask. When the value is True, + the corresponding value on the attention layer will be filled with -inf. + need_weights: output attn_output_weights. + Default: `True` + Note: `needs_weight` defaults to `True`, but should be set to `False` + For best performance when attention weights are not needed. + *Setting needs_weights to `True` + leads to a significant performance degradation.* + attn_mask: 2D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all + the batches while a 3D mask allows to specify a different mask for the entries of each batch. + use_separate_proj_weight: the function accept the proj. weights for query, key, + and value in different forms. If false, in_proj_weight will be used, which is + a combination of q_proj_weight, k_proj_weight, v_proj_weight. + q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias. + static_k, static_v: static key and value used for attention operators. + """ # noqa: E501 + tgt_len, bsz, embed_dim = query.size() + assert embed_dim == embed_dim_to_check + # allow MHA to have different sizes for the feature dimension + assert key.size(0) == value.size(0) and key.size(1) == value.size(1) + + head_dim = embed_dim // num_heads + assert head_dim * num_heads == embed_dim, \ + 'embed_dim must be divisible by num_heads' + scaling = float(head_dim)**-0.5 + + if not use_separate_proj_weight: + if (query is key or torch.equal( + query, key)) and (key is value or torch.equal(key, value)): + # self-attention + raise NotImplementedError('self-attention is not implemented') + + elif key is value or torch.equal(key, value): + # encoder-decoder attention + # This is inline in_proj function + # with in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = 0 + _end = embed_dim + _w = in_proj_weight[_start:_end, :] + if _b is not None: + _b = _b[_start:_end] + q = F.linear(query, _w, _b) + + if key is None: + assert value is None + k = None + v = None + q_k = None + q_v = None + else: + # This is inline in_proj function with + # in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = embed_dim + _end = None + _w = in_proj_weight[_start:, :] + if _b is not None: + _b = _b[_start:] + k, v = F.linear(key, _w, _b).chunk(2, dim=-1) + q_k, q_v = F.linear(query, _w, _b).chunk(2, dim=-1) + else: + # This is inline in_proj function with + # in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = 0 + _end = embed_dim + _w = in_proj_weight[_start:_end, :] + if _b is not None: + _b = _b[_start:_end] + q = F.linear(query, _w, _b) + + # This is inline in_proj function with + # in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = embed_dim + _end = embed_dim * 2 + _w = in_proj_weight[_start:_end, :] + if _b is not None: + _b = _b[_start:_end] + k = F.linear(key, _w, _b) + q_k = F.linear(query, _w, _b) + # This is inline in_proj function with + # in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = embed_dim * 2 + _end = None + _w = in_proj_weight[_start:, :] + if _b is not None: + _b = _b[_start:] + v = F.linear(value, _w, _b) + q_v = F.linear(query, _w, _b) + else: + q_proj_weight_non_opt = \ + torch.jit._unwrap_optional(q_proj_weight) + len1, len2 = q_proj_weight_non_opt.size() + assert len1 == embed_dim and len2 == query.size(-1) + + k_proj_weight_non_opt = \ + torch.jit._unwrap_optional(k_proj_weight) + len1, len2 = k_proj_weight_non_opt.size() + assert len1 == embed_dim and len2 == key.size(-1) + + v_proj_weight_non_opt = \ + torch.jit._unwrap_optional(v_proj_weight) + len1, len2 = v_proj_weight_non_opt.size() + assert len1 == embed_dim and len2 == value.size(-1) + + if in_proj_bias is not None: + q = F.linear(query, q_proj_weight_non_opt, + in_proj_bias[0:embed_dim]) + k = F.linear(key, k_proj_weight_non_opt, + in_proj_bias[embed_dim:(embed_dim * 2)]) + v = F.linear(value, v_proj_weight_non_opt, + in_proj_bias[(embed_dim * 2):]) + else: + q = F.linear(query, q_proj_weight_non_opt, in_proj_bias) + k = F.linear(key, k_proj_weight_non_opt, in_proj_bias) + v = F.linear(value, v_proj_weight_non_opt, in_proj_bias) + q = q * scaling + + if attn_mask is not None: + assert ( + attn_mask.dtype == torch.float32 + or attn_mask.dtype == torch.float64 + or attn_mask.dtype == torch.float16 + or attn_mask.dtype == torch.uint8 or attn_mask.dtype == torch.bool + ), 'Only float, byte, and bool types are supported for ' \ + 'attn_mask, not {}'.format(attn_mask.dtype) + if attn_mask.dtype == torch.uint8: + warnings.warn('Byte tensor for attn_mask in nn.MultiheadAttention ' + 'is deprecated. Use bool tensor instead.') + attn_mask = attn_mask.to(torch.bool) + + if attn_mask.dim() == 2: + attn_mask = attn_mask.unsqueeze(0) + if list(attn_mask.size()) != [1, query.size(0), key.size(0)]: + raise RuntimeError( + 'The size of the 2D attn_mask is not correct.') + elif attn_mask.dim() == 3: + if list(attn_mask.size()) != [ + bsz * num_heads, + query.size(0), key.size(0) + ]: + raise RuntimeError( + 'The size of the 3D attn_mask is not correct.') + else: + raise RuntimeError( + "attn_mask's dimension {} is not supported".format( + attn_mask.dim())) + # attn_mask's dim is 3 now. + + # convert ByteTensor key_padding_mask to bool + if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8: + warnings.warn( + 'Byte tensor for key_padding_mask in nn.MultiheadAttention ' + 'is deprecated. Use bool tensor instead.') + key_padding_mask = key_padding_mask.to(torch.bool) + + if bias_k is not None and bias_v is not None: + if static_k is None and static_v is None: + k = torch.cat([k, bias_k.repeat(1, bsz, 1)]) + v = torch.cat([v, bias_v.repeat(1, bsz, 1)]) + if attn_mask is not None: + attn_mask = F.pad(attn_mask, (0, 1)) + if key_padding_mask is not None: + key_padding_mask = F.pad(key_padding_mask, (0, 1)) + else: + assert static_k is None, 'bias cannot be added to static key.' + assert static_v is None, 'bias cannot be added to static value.' + else: + assert bias_k is None + assert bias_v is None + + q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) + if k is not None: + k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + q_k = q_k.contiguous().view(tgt_len, bsz * num_heads, + head_dim).transpose(0, 1) + if v is not None: + v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + q_v = q_v.contiguous().view(tgt_len, bsz * num_heads, + head_dim).transpose(0, 1) + + if static_k is not None: + assert static_k.size(0) == bsz * num_heads + assert static_k.size(2) == head_dim + k = static_k + + if static_v is not None: + assert static_v.size(0) == bsz * num_heads + assert static_v.size(2) == head_dim + v = static_v + + src_len = k.size(1) + + if key_padding_mask is not None: + assert key_padding_mask.size(0) == bsz + assert key_padding_mask.size(1) == src_len + + if add_zero_attn: + src_len += 1 + k = torch.cat( + [ + k, + torch.zeros( + (k.size(0), 1) + k.size()[2:], + dtype=k.dtype, + device=k.device), + ], + dim=1, + ) + v = torch.cat( + [ + v, + torch.zeros( + (v.size(0), 1) + v.size()[2:], + dtype=v.dtype, + device=v.device), + ], + dim=1, + ) + if attn_mask is not None: + attn_mask = F.pad(attn_mask, (0, 1)) + if key_padding_mask is not None: + key_padding_mask = F.pad(key_padding_mask, (0, 1)) + + attn_output_weights = torch.bmm(q, k.transpose(1, 2)) + assert list( + attn_output_weights.size()) == [bsz * num_heads, tgt_len, src_len] + + if attn_mask is not None: + if attn_mask.dtype == torch.bool: + attn_output_weights.masked_fill_(attn_mask, float('-inf')) + else: + attn_output_weights += attn_mask + + if key_padding_mask is not None: + attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, + src_len) + attn_output_weights = attn_output_weights.masked_fill( + key_padding_mask.unsqueeze(1).unsqueeze(2), + float('-inf'), + ) + attn_output_weights = attn_output_weights.view(bsz * num_heads, + tgt_len, src_len) + # attn_out_weights: [bsz * num_heads, tgt_len, src_len] + # ->[bsz * num_heads, tgt_len, src_len+1] + self_weight = (q * q_k).sum( + dim=-1, keepdim=True) # [bsz * num_heads, tgt_len, 1] + total_attn_output_weights = torch.cat([attn_output_weights, self_weight], + dim=-1) + total_attn_output_weights = F.softmax(total_attn_output_weights, dim=-1) + total_attn_output_weights = F.dropout( + total_attn_output_weights, p=dropout_p, training=training) + attn_output_weights = \ + total_attn_output_weights[:, :, : -1] + # [bsz * num_heads, tgt_len, src_len] + self_weight = \ + total_attn_output_weights[:, :, -1:] # [bsz * num_heads, tgt_len, 1] + + attn_output = torch.bmm(attn_output_weights, + v) # [bsz * num_heads, tgt_len, head_dim] + attn_output = (attn_output + self_weight * q_v + ) # [bsz * num_heads, tgt_len, head_dim] + assert list(attn_output.size()) == [bsz * num_heads, tgt_len, head_dim] + attn_output = attn_output.transpose(0, 1).contiguous().view( + tgt_len, bsz, embed_dim) + attn_output = F.linear(attn_output, out_proj_weight, out_proj_bias) + + if need_weights: + # average attention weights over heads + attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, + src_len) + return attn_output, attn_output_weights # .sum(dim=1) / num_heads + else: + return attn_output, None + + +def cross_attn_layer(tf_layer: BaseTransformerLayer, x, mem, attn_bias): + """Implementation of transformer layer with cross attention. The cross + attention shares the embedding weights with self-attention of tf_layer. + Args: + tf_layer: (TransformerEncoderLayer): The Module of transformer layer. + x (Tensor): query [K,N,C] + mem (Tensor): key and value [L,N,C] + attn_bias (Tensor): attention bias [N*num_head,K,L] + + Return: + x (Tensor): cross attention output [K,N,C] + """ + self_attn_layer = tf_layer.attentions[0].attn + attn_layer_paras = { + 'embed_dim_to_check': self_attn_layer.embed_dim, + 'num_heads': self_attn_layer.num_heads, + 'in_proj_weight': self_attn_layer.in_proj_weight, + 'in_proj_bias': self_attn_layer.in_proj_bias, + 'bias_k': self_attn_layer.bias_k, + 'bias_v': self_attn_layer.bias_v, + 'add_zero_attn': self_attn_layer.add_zero_attn, + 'dropout_p': self_attn_layer.dropout, + 'out_proj_weight': self_attn_layer.out_proj.weight, + 'out_proj_bias': self_attn_layer.out_proj.bias, + 'training': self_attn_layer.training + } + + q_x = tf_layer.norms[0](x) + k_x = v_x = tf_layer.norms[0](mem) + x = x + cross_attn_with_self_bias( + q_x, + k_x, + v_x, + attn_mask=attn_bias, + need_weights=False, + **attn_layer_paras)[0] + x = tf_layer.ffns[0](tf_layer.norms[1](x), identity=x) + return x + + +class LayerNorm2d(nn.Module): + """A LayerNorm variant, popularized by Transformers, that performs point- + wise mean and variance normalization over the channel dimension for inputs + that have shape (batch_size, channels, height, width). + + https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa B950 + """ + + def __init__(self, normalized_shape, eps=1e-6): + super().__init__() + self.weight = nn.Parameter(torch.ones(normalized_shape)) + self.bias = nn.Parameter(torch.zeros(normalized_shape)) + self.eps = eps + self.normalized_shape = (normalized_shape, ) + + def forward(self, x: torch.Tensor): + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +class MLP(nn.Module): + """Very simple multi-layer perceptron (also called FFN)""" + + def __init__(self, + input_dim, + hidden_dim, + output_dim, + num_layers, + affine_func=nn.Linear): + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + affine_func(n, k) + for n, k in zip([input_dim] + h, h + [output_dim])) + + def forward(self, x: torch.Tensor): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + return x diff --git a/third-party/InterFormer/mmseg/models/utils/se_layer.py b/third-party/InterFormer/mmseg/models/utils/se_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff632cfea728a7ffd99f1578c828c588d78f3db --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/se_layer.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.utils import is_tuple_of + +from .make_divisible import make_divisible + + +class SELayer(nn.Module): + """Squeeze-and-Excitation Module. + + Args: + channels (int): The input (and output) channels of the SE layer. + ratio (int): Squeeze ratio in SELayer, the intermediate channel will be + ``int(channels/ratio)``. Default: 16. + conv_cfg (None or dict): Config dict for convolution layer. + Default: None, which means using conv2d. + act_cfg (dict or Sequence[dict]): Config dict for activation layer. + If act_cfg is a dict, two activation layers will be configured + by this dict. If act_cfg is a sequence of dicts, the first + activation layer will be configured by the first dict and the + second activation layer will be configured by the second dict. + Default: (dict(type='ReLU'), dict(type='HSigmoid', bias=3.0, + divisor=6.0)). + """ + + def __init__(self, + channels, + ratio=16, + conv_cfg=None, + act_cfg=(dict(type='ReLU'), + dict(type='HSigmoid', bias=3.0, divisor=6.0))): + super().__init__() + if isinstance(act_cfg, dict): + act_cfg = (act_cfg, act_cfg) + assert len(act_cfg) == 2 + assert is_tuple_of(act_cfg, dict) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.conv1 = ConvModule( + in_channels=channels, + out_channels=make_divisible(channels // ratio, 8), + kernel_size=1, + stride=1, + conv_cfg=conv_cfg, + act_cfg=act_cfg[0]) + self.conv2 = ConvModule( + in_channels=make_divisible(channels // ratio, 8), + out_channels=channels, + kernel_size=1, + stride=1, + conv_cfg=conv_cfg, + act_cfg=act_cfg[1]) + + def forward(self, x): + out = self.global_avgpool(x) + out = self.conv1(out) + out = self.conv2(out) + return x * out diff --git a/third-party/InterFormer/mmseg/models/utils/self_attention_block.py b/third-party/InterFormer/mmseg/models/utils/self_attention_block.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb6e8284e599637c12553e27199338a820709e3 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/self_attention_block.py @@ -0,0 +1,161 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import ConvModule +from mmengine.model.weight_init import constant_init +from torch import nn as nn +from torch.nn import functional as F + + +class SelfAttentionBlock(nn.Module): + """General self-attention block/non-local block. + + Please refer to https://arxiv.org/abs/1706.03762 for details about key, + query and value. + + Args: + key_in_channels (int): Input channels of key feature. + query_in_channels (int): Input channels of query feature. + channels (int): Output channels of key/query transform. + out_channels (int): Output channels. + share_key_query (bool): Whether share projection weight between key + and query projection. + query_downsample (nn.Module): Query downsample module. + key_downsample (nn.Module): Key downsample module. + key_query_num_convs (int): Number of convs for key/query projection. + value_num_convs (int): Number of convs for value projection. + matmul_norm (bool): Whether normalize attention map with sqrt of + channels + with_out (bool): Whether use out projection. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict|None): Config of activation layers. + """ + + def __init__(self, key_in_channels, query_in_channels, channels, + out_channels, share_key_query, query_downsample, + key_downsample, key_query_num_convs, value_out_num_convs, + key_query_norm, value_out_norm, matmul_norm, with_out, + conv_cfg, norm_cfg, act_cfg): + super().__init__() + if share_key_query: + assert key_in_channels == query_in_channels + self.key_in_channels = key_in_channels + self.query_in_channels = query_in_channels + self.out_channels = out_channels + self.channels = channels + self.share_key_query = share_key_query + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.key_project = self.build_project( + key_in_channels, + channels, + num_convs=key_query_num_convs, + use_conv_module=key_query_norm, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + if share_key_query: + self.query_project = self.key_project + else: + self.query_project = self.build_project( + query_in_channels, + channels, + num_convs=key_query_num_convs, + use_conv_module=key_query_norm, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.value_project = self.build_project( + key_in_channels, + channels if with_out else out_channels, + num_convs=value_out_num_convs, + use_conv_module=value_out_norm, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + if with_out: + self.out_project = self.build_project( + channels, + out_channels, + num_convs=value_out_num_convs, + use_conv_module=value_out_norm, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + else: + self.out_project = None + + self.query_downsample = query_downsample + self.key_downsample = key_downsample + self.matmul_norm = matmul_norm + + self.init_weights() + + def init_weights(self): + """Initialize weight of later layer.""" + if self.out_project is not None: + if not isinstance(self.out_project, ConvModule): + constant_init(self.out_project, 0) + + def build_project(self, in_channels, channels, num_convs, use_conv_module, + conv_cfg, norm_cfg, act_cfg): + """Build projection layer for key/query/value/out.""" + if use_conv_module: + convs = [ + ConvModule( + in_channels, + channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + ] + for _ in range(num_convs - 1): + convs.append( + ConvModule( + channels, + channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + else: + convs = [nn.Conv2d(in_channels, channels, 1)] + for _ in range(num_convs - 1): + convs.append(nn.Conv2d(channels, channels, 1)) + if len(convs) > 1: + convs = nn.Sequential(*convs) + else: + convs = convs[0] + return convs + + def forward(self, query_feats, key_feats): + """Forward function.""" + batch_size = query_feats.size(0) + query = self.query_project(query_feats) + if self.query_downsample is not None: + query = self.query_downsample(query) + query = query.reshape(*query.shape[:2], -1) + query = query.permute(0, 2, 1).contiguous() + + key = self.key_project(key_feats) + value = self.value_project(key_feats) + if self.key_downsample is not None: + key = self.key_downsample(key) + value = self.key_downsample(value) + key = key.reshape(*key.shape[:2], -1) + value = value.reshape(*value.shape[:2], -1) + value = value.permute(0, 2, 1).contiguous() + + sim_map = torch.matmul(query, key) + if self.matmul_norm: + sim_map = (self.channels**-.5) * sim_map + sim_map = F.softmax(sim_map, dim=-1) + + context = torch.matmul(sim_map, value) + context = context.permute(0, 2, 1).contiguous() + context = context.reshape(batch_size, -1, *query_feats.shape[2:]) + if self.out_project is not None: + context = self.out_project(context) + return context diff --git a/third-party/InterFormer/mmseg/models/utils/shape_convert.py b/third-party/InterFormer/mmseg/models/utils/shape_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..cce1e220b645d4b02df1ec2d9ed3137c8acba707 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/shape_convert.py @@ -0,0 +1,107 @@ +# Copyright (c) OpenMMLab. All rights reserved. +def nlc_to_nchw(x, hw_shape): + """Convert [N, L, C] shape tensor to [N, C, H, W] shape tensor. + + Args: + x (Tensor): The input tensor of shape [N, L, C] before conversion. + hw_shape (Sequence[int]): The height and width of output feature map. + + Returns: + Tensor: The output tensor of shape [N, C, H, W] after conversion. + """ + H, W = hw_shape + assert len(x.shape) == 3 + B, L, C = x.shape + assert L == H * W, 'The seq_len doesn\'t match H, W' + return x.transpose(1, 2).reshape(B, C, H, W) + + +def nchw_to_nlc(x): + """Flatten [N, C, H, W] shape tensor to [N, L, C] shape tensor. + + Args: + x (Tensor): The input tensor of shape [N, C, H, W] before conversion. + + Returns: + Tensor: The output tensor of shape [N, L, C] after conversion. + """ + assert len(x.shape) == 4 + return x.flatten(2).transpose(1, 2).contiguous() + + +def nchw2nlc2nchw(module, x, contiguous=False, **kwargs): + """Flatten [N, C, H, W] shape tensor `x` to [N, L, C] shape tensor. Use the + reshaped tensor as the input of `module`, and the convert the output of + `module`, whose shape is. + + [N, L, C], to [N, C, H, W]. + + Args: + module (Callable): A callable object the takes a tensor + with shape [N, L, C] as input. + x (Tensor): The input tensor of shape [N, C, H, W]. + contiguous: + contiguous (Bool): Whether to make the tensor contiguous + after each shape transform. + + Returns: + Tensor: The output tensor of shape [N, C, H, W]. + + Example: + >>> import torch + >>> import torch.nn as nn + >>> norm = nn.LayerNorm(4) + >>> feature_map = torch.rand(4, 4, 5, 5) + >>> output = nchw2nlc2nchw(norm, feature_map) + """ + B, C, H, W = x.shape + if not contiguous: + x = x.flatten(2).transpose(1, 2) + x = module(x, **kwargs) + x = x.transpose(1, 2).reshape(B, C, H, W) + else: + x = x.flatten(2).transpose(1, 2).contiguous() + x = module(x, **kwargs) + x = x.transpose(1, 2).reshape(B, C, H, W).contiguous() + return x + + +def nlc2nchw2nlc(module, x, hw_shape, contiguous=False, **kwargs): + """Convert [N, L, C] shape tensor `x` to [N, C, H, W] shape tensor. Use the + reshaped tensor as the input of `module`, and convert the output of + `module`, whose shape is. + + [N, C, H, W], to [N, L, C]. + + Args: + module (Callable): A callable object the takes a tensor + with shape [N, C, H, W] as input. + x (Tensor): The input tensor of shape [N, L, C]. + hw_shape: (Sequence[int]): The height and width of the + feature map with shape [N, C, H, W]. + contiguous (Bool): Whether to make the tensor contiguous + after each shape transform. + + Returns: + Tensor: The output tensor of shape [N, L, C]. + + Example: + >>> import torch + >>> import torch.nn as nn + >>> conv = nn.Conv2d(16, 16, 3, 1, 1) + >>> feature_map = torch.rand(4, 25, 16) + >>> output = nlc2nchw2nlc(conv, feature_map, (5, 5)) + """ + H, W = hw_shape + assert len(x.shape) == 3 + B, L, C = x.shape + assert L == H * W, 'The seq_len doesn\'t match H, W' + if not contiguous: + x = x.transpose(1, 2).reshape(B, C, H, W) + x = module(x, **kwargs) + x = x.flatten(2).transpose(1, 2) + else: + x = x.transpose(1, 2).reshape(B, C, H, W).contiguous() + x = module(x, **kwargs) + x = x.flatten(2).transpose(1, 2).contiguous() + return x diff --git a/third-party/InterFormer/mmseg/models/utils/up_conv_block.py b/third-party/InterFormer/mmseg/models/utils/up_conv_block.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa3b598de96d53c169232d9c89ac458f6921e8d --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/up_conv_block.py @@ -0,0 +1,102 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, build_upsample_layer + + +class UpConvBlock(nn.Module): + """Upsample convolution block in decoder for UNet. + + This upsample convolution block consists of one upsample module + followed by one convolution block. The upsample module expands the + high-level low-resolution feature map and the convolution block fuses + the upsampled high-level low-resolution feature map and the low-level + high-resolution feature map from encoder. + + Args: + conv_block (nn.Sequential): Sequential of convolutional layers. + in_channels (int): Number of input channels of the high-level + skip_channels (int): Number of input channels of the low-level + high-resolution feature map from encoder. + out_channels (int): Number of output channels. + num_convs (int): Number of convolutional layers in the conv_block. + Default: 2. + stride (int): Stride of convolutional layer in conv_block. Default: 1. + dilation (int): Dilation rate of convolutional layer in conv_block. + Default: 1. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + conv_cfg (dict | None): Config dict for convolution layer. + Default: None. + norm_cfg (dict | None): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict | None): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU'). + upsample_cfg (dict): The upsample config of the upsample module in + decoder. Default: dict(type='InterpConv'). If the size of + high-level feature map is the same as that of skip feature map + (low-level feature map from encoder), it does not need upsample the + high-level feature map and the upsample_cfg is None. + dcn (bool): Use deformable convolution in convolutional layer or not. + Default: None. + plugins (dict): plugins for convolutional layers. Default: None. + """ + + def __init__(self, + conv_block, + in_channels, + skip_channels, + out_channels, + num_convs=2, + stride=1, + dilation=1, + with_cp=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + upsample_cfg=dict(type='InterpConv'), + dcn=None, + plugins=None): + super().__init__() + assert dcn is None, 'Not implemented yet.' + assert plugins is None, 'Not implemented yet.' + + self.conv_block = conv_block( + in_channels=2 * skip_channels, + out_channels=out_channels, + num_convs=num_convs, + stride=stride, + dilation=dilation, + with_cp=with_cp, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + dcn=None, + plugins=None) + if upsample_cfg is not None: + self.upsample = build_upsample_layer( + cfg=upsample_cfg, + in_channels=in_channels, + out_channels=skip_channels, + with_cp=with_cp, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + else: + self.upsample = ConvModule( + in_channels, + skip_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, skip, x): + """Forward function.""" + + x = self.upsample(x) + out = torch.cat([skip, x], dim=1) + out = self.conv_block(out) + + return out diff --git a/third-party/InterFormer/mmseg/models/utils/wrappers.py b/third-party/InterFormer/mmseg/models/utils/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..abbd0c029623b4f480a067e4b78adfec234ef8d0 --- /dev/null +++ b/third-party/InterFormer/mmseg/models/utils/wrappers.py @@ -0,0 +1,51 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch.nn as nn +import torch.nn.functional as F + + +def resize(input, + size=None, + scale_factor=None, + mode='nearest', + align_corners=None, + warning=True): + if warning: + if size is not None and align_corners: + input_h, input_w = tuple(int(x) for x in input.shape[2:]) + output_h, output_w = tuple(int(x) for x in size) + if output_h > input_h or output_w > output_h: + if ((output_h > 1 and output_w > 1 and input_h > 1 + and input_w > 1) and (output_h - 1) % (input_h - 1) + and (output_w - 1) % (input_w - 1)): + warnings.warn( + f'When align_corners={align_corners}, ' + 'the output would more aligned if ' + f'input size {(input_h, input_w)} is `x+1` and ' + f'out size {(output_h, output_w)} is `nx+1`') + return F.interpolate(input, size, scale_factor, mode, align_corners) + + +class Upsample(nn.Module): + + def __init__(self, + size=None, + scale_factor=None, + mode='nearest', + align_corners=None): + super().__init__() + self.size = size + if isinstance(scale_factor, tuple): + self.scale_factor = tuple(float(factor) for factor in scale_factor) + else: + self.scale_factor = float(scale_factor) if scale_factor else None + self.mode = mode + self.align_corners = align_corners + + def forward(self, x): + if not self.size: + size = [int(t * self.scale_factor) for t in x.shape[-2:]] + else: + size = self.size + return resize(x, size, None, self.mode, self.align_corners) diff --git a/third-party/InterFormer/mmseg/registry/__init__.py b/third-party/InterFormer/mmseg/registry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee514d1a2a2bdd54a0a9b017ec227160ee502be5 --- /dev/null +++ b/third-party/InterFormer/mmseg/registry/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .registry import (DATA_SAMPLERS, DATASETS, EVALUATOR, HOOKS, INFERENCERS, + LOG_PROCESSORS, LOOPS, METRICS, MODEL_WRAPPERS, MODELS, + OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS, OPTIMIZERS, + PARAM_SCHEDULERS, RUNNER_CONSTRUCTORS, RUNNERS, + TASK_UTILS, TRANSFORMS, VISBACKENDS, VISUALIZERS, + WEIGHT_INITIALIZERS) + +__all__ = [ + 'HOOKS', 'DATASETS', 'DATA_SAMPLERS', 'TRANSFORMS', 'MODELS', + 'WEIGHT_INITIALIZERS', 'OPTIMIZERS', 'OPTIM_WRAPPER_CONSTRUCTORS', + 'TASK_UTILS', 'PARAM_SCHEDULERS', 'METRICS', 'MODEL_WRAPPERS', + 'VISBACKENDS', 'VISUALIZERS', 'RUNNERS', 'RUNNER_CONSTRUCTORS', 'LOOPS', + 'EVALUATOR', 'LOG_PROCESSORS', 'OPTIM_WRAPPERS', 'INFERENCERS' +] diff --git a/third-party/InterFormer/mmseg/registry/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/registry/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0947432081db26154e2e11478b99688f2869e1f0 Binary files /dev/null and b/third-party/InterFormer/mmseg/registry/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/registry/__pycache__/registry.cpython-38.pyc b/third-party/InterFormer/mmseg/registry/__pycache__/registry.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daaa210119596af30e090344cdc7692c2cfe13f2 Binary files /dev/null and b/third-party/InterFormer/mmseg/registry/__pycache__/registry.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/registry/registry.py b/third-party/InterFormer/mmseg/registry/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..37b6a776095856c2fab0101b5b0ec8ed7e8fa8f2 --- /dev/null +++ b/third-party/InterFormer/mmseg/registry/registry.py @@ -0,0 +1,118 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""MMSegmentation provides 21 registry nodes to support using modules across +projects. Each node is a child of the root registry in MMEngine. + +More details can be found at +https://mmengine.readthedocs.io/en/latest/advanced_tutorials/registry.html. +""" + +from mmengine.registry import DATA_SAMPLERS as MMENGINE_DATA_SAMPLERS +from mmengine.registry import DATASETS as MMENGINE_DATASETS +from mmengine.registry import EVALUATOR as MMENGINE_EVALUATOR +from mmengine.registry import HOOKS as MMENGINE_HOOKS +from mmengine.registry import INFERENCERS as MMENGINE_INFERENCERS +from mmengine.registry import LOG_PROCESSORS as MMENGINE_LOG_PROCESSORS +from mmengine.registry import LOOPS as MMENGINE_LOOPS +from mmengine.registry import METRICS as MMENGINE_METRICS +from mmengine.registry import MODEL_WRAPPERS as MMENGINE_MODEL_WRAPPERS +from mmengine.registry import MODELS as MMENGINE_MODELS +from mmengine.registry import \ + OPTIM_WRAPPER_CONSTRUCTORS as MMENGINE_OPTIM_WRAPPER_CONSTRUCTORS +from mmengine.registry import OPTIM_WRAPPERS as MMENGINE_OPTIM_WRAPPERS +from mmengine.registry import OPTIMIZERS as MMENGINE_OPTIMIZERS +from mmengine.registry import PARAM_SCHEDULERS as MMENGINE_PARAM_SCHEDULERS +from mmengine.registry import \ + RUNNER_CONSTRUCTORS as MMENGINE_RUNNER_CONSTRUCTORS +from mmengine.registry import RUNNERS as MMENGINE_RUNNERS +from mmengine.registry import TASK_UTILS as MMENGINE_TASK_UTILS +from mmengine.registry import TRANSFORMS as MMENGINE_TRANSFORMS +from mmengine.registry import VISBACKENDS as MMENGINE_VISBACKENDS +from mmengine.registry import VISUALIZERS as MMENGINE_VISUALIZERS +from mmengine.registry import \ + WEIGHT_INITIALIZERS as MMENGINE_WEIGHT_INITIALIZERS +from mmengine.registry import Registry + +# manage all kinds of runners like `EpochBasedRunner` and `IterBasedRunner` +RUNNERS = Registry('runner', parent=MMENGINE_RUNNERS) +# manage runner constructors that define how to initialize runners +RUNNER_CONSTRUCTORS = Registry( + 'runner constructor', parent=MMENGINE_RUNNER_CONSTRUCTORS) +# manage all kinds of loops like `EpochBasedTrainLoop` +LOOPS = Registry('loop', parent=MMENGINE_LOOPS) +# manage all kinds of hooks like `CheckpointHook` +HOOKS = Registry( + 'hook', parent=MMENGINE_HOOKS, locations=['mmseg.engine.hooks']) + +# manage data-related modules +DATASETS = Registry( + 'dataset', parent=MMENGINE_DATASETS, locations=['mmseg.datasets']) +DATA_SAMPLERS = Registry('data sampler', parent=MMENGINE_DATA_SAMPLERS) +TRANSFORMS = Registry( + 'transform', + parent=MMENGINE_TRANSFORMS, + locations=['mmseg.datasets.transforms']) + +# mangage all kinds of modules inheriting `nn.Module` +MODELS = Registry('model', parent=MMENGINE_MODELS, locations=['mmseg.models']) +# mangage all kinds of model wrappers like 'MMDistributedDataParallel' +MODEL_WRAPPERS = Registry( + 'model_wrapper', + parent=MMENGINE_MODEL_WRAPPERS, + locations=['mmseg.models']) +# mangage all kinds of weight initialization modules like `Uniform` +WEIGHT_INITIALIZERS = Registry( + 'weight initializer', + parent=MMENGINE_WEIGHT_INITIALIZERS, + locations=['mmseg.models']) + +# mangage all kinds of optimizers like `SGD` and `Adam` +OPTIMIZERS = Registry( + 'optimizer', + parent=MMENGINE_OPTIMIZERS, + locations=['mmseg.engine.optimizers']) +# manage optimizer wrapper +OPTIM_WRAPPERS = Registry( + 'optim_wrapper', + parent=MMENGINE_OPTIM_WRAPPERS, + locations=['mmseg.engine.optimizers']) +# manage constructors that customize the optimization hyperparameters. +OPTIM_WRAPPER_CONSTRUCTORS = Registry( + 'optimizer wrapper constructor', + parent=MMENGINE_OPTIM_WRAPPER_CONSTRUCTORS, + locations=['mmseg.engine.optimizers']) +# mangage all kinds of parameter schedulers like `MultiStepLR` +PARAM_SCHEDULERS = Registry( + 'parameter scheduler', + parent=MMENGINE_PARAM_SCHEDULERS, + locations=['mmseg.engine.schedulers']) + +# manage all kinds of metrics +METRICS = Registry( + 'metric', parent=MMENGINE_METRICS, locations=['mmseg.evaluation']) +# manage evaluator +EVALUATOR = Registry( + 'evaluator', parent=MMENGINE_EVALUATOR, locations=['mmseg.evaluation']) + +# manage task-specific modules like ohem pixel sampler +TASK_UTILS = Registry( + 'task util', parent=MMENGINE_TASK_UTILS, locations=['mmseg.models']) + +# manage visualizer +VISUALIZERS = Registry( + 'visualizer', + parent=MMENGINE_VISUALIZERS, + locations=['mmseg.visualization']) +# manage visualizer backend +VISBACKENDS = Registry( + 'vis_backend', + parent=MMENGINE_VISBACKENDS, + locations=['mmseg.visualization']) + +# manage logprocessor +LOG_PROCESSORS = Registry( + 'log_processor', + parent=MMENGINE_LOG_PROCESSORS, + locations=['mmseg.visualization']) + +# manage inferencer +INFERENCERS = Registry('inferencer', parent=MMENGINE_INFERENCERS) diff --git a/third-party/InterFormer/mmseg/structures/__init__.py b/third-party/InterFormer/mmseg/structures/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63d118dca3ebcff30ca241f9378475bcce072627 --- /dev/null +++ b/third-party/InterFormer/mmseg/structures/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .sampler import BasePixelSampler, OHEMPixelSampler, build_pixel_sampler +from .seg_data_sample import SegDataSample + +__all__ = [ + 'SegDataSample', 'BasePixelSampler', 'OHEMPixelSampler', + 'build_pixel_sampler' +] diff --git a/third-party/InterFormer/mmseg/structures/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/structures/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaae3728fe7b5ec77e2d79ae091c87f869dff13c Binary files /dev/null and b/third-party/InterFormer/mmseg/structures/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-38.pyc b/third-party/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..093ffc399952185fa09a4843ce29f4d7335e700a Binary files /dev/null and b/third-party/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/structures/sampler/__init__.py b/third-party/InterFormer/mmseg/structures/sampler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91d762d1b4552b391ece046fa3d094409011bcec --- /dev/null +++ b/third-party/InterFormer/mmseg/structures/sampler/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .base_pixel_sampler import BasePixelSampler +from .builder import build_pixel_sampler +from .ohem_pixel_sampler import OHEMPixelSampler + +__all__ = ['build_pixel_sampler', 'BasePixelSampler', 'OHEMPixelSampler'] diff --git a/third-party/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3b1e5d406653a3ef25f80ccf46449d8f12c30cb Binary files /dev/null and b/third-party/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-38.pyc b/third-party/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50e08e76d210f63c953ea49ad7e091f95b704b11 Binary files /dev/null and b/third-party/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-38.pyc b/third-party/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0672a86d14d3c49c3c00845cdbf4c37d945fd8c7 Binary files /dev/null and b/third-party/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-38.pyc b/third-party/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cda913de0f1951a3f1321d349e34a2b7186cc705 Binary files /dev/null and b/third-party/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/structures/sampler/base_pixel_sampler.py b/third-party/InterFormer/mmseg/structures/sampler/base_pixel_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..03672cd478a2e464cc734ae92686c86f219da0a9 --- /dev/null +++ b/third-party/InterFormer/mmseg/structures/sampler/base_pixel_sampler.py @@ -0,0 +1,13 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from abc import ABCMeta, abstractmethod + + +class BasePixelSampler(metaclass=ABCMeta): + """Base class of pixel sampler.""" + + def __init__(self, **kwargs): + pass + + @abstractmethod + def sample(self, seg_logit, seg_label): + """Placeholder for sample function.""" diff --git a/third-party/InterFormer/mmseg/structures/sampler/builder.py b/third-party/InterFormer/mmseg/structures/sampler/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..48e14790264a3d4c4ff54d84e5bab67b1623a1df --- /dev/null +++ b/third-party/InterFormer/mmseg/structures/sampler/builder.py @@ -0,0 +1,14 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +from mmseg.registry import TASK_UTILS + +PIXEL_SAMPLERS = TASK_UTILS + + +def build_pixel_sampler(cfg, **default_args): + """Build pixel sampler for segmentation map.""" + warnings.warn( + '``build_pixel_sampler`` would be deprecated soon, please use ' + '``mmseg.registry.TASK_UTILS.build()`` ') + return TASK_UTILS.build(cfg, default_args=default_args) diff --git a/third-party/InterFormer/mmseg/structures/sampler/ohem_pixel_sampler.py b/third-party/InterFormer/mmseg/structures/sampler/ohem_pixel_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..a974273cab504be269e7f391e23a521b97bd8588 --- /dev/null +++ b/third-party/InterFormer/mmseg/structures/sampler/ohem_pixel_sampler.py @@ -0,0 +1,85 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .base_pixel_sampler import BasePixelSampler +from .builder import PIXEL_SAMPLERS + + +@PIXEL_SAMPLERS.register_module() +class OHEMPixelSampler(BasePixelSampler): + """Online Hard Example Mining Sampler for segmentation. + + Args: + context (nn.Module): The context of sampler, subclass of + :obj:`BaseDecodeHead`. + thresh (float, optional): The threshold for hard example selection. + Below which, are prediction with low confidence. If not + specified, the hard examples will be pixels of top ``min_kept`` + loss. Default: None. + min_kept (int, optional): The minimum number of predictions to keep. + Default: 100000. + """ + + def __init__(self, context, thresh=None, min_kept=100000): + super().__init__() + self.context = context + assert min_kept > 1 + self.thresh = thresh + self.min_kept = min_kept + + def sample(self, seg_logit, seg_label): + """Sample pixels that have high loss or with low prediction confidence. + + Args: + seg_logit (torch.Tensor): segmentation logits, shape (N, C, H, W) + seg_label (torch.Tensor): segmentation label, shape (N, 1, H, W) + + Returns: + torch.Tensor: segmentation weight, shape (N, H, W) + """ + with torch.no_grad(): + assert seg_logit.shape[2:] == seg_label.shape[2:] + assert seg_label.shape[1] == 1 + seg_label = seg_label.squeeze(1).long() + batch_kept = self.min_kept * seg_label.size(0) + valid_mask = seg_label != self.context.ignore_index + seg_weight = seg_logit.new_zeros(size=seg_label.size()) + valid_seg_weight = seg_weight[valid_mask] + if self.thresh is not None: + seg_prob = F.softmax(seg_logit, dim=1) + + tmp_seg_label = seg_label.clone().unsqueeze(1) + tmp_seg_label[tmp_seg_label == self.context.ignore_index] = 0 + seg_prob = seg_prob.gather(1, tmp_seg_label).squeeze(1) + sort_prob, sort_indices = seg_prob[valid_mask].sort() + + if sort_prob.numel() > 0: + min_threshold = sort_prob[min(batch_kept, + sort_prob.numel() - 1)] + else: + min_threshold = 0.0 + threshold = max(min_threshold, self.thresh) + valid_seg_weight[seg_prob[valid_mask] < threshold] = 1. + else: + if not isinstance(self.context.loss_decode, nn.ModuleList): + losses_decode = [self.context.loss_decode] + else: + losses_decode = self.context.loss_decode + losses = 0.0 + for loss_module in losses_decode: + losses += loss_module( + seg_logit, + seg_label, + weight=None, + ignore_index=self.context.ignore_index, + reduction_override='none') + + # faster than topk according to https://github.com/pytorch/pytorch/issues/22812 # noqa + _, sort_indices = losses[valid_mask].sort(descending=True) + valid_seg_weight[sort_indices[:batch_kept]] = 1. + + seg_weight[valid_mask] = valid_seg_weight + + return seg_weight diff --git a/third-party/InterFormer/mmseg/structures/seg_data_sample.py b/third-party/InterFormer/mmseg/structures/seg_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..ce68b5474330e2149d7d1c4de2d2406ae5b0345e --- /dev/null +++ b/third-party/InterFormer/mmseg/structures/seg_data_sample.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmengine.structures import BaseDataElement, PixelData + + +class SegDataSample(BaseDataElement): + """A data structure interface of MMSegmentation. They are used as + interfaces between different components. + + The attributes in ``SegDataSample`` are divided into several parts: + + - ``gt_sem_seg``(PixelData): Ground truth of semantic segmentation. + - ``pred_sem_seg``(PixelData): Prediction of semantic segmentation. + - ``seg_logits``(PixelData): Predicted logits of semantic segmentation. + + Examples: + >>> import torch + >>> import numpy as np + >>> from mmengine.structures import PixelData + >>> from mmseg.structures import SegDataSample + + >>> data_sample = SegDataSample() + >>> img_meta = dict(img_shape=(4, 4, 3), + ... pad_shape=(4, 4, 3)) + >>> gt_segmentations = PixelData(metainfo=img_meta) + >>> gt_segmentations.data = torch.randint(0, 2, (1, 4, 4)) + >>> data_sample.gt_sem_seg = gt_segmentations + >>> assert 'img_shape' in data_sample.gt_sem_seg.metainfo_keys() + >>> data_sample.gt_sem_seg.shape + (4, 4) + >>> print(data_sample) + + ) at 0x1c2aae44d60> + + >>> data_sample = SegDataSample() + >>> gt_sem_seg_data = dict(sem_seg=torch.rand(1, 4, 4)) + >>> gt_sem_seg = PixelData(**gt_sem_seg_data) + >>> data_sample.gt_sem_seg = gt_sem_seg + >>> assert 'gt_sem_seg' in data_sample + >>> assert 'sem_seg' in data_sample.gt_sem_seg + """ + + @property + def gt_sem_seg(self) -> PixelData: + return self._gt_sem_seg + + @gt_sem_seg.setter + def gt_sem_seg(self, value: PixelData) -> None: + self.set_field(value, '_gt_sem_seg', dtype=PixelData) + + @gt_sem_seg.deleter + def gt_sem_seg(self) -> None: + del self._gt_sem_seg + + @property + def pred_sem_seg(self) -> PixelData: + return self._pred_sem_seg + + @pred_sem_seg.setter + def pred_sem_seg(self, value: PixelData) -> None: + self.set_field(value, '_pred_sem_seg', dtype=PixelData) + + @pred_sem_seg.deleter + def pred_sem_seg(self) -> None: + del self._pred_sem_seg + + @property + def seg_logits(self) -> PixelData: + return self._seg_logits + + @seg_logits.setter + def seg_logits(self, value: PixelData) -> None: + self.set_field(value, '_seg_logits', dtype=PixelData) + + @seg_logits.deleter + def seg_logits(self) -> None: + del self._seg_logits diff --git a/third-party/InterFormer/mmseg/utils/__init__.py b/third-party/InterFormer/mmseg/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a2af58c6e0316d6f961df81160f3fc61a8a29e3 --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/__init__.py @@ -0,0 +1,70 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# yapf: disable +from .class_names import (ade_classes, ade_palette, bdd100k_classes, + bdd100k_palette, cityscapes_classes, + cityscapes_palette, cocostuff_classes, + cocostuff_palette, dataset_aliases, get_classes, + get_palette, isaid_classes, isaid_palette, + loveda_classes, loveda_palette, potsdam_classes, + potsdam_palette, stare_classes, stare_palette, + synapse_classes, synapse_palette, vaihingen_classes, + vaihingen_palette, voc_classes, voc_palette) +# yapf: enable +from .collect_env import collect_env +from .get_templates import get_predefined_templates +from .io import datafrombytes +from .misc import add_prefix, stack_batch +from .set_env import register_all_modules +from .tokenizer import tokenize +from .typing_utils import (ConfigType, ForwardResults, MultiConfig, + OptConfigType, OptMultiConfig, OptSampleList, + SampleList, TensorDict, TensorList) + +# isort: off +from .mask_classification import MatchMasks, seg_data_to_instance_data + +__all__ = [ + 'collect_env', + 'register_all_modules', + 'stack_batch', + 'add_prefix', + 'ConfigType', + 'OptConfigType', + 'MultiConfig', + 'OptMultiConfig', + 'SampleList', + 'OptSampleList', + 'TensorDict', + 'TensorList', + 'ForwardResults', + 'cityscapes_classes', + 'ade_classes', + 'voc_classes', + 'cocostuff_classes', + 'loveda_classes', + 'potsdam_classes', + 'vaihingen_classes', + 'isaid_classes', + 'stare_classes', + 'cityscapes_palette', + 'ade_palette', + 'voc_palette', + 'cocostuff_palette', + 'loveda_palette', + 'potsdam_palette', + 'vaihingen_palette', + 'isaid_palette', + 'stare_palette', + 'dataset_aliases', + 'get_classes', + 'get_palette', + 'datafrombytes', + 'synapse_palette', + 'synapse_classes', + 'get_predefined_templates', + 'tokenize', + 'seg_data_to_instance_data', + 'MatchMasks', + 'bdd100k_classes', + 'bdd100k_palette', +] diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bbb74281f672a20ed185d1ca262fbc1a81263c7 Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/class_names.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/class_names.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54733045a807af0b441fd2215655384c6678fb24 Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/class_names.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..883d09cb80aafea086851358de2d0a7c5ed899b6 Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..601d81ae230683f2c9262856c0d273abd2bfd681 Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/io.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/io.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b3a349ac63ab4e06b026d99d4a323e1fb7012b7 Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/io.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..408a1bca881e3b1a999cdd59ba824fd67fa49c1f Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/misc.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/misc.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d44213ffb07ef9ac41b61fd755202db5ec5a365f Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/misc.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/set_env.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/set_env.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e87dd522e41119cad5f9856d14085fc28a5103e3 Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/set_env.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d501605f44b1d7d68edafd9722333c04194d4a7a Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-38.pyc b/third-party/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c92d18d22b157286274fe0025745d348729b2c0 Binary files /dev/null and b/third-party/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/utils/bpe_simple_vocab_16e6.txt.gz b/third-party/InterFormer/mmseg/utils/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/third-party/InterFormer/mmseg/utils/class_names.py b/third-party/InterFormer/mmseg/utils/class_names.py new file mode 100644 index 0000000000000000000000000000000000000000..644e955966ce81fca6a82ffb0bd6d9781eae61bc --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/class_names.py @@ -0,0 +1,548 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmengine.utils import is_str + + +def cityscapes_classes(): + """Cityscapes class names for external use.""" + return [ + 'road', 'sidewalk', 'building', 'wall', 'fence', 'pole', + 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', + 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', + 'bicycle' + ] + + +def ade_classes(): + """ADE20K class names for external use.""" + return [ + 'wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ', + 'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', + 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', + 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mirror', 'rug', + 'field', 'armchair', 'seat', 'fence', 'desk', 'rock', 'wardrobe', + 'lamp', 'bathtub', 'railing', 'cushion', 'base', 'box', 'column', + 'signboard', 'chest of drawers', 'counter', 'sand', 'sink', + 'skyscraper', 'fireplace', 'refrigerator', 'grandstand', 'path', + 'stairs', 'runway', 'case', 'pool table', 'pillow', 'screen door', + 'stairway', 'river', 'bridge', 'bookcase', 'blind', 'coffee table', + 'toilet', 'flower', 'book', 'hill', 'bench', 'countertop', 'stove', + 'palm', 'kitchen island', 'computer', 'swivel chair', 'boat', 'bar', + 'arcade machine', 'hovel', 'bus', 'towel', 'light', 'truck', 'tower', + 'chandelier', 'awning', 'streetlight', 'booth', 'television receiver', + 'airplane', 'dirt track', 'apparel', 'pole', 'land', 'bannister', + 'escalator', 'ottoman', 'bottle', 'buffet', 'poster', 'stage', 'van', + 'ship', 'fountain', 'conveyer belt', 'canopy', 'washer', 'plaything', + 'swimming pool', 'stool', 'barrel', 'basket', 'waterfall', 'tent', + 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food', 'step', 'tank', + 'trade name', 'microwave', 'pot', 'animal', 'bicycle', 'lake', + 'dishwasher', 'screen', 'blanket', 'sculpture', 'hood', 'sconce', + 'vase', 'traffic light', 'tray', 'ashcan', 'fan', 'pier', 'crt screen', + 'plate', 'monitor', 'bulletin board', 'shower', 'radiator', 'glass', + 'clock', 'flag' + ] + + +def voc_classes(): + """Pascal VOC class names for external use.""" + return [ + 'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', + 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', + 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', + 'tvmonitor' + ] + + +def pcontext_classes(): + """Pascal Context class names for external use.""" + return [ + 'aeroplane', 'bag', 'bed', 'bedclothes', 'bench', 'bicycle', 'bird', + 'boat', 'book', 'bottle', 'building', 'bus', 'cabinet', 'car', 'cat', + 'ceiling', 'chair', 'cloth', 'computer', 'cow', 'cup', 'curtain', + 'dog', 'door', 'fence', 'floor', 'flower', 'food', 'grass', 'ground', + 'horse', 'keyboard', 'light', 'motorbike', 'mountain', 'mouse', + 'person', 'plate', 'platform', 'pottedplant', 'road', 'rock', 'sheep', + 'shelves', 'sidewalk', 'sign', 'sky', 'snow', 'sofa', 'table', 'track', + 'train', 'tree', 'truck', 'tvmonitor', 'wall', 'water', 'window', + 'wood' + ] + + +def cocostuff_classes(): + """CocoStuff class names for external use.""" + return [ + 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', + 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', + 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', + 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', + 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', + 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', + 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', + 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', + 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', + 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner', + 'blanket', 'branch', 'bridge', 'building-other', 'bush', 'cabinet', + 'cage', 'cardboard', 'carpet', 'ceiling-other', 'ceiling-tile', + 'cloth', 'clothes', 'clouds', 'counter', 'cupboard', 'curtain', + 'desk-stuff', 'dirt', 'door-stuff', 'fence', 'floor-marble', + 'floor-other', 'floor-stone', 'floor-tile', 'floor-wood', 'flower', + 'fog', 'food-other', 'fruit', 'furniture-other', 'grass', 'gravel', + 'ground-other', 'hill', 'house', 'leaves', 'light', 'mat', 'metal', + 'mirror-stuff', 'moss', 'mountain', 'mud', 'napkin', 'net', 'paper', + 'pavement', 'pillow', 'plant-other', 'plastic', 'platform', + 'playingfield', 'railing', 'railroad', 'river', 'road', 'rock', 'roof', + 'rug', 'salad', 'sand', 'sea', 'shelf', 'sky-other', 'skyscraper', + 'snow', 'solid-other', 'stairs', 'stone', 'straw', 'structural-other', + 'table', 'tent', 'textile-other', 'towel', 'tree', 'vegetable', + 'wall-brick', 'wall-concrete', 'wall-other', 'wall-panel', + 'wall-stone', 'wall-tile', 'wall-wood', 'water-other', 'waterdrops', + 'window-blind', 'window-other', 'wood' + ] + + +def loveda_classes(): + """LoveDA class names for external use.""" + return [ + 'background', 'building', 'road', 'water', 'barren', 'forest', + 'agricultural' + ] + + +def potsdam_classes(): + """Potsdam class names for external use.""" + return [ + 'impervious_surface', 'building', 'low_vegetation', 'tree', 'car', + 'clutter' + ] + + +def vaihingen_classes(): + """Vaihingen class names for external use.""" + return [ + 'impervious_surface', 'building', 'low_vegetation', 'tree', 'car', + 'clutter' + ] + + +def isaid_classes(): + """iSAID class names for external use.""" + return [ + 'background', 'ship', 'store_tank', 'baseball_diamond', 'tennis_court', + 'basketball_court', 'Ground_Track_Field', 'Bridge', 'Large_Vehicle', + 'Small_Vehicle', 'Helicopter', 'Swimming_pool', 'Roundabout', + 'Soccer_ball_field', 'plane', 'Harbor' + ] + + +def stare_classes(): + """stare class names for external use.""" + return ['background', 'vessel'] + + +def mapillary_v1_classes(): + """mapillary_v1 class names for external use.""" + return [ + 'Bird', 'Ground Animal', 'Curb', 'Fence', 'Guard Rail', 'Barrier', + 'Wall', 'Bike Lane', 'Crosswalk - Plain', 'Curb Cut', 'Parking', + 'Pedestrian Area', 'Rail Track', 'Road', 'Service Lane', 'Sidewalk', + 'Bridge', 'Building', 'Tunnel', 'Person', 'Bicyclist', 'Motorcyclist', + 'Other Rider', 'Lane Marking - Crosswalk', 'Lane Marking - General', + 'Mountain', 'Sand', 'Sky', 'Snow', 'Terrain', 'Vegetation', 'Water', + 'Banner', 'Bench', 'Bike Rack', 'Billboard', 'Catch Basin', + 'CCTV Camera', 'Fire Hydrant', 'Junction Box', 'Mailbox', 'Manhole', + 'Phone Booth', 'Pothole', 'Street Light', 'Pole', 'Traffic Sign Frame', + 'Utility Pole', 'Traffic Light', 'Traffic Sign (Back)', + 'Traffic Sign (Front)', 'Trash Can', 'Bicycle', 'Boat', 'Bus', 'Car', + 'Caravan', 'Motorcycle', 'On Rails', 'Other Vehicle', 'Trailer', + 'Truck', 'Wheeled Slow', 'Car Mount', 'Ego Vehicle', 'Unlabeled' + ] + + +def mapillary_v1_palette(): + """mapillary_v1_ palette for external use.""" + return [[165, 42, 42], [0, 192, 0], [196, 196, 196], [190, 153, 153], + [180, 165, 180], [90, 120, 150], [102, 102, 156], [128, 64, 255], + [140, 140, 200], [170, 170, 170], [250, 170, 160], [96, 96, 96], + [230, 150, 140], [128, 64, 128], [110, 110, 110], [244, 35, 232], + [150, 100, 100], [70, 70, 70], [150, 120, 90], [220, 20, 60], + [255, 0, 0], [255, 0, 100], [255, 0, 200], [200, 128, 128], + [255, 255, 255], [64, 170, 64], [230, 160, 50], [70, 130, 180], + [190, 255, 255], [152, 251, 152], [107, 142, 35], [0, 170, 30], + [255, 255, 128], [250, 0, 30], [100, 140, 180], [220, 220, 220], + [220, 128, 128], [222, 40, 40], [100, 170, 30], [40, 40, 40], + [33, 33, 33], [100, 128, 160], [142, 0, 0], [70, 100, 150], + [210, 170, 100], [153, 153, 153], [128, 128, 128], [0, 0, 80], + [250, 170, 30], [192, 192, 192], [220, 220, 0], [140, 140, 20], + [119, 11, 32], [150, 0, 255], [0, 60, 100], [0, 0, 142], + [0, 0, 90], [0, 0, 230], [0, 80, 100], [128, 64, 64], [0, 0, 110], + [0, 0, 70], [0, 0, 192], [32, 32, 32], [120, 10, 10], [0, 0, 0]] + + +def mapillary_v2_classes(): + """mapillary_v2 class names for external use.""" + return [ + 'Bird', 'Ground Animal', 'Ambiguous Barrier', 'Concrete Block', 'Curb', + 'Fence', 'Guard Rail', 'Barrier', 'Road Median', 'Road Side', + 'Lane Separator', 'Temporary Barrier', 'Wall', 'Bike Lane', + 'Crosswalk - Plain', 'Curb Cut', 'Driveway', 'Parking', + 'Parking Aisle', 'Pedestrian Area', 'Rail Track', 'Road', + 'Road Shoulder', 'Service Lane', 'Sidewalk', 'Traffic Island', + 'Bridge', 'Building', 'Garage', 'Tunnel', 'Person', 'Person Group', + 'Bicyclist', 'Motorcyclist', 'Other Rider', + 'Lane Marking - Dashed Line', 'Lane Marking - Straight Line', + 'Lane Marking - Zigzag Line', 'Lane Marking - Ambiguous', + 'Lane Marking - Arrow (Left)', 'Lane Marking - Arrow (Other)', + 'Lane Marking - Arrow (Right)', + 'Lane Marking - Arrow (Split Left or Straight)', + 'Lane Marking - Arrow (Split Right or Straight)', + 'Lane Marking - Arrow (Straight)', 'Lane Marking - Crosswalk', + 'Lane Marking - Give Way (Row)', 'Lane Marking - Give Way (Single)', + 'Lane Marking - Hatched (Chevron)', + 'Lane Marking - Hatched (Diagonal)', 'Lane Marking - Other', + 'Lane Marking - Stop Line', 'Lane Marking - Symbol (Bicycle)', + 'Lane Marking - Symbol (Other)', 'Lane Marking - Text', + 'Lane Marking (only) - Dashed Line', 'Lane Marking (only) - Crosswalk', + 'Lane Marking (only) - Other', 'Lane Marking (only) - Test', + 'Mountain', 'Sand', 'Sky', 'Snow', 'Terrain', 'Vegetation', 'Water', + 'Banner', 'Bench', 'Bike Rack', 'Catch Basin', 'CCTV Camera', + 'Fire Hydrant', 'Junction Box', 'Mailbox', 'Manhole', 'Parking Meter', + 'Phone Booth', 'Pothole', 'Signage - Advertisement', + 'Signage - Ambiguous', 'Signage - Back', 'Signage - Information', + 'Signage - Other', 'Signage - Store', 'Street Light', 'Pole', + 'Pole Group', 'Traffic Sign Frame', 'Utility Pole', 'Traffic Cone', + 'Traffic Light - General (Single)', 'Traffic Light - Pedestrians', + 'Traffic Light - General (Upright)', + 'Traffic Light - General (Horizontal)', 'Traffic Light - Cyclists', + 'Traffic Light - Other', 'Traffic Sign - Ambiguous', + 'Traffic Sign (Back)', 'Traffic Sign - Direction (Back)', + 'Traffic Sign - Direction (Front)', 'Traffic Sign (Front)', + 'Traffic Sign - Parking', 'Traffic Sign - Temporary (Back)', + 'Traffic Sign - Temporary (Front)', 'Trash Can', 'Bicycle', 'Boat', + 'Bus', 'Car', 'Caravan', 'Motorcycle', 'On Rails', 'Other Vehicle', + 'Trailer', 'Truck', 'Vehicle Group', 'Wheeled Slow', 'Water Valve', + 'Car Mount', 'Dynamic', 'Ego Vehicle', 'Ground', 'Static', 'Unlabeled' + ] + + +def mapillary_v2_palette(): + """mapillary_v2_ palette for external use.""" + return [[165, 42, 42], [0, 192, 0], [250, 170, 31], [250, 170, 32], + [196, 196, 196], [190, 153, 153], [180, 165, 180], [90, 120, 150], + [250, 170, 33], [250, 170, 34], [128, 128, 128], [250, 170, 35], + [102, 102, 156], [128, 64, 255], [140, 140, 200], [170, 170, 170], + [250, 170, 36], [250, 170, 160], [250, 170, 37], [96, 96, 96], + [230, 150, 140], [128, 64, 128], [110, 110, 110], [110, 110, 110], + [244, 35, 232], [128, 196, 128], [150, 100, 100], [70, 70, 70], + [150, 150, 150], [150, 120, 90], [220, 20, 60], [220, 20, 60], + [255, 0, 0], [255, 0, 100], [255, 0, 200], [255, 255, 255], + [255, 255, 255], [250, 170, 29], [250, 170, 28], [250, 170, 26], + [250, 170, 25], [250, 170, 24], [250, 170, 22], [250, 170, 21], + [250, 170, 20], [255, 255, 255], [250, 170, 19], [250, 170, 18], + [250, 170, 12], [250, 170, 11], [255, 255, 255], [255, 255, 255], + [250, 170, 16], [250, 170, 15], [250, 170, 15], [255, 255, 255], + [255, 255, 255], [255, 255, 255], [255, 255, 255], [64, 170, 64], + [230, 160, 50], [70, 130, 180], [190, 255, 255], [152, 251, 152], + [107, 142, 35], [0, 170, 30], [255, 255, 128], [250, 0, 30], + [100, 140, 180], [220, 128, 128], [222, 40, 40], [100, 170, 30], + [40, 40, 40], [33, 33, 33], [100, 128, 160], [20, 20, 255], + [142, 0, 0], [70, 100, 150], [250, 171, 30], [250, 172, 30], + [250, 173, 30], [250, 174, 30], [250, 175, 30], [250, 176, 30], + [210, 170, 100], [153, 153, 153], [153, 153, 153], [128, 128, 128], + [0, 0, 80], [210, 60, 60], [250, 170, 30], [250, 170, 30], + [250, 170, 30], [250, 170, 30], [250, 170, 30], [250, 170, 30], + [192, 192, 192], [192, 192, 192], [192, 192, 192], [220, 220, 0], + [220, 220, 0], [0, 0, 196], [192, 192, 192], [220, 220, 0], + [140, 140, 20], [119, 11, 32], [150, 0, 255], [0, 60, 100], + [0, 0, 142], [0, 0, 90], [0, 0, 230], [0, 80, 100], [128, 64, 64], + [0, 0, 110], [0, 0, 70], [0, 0, 142], [0, 0, 192], [170, 170, 170], + [32, 32, 32], [111, 74, 0], [120, 10, 10], [81, 0, 81], + [111, 111, 0], [0, 0, 0]] + + +def cityscapes_palette(): + """Cityscapes palette for external use.""" + return [[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156], + [190, 153, 153], [153, 153, 153], [250, 170, 30], [220, 220, 0], + [107, 142, 35], [152, 251, 152], [70, 130, 180], [220, 20, 60], + [255, 0, 0], [0, 0, 142], [0, 0, 70], [0, 60, 100], [0, 80, 100], + [0, 0, 230], [119, 11, 32]] + + +def ade_palette(): + """ADE20K palette for external use.""" + return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50], + [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], + [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7], + [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82], + [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3], + [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255], + [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220], + [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224], + [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255], + [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7], + [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153], + [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255], + [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0], + [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255], + [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255], + [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255], + [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0], + [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0], + [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255], + [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255], + [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20], + [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255], + [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255], + [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255], + [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0], + [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0], + [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255], + [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112], + [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160], + [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163], + [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0], + [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0], + [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255], + [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204], + [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255], + [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255], + [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194], + [102, 255, 0], [92, 0, 255]] + + +def voc_palette(): + """Pascal VOC palette for external use.""" + return [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], + [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], + [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], + [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], + [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128]] + + +def pcontext_palette(): + """Pascal Context palette for external use.""" + return [[180, 120, 120], [6, 230, 230], [80, 50, 50], [4, 200, 3], + [120, 120, 80], [140, 140, 140], [204, 5, 255], [230, 230, 230], + [4, 250, 7], [224, 5, 255], [235, 255, 7], [150, 5, 61], + [120, 120, 70], [8, 255, 51], [255, 6, 82], [143, 255, 140], + [204, 255, 4], [255, 51, 7], [204, 70, 3], [0, 102, 200], + [61, 230, 250], [255, 6, 51], [11, 102, 255], [255, 7, 71], + [255, 9, 224], [9, 7, 230], [220, 220, 220], [255, 9, 92], + [112, 9, 255], [8, 255, 214], [7, 255, 224], [255, 184, 6], + [10, 255, 71], [255, 41, 10], [7, 255, 255], [224, 255, 8], + [102, 8, 255], [255, 61, 6], [255, 194, 7], [255, 122, 8], + [0, 255, 20], [255, 8, 41], [255, 5, 153], [6, 51, 255], + [235, 12, 255], [160, 150, 20], [0, 163, 255], [140, 140, 140], + [250, 10, 15], [20, 255, 0], [31, 255, 0], [255, 31, 0], + [255, 224, 0], [153, 255, 0], [0, 0, 255], [255, 71, 0], + [0, 235, 255], [0, 173, 255], [31, 0, 255]] + + +def cocostuff_palette(): + """CocoStuff palette for external use.""" + return [[0, 192, 64], [0, 192, 64], [0, 64, 96], [128, 192, 192], + [0, 64, 64], [0, 192, 224], [0, 192, 192], [128, 192, 64], + [0, 192, 96], [128, 192, 64], [128, 32, 192], [0, 0, 224], + [0, 0, 64], [0, 160, 192], [128, 0, 96], [128, 0, 192], + [0, 32, 192], [128, 128, 224], [0, 0, 192], [128, 160, 192], + [128, 128, 0], [128, 0, 32], [128, 32, 0], [128, 0, 128], + [64, 128, 32], [0, 160, 0], [0, 0, 0], [192, 128, 160], [0, 32, 0], + [0, 128, 128], [64, 128, 160], [128, 160, 0], [0, 128, 0], + [192, 128, 32], [128, 96, 128], [0, 0, 128], [64, 0, 32], + [0, 224, 128], [128, 0, 0], [192, 0, 160], [0, 96, 128], + [128, 128, 128], [64, 0, 160], [128, 224, 128], [128, 128, 64], + [192, 0, 32], [128, 96, 0], [128, 0, 192], [0, 128, 32], + [64, 224, 0], [0, 0, 64], [128, 128, 160], [64, 96, 0], + [0, 128, 192], [0, 128, 160], [192, 224, 0], [0, 128, 64], + [128, 128, 32], [192, 32, 128], [0, 64, 192], [0, 0, 32], + [64, 160, 128], [128, 64, 64], [128, 0, 160], [64, 32, 128], + [128, 192, 192], [0, 0, 160], [192, 160, 128], [128, 192, 0], + [128, 0, 96], [192, 32, 0], [128, 64, 128], [64, 128, 96], + [64, 160, 0], [0, 64, 0], [192, 128, 224], [64, 32, 0], + [0, 192, 128], [64, 128, 224], [192, 160, 0], [0, 192, 0], + [192, 128, 96], [192, 96, 128], [0, 64, 128], [64, 0, 96], + [64, 224, 128], [128, 64, 0], [192, 0, 224], [64, 96, 128], + [128, 192, 128], [64, 0, 224], [192, 224, 128], [128, 192, 64], + [192, 0, 96], [192, 96, 0], [128, 64, 192], [0, 128, 96], + [0, 224, 0], [64, 64, 64], [128, 128, 224], [0, 96, 0], + [64, 192, 192], [0, 128, 224], [128, 224, 0], [64, 192, 64], + [128, 128, 96], [128, 32, 128], [64, 0, 192], [0, 64, 96], + [0, 160, 128], [192, 0, 64], [128, 64, 224], [0, 32, 128], + [192, 128, 192], [0, 64, 224], [128, 160, 128], [192, 128, 0], + [128, 64, 32], [128, 32, 64], [192, 0, 128], [64, 192, 32], + [0, 160, 64], [64, 0, 0], [192, 192, 160], [0, 32, 64], + [64, 128, 128], [64, 192, 160], [128, 160, 64], [64, 128, 0], + [192, 192, 32], [128, 96, 192], [64, 0, 128], [64, 64, 32], + [0, 224, 192], [192, 0, 0], [192, 64, 160], [0, 96, 192], + [192, 128, 128], [64, 64, 160], [128, 224, 192], [192, 128, 64], + [192, 64, 32], [128, 96, 64], [192, 0, 192], [0, 192, 32], + [64, 224, 64], [64, 0, 64], [128, 192, 160], [64, 96, 64], + [64, 128, 192], [0, 192, 160], [192, 224, 64], [64, 128, 64], + [128, 192, 32], [192, 32, 192], [64, 64, 192], [0, 64, 32], + [64, 160, 192], [192, 64, 64], [128, 64, 160], [64, 32, 192], + [192, 192, 192], [0, 64, 160], [192, 160, 192], [192, 192, 0], + [128, 64, 96], [192, 32, 64], [192, 64, 128], [64, 192, 96], + [64, 160, 64], [64, 64, 0]] + + +def loveda_palette(): + """LoveDA palette for external use.""" + return [[255, 255, 255], [255, 0, 0], [255, 255, 0], [0, 0, 255], + [159, 129, 183], [0, 255, 0], [255, 195, 128]] + + +def potsdam_palette(): + """Potsdam palette for external use.""" + return [[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0], + [255, 255, 0], [255, 0, 0]] + + +def vaihingen_palette(): + """Vaihingen palette for external use.""" + return [[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0], + [255, 255, 0], [255, 0, 0]] + + +def isaid_palette(): + """iSAID palette for external use.""" + return [[0, 0, 0], [0, 0, 63], [0, 63, 63], [0, 63, 0], [0, 63, 127], + [0, 63, 191], [0, 63, 255], [0, 127, 63], [0, 127, + 127], [0, 0, 127], + [0, 0, 191], [0, 0, 255], [0, 191, 127], [0, 127, 191], + [0, 127, 255], [0, 100, 155]] + + +def stare_palette(): + """STARE palette for external use.""" + return [[120, 120, 120], [6, 230, 230]] + + +def synapse_palette(): + """Synapse palette for external use.""" + return [[0, 0, 0], [0, 0, 255], [0, 255, 0], [255, 0, 0], [0, 255, 255], + [255, 0, 255], [255, 255, 0], [60, 255, 255], [240, 240, 240]] + + +def synapse_classes(): + """Synapse class names for external use.""" + return [ + 'background', 'aorta', 'gallbladder', 'left_kidney', 'right_kidney', + 'liver', 'pancreas', 'spleen', 'stomach' + ] + + +def lip_classes(): + """LIP class names for external use.""" + return [ + 'background', 'hat', 'hair', 'glove', 'sunglasses', 'upperclothes', + 'dress', 'coat', 'socks', 'pants', 'jumpsuits', 'scarf', 'skirt', + 'face', 'leftArm', 'rightArm', 'leftLeg', 'rightLeg', 'leftShoe', + 'rightShoe' + ] + + +def lip_palette(): + """LIP palette for external use.""" + return [ + 'Background', 'Hat', 'Hair', 'Glove', 'Sunglasses', 'UpperClothes', + 'Dress', 'Coat', 'Socks', 'Pants', 'Jumpsuits', 'Scarf', 'Skirt', + 'Face', 'Left-arm', 'Right-arm', 'Left-leg', 'Right-leg', 'Left-shoe', + 'Right-shoe' + ] + + +def bdd100k_classes(): + """BDD100K class names for external use(the class name is compatible with + Cityscapes ).""" + return [ + 'road', 'sidewalk', 'building', 'wall', 'fence', 'pole', + 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', + 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', + 'bicycle' + ] + + +def bdd100k_palette(): + """bdd100k palette for external use(same with cityscapes)""" + return [[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156], + [190, 153, 153], [153, 153, 153], [250, 170, 30], [220, 220, 0], + [107, 142, 35], [152, 251, 152], [70, 130, 180], [220, 20, 60], + [255, 0, 0], [0, 0, 142], [0, 0, 70], [0, 60, 100], [0, 80, 100], + [0, 0, 230], [119, 11, 32]] + + +def hsidrive_classes(): + """HSI Drive 2.0 class names for external use.""" + return [ + 'unlabelled', 'road', 'road marks', 'vegetation', 'painted metal', + 'sky', 'concrete', 'pedestrian', 'water', 'unpainted metal', 'glass' + ] + + +def hsidrive_palette(): + """HSI Drive 2.0 palette for external use.""" + return [[0, 0, 0], [77, 77, 77], [255, 255, 255], [0, 255, 0], [255, 0, 0], + [0, 0, 255], [102, 51, 0], [255, 255, 0], [0, 207, 250], + [255, 166, 0], [0, 204, 204]] + + +dataset_aliases = { + 'cityscapes': ['cityscapes'], + 'ade': ['ade', 'ade20k'], + 'voc': ['voc', 'pascal_voc', 'voc12', 'voc12aug'], + 'pcontext': ['pcontext', 'pascal_context', 'voc2010'], + 'loveda': ['loveda'], + 'potsdam': ['potsdam'], + 'vaihingen': ['vaihingen'], + 'cocostuff': [ + 'cocostuff', 'cocostuff10k', 'cocostuff164k', 'coco-stuff', + 'coco-stuff10k', 'coco-stuff164k', 'coco_stuff', 'coco_stuff10k', + 'coco_stuff164k' + ], + 'isaid': ['isaid', 'iSAID'], + 'stare': ['stare', 'STARE'], + 'lip': ['LIP', 'lip'], + 'mapillary_v1': ['mapillary_v1'], + 'mapillary_v2': ['mapillary_v2'], + 'bdd100k': ['bdd100k'], + 'hsidrive': [ + 'hsidrive', 'HSIDrive', 'HSI-Drive', 'hsidrive20', 'HSIDrive20', + 'HSI-Drive20' + ] +} + + +def get_classes(dataset): + """Get class names of a dataset.""" + alias2name = {} + for name, aliases in dataset_aliases.items(): + for alias in aliases: + alias2name[alias] = name + + if is_str(dataset): + if dataset in alias2name: + labels = eval(alias2name[dataset] + '_classes()') + else: + raise ValueError(f'Unrecognized dataset: {dataset}') + else: + raise TypeError(f'dataset must a str, but got {type(dataset)}') + return labels + + +def get_palette(dataset): + """Get class palette (RGB) of a dataset.""" + alias2name = {} + for name, aliases in dataset_aliases.items(): + for alias in aliases: + alias2name[alias] = name + + if is_str(dataset): + if dataset in alias2name: + labels = eval(alias2name[dataset] + '_palette()') + else: + raise ValueError(f'Unrecognized dataset: {dataset}') + else: + raise TypeError(f'dataset must a str, but got {type(dataset)}') + return labels diff --git a/third-party/InterFormer/mmseg/utils/collect_env.py b/third-party/InterFormer/mmseg/utils/collect_env.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d6ea290283e3af2f29475f82d225072cf39d99 --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/collect_env.py @@ -0,0 +1,18 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmengine.utils import get_git_hash +from mmengine.utils.dl_utils import collect_env as collect_base_env + +import mmseg + + +def collect_env(): + """Collect the information of the running environments.""" + env_info = collect_base_env() + env_info['MMSegmentation'] = f'{mmseg.__version__}+{get_git_hash()[:7]}' + + return env_info + + +if __name__ == '__main__': + for name, val in collect_env().items(): + print(f'{name}: {val}') diff --git a/third-party/InterFormer/mmseg/utils/get_templates.py b/third-party/InterFormer/mmseg/utils/get_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9032ba96cbe750134676fe46fc26fb607779f5 --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/get_templates.py @@ -0,0 +1,109 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List + +PREDEFINED_TEMPLATES = { + 'imagenet': [ + 'a bad photo of a {}.', + 'a photo of many {}.', + 'a sculpture of a {}.', + 'a photo of the hard to see {}.', + 'a low resolution photo of the {}.', + 'a rendering of a {}.', + 'graffiti of a {}.', + 'a bad photo of the {}.', + 'a cropped photo of the {}.', + 'a tattoo of a {}.', + 'the embroidered {}.', + 'a photo of a hard to see {}.', + 'a bright photo of a {}.', + 'a photo of a clean {}.', + 'a photo of a dirty {}.', + 'a dark photo of the {}.', + 'a drawing of a {}.', + 'a photo of my {}.', + 'the plastic {}.', + 'a photo of the cool {}.', + 'a close-up photo of a {}.', + 'a black and white photo of the {}.', + 'a painting of the {}.', + 'a painting of a {}.', + 'a pixelated photo of the {}.', + 'a sculpture of the {}.', + 'a bright photo of the {}.', + 'a cropped photo of a {}.', + 'a plastic {}.', + 'a photo of the dirty {}.', + 'a jpeg corrupted photo of a {}.', + 'a blurry photo of the {}.', + 'a photo of the {}.', + 'a good photo of the {}.', + 'a rendering of the {}.', + 'a {} in a video game.', + 'a photo of one {}.', + 'a doodle of a {}.', + 'a close-up photo of the {}.', + 'a photo of a {}.', + 'the origami {}.', + 'the {} in a video game.', + 'a sketch of a {}.', + 'a doodle of the {}.', + 'a origami {}.', + 'a low resolution photo of a {}.', + 'the toy {}.', + 'a rendition of the {}.', + 'a photo of the clean {}.', + 'a photo of a large {}.', + 'a rendition of a {}.', + 'a photo of a nice {}.', + 'a photo of a weird {}.', + 'a blurry photo of a {}.', + 'a cartoon {}.', + 'art of a {}.', + 'a sketch of the {}.', + 'a embroidered {}.', + 'a pixelated photo of a {}.', + 'itap of the {}.', + 'a jpeg corrupted photo of the {}.', + 'a good photo of a {}.', + 'a plushie {}.', + 'a photo of the nice {}.', + 'a photo of the small {}.', + 'a photo of the weird {}.', + 'the cartoon {}.', + 'art of the {}.', + 'a drawing of the {}.', + 'a photo of the large {}.', + 'a black and white photo of a {}.', + 'the plushie {}.', + 'a dark photo of a {}.', + 'itap of a {}.', + 'graffiti of the {}.', + 'a toy {}.', + 'itap of my {}.', + 'a photo of a cool {}.', + 'a photo of a small {}.', + 'a tattoo of the {}.', + ], + 'vild': [ + 'a photo of a {}.', + 'This is a photo of a {}', + 'There is a {} in the scene', + 'There is the {} in the scene', + 'a photo of a {} in the scene', + 'a photo of a small {}.', + 'a photo of a medium {}.', + 'a photo of a large {}.', + 'This is a photo of a small {}.', + 'This is a photo of a medium {}.', + 'This is a photo of a large {}.', + 'There is a small {} in the scene.', + 'There is a medium {} in the scene.', + 'There is a large {} in the scene.', + ], +} + + +def get_predefined_templates(template_set_name: str) -> List[str]: + if template_set_name not in PREDEFINED_TEMPLATES: + raise ValueError(f'Template set {template_set_name} not found') + return PREDEFINED_TEMPLATES[template_set_name] diff --git a/third-party/InterFormer/mmseg/utils/io.py b/third-party/InterFormer/mmseg/utils/io.py new file mode 100644 index 0000000000000000000000000000000000000000..7029c3cddda02c89cbb50cee9f8b7e7fa57378d9 --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/io.py @@ -0,0 +1,42 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import gzip +import io +import pickle + +import cv2 +import numpy as np + + +def datafrombytes(content: bytes, backend: str = 'numpy') -> np.ndarray: + """Data decoding from bytes. + + Args: + content (bytes): The data bytes got from files or other streams. + backend (str): The data decoding backend type. Options are 'numpy', + 'nifti', 'cv2' and 'pickle'. Defaults to 'numpy'. + + Returns: + numpy.ndarray: Loaded data array. + """ + if backend == 'pickle': + data = pickle.loads(content) + else: + with io.BytesIO(content) as f: + if backend == 'nifti': + f = gzip.open(f) + try: + from nibabel import FileHolder, Nifti1Image + except ImportError: + print('nifti files io depends on nibabel, please run' + '`pip install nibabel` to install it') + fh = FileHolder(fileobj=f) + data = Nifti1Image.from_file_map({'header': fh, 'image': fh}) + data = Nifti1Image.from_bytes(data.to_bytes()).get_fdata() + elif backend == 'numpy': + data = np.load(f) + elif backend == 'cv2': + data = np.frombuffer(f.read(), dtype=np.uint8) + data = cv2.imdecode(data, cv2.IMREAD_UNCHANGED) + else: + raise ValueError + return data diff --git a/third-party/InterFormer/mmseg/utils/mask_classification.py b/third-party/InterFormer/mmseg/utils/mask_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..205d5259754abfe07e0d84ae0739cf08043815ff --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/mask_classification.py @@ -0,0 +1,205 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +from mmcv.ops import point_sample +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import TASK_UTILS +from mmseg.utils import ConfigType, SampleList + + +def seg_data_to_instance_data(ignore_index: int, + batch_data_samples: SampleList): + """Convert the paradigm of ground truth from semantic segmentation to + instance segmentation. + + Args: + ignore_index (int): The label index to be ignored. + batch_data_samples (List[SegDataSample]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + + Returns: + tuple[Tensor]: A tuple contains two lists. + - batch_gt_instances (List[InstanceData]): Batch of + gt_instance. It usually includes ``labels``, each is + unique ground truth label id of images, with + shape (num_gt, ) and ``masks``, each is ground truth + masks of each instances of a image, shape (num_gt, h, w). + - batch_img_metas (List[Dict]): List of image meta information. + """ + batch_gt_instances = [] + + for data_sample in batch_data_samples: + gt_sem_seg = data_sample.gt_sem_seg.data + classes = torch.unique( + gt_sem_seg, + sorted=False, + return_inverse=False, + return_counts=False) + + # remove ignored region + gt_labels = classes[classes != ignore_index] + + masks = [] + for class_id in gt_labels: + masks.append(gt_sem_seg == class_id) + + if len(masks) == 0: + gt_masks = torch.zeros( + (0, gt_sem_seg.shape[-2], + gt_sem_seg.shape[-1])).to(gt_sem_seg).long() + else: + gt_masks = torch.stack(masks).squeeze(1).long() + + instance_data = InstanceData(labels=gt_labels, masks=gt_masks) + batch_gt_instances.append(instance_data) + return batch_gt_instances + + +class MatchMasks: + """Match the predictions to category labels. + + Args: + num_points (int): the number of sampled points to compute cost. + num_queries (int): the number of prediction masks. + num_classes (int): the number of classes. + assigner (BaseAssigner): the assigner to compute matching. + """ + + def __init__(self, + num_points: int, + num_queries: int, + num_classes: int, + assigner: ConfigType = None): + assert assigner is not None, "\'assigner\' in decode_head.train_cfg" \ + 'cannot be None' + assert num_points > 0, 'num_points should be a positive integer.' + self.num_points = num_points + self.num_queries = num_queries + self.num_classes = num_classes + self.assigner = TASK_UTILS.build(assigner) + + def get_targets(self, cls_scores: List[Tensor], mask_preds: List[Tensor], + batch_gt_instances: List[InstanceData]) -> Tuple: + """Compute best mask matches for all images for a decoder layer. + + Args: + cls_scores (List[Tensor]): Mask score logits from a single + decoder layer for all images. Each with shape (num_queries, + cls_out_channels). + mask_preds (List[Tensor]): Mask logits from a single decoder + layer for all images. Each with shape (num_queries, h, w). + batch_gt_instances (List[InstanceData]): each contains + ``labels`` and ``masks``. + + Returns: + tuple: a tuple containing the following targets. + + - labels (List[Tensor]): Labels of all images.\ + Each with shape (num_queries, ). + - mask_targets (List[Tensor]): Mask targets of\ + all images. Each with shape (num_queries, h, w). + - mask_weights (List[Tensor]): Mask weights of\ + all images. Each with shape (num_queries, ). + - avg_factor (int): Average factor that is used to + average the loss. `avg_factor` is usually equal + to the number of positive priors. + """ + batch_size = cls_scores.shape[0] + results = dict({ + 'labels': [], + 'mask_targets': [], + 'mask_weights': [], + }) + for i in range(batch_size): + labels, mask_targets, mask_weights\ + = self._get_targets_single(cls_scores[i], + mask_preds[i], + batch_gt_instances[i]) + results['labels'].append(labels) + results['mask_targets'].append(mask_targets) + results['mask_weights'].append(mask_weights) + + # shape (batch_size, num_queries) + labels = torch.stack(results['labels'], dim=0) + # shape (batch_size, num_gts, h, w) + mask_targets = torch.cat(results['mask_targets'], dim=0) + # shape (batch_size, num_queries) + mask_weights = torch.stack(results['mask_weights'], dim=0) + + avg_factor = sum( + [len(gt_instances.labels) for gt_instances in batch_gt_instances]) + + res = (labels, mask_targets, mask_weights, avg_factor) + + return res + + def _get_targets_single(self, cls_score: Tensor, mask_pred: Tensor, + gt_instances: InstanceData) \ + -> Tuple[Tensor, Tensor, Tensor]: + """Compute a set of best mask matches for one image. + + Args: + cls_score (Tensor): Mask score logits from a single decoder layer + for one image. Shape (num_queries, cls_out_channels). + mask_pred (Tensor): Mask logits for a single decoder layer for one + image. Shape (num_queries, h, w). + gt_instances (:obj:`InstanceData`): It contains ``labels`` and + ``masks``. + + Returns: + tuple[Tensor]: A tuple containing the following for one image. + + - labels (Tensor): Labels of each image. \ + shape (num_queries, ). + - mask_targets (Tensor): Mask targets of each image. \ + shape (num_queries, h, w). + - mask_weights (Tensor): Mask weights of each image. \ + shape (num_queries, ). + """ + gt_labels = gt_instances.labels + gt_masks = gt_instances.masks + # when "gt_labels" is empty, classify all queries to background + if len(gt_labels) == 0: + labels = gt_labels.new_full((self.num_queries, ), + self.num_classes, + dtype=torch.long) + mask_targets = gt_labels + mask_weights = gt_labels.new_zeros((self.num_queries, )) + return labels, mask_targets, mask_weights + # sample points + num_queries = cls_score.shape[0] + num_gts = gt_labels.shape[0] + + point_coords = torch.rand((1, self.num_points, 2), + device=cls_score.device) + # shape (num_queries, num_points) + mask_points_pred = point_sample( + mask_pred.unsqueeze(1), point_coords.repeat(num_queries, 1, + 1)).squeeze(1) + # shape (num_gts, num_points) + gt_points_masks = point_sample( + gt_masks.unsqueeze(1).float(), point_coords.repeat(num_gts, 1, + 1)).squeeze(1) + + sampled_gt_instances = InstanceData( + labels=gt_labels, masks=gt_points_masks) + sampled_pred_instances = InstanceData( + scores=cls_score, masks=mask_points_pred) + # assign and sample + matched_quiery_inds, matched_label_inds = self.assigner.assign( + pred_instances=sampled_pred_instances, + gt_instances=sampled_gt_instances) + labels = gt_labels.new_full((self.num_queries, ), + self.num_classes, + dtype=torch.long) + labels[matched_quiery_inds] = gt_labels[matched_label_inds] + + mask_weights = gt_labels.new_zeros((self.num_queries, )) + mask_weights[matched_quiery_inds] = 1 + mask_targets = gt_masks[matched_label_inds] + + return labels, mask_targets, mask_weights diff --git a/third-party/InterFormer/mmseg/utils/misc.py b/third-party/InterFormer/mmseg/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc469e8320d375135846cfb0474a0fc8d9b15d0 --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/misc.py @@ -0,0 +1,128 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional, Union + +import numpy as np +import torch +import torch.nn.functional as F + +from .typing_utils import SampleList + + +def add_prefix(inputs, prefix): + """Add prefix for dict. + + Args: + inputs (dict): The input dict with str keys. + prefix (str): The prefix to add. + + Returns: + + dict: The dict with keys updated with ``prefix``. + """ + + outputs = dict() + for name, value in inputs.items(): + outputs[f'{prefix}.{name}'] = value + + return outputs + + +def stack_batch(inputs: List[torch.Tensor], + data_samples: Optional[SampleList] = None, + size: Optional[tuple] = None, + size_divisor: Optional[int] = None, + pad_val: Union[int, float] = 0, + seg_pad_val: Union[int, float] = 255) -> torch.Tensor: + """Stack multiple inputs to form a batch and pad the images and gt_sem_segs + to the max shape use the right bottom padding mode. + + Args: + inputs (List[Tensor]): The input multiple tensors. each is a + CHW 3D-tensor. + data_samples (list[:obj:`SegDataSample`]): The list of data samples. + It usually includes information such as `gt_sem_seg`. + size (tuple, optional): Fixed padding size. + size_divisor (int, optional): The divisor of padded size. + pad_val (int, float): The padding value. Defaults to 0 + seg_pad_val (int, float): The padding value. Defaults to 255 + + Returns: + Tensor: The 4D-tensor. + List[:obj:`SegDataSample`]: After the padding of the gt_seg_map. + """ + assert isinstance(inputs, list), \ + f'Expected input type to be list, but got {type(inputs)}' + assert len({tensor.ndim for tensor in inputs}) == 1, \ + f'Expected the dimensions of all inputs must be the same, ' \ + f'but got {[tensor.ndim for tensor in inputs]}' + assert inputs[0].ndim == 3, f'Expected tensor dimension to be 3, ' \ + f'but got {inputs[0].ndim}' + assert len({tensor.shape[0] for tensor in inputs}) == 1, \ + f'Expected the channels of all inputs must be the same, ' \ + f'but got {[tensor.shape[0] for tensor in inputs]}' + + # only one of size and size_divisor should be valid + assert (size is not None) ^ (size_divisor is not None), \ + 'only one of size and size_divisor should be valid' + + padded_inputs = [] + padded_samples = [] + inputs_sizes = [(img.shape[-2], img.shape[-1]) for img in inputs] + max_size = np.stack(inputs_sizes).max(0) + if size_divisor is not None and size_divisor > 1: + # the last two dims are H,W, both subject to divisibility requirement + max_size = (max_size + + (size_divisor - 1)) // size_divisor * size_divisor + + for i in range(len(inputs)): + tensor = inputs[i] + if size is not None: + width = max(size[-1] - tensor.shape[-1], 0) + height = max(size[-2] - tensor.shape[-2], 0) + # (padding_left, padding_right, padding_top, padding_bottom) + padding_size = (0, width, 0, height) + elif size_divisor is not None: + width = max(max_size[-1] - tensor.shape[-1], 0) + height = max(max_size[-2] - tensor.shape[-2], 0) + padding_size = (0, width, 0, height) + else: + padding_size = [0, 0, 0, 0] + + # pad img + pad_img = F.pad(tensor, padding_size, value=pad_val) + padded_inputs.append(pad_img) + # pad gt_sem_seg + if data_samples is not None: + data_sample = data_samples[i] + pad_shape = None + if 'gt_sem_seg' in data_sample: + gt_sem_seg = data_sample.gt_sem_seg.data + del data_sample.gt_sem_seg.data + data_sample.gt_sem_seg.data = F.pad( + gt_sem_seg, padding_size, value=seg_pad_val) + pad_shape = data_sample.gt_sem_seg.shape + if 'gt_edge_map' in data_sample: + gt_edge_map = data_sample.gt_edge_map.data + del data_sample.gt_edge_map.data + data_sample.gt_edge_map.data = F.pad( + gt_edge_map, padding_size, value=seg_pad_val) + pad_shape = data_sample.gt_edge_map.shape + if 'gt_depth_map' in data_sample: + gt_depth_map = data_sample.gt_depth_map.data + del data_sample.gt_depth_map.data + data_sample.gt_depth_map.data = F.pad( + gt_depth_map, padding_size, value=seg_pad_val) + pad_shape = data_sample.gt_depth_map.shape + data_sample.set_metainfo({ + 'img_shape': tensor.shape[-2:], + 'pad_shape': pad_shape, + 'padding_size': padding_size + }) + padded_samples.append(data_sample) + else: + padded_samples.append( + dict( + img_padding_size=padding_size, + pad_shape=pad_img.shape[-2:])) + + return torch.stack(padded_inputs, dim=0), padded_samples diff --git a/third-party/InterFormer/mmseg/utils/set_env.py b/third-party/InterFormer/mmseg/utils/set_env.py new file mode 100644 index 0000000000000000000000000000000000000000..c948950d62a7463295c1055a27a9a0ce881d9fad --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/set_env.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import datetime +import warnings + +from mmengine import DefaultScope + + +def register_all_modules(init_default_scope: bool = True) -> None: + """Register all modules in mmseg into the registries. + + Args: + init_default_scope (bool): Whether initialize the mmseg default scope. + When `init_default_scope=True`, the global default scope will be + set to `mmseg`, and all registries will build modules from mmseg's + registry node. To understand more about the registry, please refer + to https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/registry.md + Defaults to True. + """ # noqa + import mmseg.datasets # noqa: F401,F403 + import mmseg.engine # noqa: F401,F403 + import mmseg.evaluation # noqa: F401,F403 + import mmseg.models # noqa: F401,F403 + import mmseg.structures # noqa: F401,F403 + + if init_default_scope: + never_created = DefaultScope.get_current_instance() is None \ + or not DefaultScope.check_instance_created('mmseg') + if never_created: + DefaultScope.get_instance('mmseg', scope_name='mmseg') + return + current_scope = DefaultScope.get_current_instance() + if current_scope.scope_name != 'mmseg': + warnings.warn('The current default scope ' + f'"{current_scope.scope_name}" is not "mmseg", ' + '`register_all_modules` will force the current' + 'default scope to be "mmseg". If this is not ' + 'expected, please set `init_default_scope=False`.') + # avoid name conflict + new_instance_name = f'mmseg-{datetime.datetime.now()}' + DefaultScope.get_instance(new_instance_name, scope_name='mmseg') diff --git a/third-party/InterFormer/mmseg/utils/tokenizer.py b/third-party/InterFormer/mmseg/utils/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..d56f5fae602506a27b9ae8835415e8dea7b611b7 --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/tokenizer.py @@ -0,0 +1,240 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""CLIP tokenizer. + +Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright +(c) 2021 OpenAI. +""" +import gzip +import html +import os +from functools import lru_cache +from typing import List, Union + +import ftfy +import regex as re +import torch + +os.environ['TOKENIZERS_PARALLELISM'] = 'false' + + +@lru_cache() +def default_bpe(): + return os.path.join( + os.path.dirname(os.path.abspath(__file__)), + 'bpe_simple_vocab_16e6.txt.gz') + + +@lru_cache() +def bytes_to_unicode(): + """Returns list of utf-8 byte and a corresponding list of unicode strings. + + The reversible bpe codes work on unicode strings. This means you need a + large # of unicode characters in your vocab if you want to avoid UNKs. When + you're at something like a 10B token dataset you end up needing around 5K + for decent coverage. This is a significant percentage of your normal, say, + 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and + unicode strings. And avoids mapping to whitespace/control characters the + bpe code barfs on. + """ + bs = list(range(ord('!'), + ord('~') + 1)) + list(range( + ord('¡'), + ord('¬') + 1)) + list(range(ord('®'), + ord('ÿ') + 1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8 + n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + + Word is represented as tuple of symbols (symbols being variable-length + strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer: + + def __init__(self, bpe_path: str = default_bpe(), special_tokens=None): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode('utf-8').split('\n') + merges = merges[1:49152 - 256 - 2 + 1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v + '' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + if not special_tokens: + special_tokens = ['', ''] + else: + special_tokens = ['', '' + ] + special_tokens + vocab.extend(special_tokens) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {t: t for t in special_tokens} + special = '|'.join(special_tokens) + self.pat = re.compile( + special + + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", + re.IGNORECASE) + + self.vocab_size = len(self.encoder) + self.all_special_ids = [self.encoder[t] for t in special_tokens] + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + (token[-1] + '', ) + pairs = get_pairs(word) + + if not pairs: + return token + '' + + while True: + bigram = min( + pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: # noqa: E722, E261 + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word) - 1 and word[ + i + 1] == second: + new_word.append(first + second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] + for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] + for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode( + 'utf-8', errors='replace').replace('', ' ') + return text + + +_tokenizer = SimpleTokenizer() + + +def decode(output_ids: torch.Tensor): + output_ids = output_ids.cpu().numpy() + return _tokenizer.decode(output_ids) + + +def tokenize(texts: Union[str, List[str]], + context_length: int = 77) -> torch.LongTensor: + """Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, + shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder[''] + eot_token = _tokenizer.encoder[''] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] + for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, :len(tokens)] = torch.tensor(tokens) + + return result + + +class HFTokenizer: + """HuggingFace tokenizer wrapper.""" + + def __init__(self, tokenizer_name: str): + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + + def save_pretrained(self, dest): + self.tokenizer.save_pretrained(dest) + + def __call__(self, + texts: Union[str, List[str]], + context_length: int = 77) -> torch.Tensor: + # same cleaning as for default tokenizer, except lowercasing + # adding lower (for case-sensitive tokenizers) will make it + # more robust but less sensitive to nuance + if isinstance(texts, str): + texts = [texts] + texts = [whitespace_clean(basic_clean(text)) for text in texts] + input_ids = self.tokenizer( + texts, + return_tensors='pt', + max_length=context_length, + padding='max_length', + truncation=True, + ).input_ids + return input_ids diff --git a/third-party/InterFormer/mmseg/utils/typing_utils.py b/third-party/InterFormer/mmseg/utils/typing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fba7d3b92bba8301171d2a0fffadfabfcd112976 --- /dev/null +++ b/third-party/InterFormer/mmseg/utils/typing_utils.py @@ -0,0 +1,25 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Collecting some commonly used type hint in mmflow.""" +from typing import Dict, List, Optional, Sequence, Tuple, Union + +import torch +from mmengine.config import ConfigDict + +from mmseg.structures import SegDataSample + +# Type hint of config data +ConfigType = Union[ConfigDict, dict] +OptConfigType = Optional[ConfigType] +# Type hint of one or more config data +MultiConfig = Union[ConfigType, Sequence[ConfigType]] +OptMultiConfig = Optional[MultiConfig] + +SampleList = Sequence[SegDataSample] +OptSampleList = Optional[SampleList] + +# Type hint of Tensor +TensorDict = Dict[str, torch.Tensor] +TensorList = Sequence[torch.Tensor] + +ForwardResults = Union[Dict[str, torch.Tensor], List[SegDataSample], + Tuple[torch.Tensor], torch.Tensor] diff --git a/third-party/InterFormer/mmseg/version.py b/third-party/InterFormer/mmseg/version.py new file mode 100644 index 0000000000000000000000000000000000000000..b76bb4580ddfa0ba0ba13fa4896c49bac9cef65a --- /dev/null +++ b/third-party/InterFormer/mmseg/version.py @@ -0,0 +1,18 @@ +# Copyright (c) Open-MMLab. All rights reserved. + +__version__ = '1.2.2' + + +def parse_version_info(version_str): + version_info = [] + for x in version_str.split('.'): + if x.isdigit(): + version_info.append(int(x)) + elif x.find('rc') != -1: + patch_version = x.split('rc') + version_info.append(int(patch_version[0])) + version_info.append(f'rc{patch_version[1]}') + return tuple(version_info) + + +version_info = parse_version_info(__version__) diff --git a/third-party/InterFormer/mmseg/visualization/__init__.py b/third-party/InterFormer/mmseg/visualization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbb211e5243aafb4ab3d91f6a6f7ce0735b13a9 --- /dev/null +++ b/third-party/InterFormer/mmseg/visualization/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .local_visualizer import SegLocalVisualizer + +__all__ = ['SegLocalVisualizer'] diff --git a/third-party/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-38.pyc b/third-party/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4da7a1d3a990f5ae47676ad6ecfb972d3b7ad663 Binary files /dev/null and b/third-party/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-38.pyc b/third-party/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae56f96764a28334abe31887725344de6092fe13 Binary files /dev/null and b/third-party/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-38.pyc differ diff --git a/third-party/InterFormer/mmseg/visualization/local_visualizer.py b/third-party/InterFormer/mmseg/visualization/local_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ee3d652c7bbe9d93ca481fb7a7ed4bb976eec80d --- /dev/null +++ b/third-party/InterFormer/mmseg/visualization/local_visualizer.py @@ -0,0 +1,349 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Dict, List, Optional + +import cv2 +import mmcv +import numpy as np +import torch +from mmengine.dist import master_only +from mmengine.structures import PixelData +from mmengine.visualization import Visualizer + +from mmseg.registry import VISUALIZERS +from mmseg.structures import SegDataSample +from mmseg.utils import get_classes, get_palette + + +@VISUALIZERS.register_module() +class SegLocalVisualizer(Visualizer): + """Local Visualizer. + + Args: + name (str): Name of the instance. Defaults to 'visualizer'. + image (np.ndarray, optional): the origin image to draw. The format + should be RGB. Defaults to None. + vis_backends (list, optional): Visual backend config list. + Defaults to None. + save_dir (str, optional): Save file dir for all storage backends. + If it is None, the backend storage will not save any data. + classes (list, optional): Input classes for result rendering, as the + prediction of segmentation model is a segment map with label + indices, `classes` is a list which includes items responding to the + label indices. If classes is not defined, visualizer will take + `cityscapes` classes by default. Defaults to None. + palette (list, optional): Input palette for result rendering, which is + a list of color palette responding to the classes. Defaults to None. + dataset_name (str, optional): `Dataset name or alias `_ + visulizer will use the meta information of the dataset i.e. classes + and palette, but the `classes` and `palette` have higher priority. + Defaults to None. + alpha (int, float): The transparency of segmentation mask. + Defaults to 0.8. + + Examples: + >>> import numpy as np + >>> import torch + >>> from mmengine.structures import PixelData + >>> from mmseg.structures import SegDataSample + >>> from mmseg.visualization import SegLocalVisualizer + + >>> seg_local_visualizer = SegLocalVisualizer() + >>> image = np.random.randint(0, 256, + ... size=(10, 12, 3)).astype('uint8') + >>> gt_sem_seg_data = dict(data=torch.randint(0, 2, (1, 10, 12))) + >>> gt_sem_seg = PixelData(**gt_sem_seg_data) + >>> gt_seg_data_sample = SegDataSample() + >>> gt_seg_data_sample.gt_sem_seg = gt_sem_seg + >>> seg_local_visualizer.dataset_meta = dict( + >>> classes=('background', 'foreground'), + >>> palette=[[120, 120, 120], [6, 230, 230]]) + >>> seg_local_visualizer.add_datasample('visualizer_example', + ... image, gt_seg_data_sample) + >>> seg_local_visualizer.add_datasample( + ... 'visualizer_example', image, + ... gt_seg_data_sample, show=True) + """ # noqa + + def __init__(self, + name: str = 'visualizer', + image: Optional[np.ndarray] = None, + vis_backends: Optional[Dict] = None, + save_dir: Optional[str] = None, + classes: Optional[List] = None, + palette: Optional[List] = None, + dataset_name: Optional[str] = None, + alpha: float = 0.8, + **kwargs): + super().__init__(name, image, vis_backends, save_dir, **kwargs) + self.alpha: float = alpha + self.set_dataset_meta(palette, classes, dataset_name) + + def _get_center_loc(self, mask: np.ndarray) -> np.ndarray: + """Get semantic seg center coordinate. + + Args: + mask: np.ndarray: get from sem_seg + """ + loc = np.argwhere(mask == 1) + + loc_sort = np.array( + sorted(loc.tolist(), key=lambda row: (row[0], row[1]))) + y_list = loc_sort[:, 0] + unique, indices, counts = np.unique( + y_list, return_index=True, return_counts=True) + y_loc = unique[counts.argmax()] + y_most_freq_loc = loc[loc_sort[:, 0] == y_loc] + center_num = len(y_most_freq_loc) // 2 + x = y_most_freq_loc[center_num][1] + y = y_most_freq_loc[center_num][0] + return np.array([x, y]) + + def _draw_sem_seg(self, + image: np.ndarray, + sem_seg: PixelData, + classes: Optional[List], + palette: Optional[List], + with_labels: Optional[bool] = True) -> np.ndarray: + """Draw semantic seg of GT or prediction. + + Args: + image (np.ndarray): The image to draw. + sem_seg (:obj:`PixelData`): Data structure for pixel-level + annotations or predictions. + classes (list, optional): Input classes for result rendering, as + the prediction of segmentation model is a segment map with + label indices, `classes` is a list which includes items + responding to the label indices. If classes is not defined, + visualizer will take `cityscapes` classes by default. + Defaults to None. + palette (list, optional): Input palette for result rendering, which + is a list of color palette responding to the classes. + Defaults to None. + with_labels(bool, optional): Add semantic labels in visualization + result, Default to True. + + Returns: + np.ndarray: the drawn image which channel is RGB. + """ + num_classes = len(classes) + + sem_seg = sem_seg.cpu().data + ids = np.unique(sem_seg)[::-1] + legal_indices = ids < num_classes + ids = ids[legal_indices] + labels = np.array(ids, dtype=np.int64) + + colors = [palette[label] for label in labels] + + mask = np.zeros_like(image, dtype=np.uint8) + for label, color in zip(labels, colors): + mask[sem_seg[0] == label, :] = color + + if with_labels: + font = cv2.FONT_HERSHEY_SIMPLEX + # (0,1] to change the size of the text relative to the image + scale = 0.05 + fontScale = min(image.shape[0], image.shape[1]) / (25 / scale) + fontColor = (255, 255, 255) + if image.shape[0] < 300 or image.shape[1] < 300: + thickness = 1 + rectangleThickness = 1 + else: + thickness = 2 + rectangleThickness = 2 + lineType = 2 + + if isinstance(sem_seg[0], torch.Tensor): + masks = sem_seg[0].numpy() == labels[:, None, None] + else: + masks = sem_seg[0] == labels[:, None, None] + masks = masks.astype(np.uint8) + for mask_num in range(len(labels)): + classes_id = labels[mask_num] + classes_color = colors[mask_num] + loc = self._get_center_loc(masks[mask_num]) + text = classes[classes_id] + (label_width, label_height), baseline = cv2.getTextSize( + text, font, fontScale, thickness) + mask = cv2.rectangle(mask, loc, + (loc[0] + label_width + baseline, + loc[1] + label_height + baseline), + classes_color, -1) + mask = cv2.rectangle(mask, loc, + (loc[0] + label_width + baseline, + loc[1] + label_height + baseline), + (0, 0, 0), rectangleThickness) + mask = cv2.putText(mask, text, (loc[0], loc[1] + label_height), + font, fontScale, fontColor, thickness, + lineType) + color_seg = (image * (1 - self.alpha) + mask * self.alpha).astype( + np.uint8) + self.set_image(color_seg) + return color_seg + + def _draw_depth_map(self, image: np.ndarray, + depth_map: PixelData) -> np.ndarray: + """Draws a depth map on a given image. + + This function takes an image and a depth map as input, + renders the depth map, and concatenates it with the original image. + Finally, it updates the internal image state of the visualizer with + the concatenated result. + + Args: + image (np.ndarray): The original image where the depth map will + be drawn. The array should be in the format HxWx3 where H is + the height, W is the width. + + depth_map (PixelData): Depth map to be drawn. The depth map + should be in the form of a PixelData object. It will be + converted to a torch tensor if it is a numpy array. + + Returns: + np.ndarray: The concatenated image with the depth map drawn. + + Example: + >>> depth_map_data = PixelData(data=torch.rand(1, 10, 10)) + >>> image = np.random.randint(0, 256, + >>> size=(10, 10, 3)).astype('uint8') + >>> visualizer = SegLocalVisualizer() + >>> visualizer._draw_depth_map(image, depth_map_data) + """ + depth_map = depth_map.cpu().data + if isinstance(depth_map, np.ndarray): + depth_map = torch.from_numpy(depth_map) + if depth_map.ndim == 2: + depth_map = depth_map[None] + + depth_map = self.draw_featmap(depth_map, resize_shape=image.shape[:2]) + out_image = np.concatenate((image, depth_map), axis=0) + self.set_image(out_image) + return out_image + + def set_dataset_meta(self, + classes: Optional[List] = None, + palette: Optional[List] = None, + dataset_name: Optional[str] = None) -> None: + """Set meta information to visualizer. + + Args: + classes (list, optional): Input classes for result rendering, as + the prediction of segmentation model is a segment map with + label indices, `classes` is a list which includes items + responding to the label indices. If classes is not defined, + visualizer will take `cityscapes` classes by default. + Defaults to None. + palette (list, optional): Input palette for result rendering, which + is a list of color palette responding to the classes. + Defaults to None. + dataset_name (str, optional): `Dataset name or alias `_ + visulizer will use the meta information of the dataset i.e. + classes and palette, but the `classes` and `palette` have + higher priority. Defaults to None. + """ # noqa + # Set default value. When calling + # `SegLocalVisualizer().dataset_meta=xxx`, + # it will override the default value. + if dataset_name is None: + dataset_name = 'cityscapes' + classes = classes if classes else get_classes(dataset_name) + palette = palette if palette else get_palette(dataset_name) + assert len(classes) == len( + palette), 'The length of classes should be equal to palette' + self.dataset_meta: dict = {'classes': classes, 'palette': palette} + + @master_only + def add_datasample( + self, + name: str, + image: np.ndarray, + data_sample: Optional[SegDataSample] = None, + draw_gt: bool = True, + draw_pred: bool = True, + show: bool = False, + wait_time: float = 0, + # TODO: Supported in mmengine's Viusalizer. + out_file: Optional[str] = None, + step: int = 0, + with_labels: Optional[bool] = True) -> None: + """Draw datasample and save to all backends. + + - If GT and prediction are plotted at the same time, they are + displayed in a stitched image where the left image is the + ground truth and the right image is the prediction. + - If ``show`` is True, all storage backends are ignored, and + the images will be displayed in a local window. + - If ``out_file`` is specified, the drawn image will be + saved to ``out_file``. it is usually used when the display + is not available. + + Args: + name (str): The image identifier. + image (np.ndarray): The image to draw. + gt_sample (:obj:`SegDataSample`, optional): GT SegDataSample. + Defaults to None. + pred_sample (:obj:`SegDataSample`, optional): Prediction + SegDataSample. Defaults to None. + draw_gt (bool): Whether to draw GT SegDataSample. Default to True. + draw_pred (bool): Whether to draw Prediction SegDataSample. + Defaults to True. + show (bool): Whether to display the drawn image. Default to False. + wait_time (float): The interval of show (s). Defaults to 0. + out_file (str): Path to output file. Defaults to None. + step (int): Global step value to record. Defaults to 0. + with_labels(bool, optional): Add semantic labels in visualization + result, Defaults to True. + """ + classes = self.dataset_meta.get('classes', None) + palette = self.dataset_meta.get('palette', None) + + gt_img_data = None + pred_img_data = None + + if draw_gt and data_sample is not None: + if 'gt_sem_seg' in data_sample: + assert classes is not None, 'class information is ' \ + 'not provided when ' \ + 'visualizing semantic ' \ + 'segmentation results.' + gt_img_data = self._draw_sem_seg(image, data_sample.gt_sem_seg, + classes, palette, with_labels) + + if 'gt_depth_map' in data_sample: + gt_img_data = gt_img_data if gt_img_data is not None else image + gt_img_data = self._draw_depth_map(gt_img_data, + data_sample.gt_depth_map) + + if draw_pred and data_sample is not None: + + if 'pred_sem_seg' in data_sample: + + assert classes is not None, 'class information is ' \ + 'not provided when ' \ + 'visualizing semantic ' \ + 'segmentation results.' + pred_img_data = self._draw_sem_seg(image, + data_sample.pred_sem_seg, + classes, palette, + with_labels) + + if 'pred_depth_map' in data_sample: + pred_img_data = pred_img_data if pred_img_data is not None \ + else image + pred_img_data = self._draw_depth_map( + pred_img_data, data_sample.pred_depth_map) + + if gt_img_data is not None and pred_img_data is not None: + drawn_img = np.concatenate((gt_img_data, pred_img_data), axis=1) + elif gt_img_data is not None: + drawn_img = gt_img_data + else: + drawn_img = pred_img_data + + if show: + self.show(drawn_img, win_name=name, wait_time=wait_time) + + if out_file is not None: + mmcv.imwrite(mmcv.rgb2bgr(drawn_img), out_file) + else: + self.add_image(name, drawn_img, step) diff --git a/third-party/InterFormer/mmsegmentation.egg-info/PKG-INFO b/third-party/InterFormer/mmsegmentation.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..2f1aa279d6109c9cb12bd527c81ef7c93d3cedb7 --- /dev/null +++ b/third-party/InterFormer/mmsegmentation.egg-info/PKG-INFO @@ -0,0 +1,447 @@ +Metadata-Version: 2.1 +Name: mmsegmentation +Version: 1.2.2 +Summary: Open MMLab Semantic Segmentation Toolbox and Benchmark +Home-page: https://github.com/open-mmlab/mmsegmentation +Author: MMSegmentation Contributors +Author-email: openmmlab@gmail.com +License: Apache License 2.0 +Keywords: computer vision,semantic segmentation +Platform: UNKNOWN +Classifier: Development Status :: 4 - Beta +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Description-Content-Type: text/markdown +Provides-Extra: all +Provides-Extra: tests +Provides-Extra: optional +Provides-Extra: mim +Provides-Extra: multimodal +License-File: LICENSE + +
+ +
 
+
+ OpenMMLab website + + + HOT + + +      + OpenMMLab platform + + + TRY IT OUT + + +
+
 
+ +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/mmsegmentation)](https://pypi.org/project/mmsegmentation/) +[![PyPI](https://img.shields.io/pypi/v/mmsegmentation)](https://pypi.org/project/mmsegmentation) +[![docs](https://img.shields.io/badge/docs-latest-blue)](https://mmsegmentation.readthedocs.io/en/latest/) +[![badge](https://github.com/open-mmlab/mmsegmentation/workflows/build/badge.svg)](https://github.com/open-mmlab/mmsegmentation/actions) +[![codecov](https://codecov.io/gh/open-mmlab/mmsegmentation/branch/master/graph/badge.svg)](https://codecov.io/gh/open-mmlab/mmsegmentation) +[![license](https://img.shields.io/github/license/open-mmlab/mmsegmentation.svg)](https://github.com/open-mmlab/mmsegmentation/blob/main/LICENSE) +[![issue resolution](https://isitmaintained.com/badge/resolution/open-mmlab/mmsegmentation.svg)](https://github.com/open-mmlab/mmsegmentation/issues) +[![open issues](https://isitmaintained.com/badge/open/open-mmlab/mmsegmentation.svg)](https://github.com/open-mmlab/mmsegmentation/issues) +[![Open in OpenXLab](https://cdn-static.openxlab.org.cn/app-center/openxlab_demo.svg)](https://openxlab.org.cn/apps?search=mmseg) + +Documentation: + +English | [简体中文](README_zh-CN.md) + +
+ +
+ + + + + + + + + + + + + + + + + +
+ +## Introduction + +MMSegmentation is an open source semantic segmentation toolbox based on PyTorch. +It is a part of the OpenMMLab project. + +The [main](https://github.com/open-mmlab/mmsegmentation/tree/main) branch works with PyTorch 1.6+. + +### 🎉 Introducing MMSegmentation v1.0.0 🎉 + +We are thrilled to announce the official release of MMSegmentation's latest version! For this new release, the [main](https://github.com/open-mmlab/mmsegmentation/tree/main) branch serves as the primary branch, while the development branch is [dev-1.x](https://github.com/open-mmlab/mmsegmentation/tree/dev-1.x). The stable branch for the previous release remains as the [0.x](https://github.com/open-mmlab/mmsegmentation/tree/0.x) branch. Please note that the [master](https://github.com/open-mmlab/mmsegmentation/tree/master) branch will only be maintained for a limited time before being removed. We encourage you to be mindful of branch selection and updates during use. Thank you for your unwavering support and enthusiasm, and let's work together to make MMSegmentation even more robust and powerful! 💪 + +MMSegmentation v1.x brings remarkable improvements over the 0.x release, offering a more flexible and feature-packed experience. To utilize the new features in v1.x, we kindly invite you to consult our detailed [📚 migration guide](https://mmsegmentation.readthedocs.io/en/latest/migration/interface.html), which will help you seamlessly transition your projects. Your support is invaluable, and we eagerly await your feedback! + +![demo image](resources/seg_demo.gif) + +### Major features + +- **Unified Benchmark** + + We provide a unified benchmark toolbox for various semantic segmentation methods. + +- **Modular Design** + + We decompose the semantic segmentation framework into different components and one can easily construct a customized semantic segmentation framework by combining different modules. + +- **Support of multiple methods out of box** + + The toolbox directly supports popular and contemporary semantic segmentation frameworks, *e.g.* PSPNet, DeepLabV3, PSANet, DeepLabV3+, etc. + +- **High efficiency** + + The training speed is faster than or comparable to other codebases. + +## What's New + +v1.2.0 was released on 10/12/2023, from 1.1.0 to 1.2.0, we have added or updated the following features: + +### Highlights + +- Support for the open-vocabulary semantic segmentation algorithm [SAN](configs/san/README.md) + +- Support monocular depth estimation task, please refer to [VPD](configs/vpd/README.md) and [Adabins](projects/Adabins/README.md) for more details. + + ![depth estimation](https://github.com/open-mmlab/mmsegmentation/assets/15952744/07afd0e9-8ace-4a00-aa1e-5bf0ca92dcbc) + +- Add new projects: open-vocabulary semantic segmentation algorithm [CAT-Seg](projects/CAT-Seg/README.md), real-time semantic segmentation algofithm [PP-MobileSeg](projects/pp_mobileseg/README.md) + +## Installation + +Please refer to [get_started.md](docs/en/get_started.md#installation) for installation and [dataset_prepare.md](docs/en/user_guides/2_dataset_prepare.md#prepare-datasets) for dataset preparation. + +## Get Started + +Please see [Overview](docs/en/overview.md) for the general introduction of MMSegmentation. + +Please see [user guides](https://mmsegmentation.readthedocs.io/en/latest/user_guides/index.html#) for the basic usage of MMSegmentation. +There are also [advanced tutorials](https://mmsegmentation.readthedocs.io/en/latest/advanced_guides/index.html) for in-depth understanding of mmseg design and implementation . + +A Colab tutorial is also provided. You may preview the notebook [here](demo/MMSegmentation_Tutorial.ipynb) or directly [run](https://colab.research.google.com/github/open-mmlab/mmsegmentation/blob/main/demo/MMSegmentation_Tutorial.ipynb) on Colab. + +To migrate from MMSegmentation 0.x, please refer to [migration](docs/en/migration). + +## Tutorial + +
+ MMSegmentation Tutorials +
+ + + + + + + + + + + + + + + +
+ Get Started + + MMSeg Basic Tutorial + + MMSeg Detail Tutorial + + MMSeg Development Tutorial +
+ + + + + + + +
+ +## Benchmark and model zoo + +Results and models are available in the [model zoo](docs/en/model_zoo.md). + +
+ Overview +
+ + + + + + + + + + + + + + + + +
+ Supported backbones + + Supported methods + + Supported Head + + Supported datasets + + Other +
+ + + + + + + + + +
+ +Please refer to [FAQ](docs/en/notes/faq.md) for frequently asked questions. + +## Projects + +[Here](projects/README.md) are some implementations of SOTA models and solutions built on MMSegmentation, which are supported and maintained by community users. These projects demonstrate the best practices based on MMSegmentation for research and product development. We welcome and appreciate all the contributions to OpenMMLab ecosystem. + +## Contributing + +We appreciate all contributions to improve MMSegmentation. Please refer to [CONTRIBUTING.md](.github/CONTRIBUTING.md) for the contributing guideline. + +## Acknowledgement + +MMSegmentation is an open source project that welcome any contribution and feedback. +We wish that the toolbox and benchmark could serve the growing research +community by providing a flexible as well as standardized toolkit to reimplement existing methods +and develop their own new semantic segmentation methods. + +## Citation + +If you find this project useful in your research, please consider cite: + +```bibtex +@misc{mmseg2020, + title={{MMSegmentation}: OpenMMLab Semantic Segmentation Toolbox and Benchmark}, + author={MMSegmentation Contributors}, + howpublished = {\url{https://github.com/open-mmlab/mmsegmentation}}, + year={2020} +} +``` + +## License + +This project is released under the [Apache 2.0 license](LICENSE). + +## OpenMMLab Family + +- [MMEngine](https://github.com/open-mmlab/mmengine): OpenMMLab foundational library for training deep learning models. +- [MMCV](https://github.com/open-mmlab/mmcv): OpenMMLab foundational library for computer vision. +- [MMPreTrain](https://github.com/open-mmlab/mmpretrain): OpenMMLab pre-training toolbox and benchmark. +- [MMagic](https://github.com/open-mmlab/mmagic): Open**MM**Lab **A**dvanced, **G**enerative and **I**ntelligent **C**reation toolbox. +- [MMDetection](https://github.com/open-mmlab/mmdetection): OpenMMLab detection toolbox and benchmark. +- [MMYOLO](https://github.com/open-mmlab/mmyolo): OpenMMLab YOLO series toolbox and benchmark. +- [MMDetection3D](https://github.com/open-mmlab/mmdetection3d): OpenMMLab's next-generation platform for general 3D object detection. +- [MMRotate](https://github.com/open-mmlab/mmrotate): OpenMMLab rotated object detection toolbox and benchmark. +- [MMTracking](https://github.com/open-mmlab/mmtracking): OpenMMLab video perception toolbox and benchmark. +- [MMSegmentation](https://github.com/open-mmlab/mmsegmentation): OpenMMLab semantic segmentation toolbox and benchmark. +- [MMOCR](https://github.com/open-mmlab/mmocr): OpenMMLab text detection, recognition, and understanding toolbox. +- [MMPose](https://github.com/open-mmlab/mmpose): OpenMMLab pose estimation toolbox and benchmark. +- [MMHuman3D](https://github.com/open-mmlab/mmhuman3d): OpenMMLab 3D human parametric model toolbox and benchmark. +- [MMFewShot](https://github.com/open-mmlab/mmfewshot): OpenMMLab fewshot learning toolbox and benchmark. +- [MMAction2](https://github.com/open-mmlab/mmaction2): OpenMMLab's next-generation action understanding toolbox and benchmark. +- [MMFlow](https://github.com/open-mmlab/mmflow): OpenMMLab optical flow toolbox and benchmark. +- [MMDeploy](https://github.com/open-mmlab/mmdeploy): OpenMMLab Model Deployment Framework. +- [MMRazor](https://github.com/open-mmlab/mmrazor): OpenMMLab model compression toolbox and benchmark. +- [MIM](https://github.com/open-mmlab/mim): MIM installs OpenMMLab packages. +- [Playground](https://github.com/open-mmlab/playground): A central hub for gathering and showcasing amazing projects built upon OpenMMLab. + + diff --git a/third-party/InterFormer/mmsegmentation.egg-info/SOURCES.txt b/third-party/InterFormer/mmsegmentation.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..9595c1163a869f1f3815510c2fedc3b938ba2a22 --- /dev/null +++ b/third-party/InterFormer/mmsegmentation.egg-info/SOURCES.txt @@ -0,0 +1,1158 @@ +LICENSE +MANIFEST.in +README.md +setup.cfg +setup.py +mmseg/__init__.py +mmseg/version.py +mmseg/.mim/model-index.yml +mmseg/.mim/configs/_base_/default_runtime.py +mmseg/.mim/configs/_base_/datasets/ade20k.py +mmseg/.mim/configs/_base_/datasets/ade20k_640x640.py +mmseg/.mim/configs/_base_/datasets/bdd100k.py +mmseg/.mim/configs/_base_/datasets/chase_db1.py +mmseg/.mim/configs/_base_/datasets/cityscapes.py +mmseg/.mim/configs/_base_/datasets/cityscapes_1024x1024.py +mmseg/.mim/configs/_base_/datasets/cityscapes_768x768.py +mmseg/.mim/configs/_base_/datasets/cityscapes_769x769.py +mmseg/.mim/configs/_base_/datasets/cityscapes_832x832.py +mmseg/.mim/configs/_base_/datasets/coco-stuff10k.py +mmseg/.mim/configs/_base_/datasets/coco-stuff164k.py +mmseg/.mim/configs/_base_/datasets/drive.py +mmseg/.mim/configs/_base_/datasets/hrf.py +mmseg/.mim/configs/_base_/datasets/hsi_drive.py +mmseg/.mim/configs/_base_/datasets/isaid.py +mmseg/.mim/configs/_base_/datasets/levir_256x256.py +mmseg/.mim/configs/_base_/datasets/loveda.py +mmseg/.mim/configs/_base_/datasets/mapillary_v1.py +mmseg/.mim/configs/_base_/datasets/mapillary_v1_65.py +mmseg/.mim/configs/_base_/datasets/mapillary_v2.py +mmseg/.mim/configs/_base_/datasets/nyu.py +mmseg/.mim/configs/_base_/datasets/nyu_512x512.py +mmseg/.mim/configs/_base_/datasets/pascal_context.py +mmseg/.mim/configs/_base_/datasets/pascal_context_59.py +mmseg/.mim/configs/_base_/datasets/pascal_voc12.py +mmseg/.mim/configs/_base_/datasets/pascal_voc12_aug.py +mmseg/.mim/configs/_base_/datasets/potsdam.py +mmseg/.mim/configs/_base_/datasets/refuge.py +mmseg/.mim/configs/_base_/datasets/stare.py +mmseg/.mim/configs/_base_/datasets/synapse.py +mmseg/.mim/configs/_base_/datasets/vaihingen.py +mmseg/.mim/configs/_base_/models/ann_r50-d8.py +mmseg/.mim/configs/_base_/models/apcnet_r50-d8.py +mmseg/.mim/configs/_base_/models/bisenetv1_r18-d32.py +mmseg/.mim/configs/_base_/models/bisenetv2.py +mmseg/.mim/configs/_base_/models/ccnet_r50-d8.py +mmseg/.mim/configs/_base_/models/cgnet.py +mmseg/.mim/configs/_base_/models/danet_r50-d8.py +mmseg/.mim/configs/_base_/models/deeplabv3_r50-d8.py +mmseg/.mim/configs/_base_/models/deeplabv3_unet_s5-d16.py +mmseg/.mim/configs/_base_/models/deeplabv3plus_r50-d8.py +mmseg/.mim/configs/_base_/models/dmnet_r50-d8.py +mmseg/.mim/configs/_base_/models/dnl_r50-d8.py +mmseg/.mim/configs/_base_/models/dpt_vit-b16.py +mmseg/.mim/configs/_base_/models/emanet_r50-d8.py +mmseg/.mim/configs/_base_/models/encnet_r50-d8.py +mmseg/.mim/configs/_base_/models/erfnet_fcn.py +mmseg/.mim/configs/_base_/models/fast_scnn.py +mmseg/.mim/configs/_base_/models/fastfcn_r50-d32_jpu_psp.py +mmseg/.mim/configs/_base_/models/fcn_hr18.py +mmseg/.mim/configs/_base_/models/fcn_r50-d8.py +mmseg/.mim/configs/_base_/models/fcn_unet_s5-d16.py +mmseg/.mim/configs/_base_/models/fpn_poolformer_s12.py +mmseg/.mim/configs/_base_/models/fpn_r50.py +mmseg/.mim/configs/_base_/models/gcnet_r50-d8.py +mmseg/.mim/configs/_base_/models/icnet_r50-d8.py +mmseg/.mim/configs/_base_/models/isanet_r50-d8.py +mmseg/.mim/configs/_base_/models/lraspp_m-v3-d8.py +mmseg/.mim/configs/_base_/models/nonlocal_r50-d8.py +mmseg/.mim/configs/_base_/models/ocrnet_hr18.py +mmseg/.mim/configs/_base_/models/ocrnet_r50-d8.py +mmseg/.mim/configs/_base_/models/pointrend_r50.py +mmseg/.mim/configs/_base_/models/psanet_r50-d8.py +mmseg/.mim/configs/_base_/models/pspnet_r50-d8.py +mmseg/.mim/configs/_base_/models/pspnet_unet_s5-d16.py +mmseg/.mim/configs/_base_/models/san_vit-b16.py +mmseg/.mim/configs/_base_/models/segformer_mit-b0.py +mmseg/.mim/configs/_base_/models/segmenter_vit-b16_mask.py +mmseg/.mim/configs/_base_/models/setr_mla.py +mmseg/.mim/configs/_base_/models/setr_naive.py +mmseg/.mim/configs/_base_/models/setr_pup.py +mmseg/.mim/configs/_base_/models/stdc.py +mmseg/.mim/configs/_base_/models/twins_pcpvt-s_fpn.py +mmseg/.mim/configs/_base_/models/twins_pcpvt-s_upernet.py +mmseg/.mim/configs/_base_/models/upernet_beit.py +mmseg/.mim/configs/_base_/models/upernet_convnext.py +mmseg/.mim/configs/_base_/models/upernet_mae.py +mmseg/.mim/configs/_base_/models/upernet_r50.py +mmseg/.mim/configs/_base_/models/upernet_swin.py +mmseg/.mim/configs/_base_/models/upernet_vit-b16_ln_mln.py +mmseg/.mim/configs/_base_/models/vpd_sd.py +mmseg/.mim/configs/_base_/schedules/schedule_160k.py +mmseg/.mim/configs/_base_/schedules/schedule_20k.py +mmseg/.mim/configs/_base_/schedules/schedule_240k.py +mmseg/.mim/configs/_base_/schedules/schedule_25k.py +mmseg/.mim/configs/_base_/schedules/schedule_320k.py +mmseg/.mim/configs/_base_/schedules/schedule_40k.py +mmseg/.mim/configs/_base_/schedules/schedule_80k.py +mmseg/.mim/configs/ann/ann_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ann/ann_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/ann/ann_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/ann/ann_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/ann/ann_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/ann/ann_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/ann/ann_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/ann/ann_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/ann/ann_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ann/ann_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/ann/ann_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/ann/ann_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/ann/ann_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/ann/ann_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/ann/ann_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/ann/ann_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/ann/metafile.yaml +mmseg/.mim/configs/apcnet/apcnet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/apcnet/apcnet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/apcnet/apcnet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/apcnet/apcnet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/apcnet/apcnet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/apcnet/apcnet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/apcnet/apcnet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/apcnet/apcnet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/apcnet/apcnet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/apcnet/apcnet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/apcnet/apcnet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/apcnet/apcnet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/apcnet/metafile.yaml +mmseg/.mim/configs/beit/beit-base_upernet_8xb2-160k_ade20k-640x640.py +mmseg/.mim/configs/beit/beit-base_upernet_8xb2-160k_ade20k-640x640_ms.py +mmseg/.mim/configs/beit/beit-large_upernet_8xb1-amp-160k_ade20k-640x640.py +mmseg/.mim/configs/beit/beit-large_upernet_8xb1-amp-160k_ade20k-640x640_ms.py +mmseg/.mim/configs/beit/metafile.yaml +mmseg/.mim/configs/bisenetv1/bisenetv1_r101-d32-in1k-pre_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r101-d32_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r18-d32-in1k-pre_4xb4-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r18-d32-in1k-pre_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r18-d32-in1k-pre_4xb8-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r18-d32_4xb4-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r18-d32_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r50-d32-in1k-pre_4xb4-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r50-d32-in1k-pre_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r50-d32_4xb4-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv1/bisenetv1_r50-d32_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/bisenetv1/metafile.yaml +mmseg/.mim/configs/bisenetv2/bisenetv2_fcn_4xb4-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv2/bisenetv2_fcn_4xb4-amp-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv2/bisenetv2_fcn_4xb4-ohem-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv2/bisenetv2_fcn_4xb8-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/bisenetv2/metafile.yaml +mmseg/.mim/configs/ccnet/ccnet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ccnet/ccnet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/ccnet/ccnet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/ccnet/ccnet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/ccnet/ccnet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/ccnet/ccnet_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/ccnet/ccnet_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/ccnet/ccnet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/ccnet/ccnet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ccnet/ccnet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/ccnet/ccnet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/ccnet/ccnet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/ccnet/ccnet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/ccnet/ccnet_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/ccnet/ccnet_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/ccnet/ccnet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/ccnet/metafile.yaml +mmseg/.mim/configs/cgnet/cgnet_fcn_4xb4-60k_cityscapes-680x680.py +mmseg/.mim/configs/cgnet/cgnet_fcn_4xb8-60k_cityscapes-512x1024.py +mmseg/.mim/configs/cgnet/metafile.yaml +mmseg/.mim/configs/convnext/convnext-base_upernet_8xb2-amp-160k_ade20k-512x512.py +mmseg/.mim/configs/convnext/convnext-base_upernet_8xb2-amp-160k_ade20k-640x640.py +mmseg/.mim/configs/convnext/convnext-large_upernet_8xb2-amp-160k_ade20k-640x640.py +mmseg/.mim/configs/convnext/convnext-small_upernet_8xb2-amp-160k_ade20k-512x512.py +mmseg/.mim/configs/convnext/convnext-tiny_upernet_8xb2-amp-160k_ade20k-512x512.py +mmseg/.mim/configs/convnext/convnext-xlarge_upernet_8xb2-amp-160k_ade20k-640x640.py +mmseg/.mim/configs/convnext/metafile.yaml +mmseg/.mim/configs/danet/danet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/danet/danet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/danet/danet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/danet/danet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/danet/danet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/danet/danet_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/danet/danet_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/danet/danet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/danet/danet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/danet/danet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/danet/danet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/danet/danet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/danet/danet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/danet/danet_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/danet/danet_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/danet/danet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/danet/metafile.yaml +mmseg/.mim/configs/ddrnet/ddrnet_23-slim_in1k-pre_2xb6-120k_cityscapes-1024x1024.py +mmseg/.mim/configs/ddrnet/ddrnet_23_in1k-pre_2xb6-120k_cityscapes-1024x1024.py +mmseg/.mim/configs/ddrnet/metafile.yaml +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d16-mg124_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d16-mg124_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb2-amp-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-20k_coco-stuff10k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-320k_coco-stuff164k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-40k_coco-stuff10k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-80k_coco-stuff164k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101-d8_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r101b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r18-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r18-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r18b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r18b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-20k_coco-stuff10k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-320k_coco-stuff164k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-40k_coco-stuff10k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-80k_coco-stuff164k-512x512.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50-d8_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3/deeplabv3_r50b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3/metafile.yaml +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d16-mg124_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d16-mg124_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb2-amp-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101-d8_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r101b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r18-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r18-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r18-d8_4xb4-80k_isaid-896x896.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r18-d8_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r18-d8_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r18-d8_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r18b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r18b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb2-300k_mapillay_v1_65-1280x1280.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-80k_isaid-896x896.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/deeplabv3plus/deeplabv3plus_r50b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/deeplabv3plus/metafile.yaml +mmseg/.mim/configs/dmnet/dmnet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/dmnet/dmnet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/dmnet/dmnet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/dmnet/dmnet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/dmnet/dmnet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/dmnet/dmnet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/dmnet/dmnet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/dmnet/dmnet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/dmnet/dmnet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/dmnet/dmnet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/dmnet/dmnet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/dmnet/dmnet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/dmnet/metafile.yaml +mmseg/.mim/configs/dnlnet/dnl_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/dnlnet/dnl_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/dnlnet/dnl_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/dnlnet/dnl_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/dnlnet/dnl_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/dnlnet/dnl_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/dnlnet/dnl_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/dnlnet/dnl_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/dnlnet/dnl_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/dnlnet/dnl_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/dnlnet/dnl_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/dnlnet/dnl_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/dnlnet/metafile.yaml +mmseg/.mim/configs/dpt/dpt_vit-b16_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/dpt/metafile.yaml +mmseg/.mim/configs/dsdl/cityscapes.py +mmseg/.mim/configs/dsdl/voc.py +mmseg/.mim/configs/emanet/emanet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/emanet/emanet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/emanet/emanet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/emanet/emanet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/emanet/metafile.yaml +mmseg/.mim/configs/encnet/encnet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/encnet/encnet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/encnet/encnet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/encnet/encnet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/encnet/encnet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/encnet/encnet_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/encnet/encnet_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/encnet/encnet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/encnet/encnet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/encnet/encnet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/encnet/encnet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/encnet/encnet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/encnet/encnet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/encnet/encnet_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/encnet/encnet_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/encnet/encnet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/encnet/encnet_r50s-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/encnet/metafile.yaml +mmseg/.mim/configs/erfnet/erfnet_fcn_4xb4-160k_cityscapes-512x1024.py +mmseg/.mim/configs/erfnet/metafile.yaml +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_aspp_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_aspp_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_aspp_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_aspp_4xb4-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_enc_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_enc_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_enc_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_enc_4xb4-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_psp_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_psp_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_psp_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/fastfcn/fastfcn_r50-d32_jpu_psp_4xb4-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fastfcn/metafile.yaml +mmseg/.mim/configs/fastscnn/fast_scnn_8xb4-160k_cityscapes-512x1024.py +mmseg/.mim/configs/fastscnn/metafile.yaml +mmseg/.mim/configs/fcn/fcn-d6_r101-d16_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn-d6_r101-d16_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn-d6_r101-d16_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn-d6_r101-d16_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn-d6_r101b-d16_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn-d6_r101b-d16_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn-d6_r50-d16_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn-d6_r50-d16_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn-d6_r50-d16_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn-d6_r50-d16_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn-d6_r50b-d16_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn-d6_r50b-d16_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb2-amp-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/fcn/fcn_r101-d8_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/fcn/fcn_r101b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r101b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn_r18-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r18-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn_r18b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r18b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/fcn/fcn_r50-d8_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/fcn/fcn_r50b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/fcn/fcn_r50b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/fcn/metafile.yaml +mmseg/.mim/configs/gcnet/gcnet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/gcnet/gcnet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/gcnet/gcnet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/gcnet/gcnet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/gcnet/gcnet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/gcnet/gcnet_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/gcnet/gcnet_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/gcnet/gcnet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/gcnet/gcnet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/gcnet/gcnet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/gcnet/gcnet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/gcnet/gcnet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/gcnet/gcnet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/gcnet/gcnet_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/gcnet/gcnet_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/gcnet/gcnet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/gcnet/metafile.yaml +mmseg/.mim/configs/hrnet/fcn_hr18_4xb2-160k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-80k_isaid-896x896.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb2-160k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-80k_isaid-896x896.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr18s_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb2-160k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-80k_isaid-896x896.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/hrnet/fcn_hr48_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/hrnet/metafile.yaml +mmseg/.mim/configs/icnet/icnet_r101-d8-in1k-pre_4xb2-160k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r101-d8-in1k-pre_4xb2-80k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r101-d8_4xb2-160k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r101-d8_4xb2-80k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r18-d8-in1k-pre_4xb2-160k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r18-d8-in1k-pre_4xb2-80k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r18-d8_4xb2-160k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r18-d8_4xb2-80k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r50-d8-in1k-pre_4xb2-160k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r50-d8-in1k-pre_4xb2-80k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r50-d8_4xb2-160k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/icnet_r50-d8_4xb2-80k_cityscapes-832x832.py +mmseg/.mim/configs/icnet/metafile.yaml +mmseg/.mim/configs/isanet/isanet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/isanet/isanet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/isanet/isanet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/isanet/isanet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/isanet/isanet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/isanet/isanet_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/isanet/isanet_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/isanet/isanet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/isanet/isanet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/isanet/isanet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/isanet/isanet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/isanet/isanet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/isanet/isanet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/isanet/isanet_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/isanet/isanet_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/isanet/isanet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/isanet/metafile.yaml +mmseg/.mim/configs/knet/knet-s3_r50-d8_deeplabv3_8xb2-adamw-80k_ade20k-512x512.py +mmseg/.mim/configs/knet/knet-s3_r50-d8_fcn_8xb2-adamw-80k_ade20k-512x512.py +mmseg/.mim/configs/knet/knet-s3_r50-d8_pspnet_8xb2-adamw-80k_ade20k-512x512.py +mmseg/.mim/configs/knet/knet-s3_r50-d8_upernet_8xb2-adamw-80k_ade20k-512x512.py +mmseg/.mim/configs/knet/knet-s3_swin-l_upernet_8xb2-adamw-80k_ade20k-512x512.py +mmseg/.mim/configs/knet/knet-s3_swin-l_upernet_8xb2-adamw-80k_ade20k-640x640.py +mmseg/.mim/configs/knet/knet-s3_swin-t_upernet_8xb2-adamw-80k_ade20k-512x512.py +mmseg/.mim/configs/knet/metafile.yaml +mmseg/.mim/configs/mae/mae-base_upernet_8xb2-amp-160k_ade20k-512x512-ms.py +mmseg/.mim/configs/mae/mae-base_upernet_8xb2-amp-160k_ade20k-512x512.py +mmseg/.mim/configs/mae/metafile.yaml +mmseg/.mim/configs/mask2former/mask2former_r101_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/mask2former/mask2former_r101_8xb2-90k_cityscapes-512x1024.py +mmseg/.mim/configs/mask2former/mask2former_r50_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/mask2former/mask2former_r50_8xb2-90k_cityscapes-512x1024.py +mmseg/.mim/configs/mask2former/mask2former_swin-b-in1k-384x384-pre_8xb2-160k_ade20k-640x640.py +mmseg/.mim/configs/mask2former/mask2former_swin-b-in22k-384x384-pre_8xb2-160k_ade20k-640x640.py +mmseg/.mim/configs/mask2former/mask2former_swin-b-in22k-384x384-pre_8xb2-90k_cityscapes-512x1024.py +mmseg/.mim/configs/mask2former/mask2former_swin-l-in22k-384x384-pre_8xb2-160k_ade20k-640x640.py +mmseg/.mim/configs/mask2former/mask2former_swin-l-in22k-384x384-pre_8xb2-90k_cityscapes-512x1024.py +mmseg/.mim/configs/mask2former/mask2former_swin-s_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/mask2former/mask2former_swin-s_8xb2-90k_cityscapes-512x1024.py +mmseg/.mim/configs/mask2former/mask2former_swin-t_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/mask2former/mask2former_swin-t_8xb2-90k_cityscapes-512x1024.py +mmseg/.mim/configs/mask2former/metafile.yaml +mmseg/.mim/configs/maskformer/maskformer_r101-d32_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/maskformer/maskformer_r50-d32_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/maskformer/maskformer_swin-s_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/maskformer/maskformer_swin-t_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/maskformer/metafile.yaml +mmseg/.mim/configs/mobilenet_v2/metafile.yaml +mmseg/.mim/configs/mobilenet_v2/mobilenet-v2-d8_deeplabv3_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/mobilenet_v2/mobilenet-v2-d8_deeplabv3_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/mobilenet_v2/mobilenet-v2-d8_deeplabv3plus_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/mobilenet_v2/mobilenet-v2-d8_deeplabv3plus_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/mobilenet_v2/mobilenet-v2-d8_fcn_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/mobilenet_v2/mobilenet-v2-d8_fcn_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/mobilenet_v2/mobilenet-v2-d8_pspnet_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/mobilenet_v2/mobilenet-v2-d8_pspnet_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/mobilenet_v3/metafile.yaml +mmseg/.mim/configs/mobilenet_v3/mobilenet-v3-d8-s_lraspp_4xb4-320k_cityscapes-512x1024.py +mmseg/.mim/configs/mobilenet_v3/mobilenet-v3-d8-scratch-s_lraspp_4xb4-320k_cityscapes-512x1024.py +mmseg/.mim/configs/mobilenet_v3/mobilenet-v3-d8-scratch_lraspp_4xb4-320k_cityscapes-512x1024.py +mmseg/.mim/configs/mobilenet_v3/mobilenet-v3-d8_lraspp_4xb4-320k_cityscapes-512x1024.py +mmseg/.mim/configs/nonlocal_net/metafile.yaml +mmseg/.mim/configs/nonlocal_net/nonlocal_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/nonlocal_net/nonlocal_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/ocrnet/metafile.yaml +mmseg/.mim/configs/ocrnet/ocrnet_hr18_4xb2-160k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18s_4xb2-160k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18s_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18s_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18s_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18s_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18s_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr18s_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr48_4xb2-160k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr48_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr48_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_hr48_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr48_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr48_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_hr48_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/ocrnet/ocrnet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_r101-d8_8xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/ocrnet/ocrnet_r101-d8_8xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pidnet/metafile.yaml +mmseg/.mim/configs/pidnet/pidnet-l_2xb6-120k_1024x1024-cityscapes.py +mmseg/.mim/configs/pidnet/pidnet-m_2xb6-120k_1024x1024-cityscapes.py +mmseg/.mim/configs/pidnet/pidnet-s_2xb6-120k_1024x1024-cityscapes.py +mmseg/.mim/configs/point_rend/metafile.yaml +mmseg/.mim/configs/point_rend/pointrend_r101_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/point_rend/pointrend_r101_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/point_rend/pointrend_r50_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/point_rend/pointrend_r50_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/poolformer/fpn_poolformer_m36_8xb4-40k_ade20k-512x512.py +mmseg/.mim/configs/poolformer/fpn_poolformer_m48_8xb4-40k_ade20k-512x512.py +mmseg/.mim/configs/poolformer/fpn_poolformer_s12_8xb4-40k_ade20k-512x512.py +mmseg/.mim/configs/poolformer/fpn_poolformer_s24_8xb4-40k_ade20k-512x512.py +mmseg/.mim/configs/poolformer/fpn_poolformer_s36_8x4_512x512_40k_ade20k.py +mmseg/.mim/configs/poolformer/metafile.yaml +mmseg/.mim/configs/psanet/metafile.yaml +mmseg/.mim/configs/psanet/psanet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/psanet/psanet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/psanet/psanet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/psanet/psanet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/psanet/psanet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/psanet/psanet_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/psanet/psanet_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/psanet/psanet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/psanet/psanet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/psanet/psanet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/psanet/psanet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/psanet/psanet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/psanet/psanet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/psanet/psanet_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/psanet/psanet_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/psanet/psanet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/pspnet/metafile.yaml +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb2-40k_cityscapes-512x1024_dark-zurich-1920x1080.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb2-40k_cityscapes-512x1024_night-driving-1920x1080.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb2-amp-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-20k_coco-stuff10k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-320k_coco-stuff164k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-40k_coco-stuff10k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-80k_coco-stuff164k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101-d8_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r101b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r101b-d8_4xb2-80k_cityscapes-512x1024_dark-zurich-1920x1080.py +mmseg/.mim/configs/pspnet/pspnet_r101b-d8_4xb2-80k_cityscapes-512x1024_night-driving-1920x1080.py +mmseg/.mim/configs/pspnet/pspnet_r101b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/pspnet/pspnet_r18-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r18-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/pspnet/pspnet_r18-d8_4xb4-80k_isaid-896x896.py +mmseg/.mim/configs/pspnet/pspnet_r18-d8_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r18-d8_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r18-d8_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r18b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r18b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/pspnet/pspnet_r50-d32_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r50-d32_rsb_4xb2-adamw-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8-rsb_4xb2-adamw-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb2-40k_cityscapes-512x1024_dark-zurich-1920x1080.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb2-40k_cityscapes-512x1024_night-driving-1920x1080.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb2-80k_cityscapes-512x1024_dark-zurich-1920x1080.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb2-80k_cityscapes-512x1024_night-driving-1920x1080.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-160k_coco-stuff164k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-20k_coco-stuff10k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-320k_coco-stuff164k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-40k_coco-stuff10k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-40k_pascal-context-480x480.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-40k_pascal-context-59-480x480.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-80k_coco-stuff164k-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-80k_isaid-896x896.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-80k_loveda-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-80k_pascal-context-480x480.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-80k_pascal-context-59-480x480.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-80k_potsdam-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50-d8_4xb4-80k_vaihingen-512x512.py +mmseg/.mim/configs/pspnet/pspnet_r50b-d32_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r50b-d8_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/pspnet/pspnet_r50b-d8_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/resnest/metafile.yaml +mmseg/.mim/configs/resnest/resnest_s101-d8_deeplabv3_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/resnest/resnest_s101-d8_deeplabv3_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/resnest/resnest_s101-d8_deeplabv3plus_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/resnest/resnest_s101-d8_deeplabv3plus_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/resnest/resnest_s101-d8_fcn_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/resnest/resnest_s101-d8_fcn_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/resnest/resnest_s101-d8_pspnet_4xb2-80k_cityscapes512x1024.py +mmseg/.mim/configs/resnest/resnest_s101-d8_pspnet_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/san/metafile.yaml +mmseg/.mim/configs/san/san-vit-b16_coco-stuff164k-640x640.py +mmseg/.mim/configs/san/san-vit-b16_pascal_context-640x640.py +mmseg/.mim/configs/san/san-vit-b16_voc12aug-640x640.py +mmseg/.mim/configs/san/san-vit-l14_coco-stuff164k-640x640.py +mmseg/.mim/configs/san/san-vit-l14_pascal_context-640x640.py +mmseg/.mim/configs/san/san-vit-l14_voc12aug-640x640.py +mmseg/.mim/configs/segformer/metafile.yaml +mmseg/.mim/configs/segformer/segformer_mit-b0_8xb1-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/segformer/segformer_mit-b0_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/segformer/segformer_mit-b1_8xb1-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/segformer/segformer_mit-b1_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/segformer/segformer_mit-b2_8xb1-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/segformer/segformer_mit-b2_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/segformer/segformer_mit-b3_8xb1-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/segformer/segformer_mit-b3_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/segformer/segformer_mit-b4_8xb1-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/segformer/segformer_mit-b4_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/segformer/segformer_mit-b5_8xb1-160k_cityscapes-1024x1024.py +mmseg/.mim/configs/segformer/segformer_mit-b5_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/segformer/segformer_mit-b5_8xb2-160k_ade20k-640x640.py +mmseg/.mim/configs/segmenter/metafile.yaml +mmseg/.mim/configs/segmenter/segmenter_vit-b_mask_8xb1-160k_ade20k-512x512.py +mmseg/.mim/configs/segmenter/segmenter_vit-l_mask_8xb1-160k_ade20k-512x512.py +mmseg/.mim/configs/segmenter/segmenter_vit-s_fcn_8xb1-160k_ade20k-512x512.py +mmseg/.mim/configs/segmenter/segmenter_vit-s_mask_8xb1-160k_ade20k-512x512.py +mmseg/.mim/configs/segmenter/segmenter_vit-t_mask_8xb1-160k_ade20k-512x512.py +mmseg/.mim/configs/segnext/metafile.yaml +mmseg/.mim/configs/segnext/segnext_mscan-b_1xb16-adamw-160k_ade20k-512x512.py +mmseg/.mim/configs/segnext/segnext_mscan-l_1xb16-adamw-160k_ade20k-512x512.py +mmseg/.mim/configs/segnext/segnext_mscan-s_1xb16-adamw-160k_ade20k-512x512.py +mmseg/.mim/configs/segnext/segnext_mscan-t_1xb16-adamw-160k_ade20k-512x512.py +mmseg/.mim/configs/sem_fpn/fpn_r101_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/sem_fpn/fpn_r101_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/sem_fpn/fpn_r50_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/sem_fpn/fpn_r50_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/sem_fpn/metafile.yaml +mmseg/.mim/configs/setr/metafile.yaml +mmseg/.mim/configs/setr/setr_vit-l-mla_8xb1-160k_ade20k-512x512.py +mmseg/.mim/configs/setr/setr_vit-l_mla_8xb1-80k_cityscapes-768x768.py +mmseg/.mim/configs/setr/setr_vit-l_mla_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/setr/setr_vit-l_naive_8xb1-80k_cityscapes-768x768.py +mmseg/.mim/configs/setr/setr_vit-l_naive_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/setr/setr_vit-l_pup_8xb1-80k_cityscapes-768x768.py +mmseg/.mim/configs/setr/setr_vit-l_pup_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/stdc/metafile.yaml +mmseg/.mim/configs/stdc/stdc1_4xb12-80k_cityscapes-512x1024.py +mmseg/.mim/configs/stdc/stdc1_in1k-pre_4xb12-80k_cityscapes-512x1024.py +mmseg/.mim/configs/stdc/stdc2_4xb12-80k_cityscapes-512x1024.py +mmseg/.mim/configs/stdc/stdc2_in1k-pre_4xb12-80k_cityscapes-512x1024.py +mmseg/.mim/configs/swin/metafile.yaml +mmseg/.mim/configs/swin/swin-base-patch4-window12-in1k-384x384-pre_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/swin/swin-base-patch4-window12-in22k-384x384-pre_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/swin/swin-base-patch4-window7-in1k-pre_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/swin/swin-base-patch4-window7-in22k-pre_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/swin/swin-large-patch4-window12-in22k-384x384-pre_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/swin/swin-large-patch4-window7-in22k-pre_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/swin/swin-small-patch4-window7-in1k-pre_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/swin/swin-tiny-patch4-window7-in1k-pre_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/swin/swin-tiny-patch4-window7_upernet_1xb8-20k_levir-256x256.py +mmseg/.mim/configs/twins/metafile.yaml +mmseg/.mim/configs/twins/twins_pcpvt-b_fpn_fpnhead_8xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_pcpvt-b_uperhead_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_pcpvt-l_fpn_fpnhead_8xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_pcpvt-l_uperhead_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_pcpvt-s_fpn_fpnhead_8xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_pcpvt-s_uperhead_8xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_svt-b_fpn_fpnhead_8xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_svt-b_uperhead_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_svt-l_fpn_fpnhead_8xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_svt-l_uperhead_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_svt-s_fpn_fpnhead_8xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/twins/twins_svt-s_uperhead_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/unet/metafile.yaml +mmseg/.mim/configs/unet/unet-s5-d16_deeplabv3_4xb4-40k_drive-64x64.py +mmseg/.mim/configs/unet/unet-s5-d16_deeplabv3_4xb4-40k_hrf-256x256.py +mmseg/.mim/configs/unet/unet-s5-d16_deeplabv3_4xb4-40k_stare-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_deeplabv3_4xb4-ce-1.0-dice-3.0-40k_chase-db1-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_deeplabv3_4xb4-ce-1.0-dice-3.0-40k_drive-64x64.py +mmseg/.mim/configs/unet/unet-s5-d16_deeplabv3_4xb4-ce-1.0-dice-3.0-40k_hrf-256x256.py +mmseg/.mim/configs/unet/unet-s5-d16_deeplabv3_4xb4-ce-1.0-dice-3.0-40k_stare-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-160k_cityscapes-512x1024.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-160k_hsidrive-192x384.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-40k_chase-db1-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-40k_drive-64x64.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-40k_hrf-256x256.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-40k_stare-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-ce-1.0-dice-3.0-40k_chase-db1-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-ce-1.0-dice-3.0-40k_drive-64x64.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-ce-1.0-dice-3.0-40k_hrf-256x256.py +mmseg/.mim/configs/unet/unet-s5-d16_fcn_4xb4-ce-1.0-dice-3.0-40k_stare-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_pspnet_4xb4-40k_chase-db1-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_pspnet_4xb4-40k_drive-64x64.py +mmseg/.mim/configs/unet/unet-s5-d16_pspnet_4xb4-40k_hrf-256x256.py +mmseg/.mim/configs/unet/unet-s5-d16_pspnet_4xb4-40k_stare-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_pspnet_4xb4-ce-1.0-dice-3.0-40k_chase-db1-128x128.py +mmseg/.mim/configs/unet/unet-s5-d16_pspnet_4xb4-ce-1.0-dice-3.0-40k_drive-64x64.py +mmseg/.mim/configs/unet/unet-s5-d16_pspnet_4xb4-ce-1.0-dice-3.0-40k_hrf-256x256.py +mmseg/.mim/configs/unet/unet-s5-d16_pspnet_4xb4-ce-1.0-dice-3.0-40k_stare-128x128.py +mmseg/.mim/configs/unet/unet_s5-d16_deeplabv3_4xb4-40k_chase-db1-128x128.py +mmseg/.mim/configs/upernet/metafile.yaml +mmseg/.mim/configs/upernet/upernet_r101_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/upernet/upernet_r101_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/upernet/upernet_r101_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/upernet/upernet_r101_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/upernet/upernet_r101_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/upernet/upernet_r101_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/upernet/upernet_r101_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/upernet/upernet_r101_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/upernet/upernet_r18_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/upernet/upernet_r18_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/upernet/upernet_r18_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/upernet/upernet_r18_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/upernet/upernet_r18_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/upernet/upernet_r18_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/upernet/upernet_r50_4xb2-40k_cityscapes-512x1024.py +mmseg/.mim/configs/upernet/upernet_r50_4xb2-40k_cityscapes-769x769.py +mmseg/.mim/configs/upernet/upernet_r50_4xb2-80k_cityscapes-512x1024.py +mmseg/.mim/configs/upernet/upernet_r50_4xb2-80k_cityscapes-769x769.py +mmseg/.mim/configs/upernet/upernet_r50_4xb4-160k_ade20k-512x512.py +mmseg/.mim/configs/upernet/upernet_r50_4xb4-20k_voc12aug-512x512.py +mmseg/.mim/configs/upernet/upernet_r50_4xb4-40k_voc12aug-512x512.py +mmseg/.mim/configs/upernet/upernet_r50_4xb4-80k_ade20k-512x512.py +mmseg/.mim/configs/vit/metafile.yaml +mmseg/.mim/configs/vit/vit_deit-b16-ln_mln_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_deit-b16_mln_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_deit-b16_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_deit-b16_upernet_8xb2-80k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_deit-s16-ln_mln_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_deit-s16_mln_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_deit-s16_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_deit-s16_upernet_8xb2-80k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_vit-b16-ln_mln_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_vit-b16_mln_upernet_8xb2-160k_ade20k-512x512.py +mmseg/.mim/configs/vit/vit_vit-b16_mln_upernet_8xb2-80k_ade20k-512x512.py +mmseg/.mim/configs/vpd/metafile.yaml +mmseg/.mim/configs/vpd/vpd_sd_4xb8-25k_nyu-480x480.py +mmseg/.mim/configs/vpd/vpd_sd_4xb8-25k_nyu-512x512.py +mmseg/.mim/tools/dist_test.sh +mmseg/.mim/tools/dist_train.sh +mmseg/.mim/tools/slurm_test.sh +mmseg/.mim/tools/slurm_train.sh +mmseg/.mim/tools/test.py +mmseg/.mim/tools/train.py +mmseg/.mim/tools/analysis_tools/analyze_logs.py +mmseg/.mim/tools/analysis_tools/benchmark.py +mmseg/.mim/tools/analysis_tools/browse_dataset.py +mmseg/.mim/tools/analysis_tools/confusion_matrix.py +mmseg/.mim/tools/analysis_tools/get_flops.py +mmseg/.mim/tools/analysis_tools/visualization_cam.py +mmseg/.mim/tools/dataset_converters/chase_db1.py +mmseg/.mim/tools/dataset_converters/cityscapes.py +mmseg/.mim/tools/dataset_converters/coco_stuff10k.py +mmseg/.mim/tools/dataset_converters/coco_stuff164k.py +mmseg/.mim/tools/dataset_converters/drive.py +mmseg/.mim/tools/dataset_converters/hrf.py +mmseg/.mim/tools/dataset_converters/isaid.py +mmseg/.mim/tools/dataset_converters/levircd.py +mmseg/.mim/tools/dataset_converters/loveda.py +mmseg/.mim/tools/dataset_converters/nyu.py +mmseg/.mim/tools/dataset_converters/pascal_context.py +mmseg/.mim/tools/dataset_converters/potsdam.py +mmseg/.mim/tools/dataset_converters/refuge.py +mmseg/.mim/tools/dataset_converters/stare.py +mmseg/.mim/tools/dataset_converters/synapse.py +mmseg/.mim/tools/dataset_converters/vaihingen.py +mmseg/.mim/tools/dataset_converters/voc_aug.py +mmseg/.mim/tools/deployment/pytorch2torchscript.py +mmseg/.mim/tools/misc/browse_dataset.py +mmseg/.mim/tools/misc/print_config.py +mmseg/.mim/tools/misc/publish_model.py +mmseg/.mim/tools/model_converters/beit2mmseg.py +mmseg/.mim/tools/model_converters/clip2mmseg.py +mmseg/.mim/tools/model_converters/mit2mmseg.py +mmseg/.mim/tools/model_converters/san2mmseg.py +mmseg/.mim/tools/model_converters/stdc2mmseg.py +mmseg/.mim/tools/model_converters/swin2mmseg.py +mmseg/.mim/tools/model_converters/twins2mmseg.py +mmseg/.mim/tools/model_converters/vit2mmseg.py +mmseg/.mim/tools/model_converters/vitjax2mmseg.py +mmseg/.mim/tools/torchserve/mmseg2torchserve.py +mmseg/.mim/tools/torchserve/mmseg_handler.py +mmseg/.mim/tools/torchserve/test_torchserve.py +mmseg/apis/__init__.py +mmseg/apis/inference.py +mmseg/apis/mmseg_inferencer.py +mmseg/apis/remote_sense_inferencer.py +mmseg/apis/utils.py +mmseg/datasets/__init__.py +mmseg/datasets/ade.py +mmseg/datasets/basesegdataset.py +mmseg/datasets/bdd100k.py +mmseg/datasets/chase_db1.py +mmseg/datasets/cityscapes.py +mmseg/datasets/coco_stuff.py +mmseg/datasets/dark_zurich.py +mmseg/datasets/dataset_wrappers.py +mmseg/datasets/decathlon.py +mmseg/datasets/drive.py +mmseg/datasets/dsdl.py +mmseg/datasets/hrf.py +mmseg/datasets/hsi_drive.py +mmseg/datasets/isaid.py +mmseg/datasets/isprs.py +mmseg/datasets/levir.py +mmseg/datasets/lip.py +mmseg/datasets/loveda.py +mmseg/datasets/mapillary.py +mmseg/datasets/night_driving.py +mmseg/datasets/nyu.py +mmseg/datasets/pascal_context.py +mmseg/datasets/potsdam.py +mmseg/datasets/refuge.py +mmseg/datasets/stare.py +mmseg/datasets/synapse.py +mmseg/datasets/voc.py +mmseg/datasets/transforms/__init__.py +mmseg/datasets/transforms/formatting.py +mmseg/datasets/transforms/loading.py +mmseg/datasets/transforms/transforms.py +mmseg/engine/__init__.py +mmseg/engine/hooks/__init__.py +mmseg/engine/hooks/visualization_hook.py +mmseg/engine/optimizers/__init__.py +mmseg/engine/optimizers/force_default_constructor.py +mmseg/engine/optimizers/layer_decay_optimizer_constructor.py +mmseg/engine/schedulers/__init__.py +mmseg/engine/schedulers/poly_ratio_scheduler.py +mmseg/evaluation/__init__.py +mmseg/evaluation/metrics/__init__.py +mmseg/evaluation/metrics/citys_metric.py +mmseg/evaluation/metrics/depth_metric.py +mmseg/evaluation/metrics/iou_metric.py +mmseg/models/__init__.py +mmseg/models/builder.py +mmseg/models/data_preprocessor.py +mmseg/models/assigners/__init__.py +mmseg/models/assigners/base_assigner.py +mmseg/models/assigners/hungarian_assigner.py +mmseg/models/assigners/match_cost.py +mmseg/models/backbones/__init__.py +mmseg/models/backbones/beit.py +mmseg/models/backbones/bisenetv1.py +mmseg/models/backbones/bisenetv2.py +mmseg/models/backbones/cgnet.py +mmseg/models/backbones/ddrnet.py +mmseg/models/backbones/erfnet.py +mmseg/models/backbones/fast_scnn.py +mmseg/models/backbones/hrnet.py +mmseg/models/backbones/icnet.py +mmseg/models/backbones/mae.py +mmseg/models/backbones/mit.py +mmseg/models/backbones/mobilenet_v2.py +mmseg/models/backbones/mobilenet_v3.py +mmseg/models/backbones/mscan.py +mmseg/models/backbones/pidnet.py +mmseg/models/backbones/resnest.py +mmseg/models/backbones/resnet.py +mmseg/models/backbones/resnext.py +mmseg/models/backbones/stdc.py +mmseg/models/backbones/swin.py +mmseg/models/backbones/timm_backbone.py +mmseg/models/backbones/twins.py +mmseg/models/backbones/unet.py +mmseg/models/backbones/vit.py +mmseg/models/backbones/vpd.py +mmseg/models/decode_heads/__init__.py +mmseg/models/decode_heads/ann_head.py +mmseg/models/decode_heads/apc_head.py +mmseg/models/decode_heads/aspp_head.py +mmseg/models/decode_heads/cascade_decode_head.py +mmseg/models/decode_heads/cc_head.py +mmseg/models/decode_heads/da_head.py +mmseg/models/decode_heads/ddr_head.py +mmseg/models/decode_heads/decode_head.py +mmseg/models/decode_heads/dm_head.py +mmseg/models/decode_heads/dnl_head.py +mmseg/models/decode_heads/dpt_head.py +mmseg/models/decode_heads/ema_head.py +mmseg/models/decode_heads/enc_head.py +mmseg/models/decode_heads/fcn_head.py +mmseg/models/decode_heads/fpn_head.py +mmseg/models/decode_heads/gc_head.py +mmseg/models/decode_heads/ham_head.py +mmseg/models/decode_heads/isa_head.py +mmseg/models/decode_heads/knet_head.py +mmseg/models/decode_heads/lraspp_head.py +mmseg/models/decode_heads/mask2former_head.py +mmseg/models/decode_heads/maskformer_head.py +mmseg/models/decode_heads/nl_head.py +mmseg/models/decode_heads/ocr_head.py +mmseg/models/decode_heads/pid_head.py +mmseg/models/decode_heads/point_head.py +mmseg/models/decode_heads/psa_head.py +mmseg/models/decode_heads/psp_head.py +mmseg/models/decode_heads/san_head.py +mmseg/models/decode_heads/segformer_head.py +mmseg/models/decode_heads/segmenter_mask_head.py +mmseg/models/decode_heads/sep_aspp_head.py +mmseg/models/decode_heads/sep_fcn_head.py +mmseg/models/decode_heads/setr_mla_head.py +mmseg/models/decode_heads/setr_up_head.py +mmseg/models/decode_heads/stdc_head.py +mmseg/models/decode_heads/uper_head.py +mmseg/models/decode_heads/vpd_depth_head.py +mmseg/models/losses/__init__.py +mmseg/models/losses/accuracy.py +mmseg/models/losses/boundary_loss.py +mmseg/models/losses/cross_entropy_loss.py +mmseg/models/losses/dice_loss.py +mmseg/models/losses/focal_loss.py +mmseg/models/losses/huasdorff_distance_loss.py +mmseg/models/losses/kldiv_loss.py +mmseg/models/losses/lovasz_loss.py +mmseg/models/losses/ohem_cross_entropy_loss.py +mmseg/models/losses/silog_loss.py +mmseg/models/losses/tversky_loss.py +mmseg/models/losses/utils.py +mmseg/models/necks/__init__.py +mmseg/models/necks/featurepyramid.py +mmseg/models/necks/fpn.py +mmseg/models/necks/ic_neck.py +mmseg/models/necks/jpu.py +mmseg/models/necks/mla_neck.py +mmseg/models/necks/multilevel_neck.py +mmseg/models/segmentors/__init__.py +mmseg/models/segmentors/base.py +mmseg/models/segmentors/cascade_encoder_decoder.py +mmseg/models/segmentors/depth_estimator.py +mmseg/models/segmentors/encoder_decoder.py +mmseg/models/segmentors/multimodal_encoder_decoder.py +mmseg/models/segmentors/seg_tta.py +mmseg/models/text_encoder/__init__.py +mmseg/models/text_encoder/clip_text_encoder.py +mmseg/models/utils/__init__.py +mmseg/models/utils/basic_block.py +mmseg/models/utils/embed.py +mmseg/models/utils/encoding.py +mmseg/models/utils/inverted_residual.py +mmseg/models/utils/make_divisible.py +mmseg/models/utils/point_sample.py +mmseg/models/utils/ppm.py +mmseg/models/utils/res_layer.py +mmseg/models/utils/san_layers.py +mmseg/models/utils/se_layer.py +mmseg/models/utils/self_attention_block.py +mmseg/models/utils/shape_convert.py +mmseg/models/utils/up_conv_block.py +mmseg/models/utils/wrappers.py +mmseg/registry/__init__.py +mmseg/registry/registry.py +mmseg/structures/__init__.py +mmseg/structures/seg_data_sample.py +mmseg/structures/sampler/__init__.py +mmseg/structures/sampler/base_pixel_sampler.py +mmseg/structures/sampler/builder.py +mmseg/structures/sampler/ohem_pixel_sampler.py +mmseg/utils/__init__.py +mmseg/utils/bpe_simple_vocab_16e6.txt.gz +mmseg/utils/class_names.py +mmseg/utils/collect_env.py +mmseg/utils/get_templates.py +mmseg/utils/io.py +mmseg/utils/mask_classification.py +mmseg/utils/misc.py +mmseg/utils/set_env.py +mmseg/utils/tokenizer.py +mmseg/utils/typing_utils.py +mmseg/visualization/__init__.py +mmseg/visualization/local_visualizer.py +mmsegmentation.egg-info/PKG-INFO +mmsegmentation.egg-info/SOURCES.txt +mmsegmentation.egg-info/dependency_links.txt +mmsegmentation.egg-info/not-zip-safe +mmsegmentation.egg-info/requires.txt +mmsegmentation.egg-info/top_level.txt +requirements/albu.txt +requirements/docs.txt +requirements/mminstall.txt +requirements/multimodal.txt +requirements/optional.txt +requirements/readthedocs.txt +requirements/runtime.txt +requirements/tests.txt +tests/__init__.py +tests/test_config.py +tests/test_digit_version.py +tests/test_sampler.py +tests/test_models/__init__.py +tests/test_models/test_data_preprocessor.py +tests/test_models/test_forward.py +tests/test_models/test_backbones/__init__.py +tests/test_models/test_backbones/test_beit.py +tests/test_models/test_backbones/test_bisenetv1.py +tests/test_models/test_backbones/test_bisenetv2.py +tests/test_models/test_backbones/test_blocks.py +tests/test_models/test_backbones/test_cgnet.py +tests/test_models/test_backbones/test_clip_text_encoder.py +tests/test_models/test_backbones/test_erfnet.py +tests/test_models/test_backbones/test_fast_scnn.py +tests/test_models/test_backbones/test_hrnet.py +tests/test_models/test_backbones/test_icnet.py +tests/test_models/test_backbones/test_mae.py +tests/test_models/test_backbones/test_mit.py +tests/test_models/test_backbones/test_mobilenet_v3.py +tests/test_models/test_backbones/test_mscan.py +tests/test_models/test_backbones/test_pidnet.py +tests/test_models/test_backbones/test_resnest.py +tests/test_models/test_backbones/test_resnet.py +tests/test_models/test_backbones/test_resnext.py +tests/test_models/test_backbones/test_stdc.py +tests/test_models/test_backbones/test_swin.py +tests/test_models/test_backbones/test_timm_backbone.py +tests/test_models/test_backbones/test_twins.py +tests/test_models/test_backbones/test_unet.py +tests/test_models/test_backbones/test_vit.py +tests/test_models/test_backbones/test_vpd.py +tests/test_models/test_backbones/utils.py +tests/test_models/test_heads/__init__.py +tests/test_models/test_heads/test_ann_head.py +tests/test_models/test_heads/test_apc_head.py +tests/test_models/test_heads/test_aspp_head.py +tests/test_models/test_heads/test_cc_head.py +tests/test_models/test_heads/test_decode_head.py +tests/test_models/test_heads/test_dm_head.py +tests/test_models/test_heads/test_dnl_head.py +tests/test_models/test_heads/test_dpt_head.py +tests/test_models/test_heads/test_ema_head.py +tests/test_models/test_heads/test_fcn_head.py +tests/test_models/test_heads/test_gc_head.py +tests/test_models/test_heads/test_ham_head.py +tests/test_models/test_heads/test_isa_head.py +tests/test_models/test_heads/test_lraspp_head.py +tests/test_models/test_heads/test_mask2former_head.py +tests/test_models/test_heads/test_maskformer_head.py +tests/test_models/test_heads/test_nl_head.py +tests/test_models/test_heads/test_ocr_head.py +tests/test_models/test_heads/test_pidnet_head.py +tests/test_models/test_heads/test_psa_head.py +tests/test_models/test_heads/test_psp_head.py +tests/test_models/test_heads/test_san_head.py +tests/test_models/test_heads/test_segformer_head.py +tests/test_models/test_heads/test_segmenter_mask_head.py +tests/test_models/test_heads/test_setr_mla_head.py +tests/test_models/test_heads/test_setr_up_head.py +tests/test_models/test_heads/test_uper_head.py +tests/test_models/test_heads/test_vpd_depth_head.py +tests/test_models/test_heads/utils.py +tests/test_models/test_necks/__init__.py +tests/test_models/test_necks/test_feature2pyramid.py +tests/test_models/test_necks/test_fpn.py +tests/test_models/test_necks/test_ic_neck.py +tests/test_models/test_necks/test_jpu.py +tests/test_models/test_necks/test_mla_neck.py +tests/test_models/test_necks/test_multilevel_neck.py +tests/test_models/test_segmentors/__init__.py +tests/test_models/test_segmentors/test_cascade_encoder_decoder.py +tests/test_models/test_segmentors/test_depth_estimator.py +tests/test_models/test_segmentors/test_encoder_decoder.py +tests/test_models/test_segmentors/test_multimodal_encoder_decoder.py +tests/test_models/test_segmentors/test_seg_tta_model.py +tests/test_models/test_segmentors/utils.py +tests/test_models/test_utils/__init__.py +tests/test_models/test_utils/test_embed.py +tests/test_models/test_utils/test_shape_convert.py \ No newline at end of file diff --git a/third-party/InterFormer/mmsegmentation.egg-info/dependency_links.txt b/third-party/InterFormer/mmsegmentation.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/third-party/InterFormer/mmsegmentation.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/third-party/InterFormer/mmsegmentation.egg-info/not-zip-safe b/third-party/InterFormer/mmsegmentation.egg-info/not-zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/third-party/InterFormer/mmsegmentation.egg-info/not-zip-safe @@ -0,0 +1 @@ + diff --git a/third-party/InterFormer/mmsegmentation.egg-info/requires.txt b/third-party/InterFormer/mmsegmentation.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..fcdd92eded8d351dd6c1541193ec17a1c80090c6 --- /dev/null +++ b/third-party/InterFormer/mmsegmentation.egg-info/requires.txt @@ -0,0 +1,82 @@ +matplotlib +numpy +packaging +prettytable +scipy + +[all] +cityscapesscripts +clip +diffusers +einops==0.3.0 +imageio==2.9.0 +imageio-ffmpeg==0.4.2 +invisible-watermark +kornia==0.6 +latent-diffusion +nibabel +omegaconf==2.1.1 +pudb==2019.2 +pytorch-lightning==1.4.2 +streamlit>=0.73.1 +taming-transformers +test-tube>=0.7.5 +timm +torch-fidelity==0.3.0 +torchmetrics==0.6.0 +transformers==4.19.2 +matplotlib +numpy +packaging +prettytable +scipy +codecov +flake8 +ftfy +interrogate +pytest +regex +xdoctest>=0.10.0 +yapf +ftfy +regex + +[mim] +mmcv<2.2.0,>=2.0.0rc4 +mmengine<1.0.0,>=0.5.0 + +[multimodal] +ftfy +regex + +[optional] +cityscapesscripts +clip +diffusers +einops==0.3.0 +imageio==2.9.0 +imageio-ffmpeg==0.4.2 +invisible-watermark +kornia==0.6 +latent-diffusion +nibabel +omegaconf==2.1.1 +pudb==2019.2 +pytorch-lightning==1.4.2 +streamlit>=0.73.1 +taming-transformers +test-tube>=0.7.5 +timm +torch-fidelity==0.3.0 +torchmetrics==0.6.0 +transformers==4.19.2 + +[tests] +codecov +flake8 +ftfy +interrogate +pytest +regex +xdoctest>=0.10.0 +yapf diff --git a/third-party/InterFormer/mmsegmentation.egg-info/top_level.txt b/third-party/InterFormer/mmsegmentation.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..21bba25bce73b52918643b3da93515ca25548ae0 --- /dev/null +++ b/third-party/InterFormer/mmsegmentation.egg-info/top_level.txt @@ -0,0 +1,2 @@ +mmseg +tests diff --git a/third-party/InterFormer/setup.cfg b/third-party/InterFormer/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..2ea07600c0b864d8ecbc4c293e1ad0d01594fcc0 --- /dev/null +++ b/third-party/InterFormer/setup.cfg @@ -0,0 +1,19 @@ +[yapf] +based_on_style = pep8 +blank_line_before_nested_class_or_def = true +split_before_expression_after_opening_paren = true + +[isort] +line_length = 79 +multi_line_output = 0 +extra_standard_library = setuptools +known_first_party = mmseg +known_third_party = PIL,cityscapesscripts,cv2,detail,matplotlib,mmcv,numpy,onnxruntime,packaging,prettytable,pytest,pytorch_sphinx_theme,requests,scipy,seaborn,torch,ts +no_lines_before = STDLIB,LOCALFOLDER +default_section = THIRDPARTY + +[codespell] +skip = *.po,*.ts,*.ipynb +count = +quiet-level = 3 +ignore-words-list = formating,sur,hist,dota,warmup,damon diff --git a/third-party/InterFormer/setup.py b/third-party/InterFormer/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..45d923db60e9720547e2bcdac2f5bec8c18c37f8 --- /dev/null +++ b/third-party/InterFormer/setup.py @@ -0,0 +1,200 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import os.path as osp +import platform +import shutil +import sys +import warnings +from setuptools import find_packages, setup + + +def readme(): + with open('README.md', encoding='utf-8') as f: + content = f.read() + return content + + +version_file = 'mmseg/version.py' + + +def get_version(): + with open(version_file) as f: + exec(compile(f.read(), version_file, 'exec')) + return locals()['__version__'] + + +def parse_requirements(fname='requirements.txt', with_version=True): + """Parse the package dependencies listed in a requirements file but strips + specific versioning information. + + Args: + fname (str): path to requirements file + with_version (bool, default=False): if True include version specs + + Returns: + List[str]: list of requirements items + + CommandLine: + python -c "import setup; print(setup.parse_requirements())" + """ + import re + import sys + from os.path import exists + require_fpath = fname + + def parse_line(line): + """Parse information from a line in a requirements text file.""" + if line.startswith('-r '): + # Allow specifying requirements in other files + target = line.split(' ')[1] + for info in parse_require_file(target): + yield info + else: + info = {'line': line} + if line.startswith('-e '): + info['package'] = line.split('#egg=')[1] + else: + # Remove versioning from the package + pat = '(' + '|'.join(['>=', '==', '>']) + ')' + parts = re.split(pat, line, maxsplit=1) + parts = [p.strip() for p in parts] + + info['package'] = parts[0] + if len(parts) > 1: + op, rest = parts[1:] + if ';' in rest: + # Handle platform specific dependencies + # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies + version, platform_deps = map(str.strip, + rest.split(';')) + info['platform_deps'] = platform_deps + else: + version = rest # NOQA + info['version'] = (op, version) + yield info + + def parse_require_file(fpath): + with open(fpath) as f: + for line in f.readlines(): + line = line.strip() + if line and not line.startswith('#'): + yield from parse_line(line) + + def gen_packages_items(): + if exists(require_fpath): + for info in parse_require_file(require_fpath): + parts = [info['package']] + if with_version and 'version' in info: + parts.extend(info['version']) + if not sys.version.startswith('3.4'): + # apparently package_deps are broken in 3.4 + platform_deps = info.get('platform_deps') + if platform_deps is not None: + parts.append(';' + platform_deps) + item = ''.join(parts) + yield item + + packages = list(gen_packages_items()) + return packages + + +def add_mim_extension(): + """Add extra files that are required to support MIM into the package. + + These files will be added by creating a symlink to the originals if the + package is installed in `editable` mode (e.g. pip install -e .), or by + copying from the originals otherwise. + """ + + # parse installment mode + if 'develop' in sys.argv: + # installed by `pip install -e .` + if platform.system() == 'Windows': + # set `copy` mode here since symlink fails on Windows. + mode = 'copy' + else: + mode = 'symlink' + elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv or \ + platform.system() == 'Windows': + # installed by `pip install .` + # or create source distribution by `python setup.py sdist` + # set `copy` mode here since symlink fails with WinError on Windows. + mode = 'copy' + else: + return + + filenames = ['tools', 'configs', 'model-index.yml', 'dataset-index.yml'] + repo_path = osp.dirname(__file__) + mim_path = osp.join(repo_path, 'mmseg', '.mim') + os.makedirs(mim_path, exist_ok=True) + + for filename in filenames: + if osp.exists(filename): + src_path = osp.join(repo_path, filename) + tar_path = osp.join(mim_path, filename) + + if osp.isfile(tar_path) or osp.islink(tar_path): + os.remove(tar_path) + elif osp.isdir(tar_path): + shutil.rmtree(tar_path) + + if mode == 'symlink': + src_relpath = osp.relpath(src_path, osp.dirname(tar_path)) + try: + os.symlink(src_relpath, tar_path) + except OSError: + # Creating a symbolic link on windows may raise an + # `OSError: [WinError 1314]` due to privilege. If + # the error happens, the src file will be copied + mode = 'copy' + warnings.warn( + f'Failed to create a symbolic link for {src_relpath}, ' + f'and it will be copied to {tar_path}') + else: + continue + + if mode == 'copy': + if osp.isfile(src_path): + shutil.copyfile(src_path, tar_path) + elif osp.isdir(src_path): + shutil.copytree(src_path, tar_path) + else: + warnings.warn(f'Cannot copy file {src_path}.') + else: + raise ValueError(f'Invalid mode {mode}') + + +if __name__ == '__main__': + add_mim_extension() + setup( + name='mmsegmentation', + version=get_version(), + description='Open MMLab Semantic Segmentation Toolbox and Benchmark', + long_description=readme(), + long_description_content_type='text/markdown', + author='MMSegmentation Contributors', + author_email='openmmlab@gmail.com', + keywords='computer vision, semantic segmentation', + url='https://github.com/open-mmlab/mmsegmentation', + packages=find_packages(exclude=('configs', 'tools', 'demo')), + include_package_data=True, + classifiers=[ + 'Development Status :: 4 - Beta', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + ], + license='Apache License 2.0', + install_requires=parse_requirements('requirements/runtime.txt'), + extras_require={ + 'all': parse_requirements('requirements.txt'), + 'tests': parse_requirements('requirements/tests.txt'), + 'optional': parse_requirements('requirements/optional.txt'), + 'mim': parse_requirements('requirements/mminstall.txt'), + 'multimodal': parse_requirements('requirements/multimodal.txt'), + }, + ext_modules=[], + zip_safe=False) diff --git a/third-party/InterFormer/tests/__init__.py b/third-party/InterFormer/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/third-party/InterFormer/tests/__init__.py @@ -0,0 +1 @@ + diff --git a/third-party/InterFormer/tests/data/biomedical.nii.gz b/third-party/InterFormer/tests/data/biomedical.nii.gz new file mode 100644 index 0000000000000000000000000000000000000000..ff0bf0e95c0dca3b8f06d198977b1c362728174d --- /dev/null +++ b/third-party/InterFormer/tests/data/biomedical.nii.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab47d6115b412ffaba041cbf48962967127f199f39eb56c777a6bb3746353b4a +size 49874 diff --git a/third-party/InterFormer/tests/data/biomedical.npy b/third-party/InterFormer/tests/data/biomedical.npy new file mode 100644 index 0000000000000000000000000000000000000000..696c5298296da1796c1f1560ee4dfe10e8e83b87 --- /dev/null +++ b/third-party/InterFormer/tests/data/biomedical.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dc2d45eef518602bf66823b332d35b8981c29faac06d223160fed2324fde565 +size 499928 diff --git a/third-party/InterFormer/tests/data/biomedical_ann.nii.gz b/third-party/InterFormer/tests/data/biomedical_ann.nii.gz new file mode 100644 index 0000000000000000000000000000000000000000..5d499706ff0e3dd20868dab8a8292a0e86cd64d4 --- /dev/null +++ b/third-party/InterFormer/tests/data/biomedical_ann.nii.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31e218cd74ee787c25a17a9cc3a13743ba8ecd11dd76fbad3c0c18c09fd8b396 +size 803 diff --git a/third-party/InterFormer/tests/data/color.jpg b/third-party/InterFormer/tests/data/color.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0d836ea802f953f9ec2c661264da9d0922bafc7b --- /dev/null +++ b/third-party/InterFormer/tests/data/color.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2eff7c1f5e8000d860ac240df63ed6c82d1e5659a5042c3a55cda536dc39833c +size 35851 diff --git a/third-party/InterFormer/tests/data/dataset.json b/third-party/InterFormer/tests/data/dataset.json new file mode 100644 index 0000000000000000000000000000000000000000..09b01235ec08b134ee4243d07ffae81206a2ef46 --- /dev/null +++ b/third-party/InterFormer/tests/data/dataset.json @@ -0,0 +1,30 @@ +{ + "name": "BRATS", + "description": "Gliomas segmentation tumour and oedema in on brain images", + "tensorImageSize": "4D", + "modality": { + "0": "FLAIR", + "1": "T1w", + "2": "t1gd", + "3": "T2w" + }, + "labels": { + "0": "background", + "1": "edema", + "2": "non-enhancing tumor", + "3": "enhancing tumour" + }, + "numTraining": 484, + "numTest": 266, + "training": [ + { + "image": "./imagesTr/BRATS_457.nii.gz", + "label": "./labelsTr/BRATS_457.nii.gz" + } + ], + "test": [ + "./imagesTs/BRATS_568.nii.gz", + "./imagesTs/BRATS_515.nii.gz", + "./imagesTs/BRATS_576.nii.gz" + ] +} diff --git a/third-party/InterFormer/tests/data/dsdl_seg/config.py b/third-party/InterFormer/tests/data/dsdl_seg/config.py new file mode 100644 index 0000000000000000000000000000000000000000..8eed751c2f747551aeb3fde1858187807d927445 --- /dev/null +++ b/third-party/InterFormer/tests/data/dsdl_seg/config.py @@ -0,0 +1,13 @@ +# Copyright (c) OpenMMLab. All rights reserved. +local = dict( + type='LocalFileReader', + working_dir='/nvme/share_data/VOC2012', +) + +ali_oss = dict( + type='AliOSSFileReader', + access_key_secret='your secret key of aliyun oss', + endpoint='your endpoint of aliyun oss', + access_key_id='your access key of aliyun oss', + bucket_name='your bucket name of aliyun oss', + working_dir='the relative path of your media dir in the bucket') diff --git a/third-party/InterFormer/tests/data/dsdl_seg/defs/class-dom.yaml b/third-party/InterFormer/tests/data/dsdl_seg/defs/class-dom.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5dd598c4ae584eb3b32b940a15747686bfc694f --- /dev/null +++ b/third-party/InterFormer/tests/data/dsdl_seg/defs/class-dom.yaml @@ -0,0 +1,24 @@ +$dsdl-version: "0.5.0" +VOCClassDom: + $def: class_domain + classes: + - aeroplane + - bicycle + - bird + - boat + - bottle + - bus + - car + - cat + - chair + - cow + - diningtable + - dog + - horse + - motorbike + - person + - pottedplant + - sheep + - sofa + - train + - tvmonitor diff --git a/third-party/InterFormer/tests/data/dsdl_seg/defs/segmentation-def.yaml b/third-party/InterFormer/tests/data/dsdl_seg/defs/segmentation-def.yaml new file mode 100644 index 0000000000000000000000000000000000000000..057139ed57e2a03863f14ee2907862c236512106 --- /dev/null +++ b/third-party/InterFormer/tests/data/dsdl_seg/defs/segmentation-def.yaml @@ -0,0 +1,15 @@ +$dsdl-version: "0.5.0" + +ImageMedia: + $def: struct + $fields: + image: Image + image_shape: ImageShape + +SegmentationSample: + $def: struct + $params: ['cdom'] + $fields: + media: ImageMedia + label_map: LabelMap[dom=$cdom] + instance_map: InstanceMap diff --git a/third-party/InterFormer/tests/data/dsdl_seg/set-train/train.yaml b/third-party/InterFormer/tests/data/dsdl_seg/set-train/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..69872445a535a8b22241f224ca10fd9f509b3202 --- /dev/null +++ b/third-party/InterFormer/tests/data/dsdl_seg/set-train/train.yaml @@ -0,0 +1,15 @@ +$dsdl-version: "0.5.0" +$import: + - ../defs/segmentation-def + - ../defs/class-dom +meta: + dataset_name: "VOC2012" + sub_dataset_name: "train" + task_type: "Segmentation" + dataset_homepage: "http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html" + dataset_publisher: "University of Leeds | ETHZ, Zurich | University of Edinburgh\ + \ |Microsoft Research Cambridge | University of Oxford" + OpenDataLab_address: "https://opendatalab.com/PASCAL_VOC2012/download" +data: + sample-type: SegmentationSample[cdom=VOCClassDom] + sample-path: train_samples.json diff --git a/third-party/InterFormer/tests/data/dsdl_seg/set-train/train_samples.json b/third-party/InterFormer/tests/data/dsdl_seg/set-train/train_samples.json new file mode 100644 index 0000000000000000000000000000000000000000..559f584572185dad95818be5e6ba2f4376f4fa90 --- /dev/null +++ b/third-party/InterFormer/tests/data/dsdl_seg/set-train/train_samples.json @@ -0,0 +1 @@ +{"samples": [{"media": {"image": "JPEGImages/2007_000032.jpg", "image_shape": [281, 500]}, "label_map": "SegmentationClass/2007_000032.png", "instance_map": "SegmentationObject/2007_000032.png"}, {"media": {"image": "JPEGImages/2007_000039.jpg", "image_shape": [375, 500]}, "label_map": "SegmentationClass/2007_000039.png", "instance_map": "SegmentationObject/2007_000039.png"}, {"media": {"image": "JPEGImages/2007_000063.jpg", "image_shape": [375, 500]}, "label_map": "SegmentationClass/2007_000063.png", "instance_map": "SegmentationObject/2007_000063.png"}]} diff --git a/third-party/InterFormer/tests/data/gray.jpg b/third-party/InterFormer/tests/data/gray.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ff5950e85dfbd17878a4979eed9e003be32be42e --- /dev/null +++ b/third-party/InterFormer/tests/data/gray.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cec2d88e594f6de1281d90d8369582b4a7b45bc9fe7bf29f570ff94d1799577 +size 39088 diff --git a/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/0004a4c0-d4dff0ad.jpg b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/0004a4c0-d4dff0ad.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ab0ce9a79181f7b053e86098a1b0681cfe4587c9 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/0004a4c0-d4dff0ad.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:adc083c4ed294579fa91181c70b53e686f6fa9cffb39ede5e7ad37da452c4dde +size 371 diff --git a/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/00054602-3bf57337.jpg b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/00054602-3bf57337.jpg new file mode 100644 index 0000000000000000000000000000000000000000..aad66746d49b6eb524f3dc11de0c9cac1a493916 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/00054602-3bf57337.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a47c378f5270292415f9d61d4d627bab6a4300237a0a1dbcc2510343b19a1c2 +size 364 diff --git a/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/00067cfb-e535423e.jpg b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/00067cfb-e535423e.jpg new file mode 100644 index 0000000000000000000000000000000000000000..69a1f9171226790e29c75db0ce1fb48a2c4cdd5c --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/train/00067cfb-e535423e.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d9b2b0f4a5a5af649c1230626bbf0c38d8d707ea86522bd7622f3ed09701e0f +size 367 diff --git a/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d06fefd-f7be05a6.jpg b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d06fefd-f7be05a6.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a8b7d841d559fc1b665036e20fb67ebf48492329 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d06fefd-f7be05a6.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43d3602bc7bdc732d4a8ad3f4f5a0cb57bd45015ba94b2b1f74e1a6cbbbb5ef5 +size 356 diff --git a/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d128593-0ccfea4c.jpg b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d128593-0ccfea4c.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b5ac696723250b3228e4556d409f37e048ddece4 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d128593-0ccfea4c.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c3d0a10c605ec25d3f651fb3222b90b9cee13a31328110b763e91ab858acb8e +size 347 diff --git a/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d15b18b-1e0d6e3f.jpg b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d15b18b-1e0d6e3f.jpg new file mode 100644 index 0000000000000000000000000000000000000000..94a0c61651f7fdcaeac8c03d7ca999bebbb810be --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_bdd100k_dataset/images/10k/val/7d15b18b-1e0d6e3f.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae956bfc16f0e7203a2cb52a23c20c3553b31026c7c87a1728a332df2f8382fe +size 387 diff --git a/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00000_img.jpg b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00000_img.jpg new file mode 100644 index 0000000000000000000000000000000000000000..be0e2acc6909524b535f330ce90eb3efeb4d8531 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00000_img.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf32fb407c11474d83e795716a3292560f6fb6751c8cbb8c046ec47a17cd8e8a +size 1633 diff --git a/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00001_img.jpg b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00001_img.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c349ecf46ccd2e494e942754060481ff019fb4eb --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00001_img.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a61b4fb430566a9cbd5021e924edbc9a547185d9544a9939ea36ac23c00183a +size 2356 diff --git a/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00002_img.jpg b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00002_img.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d3302c2dda9eb1e7ff3d458e1e0415e1f26dec92 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00002_img.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fa7b4000cc00b1f22178544cfe53bd355ef3ff29bc05674649b61091dee1ecb +size 1643 diff --git a/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00003_img.jpg b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00003_img.jpg new file mode 100644 index 0000000000000000000000000000000000000000..aaa77bc30d48725d502241320e18e8c875b5de12 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00003_img.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7be61be0b771340b6e3f92ce76a742c507bfe032ea9a2418adc25d85aa44192c +size 1859 diff --git a/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00004_img.jpg b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00004_img.jpg new file mode 100644 index 0000000000000000000000000000000000000000..39f316889a052c107e74da22627523a81141993a --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_dataset/imgs/00004_img.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94abc60b9f67d18ff421e20257da83bef8eb7a195b22640ddf925f825bf321f7 +size 1902 diff --git a/third-party/InterFormer/tests/data/pseudo_dataset/splits/train.txt b/third-party/InterFormer/tests/data/pseudo_dataset/splits/train.txt new file mode 100644 index 0000000000000000000000000000000000000000..9e25ab0266ec1191b5eba9a2c1b353cfd7541524 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_dataset/splits/train.txt @@ -0,0 +1,4 @@ +00000 +00001 +00002 +00003 diff --git a/third-party/InterFormer/tests/data/pseudo_dataset/splits/val.txt b/third-party/InterFormer/tests/data/pseudo_dataset/splits/val.txt new file mode 100644 index 0000000000000000000000000000000000000000..59dd536625d36884256d1e6f24cbae2a96579396 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_dataset/splits/val.txt @@ -0,0 +1 @@ +00004 diff --git a/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1111_577_TC.npy b/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1111_577_TC.npy new file mode 100644 index 0000000000000000000000000000000000000000..db8bd9089c1094884f6b464ce5ea5cc54246e8cf --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1111_577_TC.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64fc910e35d2db97a9d2e0a93ba213f2b1f2b28cd482a830c4a632dd0396d746 +size 8834528 diff --git a/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1112_569_TC.npy b/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1112_569_TC.npy new file mode 100644 index 0000000000000000000000000000000000000000..249ec0468875c8c0f45116e4c849cc734f670ecc --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1112_569_TC.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aef7d35c123c99b729e6f40302b98324fbdae993b739615c350e9c53980026c5 +size 8834528 diff --git a/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1113_557_TC.npy b/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1113_557_TC.npy new file mode 100644 index 0000000000000000000000000000000000000000..c8f2ec5309e90727aace9e8cce41a23aac78b7b4 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_hsidrive20_dataset/images/test/nf1113_557_TC.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31a6bedbbe50e0936fecbb2276e680c9f4358e5dd11b8ece3772668513bb7edb +size 8834528 diff --git a/third-party/InterFormer/tests/data/pseudo_isaid_dataset/splits/train.txt b/third-party/InterFormer/tests/data/pseudo_isaid_dataset/splits/train.txt new file mode 100644 index 0000000000000000000000000000000000000000..c310167fe19d7e67d21310f1b788f03eca41bfcc --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_isaid_dataset/splits/train.txt @@ -0,0 +1 @@ +P0000_0_896_1536_2432 diff --git a/third-party/InterFormer/tests/data/pseudo_isaid_dataset/splits/val.txt b/third-party/InterFormer/tests/data/pseudo_isaid_dataset/splits/val.txt new file mode 100644 index 0000000000000000000000000000000000000000..aeff0ee339dc81465d6ae88d5ac051c3119f7c29 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_isaid_dataset/splits/val.txt @@ -0,0 +1 @@ +P0000_0_896_1024_1920 diff --git a/third-party/InterFormer/tests/data/pseudo_lip_dataset/train_images/684_2150041.jpg b/third-party/InterFormer/tests/data/pseudo_lip_dataset/train_images/684_2150041.jpg new file mode 100644 index 0000000000000000000000000000000000000000..eecd4ecb21c63b748c697980558845902e78739c --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_lip_dataset/train_images/684_2150041.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0cc7e5c975cec94e6e5f3232177916473389ff09352774ffa3eb8c301f8bded +size 10950 diff --git a/third-party/InterFormer/tests/data/pseudo_lip_dataset/val_images/86_185913.jpg b/third-party/InterFormer/tests/data/pseudo_lip_dataset/val_images/86_185913.jpg new file mode 100644 index 0000000000000000000000000000000000000000..aee5ae9f4e370d1bcbcf5e8ed823623fe5e77956 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_lip_dataset/val_images/86_185913.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48673c58759ef5526bac12ce7883faa38937f1cd186034a7c60e4c57d33abe63 +size 13383 diff --git a/third-party/InterFormer/tests/data/pseudo_mapillary_dataset/images/__CRyFzoDOXn6unQ6a3DnQ.jpg b/third-party/InterFormer/tests/data/pseudo_mapillary_dataset/images/__CRyFzoDOXn6unQ6a3DnQ.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d9f3a358193c4fa3d55724c30808139de8826d72 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_mapillary_dataset/images/__CRyFzoDOXn6unQ6a3DnQ.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e78aab8f48533ba4a49623e0181cb046ec68722630bc5248622d2e513fdd312f +size 2201 diff --git a/third-party/InterFormer/tests/data/pseudo_nyu_dataset/images/bookstore_0001d_00001.jpg b/third-party/InterFormer/tests/data/pseudo_nyu_dataset/images/bookstore_0001d_00001.jpg new file mode 100644 index 0000000000000000000000000000000000000000..95884d836cc2ef783c1062c36e330885fe375b24 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_nyu_dataset/images/bookstore_0001d_00001.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7528c309c3c4799373a395dc44615a2faacffd3308467ddc48589eb2a2ab9fb +size 10775 diff --git a/third-party/InterFormer/tests/data/pseudo_synapse_dataset/img_dir/case0005_slice000.jpg b/third-party/InterFormer/tests/data/pseudo_synapse_dataset/img_dir/case0005_slice000.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a74b2b59b96961f6bc6d0e8085ece07444d83015 --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_synapse_dataset/img_dir/case0005_slice000.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c13f6cece62b7700cd65c6f1ec74b13fec027ac0ed7a0d1a3936c9760d2518d +size 33367 diff --git a/third-party/InterFormer/tests/data/pseudo_synapse_dataset/img_dir/case0005_slice001.jpg b/third-party/InterFormer/tests/data/pseudo_synapse_dataset/img_dir/case0005_slice001.jpg new file mode 100644 index 0000000000000000000000000000000000000000..713cf5d64a232eb8c9fdb0f2f82d6e3ef6582e7b --- /dev/null +++ b/third-party/InterFormer/tests/data/pseudo_synapse_dataset/img_dir/case0005_slice001.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:015e523fc7a19aba409ffa33b1d0b6cace05ea188f4c5f90fa7956b61a1a19d6 +size 33679 diff --git a/third-party/InterFormer/tests/test_apis/test_inferencer.py b/third-party/InterFormer/tests/test_apis/test_inferencer.py new file mode 100644 index 0000000000000000000000000000000000000000..d8dbce8f38583782b6a973c23da81a215a84d453 --- /dev/null +++ b/third-party/InterFormer/tests/test_apis/test_inferencer.py @@ -0,0 +1,60 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import tempfile + +import numpy as np +import torch +from mmengine import ConfigDict +from utils import * # noqa: F401, F403 + +from mmseg.apis import MMSegInferencer +from mmseg.registry import MODELS +from mmseg.utils import register_all_modules + + +def test_inferencer(): + register_all_modules() + + visualizer = dict( + type='SegLocalVisualizer', + vis_backends=[dict(type='LocalVisBackend')], + name='visualizer') + + cfg_dict = dict( + model=dict( + type='InferExampleModel', + data_preprocessor=dict(type='SegDataPreProcessor'), + backbone=dict(type='InferExampleBackbone'), + decode_head=dict(type='InferExampleHead'), + test_cfg=dict(mode='whole')), + visualizer=visualizer, + test_dataloader=dict( + dataset=dict( + type='ExampleDataset', + pipeline=[ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') + ]), )) + cfg = ConfigDict(cfg_dict) + model = MODELS.build(cfg.model) + + ckpt = model.state_dict() + ckpt_filename = tempfile.mktemp() + torch.save(ckpt, ckpt_filename) + + # test initialization + infer = MMSegInferencer(cfg, ckpt_filename) + + # test forward + img = np.random.randint(0, 256, (4, 4, 3)) + infer(img) + + imgs = [img, img] + infer(imgs) + results = infer(imgs, out_dir=tempfile.gettempdir()) + + # test results + assert 'predictions' in results + assert 'visualization' in results + assert len(results['predictions']) == 2 + assert results['predictions'][0].shape == (4, 4) diff --git a/third-party/InterFormer/tests/test_apis/test_rs_inferencer.py b/third-party/InterFormer/tests/test_apis/test_rs_inferencer.py new file mode 100644 index 0000000000000000000000000000000000000000..03423d9680e11a9e935352574c4d7a3b79c27710 --- /dev/null +++ b/third-party/InterFormer/tests/test_apis/test_rs_inferencer.py @@ -0,0 +1,73 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from unittest import TestCase + +import numpy as np +from mmengine import ConfigDict, init_default_scope +from utils import * # noqa: F401, F403 + +from mmseg.apis import RSImage, RSInferencer +from mmseg.registry import MODELS + + +class TestRSImage(TestCase): + + def test_read_whole_image(self): + init_default_scope('mmseg') + img_path = osp.join( + osp.dirname(__file__), + '../data/pseudo_loveda_dataset/img_dir/0.png') + rs_image = RSImage(img_path) + window_size = (16, 16) + rs_image.create_grids(window_size) + image_data = rs_image.read(rs_image.grids[0]) + self.assertIsNotNone(image_data) + + def test_write_image_data(self): + init_default_scope('mmseg') + img_path = osp.join( + osp.dirname(__file__), + '../data/pseudo_loveda_dataset/img_dir/0.png') + rs_image = RSImage(img_path) + window_size = (16, 16) + rs_image.create_grids(window_size) + data = np.random.random((16, 16)).astype(np.int8) + rs_image.write(data, rs_image.grids[0]) + + +class TestRSInferencer(TestCase): + + def test_read_and_inference(self): + init_default_scope('mmseg') + cfg_dict = dict( + model=dict( + type='InferExampleModel', + data_preprocessor=dict(type='SegDataPreProcessor'), + backbone=dict(type='InferExampleBackbone'), + decode_head=dict(type='InferExampleHead'), + test_cfg=dict(mode='whole')), + test_dataloader=dict( + dataset=dict( + type='ExampleDataset', + pipeline=[ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') + ])), + test_pipeline=[ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') + ]) + cfg = ConfigDict(cfg_dict) + model = MODELS.build(cfg.model) + model.cfg = cfg + inferencer = RSInferencer.from_model(model) + + img_path = osp.join( + osp.dirname(__file__), + '../data/pseudo_loveda_dataset/img_dir/0.png') + rs_image = RSImage(img_path) + window_size = (16, 16) + stride = (16, 16) + inferencer.run(rs_image, window_size, stride) diff --git a/third-party/InterFormer/tests/test_apis/utils.py b/third-party/InterFormer/tests/test_apis/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0a9928fccf1110b7ca44e53a159ee1450d9a9bb3 --- /dev/null +++ b/third-party/InterFormer/tests/test_apis/utils.py @@ -0,0 +1,38 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn + +from mmseg.models import EncoderDecoder +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.registry import MODELS + + +@MODELS.register_module(name='InferExampleHead') +class ExampleDecodeHead(BaseDecodeHead): + + def __init__(self, num_classes=19, out_channels=None): + super().__init__( + 3, 3, num_classes=num_classes, out_channels=out_channels) + + def forward(self, inputs): + return self.cls_seg(inputs[0]) + + +@MODELS.register_module(name='InferExampleBackbone') +class ExampleBackbone(nn.Module): + + def __init__(self): + super().__init__() + self.conv = nn.Conv2d(3, 3, 3) + + def init_weights(self, pretrained=None): + pass + + def forward(self, x): + return [self.conv(x)] + + +@MODELS.register_module(name='InferExampleModel') +class ExampleModel(EncoderDecoder): + + def __init__(self, **kwargs): + super().__init__(**kwargs) diff --git a/third-party/InterFormer/tests/test_config.py b/third-party/InterFormer/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd85ff57cd50b56f96cbb8c09ddd607ee92dfa9 --- /dev/null +++ b/third-party/InterFormer/tests/test_config.py @@ -0,0 +1,175 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import glob +import os +from os.path import dirname, exists, isdir, join, relpath + +import numpy as np +from mmengine import Config +from mmengine.dataset import Compose +from mmengine.registry import init_default_scope +from torch import nn + +from mmseg.models import build_segmentor + + +def _get_config_directory(): + """Find the predefined segmentor config directory.""" + try: + # Assume we are running in the source mmsegmentation repo + repo_dpath = dirname(dirname(__file__)) + except NameError: + # For IPython development when this __file__ is not defined + import mmseg + repo_dpath = dirname(dirname(mmseg.__file__)) + config_dpath = join(repo_dpath, 'configs') + if not exists(config_dpath): + raise Exception('Cannot find config path') + return config_dpath + + +def test_config_build_segmentor(): + """Test that all segmentation models defined in the configs can be + initialized.""" + init_default_scope('mmseg') + config_dpath = _get_config_directory() + print(f'Found config_dpath = {config_dpath!r}') + + config_fpaths = [] + # one config each sub folder + for sub_folder in os.listdir(config_dpath): + if isdir(sub_folder): + config_fpaths.append( + list(glob.glob(join(config_dpath, sub_folder, '*.py')))[0]) + config_fpaths = [p for p in config_fpaths if p.find('_base_') == -1] + config_names = [relpath(p, config_dpath) for p in config_fpaths] + + print(f'Using {len(config_names)} config files') + + for config_fname in config_names: + config_fpath = join(config_dpath, config_fname) + config_mod = Config.fromfile(config_fpath) + + config_mod.model + print(f'Building segmentor, config_fpath = {config_fpath!r}') + + # Remove pretrained keys to allow for testing in an offline environment + if 'pretrained' in config_mod.model: + config_mod.model['pretrained'] = None + + print(f'building {config_fname}') + segmentor = build_segmentor(config_mod.model) + assert segmentor is not None + + head_config = config_mod.model['decode_head'] + _check_decode_head(head_config, segmentor.decode_head) + + +def test_config_data_pipeline(): + """Test whether the data pipeline is valid and can process corner cases. + + CommandLine: + xdoctest -m tests/test_config.py test_config_build_data_pipeline + """ + + init_default_scope('mmseg') + config_dpath = _get_config_directory() + print(f'Found config_dpath = {config_dpath!r}') + + import glob + config_fpaths = list(glob.glob(join(config_dpath, '**', '*.py'))) + config_fpaths = [p for p in config_fpaths if p.find('_base_') == -1] + config_names = [relpath(p, config_dpath) for p in config_fpaths] + + print(f'Using {len(config_names)} config files') + + for config_fname in config_names: + config_fpath = join(config_dpath, config_fname) + print(f'Building data pipeline, config_fpath = {config_fpath!r}') + config_mod = Config.fromfile(config_fpath) + + # remove loading pipeline + load_img_pipeline = config_mod.train_pipeline.pop(0) + to_float32 = load_img_pipeline.get('to_float32', False) + del config_mod.train_pipeline[0] + del config_mod.test_pipeline[0] + # remove loading annotation in test pipeline + load_anno_idx = -1 + for i in range(len(config_mod.test_pipeline)): + if config_mod.test_pipeline[i].type in ('LoadAnnotations', + 'LoadDepthAnnotation'): + load_anno_idx = i + del config_mod.test_pipeline[load_anno_idx] + + train_pipeline = Compose(config_mod.train_pipeline) + test_pipeline = Compose(config_mod.test_pipeline) + + img = np.random.randint(0, 255, size=(1024, 2048, 3), dtype=np.uint8) + if to_float32: + img = img.astype(np.float32) + seg = np.random.randint(0, 255, size=(1024, 2048, 1), dtype=np.uint8) + depth = np.random.rand(1024, 2048).astype(np.float32) + + results = dict( + filename='test_img.png', + ori_filename='test_img.png', + img=img, + img_shape=img.shape, + ori_shape=img.shape, + gt_seg_map=seg, + gt_depth_map=depth) + results['seg_fields'] = ['gt_seg_map'] + _check_concat_cd_input(config_mod, results) + print(f'Test training data pipeline: \n{train_pipeline!r}') + output_results = train_pipeline(results) + assert output_results is not None + + _check_concat_cd_input(config_mod, results) + print(f'Test testing data pipeline: \n{test_pipeline!r}') + output_results = test_pipeline(results) + assert output_results is not None + + +def _check_concat_cd_input(config_mod: Config, results: dict): + keys = [] + pipeline = config_mod.train_pipeline.copy() + pipeline.extend(config_mod.test_pipeline) + for t in pipeline: + keys.append(t.type) + if 'ConcatCDInput' in keys: + results.update({'img2': results['img']}) + + +def _check_decode_head(decode_head_cfg, decode_head): + if isinstance(decode_head_cfg, list): + assert isinstance(decode_head, nn.ModuleList) + assert len(decode_head_cfg) == len(decode_head) + num_heads = len(decode_head) + for i in range(num_heads): + _check_decode_head(decode_head_cfg[i], decode_head[i]) + return + # check consistency between head_config and roi_head + assert decode_head_cfg['type'] == decode_head.__class__.__name__ + + assert decode_head_cfg['type'] == decode_head.__class__.__name__ + + in_channels = decode_head_cfg.in_channels + input_transform = decode_head.input_transform + assert input_transform in ['resize_concat', 'multiple_select', None] + if input_transform is not None: + assert isinstance(in_channels, (list, tuple)) + assert isinstance(decode_head.in_index, (list, tuple)) + assert len(in_channels) == len(decode_head.in_index) + elif input_transform == 'resize_concat': + assert sum(in_channels) == decode_head.in_channels + else: + assert in_channels == decode_head.in_channels + + if decode_head_cfg['type'] == 'PointHead': + assert decode_head_cfg.channels+decode_head_cfg.num_classes == \ + decode_head.fc_seg.in_channels + assert decode_head.fc_seg.out_channels == decode_head_cfg.num_classes + elif decode_head_cfg['type'] == 'VPDDepthHead': + assert decode_head.out_channels == 1 + else: + assert decode_head_cfg.channels == decode_head.conv_seg.in_channels + assert decode_head.conv_seg.out_channels == decode_head_cfg.num_classes diff --git a/third-party/InterFormer/tests/test_datasets/test_dataset.py b/third-party/InterFormer/tests/test_datasets/test_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..2904e09ceddbd9c8870cee0e3d0bbf1e2de1d2bb --- /dev/null +++ b/third-party/InterFormer/tests/test_datasets/test_dataset.py @@ -0,0 +1,475 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import os.path as osp +import tempfile + +import pytest + +from mmseg.datasets import (ADE20KDataset, BaseSegDataset, BDD100KDataset, + CityscapesDataset, COCOStuffDataset, + DecathlonDataset, DSDLSegDataset, ISPRSDataset, + LIPDataset, LoveDADataset, MapillaryDataset_v1, + MapillaryDataset_v2, NYUDataset, PascalVOCDataset, + PotsdamDataset, REFUGEDataset, SynapseDataset, + iSAIDDataset) +from mmseg.registry import DATASETS +from mmseg.utils import get_classes, get_palette + +try: + from dsdl.dataset import DSDLDataset +except ImportError: + DSDLDataset = None + + +def test_classes(): + assert list( + CityscapesDataset.METAINFO['classes']) == get_classes('cityscapes') + assert list(PascalVOCDataset.METAINFO['classes']) == get_classes( + 'voc') == get_classes('pascal_voc') + assert list(ADE20KDataset.METAINFO['classes']) == get_classes( + 'ade') == get_classes('ade20k') + assert list( + COCOStuffDataset.METAINFO['classes']) == get_classes('cocostuff') + assert list(LoveDADataset.METAINFO['classes']) == get_classes('loveda') + assert list(PotsdamDataset.METAINFO['classes']) == get_classes('potsdam') + assert list(ISPRSDataset.METAINFO['classes']) == get_classes('vaihingen') + assert list(iSAIDDataset.METAINFO['classes']) == get_classes('isaid') + assert list( + MapillaryDataset_v1.METAINFO['classes']) == get_classes('mapillary_v1') + assert list( + MapillaryDataset_v2.METAINFO['classes']) == get_classes('mapillary_v2') + assert list(BDD100KDataset.METAINFO['classes']) == get_classes('bdd100k') + with pytest.raises(ValueError): + get_classes('unsupported') + + +def test_classes_file_path(): + tmp_file = tempfile.NamedTemporaryFile() + classes_path = f'{tmp_file.name}.txt' + train_pipeline = [] + kwargs = dict( + pipeline=train_pipeline, + data_prefix=dict(img_path='./', seg_map_path='./'), + metainfo=dict(classes=classes_path)) + + # classes.txt with full categories + categories = get_classes('cityscapes') + with open(classes_path, 'w') as f: + f.write('\n'.join(categories)) + dataset = CityscapesDataset(**kwargs) + assert list(dataset.metainfo['classes']) == categories + assert dataset.label_map is None + + # classes.txt with sub categories + categories = ['road', 'sidewalk', 'building'] + with open(classes_path, 'w') as f: + f.write('\n'.join(categories)) + dataset = CityscapesDataset(**kwargs) + assert list(dataset.metainfo['classes']) == categories + assert dataset.label_map is not None + + # classes.txt with unknown categories + categories = ['road', 'sidewalk', 'unknown'] + with open(classes_path, 'w') as f: + f.write('\n'.join(categories)) + + with pytest.raises(ValueError): + CityscapesDataset(**kwargs) + + tmp_file.close() + os.remove(classes_path) + assert not osp.exists(classes_path) + + +def test_palette(): + assert CityscapesDataset.METAINFO['palette'] == get_palette('cityscapes') + assert PascalVOCDataset.METAINFO['palette'] == get_palette( + 'voc') == get_palette('pascal_voc') + assert ADE20KDataset.METAINFO['palette'] == get_palette( + 'ade') == get_palette('ade20k') + assert LoveDADataset.METAINFO['palette'] == get_palette('loveda') + assert PotsdamDataset.METAINFO['palette'] == get_palette('potsdam') + assert COCOStuffDataset.METAINFO['palette'] == get_palette('cocostuff') + assert iSAIDDataset.METAINFO['palette'] == get_palette('isaid') + assert list( + MapillaryDataset_v1.METAINFO['palette']) == get_palette('mapillary_v1') + assert list( + MapillaryDataset_v2.METAINFO['palette']) == get_palette('mapillary_v2') + assert list(BDD100KDataset.METAINFO['palette']) == get_palette('bdd100k') + with pytest.raises(ValueError): + get_palette('unsupported') + + +def test_custom_dataset(): + + # with 'img_path' and 'seg_map_path' in data_prefix + train_dataset = BaseSegDataset( + data_root=osp.join(osp.dirname(__file__), '../data/pseudo_dataset'), + data_prefix=dict( + img_path='imgs/', + seg_map_path='gts/', + ), + img_suffix='img.jpg', + seg_map_suffix='gt.png') + assert len(train_dataset) == 5 + + # with 'img_path' and 'seg_map_path' in data_prefix and ann_file + train_dataset = BaseSegDataset( + data_root=osp.join(osp.dirname(__file__), '../data/pseudo_dataset'), + data_prefix=dict( + img_path='imgs/', + seg_map_path='gts/', + ), + img_suffix='img.jpg', + seg_map_suffix='gt.png', + ann_file='splits/train.txt') + assert len(train_dataset) == 4 + + # no data_root + train_dataset = BaseSegDataset( + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), '../data/pseudo_dataset/imgs'), + seg_map_path=osp.join( + osp.dirname(__file__), '../data/pseudo_dataset/gts')), + img_suffix='img.jpg', + seg_map_suffix='gt.png') + assert len(train_dataset) == 5 + + # with data_root but 'img_path' and 'seg_map_path' in data_prefix are + # abs path + train_dataset = BaseSegDataset( + data_root=osp.join(osp.dirname(__file__), '../data/pseudo_dataset'), + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), '../data/pseudo_dataset/imgs'), + seg_map_path=osp.join( + osp.dirname(__file__), '../data/pseudo_dataset/gts')), + img_suffix='img.jpg', + seg_map_suffix='gt.png') + assert len(train_dataset) == 5 + + # test_mode=True + test_dataset = BaseSegDataset( + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), '../data/pseudo_dataset/imgs')), + img_suffix='img.jpg', + test_mode=True, + metainfo=dict(classes=('pseudo_class', ))) + assert len(test_dataset) == 5 + + # training data get + train_data = train_dataset[0] + assert isinstance(train_data, dict) + assert 'img_path' in train_data and osp.isfile(train_data['img_path']) + assert 'seg_map_path' in train_data and osp.isfile( + train_data['seg_map_path']) + + # test data get + test_data = test_dataset[0] + assert isinstance(test_data, dict) + assert 'img_path' in train_data and osp.isfile(train_data['img_path']) + assert 'seg_map_path' in train_data and osp.isfile( + train_data['seg_map_path']) + + +def test_ade(): + test_dataset = ADE20KDataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), '../data/pseudo_dataset/imgs'))) + assert len(test_dataset) == 5 + + +def test_cityscapes(): + test_dataset = CityscapesDataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_cityscapes_dataset/leftImg8bit/val'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_cityscapes_dataset/gtFine/val'))) + assert len(test_dataset) == 1 + + +def test_loveda(): + test_dataset = LoveDADataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_loveda_dataset/img_dir'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_loveda_dataset/ann_dir'))) + assert len(test_dataset) == 3 + + +def test_potsdam(): + test_dataset = PotsdamDataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_potsdam_dataset/img_dir'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_potsdam_dataset/ann_dir'))) + assert len(test_dataset) == 1 + + +def test_vaihingen(): + test_dataset = ISPRSDataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_vaihingen_dataset/img_dir'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_vaihingen_dataset/ann_dir'))) + assert len(test_dataset) == 1 + + +def test_synapse(): + test_dataset = SynapseDataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_synapse_dataset/img_dir'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_synapse_dataset/ann_dir'))) + assert len(test_dataset) == 2 + + +def test_refuge(): + test_dataset = REFUGEDataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_refuge_dataset/img_dir'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_refuge_dataset/ann_dir'))) + assert len(test_dataset) == 1 + + +def test_isaid(): + test_dataset = iSAIDDataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), '../data/pseudo_isaid_dataset/img_dir'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_isaid_dataset/ann_dir'))) + assert len(test_dataset) == 2 + test_dataset = iSAIDDataset( + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), '../data/pseudo_isaid_dataset/img_dir'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_isaid_dataset/ann_dir')), + ann_file=osp.join( + osp.dirname(__file__), + '../data/pseudo_isaid_dataset/splits/train.txt')) + assert len(test_dataset) == 1 + + +def test_decathlon(): + data_root = osp.join(osp.dirname(__file__), '../data') + # test load training dataset + test_dataset = DecathlonDataset( + pipeline=[], data_root=data_root, ann_file='dataset.json') + assert len(test_dataset) == 1 + + # test load test dataset + test_dataset = DecathlonDataset( + pipeline=[], + data_root=data_root, + ann_file='dataset.json', + test_mode=True) + assert len(test_dataset) == 3 + + +def test_lip(): + data_root = osp.join(osp.dirname(__file__), '../data/pseudo_lip_dataset') + # train load training dataset + train_dataset = LIPDataset( + pipeline=[], + data_root=data_root, + data_prefix=dict( + img_path='train_images', seg_map_path='train_segmentations')) + assert len(train_dataset) == 1 + + # test load training dataset + test_dataset = LIPDataset( + pipeline=[], + data_root=data_root, + data_prefix=dict( + img_path='val_images', seg_map_path='val_segmentations')) + assert len(test_dataset) == 1 + + +def test_mapillary(): + test_dataset = MapillaryDataset_v1( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_mapillary_dataset/images'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_mapillary_dataset/v1.2'))) + assert len(test_dataset) == 1 + + +def test_bdd100k(): + test_dataset = BDD100KDataset( + pipeline=[], + data_prefix=dict( + img_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_bdd100k_dataset/images/10k/val'), + seg_map_path=osp.join( + osp.dirname(__file__), + '../data/pseudo_bdd100k_dataset/labels/sem_seg/masks/val'))) + assert len(test_dataset) == 3 + + +@pytest.mark.parametrize('dataset, classes', [ + ('ADE20KDataset', ('wall', 'building')), + ('CityscapesDataset', ('road', 'sidewalk')), + ('BaseSegDataset', ('bus', 'car')), + ('PascalVOCDataset', ('aeroplane', 'bicycle')), +]) +def test_custom_classes_override_default(dataset, classes): + + dataset_class = DATASETS.get(dataset) + original_classes = dataset_class.METAINFO.get('classes', None) + + tmp_file = tempfile.NamedTemporaryFile() + ann_file = tmp_file.name + img_path = tempfile.mkdtemp() + + # Test setting classes as a tuple + custom_dataset = dataset_class( + data_prefix=dict(img_path=img_path), + ann_file=ann_file, + metainfo=dict(classes=classes), + test_mode=True, + lazy_init=True) + + assert custom_dataset.metainfo['classes'] != original_classes + assert custom_dataset.metainfo['classes'] == classes + if not isinstance(custom_dataset, BaseSegDataset): + assert isinstance(custom_dataset.label_map, dict) + + # Test setting classes as a list + custom_dataset = dataset_class( + data_prefix=dict(img_path=img_path), + ann_file=ann_file, + metainfo=dict(classes=list(classes)), + test_mode=True, + lazy_init=True) + + assert custom_dataset.metainfo['classes'] != original_classes + assert custom_dataset.metainfo['classes'] == list(classes) + if not isinstance(custom_dataset, BaseSegDataset): + assert isinstance(custom_dataset.label_map, dict) + + # Test overriding not a subset + custom_dataset = dataset_class( + ann_file=ann_file, + data_prefix=dict(img_path=img_path), + metainfo=dict(classes=[classes[0]]), + test_mode=True, + lazy_init=True) + + assert custom_dataset.metainfo['classes'] != original_classes + assert custom_dataset.metainfo['classes'] == [classes[0]] + if not isinstance(custom_dataset, BaseSegDataset): + assert isinstance(custom_dataset.label_map, dict) + + # Test default behavior + if dataset_class is BaseSegDataset: + with pytest.raises(AssertionError): + custom_dataset = dataset_class( + ann_file=ann_file, + data_prefix=dict(img_path=img_path), + metainfo=None, + test_mode=True, + lazy_init=True) + else: + custom_dataset = dataset_class( + data_prefix=dict(img_path=img_path), + ann_file=ann_file, + metainfo=None, + test_mode=True, + lazy_init=True) + + assert custom_dataset.METAINFO['classes'] == original_classes + assert custom_dataset.label_map is None + + +def test_custom_dataset_random_palette_is_generated(): + dataset = BaseSegDataset( + pipeline=[], + data_prefix=dict(img_path=tempfile.mkdtemp()), + ann_file=tempfile.mkdtemp(), + metainfo=dict(classes=('bus', 'car')), + lazy_init=True, + test_mode=True) + assert len(dataset.metainfo['palette']) == 2 + for class_color in dataset.metainfo['palette']: + assert len(class_color) == 3 + assert all(x >= 0 and x <= 255 for x in class_color) + + +def test_custom_dataset_custom_palette(): + dataset = BaseSegDataset( + data_prefix=dict(img_path=tempfile.mkdtemp()), + ann_file=tempfile.mkdtemp(), + metainfo=dict( + classes=('bus', 'car'), palette=[[100, 100, 100], [200, 200, + 200]]), + lazy_init=True, + test_mode=True) + assert tuple(dataset.metainfo['palette']) == tuple([[100, 100, 100], + [200, 200, 200]]) + # test custom class and palette don't match + with pytest.raises(ValueError): + dataset = BaseSegDataset( + data_prefix=dict(img_path=tempfile.mkdtemp()), + ann_file=tempfile.mkdtemp(), + metainfo=dict(classes=('bus', 'car'), palette=[[200, 200, 200]]), + lazy_init=True) + + +def test_dsdlseg_dataset(): + if DSDLDataset is not None: + dataset = DSDLSegDataset( + data_root='tests/data/dsdl_seg', ann_file='set-train/train.yaml') + assert len(dataset) == 3 + assert len(dataset.metainfo['classes']) == 21 + else: + ImportWarning('Package `dsdl` is not installed.') + + +def test_nyu_dataset(): + dataset = NYUDataset( + data_root='tests/data/pseudo_nyu_dataset', + data_prefix=dict(img_path='images', depth_map_path='annotations'), + ) + assert len(dataset) == 1 + data = dataset[0] + assert data.get('depth_map_path', None) is not None + assert data.get('category_id', -1) == 26 diff --git a/third-party/InterFormer/tests/test_datasets/test_dataset_builder.py b/third-party/InterFormer/tests/test_datasets/test_dataset_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..b67b1e7aaf07f8e4c3016021cbee36a23e4fc4cc --- /dev/null +++ b/third-party/InterFormer/tests/test_datasets/test_dataset_builder.py @@ -0,0 +1,152 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp + +from mmengine.dataset import ConcatDataset, RepeatDataset +from mmengine.registry import init_default_scope + +from mmseg.datasets import MultiImageMixDataset +from mmseg.registry import DATASETS + +init_default_scope('mmseg') + + +@DATASETS.register_module() +class ToyDataset: + + def __init__(self, cnt=0): + self.cnt = cnt + + def __item__(self, idx): + return idx + + def __len__(self): + return 100 + + +def test_build_dataset(): + cfg = dict(type='ToyDataset') + dataset = DATASETS.build(cfg) + assert isinstance(dataset, ToyDataset) + assert dataset.cnt == 0 + dataset = DATASETS.build(cfg, default_args=dict(cnt=1)) + assert isinstance(dataset, ToyDataset) + assert dataset.cnt == 1 + + data_root = osp.join(osp.dirname(__file__), '../data/pseudo_dataset') + data_prefix = dict(img_path='imgs/', seg_map_path='gts/') + + # test RepeatDataset + cfg = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=data_prefix, + serialize_data=False) + dataset = DATASETS.build(cfg) + dataset_repeat = RepeatDataset(dataset=dataset, times=5) + assert isinstance(dataset_repeat, RepeatDataset) + assert len(dataset_repeat) == 25 + + # test ConcatDataset + # We use same dir twice for simplicity + # with data_prefix.seg_map_path + cfg1 = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=data_prefix, + serialize_data=False) + cfg2 = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=data_prefix, + serialize_data=False) + dataset1 = DATASETS.build(cfg1) + dataset2 = DATASETS.build(cfg2) + dataset_concat = ConcatDataset(datasets=[dataset1, dataset2]) + assert isinstance(dataset_concat, ConcatDataset) + assert len(dataset_concat) == 10 + + # test MultiImageMixDataset + dataset = MultiImageMixDataset(dataset=dataset_concat, pipeline=[]) + assert isinstance(dataset, MultiImageMixDataset) + assert len(dataset) == 10 + + cfg = dict(type='ConcatDataset', datasets=[cfg1, cfg2]) + + dataset = MultiImageMixDataset(dataset=cfg, pipeline=[]) + assert isinstance(dataset, MultiImageMixDataset) + assert len(dataset) == 10 + + # with data_prefix.seg_map_path, ann_file + cfg1 = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=data_prefix, + ann_file='splits/train.txt', + serialize_data=False) + cfg2 = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=data_prefix, + ann_file='splits/val.txt', + serialize_data=False) + + dataset1 = DATASETS.build(cfg1) + dataset2 = DATASETS.build(cfg2) + dataset_concat = ConcatDataset(datasets=[dataset1, dataset2]) + assert isinstance(dataset_concat, ConcatDataset) + assert len(dataset_concat) == 5 + + # test mode + cfg1 = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=dict(img_path='imgs/'), + test_mode=True, + metainfo=dict(classes=('pseudo_class', )), + serialize_data=False) + cfg2 = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=dict(img_path='imgs/'), + test_mode=True, + metainfo=dict(classes=('pseudo_class', )), + serialize_data=False) + + dataset1 = DATASETS.build(cfg1) + dataset2 = DATASETS.build(cfg2) + dataset_concat = ConcatDataset(datasets=[dataset1, dataset2]) + assert isinstance(dataset_concat, ConcatDataset) + assert len(dataset_concat) == 10 + + # test mode with ann_files + cfg1 = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=dict(img_path='imgs/'), + ann_file='splits/val.txt', + test_mode=True, + metainfo=dict(classes=('pseudo_class', )), + serialize_data=False) + cfg2 = dict( + type='BaseSegDataset', + pipeline=[], + data_root=data_root, + data_prefix=dict(img_path='imgs/'), + ann_file='splits/val.txt', + test_mode=True, + metainfo=dict(classes=('pseudo_class', )), + serialize_data=False) + + dataset1 = DATASETS.build(cfg1) + dataset2 = DATASETS.build(cfg2) + dataset_concat = ConcatDataset(datasets=[dataset1, dataset2]) + assert isinstance(dataset_concat, ConcatDataset) + assert len(dataset_concat) == 2 diff --git a/third-party/InterFormer/tests/test_datasets/test_formatting.py b/third-party/InterFormer/tests/test_datasets/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e5820ec767c5a4a193a71274ad2cf46255a22b --- /dev/null +++ b/third-party/InterFormer/tests/test_datasets/test_formatting.py @@ -0,0 +1,61 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +import unittest + +import numpy as np +import pytest +from mmengine.structures import BaseDataElement + +from mmseg.datasets.transforms import PackSegInputs +from mmseg.structures import SegDataSample + + +class TestPackSegInputs(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + data_prefix = osp.join(osp.dirname(__file__), '../../data') + img_path = osp.join(data_prefix, 'color.jpg') + rng = np.random.RandomState(0) + self.results = { + 'img_path': img_path, + 'ori_shape': (300, 400), + 'pad_shape': (600, 800), + 'img_shape': (600, 800), + 'scale_factor': 2.0, + 'flip': False, + 'flip_direction': 'horizontal', + 'img_norm_cfg': None, + 'img': rng.rand(300, 400), + 'gt_seg_map': rng.rand(300, 400), + } + self.meta_keys = ('img_path', 'ori_shape', 'img_shape', 'pad_shape', + 'scale_factor', 'flip', 'flip_direction') + + def test_transform(self): + transform = PackSegInputs(meta_keys=self.meta_keys) + results = transform(copy.deepcopy(self.results)) + self.assertIn('data_samples', results) + self.assertIsInstance(results['data_samples'], SegDataSample) + self.assertIsInstance(results['data_samples'].gt_sem_seg, + BaseDataElement) + self.assertEqual(results['data_samples'].ori_shape, + results['data_samples'].gt_sem_seg.shape) + results = copy.deepcopy(self.results) + # test dataset shape is not 2D + results['gt_seg_map'] = np.random.rand(3, 300, 400) + msg = 'the segmentation map is 2D' + with pytest.warns(UserWarning, match=msg): + results = transform(results) + self.assertEqual(results['data_samples'].ori_shape, + results['data_samples'].gt_sem_seg.shape) + + def test_repr(self): + transform = PackSegInputs(meta_keys=self.meta_keys) + self.assertEqual( + repr(transform), f'PackSegInputs(meta_keys={self.meta_keys})') diff --git a/third-party/InterFormer/tests/test_datasets/test_loading.py b/third-party/InterFormer/tests/test_datasets/test_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..3eea6e3f9dde20281a3ce247f5e4096b9995cd1a --- /dev/null +++ b/third-party/InterFormer/tests/test_datasets/test_loading.py @@ -0,0 +1,295 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +import tempfile + +import mmcv +import numpy as np +from mmcv.transforms import LoadImageFromFile + +from mmseg.datasets.transforms import LoadAnnotations # noqa +from mmseg.datasets.transforms import (LoadBiomedicalAnnotation, + LoadBiomedicalData, + LoadBiomedicalImageFromFile, + LoadDepthAnnotation, + LoadImageFromNDArray) + + +class TestLoading: + + @classmethod + def setup_class(cls): + cls.data_prefix = osp.join(osp.dirname(__file__), '../data') + + def test_load_img(self): + results = dict(img_path=osp.join(self.data_prefix, 'color.jpg')) + transform = LoadImageFromFile() + results = transform(copy.deepcopy(results)) + assert results['img_path'] == osp.join(self.data_prefix, 'color.jpg') + assert results['img'].shape == (288, 512, 3) + assert results['img'].dtype == np.uint8 + assert results['ori_shape'] == results['img'].shape[:2] + assert repr(transform) == transform.__class__.__name__ + \ + "(ignore_empty=False, to_float32=False, color_type='color'," + \ + " imdecode_backend='cv2', backend_args=None)" + + # to_float32 + transform = LoadImageFromFile(to_float32=True) + results = transform(copy.deepcopy(results)) + assert results['img'].dtype == np.float32 + + # gray image + results = dict(img_path=osp.join(self.data_prefix, 'gray.jpg')) + transform = LoadImageFromFile() + results = transform(copy.deepcopy(results)) + assert results['img'].shape == (288, 512, 3) + assert results['img'].dtype == np.uint8 + + transform = LoadImageFromFile(color_type='unchanged') + results = transform(copy.deepcopy(results)) + assert results['img'].shape == (288, 512) + assert results['img'].dtype == np.uint8 + + def test_load_seg(self): + seg_path = osp.join(self.data_prefix, 'seg.png') + results = dict( + seg_map_path=seg_path, reduce_zero_label=True, seg_fields=[]) + transform = LoadAnnotations() + results = transform(copy.deepcopy(results)) + assert results['gt_seg_map'].shape == (288, 512) + assert results['gt_seg_map'].dtype == np.uint8 + assert repr(transform) == transform.__class__.__name__ + \ + "(reduce_zero_label=True, imdecode_backend='pillow', " + \ + 'backend_args=None)' + + # reduce_zero_label + transform = LoadAnnotations(reduce_zero_label=True) + results = transform(copy.deepcopy(results)) + assert results['gt_seg_map'].shape == (288, 512) + assert results['gt_seg_map'].dtype == np.uint8 + + def test_load_seg_custom_classes(self): + + test_img = np.random.rand(10, 10) + test_gt = np.zeros_like(test_img) + test_gt[2:4, 2:4] = 1 + test_gt[2:4, 6:8] = 2 + test_gt[6:8, 2:4] = 3 + test_gt[6:8, 6:8] = 4 + + tmp_dir = tempfile.TemporaryDirectory() + img_path = osp.join(tmp_dir.name, 'img.jpg') + gt_path = osp.join(tmp_dir.name, 'gt.png') + + mmcv.imwrite(test_img, img_path) + mmcv.imwrite(test_gt, gt_path) + + # test only train with label with id 3 + results = dict( + img_path=img_path, + seg_map_path=gt_path, + label_map={ + 0: 0, + 1: 0, + 2: 0, + 3: 1, + 4: 0 + }, + reduce_zero_label=False, + seg_fields=[]) + + load_imgs = LoadImageFromFile() + results = load_imgs(copy.deepcopy(results)) + + load_anns = LoadAnnotations() + results = load_anns(copy.deepcopy(results)) + + gt_array = results['gt_seg_map'] + + true_mask = np.zeros_like(gt_array) + true_mask[6:8, 2:4] = 1 + + assert results['seg_fields'] == ['gt_seg_map'] + assert gt_array.shape == (10, 10) + assert gt_array.dtype == np.uint8 + np.testing.assert_array_equal(gt_array, true_mask) + + # test only train with label with id 4 and 3 + results = dict( + img_path=osp.join(self.data_prefix, 'color.jpg'), + seg_map_path=gt_path, + label_map={ + 0: 0, + 1: 0, + 2: 0, + 3: 2, + 4: 1 + }, + reduce_zero_label=False, + seg_fields=[]) + + load_imgs = LoadImageFromFile() + results = load_imgs(copy.deepcopy(results)) + + load_anns = LoadAnnotations() + results = load_anns(copy.deepcopy(results)) + + gt_array = results['gt_seg_map'] + + true_mask = np.zeros_like(gt_array) + true_mask[6:8, 2:4] = 2 + true_mask[6:8, 6:8] = 1 + + assert results['seg_fields'] == ['gt_seg_map'] + assert gt_array.shape == (10, 10) + assert gt_array.dtype == np.uint8 + np.testing.assert_array_equal(gt_array, true_mask) + + # test with removing a class and reducing zero label simultaneously + results = dict( + img_path=img_path, + seg_map_path=gt_path, + # since reduce_zero_label is True, there are only 4 real classes. + # if the full set of classes is ["A", "B", "C", "D"], the + # following label map simulates the dataset option + # classes=["A", "C", "D"] which removes class "B". + label_map={ + 0: 0, + 1: 255, # simulate removing class 1 + 2: 1, + 3: 2 + }, + reduce_zero_label=True, # reduce zero label + seg_fields=[]) + + load_imgs = LoadImageFromFile() + results = load_imgs(copy.deepcopy(results)) + + # reduce zero label + load_anns = LoadAnnotations() + results = load_anns(copy.deepcopy(results)) + + gt_array = results['gt_seg_map'] + + true_mask = np.ones_like(gt_array) * 255 # all zeros get mapped to 255 + true_mask[2:4, 2:4] = 0 # 1s are reduced to class 0 mapped to class 0 + true_mask[2:4, 6:8] = 255 # 2s are reduced to class 1 which is removed + true_mask[6:8, 2:4] = 1 # 3s are reduced to class 2 mapped to class 1 + true_mask[6:8, 6:8] = 2 # 4s are reduced to class 3 mapped to class 2 + + assert results['seg_fields'] == ['gt_seg_map'] + assert gt_array.shape == (10, 10) + assert gt_array.dtype == np.uint8 + np.testing.assert_array_equal(gt_array, true_mask) + + # test no custom classes + results = dict( + img_path=img_path, + seg_map_path=gt_path, + reduce_zero_label=False, + seg_fields=[]) + + load_imgs = LoadImageFromFile() + results = load_imgs(copy.deepcopy(results)) + + load_anns = LoadAnnotations() + results = load_anns(copy.deepcopy(results)) + + gt_array = results['gt_seg_map'] + + assert results['seg_fields'] == ['gt_seg_map'] + assert gt_array.shape == (10, 10) + assert gt_array.dtype == np.uint8 + np.testing.assert_array_equal(gt_array, test_gt) + + tmp_dir.cleanup() + + def test_load_image_from_ndarray(self): + results = {'img': np.zeros((256, 256, 3), dtype=np.uint8)} + transform = LoadImageFromNDArray() + results = transform(results) + + assert results['img'].shape == (256, 256, 3) + assert results['img'].dtype == np.uint8 + assert results['img_shape'] == (256, 256) + assert results['ori_shape'] == (256, 256) + + # to_float32 + transform = LoadImageFromNDArray(to_float32=True) + results = transform(copy.deepcopy(results)) + assert results['img'].dtype == np.float32 + + # test repr + transform = LoadImageFromNDArray() + assert repr(transform) == ('LoadImageFromNDArray(' + 'ignore_empty=False, ' + 'to_float32=False, ' + "color_type='color', " + "imdecode_backend='cv2', " + 'backend_args=None)') + + def test_load_biomedical_img(self): + results = dict( + img_path=osp.join(self.data_prefix, 'biomedical.nii.gz')) + transform = LoadBiomedicalImageFromFile() + results = transform(copy.deepcopy(results)) + assert results['img_path'] == osp.join(self.data_prefix, + 'biomedical.nii.gz') + assert len(results['img'].shape) == 4 + assert results['img'].dtype == np.float32 + assert results['ori_shape'] == results['img'].shape[1:] + assert repr(transform) == ('LoadBiomedicalImageFromFile(' + "decode_backend='nifti', " + 'to_xyz=False, ' + 'to_float32=True, ' + 'backend_args=None)') + + def test_load_biomedical_annotation(self): + results = dict( + seg_map_path=osp.join(self.data_prefix, 'biomedical_ann.nii.gz')) + transform = LoadBiomedicalAnnotation() + results = transform(copy.deepcopy(results)) + assert len(results['gt_seg_map'].shape) == 3 + assert results['gt_seg_map'].dtype == np.float32 + + def test_load_biomedical_data(self): + input_results = dict( + img_path=osp.join(self.data_prefix, 'biomedical.npy')) + transform = LoadBiomedicalData(with_seg=True) + results = transform(copy.deepcopy(input_results)) + assert results['img_path'] == osp.join(self.data_prefix, + 'biomedical.npy') + assert results['img'][0].shape == results['gt_seg_map'].shape + assert results['img'].dtype == np.float32 + assert results['ori_shape'] == results['img'].shape[1:] + assert repr(transform) == ('LoadBiomedicalData(' + 'with_seg=True, ' + "decode_backend='numpy', " + 'to_xyz=False, ' + 'backend_args=None)') + + transform = LoadBiomedicalData(with_seg=False) + results = transform(copy.deepcopy(input_results)) + assert len(results['img'].shape) == 4 + assert results.get('gt_seg_map') is None + assert repr(transform) == ('LoadBiomedicalData(' + 'with_seg=False, ' + "decode_backend='numpy', " + 'to_xyz=False, ' + 'backend_args=None)') + + def test_load_depth_annotation(self): + input_results = dict( + img_path='tests/data/pseudo_nyu_dataset/images/' + 'bookstore_0001d_00001.jpg', + depth_map_path='tests/data/pseudo_nyu_dataset/' + 'annotations/bookstore_0001d_00001.png', + category_id=-1, + seg_fields=[]) + transform = LoadDepthAnnotation(depth_rescale_factor=0.001) + results = transform(input_results) + assert 'gt_depth_map' in results + assert results['gt_depth_map'].shape[:2] == mmcv.imread( + input_results['depth_map_path']).shape[:2] + assert results['gt_depth_map'].dtype == np.float32 + assert 'gt_depth_map' in results['seg_fields'] diff --git a/third-party/InterFormer/tests/test_datasets/test_transform.py b/third-party/InterFormer/tests/test_datasets/test_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..e73e558ee8ec9d570acb42e6e2bb1f2e638b323d --- /dev/null +++ b/third-party/InterFormer/tests/test_datasets/test_transform.py @@ -0,0 +1,1273 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from unittest import TestCase + +import mmcv +import numpy as np +import pytest +from mmengine.registry import init_default_scope +from PIL import Image + +from mmseg.datasets.transforms import * # noqa +from mmseg.datasets.transforms import (LoadBiomedicalData, + LoadBiomedicalImageFromFile, + PhotoMetricDistortion, RandomCrop, + RandomDepthMix) +from mmseg.registry import TRANSFORMS + +init_default_scope('mmseg') + + +def test_resize(): + # Test `Resize`, `RandomResize` and `RandomChoiceResize` from + # MMCV transform. Noted: `RandomResize` has args `scales` but + # `Resize` and `RandomResize` has args `scale`. + transform = dict(type='Resize', scale=(1333, 800), keep_ratio=True) + resize_module = TRANSFORMS.build(transform) + + results = dict() + # (288, 512, 3) + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + results['img'] = img + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + resized_results = resize_module(results.copy()) + # img_shape = results['img'].shape[:2] in ``MMCV resize`` function + # so right now it is (750, 1333) rather than (750, 1333, 3) + assert resized_results['img_shape'] == (750, 1333) + + # test keep_ratio=False + transform = dict( + type='RandomResize', + scale=(1280, 800), + ratio_range=(1.0, 1.0), + resize_type='Resize', + keep_ratio=False) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert resized_results['img_shape'] == (800, 1280) + + # test `RandomChoiceResize`, which in older mmsegmentation + # `Resize` is multiscale_mode='range' + transform = dict(type='RandomResize', scale=[(1333, 400), (1333, 1200)]) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert max(resized_results['img_shape'][:2]) <= 1333 + assert min(resized_results['img_shape'][:2]) >= 400 + assert min(resized_results['img_shape'][:2]) <= 1200 + + # test RandomChoiceResize, which in older mmsegmentation + # `Resize` is multiscale_mode='value' + transform = dict( + type='RandomChoiceResize', + scales=[(1333, 800), (1333, 400)], + resize_type='Resize', + keep_ratio=False) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert resized_results['img_shape'] in [(800, 1333), (400, 1333)] + + transform = dict(type='Resize', scale_factor=(0.9, 1.1), keep_ratio=True) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert max(resized_results['img_shape'][:2]) <= 1333 * 1.1 + + # test RandomChoiceResize, which `resize_type` is `ResizeShortestEdge` + transform = dict( + type='RandomChoiceResize', + scales=[128, 256, 512], + resize_type='ResizeShortestEdge', + max_size=1333) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert resized_results['img_shape'][0] in [128, 256, 512] + + transform = dict( + type='RandomChoiceResize', + scales=[512], + resize_type='ResizeShortestEdge', + max_size=512) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert resized_results['img_shape'][1] == 512 + + transform = dict( + type='RandomChoiceResize', + scales=[(128, 256), (256, 512), (512, 1024)], + resize_type='ResizeShortestEdge', + max_size=1333) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert resized_results['img_shape'][0] in [128, 256, 512] + + # test scale=None and scale_factor is tuple. + # img shape: (288, 512, 3) + transform = dict( + type='Resize', scale=None, scale_factor=(0.5, 2.0), keep_ratio=True) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert int(288 * 0.5) <= resized_results['img_shape'][0] <= 288 * 2.0 + assert int(512 * 0.5) <= resized_results['img_shape'][1] <= 512 * 2.0 + + # test minimum resized image shape is 640 + transform = dict(type='Resize', scale=(2560, 640), keep_ratio=True) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert resized_results['img_shape'] == (640, 1138) + + # test minimum resized image shape is 640 when img_scale=(512, 640) + # where should define `scale_factor` in MMCV new ``Resize`` function. + min_size_ratio = max(640 / img.shape[0], 640 / img.shape[1]) + transform = dict( + type='Resize', scale_factor=min_size_ratio, keep_ratio=True) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert resized_results['img_shape'] == (640, 1138) + + # test h > w + img = np.random.randn(512, 288, 3) + results['img'] = img + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + min_size_ratio = max(640 / img.shape[0], 640 / img.shape[1]) + transform = dict( + type='Resize', + scale=(2560, 640), + scale_factor=min_size_ratio, + keep_ratio=True) + resize_module = TRANSFORMS.build(transform) + resized_results = resize_module(results.copy()) + assert resized_results['img_shape'] == (1138, 640) + + +def test_flip(): + # test assertion for invalid prob + with pytest.raises(AssertionError): + transform = dict(type='RandomFlip', prob=1.5) + TRANSFORMS.build(transform) + + # test assertion for invalid direction + with pytest.raises(AssertionError): + transform = dict(type='RandomFlip', prob=1.0, direction='horizonta') + TRANSFORMS.build(transform) + + transform = dict(type='RandomFlip', prob=1.0) + flip_module = TRANSFORMS.build(transform) + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + original_img = copy.deepcopy(img) + seg = np.array( + Image.open(osp.join(osp.dirname(__file__), '../data/seg.png'))) + original_seg = copy.deepcopy(seg) + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = flip_module(results) + + flip_module = TRANSFORMS.build(transform) + results = flip_module(results) + assert np.equal(original_img, results['img']).all() + assert np.equal(original_seg, results['gt_semantic_seg']).all() + + results['gt_depth_map'] = seg + results['seg_fields'] = ['gt_depth_map'] + results = flip_module(results) + flip_module = TRANSFORMS.build(transform) + results = flip_module(results) + assert np.equal(original_img, results['img']).all() + assert np.equal(original_seg, results['gt_depth_map']).all() + + +def test_random_rotate_flip(): + with pytest.raises(AssertionError): + transform = dict(type='RandomRotFlip', flip_prob=1.5) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict(type='RandomRotFlip', rotate_prob=1.5) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict(type='RandomRotFlip', degree=[20, 20, 20]) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict(type='RandomRotFlip', degree=-20) + TRANSFORMS.build(transform) + + transform = dict( + type='RandomRotFlip', flip_prob=1.0, rotate_prob=0, degree=20) + rot_flip_module = TRANSFORMS.build(transform) + + results = dict() + img = mmcv.imread( + osp.join( + osp.dirname(__file__), + '../data/pseudo_synapse_dataset/img_dir/case0005_slice000.jpg'), + 'color') + original_img = copy.deepcopy(img) + seg = np.array( + Image.open( + osp.join( + osp.dirname(__file__), + '../data/pseudo_synapse_dataset/ann_dir/case0005_slice000.png') + )) + original_seg = copy.deepcopy(seg) + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + result_flip = rot_flip_module(results) + assert original_img.shape == result_flip['img'].shape + assert original_seg.shape == result_flip['gt_semantic_seg'].shape + + transform = dict( + type='RandomRotFlip', flip_prob=0, rotate_prob=1.0, degree=20) + rot_flip_module = TRANSFORMS.build(transform) + + result_rotate = rot_flip_module(results) + assert original_img.shape == result_rotate['img'].shape + assert original_seg.shape == result_rotate['gt_semantic_seg'].shape + + assert str(transform) == "{'type': 'RandomRotFlip'," \ + " 'flip_prob': 0," \ + " 'rotate_prob': 1.0," \ + " 'degree': 20}" + + +def test_pad(): + # test assertion if both size_divisor and size is None + with pytest.raises(AssertionError): + transform = dict(type='Pad') + TRANSFORMS.build(transform) + + transform = dict(type='Pad', size_divisor=32) + transform = TRANSFORMS.build(transform) + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + original_img = copy.deepcopy(img) + results['img'] = img + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = transform(results) + # original img already divisible by 32 + assert np.equal(results['img'], original_img).all() + img_shape = results['img'].shape + assert img_shape[0] % 32 == 0 + assert img_shape[1] % 32 == 0 + + +def test_normalize(): + img_norm_cfg = dict( + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True) + transform = dict(type='Normalize', **img_norm_cfg) + transform = TRANSFORMS.build(transform) + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + original_img = copy.deepcopy(img) + results['img'] = img + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = transform(results) + + mean = np.array(img_norm_cfg['mean']) + std = np.array(img_norm_cfg['std']) + converted_img = (original_img[..., ::-1] - mean) / std + assert np.allclose(results['img'], converted_img) + + +def test_random_crop(): + # test assertion for invalid random crop + with pytest.raises(AssertionError): + RandomCrop(crop_size=(-1, 0)) + + results = dict() + img = mmcv.imread(osp.join('tests/data/color.jpg'), 'color') + seg = np.array(Image.open(osp.join('tests/data/seg.png'))) + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + h, w, _ = img.shape + pipeline = RandomCrop(crop_size=(h - 20, w - 20)) + + results = pipeline(results) + assert results['img'].shape[:2] == (h - 20, w - 20) + assert results['img_shape'] == (h - 20, w - 20) + assert results['gt_semantic_seg'].shape[:2] == (h - 20, w - 20) + + +def test_rgb2gray(): + # test assertion out_channels should be greater than 0 + with pytest.raises(AssertionError): + transform = dict(type='RGB2Gray', out_channels=-1) + TRANSFORMS.build(transform) + # test assertion weights should be tuple[float] + with pytest.raises(AssertionError): + transform = dict(type='RGB2Gray', out_channels=1, weights=1.1) + TRANSFORMS.build(transform) + + # test out_channels is None + transform = dict(type='RGB2Gray') + transform = TRANSFORMS.build(transform) + + assert str(transform) == f'RGB2Gray(' \ + f'out_channels={None}, ' \ + f'weights={(0.299, 0.587, 0.114)})' + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + h, w, c = img.shape + seg = np.array( + Image.open(osp.join(osp.dirname(__file__), '../data/seg.png'))) + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = transform(results) + assert results['img'].shape == (h, w, c) + assert results['img_shape'] == (h, w, c) + assert results['ori_shape'] == (h, w, c) + + # test out_channels = 2 + transform = dict(type='RGB2Gray', out_channels=2) + transform = TRANSFORMS.build(transform) + + assert str(transform) == f'RGB2Gray(' \ + f'out_channels={2}, ' \ + f'weights={(0.299, 0.587, 0.114)})' + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + h, w, c = img.shape + seg = np.array( + Image.open(osp.join(osp.dirname(__file__), '../data/seg.png'))) + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = transform(results) + assert results['img'].shape == (h, w, 2) + assert results['img_shape'] == (h, w, 2) + + +def test_photo_metric_distortion(): + + results = dict() + img = mmcv.imread(osp.join('tests/data/color.jpg'), 'color') + seg = np.array(Image.open(osp.join('tests/data/seg.png'))) + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + pipeline = PhotoMetricDistortion(saturation_range=(1., 1.)) + results = pipeline(results) + + assert (results['gt_semantic_seg'] == seg).all() + assert results['img_shape'] == img.shape + + +def test_rerange(): + # test assertion if min_value or max_value is illegal + with pytest.raises(AssertionError): + transform = dict(type='Rerange', min_value=[0], max_value=[255]) + TRANSFORMS.build(transform) + + # test assertion if min_value >= max_value + with pytest.raises(AssertionError): + transform = dict(type='Rerange', min_value=1, max_value=1) + TRANSFORMS.build(transform) + + # test assertion if img_min_value == img_max_value + with pytest.raises(AssertionError): + transform = dict(type='Rerange', min_value=0, max_value=1) + transform = TRANSFORMS.build(transform) + results = dict() + results['img'] = np.array([[1, 1], [1, 1]]) + transform(results) + + img_rerange_cfg = dict() + transform = dict(type='Rerange', **img_rerange_cfg) + transform = TRANSFORMS.build(transform) + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + original_img = copy.deepcopy(img) + results['img'] = img + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = transform(results) + + min_value = np.min(original_img) + max_value = np.max(original_img) + converted_img = (original_img - min_value) / (max_value - min_value) * 255 + + assert np.allclose(results['img'], converted_img) + assert str(transform) == f'Rerange(min_value={0}, max_value={255})' + + +def test_CLAHE(): + # test assertion if clip_limit is None + with pytest.raises(AssertionError): + transform = dict(type='CLAHE', clip_limit=None) + TRANSFORMS.build(transform) + + # test assertion if tile_grid_size is illegal + with pytest.raises(AssertionError): + transform = dict(type='CLAHE', tile_grid_size=(8.0, 8.0)) + TRANSFORMS.build(transform) + + # test assertion if tile_grid_size is illegal + with pytest.raises(AssertionError): + transform = dict(type='CLAHE', tile_grid_size=(9, 9, 9)) + TRANSFORMS.build(transform) + + transform = dict(type='CLAHE', clip_limit=2) + transform = TRANSFORMS.build(transform) + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + original_img = copy.deepcopy(img) + results['img'] = img + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = transform(results) + + converted_img = np.empty(original_img.shape) + for i in range(original_img.shape[2]): + converted_img[:, :, i] = mmcv.clahe( + np.array(original_img[:, :, i], dtype=np.uint8), 2, (8, 8)) + + assert np.allclose(results['img'], converted_img) + assert str(transform) == f'CLAHE(clip_limit={2}, tile_grid_size={(8, 8)})' + + +def test_adjust_gamma(): + # test assertion if gamma <= 0 + with pytest.raises(AssertionError): + transform = dict(type='AdjustGamma', gamma=0) + TRANSFORMS.build(transform) + + # test assertion if gamma is list + with pytest.raises(AssertionError): + transform = dict(type='AdjustGamma', gamma=[1.2]) + TRANSFORMS.build(transform) + + # test with gamma = 1.2 + transform = dict(type='AdjustGamma', gamma=1.2) + transform = TRANSFORMS.build(transform) + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + original_img = copy.deepcopy(img) + results['img'] = img + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = transform(results) + + inv_gamma = 1.0 / 1.2 + table = np.array([((i / 255.0)**inv_gamma) * 255 + for i in np.arange(0, 256)]).astype('uint8') + converted_img = mmcv.lut_transform( + np.array(original_img, dtype=np.uint8), table) + assert np.allclose(results['img'], converted_img) + assert str(transform) == f'AdjustGamma(gamma={1.2})' + + +def test_rotate(): + # test assertion degree should be tuple[float] or float + with pytest.raises(AssertionError): + transform = dict(type='RandomRotate', prob=0.5, degree=-10) + TRANSFORMS.build(transform) + # test assertion degree should be tuple[float] or float + with pytest.raises(AssertionError): + transform = dict(type='RandomRotate', prob=0.5, degree=(10., 20., 30.)) + TRANSFORMS.build(transform) + + transform = dict(type='RandomRotate', degree=10., prob=1.) + transform = TRANSFORMS.build(transform) + + assert str(transform) == f'RandomRotate(' \ + f'prob={1.}, ' \ + f'degree=({-10.}, {10.}), ' \ + f'pad_val={0}, ' \ + f'seg_pad_val={255}, ' \ + f'center={None}, ' \ + f'auto_bound={False})' + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + h, w, _ = img.shape + seg = np.array( + Image.open(osp.join(osp.dirname(__file__), '../data/seg.png'))) + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + results = transform(results) + assert results['img'].shape[:2] == (h, w) + + +def test_seg_rescale(): + results = dict() + seg = np.array( + Image.open(osp.join(osp.dirname(__file__), '../data/seg.png'))) + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + h, w = seg.shape + + transform = dict(type='SegRescale', scale_factor=1. / 2) + rescale_module = TRANSFORMS.build(transform) + rescale_results = rescale_module(results.copy()) + assert rescale_results['gt_semantic_seg'].shape == (h // 2, w // 2) + + transform = dict(type='SegRescale', scale_factor=1) + rescale_module = TRANSFORMS.build(transform) + rescale_results = rescale_module(results.copy()) + assert rescale_results['gt_semantic_seg'].shape == (h, w) + + +def test_mosaic(): + # test prob + with pytest.raises(AssertionError): + transform = dict(type='RandomMosaic', prob=1.5) + TRANSFORMS.build(transform) + # test assertion for invalid img_scale + with pytest.raises(AssertionError): + transform = dict(type='RandomMosaic', prob=1, img_scale=640) + TRANSFORMS.build(transform) + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + seg = np.array( + Image.open(osp.join(osp.dirname(__file__), '../data/seg.png'))) + + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + + transform = dict(type='RandomMosaic', prob=1, img_scale=(10, 12)) + mosaic_module = TRANSFORMS.build(transform) + assert 'Mosaic' in repr(mosaic_module) + + # test assertion for invalid mix_results + with pytest.raises(AssertionError): + mosaic_module(results) + + results['mix_results'] = [copy.deepcopy(results)] * 3 + results = mosaic_module(results) + assert results['img'].shape[:2] == (20, 24) + + results = dict() + results['img'] = img[:, :, 0] + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + + transform = dict(type='RandomMosaic', prob=0, img_scale=(10, 12)) + mosaic_module = TRANSFORMS.build(transform) + results['mix_results'] = [copy.deepcopy(results)] * 3 + results = mosaic_module(results) + assert results['img'].shape[:2] == img.shape[:2] + + transform = dict(type='RandomMosaic', prob=1, img_scale=(10, 12)) + mosaic_module = TRANSFORMS.build(transform) + results = mosaic_module(results) + assert results['img'].shape[:2] == (20, 24) + + results = dict() + results['img'] = np.concatenate((img, img), axis=2) + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + + transform = dict(type='RandomMosaic', prob=1, img_scale=(10, 12)) + mosaic_module = TRANSFORMS.build(transform) + results['mix_results'] = [copy.deepcopy(results)] * 3 + results = mosaic_module(results) + assert results['img'].shape[2] == 6 + + +def test_cutout(): + # test prob + with pytest.raises(AssertionError): + transform = dict(type='RandomCutOut', prob=1.5, n_holes=1) + TRANSFORMS.build(transform) + # test n_holes + with pytest.raises(AssertionError): + transform = dict( + type='RandomCutOut', prob=0.5, n_holes=(5, 3), cutout_shape=(8, 8)) + TRANSFORMS.build(transform) + with pytest.raises(AssertionError): + transform = dict( + type='RandomCutOut', + prob=0.5, + n_holes=(3, 4, 5), + cutout_shape=(8, 8)) + TRANSFORMS.build(transform) + # test cutout_shape and cutout_ratio + with pytest.raises(AssertionError): + transform = dict( + type='RandomCutOut', prob=0.5, n_holes=1, cutout_shape=8) + TRANSFORMS.build(transform) + with pytest.raises(AssertionError): + transform = dict( + type='RandomCutOut', prob=0.5, n_holes=1, cutout_ratio=0.2) + TRANSFORMS.build(transform) + # either of cutout_shape and cutout_ratio should be given + with pytest.raises(AssertionError): + transform = dict(type='RandomCutOut', prob=0.5, n_holes=1) + TRANSFORMS.build(transform) + with pytest.raises(AssertionError): + transform = dict( + type='RandomCutOut', + prob=0.5, + n_holes=1, + cutout_shape=(2, 2), + cutout_ratio=(0.4, 0.4)) + TRANSFORMS.build(transform) + # test seg_fill_in + with pytest.raises(AssertionError): + transform = dict( + type='RandomCutOut', + prob=0.5, + n_holes=1, + cutout_shape=(8, 8), + seg_fill_in='a') + TRANSFORMS.build(transform) + with pytest.raises(AssertionError): + transform = dict( + type='RandomCutOut', + prob=0.5, + n_holes=1, + cutout_shape=(8, 8), + seg_fill_in=256) + TRANSFORMS.build(transform) + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + + seg = np.array( + Image.open(osp.join(osp.dirname(__file__), '../data/seg.png'))) + + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['ori_shape'] = img.shape + results['pad_shape'] = img.shape + results['img_fields'] = ['img'] + + transform = dict( + type='RandomCutOut', prob=1, n_holes=1, cutout_shape=(10, 10)) + cutout_module = TRANSFORMS.build(transform) + assert 'cutout_shape' in repr(cutout_module) + cutout_result = cutout_module(copy.deepcopy(results)) + assert cutout_result['img'].sum() < img.sum() + + transform = dict( + type='RandomCutOut', prob=1, n_holes=1, cutout_ratio=(0.8, 0.8)) + cutout_module = TRANSFORMS.build(transform) + assert 'cutout_ratio' in repr(cutout_module) + cutout_result = cutout_module(copy.deepcopy(results)) + assert cutout_result['img'].sum() < img.sum() + + transform = dict( + type='RandomCutOut', prob=0, n_holes=1, cutout_ratio=(0.8, 0.8)) + cutout_module = TRANSFORMS.build(transform) + cutout_result = cutout_module(copy.deepcopy(results)) + assert cutout_result['img'].sum() == img.sum() + assert cutout_result['gt_semantic_seg'].sum() == seg.sum() + + transform = dict( + type='RandomCutOut', + prob=1, + n_holes=(2, 4), + cutout_shape=[(10, 10), (15, 15)], + fill_in=(255, 255, 255), + seg_fill_in=None) + cutout_module = TRANSFORMS.build(transform) + cutout_result = cutout_module(copy.deepcopy(results)) + assert cutout_result['img'].sum() > img.sum() + assert cutout_result['gt_semantic_seg'].sum() == seg.sum() + + transform = dict( + type='RandomCutOut', + prob=1, + n_holes=1, + cutout_ratio=(0.8, 0.8), + fill_in=(255, 255, 255), + seg_fill_in=255) + cutout_module = TRANSFORMS.build(transform) + cutout_result = cutout_module(copy.deepcopy(results)) + assert cutout_result['img'].sum() > img.sum() + assert cutout_result['gt_semantic_seg'].sum() > seg.sum() + + +def test_resize_to_multiple(): + transform = dict(type='ResizeToMultiple', size_divisor=32) + transform = TRANSFORMS.build(transform) + + img = np.random.randn(213, 232, 3) + seg = np.random.randint(0, 19, (213, 232)) + results = dict() + results['img'] = img + results['gt_semantic_seg'] = seg + results['seg_fields'] = ['gt_semantic_seg'] + results['img_shape'] = img.shape + results['pad_shape'] = img.shape + + results = transform(results) + assert results['img'].shape == (224, 256, 3) + assert results['gt_semantic_seg'].shape == (224, 256) + assert results['img_shape'] == (224, 256) + + +def test_generate_edge(): + transform = dict(type='GenerateEdge', edge_width=1) + transform = TRANSFORMS.build(transform) + + seg_map = np.array([ + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 2], + [1, 1, 1, 2, 2], + [1, 1, 2, 2, 2], + [1, 2, 2, 2, 2], + [2, 2, 2, 2, 2], + ]) + results = dict() + results['gt_seg_map'] = seg_map + results['img_shape'] = seg_map.shape + + results = transform(results) + assert np.all(results['gt_edge_map'] == np.array([ + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 1], + [0, 1, 1, 1, 0], + [1, 1, 1, 0, 0], + [1, 1, 0, 0, 0], + [1, 0, 0, 0, 0], + ])) + + +def test_biomedical3d_random_crop(): + # test assertion for invalid random crop + with pytest.raises(AssertionError): + transform = dict(type='BioMedical3DRandomCrop', crop_shape=(-2, -1, 0)) + transform = TRANSFORMS.build(transform) + + from mmseg.datasets.transforms import (LoadBiomedicalAnnotation, + LoadBiomedicalImageFromFile) + results = dict() + results['img_path'] = osp.join( + osp.dirname(__file__), '../data', 'biomedical.nii.gz') + transform = LoadBiomedicalImageFromFile() + results = transform(copy.deepcopy(results)) + + results['seg_map_path'] = osp.join( + osp.dirname(__file__), '../data', 'biomedical_ann.nii.gz') + transform = LoadBiomedicalAnnotation() + results = transform(copy.deepcopy(results)) + + d, h, w = results['img_shape'] + transform = dict( + type='BioMedical3DRandomCrop', + crop_shape=(d - 20, h - 20, w - 20), + keep_foreground=True) + transform = TRANSFORMS.build(transform) + crop_results = transform(results) + assert crop_results['img'].shape[1:] == (d - 20, h - 20, w - 20) + assert crop_results['img_shape'] == (d - 20, h - 20, w - 20) + assert crop_results['gt_seg_map'].shape == (d - 20, h - 20, w - 20) + + transform = dict( + type='BioMedical3DRandomCrop', + crop_shape=(d - 20, h - 20, w - 20), + keep_foreground=False) + transform = TRANSFORMS.build(transform) + crop_results = transform(results) + assert crop_results['img'].shape[1:] == (d - 20, h - 20, w - 20) + assert crop_results['img_shape'] == (d - 20, h - 20, w - 20) + assert crop_results['gt_seg_map'].shape == (d - 20, h - 20, w - 20) + + +def test_biomedical_gaussian_noise(): + # test assertion for invalid prob + with pytest.raises(AssertionError): + transform = dict(type='BioMedicalGaussianNoise', prob=1.5) + TRANSFORMS.build(transform) + + # test assertion for invalid std + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalGaussianNoise', prob=0.2, mean=0.5, std=-0.5) + TRANSFORMS.build(transform) + + transform = dict(type='BioMedicalGaussianNoise', prob=1.0) + noise_module = TRANSFORMS.build(transform) + assert str(noise_module) == 'BioMedicalGaussianNoise'\ + '(prob=1.0, ' \ + 'mean=0.0, ' \ + 'std=0.1)' + + transform = dict(type='BioMedicalGaussianNoise', prob=1.0) + noise_module = TRANSFORMS.build(transform) + results = dict( + img_path=osp.join(osp.dirname(__file__), '../data/biomedical.nii.gz')) + from mmseg.datasets.transforms import LoadBiomedicalImageFromFile + transform = LoadBiomedicalImageFromFile() + results = transform(copy.deepcopy(results)) + original_img = copy.deepcopy(results['img']) + results = noise_module(results) + assert original_img.shape == results['img'].shape + + +def test_biomedical_gaussian_blur(): + # test assertion for invalid prob + with pytest.raises(AssertionError): + transform = dict(type='BioMedicalGaussianBlur', prob=-1.5) + TRANSFORMS.build(transform) + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalGaussianBlur', prob=1.0, sigma_range=0.6) + smooth_module = TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalGaussianBlur', prob=1.0, sigma_range=(0.6)) + smooth_module = TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalGaussianBlur', prob=1.0, sigma_range=(15, 8, 9)) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalGaussianBlur', prob=1.0, sigma_range='0.16') + TRANSFORMS.build(transform) + + transform = dict( + type='BioMedicalGaussianBlur', prob=1.0, sigma_range=(0.7, 0.8)) + smooth_module = TRANSFORMS.build(transform) + assert str( + smooth_module + ) == 'BioMedicalGaussianBlur(prob=1.0, ' \ + 'prob_per_channel=0.5, '\ + 'sigma_range=(0.7, 0.8), ' \ + 'different_sigma_per_channel=True, '\ + 'different_sigma_per_axis=True)' + + transform = dict(type='BioMedicalGaussianBlur', prob=1.0) + smooth_module = TRANSFORMS.build(transform) + assert str( + smooth_module + ) == 'BioMedicalGaussianBlur(prob=1.0, ' \ + 'prob_per_channel=0.5, '\ + 'sigma_range=(0.5, 1.0), ' \ + 'different_sigma_per_channel=True, '\ + 'different_sigma_per_axis=True)' + + results = dict( + img_path=osp.join(osp.dirname(__file__), '../data/biomedical.nii.gz')) + from mmseg.datasets.transforms import LoadBiomedicalImageFromFile + transform = LoadBiomedicalImageFromFile() + results = transform(copy.deepcopy(results)) + original_img = copy.deepcopy(results['img']) + results = smooth_module(results) + assert original_img.shape == results['img'].shape + # the max value in the smoothed image should be less than the original one + assert original_img.max() >= results['img'].max() + assert original_img.min() <= results['img'].min() + + transform = dict( + type='BioMedicalGaussianBlur', + prob=1.0, + different_sigma_per_axis=False) + smooth_module = TRANSFORMS.build(transform) + + results = dict( + img_path=osp.join(osp.dirname(__file__), '../data/biomedical.nii.gz')) + from mmseg.datasets.transforms import LoadBiomedicalImageFromFile + transform = LoadBiomedicalImageFromFile() + results = transform(copy.deepcopy(results)) + original_img = copy.deepcopy(results['img']) + results = smooth_module(results) + assert original_img.shape == results['img'].shape + # the max value in the smoothed image should be less than the original one + assert original_img.max() >= results['img'].max() + assert original_img.min() <= results['img'].min() + + +def test_BioMedicalRandomGamma(): + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalRandomGamma', prob=-1, gamma_range=(0.7, 1.2)) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalRandomGamma', prob=1.2, gamma_range=(0.7, 1.2)) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalRandomGamma', prob=1.0, gamma_range=(0.7)) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalRandomGamma', + prob=1.0, + gamma_range=(0.7, 0.2, 0.3)) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalRandomGamma', + prob=1.0, + gamma_range=(0.7, 2), + invert_image=1) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalRandomGamma', + prob=1.0, + gamma_range=(0.7, 2), + per_channel=1) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict( + type='BioMedicalRandomGamma', + prob=1.0, + gamma_range=(0.7, 2), + retain_stats=1) + TRANSFORMS.build(transform) + + test_img = 'tests/data/biomedical.nii.gz' + results = dict(img_path=test_img) + transform = LoadBiomedicalImageFromFile() + results = transform(copy.deepcopy(results)) + origin_img = results['img'] + transform2 = dict( + type='BioMedicalRandomGamma', + prob=1.0, + gamma_range=(0.7, 2), + ) + transform2 = TRANSFORMS.build(transform2) + results = transform2(results) + transformed_img = results['img'] + assert origin_img.shape == transformed_img.shape + + +def test_BioMedical3DPad(): + # test assertion. + with pytest.raises(AssertionError): + transform = dict(type='BioMedical3DPad', pad_shape=None) + TRANSFORMS.build(transform) + + with pytest.raises(AssertionError): + transform = dict(type='BioMedical3DPad', pad_shape=[256, 256]) + TRANSFORMS.build(transform) + + data_info1 = dict(img=np.random.random((8, 6, 4, 4))) + + transform = dict(type='BioMedical3DPad', pad_shape=(6, 6, 6)) + transform = TRANSFORMS.build(transform) + results = transform(copy.deepcopy(data_info1)) + assert results['img'].shape[1:] == (6, 6, 6) + assert results['pad_shape'] == (6, 6, 6) + + transform = dict(type='BioMedical3DPad', pad_shape=(4, 6, 6)) + transform = TRANSFORMS.build(transform) + results = transform(copy.deepcopy(data_info1)) + assert results['img'].shape[1:] == (6, 6, 6) + assert results['pad_shape'] == (6, 6, 6) + + data_info2 = dict( + img=np.random.random((8, 6, 4, 4)), + gt_seg_map=np.random.randint(0, 2, (6, 4, 4))) + + transform = dict(type='BioMedical3DPad', pad_shape=(6, 6, 6)) + transform = TRANSFORMS.build(transform) + results = transform(copy.deepcopy(data_info2)) + assert results['img'].shape[1:] == (6, 6, 6) + assert results['gt_seg_map'].shape[1:] == (6, 6, 6) + assert results['pad_shape'] == (6, 6, 6) + + transform = dict(type='BioMedical3DPad', pad_shape=(4, 6, 6)) + transform = TRANSFORMS.build(transform) + results = transform(copy.deepcopy(data_info2)) + assert results['img'].shape[1:] == (6, 6, 6) + assert results['gt_seg_map'].shape[1:] == (6, 6, 6) + assert results['pad_shape'] == (6, 6, 6) + + +def test_biomedical_3d_flip(): + # test assertion for invalid prob + with pytest.raises(AssertionError): + transform = dict(type='BioMedical3DRandomFlip', prob=1.5, axes=(0, 1)) + transform = TRANSFORMS.build(transform) + + # test assertion for invalid direction + with pytest.raises(AssertionError): + transform = dict(type='BioMedical3DRandomFlip', prob=1, axes=(0, 1, 3)) + transform = TRANSFORMS.build(transform) + + # test flip axes are (0, 1, 2) + transform = dict(type='BioMedical3DRandomFlip', prob=1, axes=(0, 1, 2)) + transform = TRANSFORMS.build(transform) + + # test with random 3d data + results = dict() + results['img_path'] = 'Null' + results['img_shape'] = (1, 16, 16, 16) + results['img'] = np.random.randn(1, 16, 16, 16) + results['gt_seg_map'] = np.random.randint(0, 4, (16, 16, 16)) + + original_img = results['img'].copy() + original_seg = results['gt_seg_map'].copy() + + # flip first time + results = transform(results) + with pytest.raises(AssertionError): + assert np.equal(original_img, results['img']).all() + with pytest.raises(AssertionError): + assert np.equal(original_seg, results['gt_seg_map']).all() + + # flip second time + results = transform(results) + assert np.equal(original_img, results['img']).all() + assert np.equal(original_seg, results['gt_seg_map']).all() + + # test with actual data and flip axes are (0, 1) + # load biomedical 3d img and seg + data_prefix = osp.join(osp.dirname(__file__), '../data') + input_results = dict(img_path=osp.join(data_prefix, 'biomedical.npy')) + biomedical_loader = LoadBiomedicalData(with_seg=True) + data = biomedical_loader(copy.deepcopy(input_results)) + results = data.copy() + + original_img = data['img'].copy() + original_seg = data['gt_seg_map'].copy() + + # test flip axes are (0, 1) + transform = dict(type='BioMedical3DRandomFlip', prob=1, axes=(0, 1)) + transform = TRANSFORMS.build(transform) + + # flip first time + results = transform(results) + with pytest.raises(AssertionError): + assert np.equal(original_img, results['img']).all() + with pytest.raises(AssertionError): + assert np.equal(original_seg, results['gt_seg_map']).all() + + # flip second time + results = transform(results) + assert np.equal(original_img, results['img']).all() + assert np.equal(original_seg, results['gt_seg_map']).all() + + # test transform with flip axes = (1) + transform = dict(type='BioMedical3DRandomFlip', prob=1, axes=(1, )) + transform = TRANSFORMS.build(transform) + results = data.copy() + results = transform(results) + results = transform(results) + assert np.equal(original_img, results['img']).all() + assert np.equal(original_seg, results['gt_seg_map']).all() + + # test transform with swap_label_pairs + transform = dict( + type='BioMedical3DRandomFlip', + prob=1, + axes=(1, 2), + swap_label_pairs=[(0, 1)]) + transform = TRANSFORMS.build(transform) + results = data.copy() + results = transform(results) + + with pytest.raises(AssertionError): + assert np.equal(original_seg, results['gt_seg_map']).all() + + # swap twice + results = transform(results) + assert np.equal(original_img, results['img']).all() + assert np.equal(original_seg, results['gt_seg_map']).all() + + +def test_albu_transform(): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../data/color.jpg')) + + # Define simple pipeline + load = dict(type='LoadImageFromFile') + load = TRANSFORMS.build(load) + + albu_transform = dict( + type='Albu', transforms=[dict(type='ChannelShuffle', p=1)]) + albu_transform = TRANSFORMS.build(albu_transform) + + normalize = dict(type='Normalize', mean=[0] * 3, std=[0] * 3, to_rgb=True) + normalize = TRANSFORMS.build(normalize) + + # Execute transforms + results = load(results) + results = albu_transform(results) + results = normalize(results) + + assert results['img'].dtype == np.float32 + + +def test_albu_channel_order(): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../data/color.jpg')) + + # Define simple pipeline + load = dict(type='LoadImageFromFile') + load = TRANSFORMS.build(load) + + # Transform is modifying B channel + albu_transform = dict( + type='Albu', + transforms=[ + dict( + type='RGBShift', + r_shift_limit=0, + g_shift_limit=0, + b_shift_limit=200, + p=1) + ]) + albu_transform = TRANSFORMS.build(albu_transform) + + # Execute transforms + results_load = load(results) + results_albu = albu_transform(results_load) + + # assert only Green and Red channel are not modified + np.testing.assert_array_equal(results_albu['img'][..., 1:], + results_load['img'][..., 1:]) + + # assert Blue channel is modified + with pytest.raises(AssertionError): + np.testing.assert_array_equal(results_albu['img'][..., 0], + results_load['img'][..., 0]) + + +class TestRandomDepthMix(TestCase): + + def setUp(self): + self.transform = RandomDepthMix(prob=1.0) + + def test_transform_shape(self): + # Create a dummy result dict + results = { + 'img_shape': (10, 10), + 'img': np.random.rand(10, 10, 3), + 'gt_depth_map': np.random.rand(10, 10) + } + transformed = self.transform.transform(results) + + # Check if the shape remains the same + self.assertEqual(results['img'].shape, transformed['img'].shape) + + def test_transform_values(self): + # Create a dummy result dict + results = { + 'img_shape': (10, 10), + 'img': np.zeros((10, 10, 3)), + 'gt_depth_map': np.ones((10, 10)) + } + transformed = self.transform.transform(results) + + # Assuming the transformation modifies a portion of the image, + # it shouldn't remain all zeros + self.assertFalse(np.all(transformed['img'] == 0)) + + def test_invalid_image_dimension(self): + # Create a dummy result dict with invalid image dimension + results = { + 'img_shape': (10, 10), + 'img': np.random.rand(10, 10, 3, 3), + 'gt_depth_map': np.random.rand(10, 10) + } + + # Check if a ValueError is raised for invalid dimension + with self.assertRaises(ValueError): + self.transform.transform(results) diff --git a/third-party/InterFormer/tests/test_datasets/test_tta.py b/third-party/InterFormer/tests/test_datasets/test_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..25b1ecdb53794349c0679dda84a083dec3a0a70f --- /dev/null +++ b/third-party/InterFormer/tests/test_datasets/test_tta.py @@ -0,0 +1,131 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp + +import mmcv +import pytest + +from mmseg.datasets.transforms import * # noqa +from mmseg.registry import TRANSFORMS + + +def test_multi_scale_flip_aug(): + # test exception + with pytest.raises(TypeError): + tta_transform = dict( + type='TestTimeAug', + transforms=[dict(type='Resize', keep_ratio=False)], + ) + TRANSFORMS.build(tta_transform) + + tta_transform = dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=scale, keep_ratio=False) + for scale in [(256, 256), (512, 512), (1024, 1024)] + ], [dict(type='mmseg.PackSegInputs')]]) + tta_module = TRANSFORMS.build(tta_transform) + + results = dict() + # (288, 512, 3) + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + results['img'] = img + results['ori_shape'] = img.shape + results['ori_height'] = img.shape[0] + results['ori_width'] = img.shape[1] + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 256, 256), + (3, 512, 512), + (3, 1024, 1024)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [ + dict(type='Resize', scale=scale, keep_ratio=False) + for scale in [(256, 256), (512, 512), (1024, 1024)] + ], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], [dict(type='mmseg.PackSegInputs')] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results: dict = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 256, 256), + (3, 256, 256), + (3, 512, 512), + (3, 512, 512), + (3, 1024, 1024), + (3, 1024, 1024)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True, False, True, False, True] + + tta_transform = dict( + type='TestTimeAug', + transforms=[[dict(type='Resize', scale=(512, 512), keep_ratio=False)], + [dict(type='mmseg.PackSegInputs')]]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [tta_results['inputs'][0].shape] == [(3, 512, 512)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [dict(type='Resize', scale=(512, 512), keep_ratio=False)], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], [dict(type='mmseg.PackSegInputs')] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 512, 512), + (3, 512, 512)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True] + + tta_transform = dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale_factor=r, keep_ratio=False) + for r in [0.5, 1.0, 2.0] + ], [dict(type='mmseg.PackSegInputs')]]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 144, 256), + (3, 288, 512), + (3, 576, 1024)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [ + dict(type='Resize', scale_factor=r, keep_ratio=True) + for r in [0.5, 1.0, 2.0] + ], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], [dict(type='mmseg.PackSegInputs')] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 144, 256), + (3, 144, 256), + (3, 288, 512), + (3, 288, 512), + (3, 576, 1024), + (3, 576, 1024)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True, False, True, False, True] diff --git a/third-party/InterFormer/tests/test_digit_version.py b/third-party/InterFormer/tests/test_digit_version.py new file mode 100644 index 0000000000000000000000000000000000000000..45daf09ca1e91f53d334db5c9ca0bed086dd3058 --- /dev/null +++ b/third-party/InterFormer/tests/test_digit_version.py @@ -0,0 +1,21 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmseg import digit_version + + +def test_digit_version(): + assert digit_version('0.2.16') == (0, 2, 16, 0, 0, 0) + assert digit_version('1.2.3') == (1, 2, 3, 0, 0, 0) + assert digit_version('1.2.3rc0') == (1, 2, 3, 0, -1, 0) + assert digit_version('1.2.3rc1') == (1, 2, 3, 0, -1, 1) + assert digit_version('1.0rc0') == (1, 0, 0, 0, -1, 0) + assert digit_version('1.0') == digit_version('1.0.0') + assert digit_version('1.5.0+cuda90_cudnn7.6.3_lms') == digit_version('1.5') + assert digit_version('1.0.0dev') < digit_version('1.0.0a') + assert digit_version('1.0.0a') < digit_version('1.0.0a1') + assert digit_version('1.0.0a') < digit_version('1.0.0b') + assert digit_version('1.0.0b') < digit_version('1.0.0rc') + assert digit_version('1.0.0rc1') < digit_version('1.0.0') + assert digit_version('1.0.0') < digit_version('1.0.0post') + assert digit_version('1.0.0post') < digit_version('1.0.0post1') + assert digit_version('v1') == (1, 0, 0, 0, 0, 0) + assert digit_version('v1.1.5') == (1, 1, 5, 0, 0, 0) diff --git a/third-party/InterFormer/tests/test_engine/test_layer_decay_optimizer_constructor.py b/third-party/InterFormer/tests/test_engine/test_layer_decay_optimizer_constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d13db1d6b738ab5c33d2b73d80b3262a595521 --- /dev/null +++ b/third-party/InterFormer/tests/test_engine/test_layer_decay_optimizer_constructor.py @@ -0,0 +1,300 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# from copyreg import constructor +import pytest +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.optim.optimizer import build_optim_wrapper +from mmengine.registry import init_default_scope + +from mmseg.engine.optimizers.layer_decay_optimizer_constructor import \ + LearningRateDecayOptimizerConstructor + +init_default_scope('mmseg') + +base_lr = 1 +decay_rate = 2 +base_wd = 0.05 +weight_decay = 0.05 + +expected_stage_wise_lr_wd_convnext = [{ + 'weight_decay': 0.0, + 'lr_scale': 128 +}, { + 'weight_decay': 0.0, + 'lr_scale': 1 +}, { + 'weight_decay': 0.05, + 'lr_scale': 64 +}, { + 'weight_decay': 0.0, + 'lr_scale': 64 +}, { + 'weight_decay': 0.05, + 'lr_scale': 32 +}, { + 'weight_decay': 0.0, + 'lr_scale': 32 +}, { + 'weight_decay': 0.05, + 'lr_scale': 16 +}, { + 'weight_decay': 0.0, + 'lr_scale': 16 +}, { + 'weight_decay': 0.05, + 'lr_scale': 8 +}, { + 'weight_decay': 0.0, + 'lr_scale': 8 +}, { + 'weight_decay': 0.05, + 'lr_scale': 128 +}, { + 'weight_decay': 0.05, + 'lr_scale': 1 +}] + +expected_layer_wise_lr_wd_convnext = [{ + 'weight_decay': 0.0, + 'lr_scale': 128 +}, { + 'weight_decay': 0.0, + 'lr_scale': 1 +}, { + 'weight_decay': 0.05, + 'lr_scale': 64 +}, { + 'weight_decay': 0.0, + 'lr_scale': 64 +}, { + 'weight_decay': 0.05, + 'lr_scale': 32 +}, { + 'weight_decay': 0.0, + 'lr_scale': 32 +}, { + 'weight_decay': 0.05, + 'lr_scale': 16 +}, { + 'weight_decay': 0.0, + 'lr_scale': 16 +}, { + 'weight_decay': 0.05, + 'lr_scale': 2 +}, { + 'weight_decay': 0.0, + 'lr_scale': 2 +}, { + 'weight_decay': 0.05, + 'lr_scale': 128 +}, { + 'weight_decay': 0.05, + 'lr_scale': 1 +}] + +expected_layer_wise_wd_lr_beit = [{ + 'weight_decay': 0.0, + 'lr_scale': 16 +}, { + 'weight_decay': 0.05, + 'lr_scale': 8 +}, { + 'weight_decay': 0.0, + 'lr_scale': 8 +}, { + 'weight_decay': 0.05, + 'lr_scale': 4 +}, { + 'weight_decay': 0.0, + 'lr_scale': 4 +}, { + 'weight_decay': 0.05, + 'lr_scale': 2 +}, { + 'weight_decay': 0.0, + 'lr_scale': 2 +}, { + 'weight_decay': 0.05, + 'lr_scale': 1 +}, { + 'weight_decay': 0.0, + 'lr_scale': 1 +}] + + +class ToyConvNeXt(nn.Module): + + def __init__(self): + super().__init__() + self.stages = nn.ModuleList() + for i in range(4): + stage = nn.Sequential(ConvModule(3, 4, kernel_size=1, bias=True)) + self.stages.append(stage) + self.norm0 = nn.BatchNorm2d(2) + + # add some variables to meet unit test coverate rate + self.cls_token = nn.Parameter(torch.ones(1)) + self.mask_token = nn.Parameter(torch.ones(1)) + self.pos_embed = nn.Parameter(torch.ones(1)) + self.stem_norm = nn.Parameter(torch.ones(1)) + self.downsample_norm0 = nn.BatchNorm2d(2) + self.downsample_norm1 = nn.BatchNorm2d(2) + self.downsample_norm2 = nn.BatchNorm2d(2) + self.lin = nn.Parameter(torch.ones(1)) + self.lin.requires_grad = False + self.downsample_layers = nn.ModuleList() + for _ in range(4): + stage = nn.Sequential(nn.Conv2d(3, 4, kernel_size=1, bias=True)) + self.downsample_layers.append(stage) + + +class ToyBEiT(nn.Module): + + def __init__(self): + super().__init__() + # add some variables to meet unit test coverate rate + self.cls_token = nn.Parameter(torch.ones(1)) + self.patch_embed = nn.Parameter(torch.ones(1)) + self.layers = nn.ModuleList() + for _ in range(3): + layer = nn.Conv2d(3, 3, 1) + self.layers.append(layer) + + +class ToyMAE(nn.Module): + + def __init__(self): + super().__init__() + # add some variables to meet unit test coverate rate + self.cls_token = nn.Parameter(torch.ones(1)) + self.patch_embed = nn.Parameter(torch.ones(1)) + self.layers = nn.ModuleList() + for _ in range(3): + layer = nn.Conv2d(3, 3, 1) + self.layers.append(layer) + + +class ToySegmentor(nn.Module): + + def __init__(self, backbone): + super().__init__() + self.backbone = backbone + self.decode_head = nn.Conv2d(2, 2, kernel_size=1, groups=2) + + +class PseudoDataParallel(nn.Module): + + def __init__(self, model): + super().__init__() + self.module = model + + +class ToyViT(nn.Module): + + def __init__(self): + super().__init__() + + +def check_optimizer_lr_wd(optimizer, gt_lr_wd): + assert isinstance(optimizer, torch.optim.AdamW) + assert optimizer.defaults['lr'] == base_lr + assert optimizer.defaults['weight_decay'] == base_wd + param_groups = optimizer.param_groups + print(param_groups) + assert len(param_groups) == len(gt_lr_wd) + for i, param_dict in enumerate(param_groups): + assert param_dict['weight_decay'] == gt_lr_wd[i]['weight_decay'] + assert param_dict['lr_scale'] == gt_lr_wd[i]['lr_scale'] + assert param_dict['lr_scale'] == param_dict['lr'] + + +def test_learning_rate_decay_optimizer_constructor(): + + # Test lr wd for ConvNeXT + backbone = ToyConvNeXt() + model = PseudoDataParallel(ToySegmentor(backbone)) + # stagewise decay + stagewise_paramwise_cfg = dict( + decay_rate=decay_rate, decay_type='stage_wise', num_layers=6) + optimizer_cfg = dict( + type='AdamW', lr=base_lr, betas=(0.9, 0.999), weight_decay=0.05) + optim_wrapper_cfg = dict( + type='OptimWrapper', + optimizer=optimizer_cfg, + paramwise_cfg=stagewise_paramwise_cfg, + constructor='LearningRateDecayOptimizerConstructor') + optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_stage_wise_lr_wd_convnext) + # layerwise decay + layerwise_paramwise_cfg = dict( + decay_rate=decay_rate, decay_type='layer_wise', num_layers=6) + optim_wrapper_cfg = dict( + type='OptimWrapper', + optimizer=optimizer_cfg, + paramwise_cfg=layerwise_paramwise_cfg, + constructor='LearningRateDecayOptimizerConstructor') + optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_layer_wise_lr_wd_convnext) + + # Test lr wd for BEiT + backbone = ToyBEiT() + model = PseudoDataParallel(ToySegmentor(backbone)) + + layerwise_paramwise_cfg = dict( + decay_rate=decay_rate, decay_type='layer_wise', num_layers=3) + optim_wrapper_cfg = dict( + type='OptimWrapper', + optimizer=optimizer_cfg, + paramwise_cfg=layerwise_paramwise_cfg, + constructor='LearningRateDecayOptimizerConstructor') + optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_layer_wise_wd_lr_beit) + + # Test invalidation of lr wd for Vit + backbone = ToyViT() + model = PseudoDataParallel(ToySegmentor(backbone)) + with pytest.raises(NotImplementedError): + optim_constructor = LearningRateDecayOptimizerConstructor( + optim_wrapper_cfg, layerwise_paramwise_cfg) + optim_constructor(model) + with pytest.raises(NotImplementedError): + optim_constructor = LearningRateDecayOptimizerConstructor( + optim_wrapper_cfg, stagewise_paramwise_cfg) + optim_constructor(model) + + # Test lr wd for MAE + backbone = ToyMAE() + model = PseudoDataParallel(ToySegmentor(backbone)) + + layerwise_paramwise_cfg = dict( + decay_rate=decay_rate, decay_type='layer_wise', num_layers=3) + optim_wrapper_cfg = dict( + type='OptimWrapper', + optimizer=optimizer_cfg, + paramwise_cfg=layerwise_paramwise_cfg, + constructor='LearningRateDecayOptimizerConstructor') + optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_layer_wise_wd_lr_beit) + + +def test_beit_layer_decay_optimizer_constructor(): + + # paramwise_cfg with BEiTExampleModel + backbone = ToyBEiT() + model = PseudoDataParallel(ToySegmentor(backbone)) + paramwise_cfg = dict(layer_decay_rate=2, num_layers=3) + optim_wrapper_cfg = dict( + type='OptimWrapper', + constructor='LayerDecayOptimizerConstructor', + paramwise_cfg=paramwise_cfg, + optimizer=dict( + type='AdamW', lr=1, betas=(0.9, 0.999), weight_decay=0.05)) + optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg) + # optimizer = optim_wrapper_builder(model) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_layer_wise_wd_lr_beit) diff --git a/third-party/InterFormer/tests/test_engine/test_optimizer.py b/third-party/InterFormer/tests/test_engine/test_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..af69f5fcbc05d3b018efe6da5586987c92da820b --- /dev/null +++ b/third-party/InterFormer/tests/test_engine/test_optimizer.py @@ -0,0 +1,33 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmengine.optim import build_optim_wrapper + + +class ExampleModel(nn.Module): + + def __init__(self): + super().__init__() + self.param1 = nn.Parameter(torch.ones(1)) + self.conv1 = nn.Conv2d(3, 4, kernel_size=1, bias=False) + self.conv2 = nn.Conv2d(4, 2, kernel_size=1) + self.bn = nn.BatchNorm2d(2) + + def forward(self, x): + return x + + +base_lr = 0.01 +base_wd = 0.0001 +momentum = 0.9 + + +def test_build_optimizer(): + model = ExampleModel() + optim_wrapper_cfg = dict( + type='OptimWrapper', + optimizer=dict( + type='SGD', lr=base_lr, weight_decay=base_wd, momentum=momentum)) + optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg) + # test whether optimizer is successfully built from parent. + assert isinstance(optim_wrapper.optimizer, torch.optim.SGD) diff --git a/third-party/InterFormer/tests/test_engine/test_visualization_hook.py b/third-party/InterFormer/tests/test_engine/test_visualization_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..022e27c77cd8ffa7d359f683c992caf14f72c1b0 --- /dev/null +++ b/third-party/InterFormer/tests/test_engine/test_visualization_hook.py @@ -0,0 +1,64 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock + +import torch +from mmengine.structures import PixelData + +from mmseg.engine.hooks import SegVisualizationHook +from mmseg.structures import SegDataSample +from mmseg.visualization import SegLocalVisualizer + + +class TestVisualizationHook(TestCase): + + def setUp(self) -> None: + + h = 288 + w = 512 + num_class = 2 + + SegLocalVisualizer.get_instance('visualizer') + SegLocalVisualizer.dataset_meta = dict( + classes=('background', 'foreground'), + palette=[[120, 120, 120], [6, 230, 230]]) + + data_sample = SegDataSample() + data_sample.set_metainfo({'img_path': 'tests/data/color.jpg'}) + self.data_batch = [{'data_sample': data_sample}] * 2 + + pred_sem_seg_data = dict(data=torch.randint(0, num_class, (1, h, w))) + pred_sem_seg = PixelData(**pred_sem_seg_data) + pred_seg_data_sample = SegDataSample() + pred_seg_data_sample.set_metainfo({'img_path': 'tests/data/color.jpg'}) + pred_seg_data_sample.pred_sem_seg = pred_sem_seg + self.outputs = [pred_seg_data_sample] * 2 + + def test_after_iter(self): + runner = Mock() + runner.iter = 1 + hook = SegVisualizationHook(draw=True, interval=1) + hook._after_iter( + runner, 1, self.data_batch, self.outputs, mode='train') + hook._after_iter(runner, 1, self.data_batch, self.outputs, mode='val') + hook._after_iter(runner, 1, self.data_batch, self.outputs, mode='test') + + def test_after_val_iter(self): + runner = Mock() + runner.iter = 2 + hook = SegVisualizationHook(interval=1) + hook.after_val_iter(runner, 1, self.data_batch, self.outputs) + + hook = SegVisualizationHook(draw=True, interval=1) + hook.after_val_iter(runner, 1, self.data_batch, self.outputs) + + hook = SegVisualizationHook( + draw=True, interval=1, show=True, wait_time=1) + hook.after_val_iter(runner, 1, self.data_batch, self.outputs) + + def test_after_test_iter(self): + runner = Mock() + hook = SegVisualizationHook(draw=True, interval=1) + assert hook._test_index == 0 + hook.after_test_iter(runner, 1, self.data_batch, self.outputs) + assert hook._test_index == len(self.outputs) diff --git a/third-party/InterFormer/tests/test_evaluation/test_metrics/test_citys_metric.py b/third-party/InterFormer/tests/test_evaluation/test_metrics/test_citys_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..06f956f54aee9201e914b9b32aaf1769e2773d17 --- /dev/null +++ b/third-party/InterFormer/tests/test_evaluation/test_metrics/test_citys_metric.py @@ -0,0 +1,119 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import shutil +from unittest import TestCase + +import numpy as np +import pytest +import torch +from mmengine.structures import PixelData + +from mmseg.evaluation import CityscapesMetric +from mmseg.structures import SegDataSample + + +class TestCityscapesMetric(TestCase): + + def _demo_mm_inputs(self, + batch_size=1, + image_shapes=(3, 128, 256), + num_classes=5): + """Create a superset of inputs needed to run test or train batches. + + Args: + batch_size (int): batch size. Default to 2. + image_shapes (List[tuple], Optional): image shape. + Default to (3, 64, 64) + num_classes (int): number of different classes. + Default to 5. + """ + if isinstance(image_shapes, list): + assert len(image_shapes) == batch_size + else: + image_shapes = [image_shapes] * batch_size + + packed_inputs = [] + for idx in range(batch_size): + image_shape = image_shapes[idx] + _, h, w = image_shape + + data_sample = SegDataSample() + gt_semantic_seg = np.random.randint( + 0, num_classes, (1, h, w), dtype=np.uint8) + gt_semantic_seg = torch.LongTensor(gt_semantic_seg) + gt_sem_seg_data = dict(data=gt_semantic_seg) + data_sample.gt_sem_seg = PixelData(**gt_sem_seg_data) + data_sample = data_sample.to_dict() + data_sample[ + 'seg_map_path'] = 'tests/data/pseudo_cityscapes_dataset/gtFine/val/frankfurt/frankfurt_000000_000294_gtFine_labelTrainIds.png' # noqa + packed_inputs.append(data_sample) + + return packed_inputs + + def _demo_mm_model_output(self, + batch_size=1, + image_shapes=(3, 128, 256), + num_classes=5): + """Create a superset of inputs needed to run test or train batches. + + Args: + batch_size (int): batch size. Default to 2. + image_shapes (List[tuple], Optional): image shape. + Default to (3, 64, 64) + num_classes (int): number of different classes. + Default to 5. + """ + results_dict = dict() + _, h, w = image_shapes + seg_logit = torch.randn(batch_size, num_classes, h, w) + results_dict['seg_logits'] = seg_logit + seg_pred = np.random.randint( + 0, num_classes, (batch_size, h, w), dtype=np.uint8) + seg_pred = torch.LongTensor(seg_pred) + results_dict['pred_sem_seg'] = seg_pred + + batch_datasampes = [ + SegDataSample() + for _ in range(results_dict['pred_sem_seg'].shape[0]) + ] + for key, value in results_dict.items(): + for i in range(value.shape[0]): + setattr(batch_datasampes[i], key, PixelData(data=value[i])) + + _predictions = [] + for pred in batch_datasampes: + test_data = pred.to_dict() + test_data[ + 'img_path'] = 'tests/data/pseudo_cityscapes_dataset/leftImg8bit/val/frankfurt/frankfurt_000000_000294_leftImg8bit.png' # noqa + _predictions.append(test_data) + + return _predictions + + def test_evaluate(self): + """Test using the metric in the same way as Evalutor.""" + + data_batch = self._demo_mm_inputs(2) + predictions = self._demo_mm_model_output(2) + data_samples = [ + dict(**data, **result) + for data, result in zip(data_batch, predictions) + ] + # test keep_results should be True when format_only is True + with pytest.raises(AssertionError): + CityscapesMetric( + output_dir='tmp', format_only=True, keep_results=False) + + # test evaluate with cityscape metric + metric = CityscapesMetric(output_dir='tmp') + metric.process(data_batch, data_samples) + res = metric.evaluate(2) + self.assertIsInstance(res, dict) + + # test format_only + metric = CityscapesMetric( + output_dir='tmp', format_only=True, keep_results=True) + metric.process(data_batch, data_samples) + metric.evaluate(2) + assert osp.exists('tmp') + assert osp.isfile('tmp/frankfurt_000000_000294_leftImg8bit.png') + shutil.rmtree('tmp') diff --git a/third-party/InterFormer/tests/test_evaluation/test_metrics/test_depth_metric.py b/third-party/InterFormer/tests/test_evaluation/test_metrics/test_depth_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..a172db8fa209fc9e9d5ed0a5be6a561435e27e8f --- /dev/null +++ b/third-party/InterFormer/tests/test_evaluation/test_metrics/test_depth_metric.py @@ -0,0 +1,85 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import shutil +from unittest import TestCase + +import torch +from mmengine.structures import PixelData + +from mmseg.evaluation import DepthMetric +from mmseg.structures import SegDataSample + + +class TestDepthMetric(TestCase): + + def _demo_mm_inputs(self, + batch_size=2, + image_shapes=(3, 64, 64), + num_classes=5): + """Create a superset of inputs needed to run test or train batches. + + Args: + batch_size (int): batch size. Default to 2. + image_shapes (List[tuple], Optional): image shape. + Default to (3, 64, 64) + num_classes (int): number of different classes. + Default to 5. + """ + if isinstance(image_shapes, list): + assert len(image_shapes) == batch_size + else: + image_shapes = [image_shapes] * batch_size + + data_samples = [] + for idx in range(batch_size): + image_shape = image_shapes[idx] + _, h, w = image_shape + + data_sample = SegDataSample() + gt_depth_map = torch.rand((1, h, w)) * 10 + data_sample.gt_depth_map = PixelData(data=gt_depth_map) + + data_samples.append(data_sample.to_dict()) + + return data_samples + + def _demo_mm_model_output(self, + data_samples, + batch_size=2, + image_shapes=(3, 64, 64), + num_classes=5): + + _, h, w = image_shapes + + for data_sample in data_samples: + data_sample['pred_depth_map'] = dict(data=torch.randn(1, h, w)) + + data_sample[ + 'img_path'] = 'tests/data/pseudo_dataset/imgs/00000_img.jpg' + return data_samples + + def test_evaluate(self): + """Test using the metric in the same way as Evalutor.""" + + data_samples = self._demo_mm_inputs() + data_samples = self._demo_mm_model_output(data_samples) + + depth_metric = DepthMetric() + depth_metric.process([0] * len(data_samples), data_samples) + res = depth_metric.compute_metrics(depth_metric.results) + self.assertIsInstance(res, dict) + + # test save depth map file in output_dir + depth_metric = DepthMetric(output_dir='tmp') + depth_metric.process([0] * len(data_samples), data_samples) + assert osp.exists('tmp') + assert osp.isfile('tmp/00000_img.png') + shutil.rmtree('tmp') + + # test format_only + depth_metric = DepthMetric(output_dir='tmp', format_only=True) + depth_metric.process([0] * len(data_samples), data_samples) + assert depth_metric.results == [] + assert osp.exists('tmp') + assert osp.isfile('tmp/00000_img.png') + shutil.rmtree('tmp') diff --git a/third-party/InterFormer/tests/test_evaluation/test_metrics/test_iou_metric.py b/third-party/InterFormer/tests/test_evaluation/test_metrics/test_iou_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..7a0e9d53e3cb49beb6b3cf9bce9bfe00fd094937 --- /dev/null +++ b/third-party/InterFormer/tests/test_evaluation/test_metrics/test_iou_metric.py @@ -0,0 +1,104 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import shutil +from unittest import TestCase + +import numpy as np +import torch +from mmengine.structures import PixelData + +from mmseg.evaluation import IoUMetric +from mmseg.structures import SegDataSample + + +class TestIoUMetric(TestCase): + + def _demo_mm_inputs(self, + batch_size=2, + image_shapes=(3, 64, 64), + num_classes=5): + """Create a superset of inputs needed to run test or train batches. + + Args: + batch_size (int): batch size. Default to 2. + image_shapes (List[tuple], Optional): image shape. + Default to (3, 64, 64) + num_classes (int): number of different classes. + Default to 5. + """ + if isinstance(image_shapes, list): + assert len(image_shapes) == batch_size + else: + image_shapes = [image_shapes] * batch_size + + data_samples = [] + for idx in range(batch_size): + image_shape = image_shapes[idx] + _, h, w = image_shape + + data_sample = SegDataSample() + gt_semantic_seg = np.random.randint( + 0, num_classes, (1, h, w), dtype=np.uint8) + gt_semantic_seg = torch.LongTensor(gt_semantic_seg) + gt_sem_seg_data = dict(data=gt_semantic_seg) + data_sample.gt_sem_seg = PixelData(**gt_sem_seg_data) + + data_samples.append(data_sample.to_dict()) + + return data_samples + + def _demo_mm_model_output(self, + data_samples, + batch_size=2, + image_shapes=(3, 64, 64), + num_classes=5): + + _, h, w = image_shapes + + for data_sample in data_samples: + data_sample['seg_logits'] = dict( + data=torch.randn(num_classes, h, w)) + data_sample['pred_sem_seg'] = dict( + data=torch.randint(0, num_classes, (1, h, w))) + data_sample[ + 'img_path'] = 'tests/data/pseudo_dataset/imgs/00000_img.jpg' + return data_samples + + def test_evaluate(self): + """Test using the metric in the same way as Evalutor.""" + + data_samples = self._demo_mm_inputs() + data_samples = self._demo_mm_model_output(data_samples) + + iou_metric = IoUMetric(iou_metrics=['mIoU']) + iou_metric.dataset_meta = dict( + classes=['wall', 'building', 'sky', 'floor', 'tree'], + label_map=dict(), + reduce_zero_label=False) + iou_metric.process([0] * len(data_samples), data_samples) + res = iou_metric.evaluate(2) + self.assertIsInstance(res, dict) + + # test save segment file in output_dir + iou_metric = IoUMetric(iou_metrics=['mIoU'], output_dir='tmp') + iou_metric.dataset_meta = dict( + classes=['wall', 'building', 'sky', 'floor', 'tree'], + label_map=dict(), + reduce_zero_label=False) + iou_metric.process([0] * len(data_samples), data_samples) + assert osp.exists('tmp') + assert osp.isfile('tmp/00000_img.png') + shutil.rmtree('tmp') + + # test format_only + iou_metric = IoUMetric( + iou_metrics=['mIoU'], output_dir='tmp', format_only=True) + iou_metric.dataset_meta = dict( + classes=['wall', 'building', 'sky', 'floor', 'tree'], + label_map=dict(), + reduce_zero_label=False) + iou_metric.process([0] * len(data_samples), data_samples) + assert iou_metric.results == [] + assert osp.exists('tmp') + assert osp.isfile('tmp/00000_img.png') + shutil.rmtree('tmp') diff --git a/third-party/InterFormer/tests/test_models/__init__.py b/third-party/InterFormer/tests/test_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/third-party/InterFormer/tests/test_models/test_assigners/test_hungarian_assigner.py b/third-party/InterFormer/tests/test_models/test_assigners/test_hungarian_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..2cdb1de839d8ba19bc686fef95f8a65951aff136 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_assigners/test_hungarian_assigner.py @@ -0,0 +1,77 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmseg.models.assigners import HungarianAssigner + + +class TestHungarianAssigner(TestCase): + + def test_init(self): + with self.assertRaises(AssertionError): + HungarianAssigner([]) + + def test_hungarian_match_assigner(self): + assigner = HungarianAssigner([ + dict(type='ClassificationCost', weight=2.0), + dict(type='CrossEntropyLossCost', weight=5.0, use_sigmoid=True), + dict(type='DiceCost', weight=5.0, pred_act=True, eps=1.0) + ]) + num_classes = 3 + num_masks = 10 + num_points = 20 + gt_instances = InstanceData() + gt_instances.labels = torch.randint(0, num_classes, (num_classes, )) + gt_instances.masks = torch.randint(0, 2, (num_classes, num_points)) + pred_instances = InstanceData() + pred_instances.scores = torch.rand((num_masks, num_classes)) + pred_instances.masks = torch.rand((num_masks, num_points)) + + matched_quiery_inds, matched_label_inds = \ + assigner.assign(pred_instances, gt_instances) + unique_quiery_inds = torch.unique(matched_quiery_inds) + unique_label_inds = torch.unique(matched_label_inds) + self.assertTrue(len(unique_quiery_inds) == len(matched_quiery_inds)) + self.assertTrue( + torch.equal(unique_label_inds, torch.arange(0, num_classes))) + + def test_cls_match_cost(self): + num_classes = 3 + num_masks = 10 + gt_instances = InstanceData() + gt_instances.labels = torch.randint(0, num_classes, (num_classes, )) + pred_instances = InstanceData() + pred_instances.scores = torch.rand((num_masks, num_classes)) + + # test ClassificationCost + assigner = HungarianAssigner(dict(type='ClassificationCost')) + matched_quiery_inds, matched_label_inds = \ + assigner.assign(pred_instances, gt_instances) + unique_quiery_inds = torch.unique(matched_quiery_inds) + unique_label_inds = torch.unique(matched_label_inds) + self.assertTrue(len(unique_quiery_inds) == len(matched_quiery_inds)) + self.assertTrue( + torch.equal(unique_label_inds, torch.arange(0, num_classes))) + + def test_mask_match_cost(self): + num_classes = 3 + num_masks = 10 + num_points = 20 + gt_instances = InstanceData() + gt_instances.masks = torch.randint(0, 2, (num_classes, num_points)) + pred_instances = InstanceData() + pred_instances.masks = torch.rand((num_masks, num_points)) + + # test DiceCost + assigner = HungarianAssigner( + dict(type='DiceCost', pred_act=True, eps=1.0)) + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertTrue(len(assign_result[0]) == len(assign_result[1])) + + # test CrossEntropyLossCost + assigner = HungarianAssigner( + dict(type='CrossEntropyLossCost', use_sigmoid=True)) + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertTrue(len(assign_result[0]) == len(assign_result[1])) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/__init__.py b/third-party/InterFormer/tests/test_models/test_backbones/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_beit.py b/third-party/InterFormer/tests/test_models/test_backbones/test_beit.py new file mode 100644 index 0000000000000000000000000000000000000000..59a12c5d09e2e022330d0671700975477963c91d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_beit.py @@ -0,0 +1,185 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones.beit import BEiT +from .utils import check_norm_state + + +def test_beit_backbone(): + with pytest.raises(TypeError): + # pretrained must be a string path + model = BEiT() + model.init_weights(pretrained=0) + + with pytest.raises(TypeError): + # img_size must be int or tuple + model = BEiT(img_size=512.0) + + with pytest.raises(TypeError): + # out_indices must be int ,list or tuple + model = BEiT(out_indices=1.) + + with pytest.raises(AssertionError): + # The length of img_size tuple must be lower than 3. + BEiT(img_size=(224, 224, 224)) + + with pytest.raises(TypeError): + # Pretrained must be None or Str. + BEiT(pretrained=123) + + # Test img_size isinstance tuple + imgs = torch.randn(1, 3, 224, 224) + model = BEiT(img_size=(224, )) + model.init_weights() + model(imgs) + + # Test img_size isinstance tuple + imgs = torch.randn(1, 3, 224, 224) + model = BEiT(img_size=(224, 224)) + model(imgs) + + # Test norm_eval = True + model = BEiT(norm_eval=True) + model.train() + + # Test BEiT backbone with input size of 224 and patch size of 16 + model = BEiT() + model.init_weights() + model.train() + + # Test qv_bias + model = BEiT(qv_bias=False) + model.train() + + # Test out_indices = list + model = BEiT(out_indices=[2, 4, 8, 12]) + model.train() + + assert check_norm_state(model.modules(), True) + + # Test image size = (224, 224) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test BEiT backbone with input size of 256 and patch size of 16 + model = BEiT(img_size=(256, 256)) + model.init_weights() + model.train() + imgs = torch.randn(1, 3, 256, 256) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 16, 16) + + # Test BEiT backbone with input size of 32 and patch size of 16 + model = BEiT(img_size=(32, 32)) + model.init_weights() + model.train() + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 2, 2) + + # Test unbalanced size input image + model = BEiT(img_size=(112, 224)) + model.init_weights() + model.train() + imgs = torch.randn(1, 3, 112, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 7, 14) + + # Test irregular input image + model = BEiT(img_size=(234, 345)) + model.init_weights() + model.train() + imgs = torch.randn(1, 3, 234, 345) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 21) + + # Test init_values=0 + model = BEiT(init_values=0) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test final norm + model = BEiT(final_norm=True) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test patch norm + model = BEiT(patch_norm=True) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + +def test_beit_init(): + path = 'PATH_THAT_DO_NOT_EXIST' + # Test all combinations of pretrained and init_cfg + # pretrained=None, init_cfg=None + model = BEiT(pretrained=None, init_cfg=None) + assert model.init_cfg is None + model.init_weights() + + # pretrained=None + # init_cfg loads pretrain from an non-existent file + model = BEiT( + pretrained=None, init_cfg=dict(type='Pretrained', checkpoint=path)) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # test resize_rel_pos_embed + value = torch.randn(732, 16) + ckpt = { + 'state_dict': { + 'layers.0.attn.relative_position_index': 0, + 'layers.0.attn.relative_position_bias_table': value + } + } + model = BEiT(img_size=(512, 512)) + # If scipy is installed, this AttributeError would not be raised. + from mmengine.utils import is_installed + if not is_installed('scipy'): + with pytest.raises(AttributeError): + model.resize_rel_pos_embed(ckpt) + + # pretrained=None + # init_cfg=123, whose type is unsupported + model = BEiT(pretrained=None, init_cfg=123) + with pytest.raises(TypeError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg=None + model = BEiT(pretrained=path, init_cfg=None) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = BEiT( + pretrained=path, init_cfg=dict(type='Pretrained', checkpoint=path)) + with pytest.raises(AssertionError): + model = BEiT(pretrained=path, init_cfg=123) + + # pretrain=123, whose type is unsupported + # init_cfg=None + with pytest.raises(TypeError): + model = BEiT(pretrained=123, init_cfg=None) + + # pretrain=123, whose type is unsupported + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = BEiT( + pretrained=123, init_cfg=dict(type='Pretrained', checkpoint=path)) + + # pretrain=123, whose type is unsupported + # init_cfg=123, whose type is unsupported + with pytest.raises(AssertionError): + model = BEiT(pretrained=123, init_cfg=123) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_bisenetv1.py b/third-party/InterFormer/tests/test_models/test_backbones/test_bisenetv1.py new file mode 100644 index 0000000000000000000000000000000000000000..c0677493d6894f6285b6ee37a4a2c8a052ff8b4c --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_bisenetv1.py @@ -0,0 +1,109 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import BiSeNetV1 +from mmseg.models.backbones.bisenetv1 import (AttentionRefinementModule, + ContextPath, FeatureFusionModule, + SpatialPath) + + +def test_bisenetv1_backbone(): + # Test BiSeNetV1 Standard Forward + backbone_cfg = dict( + type='ResNet', + in_channels=3, + depth=18, + num_stages=4, + out_indices=(0, 1, 2, 3), + dilations=(1, 1, 1, 1), + strides=(1, 2, 2, 2), + norm_eval=False, + style='pytorch', + contract_dilation=True) + model = BiSeNetV1(in_channels=3, backbone_cfg=backbone_cfg) + model.init_weights() + model.train() + batch_size = 2 + imgs = torch.randn(batch_size, 3, 64, 128) + feat = model(imgs) + + assert len(feat) == 3 + # output for segment Head + assert feat[0].shape == torch.Size([batch_size, 256, 8, 16]) + # for auxiliary head 1 + assert feat[1].shape == torch.Size([batch_size, 128, 8, 16]) + # for auxiliary head 2 + assert feat[2].shape == torch.Size([batch_size, 128, 4, 8]) + + # Test input with rare shape + batch_size = 2 + imgs = torch.randn(batch_size, 3, 95, 27) + feat = model(imgs) + assert len(feat) == 3 + + with pytest.raises(AssertionError): + # BiSeNetV1 spatial path channel constraints. + BiSeNetV1( + backbone_cfg=backbone_cfg, + in_channels=3, + spatial_channels=(16, 16, 16)) + + with pytest.raises(AssertionError): + # BiSeNetV1 context path constraints. + BiSeNetV1( + backbone_cfg=backbone_cfg, + in_channels=3, + context_channels=(16, 32, 64, 128)) + + +def test_bisenetv1_spatial_path(): + with pytest.raises(AssertionError): + # BiSeNetV1 spatial path channel constraints. + SpatialPath(num_channels=(16, 16, 16), in_channels=3) + + +def test_bisenetv1_context_path(): + backbone_cfg = dict( + type='ResNet', + in_channels=3, + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + dilations=(1, 1, 1, 1), + strides=(1, 2, 2, 2), + norm_eval=False, + style='pytorch', + contract_dilation=True) + + with pytest.raises(AssertionError): + # BiSeNetV1 context path constraints. + ContextPath( + backbone_cfg=backbone_cfg, context_channels=(16, 32, 64, 128)) + + +def test_bisenetv1_attention_refinement_module(): + x_arm = AttentionRefinementModule(32, 8) + assert x_arm.conv_layer.in_channels == 32 + assert x_arm.conv_layer.out_channels == 8 + assert x_arm.conv_layer.kernel_size == (3, 3) + x = torch.randn(2, 32, 8, 16) + x_out = x_arm(x) + assert x_out.shape == torch.Size([2, 8, 8, 16]) + + +def test_bisenetv1_feature_fusion_module(): + ffm = FeatureFusionModule(16, 32) + assert ffm.conv1.in_channels == 16 + assert ffm.conv1.out_channels == 32 + assert ffm.conv1.kernel_size == (1, 1) + assert ffm.gap.output_size == (1, 1) + assert ffm.conv_atten[0].in_channels == 32 + assert ffm.conv_atten[0].out_channels == 32 + assert ffm.conv_atten[0].kernel_size == (1, 1) + + ffm = FeatureFusionModule(16, 16) + x1 = torch.randn(2, 8, 8, 16) + x2 = torch.randn(2, 8, 8, 16) + x_out = ffm(x1, x2) + assert x_out.shape == torch.Size([2, 16, 8, 16]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_bisenetv2.py b/third-party/InterFormer/tests/test_models/test_backbones/test_bisenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..cf2dfb3253a0c766b2a052f22a4140693910ade1 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_bisenetv2.py @@ -0,0 +1,57 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import ConvModule + +from mmseg.models.backbones import BiSeNetV2 +from mmseg.models.backbones.bisenetv2 import (BGALayer, DetailBranch, + SemanticBranch) + + +def test_bisenetv2_backbone(): + # Test BiSeNetV2 Standard Forward + model = BiSeNetV2() + model.init_weights() + model.train() + batch_size = 2 + imgs = torch.randn(batch_size, 3, 128, 256) + feat = model(imgs) + + assert len(feat) == 5 + # output for segment Head + assert feat[0].shape == torch.Size([batch_size, 128, 16, 32]) + # for auxiliary head 1 + assert feat[1].shape == torch.Size([batch_size, 16, 32, 64]) + # for auxiliary head 2 + assert feat[2].shape == torch.Size([batch_size, 32, 16, 32]) + # for auxiliary head 3 + assert feat[3].shape == torch.Size([batch_size, 64, 8, 16]) + # for auxiliary head 4 + assert feat[4].shape == torch.Size([batch_size, 128, 4, 8]) + + # Test input with rare shape + batch_size = 2 + imgs = torch.randn(batch_size, 3, 95, 27) + feat = model(imgs) + assert len(feat) == 5 + + +def test_bisenetv2_DetailBranch(): + x = torch.randn(1, 3, 32, 64) + detail_branch = DetailBranch(detail_channels=(64, 16, 32)) + assert isinstance(detail_branch.detail_branch[0][0], ConvModule) + x_out = detail_branch(x) + assert x_out.shape == torch.Size([1, 32, 4, 8]) + + +def test_bisenetv2_SemanticBranch(): + semantic_branch = SemanticBranch(semantic_channels=(16, 32, 64, 128)) + assert semantic_branch.stage1.pool.stride == 2 + + +def test_bisenetv2_BGALayer(): + x_a = torch.randn(1, 8, 8, 16) + x_b = torch.randn(1, 8, 2, 4) + bga = BGALayer(out_channels=8) + assert isinstance(bga.conv, ConvModule) + x_out = bga(x_a, x_b) + assert x_out.shape == torch.Size([1, 8, 8, 16]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_blocks.py b/third-party/InterFormer/tests/test_models/test_backbones/test_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..7a65d272cfe0f2270e7bed5aadbf32f4a9e9665e --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_blocks.py @@ -0,0 +1,187 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import mmcv +import pytest +import torch +from mmengine.utils import digit_version +from mmengine.utils.dl_utils import TORCH_VERSION + +from mmseg.models.utils import (InvertedResidual, InvertedResidualV3, SELayer, + make_divisible) + + +def test_make_divisible(): + # test with min_value = None + assert make_divisible(10, 4) == 12 + assert make_divisible(9, 4) == 12 + assert make_divisible(1, 4) == 4 + + # test with min_value = 8 + assert make_divisible(10, 4, 8) == 12 + assert make_divisible(9, 4, 8) == 12 + assert make_divisible(1, 4, 8) == 8 + + +def test_inv_residual(): + with pytest.raises(AssertionError): + # test stride assertion. + InvertedResidual(32, 32, 3, 4) + + # test default config with res connection. + # set expand_ratio = 4, stride = 1 and inp=oup. + inv_module = InvertedResidual(32, 32, 1, 4) + assert inv_module.use_res_connect + assert inv_module.conv[0].kernel_size == (1, 1) + assert inv_module.conv[0].padding == 0 + assert inv_module.conv[1].kernel_size == (3, 3) + assert inv_module.conv[1].padding == 1 + assert inv_module.conv[0].with_norm + assert inv_module.conv[1].with_norm + x = torch.rand(1, 32, 64, 64) + output = inv_module(x) + assert output.shape == (1, 32, 64, 64) + + # test inv_residual module without res connection. + # set expand_ratio = 4, stride = 2. + inv_module = InvertedResidual(32, 32, 2, 4) + assert not inv_module.use_res_connect + assert inv_module.conv[0].kernel_size == (1, 1) + x = torch.rand(1, 32, 64, 64) + output = inv_module(x) + assert output.shape == (1, 32, 32, 32) + + # test expand_ratio == 1 + inv_module = InvertedResidual(32, 32, 1, 1) + assert inv_module.conv[0].kernel_size == (3, 3) + x = torch.rand(1, 32, 64, 64) + output = inv_module(x) + assert output.shape == (1, 32, 64, 64) + + # test with checkpoint forward + inv_module = InvertedResidual(32, 32, 1, 1, with_cp=True) + assert inv_module.with_cp + x = torch.rand(1, 32, 64, 64, requires_grad=True) + output = inv_module(x) + assert output.shape == (1, 32, 64, 64) + + +def test_inv_residualv3(): + with pytest.raises(AssertionError): + # test stride assertion. + InvertedResidualV3(32, 32, 16, stride=3) + + with pytest.raises(AssertionError): + # test assertion. + InvertedResidualV3(32, 32, 16, with_expand_conv=False) + + # test with se_cfg=None, with_expand_conv=False + inv_module = InvertedResidualV3(32, 32, 32, with_expand_conv=False) + + assert inv_module.with_res_shortcut is True + assert inv_module.with_se is False + assert inv_module.with_expand_conv is False + assert not hasattr(inv_module, 'expand_conv') + assert isinstance(inv_module.depthwise_conv.conv, torch.nn.Conv2d) + assert inv_module.depthwise_conv.conv.kernel_size == (3, 3) + assert inv_module.depthwise_conv.conv.stride == (1, 1) + assert inv_module.depthwise_conv.conv.padding == (1, 1) + assert isinstance(inv_module.depthwise_conv.bn, torch.nn.BatchNorm2d) + assert isinstance(inv_module.depthwise_conv.activate, torch.nn.ReLU) + assert inv_module.linear_conv.conv.kernel_size == (1, 1) + assert inv_module.linear_conv.conv.stride == (1, 1) + assert inv_module.linear_conv.conv.padding == (0, 0) + assert isinstance(inv_module.linear_conv.bn, torch.nn.BatchNorm2d) + + x = torch.rand(1, 32, 64, 64) + output = inv_module(x) + assert output.shape == (1, 32, 64, 64) + + # test with se_cfg and with_expand_conv + se_cfg = dict( + channels=16, + ratio=4, + act_cfg=(dict(type='ReLU'), + dict(type='HSigmoid', bias=3.0, divisor=6.0))) + act_cfg = dict(type='HSwish') + inv_module = InvertedResidualV3( + 32, 40, 16, 3, 2, se_cfg=se_cfg, act_cfg=act_cfg) + assert inv_module.with_res_shortcut is False + assert inv_module.with_se is True + assert inv_module.with_expand_conv is True + assert inv_module.expand_conv.conv.kernel_size == (1, 1) + assert inv_module.expand_conv.conv.stride == (1, 1) + assert inv_module.expand_conv.conv.padding == (0, 0) + + assert isinstance(inv_module.depthwise_conv.conv, + mmcv.cnn.bricks.Conv2dAdaptivePadding) + assert inv_module.depthwise_conv.conv.kernel_size == (3, 3) + assert inv_module.depthwise_conv.conv.stride == (2, 2) + assert inv_module.depthwise_conv.conv.padding == (0, 0) + assert isinstance(inv_module.depthwise_conv.bn, torch.nn.BatchNorm2d) + + assert inv_module.linear_conv.conv.kernel_size == (1, 1) + assert inv_module.linear_conv.conv.stride == (1, 1) + assert inv_module.linear_conv.conv.padding == (0, 0) + assert isinstance(inv_module.linear_conv.bn, torch.nn.BatchNorm2d) + + if (TORCH_VERSION == 'parrots' + or digit_version(TORCH_VERSION) < digit_version('1.7')): + # Note: Use PyTorch official HSwish + # when torch>=1.7 after MMCV >= 1.4.5. + # Hardswish is not supported when PyTorch version < 1.6. + # And Hardswish in PyTorch 1.6 does not support inplace. + # More details could be found from: + # https://github.com/open-mmlab/mmcv/pull/1709 + assert isinstance(inv_module.expand_conv.activate, mmcv.cnn.HSwish) + assert isinstance(inv_module.depthwise_conv.activate, mmcv.cnn.HSwish) + else: + assert isinstance(inv_module.expand_conv.activate, torch.nn.Hardswish) + assert isinstance(inv_module.depthwise_conv.activate, + torch.nn.Hardswish) + + x = torch.rand(1, 32, 64, 64) + output = inv_module(x) + assert output.shape == (1, 40, 32, 32) + + # test with checkpoint forward + inv_module = InvertedResidualV3( + 32, 40, 16, 3, 2, se_cfg=se_cfg, act_cfg=act_cfg, with_cp=True) + assert inv_module.with_cp + x = torch.randn(2, 32, 64, 64, requires_grad=True) + output = inv_module(x) + assert output.shape == (2, 40, 32, 32) + + +def test_se_layer(): + with pytest.raises(AssertionError): + # test act_cfg assertion. + SELayer(32, act_cfg=(dict(type='ReLU'), )) + + # test config with channels = 16. + se_layer = SELayer(16) + assert se_layer.conv1.conv.kernel_size == (1, 1) + assert se_layer.conv1.conv.stride == (1, 1) + assert se_layer.conv1.conv.padding == (0, 0) + assert isinstance(se_layer.conv1.activate, torch.nn.ReLU) + assert se_layer.conv2.conv.kernel_size == (1, 1) + assert se_layer.conv2.conv.stride == (1, 1) + assert se_layer.conv2.conv.padding == (0, 0) + assert isinstance(se_layer.conv2.activate, mmcv.cnn.HSigmoid) + + x = torch.rand(1, 16, 64, 64) + output = se_layer(x) + assert output.shape == (1, 16, 64, 64) + + # test config with channels = 16, act_cfg = dict(type='ReLU'). + se_layer = SELayer(16, act_cfg=dict(type='ReLU')) + assert se_layer.conv1.conv.kernel_size == (1, 1) + assert se_layer.conv1.conv.stride == (1, 1) + assert se_layer.conv1.conv.padding == (0, 0) + assert isinstance(se_layer.conv1.activate, torch.nn.ReLU) + assert se_layer.conv2.conv.kernel_size == (1, 1) + assert se_layer.conv2.conv.stride == (1, 1) + assert se_layer.conv2.conv.padding == (0, 0) + assert isinstance(se_layer.conv2.activate, torch.nn.ReLU) + + x = torch.rand(1, 16, 64, 64) + output = se_layer(x) + assert output.shape == (1, 16, 64, 64) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_cgnet.py b/third-party/InterFormer/tests/test_models/test_backbones/test_cgnet.py new file mode 100644 index 0000000000000000000000000000000000000000..f938525d0a4433cf1f7302c74a4a5bf20be9bec6 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_cgnet.py @@ -0,0 +1,151 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import CGNet +from mmseg.models.backbones.cgnet import (ContextGuidedBlock, + GlobalContextExtractor) + + +def test_cgnet_GlobalContextExtractor(): + block = GlobalContextExtractor(16, 16, with_cp=True) + x = torch.randn(2, 16, 64, 64, requires_grad=True) + x_out = block(x) + assert x_out.shape == torch.Size([2, 16, 64, 64]) + + +def test_cgnet_context_guided_block(): + with pytest.raises(AssertionError): + # cgnet ContextGuidedBlock GlobalContextExtractor channel and reduction + # constraints. + ContextGuidedBlock(8, 8) + + # test cgnet ContextGuidedBlock with checkpoint forward + block = ContextGuidedBlock( + 16, 16, act_cfg=dict(type='PReLU'), with_cp=True) + assert block.with_cp + x = torch.randn(2, 16, 64, 64, requires_grad=True) + x_out = block(x) + assert x_out.shape == torch.Size([2, 16, 64, 64]) + + # test cgnet ContextGuidedBlock without checkpoint forward + block = ContextGuidedBlock(32, 32) + assert not block.with_cp + x = torch.randn(3, 32, 32, 32) + x_out = block(x) + assert x_out.shape == torch.Size([3, 32, 32, 32]) + + # test cgnet ContextGuidedBlock with down sampling + block = ContextGuidedBlock(32, 32, downsample=True) + assert block.conv1x1.conv.in_channels == 32 + assert block.conv1x1.conv.out_channels == 32 + assert block.conv1x1.conv.kernel_size == (3, 3) + assert block.conv1x1.conv.stride == (2, 2) + assert block.conv1x1.conv.padding == (1, 1) + + assert block.f_loc.in_channels == 32 + assert block.f_loc.out_channels == 32 + assert block.f_loc.kernel_size == (3, 3) + assert block.f_loc.stride == (1, 1) + assert block.f_loc.padding == (1, 1) + assert block.f_loc.groups == 32 + assert block.f_loc.dilation == (1, 1) + assert block.f_loc.bias is None + + assert block.f_sur.in_channels == 32 + assert block.f_sur.out_channels == 32 + assert block.f_sur.kernel_size == (3, 3) + assert block.f_sur.stride == (1, 1) + assert block.f_sur.padding == (2, 2) + assert block.f_sur.groups == 32 + assert block.f_sur.dilation == (2, 2) + assert block.f_sur.bias is None + + assert block.bottleneck.in_channels == 64 + assert block.bottleneck.out_channels == 32 + assert block.bottleneck.kernel_size == (1, 1) + assert block.bottleneck.stride == (1, 1) + assert block.bottleneck.bias is None + + x = torch.randn(1, 32, 32, 32) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 16, 16]) + + # test cgnet ContextGuidedBlock without down sampling + block = ContextGuidedBlock(32, 32, downsample=False) + assert block.conv1x1.conv.in_channels == 32 + assert block.conv1x1.conv.out_channels == 16 + assert block.conv1x1.conv.kernel_size == (1, 1) + assert block.conv1x1.conv.stride == (1, 1) + assert block.conv1x1.conv.padding == (0, 0) + + assert block.f_loc.in_channels == 16 + assert block.f_loc.out_channels == 16 + assert block.f_loc.kernel_size == (3, 3) + assert block.f_loc.stride == (1, 1) + assert block.f_loc.padding == (1, 1) + assert block.f_loc.groups == 16 + assert block.f_loc.dilation == (1, 1) + assert block.f_loc.bias is None + + assert block.f_sur.in_channels == 16 + assert block.f_sur.out_channels == 16 + assert block.f_sur.kernel_size == (3, 3) + assert block.f_sur.stride == (1, 1) + assert block.f_sur.padding == (2, 2) + assert block.f_sur.groups == 16 + assert block.f_sur.dilation == (2, 2) + assert block.f_sur.bias is None + + x = torch.randn(1, 32, 32, 32) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 32, 32]) + + +def test_cgnet_backbone(): + with pytest.raises(AssertionError): + # check invalid num_channels + CGNet(num_channels=(32, 64, 128, 256)) + + with pytest.raises(AssertionError): + # check invalid num_blocks + CGNet(num_blocks=(3, 21, 3)) + + with pytest.raises(AssertionError): + # check invalid dilation + CGNet(num_blocks=2) + + with pytest.raises(AssertionError): + # check invalid reduction + CGNet(reductions=16) + + with pytest.raises(AssertionError): + # check invalid num_channels and reduction + CGNet(num_channels=(32, 64, 128), reductions=(64, 129)) + + # Test CGNet with default settings + model = CGNet() + model.init_weights() + model.train() + + imgs = torch.randn(2, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == torch.Size([2, 35, 112, 112]) + assert feat[1].shape == torch.Size([2, 131, 56, 56]) + assert feat[2].shape == torch.Size([2, 256, 28, 28]) + + # Test CGNet with norm_eval True and with_cp True + model = CGNet(norm_eval=True, with_cp=True) + with pytest.raises(TypeError): + # check invalid pretrained + model.init_weights(pretrained=8) + model.init_weights() + model.train() + + imgs = torch.randn(2, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == torch.Size([2, 35, 112, 112]) + assert feat[1].shape == torch.Size([2, 131, 56, 56]) + assert feat[2].shape == torch.Size([2, 256, 28, 28]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_clip_text_encoder.py b/third-party/InterFormer/tests/test_models/test_backbones/test_clip_text_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..ea06c5b5b3fa3fa4c5ea73e858c98be1a14ac18b --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_clip_text_encoder.py @@ -0,0 +1,43 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine import Config +from mmengine.registry import init_default_scope + +from mmseg.models.text_encoder import CLIPTextEncoder +from mmseg.utils import get_classes + + +def test_clip_text_encoder(): + init_default_scope('mmseg') + # test vocabulary + output_dims = 8 + embed_dims = 32 + vocabulary = ['cat', 'dog', 'bird', 'car', 'bike'] + cfg = dict( + vocabulary=vocabulary, + templates=['a photo of a {}.'], + embed_dims=embed_dims, + output_dims=output_dims) + cfg = Config(cfg) + + text_encoder = CLIPTextEncoder(**cfg) + if torch.cuda.is_available(): + text_encoder = text_encoder.cuda() + + with torch.no_grad(): + class_embeds = text_encoder() + assert class_embeds.shape == (len(vocabulary) + 1, output_dims) + + # test dataset name + cfg = dict( + dataset_name='vaihingen', + templates=['a photo of a {}.'], + embed_dims=embed_dims, + output_dims=output_dims) + cfg = Config(cfg) + + text_encoder = CLIPTextEncoder(**cfg) + with torch.no_grad(): + class_embeds = text_encoder() + class_nums = len(get_classes('vaihingen')) + assert class_embeds.shape == (class_nums + 1, output_dims) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_erfnet.py b/third-party/InterFormer/tests/test_models/test_backbones/test_erfnet.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae7345e1524fd104eb243e52bec5d0f75a24d64 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_erfnet.py @@ -0,0 +1,146 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import ERFNet +from mmseg.models.backbones.erfnet import (DownsamplerBlock, NonBottleneck1d, + UpsamplerBlock) + + +def test_erfnet_backbone(): + # Test ERFNet Standard Forward. + model = ERFNet( + in_channels=3, + enc_downsample_channels=(16, 64, 128), + enc_stage_non_bottlenecks=(5, 8), + enc_non_bottleneck_dilations=(2, 4, 8, 16), + enc_non_bottleneck_channels=(64, 128), + dec_upsample_channels=(64, 16), + dec_stages_non_bottleneck=(2, 2), + dec_non_bottleneck_channels=(64, 16), + dropout_ratio=0.1, + ) + model.init_weights() + model.train() + batch_size = 2 + imgs = torch.randn(batch_size, 3, 256, 512) + output = model(imgs) + + # output for segment Head + assert output[0].shape == torch.Size([batch_size, 16, 128, 256]) + + # Test input with rare shape + batch_size = 2 + imgs = torch.randn(batch_size, 3, 527, 279) + output = model(imgs) + assert len(output[0]) == batch_size + + with pytest.raises(AssertionError): + # Number of encoder downsample block and decoder upsample block. + ERFNet( + in_channels=3, + enc_downsample_channels=(16, 64, 128), + enc_stage_non_bottlenecks=(5, 8), + enc_non_bottleneck_dilations=(2, 4, 8, 16), + enc_non_bottleneck_channels=(64, 128), + dec_upsample_channels=(128, 64, 16), + dec_stages_non_bottleneck=(2, 2), + dec_non_bottleneck_channels=(64, 16), + dropout_ratio=0.1, + ) + with pytest.raises(AssertionError): + # Number of encoder downsample block and encoder Non-bottleneck block. + ERFNet( + in_channels=3, + enc_downsample_channels=(16, 64, 128), + enc_stage_non_bottlenecks=(5, 8, 10), + enc_non_bottleneck_dilations=(2, 4, 8, 16), + enc_non_bottleneck_channels=(64, 128), + dec_upsample_channels=(64, 16), + dec_stages_non_bottleneck=(2, 2), + dec_non_bottleneck_channels=(64, 16), + dropout_ratio=0.1, + ) + with pytest.raises(AssertionError): + # Number of encoder downsample block and + # channels of encoder Non-bottleneck block. + ERFNet( + in_channels=3, + enc_downsample_channels=(16, 64, 128), + enc_stage_non_bottlenecks=(5, 8), + enc_non_bottleneck_dilations=(2, 4, 8, 16), + enc_non_bottleneck_channels=(64, 128, 256), + dec_upsample_channels=(64, 16), + dec_stages_non_bottleneck=(2, 2), + dec_non_bottleneck_channels=(64, 16), + dropout_ratio=0.1, + ) + + with pytest.raises(AssertionError): + # Number of encoder Non-bottleneck block and number of its channels. + ERFNet( + in_channels=3, + enc_downsample_channels=(16, 64, 128), + enc_stage_non_bottlenecks=(5, 8, 3), + enc_non_bottleneck_dilations=(2, 4, 8, 16), + enc_non_bottleneck_channels=(64, 128), + dec_upsample_channels=(64, 16), + dec_stages_non_bottleneck=(2, 2), + dec_non_bottleneck_channels=(64, 16), + dropout_ratio=0.1, + ) + with pytest.raises(AssertionError): + # Number of decoder upsample block and decoder Non-bottleneck block. + ERFNet( + in_channels=3, + enc_downsample_channels=(16, 64, 128), + enc_stage_non_bottlenecks=(5, 8), + enc_non_bottleneck_dilations=(2, 4, 8, 16), + enc_non_bottleneck_channels=(64, 128), + dec_upsample_channels=(64, 16), + dec_stages_non_bottleneck=(2, 2, 3), + dec_non_bottleneck_channels=(64, 16), + dropout_ratio=0.1, + ) + with pytest.raises(AssertionError): + # Number of decoder Non-bottleneck block and number of its channels. + ERFNet( + in_channels=3, + enc_downsample_channels=(16, 64, 128), + enc_stage_non_bottlenecks=(5, 8), + enc_non_bottleneck_dilations=(2, 4, 8, 16), + enc_non_bottleneck_channels=(64, 128), + dec_upsample_channels=(64, 16), + dec_stages_non_bottleneck=(2, 2), + dec_non_bottleneck_channels=(64, 16, 8), + dropout_ratio=0.1, + ) + + +def test_erfnet_downsampler_block(): + x_db = DownsamplerBlock(16, 64) + assert x_db.conv.in_channels == 16 + assert x_db.conv.out_channels == 48 + assert len(x_db.bn.weight) == 64 + assert x_db.pool.kernel_size == 2 + assert x_db.pool.stride == 2 + + +def test_erfnet_non_bottleneck_1d(): + x_nb1d = NonBottleneck1d(16, 0, 1) + assert x_nb1d.convs_layers[0].in_channels == 16 + assert x_nb1d.convs_layers[0].out_channels == 16 + assert x_nb1d.convs_layers[2].in_channels == 16 + assert x_nb1d.convs_layers[2].out_channels == 16 + assert x_nb1d.convs_layers[5].in_channels == 16 + assert x_nb1d.convs_layers[5].out_channels == 16 + assert x_nb1d.convs_layers[7].in_channels == 16 + assert x_nb1d.convs_layers[7].out_channels == 16 + assert x_nb1d.convs_layers[9].p == 0 + + +def test_erfnet_upsampler_block(): + x_ub = UpsamplerBlock(64, 16) + assert x_ub.conv.in_channels == 64 + assert x_ub.conv.out_channels == 16 + assert len(x_ub.bn.weight) == 16 diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_fast_scnn.py b/third-party/InterFormer/tests/test_models/test_backbones/test_fast_scnn.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee638b510af37783fc7f18f30302800b0196ddb --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_fast_scnn.py @@ -0,0 +1,42 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import FastSCNN + + +def test_fastscnn_backbone(): + with pytest.raises(AssertionError): + # Fast-SCNN channel constraints. + FastSCNN( + 3, (32, 48), + 64, (64, 96, 128), (2, 2, 1), + global_out_channels=127, + higher_in_channels=64, + lower_in_channels=128) + + # Test FastSCNN Standard Forward + model = FastSCNN( + in_channels=3, + downsample_dw_channels=(4, 6), + global_in_channels=8, + global_block_channels=(8, 12, 16), + global_block_strides=(2, 2, 1), + global_out_channels=16, + higher_in_channels=8, + lower_in_channels=16, + fusion_out_channels=16, + ) + model.init_weights() + model.train() + batch_size = 4 + imgs = torch.randn(batch_size, 3, 64, 128) + feat = model(imgs) + + assert len(feat) == 3 + # higher-res + assert feat[0].shape == torch.Size([batch_size, 8, 8, 16]) + # lower-res + assert feat[1].shape == torch.Size([batch_size, 16, 2, 4]) + # FFM output + assert feat[2].shape == torch.Size([batch_size, 16, 8, 16]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_hrnet.py b/third-party/InterFormer/tests/test_models/test_backbones/test_hrnet.py new file mode 100644 index 0000000000000000000000000000000000000000..3e355153906ea0181d289186767e1f41cfb294cc --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_hrnet.py @@ -0,0 +1,144 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm + +from mmseg.models.backbones.hrnet import HRModule, HRNet +from mmseg.models.backbones.resnet import BasicBlock, Bottleneck + + +@pytest.mark.parametrize('block', [BasicBlock, Bottleneck]) +def test_hrmodule(block): + # Test multiscale forward + num_channles = (32, 64) + in_channels = [c * block.expansion for c in num_channles] + hrmodule = HRModule( + num_branches=2, + blocks=block, + in_channels=in_channels, + num_blocks=(4, 4), + num_channels=num_channles, + ) + + feats = [ + torch.randn(1, in_channels[0], 64, 64), + torch.randn(1, in_channels[1], 32, 32) + ] + feats = hrmodule(feats) + + assert len(feats) == 2 + assert feats[0].shape == torch.Size([1, in_channels[0], 64, 64]) + assert feats[1].shape == torch.Size([1, in_channels[1], 32, 32]) + + # Test single scale forward + num_channles = (32, 64) + in_channels = [c * block.expansion for c in num_channles] + hrmodule = HRModule( + num_branches=2, + blocks=block, + in_channels=in_channels, + num_blocks=(4, 4), + num_channels=num_channles, + multiscale_output=False, + ) + + feats = [ + torch.randn(1, in_channels[0], 64, 64), + torch.randn(1, in_channels[1], 32, 32) + ] + feats = hrmodule(feats) + + assert len(feats) == 1 + assert feats[0].shape == torch.Size([1, in_channels[0], 64, 64]) + + +def test_hrnet_backbone(): + # only have 3 stages + extra = dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128))) + + with pytest.raises(AssertionError): + # HRNet now only support 4 stages + HRNet(extra=extra) + extra['stage4'] = dict( + num_modules=3, + num_branches=3, # should be 4 + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256)) + + with pytest.raises(AssertionError): + # len(num_blocks) should equal num_branches + HRNet(extra=extra) + + extra['stage4']['num_branches'] = 4 + + # Test hrnetv2p_w32 + model = HRNet(extra=extra) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 64, 64) + feats = model(imgs) + assert len(feats) == 4 + assert feats[0].shape == torch.Size([1, 32, 16, 16]) + assert feats[3].shape == torch.Size([1, 256, 2, 2]) + + # Test single scale output + model = HRNet(extra=extra, multiscale_output=False) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 64, 64) + feats = model(imgs) + assert len(feats) == 1 + assert feats[0].shape == torch.Size([1, 32, 16, 16]) + + # Test HRNET with two stage frozen + frozen_stages = 2 + model = HRNet(extra, frozen_stages=frozen_stages) + model.init_weights() + model.train() + assert model.norm1.training is False + + for layer in [model.conv1, model.norm1]: + for param in layer.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + if i == 1: + layer = getattr(model, f'layer{i}') + transition = getattr(model, f'transition{i}') + elif i == 4: + layer = getattr(model, f'stage{i}') + else: + layer = getattr(model, f'stage{i}') + transition = getattr(model, f'transition{i}') + + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + for mod in transition.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in transition.parameters(): + assert param.requires_grad is False diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_icnet.py b/third-party/InterFormer/tests/test_models/test_backbones/test_icnet.py new file mode 100644 index 0000000000000000000000000000000000000000..a96d8d86fbd98db07b34770f7b46d03c32fb067c --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_icnet.py @@ -0,0 +1,50 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import ICNet + + +def test_icnet_backbone(): + with pytest.raises(TypeError): + # Must give backbone dict in config file. + ICNet( + in_channels=3, + layer_channels=(128, 512), + light_branch_middle_channels=8, + psp_out_channels=128, + out_channels=(16, 128, 128), + backbone_cfg=None) + + # Test ICNet Standard Forward + model = ICNet( + layer_channels=(128, 512), + backbone_cfg=dict( + type='ResNetV1c', + in_channels=3, + depth=18, + num_stages=4, + out_indices=(0, 1, 2, 3), + dilations=(1, 1, 2, 4), + strides=(1, 2, 1, 1), + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=False, + style='pytorch', + contract_dilation=True), + ) + assert hasattr(model.backbone, + 'maxpool') and model.backbone.maxpool.ceil_mode is True + model.init_weights() + model.train() + batch_size = 2 + imgs = torch.randn(batch_size, 3, 32, 64) + feat = model(imgs) + + assert model.psp_modules[0][0].output_size == 1 + assert model.psp_modules[1][0].output_size == 2 + assert model.psp_modules[2][0].output_size == 3 + assert model.psp_bottleneck.padding == 1 + assert model.conv_sub1[0].padding == 1 + + assert len(feat) == 3 + assert feat[0].shape == torch.Size([batch_size, 64, 4, 8]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_mae.py b/third-party/InterFormer/tests/test_models/test_backbones/test_mae.py new file mode 100644 index 0000000000000000000000000000000000000000..16f52b54b4f1ab6f2900dcd2cb7a819b15bb2c46 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_mae.py @@ -0,0 +1,186 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones.mae import MAE +from .utils import check_norm_state + + +def test_mae_backbone(): + with pytest.raises(TypeError): + # pretrained must be a string path + model = MAE() + model.init_weights(pretrained=0) + + with pytest.raises(TypeError): + # img_size must be int or tuple + model = MAE(img_size=512.0) + + with pytest.raises(TypeError): + # out_indices must be int ,list or tuple + model = MAE(out_indices=1.) + + with pytest.raises(AssertionError): + # The length of img_size tuple must be lower than 3. + MAE(img_size=(224, 224, 224)) + + with pytest.raises(TypeError): + # Pretrained must be None or Str. + MAE(pretrained=123) + + # Test img_size isinstance tuple + imgs = torch.randn(1, 3, 224, 224) + model = MAE(img_size=(224, )) + model.init_weights() + model(imgs) + + # Test img_size isinstance tuple + imgs = torch.randn(1, 3, 224, 224) + model = MAE(img_size=(224, 224)) + model(imgs) + + # Test norm_eval = True + model = MAE(norm_eval=True) + model.train() + + # Test BEiT backbone with input size of 224 and patch size of 16 + model = MAE() + model.init_weights() + model.train() + + # Test out_indices = list + model = MAE(out_indices=[2, 4, 8, 12]) + model.train() + + assert check_norm_state(model.modules(), True) + + # Test image size = (224, 224) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test MAE backbone with input size of 256 and patch size of 16 + model = MAE(img_size=(256, 256)) + model.init_weights() + model.train() + imgs = torch.randn(1, 3, 256, 256) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 16, 16) + + # Test MAE backbone with input size of 32 and patch size of 16 + model = MAE(img_size=(32, 32)) + model.init_weights() + model.train() + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 2, 2) + + # Test unbalanced size input image + model = MAE(img_size=(112, 224)) + model.init_weights() + model.train() + imgs = torch.randn(1, 3, 112, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 7, 14) + + # Test irregular input image + model = MAE(img_size=(234, 345)) + model.init_weights() + model.train() + imgs = torch.randn(1, 3, 234, 345) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 21) + + # Test init_values=0 + model = MAE(init_values=0) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test final norm + model = MAE(final_norm=True) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test patch norm + model = MAE(patch_norm=True) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + +def test_mae_init(): + path = 'PATH_THAT_DO_NOT_EXIST' + # Test all combinations of pretrained and init_cfg + # pretrained=None, init_cfg=None + model = MAE(pretrained=None, init_cfg=None) + assert model.init_cfg is None + model.init_weights() + + # pretrained=None + # init_cfg loads pretrain from an non-existent file + model = MAE( + pretrained=None, init_cfg=dict(type='Pretrained', checkpoint=path)) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # test resize_rel_pos_embed + value = torch.randn(732, 16) + abs_pos_embed_value = torch.rand(1, 17, 768) + ckpt = { + 'state_dict': { + 'layers.0.attn.relative_position_index': 0, + 'layers.0.attn.relative_position_bias_table': value, + 'pos_embed': abs_pos_embed_value + } + } + model = MAE(img_size=(512, 512)) + # If scipy is installed, this AttributeError would not be raised. + from mmengine.utils import is_installed + if not is_installed('scipy'): + with pytest.raises(AttributeError): + model.resize_rel_pos_embed(ckpt) + + # test resize abs pos embed + ckpt = model.resize_abs_pos_embed(ckpt['state_dict']) + + # pretrained=None + # init_cfg=123, whose type is unsupported + model = MAE(pretrained=None, init_cfg=123) + with pytest.raises(TypeError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg=None + model = MAE(pretrained=path, init_cfg=None) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = MAE( + pretrained=path, init_cfg=dict(type='Pretrained', checkpoint=path)) + with pytest.raises(AssertionError): + model = MAE(pretrained=path, init_cfg=123) + + # pretrain=123, whose type is unsupported + # init_cfg=None + with pytest.raises(TypeError): + model = MAE(pretrained=123, init_cfg=None) + + # pretrain=123, whose type is unsupported + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = MAE( + pretrained=123, init_cfg=dict(type='Pretrained', checkpoint=path)) + + # pretrain=123, whose type is unsupported + # init_cfg=123, whose type is unsupported + with pytest.raises(AssertionError): + model = MAE(pretrained=123, init_cfg=123) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_mit.py b/third-party/InterFormer/tests/test_models/test_backbones/test_mit.py new file mode 100644 index 0000000000000000000000000000000000000000..72f74fe209423daed07fcf3bd59d5979e43c43d1 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_mit.py @@ -0,0 +1,122 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import MixVisionTransformer +from mmseg.models.backbones.mit import (EfficientMultiheadAttention, MixFFN, + TransformerEncoderLayer) + + +def test_mit(): + with pytest.raises(TypeError): + # Pretrained represents pretrain url and must be str or None. + MixVisionTransformer(pretrained=123) + + # Test normal input + H, W = (224, 224) + temp = torch.randn((1, 3, H, W)) + model = MixVisionTransformer( + embed_dims=32, num_heads=[1, 2, 5, 8], out_indices=(0, 1, 2, 3)) + model.init_weights() + outs = model(temp) + assert outs[0].shape == (1, 32, H // 4, W // 4) + assert outs[1].shape == (1, 64, H // 8, W // 8) + assert outs[2].shape == (1, 160, H // 16, W // 16) + assert outs[3].shape == (1, 256, H // 32, W // 32) + + # Test non-squared input + H, W = (224, 256) + temp = torch.randn((1, 3, H, W)) + outs = model(temp) + assert outs[0].shape == (1, 32, H // 4, W // 4) + assert outs[1].shape == (1, 64, H // 8, W // 8) + assert outs[2].shape == (1, 160, H // 16, W // 16) + assert outs[3].shape == (1, 256, H // 32, W // 32) + + # Test MixFFN + FFN = MixFFN(64, 128) + hw_shape = (32, 32) + token_len = 32 * 32 + temp = torch.randn((1, token_len, 64)) + # Self identity + out = FFN(temp, hw_shape) + assert out.shape == (1, token_len, 64) + # Out identity + outs = FFN(temp, hw_shape, temp) + assert out.shape == (1, token_len, 64) + + # Test EfficientMHA + MHA = EfficientMultiheadAttention(64, 2) + hw_shape = (32, 32) + token_len = 32 * 32 + temp = torch.randn((1, token_len, 64)) + # Self identity + out = MHA(temp, hw_shape) + assert out.shape == (1, token_len, 64) + # Out identity + outs = MHA(temp, hw_shape, temp) + assert out.shape == (1, token_len, 64) + + # Test TransformerEncoderLayer with checkpoint forward + block = TransformerEncoderLayer( + embed_dims=64, num_heads=4, feedforward_channels=256, with_cp=True) + assert block.with_cp + x = torch.randn(1, 56 * 56, 64) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + +def test_mit_init(): + path = 'PATH_THAT_DO_NOT_EXIST' + # Test all combinations of pretrained and init_cfg + # pretrained=None, init_cfg=None + model = MixVisionTransformer(pretrained=None, init_cfg=None) + assert model.init_cfg is None + model.init_weights() + + # pretrained=None + # init_cfg loads pretrain from an non-existent file + model = MixVisionTransformer( + pretrained=None, init_cfg=dict(type='Pretrained', checkpoint=path)) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained=None + # init_cfg=123, whose type is unsupported + model = MixVisionTransformer(pretrained=None, init_cfg=123) + with pytest.raises(TypeError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg=None + model = MixVisionTransformer(pretrained=path, init_cfg=None) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + MixVisionTransformer( + pretrained=path, init_cfg=dict(type='Pretrained', checkpoint=path)) + with pytest.raises(AssertionError): + MixVisionTransformer(pretrained=path, init_cfg=123) + + # pretrain=123, whose type is unsupported + # init_cfg=None + with pytest.raises(TypeError): + MixVisionTransformer(pretrained=123, init_cfg=None) + + # pretrain=123, whose type is unsupported + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + MixVisionTransformer( + pretrained=123, init_cfg=dict(type='Pretrained', checkpoint=path)) + + # pretrain=123, whose type is unsupported + # init_cfg=123, whose type is unsupported + with pytest.raises(AssertionError): + MixVisionTransformer(pretrained=123, init_cfg=123) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_mobilenet_v3.py b/third-party/InterFormer/tests/test_models/test_backbones/test_mobilenet_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..769ee14bc2423ba82a46e7637fa1fa7004609be0 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_mobilenet_v3.py @@ -0,0 +1,67 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import MobileNetV3 + + +def test_mobilenet_v3(): + with pytest.raises(AssertionError): + # check invalid arch + MobileNetV3('big') + + with pytest.raises(AssertionError): + # check invalid reduction_factor + MobileNetV3(reduction_factor=0) + + with pytest.raises(ValueError): + # check invalid out_indices + MobileNetV3(out_indices=(0, 1, 15)) + + with pytest.raises(ValueError): + # check invalid frozen_stages + MobileNetV3(frozen_stages=15) + + with pytest.raises(TypeError): + # check invalid pretrained + model = MobileNetV3() + model.init_weights(pretrained=8) + + # Test MobileNetV3 with default settings + model = MobileNetV3() + model.init_weights() + model.train() + + imgs = torch.randn(2, 3, 56, 56) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == (2, 16, 28, 28) + assert feat[1].shape == (2, 16, 14, 14) + assert feat[2].shape == (2, 576, 7, 7) + + # Test MobileNetV3 with arch = 'large' + model = MobileNetV3(arch='large', out_indices=(1, 3, 16)) + model.init_weights() + model.train() + + imgs = torch.randn(2, 3, 56, 56) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == (2, 16, 28, 28) + assert feat[1].shape == (2, 24, 14, 14) + assert feat[2].shape == (2, 960, 7, 7) + + # Test MobileNetV3 with norm_eval True, with_cp True and frozen_stages=5 + model = MobileNetV3(norm_eval=True, with_cp=True, frozen_stages=5) + with pytest.raises(TypeError): + # check invalid pretrained + model.init_weights(pretrained=8) + model.init_weights() + model.train() + + imgs = torch.randn(2, 3, 56, 56) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == (2, 16, 28, 28) + assert feat[1].shape == (2, 16, 14, 14) + assert feat[2].shape == (2, 576, 7, 7) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_mscan.py b/third-party/InterFormer/tests/test_models/test_backbones/test_mscan.py new file mode 100644 index 0000000000000000000000000000000000000000..84dfb8e4504d5ca3be23ca0a16cc9db414025a1b --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_mscan.py @@ -0,0 +1,69 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.backbones import MSCAN +from mmseg.models.backbones.mscan import (MSCAAttention, MSCASpatialAttention, + OverlapPatchEmbed, StemConv) + + +def test_mscan_backbone(): + # Test MSCAN Standard Forward + model = MSCAN( + embed_dims=[8, 16, 32, 64], + norm_cfg=dict(type='BN', requires_grad=True)) + model.init_weights() + model.train() + batch_size = 2 + imgs = torch.randn(batch_size, 3, 64, 128) + feat = model(imgs) + + assert len(feat) == 4 + # output for segment Head + assert feat[0].shape == torch.Size([batch_size, 8, 16, 32]) + assert feat[1].shape == torch.Size([batch_size, 16, 8, 16]) + assert feat[2].shape == torch.Size([batch_size, 32, 4, 8]) + assert feat[3].shape == torch.Size([batch_size, 64, 2, 4]) + + # Test input with rare shape + batch_size = 2 + imgs = torch.randn(batch_size, 3, 95, 27) + feat = model(imgs) + assert len(feat) == 4 + + +def test_mscan_overlap_patch_embed_module(): + x_overlap_patch_embed = OverlapPatchEmbed( + norm_cfg=dict(type='BN', requires_grad=True)) + assert x_overlap_patch_embed.proj.in_channels == 3 + assert x_overlap_patch_embed.norm.weight.shape == torch.Size([768]) + x = torch.randn(2, 3, 16, 32) + x_out, H, W = x_overlap_patch_embed(x) + assert x_out.shape == torch.Size([2, 32, 768]) + + +def test_mscan_spatial_attention_module(): + x_spatial_attention = MSCASpatialAttention(8) + assert x_spatial_attention.proj_1.kernel_size == (1, 1) + assert x_spatial_attention.proj_2.stride == (1, 1) + x = torch.randn(2, 8, 16, 32) + x_out = x_spatial_attention(x) + assert x_out.shape == torch.Size([2, 8, 16, 32]) + + +def test_mscan_attention_module(): + x_attention = MSCAAttention(8) + assert x_attention.conv0.weight.shape[0] == 8 + assert x_attention.conv3.kernel_size == (1, 1) + x = torch.randn(2, 8, 16, 32) + x_out = x_attention(x) + assert x_out.shape == torch.Size([2, 8, 16, 32]) + + +def test_mscan_stem_module(): + x_stem = StemConv(8, 8, norm_cfg=dict(type='BN', requires_grad=True)) + assert x_stem.proj[0].weight.shape[0] == 4 + assert x_stem.proj[-1].weight.shape[0] == 8 + x = torch.randn(2, 8, 16, 32) + x_out, H, W = x_stem(x) + assert x_out.shape == torch.Size([2, 32, 8]) + assert (H, W) == (4, 8) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_pidnet.py b/third-party/InterFormer/tests/test_models/test_backbones/test_pidnet.py new file mode 100644 index 0000000000000000000000000000000000000000..208dfc7814ec9a81dae06a313c3ecfaa17042df1 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_pidnet.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import tempfile + +import torch +from mmengine.registry import init_default_scope + +from mmseg.registry import MODELS + +init_default_scope('mmseg') + + +def test_pidnet_backbone(): + # Test PIDNet Standard Forward + norm_cfg = dict(type='BN', requires_grad=True) + backbone_cfg = dict( + type='PIDNet', + in_channels=3, + channels=32, + ppm_channels=96, + num_stem_blocks=2, + num_branch_blocks=3, + align_corners=False, + norm_cfg=norm_cfg, + act_cfg=dict(type='ReLU', inplace=True)) + model = MODELS.build(backbone_cfg) + model.init_weights() + + # Test init weights + temp_file = tempfile.NamedTemporaryFile() + temp_file.close() + torch.save(model.state_dict(), temp_file.name) + backbone_cfg.update( + init_cfg=dict(type='Pretrained', checkpoint=temp_file.name)) + model = MODELS.build(backbone_cfg) + model.init_weights() + os.remove(temp_file.name) + + # Test eval mode + model.eval() + batch_size = 1 + imgs = torch.randn(batch_size, 3, 64, 128) + feats = model(imgs) + + assert type(feats) == torch.Tensor + assert feats.shape == torch.Size([batch_size, 128, 8, 16]) + + # Test train mode + model.train() + batch_size = 2 + imgs = torch.randn(batch_size, 3, 64, 128) + feats = model(imgs) + + assert len(feats) == 3 + # test output for P branch + assert feats[0].shape == torch.Size([batch_size, 64, 8, 16]) + # test output for I branch + assert feats[1].shape == torch.Size([batch_size, 128, 8, 16]) + # test output for D branch + assert feats[2].shape == torch.Size([batch_size, 64, 8, 16]) + + # Test pidnet-m + backbone_cfg.update(channels=64) + model = MODELS.build(backbone_cfg) + feats = model(imgs) + + assert len(feats) == 3 + # test output for P branch + assert feats[0].shape == torch.Size([batch_size, 128, 8, 16]) + # test output for I branch + assert feats[1].shape == torch.Size([batch_size, 256, 8, 16]) + # test output for D branch + assert feats[2].shape == torch.Size([batch_size, 128, 8, 16]) + + # Test pidnet-l + backbone_cfg.update( + channels=64, ppm_channesl=112, num_stem_blocks=3, num_branch_blocks=4) + model = MODELS.build(backbone_cfg) + feats = model(imgs) + + assert len(feats) == 3 + # test output for P branch + assert feats[0].shape == torch.Size([batch_size, 128, 8, 16]) + # test output for I branch + assert feats[1].shape == torch.Size([batch_size, 256, 8, 16]) + # test output for D branch + assert feats[2].shape == torch.Size([batch_size, 128, 8, 16]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_resnest.py b/third-party/InterFormer/tests/test_models/test_backbones/test_resnest.py new file mode 100644 index 0000000000000000000000000000000000000000..3013f34fcca8c6f052946a710c0007dc4b23570f --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_resnest.py @@ -0,0 +1,44 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import ResNeSt +from mmseg.models.backbones.resnest import Bottleneck as BottleneckS + + +def test_resnest_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + BottleneckS(64, 64, radix=2, reduction_factor=4, style='tensorflow') + + # Test ResNeSt Bottleneck structure + block = BottleneckS( + 64, 256, radix=2, reduction_factor=4, stride=2, style='pytorch') + assert block.avd_layer.stride == 2 + assert block.conv2.channels == 256 + + # Test ResNeSt Bottleneck forward + block = BottleneckS(64, 16, radix=2, reduction_factor=4) + x = torch.randn(2, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([2, 64, 56, 56]) + + +def test_resnest_backbone(): + with pytest.raises(KeyError): + # ResNeSt depth should be in [50, 101, 152, 200] + ResNeSt(depth=18) + + # Test ResNeSt with radix 2, reduction_factor 4 + model = ResNeSt( + depth=50, radix=2, reduction_factor=4, out_indices=(0, 1, 2, 3)) + model.init_weights() + model.train() + + imgs = torch.randn(2, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([2, 256, 56, 56]) + assert feat[1].shape == torch.Size([2, 512, 28, 28]) + assert feat[2].shape == torch.Size([2, 1024, 14, 14]) + assert feat[3].shape == torch.Size([2, 2048, 7, 7]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_resnet.py b/third-party/InterFormer/tests/test_models/test_backbones/test_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f24ba568dbdd766a79e961723cfcfec64c6f41 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_resnet.py @@ -0,0 +1,575 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmcv.ops import DeformConv2dPack +from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm +from torch.nn.modules import AvgPool2d, GroupNorm + +from mmseg.models.backbones import ResNet, ResNetV1d +from mmseg.models.backbones.resnet import BasicBlock, Bottleneck +from mmseg.models.utils import ResLayer +from .utils import all_zeros, check_norm_state, is_block, is_norm + + +def test_resnet_basic_block(): + with pytest.raises(AssertionError): + # Not implemented yet. + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + BasicBlock(64, 64, dcn=dcn) + + with pytest.raises(AssertionError): + # Not implemented yet. + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + BasicBlock(64, 64, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + BasicBlock(64, 64, plugins=plugins) + + # Test BasicBlock with checkpoint forward + block = BasicBlock(16, 16, with_cp=True) + assert block.with_cp + x = torch.randn(1, 16, 28, 28) + x_out = block(x) + assert x_out.shape == torch.Size([1, 16, 28, 28]) + + # test BasicBlock structure and forward + block = BasicBlock(32, 32) + assert block.conv1.in_channels == 32 + assert block.conv1.out_channels == 32 + assert block.conv1.kernel_size == (3, 3) + assert block.conv2.in_channels == 32 + assert block.conv2.out_channels == 32 + assert block.conv2.kernel_size == (3, 3) + x = torch.randn(1, 32, 28, 28) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 28, 28]) + + +def test_resnet_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + Bottleneck(64, 64, style='tensorflow') + + with pytest.raises(AssertionError): + # Allowed positions are 'after_conv1', 'after_conv2', 'after_conv3' + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv4') + ] + Bottleneck(64, 16, plugins=plugins) + + with pytest.raises(AssertionError): + # Need to specify different postfix to avoid duplicate plugin name + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + Bottleneck(64, 16, plugins=plugins) + + with pytest.raises(KeyError): + # Plugin type is not supported + plugins = [dict(cfg=dict(type='WrongPlugin'), position='after_conv3')] + Bottleneck(64, 16, plugins=plugins) + + # Test Bottleneck with checkpoint forward + block = Bottleneck(64, 16, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck style + block = Bottleneck(64, 64, stride=2, style='pytorch') + assert block.conv1.stride == (1, 1) + assert block.conv2.stride == (2, 2) + block = Bottleneck(64, 64, stride=2, style='caffe') + assert block.conv1.stride == (2, 2) + assert block.conv2.stride == (1, 1) + + # Test Bottleneck DCN + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + with pytest.raises(AssertionError): + Bottleneck(64, 64, dcn=dcn, conv_cfg=dict(type='Conv')) + block = Bottleneck(64, 64, dcn=dcn) + assert isinstance(block.conv2, DeformConv2dPack) + + # Test Bottleneck forward + block = Bottleneck(64, 16) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2, 1 NonLocal2d + # after conv2, 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2'), + dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + assert block.nonlocal_block.in_channels == 16 + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv2, 2 ContextBlock after + # conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), + position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=3), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.context_block1.in_channels == 16 + assert block.context_block2.in_channels == 64 + assert block.context_block3.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnet_res_layer(): + # Test ResLayer of 3 Bottleneck w\o downsample + layer = ResLayer(Bottleneck, 64, 16, 3) + assert len(layer) == 3 + assert layer[0].conv1.in_channels == 64 + assert layer[0].conv1.out_channels == 16 + for i in range(1, len(layer)): + assert layer[i].conv1.in_channels == 64 + assert layer[i].conv1.out_channels == 16 + for i in range(len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test ResLayer of 3 Bottleneck with downsample + layer = ResLayer(Bottleneck, 64, 64, 3) + assert layer[0].downsample[0].out_channels == 256 + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 56, 56]) + + # Test ResLayer of 3 Bottleneck with stride=2 + layer = ResLayer(Bottleneck, 64, 64, 3, stride=2) + assert layer[0].downsample[0].out_channels == 256 + assert layer[0].downsample[0].stride == (2, 2) + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 28, 28]) + + # Test ResLayer of 3 Bottleneck with stride=2 and average downsample + layer = ResLayer(Bottleneck, 64, 64, 3, stride=2, avg_down=True) + assert isinstance(layer[0].downsample[0], AvgPool2d) + assert layer[0].downsample[1].out_channels == 256 + assert layer[0].downsample[1].stride == (1, 1) + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 28, 28]) + + # Test ResLayer of 3 Bottleneck with dilation=2 + layer = ResLayer(Bottleneck, 64, 16, 3, dilation=2) + for i in range(len(layer)): + assert layer[i].conv2.dilation == (2, 2) + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test ResLayer of 3 Bottleneck with dilation=2, contract_dilation=True + layer = ResLayer(Bottleneck, 64, 16, 3, dilation=2, contract_dilation=True) + assert layer[0].conv2.dilation == (1, 1) + for i in range(1, len(layer)): + assert layer[i].conv2.dilation == (2, 2) + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test ResLayer of 3 Bottleneck with dilation=2, multi_grid + layer = ResLayer(Bottleneck, 64, 16, 3, dilation=2, multi_grid=(1, 2, 4)) + assert layer[0].conv2.dilation == (1, 1) + assert layer[1].conv2.dilation == (2, 2) + assert layer[2].conv2.dilation == (4, 4) + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnet_backbone(): + """Test resnet backbone.""" + with pytest.raises(KeyError): + # ResNet depth should be in [18, 34, 50, 101, 152] + ResNet(20) + + with pytest.raises(AssertionError): + # In ResNet: 1 <= num_stages <= 4 + ResNet(50, num_stages=0) + + with pytest.raises(AssertionError): + # len(stage_with_dcn) == num_stages + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + ResNet(50, dcn=dcn, stage_with_dcn=(True, )) + + with pytest.raises(AssertionError): + # len(stage_with_plugin) == num_stages + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + stages=(False, True, True), + position='after_conv3') + ] + ResNet(50, plugins=plugins) + + with pytest.raises(AssertionError): + # In ResNet: 1 <= num_stages <= 4 + ResNet(18, num_stages=5) + + with pytest.raises(AssertionError): + # len(strides) == len(dilations) == num_stages + ResNet(18, strides=(1, ), dilations=(1, 1), num_stages=3) + + with pytest.raises(TypeError): + # pretrained must be a string path + model = ResNet(18, pretrained=0) + model.init_weights() + + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + ResNet(50, style='tensorflow') + + # Test ResNet18 norm_eval=True + model = ResNet(18, norm_eval=True) + model.init_weights() + model.train() + assert check_norm_state(model.modules(), False) + + # Test ResNet18 with torchvision pretrained weight + model = ResNet( + depth=18, norm_eval=True, pretrained='torchvision://resnet18') + model.init_weights() + model.train() + assert check_norm_state(model.modules(), False) + + # Test ResNet18 with first stage frozen + frozen_stages = 1 + model = ResNet(18, frozen_stages=frozen_stages) + model.init_weights() + model.train() + assert model.norm1.training is False + for layer in [model.conv1, model.norm1]: + for param in layer.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'layer{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test ResNet18V1d with first stage frozen + model = ResNetV1d(depth=18, frozen_stages=frozen_stages) + assert len(model.stem) == 9 + model.init_weights() + model.train() + check_norm_state(model.stem, False) + for param in model.stem.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'layer{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test ResNet18 forward + model = ResNet(18) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 56, 56]) + assert feat[1].shape == torch.Size([1, 128, 28, 28]) + assert feat[2].shape == torch.Size([1, 256, 14, 14]) + assert feat[3].shape == torch.Size([1, 512, 7, 7]) + + # Test ResNet18 with BatchNorm forward + model = ResNet(18) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, _BatchNorm) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 56, 56]) + assert feat[1].shape == torch.Size([1, 128, 28, 28]) + assert feat[2].shape == torch.Size([1, 256, 14, 14]) + assert feat[3].shape == torch.Size([1, 512, 7, 7]) + + # Test ResNet18 with layers 1, 2, 3 out forward + model = ResNet(18, out_indices=(0, 1, 2)) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 112, 112) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == torch.Size([1, 64, 28, 28]) + assert feat[1].shape == torch.Size([1, 128, 14, 14]) + assert feat[2].shape == torch.Size([1, 256, 7, 7]) + + # Test ResNet18 with checkpoint forward + model = ResNet(18, with_cp=True) + for m in model.modules(): + if is_block(m): + assert m.with_cp + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 56, 56]) + assert feat[1].shape == torch.Size([1, 128, 28, 28]) + assert feat[2].shape == torch.Size([1, 256, 14, 14]) + assert feat[3].shape == torch.Size([1, 512, 7, 7]) + + # Test ResNet18 with checkpoint forward + model = ResNet(18, with_cp=True) + for m in model.modules(): + if is_block(m): + assert m.with_cp + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 56, 56]) + assert feat[1].shape == torch.Size([1, 128, 28, 28]) + assert feat[2].shape == torch.Size([1, 256, 14, 14]) + assert feat[3].shape == torch.Size([1, 512, 7, 7]) + + # Test ResNet18 with GroupNorm forward + model = ResNet( + 18, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, GroupNorm) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 56, 56]) + assert feat[1].shape == torch.Size([1, 128, 28, 28]) + assert feat[2].shape == torch.Size([1, 256, 14, 14]) + assert feat[3].shape == torch.Size([1, 512, 7, 7]) + + # Test ResNet50 with 1 GeneralizedAttention after conv2, 1 NonLocal2d + # after conv2, 1 ContextBlock after conv3 in layers 2, 3, 4 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + stages=(False, True, True, True), + position='after_conv2'), + dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + stages=(False, True, True, False), + position='after_conv3') + ] + model = ResNet(50, plugins=plugins) + for m in model.layer1.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'gen_attention_block') + assert m.nonlocal_block.in_channels == 64 + for m in model.layer2.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 128 + assert m.gen_attention_block.in_channels == 128 + assert m.context_block.in_channels == 512 + + for m in model.layer3.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 256 + assert m.gen_attention_block.in_channels == 256 + assert m.context_block.in_channels == 1024 + + for m in model.layer4.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 512 + assert m.gen_attention_block.in_channels == 512 + assert not hasattr(m, 'context_block') + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 256, 56, 56]) + assert feat[1].shape == torch.Size([1, 512, 28, 28]) + assert feat[2].shape == torch.Size([1, 1024, 14, 14]) + assert feat[3].shape == torch.Size([1, 2048, 7, 7]) + + # Test ResNet50 with 1 ContextBlock after conv2, 1 ContextBlock after + # conv3 in layers 2, 3, 4 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), + stages=(False, True, True, False), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), + stages=(False, True, True, False), + position='after_conv3') + ] + + model = ResNet(50, plugins=plugins) + for m in model.layer1.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'context_block1') + assert not hasattr(m, 'context_block2') + for m in model.layer2.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert m.context_block1.in_channels == 512 + assert m.context_block2.in_channels == 512 + + for m in model.layer3.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert m.context_block1.in_channels == 1024 + assert m.context_block2.in_channels == 1024 + + for m in model.layer4.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'context_block1') + assert not hasattr(m, 'context_block2') + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 256, 56, 56]) + assert feat[1].shape == torch.Size([1, 512, 28, 28]) + assert feat[2].shape == torch.Size([1, 1024, 14, 14]) + assert feat[3].shape == torch.Size([1, 2048, 7, 7]) + + # Test ResNet18 zero initialization of residual + model = ResNet(18, zero_init_residual=True) + model.init_weights() + for m in model.modules(): + if isinstance(m, Bottleneck): + assert all_zeros(m.norm3) + elif isinstance(m, BasicBlock): + assert all_zeros(m.norm2) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 56, 56]) + assert feat[1].shape == torch.Size([1, 128, 28, 28]) + assert feat[2].shape == torch.Size([1, 256, 14, 14]) + assert feat[3].shape == torch.Size([1, 512, 7, 7]) + + # Test ResNetV1d forward + model = ResNetV1d(depth=18) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 56, 56]) + assert feat[1].shape == torch.Size([1, 128, 28, 28]) + assert feat[2].shape == torch.Size([1, 256, 14, 14]) + assert feat[3].shape == torch.Size([1, 512, 7, 7]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_resnext.py b/third-party/InterFormer/tests/test_models/test_backbones/test_resnext.py new file mode 100644 index 0000000000000000000000000000000000000000..2aecaf0d3d4c22d79654df26f088bdcbb5ec376e --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_resnext.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import ResNeXt +from mmseg.models.backbones.resnext import Bottleneck as BottleneckX +from .utils import is_block + + +def test_renext_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + BottleneckX(64, 64, groups=32, base_width=4, style='tensorflow') + + # Test ResNeXt Bottleneck structure + block = BottleneckX( + 64, 64, groups=32, base_width=4, stride=2, style='pytorch') + assert block.conv2.stride == (2, 2) + assert block.conv2.groups == 32 + assert block.conv2.out_channels == 128 + + # Test ResNeXt Bottleneck with DCN + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + with pytest.raises(AssertionError): + # conv_cfg must be None if dcn is not None + BottleneckX( + 64, + 64, + groups=32, + base_width=4, + dcn=dcn, + conv_cfg=dict(type='Conv')) + BottleneckX(64, 64, dcn=dcn) + + # Test ResNeXt Bottleneck forward + block = BottleneckX(64, 16, groups=32, base_width=4) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnext_backbone(): + with pytest.raises(KeyError): + # ResNeXt depth should be in [50, 101, 152] + ResNeXt(depth=18) + + # Test ResNeXt with group 32, base_width 4 + model = ResNeXt(depth=50, groups=32, base_width=4) + print(model) + for m in model.modules(): + if is_block(m): + assert m.conv2.groups == 32 + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 256, 56, 56]) + assert feat[1].shape == torch.Size([1, 512, 28, 28]) + assert feat[2].shape == torch.Size([1, 1024, 14, 14]) + assert feat[3].shape == torch.Size([1, 2048, 7, 7]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_stdc.py b/third-party/InterFormer/tests/test_models/test_backbones/test_stdc.py new file mode 100644 index 0000000000000000000000000000000000000000..1e3862b0b387e6f84edb4f6edca5e8d0db36dbdc --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_stdc.py @@ -0,0 +1,131 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import STDCContextPathNet +from mmseg.models.backbones.stdc import (AttentionRefinementModule, + FeatureFusionModule, STDCModule, + STDCNet) + + +def test_stdc_context_path_net(): + # Test STDCContextPathNet Standard Forward + model = STDCContextPathNet( + backbone_cfg=dict( + type='STDCNet', + stdc_type='STDCNet1', + in_channels=3, + channels=(32, 64, 256, 512, 1024), + bottleneck_type='cat', + num_convs=4, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='ReLU'), + with_final_conv=True), + last_in_channels=(1024, 512), + out_channels=128, + ffm_cfg=dict(in_channels=384, out_channels=256, scale_factor=4)) + model.init_weights() + model.train() + batch_size = 2 + imgs = torch.randn(batch_size, 3, 256, 512) + feat = model(imgs) + + assert len(feat) == 4 + # output for segment Head + assert feat[0].shape == torch.Size([batch_size, 256, 32, 64]) + # for auxiliary head 1 + assert feat[1].shape == torch.Size([batch_size, 128, 16, 32]) + # for auxiliary head 2 + assert feat[2].shape == torch.Size([batch_size, 128, 32, 64]) + # for auxiliary head 3 + assert feat[3].shape == torch.Size([batch_size, 256, 32, 64]) + + # Test input with rare shape + batch_size = 2 + imgs = torch.randn(batch_size, 3, 527, 279) + model = STDCContextPathNet( + backbone_cfg=dict( + type='STDCNet', + stdc_type='STDCNet1', + in_channels=3, + channels=(32, 64, 256, 512, 1024), + bottleneck_type='add', + num_convs=4, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='ReLU'), + with_final_conv=False), + last_in_channels=(1024, 512), + out_channels=128, + ffm_cfg=dict(in_channels=384, out_channels=256, scale_factor=4)) + model.init_weights() + model.train() + feat = model(imgs) + assert len(feat) == 4 + + +def test_stdcnet(): + with pytest.raises(AssertionError): + # STDC backbone constraints. + STDCNet( + stdc_type='STDCNet3', + in_channels=3, + channels=(32, 64, 256, 512, 1024), + bottleneck_type='cat', + num_convs=4, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='ReLU'), + with_final_conv=False) + + with pytest.raises(AssertionError): + # STDC bottleneck type constraints. + STDCNet( + stdc_type='STDCNet1', + in_channels=3, + channels=(32, 64, 256, 512, 1024), + bottleneck_type='dog', + num_convs=4, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='ReLU'), + with_final_conv=False) + + with pytest.raises(AssertionError): + # STDC channels length constraints. + STDCNet( + stdc_type='STDCNet1', + in_channels=3, + channels=(16, 32, 64, 256, 512, 1024), + bottleneck_type='cat', + num_convs=4, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='ReLU'), + with_final_conv=False) + + +def test_feature_fusion_module(): + x_ffm = FeatureFusionModule(in_channels=64, out_channels=32) + assert x_ffm.conv0.in_channels == 64 + assert x_ffm.attention[1].in_channels == 32 + assert x_ffm.attention[2].in_channels == 8 + assert x_ffm.attention[2].out_channels == 32 + x1 = torch.randn(2, 32, 32, 64) + x2 = torch.randn(2, 32, 32, 64) + x_out = x_ffm(x1, x2) + assert x_out.shape == torch.Size([2, 32, 32, 64]) + + +def test_attention_refinement_module(): + x_arm = AttentionRefinementModule(128, 32) + assert x_arm.conv_layer.in_channels == 128 + assert x_arm.atten_conv_layer[1].conv.out_channels == 32 + x = torch.randn(2, 128, 32, 64) + x_out = x_arm(x) + assert x_out.shape == torch.Size([2, 32, 32, 64]) + + +def test_stdc_module(): + x_stdc = STDCModule(in_channels=32, out_channels=32, stride=4) + assert x_stdc.layers[0].conv.in_channels == 32 + assert x_stdc.layers[3].conv.out_channels == 4 + x = torch.randn(2, 32, 32, 64) + x_out = x_stdc(x) + assert x_out.shape == torch.Size([2, 32, 32, 64]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_swin.py b/third-party/InterFormer/tests/test_models/test_backbones/test_swin.py new file mode 100644 index 0000000000000000000000000000000000000000..8d14d47ab584b3eead28a6d777dfabbd59b33ba8 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_swin.py @@ -0,0 +1,100 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones.swin import SwinBlock, SwinTransformer + + +def test_swin_block(): + # test SwinBlock structure and forward + block = SwinBlock(embed_dims=32, num_heads=4, feedforward_channels=128) + assert block.ffn.embed_dims == 32 + assert block.attn.w_msa.num_heads == 4 + assert block.ffn.feedforward_channels == 128 + x = torch.randn(1, 56 * 56, 32) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 32]) + + # Test BasicBlock with checkpoint forward + block = SwinBlock( + embed_dims=64, num_heads=4, feedforward_channels=256, with_cp=True) + assert block.with_cp + x = torch.randn(1, 56 * 56, 64) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + +def test_swin_transformer(): + """Test Swin Transformer backbone.""" + + with pytest.raises(TypeError): + # Pretrained arg must be str or None. + SwinTransformer(pretrained=123) + + with pytest.raises(AssertionError): + # Because swin uses non-overlapping patch embed, so the stride of patch + # embed must be equal to patch size. + SwinTransformer(strides=(2, 2, 2, 2), patch_size=4) + + # test pretrained image size + with pytest.raises(AssertionError): + SwinTransformer(pretrain_img_size=(112, 112, 112)) + + # Test absolute position embedding + temp = torch.randn((1, 3, 112, 112)) + model = SwinTransformer(pretrain_img_size=112, use_abs_pos_embed=True) + model.init_weights() + model(temp) + + # Test patch norm + model = SwinTransformer(patch_norm=False) + model(temp) + + # Test normal inference + temp = torch.randn((1, 3, 256, 256)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 64, 64) + assert outs[1].shape == (1, 192, 32, 32) + assert outs[2].shape == (1, 384, 16, 16) + assert outs[3].shape == (1, 768, 8, 8) + + # Test abnormal inference size + temp = torch.randn((1, 3, 255, 255)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 64, 64) + assert outs[1].shape == (1, 192, 32, 32) + assert outs[2].shape == (1, 384, 16, 16) + assert outs[3].shape == (1, 768, 8, 8) + + # Test abnormal inference size + temp = torch.randn((1, 3, 112, 137)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 28, 35) + assert outs[1].shape == (1, 192, 14, 18) + assert outs[2].shape == (1, 384, 7, 9) + assert outs[3].shape == (1, 768, 4, 5) + + # Test frozen + model = SwinTransformer(frozen_stages=4) + model.train() + for p in model.parameters(): + assert not p.requires_grad + + # Test absolute position embedding frozen + model = SwinTransformer(frozen_stages=4, use_abs_pos_embed=True) + model.train() + for p in model.parameters(): + assert not p.requires_grad + + # Test Swin with checkpoint forward + temp = torch.randn((1, 3, 56, 56)) + model = SwinTransformer(with_cp=True) + for m in model.modules(): + if isinstance(m, SwinBlock): + assert m.with_cp + model.init_weights() + model.train() + model(temp) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_timm_backbone.py b/third-party/InterFormer/tests/test_models/test_backbones/test_timm_backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a50cf5261d40b66b92c6a18d2f1ac6e4f8b5f9 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_timm_backbone.py @@ -0,0 +1,133 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones import TIMMBackbone +from .utils import check_norm_state + + +def test_timm_backbone(): + with pytest.raises(TypeError): + # pretrained must be a string path + model = TIMMBackbone() + model.init_weights(pretrained=0) + + # Test different norm_layer, can be: 'SyncBN', 'BN2d', 'GN', 'LN', 'IN' + # Test resnet18 from timm, norm_layer='BN2d' + model = TIMMBackbone( + model_name='resnet18', + features_only=True, + pretrained=False, + output_stride=32, + norm_layer='BN2d') + + # Test resnet18 from timm, norm_layer='SyncBN' + model = TIMMBackbone( + model_name='resnet18', + features_only=True, + pretrained=False, + output_stride=32, + norm_layer='SyncBN2d') + + # Test resnet18 from timm, features_only=True, output_stride=32 + model = TIMMBackbone( + model_name='resnet18', + features_only=True, + pretrained=False, + output_stride=32) + model.init_weights() + model.train() + assert check_norm_state(model.modules(), True) + + imgs = torch.randn(1, 3, 224, 224) + feats = model(imgs) + feats = [feat.shape for feat in feats] + assert len(feats) == 5 + assert feats[0] == torch.Size((1, 64, 112, 112)) + assert feats[1] == torch.Size((1, 64, 56, 56)) + assert feats[2] == torch.Size((1, 128, 28, 28)) + assert feats[3] == torch.Size((1, 256, 14, 14)) + assert feats[4] == torch.Size((1, 512, 7, 7)) + + # Test resnet18 from timm, features_only=True, output_stride=16 + model = TIMMBackbone( + model_name='resnet18', + features_only=True, + pretrained=False, + output_stride=16) + imgs = torch.randn(1, 3, 224, 224) + feats = model(imgs) + feats = [feat.shape for feat in feats] + assert len(feats) == 5 + assert feats[0] == torch.Size((1, 64, 112, 112)) + assert feats[1] == torch.Size((1, 64, 56, 56)) + assert feats[2] == torch.Size((1, 128, 28, 28)) + assert feats[3] == torch.Size((1, 256, 14, 14)) + assert feats[4] == torch.Size((1, 512, 14, 14)) + + # Test resnet18 from timm, features_only=True, output_stride=8 + model = TIMMBackbone( + model_name='resnet18', + features_only=True, + pretrained=False, + output_stride=8) + imgs = torch.randn(1, 3, 224, 224) + feats = model(imgs) + feats = [feat.shape for feat in feats] + assert len(feats) == 5 + assert feats[0] == torch.Size((1, 64, 112, 112)) + assert feats[1] == torch.Size((1, 64, 56, 56)) + assert feats[2] == torch.Size((1, 128, 28, 28)) + assert feats[3] == torch.Size((1, 256, 28, 28)) + assert feats[4] == torch.Size((1, 512, 28, 28)) + + # Test efficientnet_b1 with pretrained weights + model = TIMMBackbone(model_name='efficientnet_b1', pretrained=True) + + # Test resnetv2_50x1_bitm from timm, features_only=True, output_stride=8 + model = TIMMBackbone( + model_name='resnetv2_50x1_bitm', + features_only=True, + pretrained=False, + output_stride=8) + imgs = torch.randn(1, 3, 8, 8) + feats = model(imgs) + feats = [feat.shape for feat in feats] + assert len(feats) == 5 + assert feats[0] == torch.Size((1, 64, 4, 4)) + assert feats[1] == torch.Size((1, 256, 2, 2)) + assert feats[2] == torch.Size((1, 512, 1, 1)) + assert feats[3] == torch.Size((1, 1024, 1, 1)) + assert feats[4] == torch.Size((1, 2048, 1, 1)) + + # Test resnetv2_50x3_bitm from timm, features_only=True, output_stride=8 + model = TIMMBackbone( + model_name='resnetv2_50x3_bitm', + features_only=True, + pretrained=False, + output_stride=8) + imgs = torch.randn(1, 3, 8, 8) + feats = model(imgs) + feats = [feat.shape for feat in feats] + assert len(feats) == 5 + assert feats[0] == torch.Size((1, 192, 4, 4)) + assert feats[1] == torch.Size((1, 768, 2, 2)) + assert feats[2] == torch.Size((1, 1536, 1, 1)) + assert feats[3] == torch.Size((1, 3072, 1, 1)) + assert feats[4] == torch.Size((1, 6144, 1, 1)) + + # Test resnetv2_101x1_bitm from timm, features_only=True, output_stride=8 + model = TIMMBackbone( + model_name='resnetv2_101x1_bitm', + features_only=True, + pretrained=False, + output_stride=8) + imgs = torch.randn(1, 3, 8, 8) + feats = model(imgs) + feats = [feat.shape for feat in feats] + assert len(feats) == 5 + assert feats[0] == torch.Size((1, 64, 4, 4)) + assert feats[1] == torch.Size((1, 256, 2, 2)) + assert feats[2] == torch.Size((1, 512, 1, 1)) + assert feats[3] == torch.Size((1, 1024, 1, 1)) + assert feats[4] == torch.Size((1, 2048, 1, 1)) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_twins.py b/third-party/InterFormer/tests/test_models/test_backbones/test_twins.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3eaf9f45bb1097c5c90ec450d17638b68f5624 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_twins.py @@ -0,0 +1,171 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones.twins import (PCPVT, SVT, + ConditionalPositionEncoding, + LocallyGroupedSelfAttention) + + +def test_pcpvt(): + # Test normal input + H, W = (224, 224) + temp = torch.randn((1, 3, H, W)) + model = PCPVT( + embed_dims=[32, 64, 160, 256], + num_heads=[1, 2, 5, 8], + mlp_ratios=[8, 8, 4, 4], + qkv_bias=True, + depths=[3, 4, 6, 3], + sr_ratios=[8, 4, 2, 1], + norm_after_stage=False) + model.init_weights() + outs = model(temp) + assert outs[0].shape == (1, 32, H // 4, W // 4) + assert outs[1].shape == (1, 64, H // 8, W // 8) + assert outs[2].shape == (1, 160, H // 16, W // 16) + assert outs[3].shape == (1, 256, H // 32, W // 32) + + +def test_svt(): + # Test normal input + H, W = (224, 224) + temp = torch.randn((1, 3, H, W)) + model = SVT( + embed_dims=[32, 64, 128], + num_heads=[1, 2, 4], + mlp_ratios=[4, 4, 4], + qkv_bias=False, + depths=[4, 4, 4], + windiow_sizes=[7, 7, 7], + norm_after_stage=True) + + model.init_weights() + outs = model(temp) + assert outs[0].shape == (1, 32, H // 4, W // 4) + assert outs[1].shape == (1, 64, H // 8, W // 8) + assert outs[2].shape == (1, 128, H // 16, W // 16) + + +def test_svt_init(): + path = 'PATH_THAT_DO_NOT_EXIST' + # Test all combinations of pretrained and init_cfg + # pretrained=None, init_cfg=None + model = SVT(pretrained=None, init_cfg=None) + assert model.init_cfg is None + model.init_weights() + + # pretrained=None + # init_cfg loads pretrain from an non-existent file + model = SVT( + pretrained=None, init_cfg=dict(type='Pretrained', checkpoint=path)) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained=None + # init_cfg=123, whose type is unsupported + model = SVT(pretrained=None, init_cfg=123) + with pytest.raises(TypeError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg=None + model = SVT(pretrained=path, init_cfg=None) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = SVT( + pretrained=path, init_cfg=dict(type='Pretrained', checkpoint=path)) + with pytest.raises(AssertionError): + model = SVT(pretrained=path, init_cfg=123) + + # pretrain=123, whose type is unsupported + # init_cfg=None + with pytest.raises(TypeError): + model = SVT(pretrained=123, init_cfg=None) + + # pretrain=123, whose type is unsupported + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = SVT( + pretrained=123, init_cfg=dict(type='Pretrained', checkpoint=path)) + + # pretrain=123, whose type is unsupported + # init_cfg=123, whose type is unsupported + with pytest.raises(AssertionError): + model = SVT(pretrained=123, init_cfg=123) + + +def test_pcpvt_init(): + path = 'PATH_THAT_DO_NOT_EXIST' + # Test all combinations of pretrained and init_cfg + # pretrained=None, init_cfg=None + model = PCPVT(pretrained=None, init_cfg=None) + assert model.init_cfg is None + model.init_weights() + + # pretrained=None + # init_cfg loads pretrain from an non-existent file + model = PCPVT( + pretrained=None, init_cfg=dict(type='Pretrained', checkpoint=path)) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained=None + # init_cfg=123, whose type is unsupported + model = PCPVT(pretrained=None, init_cfg=123) + with pytest.raises(TypeError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg=None + model = PCPVT(pretrained=path, init_cfg=None) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = PCPVT( + pretrained=path, init_cfg=dict(type='Pretrained', checkpoint=path)) + with pytest.raises(AssertionError): + model = PCPVT(pretrained=path, init_cfg=123) + + # pretrain=123, whose type is unsupported + # init_cfg=None + with pytest.raises(TypeError): + model = PCPVT(pretrained=123, init_cfg=None) + + # pretrain=123, whose type is unsupported + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = PCPVT( + pretrained=123, init_cfg=dict(type='Pretrained', checkpoint=path)) + + # pretrain=123, whose type is unsupported + # init_cfg=123, whose type is unsupported + with pytest.raises(AssertionError): + model = PCPVT(pretrained=123, init_cfg=123) + + +def test_locallygrouped_self_attention_module(): + LSA = LocallyGroupedSelfAttention(embed_dims=32, window_size=3) + outs = LSA(torch.randn(1, 3136, 32), (56, 56)) + assert outs.shape == torch.Size([1, 3136, 32]) + + +def test_conditional_position_encoding_module(): + CPE = ConditionalPositionEncoding(in_channels=32, embed_dims=32, stride=2) + outs = CPE(torch.randn(1, 3136, 32), (56, 56)) + assert outs.shape == torch.Size([1, 784, 32]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_unet.py b/third-party/InterFormer/tests/test_models/test_backbones/test_unet.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3faf68cc1717dadebbab4e8a64dc1f5fa6beba --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_unet.py @@ -0,0 +1,825 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmcv.cnn import ConvModule +from mmengine.registry import init_default_scope + +from mmseg.models.backbones.unet import (BasicConvBlock, DeconvModule, + InterpConv, UNet, UpConvBlock) +from mmseg.models.utils import Upsample +from .utils import check_norm_state + +init_default_scope('mmseg') + + +def test_unet_basic_conv_block(): + with pytest.raises(AssertionError): + # Not implemented yet. + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + BasicConvBlock(64, 64, dcn=dcn) + + with pytest.raises(AssertionError): + # Not implemented yet. + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + BasicConvBlock(64, 64, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + BasicConvBlock(64, 64, plugins=plugins) + + # test BasicConvBlock with checkpoint forward + block = BasicConvBlock(16, 16, with_cp=True) + assert block.with_cp + x = torch.randn(1, 16, 64, 64, requires_grad=True) + x_out = block(x) + assert x_out.shape == torch.Size([1, 16, 64, 64]) + + block = BasicConvBlock(16, 16, with_cp=False) + assert not block.with_cp + x = torch.randn(1, 16, 64, 64) + x_out = block(x) + assert x_out.shape == torch.Size([1, 16, 64, 64]) + + # test BasicConvBlock with stride convolution to downsample + block = BasicConvBlock(16, 16, stride=2) + x = torch.randn(1, 16, 64, 64) + x_out = block(x) + assert x_out.shape == torch.Size([1, 16, 32, 32]) + + # test BasicConvBlock structure and forward + block = BasicConvBlock(16, 64, num_convs=3, dilation=3) + assert block.convs[0].conv.in_channels == 16 + assert block.convs[0].conv.out_channels == 64 + assert block.convs[0].conv.kernel_size == (3, 3) + assert block.convs[0].conv.dilation == (1, 1) + assert block.convs[0].conv.padding == (1, 1) + + assert block.convs[1].conv.in_channels == 64 + assert block.convs[1].conv.out_channels == 64 + assert block.convs[1].conv.kernel_size == (3, 3) + assert block.convs[1].conv.dilation == (3, 3) + assert block.convs[1].conv.padding == (3, 3) + + assert block.convs[2].conv.in_channels == 64 + assert block.convs[2].conv.out_channels == 64 + assert block.convs[2].conv.kernel_size == (3, 3) + assert block.convs[2].conv.dilation == (3, 3) + assert block.convs[2].conv.padding == (3, 3) + + +def test_deconv_module(): + with pytest.raises(AssertionError): + # kernel_size should be greater than or equal to scale_factor and + # (kernel_size - scale_factor) should be even numbers + DeconvModule(64, 32, kernel_size=1, scale_factor=2) + + with pytest.raises(AssertionError): + # kernel_size should be greater than or equal to scale_factor and + # (kernel_size - scale_factor) should be even numbers + DeconvModule(64, 32, kernel_size=3, scale_factor=2) + + with pytest.raises(AssertionError): + # kernel_size should be greater than or equal to scale_factor and + # (kernel_size - scale_factor) should be even numbers + DeconvModule(64, 32, kernel_size=5, scale_factor=4) + + # test DeconvModule with checkpoint forward and upsample 2X. + block = DeconvModule(64, 32, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 128, 128, requires_grad=True) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + block = DeconvModule(64, 32, with_cp=False) + assert not block.with_cp + x = torch.randn(1, 64, 128, 128) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test DeconvModule with different kernel size for upsample 2X. + x = torch.randn(1, 64, 64, 64) + block = DeconvModule(64, 32, kernel_size=2, scale_factor=2) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 128, 128]) + + block = DeconvModule(64, 32, kernel_size=6, scale_factor=2) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 128, 128]) + + # test DeconvModule with different kernel size for upsample 4X. + x = torch.randn(1, 64, 64, 64) + block = DeconvModule(64, 32, kernel_size=4, scale_factor=4) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + block = DeconvModule(64, 32, kernel_size=6, scale_factor=4) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + +def test_interp_conv(): + # test InterpConv with checkpoint forward and upsample 2X. + block = InterpConv(64, 32, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 128, 128, requires_grad=True) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + block = InterpConv(64, 32, with_cp=False) + assert not block.with_cp + x = torch.randn(1, 64, 128, 128) + x_out = block(x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test InterpConv with conv_first=False for upsample 2X. + block = InterpConv(64, 32, conv_first=False) + x = torch.randn(1, 64, 128, 128) + x_out = block(x) + assert isinstance(block.interp_upsample[0], Upsample) + assert isinstance(block.interp_upsample[1], ConvModule) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test InterpConv with conv_first=True for upsample 2X. + block = InterpConv(64, 32, conv_first=True) + x = torch.randn(1, 64, 128, 128) + x_out = block(x) + assert isinstance(block.interp_upsample[0], ConvModule) + assert isinstance(block.interp_upsample[1], Upsample) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test InterpConv with bilinear upsample for upsample 2X. + block = InterpConv( + 64, + 32, + conv_first=False, + upsample_cfg=dict( + scale_factor=2, mode='bilinear', align_corners=False)) + x = torch.randn(1, 64, 128, 128) + x_out = block(x) + assert isinstance(block.interp_upsample[0], Upsample) + assert isinstance(block.interp_upsample[1], ConvModule) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + assert block.interp_upsample[0].mode == 'bilinear' + + # test InterpConv with nearest upsample for upsample 2X. + block = InterpConv( + 64, + 32, + conv_first=False, + upsample_cfg=dict(scale_factor=2, mode='nearest')) + x = torch.randn(1, 64, 128, 128) + x_out = block(x) + assert isinstance(block.interp_upsample[0], Upsample) + assert isinstance(block.interp_upsample[1], ConvModule) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + assert block.interp_upsample[0].mode == 'nearest' + + +def test_up_conv_block(): + with pytest.raises(AssertionError): + # Not implemented yet. + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + UpConvBlock(BasicConvBlock, 64, 32, 32, dcn=dcn) + + with pytest.raises(AssertionError): + # Not implemented yet. + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + UpConvBlock(BasicConvBlock, 64, 32, 32, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + UpConvBlock(BasicConvBlock, 64, 32, 32, plugins=plugins) + + # test UpConvBlock with checkpoint forward and upsample 2X. + block = UpConvBlock(BasicConvBlock, 64, 32, 32, with_cp=True) + skip_x = torch.randn(1, 32, 256, 256, requires_grad=True) + x = torch.randn(1, 64, 128, 128, requires_grad=True) + x_out = block(skip_x, x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test UpConvBlock with upsample=True for upsample 2X. The spatial size of + # skip_x is 2X larger than x. + block = UpConvBlock( + BasicConvBlock, 64, 32, 32, upsample_cfg=dict(type='InterpConv')) + skip_x = torch.randn(1, 32, 256, 256) + x = torch.randn(1, 64, 128, 128) + x_out = block(skip_x, x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test UpConvBlock with upsample=False for upsample 2X. The spatial size of + # skip_x is the same as that of x. + block = UpConvBlock(BasicConvBlock, 64, 32, 32, upsample_cfg=None) + skip_x = torch.randn(1, 32, 256, 256) + x = torch.randn(1, 64, 256, 256) + x_out = block(skip_x, x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test UpConvBlock with different upsample method for upsample 2X. + # The upsample method is interpolation upsample (bilinear or nearest). + block = UpConvBlock( + BasicConvBlock, + 64, + 32, + 32, + upsample_cfg=dict( + type='InterpConv', + upsample_cfg=dict( + scale_factor=2, mode='bilinear', align_corners=False))) + skip_x = torch.randn(1, 32, 256, 256) + x = torch.randn(1, 64, 128, 128) + x_out = block(skip_x, x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test UpConvBlock with different upsample method for upsample 2X. + # The upsample method is deconvolution upsample. + block = UpConvBlock( + BasicConvBlock, + 64, + 32, + 32, + upsample_cfg=dict(type='DeconvModule', kernel_size=4, scale_factor=2)) + skip_x = torch.randn(1, 32, 256, 256) + x = torch.randn(1, 64, 128, 128) + x_out = block(skip_x, x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + # test BasicConvBlock structure and forward + block = UpConvBlock( + conv_block=BasicConvBlock, + in_channels=64, + skip_channels=32, + out_channels=32, + num_convs=3, + dilation=3, + upsample_cfg=dict( + type='InterpConv', + upsample_cfg=dict( + scale_factor=2, mode='bilinear', align_corners=False))) + skip_x = torch.randn(1, 32, 256, 256) + x = torch.randn(1, 64, 128, 128) + x_out = block(skip_x, x) + assert x_out.shape == torch.Size([1, 32, 256, 256]) + + assert block.conv_block.convs[0].conv.in_channels == 64 + assert block.conv_block.convs[0].conv.out_channels == 32 + assert block.conv_block.convs[0].conv.kernel_size == (3, 3) + assert block.conv_block.convs[0].conv.dilation == (1, 1) + assert block.conv_block.convs[0].conv.padding == (1, 1) + + assert block.conv_block.convs[1].conv.in_channels == 32 + assert block.conv_block.convs[1].conv.out_channels == 32 + assert block.conv_block.convs[1].conv.kernel_size == (3, 3) + assert block.conv_block.convs[1].conv.dilation == (3, 3) + assert block.conv_block.convs[1].conv.padding == (3, 3) + + assert block.conv_block.convs[2].conv.in_channels == 32 + assert block.conv_block.convs[2].conv.out_channels == 32 + assert block.conv_block.convs[2].conv.kernel_size == (3, 3) + assert block.conv_block.convs[2].conv.dilation == (3, 3) + assert block.conv_block.convs[2].conv.padding == (3, 3) + + assert block.upsample.interp_upsample[1].conv.in_channels == 64 + assert block.upsample.interp_upsample[1].conv.out_channels == 32 + assert block.upsample.interp_upsample[1].conv.kernel_size == (1, 1) + assert block.upsample.interp_upsample[1].conv.dilation == (1, 1) + assert block.upsample.interp_upsample[1].conv.padding == (0, 0) + + +def test_unet(): + with pytest.raises(AssertionError): + # Not implemented yet. + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + UNet(3, 64, 5, dcn=dcn) + + with pytest.raises(AssertionError): + # Not implemented yet. + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + UNet(3, 64, 5, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + UNet(3, 64, 5, plugins=plugins) + + with pytest.raises(AssertionError): + # Check whether the input image size can be divisible by the whole + # downsample rate of the encoder. The whole downsample rate of this + # case is 8. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=4, + strides=(1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2), + dec_num_convs=(2, 2, 2), + downsamples=(True, True, True), + enc_dilations=(1, 1, 1, 1), + dec_dilations=(1, 1, 1)) + x = torch.randn(2, 3, 65, 65) + unet(x) + + with pytest.raises(AssertionError): + # Check whether the input image size can be divisible by the whole + # downsample rate of the encoder. The whole downsample rate of this + # case is 16. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 65, 65) + unet(x) + + with pytest.raises(AssertionError): + # Check whether the input image size can be divisible by the whole + # downsample rate of the encoder. The whole downsample rate of this + # case is 8. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 65, 65) + unet(x) + + with pytest.raises(AssertionError): + # Check whether the input image size can be divisible by the whole + # downsample rate of the encoder. The whole downsample rate of this + # case is 8. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 2, 2, 2, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 65, 65) + unet(x) + + with pytest.raises(AssertionError): + # Check whether the input image size can be divisible by the whole + # downsample rate of the encoder. The whole downsample rate of this + # case is 32. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=6, + strides=(1, 1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2, 2), + downsamples=(True, True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1, 1)) + x = torch.randn(2, 3, 65, 65) + unet(x) + + with pytest.raises(AssertionError): + # Check if num_stages matches strides, len(strides)=num_stages + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 64, 64) + unet(x) + + with pytest.raises(AssertionError): + # Check if num_stages matches strides, len(enc_num_convs)=num_stages + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 64, 64) + unet(x) + + with pytest.raises(AssertionError): + # Check if num_stages matches strides, len(dec_num_convs)=num_stages-1 + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 64, 64) + unet(x) + + with pytest.raises(AssertionError): + # Check if num_stages matches strides, len(downsamples)=num_stages-1 + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 64, 64) + unet(x) + + with pytest.raises(AssertionError): + # Check if num_stages matches strides, len(enc_dilations)=num_stages + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 64, 64) + unet(x) + + with pytest.raises(AssertionError): + # Check if num_stages matches strides, len(dec_dilations)=num_stages-1 + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1, 1)) + x = torch.randn(2, 3, 64, 64) + unet(x) + + # test UNet norm_eval=True + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1), + norm_eval=True) + unet.train() + assert check_norm_state(unet.modules(), False) + + # test UNet norm_eval=False + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1), + norm_eval=False) + unet.train() + assert check_norm_state(unet.modules(), True) + + # test UNet forward and outputs. The whole downsample rate is 16. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 8, 8]) + assert x_outs[1].shape == torch.Size([2, 32, 16, 16]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 8. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 16, 16]) + assert x_outs[1].shape == torch.Size([2, 32, 16, 16]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 8. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 2, 2, 2, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 16, 16]) + assert x_outs[1].shape == torch.Size([2, 32, 16, 16]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 4. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, False, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 32, 32]) + assert x_outs[1].shape == torch.Size([2, 32, 32, 32]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 4. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 2, 2, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, False, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 32, 32]) + assert x_outs[1].shape == torch.Size([2, 32, 32, 32]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 8. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 16, 16]) + assert x_outs[1].shape == torch.Size([2, 32, 16, 16]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 4. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, False, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 32, 32]) + assert x_outs[1].shape == torch.Size([2, 32, 32, 32]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 2. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, False, False, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 64, 64]) + assert x_outs[1].shape == torch.Size([2, 32, 64, 64]) + assert x_outs[2].shape == torch.Size([2, 16, 64, 64]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 1. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 1, 1, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(False, False, False, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 128, 128]) + assert x_outs[1].shape == torch.Size([2, 32, 128, 128]) + assert x_outs[2].shape == torch.Size([2, 16, 128, 128]) + assert x_outs[3].shape == torch.Size([2, 8, 128, 128]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 16. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 2, 2, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, True), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 8, 8]) + assert x_outs[1].shape == torch.Size([2, 32, 16, 16]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 8. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 2, 2, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 16, 16]) + assert x_outs[1].shape == torch.Size([2, 32, 16, 16]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 8. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 2, 2, 2, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, True, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 16, 16]) + assert x_outs[1].shape == torch.Size([2, 32, 16, 16]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet forward and outputs. The whole downsample rate is 4. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 2, 2, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, False, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1)) + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 32, 32]) + assert x_outs[1].shape == torch.Size([2, 32, 32, 32]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) + + # test UNet init_weights method. + unet = UNet( + in_channels=3, + base_channels=4, + num_stages=5, + strides=(1, 2, 2, 1, 1), + enc_num_convs=(2, 2, 2, 2, 2), + dec_num_convs=(2, 2, 2, 2), + downsamples=(True, True, False, False), + enc_dilations=(1, 1, 1, 1, 1), + dec_dilations=(1, 1, 1, 1), + pretrained=None) + unet.init_weights() + x = torch.randn(2, 3, 128, 128) + x_outs = unet(x) + assert x_outs[0].shape == torch.Size([2, 64, 32, 32]) + assert x_outs[1].shape == torch.Size([2, 32, 32, 32]) + assert x_outs[2].shape == torch.Size([2, 16, 32, 32]) + assert x_outs[3].shape == torch.Size([2, 8, 64, 64]) + assert x_outs[4].shape == torch.Size([2, 4, 128, 128]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_vit.py b/third-party/InterFormer/tests/test_models/test_backbones/test_vit.py new file mode 100644 index 0000000000000000000000000000000000000000..0d1ba7000967951347602f2d6e53563bd00b850d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_vit.py @@ -0,0 +1,185 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.backbones.vit import (TransformerEncoderLayer, + VisionTransformer) +from .utils import check_norm_state + + +def test_vit_backbone(): + with pytest.raises(TypeError): + # pretrained must be a string path + model = VisionTransformer() + model.init_weights(pretrained=0) + + with pytest.raises(TypeError): + # img_size must be int or tuple + model = VisionTransformer(img_size=512.0) + + with pytest.raises(TypeError): + # out_indices must be int ,list or tuple + model = VisionTransformer(out_indices=1.) + + with pytest.raises(TypeError): + # test upsample_pos_embed function + x = torch.randn(1, 196) + VisionTransformer.resize_pos_embed(x, 512, 512, 224, 224, 'bilinear') + + with pytest.raises(AssertionError): + # The length of img_size tuple must be lower than 3. + VisionTransformer(img_size=(224, 224, 224)) + + with pytest.raises(TypeError): + # Pretrained must be None or Str. + VisionTransformer(pretrained=123) + + with pytest.raises(AssertionError): + # with_cls_token must be True when output_cls_token == True + VisionTransformer(with_cls_token=False, output_cls_token=True) + + # Test img_size isinstance tuple + imgs = torch.randn(1, 3, 224, 224) + model = VisionTransformer(img_size=(224, )) + model.init_weights() + model(imgs) + + # Test img_size isinstance tuple + imgs = torch.randn(1, 3, 224, 224) + model = VisionTransformer(img_size=(224, 224)) + model(imgs) + + # Test norm_eval = True + model = VisionTransformer(norm_eval=True) + model.train() + + # Test ViT backbone with input size of 224 and patch size of 16 + model = VisionTransformer() + model.init_weights() + model.train() + + assert check_norm_state(model.modules(), True) + + # Test normal size input image + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test large size input image + imgs = torch.randn(1, 3, 256, 256) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 16, 16) + + # Test small size input image + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 2, 2) + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test unbalanced size input image + imgs = torch.randn(1, 3, 112, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 7, 14) + + # Test irregular input image + imgs = torch.randn(1, 3, 234, 345) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 15, 22) + + # Test with_cp=True + model = VisionTransformer(with_cp=True) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test with_cls_token=False + model = VisionTransformer(with_cls_token=False) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test final norm + model = VisionTransformer(final_norm=True) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test patch norm + model = VisionTransformer(patch_norm=True) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[-1].shape == (1, 768, 14, 14) + + # Test output_cls_token + model = VisionTransformer(with_cls_token=True, output_cls_token=True) + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[0][0].shape == (1, 768, 14, 14) + assert feat[0][1].shape == (1, 768) + + # Test TransformerEncoderLayer with checkpoint forward + block = TransformerEncoderLayer( + embed_dims=64, num_heads=4, feedforward_channels=256, with_cp=True) + assert block.with_cp + x = torch.randn(1, 56 * 56, 64) + x_out = block(x) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + +def test_vit_init(): + path = 'PATH_THAT_DO_NOT_EXIST' + # Test all combinations of pretrained and init_cfg + # pretrained=None, init_cfg=None + model = VisionTransformer(pretrained=None, init_cfg=None) + assert model.init_cfg is None + model.init_weights() + + # pretrained=None + # init_cfg loads pretrain from an non-existent file + model = VisionTransformer( + pretrained=None, init_cfg=dict(type='Pretrained', checkpoint=path)) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained=None + # init_cfg=123, whose type is unsupported + model = VisionTransformer(pretrained=None, init_cfg=123) + with pytest.raises(TypeError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg=None + model = VisionTransformer(pretrained=path, init_cfg=None) + assert model.init_cfg == dict(type='Pretrained', checkpoint=path) + # Test loading a checkpoint from an non-existent file + with pytest.raises(OSError): + model.init_weights() + + # pretrained loads pretrain from an non-existent file + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = VisionTransformer( + pretrained=path, init_cfg=dict(type='Pretrained', checkpoint=path)) + with pytest.raises(AssertionError): + model = VisionTransformer(pretrained=path, init_cfg=123) + + # pretrain=123, whose type is unsupported + # init_cfg=None + with pytest.raises(TypeError): + model = VisionTransformer(pretrained=123, init_cfg=None) + + # pretrain=123, whose type is unsupported + # init_cfg loads pretrain from an non-existent file + with pytest.raises(AssertionError): + model = VisionTransformer( + pretrained=123, init_cfg=dict(type='Pretrained', checkpoint=path)) + + # pretrain=123, whose type is unsupported + # init_cfg=123, whose type is unsupported + with pytest.raises(AssertionError): + model = VisionTransformer(pretrained=123, init_cfg=123) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/test_vpd.py b/third-party/InterFormer/tests/test_models/test_backbones/test_vpd.py new file mode 100644 index 0000000000000000000000000000000000000000..a268159155e8f1451284125e36f79b59bf75dda0 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/test_vpd.py @@ -0,0 +1,51 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from os.path import dirname, join +from unittest import TestCase + +import torch +from mmengine import Config + +import mmseg +from mmseg.models.backbones import VPD + + +class TestVPD(TestCase): + + def setUp(self) -> None: + + repo_dpath = dirname(dirname(mmseg.__file__)) + config_dpath = join(repo_dpath, 'configs/_base_/models/vpd_sd.py') + vpd_cfg = Config.fromfile(config_dpath).stable_diffusion_cfg + vpd_cfg.pop('checkpoint') + + self.vpd_model = VPD( + diffusion_cfg=vpd_cfg, + class_embed_path='https://download.openmmlab.com/mmsegmentation/' + 'v0.5/vpd/nyu_class_embeddings.pth', + class_embed_select=True, + pad_shape=64, + unet_cfg=dict(use_attn=False), + ) + + def test_forward(self): + # test forward without class_id + x = torch.randn(1, 3, 60, 60) + with torch.no_grad(): + out = self.vpd_model(x) + + self.assertEqual(len(out), 4) + self.assertListEqual(list(out[0].shape), [1, 320, 8, 8]) + self.assertListEqual(list(out[1].shape), [1, 640, 4, 4]) + self.assertListEqual(list(out[2].shape), [1, 1280, 2, 2]) + self.assertListEqual(list(out[3].shape), [1, 1280, 1, 1]) + + # test forward with class_id + x = torch.randn(1, 3, 60, 60) + with torch.no_grad(): + out = self.vpd_model((x, torch.tensor([2]))) + + self.assertEqual(len(out), 4) + self.assertListEqual(list(out[0].shape), [1, 320, 8, 8]) + self.assertListEqual(list(out[1].shape), [1, 640, 4, 4]) + self.assertListEqual(list(out[2].shape), [1, 1280, 2, 2]) + self.assertListEqual(list(out[3].shape), [1, 1280, 1, 1]) diff --git a/third-party/InterFormer/tests/test_models/test_backbones/utils.py b/third-party/InterFormer/tests/test_models/test_backbones/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..54b6404c603f54c25a02f13b39dc3ddec2181680 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_backbones/utils.py @@ -0,0 +1,43 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from torch.nn.modules import GroupNorm +from torch.nn.modules.batchnorm import _BatchNorm + +from mmseg.models.backbones.resnet import BasicBlock, Bottleneck +from mmseg.models.backbones.resnext import Bottleneck as BottleneckX + + +def is_block(modules): + """Check if is ResNet building block.""" + if isinstance(modules, (BasicBlock, Bottleneck, BottleneckX)): + return True + return False + + +def is_norm(modules): + """Check if is one of the norms.""" + if isinstance(modules, (GroupNorm, _BatchNorm)): + return True + return False + + +def all_zeros(modules): + """Check if the weight(and bias) is all zero.""" + weight_zero = torch.allclose(modules.weight.data, + torch.zeros_like(modules.weight.data)) + if hasattr(modules, 'bias'): + bias_zero = torch.allclose(modules.bias.data, + torch.zeros_like(modules.bias.data)) + else: + bias_zero = True + + return weight_zero and bias_zero + + +def check_norm_state(modules, train_state): + """Check if norm layer is in correct train state.""" + for mod in modules: + if isinstance(mod, _BatchNorm): + if mod.training != train_state: + return False + return True diff --git a/third-party/InterFormer/tests/test_models/test_data_preprocessor.py b/third-party/InterFormer/tests/test_models/test_data_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..d05eef1c7d8035f395e483424c14bdf3c43e82e5 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_data_preprocessor.py @@ -0,0 +1,64 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import PixelData + +from mmseg.models import SegDataPreProcessor +from mmseg.structures import SegDataSample + + +class TestSegDataPreProcessor(TestCase): + + def test_init(self): + # test mean is None + processor = SegDataPreProcessor() + self.assertTrue(not hasattr(processor, 'mean')) + self.assertTrue(processor._enable_normalize is False) + + # test mean is not None + processor = SegDataPreProcessor(mean=[0, 0, 0], std=[1, 1, 1]) + self.assertTrue(hasattr(processor, 'mean')) + self.assertTrue(hasattr(processor, 'std')) + self.assertTrue(processor._enable_normalize) + + # please specify both mean and std + with self.assertRaises(AssertionError): + SegDataPreProcessor(mean=[0, 0, 0]) + + # bgr2rgb and rgb2bgr cannot be set to True at the same time + with self.assertRaises(AssertionError): + SegDataPreProcessor(bgr_to_rgb=True, rgb_to_bgr=True) + + def test_forward(self): + data_sample = SegDataSample() + data_sample.gt_sem_seg = PixelData( + **{'data': torch.randint(0, 10, (1, 11, 10))}) + processor = SegDataPreProcessor( + mean=[0, 0, 0], std=[1, 1, 1], size=(20, 20)) + data = { + 'inputs': [ + torch.randint(0, 256, (3, 11, 10)), + torch.randint(0, 256, (3, 11, 10)) + ], + 'data_samples': [data_sample, data_sample] + } + out = processor(data, training=True) + self.assertEqual(out['inputs'].shape, (2, 3, 20, 20)) + self.assertEqual(len(out['data_samples']), 2) + + # test predict with padding + processor = SegDataPreProcessor( + mean=[0, 0, 0], + std=[1, 1, 1], + size=(20, 20), + test_cfg=dict(size_divisor=15)) + data = { + 'inputs': [ + torch.randint(0, 256, (3, 11, 10)), + ], + 'data_samples': [data_sample] + } + out = processor(data, training=False) + self.assertEqual(out['inputs'].shape[2] % 15, 0) + self.assertEqual(out['inputs'].shape[3] % 15, 0) diff --git a/third-party/InterFormer/tests/test_models/test_forward.py b/third-party/InterFormer/tests/test_models/test_forward.py new file mode 100644 index 0000000000000000000000000000000000000000..bb3967f8dd64ef985f8d39673d8598a60cd23608 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_forward.py @@ -0,0 +1,229 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""pytest tests/test_forward.py.""" +import copy +from os.path import dirname, exists, join +from unittest.mock import patch + +import numpy as np +import pytest +import torch +import torch.nn as nn +from mmengine.model.utils import revert_sync_batchnorm +from mmengine.registry import init_default_scope +from mmengine.structures import PixelData +from mmengine.utils import is_list_of, is_tuple_of +from torch import Tensor + +from mmseg.structures import SegDataSample + +init_default_scope('mmseg') + + +def _demo_mm_inputs(batch_size=2, image_shapes=(3, 32, 32), num_classes=5): + """Create a superset of inputs needed to run test or train batches. + + Args: + batch_size (int): batch size. Default to 2. + image_shapes (List[tuple], Optional): image shape. + Default to (3, 128, 128) + num_classes (int): number of different labels a + box might have. Default to 10. + """ + if isinstance(image_shapes, list): + assert len(image_shapes) == batch_size + else: + image_shapes = [image_shapes] * batch_size + + inputs = [] + data_samples = [] + for idx in range(batch_size): + image_shape = image_shapes[idx] + c, h, w = image_shape + image = np.random.randint(0, 255, size=image_shape, dtype=np.uint8) + + mm_input = torch.from_numpy(image) + + img_meta = { + 'img_id': idx, + 'img_shape': image_shape[1:], + 'ori_shape': image_shape[1:], + 'pad_shape': image_shape[1:], + 'filename': '.png', + 'scale_factor': 1.0, + 'flip': False, + 'flip_direction': None, + } + + data_sample = SegDataSample() + data_sample.set_metainfo(img_meta) + + gt_semantic_seg = np.random.randint( + 0, num_classes, (1, h, w), dtype=np.uint8) + gt_semantic_seg = torch.LongTensor(gt_semantic_seg) + gt_sem_seg_data = dict(data=gt_semantic_seg) + data_sample.gt_sem_seg = PixelData(**gt_sem_seg_data) + inputs.append(mm_input) + data_samples.append(data_sample) + return dict(inputs=inputs, data_samples=data_samples) + + +def _get_config_directory(): + """Find the predefined segmentor config directory.""" + try: + # Assume we are running in the source mmsegmentation repo + repo_dpath = dirname(dirname(dirname(__file__))) + except NameError: + # For IPython development when this __file__ is not defined + import mmseg + repo_dpath = dirname(dirname(dirname(mmseg.__file__))) + config_dpath = join(repo_dpath, 'configs') + if not exists(config_dpath): + raise Exception('Cannot find config path') + return config_dpath + + +def _get_config_module(fname): + """Load a configuration as a python module.""" + from mmengine import Config + config_dpath = _get_config_directory() + config_fpath = join(config_dpath, fname) + config_mod = Config.fromfile(config_fpath) + return config_mod + + +def _get_segmentor_cfg(fname): + """Grab configs necessary to create a segmentor. + + These are deep copied to allow for safe modification of parameters without + influencing other tests. + """ + config = _get_config_module(fname) + model = copy.deepcopy(config.model) + return model + + +def test_pspnet_forward(): + _test_encoder_decoder_forward( + 'pspnet/pspnet_r18-d8_4xb2-80k_cityscapes-512x1024.py') + + +def test_fcn_forward(): + _test_encoder_decoder_forward( + 'fcn/fcn_r18-d8_4xb2-80k_cityscapes-512x1024.py') + + +def test_deeplabv3_forward(): + _test_encoder_decoder_forward( + 'deeplabv3/deeplabv3_r18-d8_4xb2-80k_cityscapes-512x1024.py') + + +def test_deeplabv3plus_forward(): + _test_encoder_decoder_forward( + 'deeplabv3plus/deeplabv3plus_r18-d8_4xb2-80k_cityscapes-512x1024.py') + + +def test_gcnet_forward(): + _test_encoder_decoder_forward( + 'gcnet/gcnet_r50-d8_4xb2-40k_cityscapes-512x1024.py') + + +def test_ccnet_forward(): + if not torch.cuda.is_available(): + pytest.skip('CCNet requires CUDA') + _test_encoder_decoder_forward( + 'ccnet/ccnet_r50-d8_4xb2-40k_cityscapes-512x1024.py') + + +def test_upernet_forward(): + _test_encoder_decoder_forward( + 'upernet/upernet_r50_4xb2-40k_cityscapes-512x1024.py') + + +def test_hrnet_forward(): + _test_encoder_decoder_forward( + 'hrnet/fcn_hr18s_4xb2-40k_cityscapes-512x1024.py') + + +def test_ocrnet_forward(): + _test_encoder_decoder_forward( + 'ocrnet/ocrnet_hr18s_4xb2-40k_cityscapes-512x1024.py') + + +def test_sem_fpn_forward(): + _test_encoder_decoder_forward( + 'sem_fpn/fpn_r50_4xb2-80k_cityscapes-512x1024.py') + + +def test_mobilenet_v2_forward(): + _test_encoder_decoder_forward( + 'mobilenet_v2/mobilenet-v2-d8_pspnet_4xb2-80k_cityscapes-512x1024.py') + + +def get_world_size(process_group): + + return 1 + + +def _check_input_dim(self, inputs): + pass + + +@patch('torch.nn.modules.batchnorm._BatchNorm._check_input_dim', + _check_input_dim) +@patch('torch.distributed.get_world_size', get_world_size) +def _test_encoder_decoder_forward(cfg_file): + model = _get_segmentor_cfg(cfg_file) + model['pretrained'] = None + model['test_cfg']['mode'] = 'whole' + + from mmseg.models import build_segmentor + segmentor = build_segmentor(model) + segmentor.init_weights() + + if isinstance(segmentor.decode_head, nn.ModuleList): + num_classes = segmentor.decode_head[-1].num_classes + else: + num_classes = segmentor.decode_head.num_classes + # batch_size=2 for BatchNorm + packed_inputs = _demo_mm_inputs( + batch_size=2, image_shapes=(3, 4, 4), num_classes=num_classes) + # convert to cuda Tensor if applicable + if torch.cuda.is_available(): + segmentor = segmentor.cuda() + else: + segmentor = revert_sync_batchnorm(segmentor) + + # Test forward train + data = segmentor.data_preprocessor(packed_inputs, True) + losses = segmentor.forward(**data, mode='loss') + assert isinstance(losses, dict) + + packed_inputs = _demo_mm_inputs( + batch_size=1, image_shapes=(3, 32, 32), num_classes=num_classes) + data = segmentor.data_preprocessor(packed_inputs, False) + with torch.no_grad(): + segmentor.eval() + # Test forward predict + batch_results = segmentor.forward(**data, mode='predict') + assert len(batch_results) == 1 + assert is_list_of(batch_results, SegDataSample) + assert batch_results[0].pred_sem_seg.shape == (32, 32) + assert batch_results[0].seg_logits.data.shape == (num_classes, 32, 32) + assert batch_results[0].gt_sem_seg.shape == (32, 32) + + # Test forward tensor + batch_results = segmentor.forward(**data, mode='tensor') + assert isinstance(batch_results, Tensor) or is_tuple_of( + batch_results, Tensor) + + # Test forward predict without ground truth + data.pop('data_samples') + batch_results = segmentor.forward(**data, mode='predict') + assert len(batch_results) == 1 + assert is_list_of(batch_results, SegDataSample) + assert batch_results[0].pred_sem_seg.shape == (32, 32) + + # Test forward tensor without ground truth + batch_results = segmentor.forward(**data, mode='tensor') + assert isinstance(batch_results, Tensor) or is_tuple_of( + batch_results, Tensor) diff --git a/third-party/InterFormer/tests/test_models/test_heads/__init__.py b/third-party/InterFormer/tests/test_models/test_heads/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_ann_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_ann_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e44bc6857524100197c5dbd511f20953ca13fa --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_ann_head.py @@ -0,0 +1,20 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import ANNHead +from .utils import to_cuda + + +def test_ann_head(): + + inputs = [torch.randn(1, 4, 45, 45), torch.randn(1, 8, 21, 21)] + head = ANNHead( + in_channels=[4, 8], + channels=2, + num_classes=19, + in_index=[-2, -1], + project_channels=8) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 21, 21) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_apc_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_apc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..dc55ccc1d524425ff12225220a5bf0ccdbd56920 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_apc_head.py @@ -0,0 +1,59 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import APCHead +from .utils import _conv_has_norm, to_cuda + + +def test_apc_head(): + + with pytest.raises(AssertionError): + # pool_scales must be list|tuple + APCHead(in_channels=8, channels=2, num_classes=19, pool_scales=1) + + # test no norm_cfg + head = APCHead(in_channels=8, channels=2, num_classes=19) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = APCHead( + in_channels=8, + channels=2, + num_classes=19, + norm_cfg=dict(type='SyncBN')) + assert _conv_has_norm(head, sync_bn=True) + + # fusion=True + inputs = [torch.randn(1, 8, 45, 45)] + head = APCHead( + in_channels=8, + channels=2, + num_classes=19, + pool_scales=(1, 2, 3), + fusion=True) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.fusion is True + assert head.acm_modules[0].pool_scale == 1 + assert head.acm_modules[1].pool_scale == 2 + assert head.acm_modules[2].pool_scale == 3 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 45, 45) + + # fusion=False + inputs = [torch.randn(1, 8, 45, 45)] + head = APCHead( + in_channels=8, + channels=2, + num_classes=19, + pool_scales=(1, 2, 3), + fusion=False) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.fusion is False + assert head.acm_modules[0].pool_scale == 1 + assert head.acm_modules[1].pool_scale == 2 + assert head.acm_modules[2].pool_scale == 3 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 45, 45) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_aspp_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_aspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..db9e89324f53aa7942315593ae26aadc2eeebd8b --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_aspp_head.py @@ -0,0 +1,76 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import ASPPHead, DepthwiseSeparableASPPHead +from .utils import _conv_has_norm, to_cuda + + +def test_aspp_head(): + + with pytest.raises(AssertionError): + # pool_scales must be list|tuple + ASPPHead(in_channels=8, channels=4, num_classes=19, dilations=1) + + # test no norm_cfg + head = ASPPHead(in_channels=8, channels=4, num_classes=19) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = ASPPHead( + in_channels=8, + channels=4, + num_classes=19, + norm_cfg=dict(type='SyncBN')) + assert _conv_has_norm(head, sync_bn=True) + + inputs = [torch.randn(1, 8, 45, 45)] + head = ASPPHead( + in_channels=8, channels=4, num_classes=19, dilations=(1, 12, 24)) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.aspp_modules[0].conv.dilation == (1, 1) + assert head.aspp_modules[1].conv.dilation == (12, 12) + assert head.aspp_modules[2].conv.dilation == (24, 24) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 45, 45) + + +def test_dw_aspp_head(): + + # test w.o. c1 + inputs = [torch.randn(1, 8, 45, 45)] + head = DepthwiseSeparableASPPHead( + c1_in_channels=0, + c1_channels=0, + in_channels=8, + channels=4, + num_classes=19, + dilations=(1, 12, 24)) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.c1_bottleneck is None + assert head.aspp_modules[0].conv.dilation == (1, 1) + assert head.aspp_modules[1].depthwise_conv.dilation == (12, 12) + assert head.aspp_modules[2].depthwise_conv.dilation == (24, 24) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 45, 45) + + # test with c1 + inputs = [torch.randn(1, 4, 45, 45), torch.randn(1, 16, 21, 21)] + head = DepthwiseSeparableASPPHead( + c1_in_channels=4, + c1_channels=2, + in_channels=16, + channels=8, + num_classes=19, + dilations=(1, 12, 24)) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.c1_bottleneck.in_channels == 4 + assert head.c1_bottleneck.out_channels == 2 + assert head.aspp_modules[0].conv.dilation == (1, 1) + assert head.aspp_modules[1].depthwise_conv.dilation == (12, 12) + assert head.aspp_modules[2].depthwise_conv.dilation == (24, 24) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 45, 45) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_cc_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_cc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..06304172dba1334e521dca3a6b7da7f78f091690 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_cc_head.py @@ -0,0 +1,18 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import CCHead +from .utils import to_cuda + + +def test_cc_head(): + head = CCHead(in_channels=16, channels=8, num_classes=19) + assert len(head.convs) == 2 + assert hasattr(head, 'cca') + if not torch.cuda.is_available(): + pytest.skip('CCHead requires CUDA') + inputs = [torch.randn(1, 16, 23, 23)] + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_decode_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_decode_head.py new file mode 100644 index 0000000000000000000000000000000000000000..88e6bed10fe0c1cd8961b375c78f8406e755aaed --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_decode_head.py @@ -0,0 +1,193 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest.mock import patch + +import pytest +import torch +from mmengine.structures import PixelData + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.structures import SegDataSample +from .utils import to_cuda + + +@patch.multiple(BaseDecodeHead, __abstractmethods__=set()) +def test_decode_head(): + + with pytest.raises(AssertionError): + # default input_transform doesn't accept multiple inputs + BaseDecodeHead([32, 16], 16, num_classes=19) + + with pytest.raises(AssertionError): + # default input_transform doesn't accept multiple inputs + BaseDecodeHead(32, 16, num_classes=19, in_index=[-1, -2]) + + with pytest.raises(AssertionError): + # supported mode is resize_concat only + BaseDecodeHead(32, 16, num_classes=19, input_transform='concat') + + with pytest.raises(AssertionError): + # in_channels should be list|tuple + BaseDecodeHead(32, 16, num_classes=19, input_transform='resize_concat') + + with pytest.raises(AssertionError): + # in_index should be list|tuple + BaseDecodeHead([32], + 16, + in_index=-1, + num_classes=19, + input_transform='resize_concat') + + with pytest.raises(AssertionError): + # len(in_index) should equal len(in_channels) + BaseDecodeHead([32, 16], + 16, + num_classes=19, + in_index=[-1], + input_transform='resize_concat') + + with pytest.raises(ValueError): + # out_channels should be equal to num_classes + BaseDecodeHead(32, 16, num_classes=19, out_channels=18) + + # test out_channels + head = BaseDecodeHead(32, 16, num_classes=2) + assert head.out_channels == 2 + + # test out_channels == 1 and num_classes == 2 + head = BaseDecodeHead(32, 16, num_classes=2, out_channels=1) + assert head.out_channels == 1 and head.num_classes == 2 + + # test default dropout + head = BaseDecodeHead(32, 16, num_classes=19) + assert hasattr(head, 'dropout') and head.dropout.p == 0.1 + + # test set dropout + head = BaseDecodeHead(32, 16, num_classes=19, dropout_ratio=0.2) + assert hasattr(head, 'dropout') and head.dropout.p == 0.2 + + # test no input_transform + inputs = [torch.randn(1, 32, 45, 45)] + head = BaseDecodeHead(32, 16, num_classes=19) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.in_channels == 32 + assert head.input_transform is None + transformed_inputs = head._transform_inputs(inputs) + assert transformed_inputs.shape == (1, 32, 45, 45) + + # test input_transform = resize_concat + inputs = [torch.randn(1, 32, 45, 45), torch.randn(1, 16, 21, 21)] + head = BaseDecodeHead([32, 16], + 16, + num_classes=19, + in_index=[0, 1], + input_transform='resize_concat') + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.in_channels == 48 + assert head.input_transform == 'resize_concat' + transformed_inputs = head._transform_inputs(inputs) + assert transformed_inputs.shape == (1, 48, 45, 45) + + # test multi-loss, loss_decode is dict + with pytest.raises(TypeError): + # loss_decode must be a dict or sequence of dict. + BaseDecodeHead(3, 16, num_classes=19, loss_decode=['CrossEntropyLoss']) + + inputs = torch.randn(2, 19, 8, 8).float() + data_samples = [ + SegDataSample(gt_sem_seg=PixelData(data=torch.ones(64, 64).long())) + for _ in range(2) + ] + + head = BaseDecodeHead( + 3, + 16, + num_classes=19, + loss_decode=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + loss = head.loss_by_feat( + seg_logits=inputs, batch_data_samples=data_samples) + assert 'loss_ce' in loss + + # test multi-loss, loss_decode is list of dict + inputs = torch.randn(2, 19, 8, 8).float() + data_samples = [ + SegDataSample(gt_sem_seg=PixelData(data=torch.ones(64, 64).long())) + for _ in range(2) + ] + head = BaseDecodeHead( + 3, + 16, + num_classes=19, + loss_decode=[ + dict(type='CrossEntropyLoss', loss_name='loss_1'), + dict(type='CrossEntropyLoss', loss_name='loss_2') + ]) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + + loss = head.loss_by_feat( + seg_logits=inputs, batch_data_samples=data_samples) + assert 'loss_1' in loss + assert 'loss_2' in loss + + # 'loss_decode' must be a dict or sequence of dict + with pytest.raises(TypeError): + BaseDecodeHead(3, 16, num_classes=19, loss_decode=['CrossEntropyLoss']) + with pytest.raises(TypeError): + BaseDecodeHead(3, 16, num_classes=19, loss_decode=0) + + # test multi-loss, loss_decode is list of dict + inputs = torch.randn(2, 19, 8, 8).float() + data_samples = [ + SegDataSample(gt_sem_seg=PixelData(data=torch.ones(64, 64).long())) + for _ in range(2) + ] + head = BaseDecodeHead( + 3, + 16, + num_classes=19, + loss_decode=(dict(type='CrossEntropyLoss', loss_name='loss_1'), + dict(type='CrossEntropyLoss', loss_name='loss_2'), + dict(type='CrossEntropyLoss', loss_name='loss_3'))) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + loss = head.loss_by_feat( + seg_logits=inputs, batch_data_samples=data_samples) + assert 'loss_1' in loss + assert 'loss_2' in loss + assert 'loss_3' in loss + + # test multi-loss, loss_decode is list of dict, names of them are identical + inputs = torch.randn(2, 19, 8, 8).float() + data_samples = [ + SegDataSample(gt_sem_seg=PixelData(data=torch.ones(64, 64).long())) + for _ in range(2) + ] + head = BaseDecodeHead( + 3, + 16, + num_classes=19, + loss_decode=(dict(type='CrossEntropyLoss', loss_name='loss_ce'), + dict(type='CrossEntropyLoss', loss_name='loss_ce'), + dict(type='CrossEntropyLoss', loss_name='loss_ce'))) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + loss_3 = head.loss_by_feat( + seg_logits=inputs, batch_data_samples=data_samples) + + head = BaseDecodeHead( + 3, + 16, + num_classes=19, + loss_decode=(dict(type='CrossEntropyLoss', loss_name='loss_ce'))) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + loss = head.loss_by_feat( + seg_logits=inputs, batch_data_samples=data_samples) + assert 'loss_ce' in loss + assert 'loss_ce' in loss_3 + assert loss_3['loss_ce'] == 3 * loss['loss_ce'] diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_dm_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_dm_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a922ff72950de236c024ef0f311b0abe994bc3a5 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_dm_head.py @@ -0,0 +1,59 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import DMHead +from .utils import _conv_has_norm, to_cuda + + +def test_dm_head(): + + with pytest.raises(AssertionError): + # filter_sizes must be list|tuple + DMHead(in_channels=8, channels=4, num_classes=19, filter_sizes=1) + + # test no norm_cfg + head = DMHead(in_channels=8, channels=4, num_classes=19) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = DMHead( + in_channels=8, + channels=4, + num_classes=19, + norm_cfg=dict(type='SyncBN')) + assert _conv_has_norm(head, sync_bn=True) + + # fusion=True + inputs = [torch.randn(1, 8, 23, 23)] + head = DMHead( + in_channels=8, + channels=4, + num_classes=19, + filter_sizes=(1, 3, 5), + fusion=True) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.fusion is True + assert head.dcm_modules[0].filter_size == 1 + assert head.dcm_modules[1].filter_size == 3 + assert head.dcm_modules[2].filter_size == 5 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # fusion=False + inputs = [torch.randn(1, 8, 23, 23)] + head = DMHead( + in_channels=8, + channels=4, + num_classes=19, + filter_sizes=(1, 3, 5), + fusion=False) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.fusion is False + assert head.dcm_modules[0].filter_size == 1 + assert head.dcm_modules[1].filter_size == 3 + assert head.dcm_modules[2].filter_size == 5 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_dnl_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_dnl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..720cb07fc683e98949fb0ad89298cbf829a87dab --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_dnl_head.py @@ -0,0 +1,44 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import DNLHead +from .utils import to_cuda + + +def test_dnl_head(): + # DNL with 'embedded_gaussian' mode + head = DNLHead(in_channels=8, channels=4, num_classes=19) + assert len(head.convs) == 2 + assert hasattr(head, 'dnl_block') + assert head.dnl_block.temperature == 0.05 + inputs = [torch.randn(1, 8, 23, 23)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # NonLocal2d with 'dot_product' mode + head = DNLHead( + in_channels=8, channels=4, num_classes=19, mode='dot_product') + inputs = [torch.randn(1, 8, 23, 23)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # NonLocal2d with 'gaussian' mode + head = DNLHead(in_channels=8, channels=4, num_classes=19, mode='gaussian') + inputs = [torch.randn(1, 8, 23, 23)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # NonLocal2d with 'concatenation' mode + head = DNLHead( + in_channels=8, channels=4, num_classes=19, mode='concatenation') + inputs = [torch.randn(1, 8, 23, 23)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_dpt_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_dpt_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0a6af610e18fe8eae1947672d80d1cd52ce42e98 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_dpt_head.py @@ -0,0 +1,49 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import DPTHead + + +def test_dpt_head(): + + with pytest.raises(AssertionError): + # input_transform must be 'multiple_select' + head = DPTHead( + in_channels=[768, 768, 768, 768], + channels=4, + num_classes=19, + in_index=[0, 1, 2, 3]) + + head = DPTHead( + in_channels=[768, 768, 768, 768], + channels=4, + num_classes=19, + in_index=[0, 1, 2, 3], + input_transform='multiple_select') + + inputs = [[torch.randn(4, 768, 2, 2), + torch.randn(4, 768)] for _ in range(4)] + output = head(inputs) + assert output.shape == torch.Size((4, 19, 16, 16)) + + # test readout operation + head = DPTHead( + in_channels=[768, 768, 768, 768], + channels=4, + num_classes=19, + in_index=[0, 1, 2, 3], + input_transform='multiple_select', + readout_type='add') + output = head(inputs) + assert output.shape == torch.Size((4, 19, 16, 16)) + + head = DPTHead( + in_channels=[768, 768, 768, 768], + channels=4, + num_classes=19, + in_index=[0, 1, 2, 3], + input_transform='multiple_select', + readout_type='project') + output = head(inputs) + assert output.shape == torch.Size((4, 19, 16, 16)) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_ema_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_ema_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1811cd2bb25eb6234975af28a9e10b054d678c71 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_ema_head.py @@ -0,0 +1,23 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import EMAHead +from .utils import to_cuda + + +def test_emanet_head(): + head = EMAHead( + in_channels=4, + ema_channels=3, + channels=2, + num_stages=3, + num_bases=2, + num_classes=19) + for param in head.ema_mid_conv.parameters(): + assert not param.requires_grad + assert hasattr(head, 'ema_module') + inputs = [torch.randn(1, 4, 23, 23)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_fcn_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_fcn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..664b543e07fd25f7a9bc0e32010df7045af9c049 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_fcn_head.py @@ -0,0 +1,131 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule +from mmengine.utils.dl_utils.parrots_wrapper import SyncBatchNorm + +from mmseg.models.decode_heads import DepthwiseSeparableFCNHead, FCNHead +from .utils import to_cuda + + +def test_fcn_head(): + + with pytest.raises(AssertionError): + # num_convs must be not less than 0 + FCNHead(num_classes=19, num_convs=-1) + + # test no norm_cfg + head = FCNHead(in_channels=8, channels=4, num_classes=19) + for m in head.modules(): + if isinstance(m, ConvModule): + assert not m.with_norm + + # test with norm_cfg + head = FCNHead( + in_channels=8, + channels=4, + num_classes=19, + norm_cfg=dict(type='SyncBN')) + for m in head.modules(): + if isinstance(m, ConvModule): + assert m.with_norm and isinstance(m.bn, SyncBatchNorm) + + # test concat_input=False + inputs = [torch.randn(1, 8, 23, 23)] + head = FCNHead( + in_channels=8, channels=4, num_classes=19, concat_input=False) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert len(head.convs) == 2 + assert not head.concat_input and not hasattr(head, 'conv_cat') + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # test concat_input=True + inputs = [torch.randn(1, 8, 23, 23)] + head = FCNHead( + in_channels=8, channels=4, num_classes=19, concat_input=True) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert len(head.convs) == 2 + assert head.concat_input + assert head.conv_cat.in_channels == 12 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # test kernel_size=3 + inputs = [torch.randn(1, 8, 23, 23)] + head = FCNHead(in_channels=8, channels=4, num_classes=19) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + for i in range(len(head.convs)): + assert head.convs[i].kernel_size == (3, 3) + assert head.convs[i].padding == 1 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # test kernel_size=1 + inputs = [torch.randn(1, 8, 23, 23)] + head = FCNHead(in_channels=8, channels=4, num_classes=19, kernel_size=1) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + for i in range(len(head.convs)): + assert head.convs[i].kernel_size == (1, 1) + assert head.convs[i].padding == 0 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # test num_conv + inputs = [torch.randn(1, 8, 23, 23)] + head = FCNHead(in_channels=8, channels=4, num_classes=19, num_convs=1) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert len(head.convs) == 1 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + # test num_conv = 0 + inputs = [torch.randn(1, 8, 23, 23)] + head = FCNHead( + in_channels=8, + channels=8, + num_classes=19, + num_convs=0, + concat_input=False) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert isinstance(head.convs, torch.nn.Identity) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) + + +def test_sep_fcn_head(): + # test sep_fcn_head with concat_input=False + head = DepthwiseSeparableFCNHead( + in_channels=128, + channels=128, + concat_input=False, + num_classes=19, + in_index=-1, + norm_cfg=dict(type='BN', requires_grad=True, momentum=0.01)) + x = [torch.rand(2, 128, 8, 8)] + output = head(x) + assert output.shape == (2, head.num_classes, 8, 8) + assert not head.concat_input + assert isinstance(head.convs[0], DepthwiseSeparableConvModule) + assert isinstance(head.convs[1], DepthwiseSeparableConvModule) + assert head.conv_seg.kernel_size == (1, 1) + + head = DepthwiseSeparableFCNHead( + in_channels=64, + channels=64, + concat_input=True, + num_classes=19, + in_index=-1, + norm_cfg=dict(type='BN', requires_grad=True, momentum=0.01)) + x = [torch.rand(3, 64, 8, 8)] + output = head(x) + assert output.shape == (3, head.num_classes, 8, 8) + assert head.concat_input + assert isinstance(head.convs[0], DepthwiseSeparableConvModule) + assert isinstance(head.convs[1], DepthwiseSeparableConvModule) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_gc_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_gc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c62ac9ae74fa645c20f74fba893c85ef015cb54e --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_gc_head.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import GCHead +from .utils import to_cuda + + +def test_gc_head(): + head = GCHead(in_channels=4, channels=4, num_classes=19) + assert len(head.convs) == 2 + assert hasattr(head, 'gc_block') + inputs = [torch.randn(1, 4, 23, 23)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_ham_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_ham_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f802d2d8db46362e316eac1780dcd1593d396e75 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_ham_head.py @@ -0,0 +1,44 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import LightHamHead +from .utils import _conv_has_norm, to_cuda + +ham_norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) + + +def test_ham_head(): + + # test without sync_bn + head = LightHamHead( + in_channels=[16, 32, 64], + in_index=[1, 2, 3], + channels=64, + ham_channels=64, + dropout_ratio=0.1, + num_classes=19, + norm_cfg=ham_norm_cfg, + align_corners=False, + loss_decode=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), + ham_kwargs=dict( + MD_S=1, + MD_R=64, + train_steps=6, + eval_steps=7, + inv_t=100, + rand_init=True)) + assert not _conv_has_norm(head, sync_bn=False) + + inputs = [ + torch.randn(1, 8, 32, 32), + torch.randn(1, 16, 16, 16), + torch.randn(1, 32, 8, 8), + torch.randn(1, 64, 4, 4) + ] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.in_channels == [16, 32, 64] + assert head.hamburger.ham_in.in_channels == 64 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 16, 16) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_isa_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_isa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b177f6d23ebc60a004435c6d9134e1ef8e8eb00a --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_isa_head.py @@ -0,0 +1,20 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import ISAHead +from .utils import to_cuda + + +def test_isa_head(): + + inputs = [torch.randn(1, 8, 23, 23)] + isa_head = ISAHead( + in_channels=8, + channels=4, + num_classes=19, + isa_channels=4, + down_factor=(8, 8)) + if torch.cuda.is_available(): + isa_head, inputs = to_cuda(isa_head, inputs) + output = isa_head(inputs) + assert output.shape == (1, isa_head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_lraspp_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_lraspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a46e6a19a221d4d13f5d2d53d368169398e834a0 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_lraspp_head.py @@ -0,0 +1,68 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import LRASPPHead + + +def test_lraspp_head(): + with pytest.raises(ValueError): + # check invalid input_transform + LRASPPHead( + in_channels=(4, 4, 123), + in_index=(0, 1, 2), + channels=32, + input_transform='resize_concat', + dropout_ratio=0.1, + num_classes=19, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + loss_decode=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)) + + with pytest.raises(AssertionError): + # check invalid branch_channels + LRASPPHead( + in_channels=(4, 4, 123), + in_index=(0, 1, 2), + channels=32, + branch_channels=64, + input_transform='multiple_select', + dropout_ratio=0.1, + num_classes=19, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + loss_decode=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)) + + # test with default settings + lraspp_head = LRASPPHead( + in_channels=(4, 4, 123), + in_index=(0, 1, 2), + channels=32, + input_transform='multiple_select', + dropout_ratio=0.1, + num_classes=19, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + loss_decode=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)) + inputs = [ + torch.randn(2, 4, 45, 45), + torch.randn(2, 4, 28, 28), + torch.randn(2, 123, 14, 14) + ] + with pytest.raises(RuntimeError): + # check invalid inputs + output = lraspp_head(inputs) + + inputs = [ + torch.randn(2, 4, 111, 111), + torch.randn(2, 4, 77, 77), + torch.randn(2, 123, 55, 55) + ] + output = lraspp_head(inputs) + assert output.shape == (2, 19, 111, 111) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_mask2former_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_mask2former_head.py new file mode 100644 index 0000000000000000000000000000000000000000..45b353d441b14cf279cda14997acb584cfa307ca --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_mask2former_head.py @@ -0,0 +1,153 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine import Config +from mmengine.structures import PixelData + +from mmseg.models.decode_heads import Mask2FormerHead +from mmseg.structures import SegDataSample +from mmseg.utils import SampleList +from .utils import to_cuda + + +def test_mask2former_head(): + num_classes = 19 + cfg = dict( + in_channels=[96, 192, 384, 768], + strides=[4, 8, 16, 32], + feat_channels=256, + out_channels=256, + num_classes=num_classes, + num_queries=100, + num_transformer_feat_level=3, + align_corners=False, + pixel_decoder=dict( + type='mmdet.MSDeformAttnPixelDecoder', + num_outs=3, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'), + encoder=dict( # DeformableDetrTransformerEncoder + num_layers=6, + layer_cfg=dict( # DeformableDetrTransformerEncoderLayer + self_attn_cfg=dict( # MultiScaleDeformableAttention + embed_dims=256, + num_heads=8, + num_levels=3, + num_points=4, + im2col_step=64, + dropout=0.0, + batch_first=True, + norm_cfg=None, + init_cfg=None), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=1024, + num_fcs=2, + ffn_drop=0.0, + act_cfg=dict(type='ReLU', inplace=True))), + init_cfg=None), + positional_encoding=dict( # SinePositionalEncoding + num_feats=128, normalize=True), + init_cfg=None), + enforce_decoder_input_project=False, + positional_encoding=dict( # SinePositionalEncoding + num_feats=128, normalize=True), + transformer_decoder=dict( # Mask2FormerTransformerDecoder + return_intermediate=True, + num_layers=9, + layer_cfg=dict( # Mask2FormerTransformerDecoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + attn_drop=0.0, + proj_drop=0.0, + dropout_layer=None, + batch_first=True), + cross_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + attn_drop=0.0, + proj_drop=0.0, + dropout_layer=None, + batch_first=True), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + act_cfg=dict(type='ReLU', inplace=True), + ffn_drop=0.0, + dropout_layer=None, + add_identity=True)), + init_cfg=None), + loss_cls=dict( + type='mmdet.CrossEntropyLoss', + use_sigmoid=False, + loss_weight=2.0, + reduction='mean', + class_weight=[1.0] * num_classes + [0.1]), + loss_mask=dict( + type='mmdet.CrossEntropyLoss', + use_sigmoid=True, + reduction='mean', + loss_weight=5.0), + loss_dice=dict( + type='mmdet.DiceLoss', + use_sigmoid=True, + activate=True, + reduction='mean', + naive_dice=True, + eps=1.0, + loss_weight=5.0), + train_cfg=dict( + num_points=12544, + oversample_ratio=3.0, + importance_sample_ratio=0.75, + assigner=dict( + type='mmdet.HungarianAssigner', + match_costs=[ + dict(type='mmdet.ClassificationCost', weight=2.0), + dict( + type='mmdet.CrossEntropyLossCost', + weight=5.0, + use_sigmoid=True), + dict( + type='mmdet.DiceCost', + weight=5.0, + pred_act=True, + eps=1.0) + ]), + sampler=dict(type='mmdet.MaskPseudoSampler'))) + cfg = Config(cfg) + head = Mask2FormerHead(**cfg) + + inputs = [ + torch.rand((2, 96, 8, 8)), + torch.rand((2, 192, 4, 4)), + torch.rand((2, 384, 2, 2)), + torch.rand((2, 768, 1, 1)) + ] + + data_samples: SampleList = [] + for i in range(2): + data_sample = SegDataSample() + img_meta = {} + img_meta['img_shape'] = (32, 32) + img_meta['ori_shape'] = (32, 32) + data_sample.gt_sem_seg = PixelData( + data=torch.randint(0, num_classes, (1, 32, 32))) + data_sample.set_metainfo(img_meta) + data_samples.append(data_sample) + + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + for data_sample in data_samples: + data_sample.gt_sem_seg.data = data_sample.gt_sem_seg.data.cuda() + + loss_dict = head.loss(inputs, data_samples, None) + assert isinstance(loss_dict, dict) + + batch_img_metas = [] + for data_sample in data_samples: + batch_img_metas.append(data_sample.metainfo) + + seg_logits = head.predict(inputs, batch_img_metas, None) + assert seg_logits.shape == torch.Size((2, num_classes, 32, 32)) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_maskformer_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_maskformer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6a47239b03f23224ba0498319c77f82fe0c4bddf --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_maskformer_head.py @@ -0,0 +1,54 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from os.path import dirname, join + +import torch +from mmengine import Config +from mmengine.registry import init_default_scope +from mmengine.structures import PixelData + +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample + + +def test_maskformer_head(): + init_default_scope('mmseg') + repo_dpath = dirname(dirname(__file__)) + cfg = Config.fromfile( + join( + repo_dpath, + '../../configs/maskformer/maskformer_r50-d32_8xb2-160k_ade20k-512x512.py' # noqa + )) + cfg.model.train_cfg = None + decode_head = MODELS.build(cfg.model.decode_head) + inputs = (torch.randn(1, 256, 32, 32), torch.randn(1, 512, 16, 16), + torch.randn(1, 1024, 8, 8), torch.randn(1, 2048, 4, 4)) + # test inference + batch_img_metas = [ + dict( + scale_factor=(1.0, 1.0), + img_shape=(512, 683), + ori_shape=(512, 683)) + ] + test_cfg = dict(mode='whole') + output = decode_head.predict(inputs, batch_img_metas, test_cfg) + assert output.shape == (1, 150, 512, 683) + + # test training + inputs = (torch.randn(2, 256, 32, 32), torch.randn(2, 512, 16, 16), + torch.randn(2, 1024, 8, 8), torch.randn(2, 2048, 4, 4)) + batch_data_samples = [] + img_meta = { + 'img_shape': (512, 512), + 'ori_shape': (480, 640), + 'pad_shape': (512, 512), + 'scale_factor': (1.425, 1.425), + } + for _ in range(2): + data_sample = SegDataSample( + gt_sem_seg=PixelData(data=torch.ones(512, 512).long())) + data_sample.set_metainfo(img_meta) + batch_data_samples.append(data_sample) + train_cfg = {} + losses = decode_head.loss(inputs, batch_data_samples, train_cfg) + assert (loss in losses.keys() + for loss in ('loss_cls', 'loss_mask', 'loss_dice')) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_nl_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_nl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ef0b9db312b627649f118488ae162c9ef7b197 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_nl_head.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import NLHead +from .utils import to_cuda + + +def test_nl_head(): + head = NLHead(in_channels=8, channels=4, num_classes=19) + assert len(head.convs) == 2 + assert hasattr(head, 'nl_block') + inputs = [torch.randn(1, 8, 23, 23)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_ocr_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_ocr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5d669b140b4d4a71addf75e04559eac75c1137 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_ocr_head.py @@ -0,0 +1,19 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import FCNHead, OCRHead +from .utils import to_cuda + + +def test_ocr_head(): + + inputs = [torch.randn(1, 8, 23, 23)] + ocr_head = OCRHead( + in_channels=8, channels=4, num_classes=19, ocr_channels=8) + fcn_head = FCNHead(in_channels=8, channels=4, num_classes=19) + if torch.cuda.is_available(): + head, inputs = to_cuda(ocr_head, inputs) + head, inputs = to_cuda(fcn_head, inputs) + prev_output = fcn_head(inputs) + output = ocr_head(inputs, prev_output) + assert output.shape == (1, ocr_head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_pidnet_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_pidnet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a6247371c5534715422e1ce33a56435b98e3f510 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_pidnet_head.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine.registry import init_default_scope + +from mmseg.registry import MODELS + + +def test_pidnet_head(): + init_default_scope('mmseg') + + # Test PIDNet decode head Standard Forward + norm_cfg = dict(type='BN', requires_grad=True) + backbone_cfg = dict( + type='PIDNet', + in_channels=3, + channels=32, + ppm_channels=96, + num_stem_blocks=2, + num_branch_blocks=3, + align_corners=False, + norm_cfg=norm_cfg, + act_cfg=dict(type='ReLU', inplace=True)) + decode_head_cfg = dict( + type='PIDHead', + in_channels=128, + channels=128, + num_classes=19, + norm_cfg=norm_cfg, + act_cfg=dict(type='ReLU', inplace=True), + align_corners=True, + loss_decode=[ + dict( + type='CrossEntropyLoss', + use_sigmoid=False, + class_weight=[ + 0.8373, 0.918, 0.866, 1.0345, 1.0166, 0.9969, 0.9754, + 1.0489, 0.8786, 1.0023, 0.9539, 0.9843, 1.1116, 0.9037, + 1.0865, 1.0955, 1.0865, 1.1529, 1.0507 + ], + loss_weight=0.4), + dict( + type='OhemCrossEntropy', + thres=0.9, + min_kept=131072, + class_weight=[ + 0.8373, 0.918, 0.866, 1.0345, 1.0166, 0.9969, 0.9754, + 1.0489, 0.8786, 1.0023, 0.9539, 0.9843, 1.1116, 0.9037, + 1.0865, 1.0955, 1.0865, 1.1529, 1.0507 + ], + loss_weight=1.0), + dict(type='BoundaryLoss', loss_weight=20.0), + dict( + type='OhemCrossEntropy', + thres=0.9, + min_kept=131072, + class_weight=[ + 0.8373, 0.918, 0.866, 1.0345, 1.0166, 0.9969, 0.9754, + 1.0489, 0.8786, 1.0023, 0.9539, 0.9843, 1.1116, 0.9037, + 1.0865, 1.0955, 1.0865, 1.1529, 1.0507 + ], + loss_weight=1.0) + ]) + backbone = MODELS.build(backbone_cfg) + head = MODELS.build(decode_head_cfg) + + # Test train mode + backbone.train() + head.train() + batch_size = 2 + imgs = torch.randn(batch_size, 3, 64, 128) + feats = backbone(imgs) + seg_logit = head(feats) + + assert isinstance(seg_logit, tuple) + assert len(seg_logit) == 3 + + p_logits, i_logits, d_logits = seg_logit + assert p_logits.shape == (batch_size, 19, 8, 16) + assert i_logits.shape == (batch_size, 19, 8, 16) + assert d_logits.shape == (batch_size, 1, 8, 16) + + # Test eval mode + backbone.eval() + head.eval() + feats = backbone(imgs) + seg_logit = head(feats) + + assert isinstance(seg_logit, torch.Tensor) + assert seg_logit.shape == (batch_size, 19, 8, 16) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_psa_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_psa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..34f592b026293b1e7fa15f6cde103c0c1ae0052c --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_psa_head.py @@ -0,0 +1,122 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import PSAHead +from .utils import _conv_has_norm, to_cuda + + +def test_psa_head(): + + with pytest.raises(AssertionError): + # psa_type must be in 'bi-direction', 'collect', 'distribute' + PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_type='gather') + + # test no norm_cfg + head = PSAHead( + in_channels=4, channels=2, num_classes=19, mask_size=(13, 13)) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + norm_cfg=dict(type='SyncBN')) + assert _conv_has_norm(head, sync_bn=True) + + # test 'bi-direction' psa_type + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, channels=2, num_classes=19, mask_size=(13, 13)) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'bi-direction' psa_type, shrink_factor=1 + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + shrink_factor=1) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'bi-direction' psa_type with soft_max + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_softmax=True) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'collect' psa_type + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_type='collect') + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'collect' psa_type, shrink_factor=1 + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + shrink_factor=1, + psa_type='collect') + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'collect' psa_type, shrink_factor=1, compact=True + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_type='collect', + shrink_factor=1, + compact=True) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) + + # test 'distribute' psa_type + inputs = [torch.randn(1, 4, 13, 13)] + head = PSAHead( + in_channels=4, + channels=2, + num_classes=19, + mask_size=(13, 13), + psa_type='distribute') + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 13, 13) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_psp_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_psp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fde4087c8e4c1f5979c1e5e3247f9633e4798f60 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_psp_head.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import PSPHead +from .utils import _conv_has_norm, to_cuda + + +def test_psp_head(): + + with pytest.raises(AssertionError): + # pool_scales must be list|tuple + PSPHead(in_channels=4, channels=2, num_classes=19, pool_scales=1) + + # test no norm_cfg + head = PSPHead(in_channels=4, channels=2, num_classes=19) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = PSPHead( + in_channels=4, + channels=2, + num_classes=19, + norm_cfg=dict(type='SyncBN')) + assert _conv_has_norm(head, sync_bn=True) + + inputs = [torch.randn(1, 4, 23, 23)] + head = PSPHead( + in_channels=4, channels=2, num_classes=19, pool_scales=(1, 2, 3)) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + assert head.psp_modules[0][0].output_size == 1 + assert head.psp_modules[1][0].output_size == 2 + assert head.psp_modules[2][0].output_size == 3 + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 23, 23) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_san_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_san_head.py new file mode 100644 index 0000000000000000000000000000000000000000..af85a6e2ca02771a3e750010b047ce4d03f595bd --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_san_head.py @@ -0,0 +1,126 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine import Config +from mmengine.structures import PixelData + +from mmseg.models.decode_heads import SideAdapterCLIPHead +from mmseg.structures import SegDataSample +from .utils import list_to_cuda + + +def test_san_head(): + H, W = (64, 64) + clip_channels = 64 + img_channels = 4 + num_queries = 40 + out_dims = 64 + num_classes = 19 + cfg = dict( + num_classes=num_classes, + deep_supervision_idxs=[4], + san_cfg=dict( + in_channels=img_channels, + embed_dims=128, + clip_channels=clip_channels, + num_queries=num_queries, + cfg_encoder=dict(num_encode_layer=4, mlp_ratio=2, num_heads=2), + cfg_decoder=dict( + num_heads=4, + num_layers=1, + embed_channels=32, + mlp_channels=32, + num_mlp=2, + rescale=True)), + maskgen_cfg=dict( + sos_token_num=num_queries, + embed_dims=clip_channels, + out_dims=out_dims, + num_heads=4, + mlp_ratio=2), + train_cfg=dict( + num_points=100, + oversample_ratio=3.0, + importance_sample_ratio=0.75, + assigner=dict( + type='HungarianAssigner', + match_costs=[ + dict(type='ClassificationCost', weight=2.0), + dict( + type='CrossEntropyLossCost', + weight=5.0, + use_sigmoid=True), + dict(type='DiceCost', weight=5.0, pred_act=True, eps=1.0) + ])), + loss_decode=[ + dict( + type='CrossEntropyLoss', + loss_name='loss_cls_ce', + loss_weight=2.0, + class_weight=[1.0] * num_classes + [0.1]), + dict( + type='CrossEntropyLoss', + use_sigmoid=True, + loss_name='loss_mask_ce', + loss_weight=5.0), + dict( + type='DiceLoss', + ignore_index=None, + naive_dice=True, + eps=1, + loss_name='loss_mask_dice', + loss_weight=5.0) + ]) + + cfg = Config(cfg) + head = SideAdapterCLIPHead(**cfg) + + inputs = torch.rand((2, img_channels, H, W)) + clip_feature = [[ + torch.rand((2, clip_channels, H // 2, W // 2)), + torch.rand((2, clip_channels)) + ], + [ + torch.rand((2, clip_channels, H // 2, W // 2)), + torch.rand((2, clip_channels)) + ], + [ + torch.rand((2, clip_channels, H // 2, W // 2)), + torch.rand((2, clip_channels)) + ], + [ + torch.rand((2, clip_channels, H // 2, W // 2)), + torch.rand((2, clip_channels)) + ]] + class_embed = torch.rand((num_classes + 1, out_dims)) + + data_samples = [] + for i in range(2): + data_sample = SegDataSample() + img_meta = {} + img_meta['img_shape'] = (H, W) + img_meta['ori_shape'] = (H, W) + data_sample.gt_sem_seg = PixelData( + data=torch.randint(0, num_classes, (1, H, W))) + data_sample.set_metainfo(img_meta) + data_samples.append(data_sample) + + batch_img_metas = [] + for data_sample in data_samples: + batch_img_metas.append(data_sample.metainfo) + + if torch.cuda.is_available(): + head = head.cuda() + data = list_to_cuda([inputs, clip_feature, class_embed]) + for data_sample in data_samples: + data_sample.gt_sem_seg.data = data_sample.gt_sem_seg.data.cuda() + else: + data = [inputs, clip_feature, class_embed] + + # loss test + loss_dict = head.loss(data, data_samples, None) + assert isinstance(loss_dict, dict) + + # prediction test + with torch.no_grad(): + seg_logits = head.predict(data, batch_img_metas, None) + assert seg_logits.shape == torch.Size((2, num_classes, H, W)) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_segformer_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_segformer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..73afaba2ca7957364e5ebd56cd6e0416655354ec --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_segformer_head.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import SegformerHead + + +def test_segformer_head(): + with pytest.raises(AssertionError): + # `in_channels` must have same length as `in_index` + SegformerHead( + in_channels=(1, 2, 3), in_index=(0, 1), channels=5, num_classes=2) + + H, W = (64, 64) + in_channels = (32, 64, 160, 256) + shapes = [(H // 2**(i + 2), W // 2**(i + 2)) + for i in range(len(in_channels))] + model = SegformerHead( + in_channels=in_channels, + in_index=[0, 1, 2, 3], + channels=256, + num_classes=19) + + with pytest.raises(IndexError): + # in_index must match the input feature maps. + inputs = [ + torch.randn((1, in_channel, *shape)) + for in_channel, shape in zip(in_channels, shapes) + ][:3] + temp = model(inputs) + + # Normal Input + # ((1, 32, 16, 16), (1, 64, 8, 8), (1, 160, 4, 4), (1, 256, 2, 2) + inputs = [ + torch.randn((1, in_channel, *shape)) + for in_channel, shape in zip(in_channels, shapes) + ] + temp = model(inputs) + + assert temp.shape == (1, 19, H // 4, W // 4) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_segmenter_mask_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_segmenter_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7b681ac15ce594e9ac641bf307fea77d1928204a --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_segmenter_mask_head.py @@ -0,0 +1,24 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.decode_heads import SegmenterMaskTransformerHead +from .utils import _conv_has_norm, to_cuda + + +def test_segmenter_mask_transformer_head(): + head = SegmenterMaskTransformerHead( + in_channels=2, + channels=2, + num_classes=150, + num_layers=2, + num_heads=3, + embed_dims=192, + dropout_ratio=0.0) + assert _conv_has_norm(head, sync_bn=True) + head.init_weights() + + inputs = [torch.randn(1, 2, 32, 32)] + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 32, 32) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_setr_mla_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_setr_mla_head.py new file mode 100644 index 0000000000000000000000000000000000000000..301bc0bff4c0bce8751b3cd2cc4cd4b2d7eaac06 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_setr_mla_head.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import SETRMLAHead +from .utils import to_cuda + + +def test_setr_mla_head(capsys): + + with pytest.raises(AssertionError): + # MLA requires input multiple stage feature information. + SETRMLAHead(in_channels=8, channels=4, num_classes=19, in_index=1) + + with pytest.raises(AssertionError): + # multiple in_indexs requires multiple in_channels. + SETRMLAHead( + in_channels=8, channels=4, num_classes=19, in_index=(0, 1, 2, 3)) + + with pytest.raises(AssertionError): + # channels should be len(in_channels) * mla_channels + SETRMLAHead( + in_channels=(8, 8, 8, 8), + channels=8, + mla_channels=4, + in_index=(0, 1, 2, 3), + num_classes=19) + + # test inference of MLA head + img_size = (8, 8) + patch_size = 4 + head = SETRMLAHead( + in_channels=(8, 8, 8, 8), + channels=16, + mla_channels=4, + in_index=(0, 1, 2, 3), + num_classes=19, + norm_cfg=dict(type='BN')) + + h, w = img_size[0] // patch_size, img_size[1] // patch_size + # Input square NCHW format feature information + x = [ + torch.randn(1, 8, h, w), + torch.randn(1, 8, h, w), + torch.randn(1, 8, h, w), + torch.randn(1, 8, h, w) + ] + if torch.cuda.is_available(): + head, x = to_cuda(head, x) + out = head(x) + assert out.shape == (1, head.num_classes, h * 4, w * 4) + + # Input non-square NCHW format feature information + x = [ + torch.randn(1, 8, h, w * 2), + torch.randn(1, 8, h, w * 2), + torch.randn(1, 8, h, w * 2), + torch.randn(1, 8, h, w * 2) + ] + if torch.cuda.is_available(): + head, x = to_cuda(head, x) + out = head(x) + assert out.shape == (1, head.num_classes, h * 4, w * 8) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_setr_up_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_setr_up_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a05192229c7ff216425fae9bd10b75fc8f493873 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_setr_up_head.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import SETRUPHead +from .utils import to_cuda + + +def test_setr_up_head(capsys): + + with pytest.raises(AssertionError): + # kernel_size must be [1/3] + SETRUPHead(num_classes=19, kernel_size=2) + + with pytest.raises(AssertionError): + # in_channels must be int type and in_channels must be same + # as embed_dim. + SETRUPHead(in_channels=(4, 4), channels=2, num_classes=19) + + # test init_cfg of head + head = SETRUPHead( + in_channels=4, + channels=2, + norm_cfg=dict(type='SyncBN'), + num_classes=19, + init_cfg=dict(type='Kaiming')) + super(SETRUPHead, head).init_weights() + + # test inference of Naive head + # the auxiliary head of Naive head is same as Naive head + img_size = (4, 4) + patch_size = 2 + head = SETRUPHead( + in_channels=4, + channels=2, + num_classes=19, + num_convs=1, + up_scale=4, + kernel_size=1, + norm_cfg=dict(type='BN')) + + h, w = img_size[0] // patch_size, img_size[1] // patch_size + + # Input square NCHW format feature information + x = [torch.randn(1, 4, h, w)] + if torch.cuda.is_available(): + head, x = to_cuda(head, x) + out = head(x) + assert out.shape == (1, head.num_classes, h * 4, w * 4) + + # Input non-square NCHW format feature information + x = [torch.randn(1, 4, h, w * 2)] + if torch.cuda.is_available(): + head, x = to_cuda(head, x) + out = head(x) + assert out.shape == (1, head.num_classes, h * 4, w * 8) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_uper_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_uper_head.py new file mode 100644 index 0000000000000000000000000000000000000000..09456a80c4e2a38527a631e8818c2ec9d778f312 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_uper_head.py @@ -0,0 +1,35 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import UPerHead +from .utils import _conv_has_norm, to_cuda + + +def test_uper_head(): + + with pytest.raises(AssertionError): + # fpn_in_channels must be list|tuple + UPerHead(in_channels=4, channels=2, num_classes=19) + + # test no norm_cfg + head = UPerHead( + in_channels=[4, 2], channels=2, num_classes=19, in_index=[-2, -1]) + assert not _conv_has_norm(head, sync_bn=False) + + # test with norm_cfg + head = UPerHead( + in_channels=[4, 2], + channels=2, + num_classes=19, + norm_cfg=dict(type='SyncBN'), + in_index=[-2, -1]) + assert _conv_has_norm(head, sync_bn=True) + + inputs = [torch.randn(1, 4, 45, 45), torch.randn(1, 2, 21, 21)] + head = UPerHead( + in_channels=[4, 2], channels=2, num_classes=19, in_index=[-2, -1]) + if torch.cuda.is_available(): + head, inputs = to_cuda(head, inputs) + outputs = head(inputs) + assert outputs.shape == (1, head.num_classes, 45, 45) diff --git a/third-party/InterFormer/tests/test_models/test_heads/test_vpd_depth_head.py b/third-party/InterFormer/tests/test_models/test_heads/test_vpd_depth_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a4f7558eccd29151813331cad942a164c83874 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/test_vpd_depth_head.py @@ -0,0 +1,50 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import PixelData + +from mmseg.models.decode_heads import VPDDepthHead +from mmseg.structures import SegDataSample + + +class TestVPDDepthHead(TestCase): + + def setUp(self): + """Set up common resources.""" + self.in_channels = [320, 640, 1280, 1280] + self.max_depth = 10.0 + self.loss_decode = dict( + type='SiLogLoss' + ) # Replace with your actual loss type and parameters + self.vpd_depth_head = VPDDepthHead( + max_depth=self.max_depth, + in_channels=self.in_channels, + loss_decode=self.loss_decode) + + def test_forward(self): + """Test the forward method.""" + # Create a mock input tensor. Replace shape as per your needs. + x = [ + torch.randn(1, 320, 32, 32), + torch.randn(1, 640, 16, 16), + torch.randn(1, 1280, 8, 8), + torch.randn(1, 1280, 4, 4) + ] + + output = self.vpd_depth_head.forward(x) + print(output.shape) + + self.assertEqual(output.shape, (1, 1, 256, 256)) + + def test_loss_by_feat(self): + """Test the loss_by_feat method.""" + # Create mock data for `pred_depth_map` and `batch_data_samples`. + pred_depth_map = torch.randn(1, 1, 32, 32) + gt_depth_map = PixelData(data=torch.rand(1, 32, 32)) + batch_data_samples = [SegDataSample(gt_depth_map=gt_depth_map)] + + loss = self.vpd_depth_head.loss_by_feat(pred_depth_map, + batch_data_samples) + + self.assertIsNotNone(loss) diff --git a/third-party/InterFormer/tests/test_models/test_heads/utils.py b/third-party/InterFormer/tests/test_models/test_heads/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7282340155239b7abbdc5abfe86108c3cf3b5944 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_heads/utils.py @@ -0,0 +1,31 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.cnn import ConvModule +from mmengine.utils.dl_utils.parrots_wrapper import SyncBatchNorm + + +def _conv_has_norm(module, sync_bn): + for m in module.modules(): + if isinstance(m, ConvModule): + if not m.with_norm: + return False + if sync_bn: + if not isinstance(m.bn, SyncBatchNorm): + return False + return True + + +def to_cuda(module, data): + module = module.cuda() + if isinstance(data, list): + for i in range(len(data)): + data[i] = data[i].cuda() + return module, data + + +def list_to_cuda(data): + if isinstance(data, list): + for i in range(len(data)): + data[i] = list_to_cuda(data[i]) + return data + else: + return data.cuda() diff --git a/third-party/InterFormer/tests/test_models/test_losses/test_cross_entropy_loss.py b/third-party/InterFormer/tests/test_models/test_losses/test_cross_entropy_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..8c6b86d0149a7c4c106713c7785b8a9c7f17f075 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_losses/test_cross_entropy_loss.py @@ -0,0 +1,28 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn.functional as F + +from mmseg.models.losses import CrossEntropyLoss, weight_reduce_loss + + +def test_cross_entropy_loss_class_weights(): + loss_class = CrossEntropyLoss + pred = torch.rand((1, 10, 4, 4)) + target = torch.randint(0, 10, (1, 4, 4)) + class_weight = torch.ones(10) + avg_factor = target.numel() + + cross_entropy_loss = F.cross_entropy( + pred, target, weight=class_weight, reduction='none', ignore_index=-100) + + expected_loss = weight_reduce_loss( + cross_entropy_loss, + weight=None, + reduction='mean', + avg_factor=avg_factor) + + # Test loss forward + loss = loss_class(class_weight=class_weight.tolist())(pred, target) + + assert isinstance(loss, torch.Tensor) + assert expected_loss == loss diff --git a/third-party/InterFormer/tests/test_models/test_losses/test_dice_loss.py b/third-party/InterFormer/tests/test_models/test_losses/test_dice_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..34253dae12e3943efa29953cb753e7f8683d9279 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_losses/test_dice_loss.py @@ -0,0 +1,96 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.losses import DiceLoss + + +@pytest.mark.parametrize('naive_dice', [True, False]) +def test_dice_loss(naive_dice): + loss_class = DiceLoss + pred = torch.rand((1, 10, 4, 4)) + target = torch.randint(0, 10, (1, 4, 4)) + weight = torch.rand(1) + # Test loss forward + loss = loss_class(naive_dice=naive_dice)(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with weight + loss = loss_class(naive_dice=naive_dice)(pred, target, weight) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class(naive_dice=naive_dice)( + pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class(naive_dice=naive_dice)(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class(naive_dice=naive_dice)( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class(naive_dice=naive_dice)( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with has_acted=False and use_sigmoid=False + for use_sigmoid in [True, False]: + loss_class( + use_sigmoid=use_sigmoid, activate=True, + naive_dice=naive_dice)(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with weight.ndim != loss.ndim + with pytest.raises(AssertionError): + weight = torch.rand((2, 8)) + loss_class(naive_dice=naive_dice)(pred, target, weight) + + # Test loss forward with len(weight) != len(pred) + with pytest.raises(AssertionError): + weight = torch.rand(8) + loss_class(naive_dice=naive_dice)(pred, target, weight) + + # Test _expand_onehot_labels_dice + pred = torch.tensor([[[[1, 1], [1, 0]], [[0, 1], [1, 1]]]]).float() + target = torch.tensor([[[0, 0], [0, 1]]]) + target_onehot = torch.tensor([[[[1, 1], [1, 0]], [[0, 0], [0, 1]]]]) + weight = torch.rand(1) + loss = loss_class(naive_dice=naive_dice)(pred, target, weight) + loss_onehot = loss_class(naive_dice=naive_dice)(pred, target_onehot, + weight) + assert torch.equal(loss, loss_onehot) + + # Test Whether Loss is 0 when pred == target, eps == 0 and naive_dice=False + target = torch.randint(0, 2, (1, 10, 4, 4)) + pred = target.float() + target = target.sigmoid() + weight = torch.rand(1) + loss = loss_class( + naive_dice=False, use_sigmoid=True, eps=0)(pred, target, weight) + assert loss.item() == 0 + + # Test ignore_index when ignore_index is the only class + with pytest.raises(AssertionError): + pred = torch.ones((1, 1, 4, 4)) + target = torch.randint(0, 1, (1, 4, 4)) + weight = torch.rand(1) + loss = loss_class( + naive_dice=naive_dice, use_sigmoid=False, ignore_index=0, + eps=0)(pred, target, weight) + + # Test ignore_index with naive_dice = False + pred = torch.tensor([[[[1, 1], [1, 0]], [[0, 1], [1, 1]]]]).float() + target = torch.tensor([[[[1, 1], [1, 0]], [[1, 0], [0, 1]]]]).sigmoid() + weight = torch.rand(1) + loss = loss_class( + naive_dice=False, use_sigmoid=True, ignore_index=1, + eps=0)(pred, target, weight) + assert loss.item() == 0 diff --git a/third-party/InterFormer/tests/test_models/test_losses/test_huasdorff_distance_loss.py b/third-party/InterFormer/tests/test_models/test_losses/test_huasdorff_distance_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..29c2732d3f158701009976e23472e4d0f9309923 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_losses/test_huasdorff_distance_loss.py @@ -0,0 +1,29 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.losses import HuasdorffDisstanceLoss + + +def test_huasdorff_distance_loss(): + loss_class = HuasdorffDisstanceLoss + pred = torch.rand((10, 8, 6, 6)) + target = torch.rand((10, 6, 6)) + class_weight = torch.rand(8) + + # Test loss forward + loss = loss_class()(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class()(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor and reduction is None, 'sum' and 'mean' + for reduction in [None, 'sum', 'mean']: + loss = loss_class()(pred, target, avg_factor=10, reduction=reduction) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with class_weight + with pytest.raises(AssertionError): + loss_class(class_weight=class_weight)(pred, target) diff --git a/third-party/InterFormer/tests/test_models/test_losses/test_kldiv_loss.py b/third-party/InterFormer/tests/test_models/test_losses/test_kldiv_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..48bcc4bfd9f5b1e45b2fc499611b57d5d5004a19 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_losses/test_kldiv_loss.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.losses.kldiv_loss import KLDivLoss + + +def test_kldiv_loss_with_none_reduction(): + loss_class = KLDivLoss + pred = torch.rand((8, 5, 5)) + target = torch.rand((8, 5, 5)) + reduction = 'none' + + # Test loss forward + loss = loss_class(reduction=reduction)(pred, target) + assert isinstance(loss, torch.Tensor) + assert loss.shape == (8, 5, 5), f'{loss.shape}' + + +def test_kldiv_loss_with_mean_reduction(): + loss_class = KLDivLoss + pred = torch.rand((8, 5, 5)) + target = torch.rand((8, 5, 5)) + reduction = 'mean' + + # Test loss forward + loss = loss_class(reduction=reduction)(pred, target) + assert isinstance(loss, torch.Tensor) + assert loss.shape == (8, ), f'{loss.shape}' + + +def test_kldiv_loss_with_sum_reduction(): + loss_class = KLDivLoss + pred = torch.rand((8, 5, 5)) + target = torch.rand((8, 5, 5)) + reduction = 'sum' + + # Test loss forward + loss = loss_class(reduction=reduction)(pred, target) + assert isinstance(loss, torch.Tensor) + assert loss.shape == (8, ), f'{loss.shape}' diff --git a/third-party/InterFormer/tests/test_models/test_losses/test_silog_loss.py b/third-party/InterFormer/tests/test_models/test_losses/test_silog_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..022434bcc149491552b3b9528b4a3c1431bee369 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_losses/test_silog_loss.py @@ -0,0 +1,20 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmseg.models.losses import SiLogLoss + + +class TestSiLogLoss(TestCase): + + def test_SiLogLoss_forward(self): + pred = torch.tensor([[1.0, 2.0], [3.5, 4.0]], dtype=torch.float32) + target = torch.tensor([[0.0, 2.0], [3.0, 4.0]], dtype=torch.float32) + weight = torch.tensor([1.0, 0.5], dtype=torch.float32) + + loss_module = SiLogLoss() + loss = loss_module.forward(pred, target, weight) + + expected_loss = 0.02 + self.assertAlmostEqual(loss.item(), expected_loss, places=2) diff --git a/third-party/InterFormer/tests/test_models/test_losses/test_tversky_loss.py b/third-party/InterFormer/tests/test_models/test_losses/test_tversky_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c581d8b48c9f85d5064ac4cb01ece96599e0d1 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_losses/test_tversky_loss.py @@ -0,0 +1,77 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + + +def test_tversky_lose(): + from mmseg.models import build_loss + + # test alpha + beta != 1 + with pytest.raises(AssertionError): + loss_cfg = dict( + type='TverskyLoss', + class_weight=[1.0, 2.0, 3.0], + loss_weight=1.0, + alpha=0.4, + beta=0.7, + loss_name='loss_tversky') + tversky_loss = build_loss(loss_cfg) + logits = torch.rand(8, 3, 4, 4) + labels = (torch.rand(8, 4, 4) * 3).long() + tversky_loss(logits, labels, ignore_index=1) + + # test tversky loss + loss_cfg = dict( + type='TverskyLoss', + class_weight=[1.0, 2.0, 3.0], + loss_weight=1.0, + ignore_index=1, + loss_name='loss_tversky') + tversky_loss = build_loss(loss_cfg) + logits = torch.rand(8, 3, 4, 4) + labels = (torch.rand(8, 4, 4) * 3).long() + tversky_loss(logits, labels) + + # test loss with class weights from file + import os + import tempfile + + import mmengine + import numpy as np + tmp_file = tempfile.NamedTemporaryFile() + + mmengine.dump([1.0, 2.0, 3.0], f'{tmp_file.name}.pkl', + 'pkl') # from pkl file + loss_cfg = dict( + type='TverskyLoss', + class_weight=f'{tmp_file.name}.pkl', + loss_weight=1.0, + ignore_index=1, + loss_name='loss_tversky') + tversky_loss = build_loss(loss_cfg) + tversky_loss(logits, labels) + + np.save(f'{tmp_file.name}.npy', np.array([1.0, 2.0, 3.0])) # from npy file + loss_cfg = dict( + type='TverskyLoss', + class_weight=f'{tmp_file.name}.pkl', + loss_weight=1.0, + ignore_index=1, + loss_name='loss_tversky') + tversky_loss = build_loss(loss_cfg) + tversky_loss(logits, labels) + tmp_file.close() + os.remove(f'{tmp_file.name}.pkl') + os.remove(f'{tmp_file.name}.npy') + + # test tversky loss has name `loss_tversky` + loss_cfg = dict( + type='TverskyLoss', + smooth=2, + loss_weight=1.0, + ignore_index=1, + alpha=0.3, + beta=0.7, + loss_name='loss_tversky') + tversky_loss = build_loss(loss_cfg) + assert tversky_loss.loss_name == 'loss_tversky' diff --git a/third-party/InterFormer/tests/test_models/test_necks/__init__.py b/third-party/InterFormer/tests/test_models/test_necks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_necks/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/third-party/InterFormer/tests/test_models/test_necks/test_feature2pyramid.py b/third-party/InterFormer/tests/test_models/test_necks/test_feature2pyramid.py new file mode 100644 index 0000000000000000000000000000000000000000..44fd02c489152846b17f7d46abd8064a771e6493 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_necks/test_feature2pyramid.py @@ -0,0 +1,38 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models import Feature2Pyramid + + +def test_feature2pyramid(): + # test + rescales = [4, 2, 1, 0.5] + embed_dim = 64 + inputs = [torch.randn(1, embed_dim, 32, 32) for i in range(len(rescales))] + + fpn = Feature2Pyramid( + embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True)) + outputs = fpn(inputs) + assert outputs[0].shape == torch.Size([1, 64, 128, 128]) + assert outputs[1].shape == torch.Size([1, 64, 64, 64]) + assert outputs[2].shape == torch.Size([1, 64, 32, 32]) + assert outputs[3].shape == torch.Size([1, 64, 16, 16]) + + # test rescales = [2, 1, 0.5, 0.25] + rescales = [2, 1, 0.5, 0.25] + inputs = [torch.randn(1, embed_dim, 32, 32) for i in range(len(rescales))] + + fpn = Feature2Pyramid( + embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True)) + outputs = fpn(inputs) + assert outputs[0].shape == torch.Size([1, 64, 64, 64]) + assert outputs[1].shape == torch.Size([1, 64, 32, 32]) + assert outputs[2].shape == torch.Size([1, 64, 16, 16]) + assert outputs[3].shape == torch.Size([1, 64, 8, 8]) + + # test rescales = [4, 2, 0.25, 0] + rescales = [4, 2, 0.25, 0] + with pytest.raises(KeyError): + fpn = Feature2Pyramid( + embed_dim, rescales, norm_cfg=dict(type='BN', requires_grad=True)) diff --git a/third-party/InterFormer/tests/test_models/test_necks/test_fpn.py b/third-party/InterFormer/tests/test_models/test_necks/test_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..c29400602d55319621fbff5423196131200929d9 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_necks/test_fpn.py @@ -0,0 +1,30 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models import FPN + + +def test_fpn(): + in_channels = [64, 128, 256, 512] + inputs = [ + torch.randn(1, c, 56 // 2**i, 56 // 2**i) + for i, c in enumerate(in_channels) + ] + + fpn = FPN(in_channels, 64, len(in_channels)) + outputs = fpn(inputs) + assert outputs[0].shape == torch.Size([1, 64, 56, 56]) + assert outputs[1].shape == torch.Size([1, 64, 28, 28]) + assert outputs[2].shape == torch.Size([1, 64, 14, 14]) + assert outputs[3].shape == torch.Size([1, 64, 7, 7]) + + fpn = FPN( + in_channels, + 64, + len(in_channels), + upsample_cfg=dict(mode='nearest', scale_factor=2.0)) + outputs = fpn(inputs) + assert outputs[0].shape == torch.Size([1, 64, 56, 56]) + assert outputs[1].shape == torch.Size([1, 64, 28, 28]) + assert outputs[2].shape == torch.Size([1, 64, 14, 14]) + assert outputs[3].shape == torch.Size([1, 64, 7, 7]) diff --git a/third-party/InterFormer/tests/test_models/test_necks/test_ic_neck.py b/third-party/InterFormer/tests/test_models/test_necks/test_ic_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..3d13008b5fbf1899acf86dfd42a704bf39c7124e --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_necks/test_ic_neck.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.necks import ICNeck +from mmseg.models.necks.ic_neck import CascadeFeatureFusion +from ..test_heads.utils import _conv_has_norm, to_cuda + + +def test_ic_neck(): + # test with norm_cfg + neck = ICNeck( + in_channels=(4, 16, 16), + out_channels=8, + norm_cfg=dict(type='SyncBN'), + align_corners=False) + assert _conv_has_norm(neck, sync_bn=True) + + inputs = [ + torch.randn(1, 4, 32, 64), + torch.randn(1, 16, 16, 32), + torch.randn(1, 16, 8, 16) + ] + neck = ICNeck( + in_channels=(4, 16, 16), + out_channels=4, + norm_cfg=dict(type='BN', requires_grad=True), + align_corners=False) + if torch.cuda.is_available(): + neck, inputs = to_cuda(neck, inputs) + + outputs = neck(inputs) + assert outputs[0].shape == (1, 4, 16, 32) + assert outputs[1].shape == (1, 4, 32, 64) + assert outputs[1].shape == (1, 4, 32, 64) + + +def test_ic_neck_cascade_feature_fusion(): + cff = CascadeFeatureFusion(64, 64, 32) + assert cff.conv_low.in_channels == 64 + assert cff.conv_low.out_channels == 32 + assert cff.conv_high.in_channels == 64 + assert cff.conv_high.out_channels == 32 + + +def test_ic_neck_input_channels(): + with pytest.raises(AssertionError): + # ICNet Neck input channel constraints. + ICNeck( + in_channels=(16, 64, 64, 64), + out_channels=32, + norm_cfg=dict(type='BN', requires_grad=True), + align_corners=False) diff --git a/third-party/InterFormer/tests/test_models/test_necks/test_jpu.py b/third-party/InterFormer/tests/test_models/test_necks/test_jpu.py new file mode 100644 index 0000000000000000000000000000000000000000..4c3fa9f6bb8ca6f965f4b34bcbb43ceb7996c67b --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_necks/test_jpu.py @@ -0,0 +1,46 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.necks import JPU + + +def test_fastfcn_neck(): + # Test FastFCN Standard Forward + model = JPU( + in_channels=(64, 128, 256), + mid_channels=64, + start_level=0, + end_level=-1, + dilations=(1, 2, 4, 8), + ) + model.init_weights() + model.train() + batch_size = 1 + input = [ + torch.randn(batch_size, 64, 64, 128), + torch.randn(batch_size, 128, 32, 64), + torch.randn(batch_size, 256, 16, 32) + ] + feat = model(input) + + assert len(feat) == 3 + assert feat[0].shape == torch.Size([batch_size, 64, 64, 128]) + assert feat[1].shape == torch.Size([batch_size, 128, 32, 64]) + assert feat[2].shape == torch.Size([batch_size, 256, 64, 128]) + + with pytest.raises(AssertionError): + # FastFCN input and in_channels constraints. + JPU(in_channels=(256, 64, 128), start_level=0, end_level=5) + + # Test not default start_level + model = JPU(in_channels=(64, 128, 256), start_level=1, end_level=-1) + input = [ + torch.randn(batch_size, 64, 64, 128), + torch.randn(batch_size, 128, 32, 64), + torch.randn(batch_size, 256, 16, 32) + ] + feat = model(input) + assert len(feat) == 2 + assert feat[0].shape == torch.Size([batch_size, 128, 32, 64]) + assert feat[1].shape == torch.Size([batch_size, 2048, 32, 64]) diff --git a/third-party/InterFormer/tests/test_models/test_necks/test_mla_neck.py b/third-party/InterFormer/tests/test_models/test_necks/test_mla_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..e385418949aad1e5016670b485cc10725ab69e93 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_necks/test_mla_neck.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models import MLANeck + + +def test_mla(): + in_channels = [4, 4, 4, 4] + mla = MLANeck(in_channels, 32) + + inputs = [torch.randn(1, c, 12, 12) for i, c in enumerate(in_channels)] + outputs = mla(inputs) + assert outputs[0].shape == torch.Size([1, 32, 12, 12]) + assert outputs[1].shape == torch.Size([1, 32, 12, 12]) + assert outputs[2].shape == torch.Size([1, 32, 12, 12]) + assert outputs[3].shape == torch.Size([1, 32, 12, 12]) diff --git a/third-party/InterFormer/tests/test_models/test_necks/test_multilevel_neck.py b/third-party/InterFormer/tests/test_models/test_necks/test_multilevel_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..9c71d51563ffc1f0c7a1d14c3e6e7171f42440e7 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_necks/test_multilevel_neck.py @@ -0,0 +1,32 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models import MultiLevelNeck + + +def test_multilevel_neck(): + + # Test init_weights + MultiLevelNeck([266], 32).init_weights() + + # Test multi feature maps + in_channels = [32, 64, 128, 256] + inputs = [torch.randn(1, c, 14, 14) for i, c in enumerate(in_channels)] + + neck = MultiLevelNeck(in_channels, 32) + outputs = neck(inputs) + assert outputs[0].shape == torch.Size([1, 32, 7, 7]) + assert outputs[1].shape == torch.Size([1, 32, 14, 14]) + assert outputs[2].shape == torch.Size([1, 32, 28, 28]) + assert outputs[3].shape == torch.Size([1, 32, 56, 56]) + + # Test one feature map + in_channels = [768] + inputs = [torch.randn(1, 768, 14, 14)] + + neck = MultiLevelNeck(in_channels, 32) + outputs = neck(inputs) + assert outputs[0].shape == torch.Size([1, 32, 7, 7]) + assert outputs[1].shape == torch.Size([1, 32, 14, 14]) + assert outputs[2].shape == torch.Size([1, 32, 28, 28]) + assert outputs[3].shape == torch.Size([1, 32, 56, 56]) diff --git a/third-party/InterFormer/tests/test_models/test_segmentors/__init__.py b/third-party/InterFormer/tests/test_models/test_segmentors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_segmentors/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/third-party/InterFormer/tests/test_models/test_segmentors/test_cascade_encoder_decoder.py b/third-party/InterFormer/tests/test_models/test_segmentors/test_cascade_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..941816d253766756869c0f3c04da16abfa744203 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_segmentors/test_cascade_encoder_decoder.py @@ -0,0 +1,57 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmengine import ConfigDict + +from mmseg.models import build_segmentor +from .utils import _segmentor_forward_train_test + + +def test_cascade_encoder_decoder(): + + # test 1 decode head, w.o. aux head + cfg = ConfigDict( + type='CascadeEncoderDecoder', + num_stages=2, + backbone=dict(type='ExampleBackbone'), + decode_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleCascadeDecodeHead') + ]) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test slide mode + cfg.test_cfg = ConfigDict(mode='slide', crop_size=(3, 3), stride=(2, 2)) + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test 1 decode head, 1 aux head + cfg = ConfigDict( + type='CascadeEncoderDecoder', + num_stages=2, + backbone=dict(type='ExampleBackbone'), + decode_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleCascadeDecodeHead') + ], + auxiliary_head=dict(type='ExampleDecodeHead')) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test 1 decode head, 2 aux head + cfg = ConfigDict( + type='CascadeEncoderDecoder', + num_stages=2, + backbone=dict(type='ExampleBackbone'), + decode_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleCascadeDecodeHead') + ], + auxiliary_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleDecodeHead') + ]) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) diff --git a/third-party/InterFormer/tests/test_models/test_segmentors/test_depth_estimator.py b/third-party/InterFormer/tests/test_models/test_segmentors/test_depth_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..e819c9e7633f82443c8d4101300486ebb663856d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_segmentors/test_depth_estimator.py @@ -0,0 +1,64 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from copy import deepcopy +from os.path import dirname, join +from unittest import TestCase + +import torch +from mmengine import Config, ConfigDict +from mmengine.structures import PixelData + +import mmseg +from mmseg.models.segmentors import DepthEstimator +from mmseg.structures import SegDataSample + + +class TestDepthEstimator(TestCase): + + def setUp(self) -> None: + repo_dpath = dirname(dirname(mmseg.__file__)) + config_dpath = join(repo_dpath, 'configs/_base_/models/vpd_sd.py') + vpd_cfg = Config.fromfile(config_dpath).stable_diffusion_cfg + vpd_cfg.pop('checkpoint') + + backbone_cfg = dict( + type='VPD', + diffusion_cfg=vpd_cfg, + class_embed_path='https://download.openmmlab.com/mmsegmentation/' + 'v0.5/vpd/nyu_class_embeddings.pth', + class_embed_select=True, + pad_shape=64, + unet_cfg=dict(use_attn=False), + ) + + head_cfg = dict( + type='VPDDepthHead', + max_depth=10, + ) + + self.model = DepthEstimator( + backbone=backbone_cfg, decode_head=head_cfg) + + inputs = torch.randn(1, 3, 64, 80) + data_sample = SegDataSample() + data_sample.gt_depth_map = PixelData(data=torch.rand(1, 64, 80)) + data_sample.set_metainfo(dict(img_shape=(64, 80), ori_shape=(64, 80))) + self.data = dict(inputs=inputs, data_samples=[data_sample]) + + def test_slide_flip_inference(self): + + self.model.test_cfg = ConfigDict( + dict(mode='slide_flip', crop_size=(64, 64), stride=(16, 16))) + + with torch.no_grad(): + out = self.model.predict(**deepcopy(self.data)) + + self.assertEqual(len(out), 1) + self.assertIn('pred_depth_map', out[0].keys()) + self.assertListEqual(list(out[0].pred_depth_map.shape), [64, 80]) + + def test__forward(self): + data = deepcopy(self.data) + data['inputs'] = data['inputs'][:, :, :64, :64] + with torch.no_grad(): + out = self.model._forward(**data) + self.assertListEqual(list(out.shape), [1, 1, 64, 64]) diff --git a/third-party/InterFormer/tests/test_models/test_segmentors/test_encoder_decoder.py b/third-party/InterFormer/tests/test_models/test_segmentors/test_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..5795f513d3d83299c2ffbf1f2fde035480526963 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_segmentors/test_encoder_decoder.py @@ -0,0 +1,100 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine import ConfigDict +from mmengine.structures import PixelData + +from mmseg.models import build_segmentor +from mmseg.structures import SegDataSample +from .utils import _segmentor_forward_train_test + + +def test_encoder_decoder(): + + # test 1 decode head, w.o. aux head + + cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict(type='ExampleDecodeHead'), + train_cfg=None, + test_cfg=dict(mode='whole')) + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test out_channels == 1 + cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict( + type='ExampleDecodeHead', num_classes=2, out_channels=1), + train_cfg=None, + test_cfg=dict(mode='whole')) + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test slide mode + cfg.test_cfg = ConfigDict(mode='slide', crop_size=(3, 3), stride=(2, 2)) + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test 1 decode head, 1 aux head + cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict(type='ExampleDecodeHead'), + auxiliary_head=dict(type='ExampleDecodeHead')) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + # test 1 decode head, 2 aux head + cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict(type='ExampleDecodeHead'), + auxiliary_head=[ + dict(type='ExampleDecodeHead'), + dict(type='ExampleDecodeHead') + ]) + cfg.test_cfg = ConfigDict(mode='whole') + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) + + +def test_postprocess_result(): + cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict(type='ExampleDecodeHead'), + train_cfg=None, + test_cfg=dict(mode='whole')) + model = build_segmentor(cfg) + + # test postprocess + data_sample = SegDataSample() + data_sample.gt_sem_seg = PixelData( + **{'data': torch.randint(0, 10, (1, 8, 8))}) + data_sample.set_metainfo({ + 'padding_size': (0, 2, 0, 2), + 'ori_shape': (8, 8) + }) + seg_logits = torch.zeros((1, 2, 10, 10)) + seg_logits[:, :, :8, :8] = 1 + data_samples = [data_sample] + + outputs = model.postprocess_result(seg_logits, data_samples) + assert outputs[0].seg_logits.data.shape == torch.Size((2, 8, 8)) + assert torch.allclose(outputs[0].seg_logits.data, torch.ones((2, 8, 8))) + + data_sample = SegDataSample() + data_sample.gt_sem_seg = PixelData( + **{'data': torch.randint(0, 10, (1, 8, 8))}) + data_sample.set_metainfo({ + 'img_padding_size': (0, 2, 0, 2), + 'ori_shape': (8, 8) + }) + + data_samples = [data_sample] + outputs = model.postprocess_result(seg_logits, data_samples) + assert outputs[0].seg_logits.data.shape == torch.Size((2, 8, 8)) + assert torch.allclose(outputs[0].seg_logits.data, torch.ones((2, 8, 8))) diff --git a/third-party/InterFormer/tests/test_models/test_segmentors/test_multimodal_encoder_decoder.py b/third-party/InterFormer/tests/test_models/test_segmentors/test_multimodal_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..75258d89a7d2fad4614aa2054fb977ff3df02a49 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_segmentors/test_multimodal_encoder_decoder.py @@ -0,0 +1,24 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmengine import ConfigDict + +from mmseg.models import build_segmentor +from tests.test_models.test_segmentors.utils import \ + _segmentor_forward_train_test + + +def test_multimodal_encoder_decoder(): + + cfg = ConfigDict( + type='MultimodalEncoderDecoder', + asymetric_input=False, + image_encoder=dict(type='ExampleBackbone', out_indices=[1, 2, 3, 4]), + text_encoder=dict( + type='ExampleTextEncoder', + vocabulary=['A', 'B', 'C'], + output_dims=3), + decode_head=dict( + type='ExampleDecodeHead', out_channels=1, num_classes=2), + train_cfg=None, + test_cfg=dict(mode='whole')) + segmentor = build_segmentor(cfg) + _segmentor_forward_train_test(segmentor) diff --git a/third-party/InterFormer/tests/test_models/test_segmentors/test_seg_tta_model.py b/third-party/InterFormer/tests/test_models/test_segmentors/test_seg_tta_model.py new file mode 100644 index 0000000000000000000000000000000000000000..1e152ed0565329fd220f8578c4b9a6cce6f3de30 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_segmentors/test_seg_tta_model.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import tempfile + +import torch +from mmengine import ConfigDict +from mmengine.model import BaseTTAModel +from mmengine.registry import init_default_scope +from mmengine.structures import PixelData + +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample +from .utils import * # noqa: F401,F403 + +init_default_scope('mmseg') + + +def test_encoder_decoder_tta(): + + segmentor_cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict(type='ExampleDecodeHead'), + train_cfg=None, + test_cfg=dict(mode='whole')) + + cfg = ConfigDict(type='SegTTAModel', module=segmentor_cfg) + + model: BaseTTAModel = MODELS.build(cfg) + + imgs = [] + data_samples = [] + directions = ['horizontal', 'vertical'] + for i in range(12): + flip_direction = directions[0] if i % 3 == 0 else directions[1] + imgs.append(torch.randn(1, 3, 10 + i, 10 + i)) + data_samples.append([ + SegDataSample( + metainfo=dict( + ori_shape=(10, 10), + img_shape=(10 + i, 10 + i), + flip=(i % 2 == 0), + flip_direction=flip_direction, + img_path=tempfile.mktemp()), + gt_sem_seg=PixelData(data=torch.randint(0, 19, (1, 10, 10)))) + ]) + + model.test_step(dict(inputs=imgs, data_samples=data_samples)) + + # test out_channels == 1 + segmentor_cfg = ConfigDict( + type='EncoderDecoder', + backbone=dict(type='ExampleBackbone'), + decode_head=dict( + type='ExampleDecodeHead', + num_classes=2, + out_channels=1, + threshold=0.4), + train_cfg=None, + test_cfg=dict(mode='whole')) + model.module = MODELS.build(segmentor_cfg) + for data_sample in data_samples: + data_sample[0].gt_sem_seg.data = torch.randint(0, 2, (1, 10, 10)) + model.test_step(dict(inputs=imgs, data_samples=data_samples)) diff --git a/third-party/InterFormer/tests/test_models/test_segmentors/utils.py b/third-party/InterFormer/tests/test_models/test_segmentors/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ac31e2b277467e86e835dda0e2cfbc4829e73582 --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_segmentors/utils.py @@ -0,0 +1,182 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine.optim import OptimWrapper +from mmengine.structures import PixelData +from torch import nn +from torch.optim import SGD + +from mmseg.models import SegDataPreProcessor +from mmseg.models.decode_heads.cascade_decode_head import BaseCascadeDecodeHead +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample + + +def _demo_mm_inputs(input_shape=(1, 3, 8, 16), num_classes=10): + """Create a superset of inputs needed to run test or train batches. + + Args: + input_shape (tuple): + input batch dimensions + + num_classes (int): + number of semantic classes + """ + (N, C, H, W) = input_shape + + imgs = torch.randn(*input_shape) + segs = torch.randint( + low=0, high=num_classes - 1, size=(N, H, W), dtype=torch.long) + + img_metas = [{ + 'img_shape': (H, W), + 'ori_shape': (H, W), + 'pad_shape': (H, W, C), + 'filename': '.png', + 'scale_factor': 1.0, + 'flip': False, + 'flip_direction': 'horizontal' + } for _ in range(N)] + + data_samples = [ + SegDataSample( + gt_sem_seg=PixelData(data=segs[i]), metainfo=img_metas[i]) + for i in range(N) + ] + + mm_inputs = {'imgs': torch.FloatTensor(imgs), 'data_samples': data_samples} + + return mm_inputs + + +@MODELS.register_module() +class ExampleBackbone(nn.Module): + + def __init__(self, out_indices=None): + super().__init__() + self.conv = nn.Conv2d(3, 3, 3) + self.out_indices = out_indices + + def init_weights(self, pretrained=None): + pass + + def forward(self, x): + if self.out_indices is None: + return [self.conv(x)] + else: + outs = [] + for i in self.out_indices: + outs.append(self.conv(x)) + return outs + + +@MODELS.register_module() +class ExampleDecodeHead(BaseDecodeHead): + + def __init__(self, num_classes=19, out_channels=None, **kwargs): + super().__init__( + 3, 3, num_classes=num_classes, out_channels=out_channels, **kwargs) + + def forward(self, inputs): + return self.cls_seg(inputs[0]) + + +@MODELS.register_module() +class ExampleTextEncoder(nn.Module): + + def __init__(self, vocabulary=None, output_dims=None): + super().__init__() + self.vocabulary = vocabulary + self.output_dims = output_dims + + def forward(self): + return torch.randn((len(self.vocabulary), self.output_dims)) + + +@MODELS.register_module() +class ExampleCascadeDecodeHead(BaseCascadeDecodeHead): + + def __init__(self): + super().__init__(3, 3, num_classes=19) + + def forward(self, inputs, prev_out): + return self.cls_seg(inputs[0]) + + +def _segmentor_forward_train_test(segmentor): + if isinstance(segmentor.decode_head, nn.ModuleList): + num_classes = segmentor.decode_head[-1].num_classes + else: + num_classes = segmentor.decode_head.num_classes + # batch_size=2 for BatchNorm + mm_inputs = _demo_mm_inputs(num_classes=num_classes) + + # convert to cuda Tensor if applicable + if torch.cuda.is_available(): + segmentor = segmentor.cuda() + + # check data preprocessor + if not hasattr(segmentor, + 'data_preprocessor') or segmentor.data_preprocessor is None: + segmentor.data_preprocessor = SegDataPreProcessor() + + mm_inputs = segmentor.data_preprocessor(mm_inputs, True) + imgs = mm_inputs.pop('imgs') + data_samples = mm_inputs.pop('data_samples') + + # create optimizer wrapper + optimizer = SGD(segmentor.parameters(), lr=0.1) + optim_wrapper = OptimWrapper(optimizer) + + # Test forward train + losses = segmentor.forward(imgs, data_samples, mode='loss') + assert isinstance(losses, dict) + + # Test train_step + data_batch = dict(inputs=imgs, data_samples=data_samples) + outputs = segmentor.train_step(data_batch, optim_wrapper) + assert isinstance(outputs, dict) + assert 'loss' in outputs + + # Test val_step + with torch.no_grad(): + segmentor.eval() + data_batch = dict(inputs=imgs, data_samples=data_samples) + outputs = segmentor.val_step(data_batch) + assert isinstance(outputs, list) + + # Test forward simple test + with torch.no_grad(): + segmentor.eval() + data_batch = dict(inputs=imgs, data_samples=data_samples) + results = segmentor.forward(imgs, data_samples, mode='tensor') + assert isinstance(results, torch.Tensor) + + +def _segmentor_predict(segmentor): + if isinstance(segmentor.decode_head, nn.ModuleList): + num_classes = segmentor.decode_head[-1].num_classes + else: + num_classes = segmentor.decode_head.num_classes + # batch_size=2 for BatchNorm + mm_inputs = _demo_mm_inputs(num_classes=num_classes) + + # convert to cuda Tensor if applicable + if torch.cuda.is_available(): + segmentor = segmentor.cuda() + + # check data preprocessor + if not hasattr(segmentor, + 'data_preprocessor') or segmentor.data_preprocessor is None: + segmentor.data_preprocessor = SegDataPreProcessor() + + mm_inputs = segmentor.data_preprocessor(mm_inputs, True) + imgs = mm_inputs.pop('imgs') + data_samples = mm_inputs.pop('data_samples') + + # Test predict + with torch.no_grad(): + segmentor.eval() + data_batch = dict(inputs=imgs, data_samples=data_samples) + outputs = segmentor.predict(**data_batch) + assert isinstance(outputs, list) diff --git a/third-party/InterFormer/tests/test_models/test_utils/__init__.py b/third-party/InterFormer/tests/test_models/test_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_utils/__init__.py @@ -0,0 +1 @@ +# Copyright (c) OpenMMLab. All rights reserved. diff --git a/third-party/InterFormer/tests/test_models/test_utils/test_embed.py b/third-party/InterFormer/tests/test_models/test_utils/test_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..be20c97b0d2a368428c8383fad1b1558a6bda34a --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_utils/test_embed.py @@ -0,0 +1,461 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.utils.embed import AdaptivePadding, PatchEmbed, PatchMerging + + +def test_adaptive_padding(): + + for padding in ('same', 'corner'): + kernel_size = 16 + stride = 16 + dilation = 1 + input = torch.rand(1, 1, 15, 17) + adap_pool = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + out = adap_pool(input) + # padding to divisible by 16 + assert (out.shape[2], out.shape[3]) == (16, 32) + input = torch.rand(1, 1, 16, 17) + out = adap_pool(input) + # padding to divisible by 16 + assert (out.shape[2], out.shape[3]) == (16, 32) + + kernel_size = (2, 2) + stride = (2, 2) + dilation = (1, 1) + + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 11, 13) + out = adap_pad(input) + # padding to divisible by 2 + assert (out.shape[2], out.shape[3]) == (12, 14) + + kernel_size = (2, 2) + stride = (10, 10) + dilation = (1, 1) + + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 10, 13) + out = adap_pad(input) + # no padding + assert (out.shape[2], out.shape[3]) == (10, 13) + + kernel_size = (11, 11) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 11, 13) + out = adap_pad(input) + # all padding + assert (out.shape[2], out.shape[3]) == (21, 21) + + # test padding as kernel is (7,9) + input = torch.rand(1, 1, 11, 13) + stride = (3, 4) + kernel_size = (4, 5) + dilation = (2, 2) + # actually (7, 9) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + dilation_out = adap_pad(input) + assert (dilation_out.shape[2], dilation_out.shape[3]) == (16, 21) + kernel_size = (7, 9) + dilation = (1, 1) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + kernel79_out = adap_pad(input) + assert (kernel79_out.shape[2], kernel79_out.shape[3]) == (16, 21) + assert kernel79_out.shape == dilation_out.shape + + # assert only support "same" "corner" + with pytest.raises(AssertionError): + AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=1) + + +def test_patch_embed(): + B = 2 + H = 3 + W = 4 + C = 3 + embed_dims = 10 + kernel_size = 3 + stride = 1 + dummy_input = torch.rand(B, C, H, W) + patch_merge_1 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=1, + norm_cfg=None) + + x1, shape = patch_merge_1(dummy_input) + # test out shape + assert x1.shape == (2, 2, 10) + # test outsize is correct + assert shape == (1, 2) + # test L = out_h * out_w + assert shape[0] * shape[1] == x1.shape[1] + + B = 2 + H = 10 + W = 10 + C = 3 + embed_dims = 10 + kernel_size = 5 + stride = 2 + dummy_input = torch.rand(B, C, H, W) + # test dilation + patch_merge_2 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=None, + ) + + x2, shape = patch_merge_2(dummy_input) + # test out shape + assert x2.shape == (2, 1, 10) + # test outsize is correct + assert shape == (1, 1) + # test L = out_h * out_w + assert shape[0] * shape[1] == x2.shape[1] + + stride = 2 + input_size = (10, 10) + + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + x3, shape = patch_merge_3(dummy_input) + # test out shape + assert x3.shape == (2, 1, 10) + # test outsize is correct + assert shape == (1, 1) + # test L = out_h * out_w + assert shape[0] * shape[1] == x3.shape[1] + + # test the init_out_size with nn.Unfold + assert patch_merge_3.init_out_size[1] == (input_size[0] - 2 * 4 - + 1) // 2 + 1 + assert patch_merge_3.init_out_size[0] == (input_size[0] - 2 * 4 - + 1) // 2 + 1 + H = 11 + W = 12 + input_size = (H, W) + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + _, shape = patch_merge_3(dummy_input) + # when input_size equal to real input + # the out_size should be equal to `init_out_size` + assert shape == patch_merge_3.init_out_size + + input_size = (H, W) + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + _, shape = patch_merge_3(dummy_input) + # when input_size equal to real input + # the out_size should be equal to `init_out_size` + assert shape == patch_merge_3.init_out_size + + # test adap padding + for padding in ('same', 'corner'): + in_c = 2 + embed_dims = 3 + B = 2 + + # test stride is 1 + input_size = (5, 5) + kernel_size = (5, 5) + stride = (1, 1) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 25, 3) + assert out_size == (5, 5) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (5, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 1, 3) + assert out_size == (1, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (6, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 2, 3) + assert out_size == (2, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test different kernel_size with different stride + input_size = (6, 5) + kernel_size = (6, 2) + stride = (6, 2) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 3, 3) + assert out_size == (1, 3) + assert x_out.size(1) == out_size[0] * out_size[1] + + +def test_patch_merging(): + + # Test the model with int padding + in_c = 3 + out_c = 4 + kernel_size = 3 + stride = 3 + padding = 1 + dilation = 1 + bias = False + # test the case `pad_to_stride` is False + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + B, L, C = 1, 100, 3 + input_size = (10, 10) + x = torch.rand(B, L, C) + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (1, 16, 4) + assert out_size == (4, 4) + # assert out size is consistent with real output + assert x_out.size(1) == out_size[0] * out_size[1] + in_c = 4 + out_c = 5 + kernel_size = 6 + stride = 3 + padding = 2 + dilation = 2 + bias = False + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + B, L, C = 1, 100, 4 + input_size = (10, 10) + x = torch.rand(B, L, C) + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (1, 4, 5) + assert out_size == (2, 2) + # assert out size is consistent with real output + assert x_out.size(1) == out_size[0] * out_size[1] + + # Test with adaptive padding + for padding in ('same', 'corner'): + in_c = 2 + out_c = 3 + B = 2 + + # test stride is 1 + input_size = (5, 5) + kernel_size = (5, 5) + stride = (1, 1) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 25, 3) + assert out_size == (5, 5) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (5, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 1, 3) + assert out_size == (1, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (6, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 2, 3) + assert out_size == (2, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test different kernel_size with different stride + input_size = (6, 5) + kernel_size = (6, 2) + stride = (6, 2) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 3, 3) + assert out_size == (1, 3) + assert x_out.size(1) == out_size[0] * out_size[1] diff --git a/third-party/InterFormer/tests/test_models/test_utils/test_shape_convert.py b/third-party/InterFormer/tests/test_models/test_utils/test_shape_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..60e87f38ed8b04fb964fa187d926061357d730cb --- /dev/null +++ b/third-party/InterFormer/tests/test_models/test_utils/test_shape_convert.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.models.utils import (nchw2nlc2nchw, nchw_to_nlc, nlc2nchw2nlc, + nlc_to_nchw) + + +def test_nchw2nlc2nchw(): + # Test nchw2nlc2nchw function + shape_nchw = (4, 2, 5, 5) + shape_nlc = (4, 25, 2) + + def test_func(x): + assert x.shape == torch.Size(shape_nlc) + return x + + x = torch.rand(*shape_nchw) + output = nchw2nlc2nchw(test_func, x) + assert output.shape == torch.Size(shape_nchw) + + def test_func2(x, arg): + assert x.shape == torch.Size(shape_nlc) + assert arg == 100 + return x + + x = torch.rand(*shape_nchw) + output = nchw2nlc2nchw(test_func2, x, arg=100) + assert output.shape == torch.Size(shape_nchw) + + def test_func3(x): + assert x.is_contiguous() + assert x.shape == torch.Size(shape_nlc) + return x + + x = torch.rand(*shape_nchw) + output = nchw2nlc2nchw(test_func3, x, contiguous=True) + assert output.shape == torch.Size(shape_nchw) + assert output.is_contiguous() + + +def test_nlc2nchw2nlc(): + # Test nlc2nchw2nlc function + shape_nchw = (4, 2, 5, 5) + shape_nlc = (4, 25, 2) + + def test_func(x): + assert x.shape == torch.Size(shape_nchw) + return x + + x = torch.rand(*shape_nlc) + output = nlc2nchw2nlc(test_func, x, shape_nchw[2:]) + assert output.shape == torch.Size(shape_nlc) + + def test_func2(x, arg): + assert x.shape == torch.Size(shape_nchw) + assert arg == 100 + return x + + x = torch.rand(*shape_nlc) + output = nlc2nchw2nlc(test_func2, x, shape_nchw[2:], arg=100) + assert output.shape == torch.Size(shape_nlc) + + def test_func3(x): + assert x.is_contiguous() + assert x.shape == torch.Size(shape_nchw) + return x + + x = torch.rand(*shape_nlc) + output = nlc2nchw2nlc(test_func3, x, shape_nchw[2:], contiguous=True) + assert output.shape == torch.Size(shape_nlc) + assert output.is_contiguous() + + +def test_nchw_to_nlc(): + # Test nchw_to_nlc function + shape_nchw = (4, 2, 5, 5) + shape_nlc = (4, 25, 2) + x = torch.rand(*shape_nchw) + y = nchw_to_nlc(x) + assert y.shape == torch.Size(shape_nlc) + + +def test_nlc_to_nchw(): + # Test nlc_to_nchw function + shape_nchw = (4, 2, 5, 5) + shape_nlc = (4, 25, 2) + x = torch.rand(*shape_nlc) + y = nlc_to_nchw(x, (5, 5)) + assert y.shape == torch.Size(shape_nchw) diff --git a/third-party/InterFormer/tests/test_sampler.py b/third-party/InterFormer/tests/test_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..322be9579b799530d3edc374e951b85a3dcf3a22 --- /dev/null +++ b/third-party/InterFormer/tests/test_sampler.py @@ -0,0 +1,78 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmseg.models.decode_heads import FCNHead +from mmseg.structures import OHEMPixelSampler + + +def _context_for_ohem(): + return FCNHead(in_channels=32, channels=16, num_classes=19) + + +def _context_for_ohem_multiple_loss(): + return FCNHead( + in_channels=32, + channels=16, + num_classes=19, + loss_decode=[ + dict(type='CrossEntropyLoss', loss_name='loss_1'), + dict(type='CrossEntropyLoss', loss_name='loss_2') + ]) + + +def test_ohem_sampler(): + + with pytest.raises(AssertionError): + # seg_logit and seg_label must be of the same size + sampler = OHEMPixelSampler(context=_context_for_ohem()) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 89, 89)) + sampler.sample(seg_logit, seg_label) + + # test with thresh + sampler = OHEMPixelSampler( + context=_context_for_ohem(), thresh=0.7, min_kept=200) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 45, 45)) + seg_weight = sampler.sample(seg_logit, seg_label) + assert seg_weight.shape[0] == seg_logit.shape[0] + assert seg_weight.shape[1:] == seg_logit.shape[2:] + assert seg_weight.sum() > 200 + + # test w.o thresh + sampler = OHEMPixelSampler(context=_context_for_ohem(), min_kept=200) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 45, 45)) + seg_weight = sampler.sample(seg_logit, seg_label) + assert seg_weight.shape[0] == seg_logit.shape[0] + assert seg_weight.shape[1:] == seg_logit.shape[2:] + assert seg_weight.sum() == 200 + + # test multiple losses case + with pytest.raises(AssertionError): + # seg_logit and seg_label must be of the same size + sampler = OHEMPixelSampler(context=_context_for_ohem_multiple_loss()) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 89, 89)) + sampler.sample(seg_logit, seg_label) + + # test with thresh in multiple losses case + sampler = OHEMPixelSampler( + context=_context_for_ohem_multiple_loss(), thresh=0.7, min_kept=200) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 45, 45)) + seg_weight = sampler.sample(seg_logit, seg_label) + assert seg_weight.shape[0] == seg_logit.shape[0] + assert seg_weight.shape[1:] == seg_logit.shape[2:] + assert seg_weight.sum() > 200 + + # test w.o thresh in multiple losses case + sampler = OHEMPixelSampler( + context=_context_for_ohem_multiple_loss(), min_kept=200) + seg_logit = torch.randn(1, 19, 45, 45) + seg_label = torch.randint(0, 19, size=(1, 1, 45, 45)) + seg_weight = sampler.sample(seg_logit, seg_label) + assert seg_weight.shape[0] == seg_logit.shape[0] + assert seg_weight.shape[1:] == seg_logit.shape[2:] + assert seg_weight.sum() == 200 diff --git a/third-party/InterFormer/tests/test_structures/test_seg_data_sample.py b/third-party/InterFormer/tests/test_structures/test_seg_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..37796b611de4bafe937bf2ccbd790303bf7a2770 --- /dev/null +++ b/third-party/InterFormer/tests/test_structures/test_seg_data_sample.py @@ -0,0 +1,77 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import pytest +import torch +from mmengine.structures import PixelData + +from mmseg.structures import SegDataSample + + +def _equal(a, b): + if isinstance(a, (torch.Tensor, np.ndarray)): + return (a == b).all() + else: + return a == b + + +class TestSegDataSample(TestCase): + + def test_init(self): + meta_info = dict( + img_size=[256, 256], + scale_factor=np.array([1.5, 1.5]), + img_shape=torch.rand(4)) + + seg_data_sample = SegDataSample(metainfo=meta_info) + assert 'img_size' in seg_data_sample + assert seg_data_sample.img_size == [256, 256] + assert seg_data_sample.get('img_size') == [256, 256] + + def test_setter(self): + seg_data_sample = SegDataSample() + + # test gt_sem_seg + gt_sem_seg_data = dict(sem_seg=torch.rand(5, 4, 2)) + gt_sem_seg = PixelData(**gt_sem_seg_data) + seg_data_sample.gt_sem_seg = gt_sem_seg + assert 'gt_sem_seg' in seg_data_sample + assert _equal(seg_data_sample.gt_sem_seg.sem_seg, + gt_sem_seg_data['sem_seg']) + + # test pred_sem_seg + pred_sem_seg_data = dict(sem_seg=torch.rand(5, 4, 2)) + pred_sem_seg = PixelData(**pred_sem_seg_data) + seg_data_sample.pred_sem_seg = pred_sem_seg + assert 'pred_sem_seg' in seg_data_sample + assert _equal(seg_data_sample.pred_sem_seg.sem_seg, + pred_sem_seg_data['sem_seg']) + + # test seg_logits + seg_logits_data = dict(sem_seg=torch.rand(5, 4, 2)) + seg_logits = PixelData(**seg_logits_data) + seg_data_sample.seg_logits = seg_logits + assert 'seg_logits' in seg_data_sample + assert _equal(seg_data_sample.seg_logits.sem_seg, + seg_logits_data['sem_seg']) + + # test type error + with pytest.raises(AssertionError): + seg_data_sample.gt_sem_seg = torch.rand(2, 4) + + with pytest.raises(AssertionError): + seg_data_sample.pred_sem_seg = torch.rand(2, 4) + + with pytest.raises(AssertionError): + seg_data_sample.seg_logits = torch.rand(2, 4) + + def test_deleter(self): + seg_data_sample = SegDataSample() + + pred_sem_seg_data = dict(sem_seg=torch.rand(5, 4, 2)) + pred_sem_seg = PixelData(**pred_sem_seg_data) + seg_data_sample.pred_sem_seg = pred_sem_seg + assert 'pred_sem_seg' in seg_data_sample + del seg_data_sample.pred_sem_seg + assert 'pred_sem_seg' not in seg_data_sample diff --git a/third-party/InterFormer/tests/test_utils/test_io.py b/third-party/InterFormer/tests/test_utils/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..05abd275f8ca829d56323f7d3cabbfadeab076ce --- /dev/null +++ b/third-party/InterFormer/tests/test_utils/test_io.py @@ -0,0 +1,33 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp + +import numpy as np +import pytest +from mmengine import FileClient + +from mmseg.utils import datafrombytes + + +@pytest.mark.parametrize( + ['backend', 'suffix'], + [['nifti', '.nii.gz'], ['numpy', '.npy'], ['pickle', '.pkl']]) +def test_datafrombytes(backend, suffix): + + file_client = FileClient('disk') + file_path = osp.join(osp.dirname(__file__), '../data/biomedical' + suffix) + bytes = file_client.get(file_path) + data = datafrombytes(bytes, backend) + + if backend == 'pickle': + # test pickle loading + assert isinstance(data, dict) + else: + assert isinstance(data, np.ndarray) + if backend == 'nifti': + # test nifti file loading + assert len(data.shape) == 3 + else: + # test npy file loading + # testing data biomedical.npy includes data and label + assert len(data.shape) == 4 + assert data.shape[0] == 2 diff --git a/third-party/InterFormer/tests/test_utils/test_set_env.py b/third-party/InterFormer/tests/test_utils/test_set_env.py new file mode 100644 index 0000000000000000000000000000000000000000..86a2d29aecac9b651e15b1a1d70507eb6d396a36 --- /dev/null +++ b/third-party/InterFormer/tests/test_utils/test_set_env.py @@ -0,0 +1,39 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import datetime +import sys +from unittest import TestCase + +from mmengine import DefaultScope + +from mmseg.utils import register_all_modules + + +class TestSetupEnv(TestCase): + + def test_register_all_modules(self): + from mmseg.registry import DATASETS + + # not init default scope + sys.modules.pop('mmseg.datasets', None) + sys.modules.pop('mmseg.datasets.ade', None) + DATASETS._module_dict.pop('ADE20KDataset', None) + self.assertFalse('ADE20KDataset' in DATASETS.module_dict) + register_all_modules(init_default_scope=False) + self.assertTrue('ADE20KDataset' in DATASETS.module_dict) + + # init default scope + sys.modules.pop('mmseg.datasets') + sys.modules.pop('mmseg.datasets.ade') + DATASETS._module_dict.pop('ADE20KDataset', None) + self.assertFalse('ADE20KDataset' in DATASETS.module_dict) + register_all_modules(init_default_scope=True) + self.assertTrue('ADE20KDataset' in DATASETS.module_dict) + self.assertEqual(DefaultScope.get_current_instance().scope_name, + 'mmseg') + + # init default scope when another scope is init + name = f'test-{datetime.datetime.now()}' + DefaultScope.get_instance(name, scope_name='test') + with self.assertWarnsRegex( + Warning, 'The current default scope "test" is not "mmseg"'): + register_all_modules(init_default_scope=True) diff --git a/third-party/InterFormer/tests/test_visualization/test_local_visualizer.py b/third-party/InterFormer/tests/test_visualization/test_local_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b2a88cfb794c6aa413b8469ba0549e6e121ae4 --- /dev/null +++ b/third-party/InterFormer/tests/test_visualization/test_local_visualizer.py @@ -0,0 +1,213 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import os.path as osp +import tempfile +from unittest import TestCase + +import cv2 +import mmcv +import numpy as np +import torch +from mmengine.structures import PixelData + +from mmseg.structures import SegDataSample +from mmseg.visualization import SegLocalVisualizer + + +class TestSegLocalVisualizer(TestCase): + + def test_add_datasample(self): + h = 10 + w = 12 + num_class = 2 + out_file = 'out_file' + + image = np.random.randint(0, 256, size=(h, w, 3)).astype('uint8') + + # test gt_sem_seg + gt_sem_seg_data = dict(data=torch.randint(0, num_class, (1, h, w))) + gt_sem_seg = PixelData(**gt_sem_seg_data) + + def test_add_datasample_forward(gt_sem_seg): + data_sample = SegDataSample() + data_sample.gt_sem_seg = gt_sem_seg + + with tempfile.TemporaryDirectory() as tmp_dir: + seg_local_visualizer = SegLocalVisualizer( + vis_backends=[dict(type='LocalVisBackend')], + save_dir=tmp_dir) + seg_local_visualizer.dataset_meta = dict( + classes=('background', 'foreground'), + palette=[[120, 120, 120], [6, 230, 230]]) + + # test out_file + seg_local_visualizer.add_datasample(out_file, image, + data_sample) + + assert os.path.exists( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png')) + drawn_img = cv2.imread( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png')) + assert drawn_img.shape == (h, w, 3) + + # test gt_instances and pred_instances + pred_sem_seg_data = dict( + data=torch.randint(0, num_class, (1, h, w))) + pred_sem_seg = PixelData(**pred_sem_seg_data) + + data_sample.pred_sem_seg = pred_sem_seg + + seg_local_visualizer.add_datasample(out_file, image, + data_sample) + self._assert_image_and_shape( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png'), (h, w * 2, 3)) + + seg_local_visualizer.add_datasample( + out_file, image, data_sample, draw_gt=False) + self._assert_image_and_shape( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png'), (h, w, 3)) + + if torch.cuda.is_available(): + test_add_datasample_forward(gt_sem_seg.cuda()) + test_add_datasample_forward(gt_sem_seg) + + def test_cityscapes_add_datasample(self): + h = 128 + w = 256 + num_class = 19 + out_file = 'out_file_cityscapes' + + image = mmcv.imread( + osp.join( + osp.dirname(__file__), + '../data/pseudo_cityscapes_dataset/leftImg8bit/val/frankfurt/frankfurt_000000_000294_leftImg8bit.png' # noqa + ), + 'color') + sem_seg = mmcv.imread( + osp.join( + osp.dirname(__file__), + '../data/pseudo_cityscapes_dataset/gtFine/val/frankfurt/frankfurt_000000_000294_gtFine_labelTrainIds.png' # noqa + ), + 'unchanged') + sem_seg = torch.unsqueeze(torch.from_numpy(sem_seg), 0) + gt_sem_seg_data = dict(data=sem_seg) + gt_sem_seg = PixelData(**gt_sem_seg_data) + + def test_cityscapes_add_datasample_forward(gt_sem_seg): + data_sample = SegDataSample() + data_sample.gt_sem_seg = gt_sem_seg + + with tempfile.TemporaryDirectory() as tmp_dir: + seg_local_visualizer = SegLocalVisualizer( + vis_backends=[dict(type='LocalVisBackend')], + save_dir=tmp_dir) + seg_local_visualizer.dataset_meta = dict( + classes=('road', 'sidewalk', 'building', 'wall', 'fence', + 'pole', 'traffic light', 'traffic sign', + 'vegetation', 'terrain', 'sky', 'person', 'rider', + 'car', 'truck', 'bus', 'train', 'motorcycle', + 'bicycle'), + palette=[[128, 64, 128], [244, 35, 232], [70, 70, 70], + [102, 102, 156], [190, 153, 153], [153, 153, 153], + [250, 170, 30], [220, 220, 0], [107, 142, 35], + [152, 251, 152], [70, 130, 180], [220, 20, 60], + [255, 0, 0], [0, 0, 142], [0, 0, 70], + [0, 60, 100], [0, 80, 100], [0, 0, 230], + [119, 11, 32]]) + # test out_file + seg_local_visualizer.add_datasample( + out_file, + image, + data_sample, + out_file=osp.join(tmp_dir, 'test.png')) + self._assert_image_and_shape( + osp.join(tmp_dir, 'test.png'), (h, w, 3)) + + # test gt_instances and pred_instances + pred_sem_seg_data = dict( + data=torch.randint(0, num_class, (1, h, w))) + pred_sem_seg = PixelData(**pred_sem_seg_data) + + data_sample.pred_sem_seg = pred_sem_seg + + # test draw prediction with gt + seg_local_visualizer.add_datasample(out_file, image, + data_sample) + self._assert_image_and_shape( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png'), (h, w * 2, 3)) + # test draw prediction without gt + seg_local_visualizer.add_datasample( + out_file, image, data_sample, draw_gt=False) + self._assert_image_and_shape( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png'), (h, w, 3)) + + if torch.cuda.is_available(): + test_cityscapes_add_datasample_forward(gt_sem_seg.cuda()) + test_cityscapes_add_datasample_forward(gt_sem_seg) + + def _assert_image_and_shape(self, out_file, out_shape): + assert os.path.exists(out_file) + drawn_img = cv2.imread(out_file) + assert drawn_img.shape == out_shape + + def test_add_datasample_depth(self): + h = 10 + w = 12 + out_file = 'out_file' + + image = np.random.randint(0, 256, size=(h, w, 3)).astype('uint8') + + # test gt_depth_map + gt_depth_map = PixelData(data=torch.rand(1, h, w)) + + def test_add_datasample_forward_depth(gt_depth_map): + data_sample = SegDataSample() + data_sample.gt_depth_map = gt_depth_map + + with tempfile.TemporaryDirectory() as tmp_dir: + seg_local_visualizer = SegLocalVisualizer( + vis_backends=[dict(type='LocalVisBackend')], + save_dir=tmp_dir) + seg_local_visualizer.dataset_meta = dict( + classes=('background', 'foreground'), + palette=[[120, 120, 120], [6, 230, 230]]) + + # test out_file + seg_local_visualizer.add_datasample(out_file, image, + data_sample) + + assert os.path.exists( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png')) + drawn_img = cv2.imread( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png')) + assert drawn_img.shape == (h * 2, w, 3) + + # test gt_instances and pred_instances + + pred_depth_map = PixelData(data=torch.rand(1, h, w)) + + data_sample.pred_depth_map = pred_depth_map + + seg_local_visualizer.add_datasample(out_file, image, + data_sample) + self._assert_image_and_shape( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png'), (h * 2, w * 2, 3)) + + seg_local_visualizer.add_datasample( + out_file, image, data_sample, draw_gt=False) + self._assert_image_and_shape( + osp.join(tmp_dir, 'vis_data', 'vis_image', + out_file + '_0.png'), (h * 2, w, 3)) + + if torch.cuda.is_available(): + test_add_datasample_forward_depth(gt_depth_map.cuda()) + test_add_datasample_forward_depth(gt_depth_map) diff --git a/third-party/InterFormer/tools/analysis_tools/analyze_logs.py b/third-party/InterFormer/tools/analysis_tools/analyze_logs.py new file mode 100644 index 0000000000000000000000000000000000000000..7464d231621b17249ce69f358479bbba42757362 --- /dev/null +++ b/third-party/InterFormer/tools/analysis_tools/analyze_logs.py @@ -0,0 +1,130 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from https://github.com/open- +mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py.""" +import argparse +import json +from collections import defaultdict + +import matplotlib.pyplot as plt +import seaborn as sns + + +def plot_curve(log_dicts, args): + if args.backend is not None: + plt.switch_backend(args.backend) + sns.set_style(args.style) + # if legend is None, use {filename}_{key} as legend + legend = args.legend + if legend is None: + legend = [] + for json_log in args.json_logs: + for metric in args.keys: + legend.append(f'{json_log}_{metric}') + assert len(legend) == (len(args.json_logs) * len(args.keys)) + metrics = args.keys + + num_metrics = len(metrics) + for i, log_dict in enumerate(log_dicts): + epochs = list(log_dict.keys()) + for j, metric in enumerate(metrics): + print(f'plot curve of {args.json_logs[i]}, metric is {metric}') + plot_epochs = [] + plot_iters = [] + plot_values = [] + # In some log files exist lines of validation, + # `mode` list is used to only collect iter number + # of training line. + for epoch in epochs: + epoch_logs = log_dict[epoch] + if metric not in epoch_logs.keys(): + continue + if metric in ['mIoU', 'mAcc', 'aAcc']: + plot_epochs.append(epoch) + plot_values.append(epoch_logs[metric][0]) + else: + for idx in range(len(epoch_logs[metric])): + plot_iters.append(epoch_logs['step'][idx]) + plot_values.append(epoch_logs[metric][idx]) + ax = plt.gca() + label = legend[i * num_metrics + j] + if metric in ['mIoU', 'mAcc', 'aAcc']: + ax.set_xticks(plot_epochs) + plt.xlabel('step') + plt.plot(plot_epochs, plot_values, label=label, marker='o') + else: + plt.xlabel('iter') + plt.plot(plot_iters, plot_values, label=label, linewidth=0.5) + plt.legend() + if args.title is not None: + plt.title(args.title) + if args.out is None: + plt.show() + else: + print(f'save curve to: {args.out}') + plt.savefig(args.out) + plt.cla() + + +def parse_args(): + parser = argparse.ArgumentParser(description='Analyze Json Log') + parser.add_argument( + 'json_logs', + type=str, + nargs='+', + help='path of train log in json format') + parser.add_argument( + '--keys', + type=str, + nargs='+', + default=['mIoU'], + help='the metric that you want to plot') + parser.add_argument('--title', type=str, help='title of figure') + parser.add_argument( + '--legend', + type=str, + nargs='+', + default=None, + help='legend of each plot') + parser.add_argument( + '--backend', type=str, default=None, help='backend of plt') + parser.add_argument( + '--style', type=str, default='dark', help='style of plt') + parser.add_argument('--out', type=str, default=None) + args = parser.parse_args() + return args + + +def load_json_logs(json_logs): + # load and convert json_logs to log_dict, key is step, value is a sub dict + # keys of sub dict is different metrics + # value of sub dict is a list of corresponding values of all iterations + log_dicts = [dict() for _ in json_logs] + prev_step = 0 + for json_log, log_dict in zip(json_logs, log_dicts): + with open(json_log) as log_file: + for line in log_file: + log = json.loads(line.strip()) + # the final step in json file is 0. + if 'step' in log and log['step'] != 0: + step = log['step'] + prev_step = step + else: + step = prev_step + if step not in log_dict: + log_dict[step] = defaultdict(list) + for k, v in log.items(): + log_dict[step][k].append(v) + return log_dicts + + +def main(): + args = parse_args() + json_logs = args.json_logs + for json_log in json_logs: + assert json_log.endswith('.json') + log_dicts = load_json_logs(json_logs) + plot_curve(log_dicts, args) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/analysis_tools/benchmark.py b/third-party/InterFormer/tools/analysis_tools/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..afaeabac85fa642b03c006b8a920c0d95d4cb400 --- /dev/null +++ b/third-party/InterFormer/tools/analysis_tools/benchmark.py @@ -0,0 +1,121 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import time + +import numpy as np +import torch +from mmengine import Config +from mmengine.fileio import dump +from mmengine.model.utils import revert_sync_batchnorm +from mmengine.registry import init_default_scope +from mmengine.runner import Runner, load_checkpoint +from mmengine.utils import mkdir_or_exist + +from mmseg.registry import MODELS + + +def parse_args(): + parser = argparse.ArgumentParser(description='MMSeg benchmark a model') + parser.add_argument('config', help='test config file path') + parser.add_argument('checkpoint', help='checkpoint file') + parser.add_argument( + '--log-interval', type=int, default=50, help='interval of logging') + parser.add_argument( + '--work-dir', + help=('if specified, the results will be dumped ' + 'into the directory as json')) + parser.add_argument('--repeat-times', type=int, default=1) + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cfg = Config.fromfile(args.config) + + init_default_scope(cfg.get('default_scope', 'mmseg')) + + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + if args.work_dir is not None: + mkdir_or_exist(osp.abspath(args.work_dir)) + json_file = osp.join(args.work_dir, f'fps_{timestamp}.json') + else: + # use config filename as default work_dir if cfg.work_dir is None + work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + mkdir_or_exist(osp.abspath(work_dir)) + json_file = osp.join(work_dir, f'fps_{timestamp}.json') + + repeat_times = args.repeat_times + # set cudnn_benchmark + torch.backends.cudnn.benchmark = False + cfg.model.pretrained = None + + benchmark_dict = dict(config=args.config, unit='img / s') + overall_fps_list = [] + cfg.test_dataloader.batch_size = 1 + for time_index in range(repeat_times): + print(f'Run {time_index + 1}:') + # build the dataloader + data_loader = Runner.build_dataloader(cfg.test_dataloader) + + # build the model and load checkpoint + cfg.model.train_cfg = None + model = MODELS.build(cfg.model) + + if 'checkpoint' in args and osp.exists(args.checkpoint): + load_checkpoint(model, args.checkpoint, map_location='cpu') + + if torch.cuda.is_available(): + model = model.cuda() + + model = revert_sync_batchnorm(model) + + model.eval() + + # the first several iterations may be very slow so skip them + num_warmup = 5 + pure_inf_time = 0 + total_iters = 200 + + # benchmark with 200 batches and take the average + for i, data in enumerate(data_loader): + data = model.data_preprocessor(data, True) + inputs = data['inputs'] + data_samples = data['data_samples'] + if torch.cuda.is_available(): + torch.cuda.synchronize() + start_time = time.perf_counter() + + with torch.no_grad(): + model(inputs, data_samples, mode='predict') + + if torch.cuda.is_available(): + torch.cuda.synchronize() + elapsed = time.perf_counter() - start_time + + if i >= num_warmup: + pure_inf_time += elapsed + if (i + 1) % args.log_interval == 0: + fps = (i + 1 - num_warmup) / pure_inf_time + print(f'Done image [{i + 1:<3}/ {total_iters}], ' + f'fps: {fps:.2f} img / s') + + if (i + 1) == total_iters: + fps = (i + 1 - num_warmup) / pure_inf_time + print(f'Overall fps: {fps:.2f} img / s\n') + benchmark_dict[f'overall_fps_{time_index + 1}'] = round(fps, 2) + overall_fps_list.append(fps) + break + benchmark_dict['average_fps'] = round(np.mean(overall_fps_list), 2) + benchmark_dict['fps_variance'] = round(np.var(overall_fps_list), 4) + print(f'Average fps of {repeat_times} evaluations: ' + f'{benchmark_dict["average_fps"]}') + print(f'The variance of {repeat_times} evaluations: ' + f'{benchmark_dict["fps_variance"]}') + dump(benchmark_dict, json_file, indent=4) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/analysis_tools/browse_dataset.py b/third-party/InterFormer/tools/analysis_tools/browse_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..925c14a8ab63b4e38950b6c6af58e37dba002a4c --- /dev/null +++ b/third-party/InterFormer/tools/analysis_tools/browse_dataset.py @@ -0,0 +1,77 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +from mmengine.config import Config, DictAction +from mmengine.utils import ProgressBar + +from mmseg.registry import DATASETS, VISUALIZERS +from mmseg.utils import register_all_modules + + +def parse_args(): + parser = argparse.ArgumentParser(description='Browse a dataset') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--output-dir', + default=None, + type=str, + help='If there is no display interface, you can save it') + parser.add_argument('--not-show', default=False, action='store_true') + parser.add_argument( + '--show-interval', + type=float, + default=2, + help='the interval of show (s)') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # register all modules in mmdet into the registries + register_all_modules() + + dataset = DATASETS.build(cfg.train_dataloader.dataset) + visualizer = VISUALIZERS.build(cfg.visualizer) + visualizer.dataset_meta = dataset.metainfo + + progress_bar = ProgressBar(len(dataset)) + for item in dataset: + img = item['inputs'].permute(1, 2, 0).numpy() + img = img[..., [2, 1, 0]] # bgr to rgb + data_sample = item['data_samples'].numpy() + img_path = osp.basename(item['data_samples'].img_path) + + out_file = osp.join( + args.output_dir, + osp.basename(img_path)) if args.output_dir is not None else None + + visualizer.add_datasample( + name=osp.basename(img_path), + image=img, + data_sample=data_sample, + draw_gt=True, + draw_pred=False, + wait_time=args.show_interval, + out_file=out_file, + show=not args.not_show) + progress_bar.update() + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/analysis_tools/confusion_matrix.py b/third-party/InterFormer/tools/analysis_tools/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..39756cdfdd2341e7e02f9de24077da880b6021c3 --- /dev/null +++ b/third-party/InterFormer/tools/analysis_tools/confusion_matrix.py @@ -0,0 +1,197 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os + +import matplotlib.pyplot as plt +import numpy as np +from matplotlib.ticker import MultipleLocator +from mmengine.config import Config, DictAction +from mmengine.registry import init_default_scope +from mmengine.utils import mkdir_or_exist, progressbar +from PIL import Image + +from mmseg.registry import DATASETS + +init_default_scope('mmseg') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Generate confusion matrix from segmentation results') + parser.add_argument('config', help='test config file path') + parser.add_argument( + 'prediction_path', help='prediction path where test folder result') + parser.add_argument( + 'save_dir', help='directory where confusion matrix will be saved') + parser.add_argument( + '--show', action='store_true', help='show confusion matrix') + parser.add_argument( + '--color-theme', + default='winter', + help='theme of the matrix color map') + parser.add_argument( + '--title', + default='Normalized Confusion Matrix', + help='title of the matrix color map') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def calculate_confusion_matrix(dataset, results): + """Calculate the confusion matrix. + + Args: + dataset (Dataset): Test or val dataset. + results (list[ndarray]): A list of segmentation results in each image. + """ + n = len(dataset.METAINFO['classes']) + confusion_matrix = np.zeros(shape=[n, n]) + assert len(dataset) == len(results) + ignore_index = dataset.ignore_index + reduce_zero_label = dataset.reduce_zero_label + prog_bar = progressbar.ProgressBar(len(results)) + for idx, per_img_res in enumerate(results): + res_segm = per_img_res + gt_segm = dataset[idx]['data_samples'] \ + .gt_sem_seg.data.squeeze().numpy().astype(np.uint8) + gt_segm, res_segm = gt_segm.flatten(), res_segm.flatten() + if reduce_zero_label: + gt_segm = gt_segm - 1 + to_ignore = gt_segm == ignore_index + + gt_segm, res_segm = gt_segm[~to_ignore], res_segm[~to_ignore] + inds = n * gt_segm + res_segm + mat = np.bincount(inds, minlength=n**2).reshape(n, n) + confusion_matrix += mat + prog_bar.update() + return confusion_matrix + + +def plot_confusion_matrix(confusion_matrix, + labels, + save_dir=None, + show=True, + title='Normalized Confusion Matrix', + color_theme='OrRd'): + """Draw confusion matrix with matplotlib. + + Args: + confusion_matrix (ndarray): The confusion matrix. + labels (list[str]): List of class names. + save_dir (str|optional): If set, save the confusion matrix plot to the + given path. Default: None. + show (bool): Whether to show the plot. Default: True. + title (str): Title of the plot. Default: `Normalized Confusion Matrix`. + color_theme (str): Theme of the matrix color map. Default: `winter`. + """ + # normalize the confusion matrix + per_label_sums = confusion_matrix.sum(axis=1)[:, np.newaxis] + confusion_matrix = \ + confusion_matrix.astype(np.float32) / per_label_sums * 100 + + num_classes = len(labels) + fig, ax = plt.subplots( + figsize=(2 * num_classes, 2 * num_classes * 0.8), dpi=300) + cmap = plt.get_cmap(color_theme) + im = ax.imshow(confusion_matrix, cmap=cmap) + colorbar = plt.colorbar(mappable=im, ax=ax) + colorbar.ax.tick_params(labelsize=20) # 设置 colorbar 标签的字体大小 + + title_font = {'weight': 'bold', 'size': 20} + ax.set_title(title, fontdict=title_font) + label_font = {'size': 40} + plt.ylabel('Ground Truth Label', fontdict=label_font) + plt.xlabel('Prediction Label', fontdict=label_font) + + # draw locator + xmajor_locator = MultipleLocator(1) + xminor_locator = MultipleLocator(0.5) + ax.xaxis.set_major_locator(xmajor_locator) + ax.xaxis.set_minor_locator(xminor_locator) + ymajor_locator = MultipleLocator(1) + yminor_locator = MultipleLocator(0.5) + ax.yaxis.set_major_locator(ymajor_locator) + ax.yaxis.set_minor_locator(yminor_locator) + + # draw grid + ax.grid(True, which='minor', linestyle='-') + + # draw label + ax.set_xticks(np.arange(num_classes)) + ax.set_yticks(np.arange(num_classes)) + ax.set_xticklabels(labels, fontsize=20) + ax.set_yticklabels(labels, fontsize=20) + + ax.tick_params( + axis='x', bottom=False, top=True, labelbottom=False, labeltop=True) + plt.setp( + ax.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor') + + # draw confusion matrix value + for i in range(num_classes): + for j in range(num_classes): + ax.text( + j, + i, + '{}%'.format( + round(confusion_matrix[i, j], 2 + ) if not np.isnan(confusion_matrix[i, j]) else -1), + ha='center', + va='center', + color='k', + size=20) + + ax.set_ylim(len(confusion_matrix) - 0.5, -0.5) # matplotlib>3.1.1 + + fig.tight_layout() + if save_dir is not None: + mkdir_or_exist(save_dir) + plt.savefig( + os.path.join(save_dir, 'confusion_matrix.png'), format='png') + if show: + plt.show() + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + results = [] + for img in sorted(os.listdir(args.prediction_path)): + img = os.path.join(args.prediction_path, img) + image = Image.open(img) + image = np.copy(image) + results.append(image) + + assert isinstance(results, list) + if isinstance(results[0], np.ndarray): + pass + else: + raise TypeError('invalid type of prediction results') + + dataset = DATASETS.build(cfg.test_dataloader.dataset) + confusion_matrix = calculate_confusion_matrix(dataset, results) + plot_confusion_matrix( + confusion_matrix, + dataset.METAINFO['classes'], + save_dir=args.save_dir, + show=args.show, + title=args.title, + color_theme=args.color_theme) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/analysis_tools/get_flops.py b/third-party/InterFormer/tools/analysis_tools/get_flops.py new file mode 100644 index 0000000000000000000000000000000000000000..78a73988d4e037094bffb23f7e70b24439c97799 --- /dev/null +++ b/third-party/InterFormer/tools/analysis_tools/get_flops.py @@ -0,0 +1,124 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import tempfile +from pathlib import Path + +import torch +from mmengine import Config, DictAction +from mmengine.logging import MMLogger +from mmengine.model import revert_sync_batchnorm +from mmengine.registry import init_default_scope + +from mmseg.models import BaseSegmentor +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample + +try: + from mmengine.analysis import get_model_complexity_info + from mmengine.analysis.print_helper import _format_size +except ImportError: + raise ImportError('Please upgrade mmengine >= 0.6.0 to use this script.') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Get the FLOPs of a segmentor') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--shape', + type=int, + nargs='+', + default=[2048, 1024], + help='input image size') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def inference(args: argparse.Namespace, logger: MMLogger) -> dict: + config_name = Path(args.config) + + if not config_name.exists(): + logger.error(f'Config file {config_name} does not exist') + + cfg: Config = Config.fromfile(config_name) + cfg.work_dir = tempfile.TemporaryDirectory().name + cfg.log_level = 'WARN' + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + init_default_scope(cfg.get('scope', 'mmseg')) + + if len(args.shape) == 1: + input_shape = (3, args.shape[0], args.shape[0]) + elif len(args.shape) == 2: + input_shape = (3, ) + tuple(args.shape) + else: + raise ValueError('invalid input shape') + result = {} + + model: BaseSegmentor = MODELS.build(cfg.model) + if hasattr(model, 'auxiliary_head'): + model.auxiliary_head = None + if torch.cuda.is_available(): + model.cuda() + model = revert_sync_batchnorm(model) + result['ori_shape'] = input_shape[-2:] + result['pad_shape'] = input_shape[-2:] + data_batch = { + 'inputs': [torch.rand(input_shape)], + 'data_samples': [SegDataSample(metainfo=result)] + } + data = model.data_preprocessor(data_batch) + model.eval() + if cfg.model.decode_head.type in ['MaskFormerHead', 'Mask2FormerHead']: + # TODO: Support MaskFormer and Mask2Former + raise NotImplementedError('MaskFormer and Mask2Former are not ' + 'supported yet.') + outputs = get_model_complexity_info( + model, + input_shape=None, + inputs=data['inputs'], + show_table=False, + show_arch=False) + result['flops'] = _format_size(outputs['flops']) + result['params'] = _format_size(outputs['params']) + result['compute_type'] = 'direct: randomly generate a picture' + return result + + +def main(): + + args = parse_args() + logger = MMLogger.get_instance(name='MMLogger') + + result = inference(args, logger) + split_line = '=' * 30 + ori_shape = result['ori_shape'] + pad_shape = result['pad_shape'] + flops = result['flops'] + params = result['params'] + compute_type = result['compute_type'] + + if pad_shape != ori_shape: + print(f'{split_line}\nUse size divisor set input shape ' + f'from {ori_shape} to {pad_shape}') + print(f'{split_line}\nCompute type: {compute_type}\n' + f'Input shape: {pad_shape}\nFlops: {flops}\n' + f'Params: {params}\n{split_line}') + print('!!!Please be cautious if you use the results in papers. ' + 'You may need to check if all ops are supported and verify ' + 'that the flops computation is correct.') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/analysis_tools/visualization_cam.py b/third-party/InterFormer/tools/analysis_tools/visualization_cam.py new file mode 100644 index 0000000000000000000000000000000000000000..00cdb3e04ab1f9000844ace781bc138f230d4630 --- /dev/null +++ b/third-party/InterFormer/tools/analysis_tools/visualization_cam.py @@ -0,0 +1,127 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Use the pytorch-grad-cam tool to visualize Class Activation Maps (CAM). + +requirement: pip install grad-cam +""" + +from argparse import ArgumentParser + +import numpy as np +import torch +import torch.nn.functional as F +from mmengine import Config +from mmengine.model import revert_sync_batchnorm +from PIL import Image +from pytorch_grad_cam import GradCAM +from pytorch_grad_cam.utils.image import preprocess_image, show_cam_on_image + +from mmseg.apis import inference_model, init_model, show_result_pyplot +from mmseg.utils import register_all_modules + + +class SemanticSegmentationTarget: + """wrap the model. + + requirement: pip install grad-cam + + Args: + category (int): Visualization class. + mask (ndarray): Mask of class. + size (tuple): Image size. + """ + + def __init__(self, category, mask, size): + self.category = category + self.mask = torch.from_numpy(mask) + self.size = size + if torch.cuda.is_available(): + self.mask = self.mask.cuda() + + def __call__(self, model_output): + model_output = torch.unsqueeze(model_output, dim=0) + model_output = F.interpolate( + model_output, size=self.size, mode='bilinear') + model_output = torch.squeeze(model_output, dim=0) + + return (model_output[self.category, :, :] * self.mask).sum() + + +def main(): + parser = ArgumentParser() + parser.add_argument('img', help='Image file') + parser.add_argument('config', help='Config file') + parser.add_argument('checkpoint', help='Checkpoint file') + parser.add_argument( + '--out-file', + default='prediction.png', + help='Path to output prediction file') + parser.add_argument( + '--cam-file', default='vis_cam.png', help='Path to output cam file') + parser.add_argument( + '--target-layers', + default='backbone.layer4[2]', + help='Target layers to visualize CAM') + parser.add_argument( + '--category-index', default='7', help='Category to visualize CAM') + parser.add_argument( + '--device', default='cuda:0', help='Device used for inference') + args = parser.parse_args() + + # build the model from a config file and a checkpoint file + register_all_modules() + model = init_model(args.config, args.checkpoint, device=args.device) + if args.device == 'cpu': + model = revert_sync_batchnorm(model) + + # test a single image + result = inference_model(model, args.img) + + # show the results + show_result_pyplot( + model, + args.img, + result, + draw_gt=False, + show=False if args.out_file is not None else True, + out_file=args.out_file) + + # result data conversion + prediction_data = result.pred_sem_seg.data + pre_np_data = prediction_data.cpu().numpy().squeeze(0) + + target_layers = args.target_layers + target_layers = [eval(f'model.{target_layers}')] + + category = int(args.category_index) + mask_float = np.float32(pre_np_data == category) + + # data processing + image = np.array(Image.open(args.img).convert('RGB')) + height, width = image.shape[0], image.shape[1] + rgb_img = np.float32(image) / 255 + config = Config.fromfile(args.config) + image_mean = config.data_preprocessor['mean'] + image_std = config.data_preprocessor['std'] + input_tensor = preprocess_image( + rgb_img, + mean=[x / 255 for x in image_mean], + std=[x / 255 for x in image_std]) + + # Grad CAM(Class Activation Maps) + # Can also be LayerCAM, XGradCAM, GradCAMPlusPlus, EigenCAM, EigenGradCAM + targets = [ + SemanticSegmentationTarget(category, mask_float, (height, width)) + ] + with GradCAM( + model=model, + target_layers=target_layers, + use_cuda=torch.cuda.is_available()) as cam: + grayscale_cam = cam(input_tensor=input_tensor, targets=targets)[0, :] + cam_image = show_cam_on_image(rgb_img, grayscale_cam, use_rgb=True) + + # save cam file + Image.fromarray(cam_image).save(args.cam_file) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/chase_db1.py b/third-party/InterFormer/tools/dataset_converters/chase_db1.py new file mode 100644 index 0000000000000000000000000000000000000000..f4fefbd77435c5745d290269cd00f67fda604455 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/chase_db1.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +from mmengine.utils import mkdir_or_exist + +CHASE_DB1_LEN = 28 * 3 +TRAINING_LEN = 60 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert CHASE_DB1 dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='path of CHASEDB1.zip') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'CHASE_DB1') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + print('Extracting CHASEDB1.zip...') + zip_file = zipfile.ZipFile(dataset_path) + zip_file.extractall(tmp_dir) + + print('Generating training dataset...') + + assert len(os.listdir(tmp_dir)) == CHASE_DB1_LEN, \ + f'len(os.listdir(tmp_dir)) != {CHASE_DB1_LEN}' + + for img_name in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, img_name)) + if osp.splitext(img_name)[1] == '.jpg': + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(img_name)[0] + '.png')) + else: + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(img_name)[0] + '.png')) + + for img_name in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, img_name)) + if osp.splitext(img_name)[1] == '.jpg': + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(img_name)[0] + '.png')) + else: + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/cityscapes.py b/third-party/InterFormer/tools/dataset_converters/cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..0d6a80135d906db7330a736ccbcc908e0a6309c6 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/cityscapes.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +from cityscapesscripts.preparation.json2labelImg import json2labelImg +from mmengine.utils import (mkdir_or_exist, scandir, track_parallel_progress, + track_progress) + + +def convert_json_to_label(json_file): + label_file = json_file.replace('_polygons.json', '_labelTrainIds.png') + json2labelImg(json_file, label_file, 'trainIds') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert Cityscapes annotations to TrainIds') + parser.add_argument('cityscapes_path', help='cityscapes data path') + parser.add_argument('--gt-dir', default='gtFine', type=str) + parser.add_argument('-o', '--out-dir', help='output path') + parser.add_argument( + '--nproc', default=1, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cityscapes_path = args.cityscapes_path + out_dir = args.out_dir if args.out_dir else cityscapes_path + mkdir_or_exist(out_dir) + + gt_dir = osp.join(cityscapes_path, args.gt_dir) + + poly_files = [] + for poly in scandir(gt_dir, '_polygons.json', recursive=True): + poly_file = osp.join(gt_dir, poly) + poly_files.append(poly_file) + if args.nproc > 1: + track_parallel_progress(convert_json_to_label, poly_files, args.nproc) + else: + track_progress(convert_json_to_label, poly_files) + + split_names = ['train', 'val', 'test'] + + for split in split_names: + filenames = [] + for poly in scandir( + osp.join(gt_dir, split), '_polygons.json', recursive=True): + filenames.append(poly.replace('_gtFine_polygons.json', '')) + with open(osp.join(out_dir, f'{split}.txt'), 'w') as f: + f.writelines(f + '\n' for f in filenames) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/coco_stuff10k.py b/third-party/InterFormer/tools/dataset_converters/coco_stuff10k.py new file mode 100644 index 0000000000000000000000000000000000000000..920127ee10fc09b76f8e2344ecdf3b7800d51802 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/coco_stuff10k.py @@ -0,0 +1,308 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import shutil +from functools import partial + +import numpy as np +from mmengine.utils import (mkdir_or_exist, track_parallel_progress, + track_progress) +from PIL import Image +from scipy.io import loadmat + +COCO_LEN = 10000 + +clsID_to_trID = { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + 10: 10, + 11: 11, + 13: 12, + 14: 13, + 15: 14, + 16: 15, + 17: 16, + 18: 17, + 19: 18, + 20: 19, + 21: 20, + 22: 21, + 23: 22, + 24: 23, + 25: 24, + 27: 25, + 28: 26, + 31: 27, + 32: 28, + 33: 29, + 34: 30, + 35: 31, + 36: 32, + 37: 33, + 38: 34, + 39: 35, + 40: 36, + 41: 37, + 42: 38, + 43: 39, + 44: 40, + 46: 41, + 47: 42, + 48: 43, + 49: 44, + 50: 45, + 51: 46, + 52: 47, + 53: 48, + 54: 49, + 55: 50, + 56: 51, + 57: 52, + 58: 53, + 59: 54, + 60: 55, + 61: 56, + 62: 57, + 63: 58, + 64: 59, + 65: 60, + 67: 61, + 70: 62, + 72: 63, + 73: 64, + 74: 65, + 75: 66, + 76: 67, + 77: 68, + 78: 69, + 79: 70, + 80: 71, + 81: 72, + 82: 73, + 84: 74, + 85: 75, + 86: 76, + 87: 77, + 88: 78, + 89: 79, + 90: 80, + 92: 81, + 93: 82, + 94: 83, + 95: 84, + 96: 85, + 97: 86, + 98: 87, + 99: 88, + 100: 89, + 101: 90, + 102: 91, + 103: 92, + 104: 93, + 105: 94, + 106: 95, + 107: 96, + 108: 97, + 109: 98, + 110: 99, + 111: 100, + 112: 101, + 113: 102, + 114: 103, + 115: 104, + 116: 105, + 117: 106, + 118: 107, + 119: 108, + 120: 109, + 121: 110, + 122: 111, + 123: 112, + 124: 113, + 125: 114, + 126: 115, + 127: 116, + 128: 117, + 129: 118, + 130: 119, + 131: 120, + 132: 121, + 133: 122, + 134: 123, + 135: 124, + 136: 125, + 137: 126, + 138: 127, + 139: 128, + 140: 129, + 141: 130, + 142: 131, + 143: 132, + 144: 133, + 145: 134, + 146: 135, + 147: 136, + 148: 137, + 149: 138, + 150: 139, + 151: 140, + 152: 141, + 153: 142, + 154: 143, + 155: 144, + 156: 145, + 157: 146, + 158: 147, + 159: 148, + 160: 149, + 161: 150, + 162: 151, + 163: 152, + 164: 153, + 165: 154, + 166: 155, + 167: 156, + 168: 157, + 169: 158, + 170: 159, + 171: 160, + 172: 161, + 173: 162, + 174: 163, + 175: 164, + 176: 165, + 177: 166, + 178: 167, + 179: 168, + 180: 169, + 181: 170, + 182: 171 +} + + +def convert_to_trainID(tuple_path, in_img_dir, in_ann_dir, out_img_dir, + out_mask_dir, is_train): + imgpath, maskpath = tuple_path + shutil.copyfile( + osp.join(in_img_dir, imgpath), + osp.join(out_img_dir, 'train2014', imgpath) if is_train else osp.join( + out_img_dir, 'test2014', imgpath)) + annotate = loadmat(osp.join(in_ann_dir, maskpath)) + mask = annotate['S'].astype(np.uint8) + mask_copy = mask.copy() + for clsID, trID in clsID_to_trID.items(): + mask_copy[mask == clsID] = trID + seg_filename = osp.join(out_mask_dir, 'train2014', + maskpath.split('.')[0] + + '_labelTrainIds.png') if is_train else osp.join( + out_mask_dir, 'test2014', + maskpath.split('.')[0] + '_labelTrainIds.png') + Image.fromarray(mask_copy).save(seg_filename, 'PNG') + + +def generate_coco_list(folder): + train_list = osp.join(folder, 'imageLists', 'train.txt') + test_list = osp.join(folder, 'imageLists', 'test.txt') + train_paths = [] + test_paths = [] + + with open(train_list) as f: + for filename in f: + basename = filename.strip() + imgpath = basename + '.jpg' + maskpath = basename + '.mat' + train_paths.append((imgpath, maskpath)) + + with open(test_list) as f: + for filename in f: + basename = filename.strip() + imgpath = basename + '.jpg' + maskpath = basename + '.mat' + test_paths.append((imgpath, maskpath)) + + return train_paths, test_paths + + +def parse_args(): + parser = argparse.ArgumentParser( + description=\ + 'Convert COCO Stuff 10k annotations to mmsegmentation format') # noqa + parser.add_argument('coco_path', help='coco stuff path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=16, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + coco_path = args.coco_path + nproc = args.nproc + + out_dir = args.out_dir or coco_path + out_img_dir = osp.join(out_dir, 'images') + out_mask_dir = osp.join(out_dir, 'annotations') + + mkdir_or_exist(osp.join(out_img_dir, 'train2014')) + mkdir_or_exist(osp.join(out_img_dir, 'test2014')) + mkdir_or_exist(osp.join(out_mask_dir, 'train2014')) + mkdir_or_exist(osp.join(out_mask_dir, 'test2014')) + + train_list, test_list = generate_coco_list(coco_path) + assert (len(train_list) + + len(test_list)) == COCO_LEN, 'Wrong length of list {} & {}'.format( + len(train_list), len(test_list)) + + if args.nproc > 1: + track_parallel_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=True), + train_list, + nproc=nproc) + track_parallel_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=False), + test_list, + nproc=nproc) + else: + track_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=True), train_list) + track_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=False), test_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/coco_stuff164k.py b/third-party/InterFormer/tools/dataset_converters/coco_stuff164k.py new file mode 100644 index 0000000000000000000000000000000000000000..a13114ab1e0c37675369b2e9ba065cbfb2dca1e7 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/coco_stuff164k.py @@ -0,0 +1,265 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import shutil +from functools import partial +from glob import glob + +import numpy as np +from mmengine.utils import (mkdir_or_exist, track_parallel_progress, + track_progress) +from PIL import Image + +COCO_LEN = 123287 + +clsID_to_trID = { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + 10: 10, + 12: 11, + 13: 12, + 14: 13, + 15: 14, + 16: 15, + 17: 16, + 18: 17, + 19: 18, + 20: 19, + 21: 20, + 22: 21, + 23: 22, + 24: 23, + 26: 24, + 27: 25, + 30: 26, + 31: 27, + 32: 28, + 33: 29, + 34: 30, + 35: 31, + 36: 32, + 37: 33, + 38: 34, + 39: 35, + 40: 36, + 41: 37, + 42: 38, + 43: 39, + 45: 40, + 46: 41, + 47: 42, + 48: 43, + 49: 44, + 50: 45, + 51: 46, + 52: 47, + 53: 48, + 54: 49, + 55: 50, + 56: 51, + 57: 52, + 58: 53, + 59: 54, + 60: 55, + 61: 56, + 62: 57, + 63: 58, + 64: 59, + 66: 60, + 69: 61, + 71: 62, + 72: 63, + 73: 64, + 74: 65, + 75: 66, + 76: 67, + 77: 68, + 78: 69, + 79: 70, + 80: 71, + 81: 72, + 83: 73, + 84: 74, + 85: 75, + 86: 76, + 87: 77, + 88: 78, + 89: 79, + 91: 80, + 92: 81, + 93: 82, + 94: 83, + 95: 84, + 96: 85, + 97: 86, + 98: 87, + 99: 88, + 100: 89, + 101: 90, + 102: 91, + 103: 92, + 104: 93, + 105: 94, + 106: 95, + 107: 96, + 108: 97, + 109: 98, + 110: 99, + 111: 100, + 112: 101, + 113: 102, + 114: 103, + 115: 104, + 116: 105, + 117: 106, + 118: 107, + 119: 108, + 120: 109, + 121: 110, + 122: 111, + 123: 112, + 124: 113, + 125: 114, + 126: 115, + 127: 116, + 128: 117, + 129: 118, + 130: 119, + 131: 120, + 132: 121, + 133: 122, + 134: 123, + 135: 124, + 136: 125, + 137: 126, + 138: 127, + 139: 128, + 140: 129, + 141: 130, + 142: 131, + 143: 132, + 144: 133, + 145: 134, + 146: 135, + 147: 136, + 148: 137, + 149: 138, + 150: 139, + 151: 140, + 152: 141, + 153: 142, + 154: 143, + 155: 144, + 156: 145, + 157: 146, + 158: 147, + 159: 148, + 160: 149, + 161: 150, + 162: 151, + 163: 152, + 164: 153, + 165: 154, + 166: 155, + 167: 156, + 168: 157, + 169: 158, + 170: 159, + 171: 160, + 172: 161, + 173: 162, + 174: 163, + 175: 164, + 176: 165, + 177: 166, + 178: 167, + 179: 168, + 180: 169, + 181: 170, + 255: 255 +} + + +def convert_to_trainID(maskpath, out_mask_dir, is_train): + mask = np.array(Image.open(maskpath)) + mask_copy = mask.copy() + for clsID, trID in clsID_to_trID.items(): + mask_copy[mask == clsID] = trID + seg_filename = osp.join( + out_mask_dir, 'train2017', + osp.basename(maskpath).split('.')[0] + + '_labelTrainIds.png') if is_train else osp.join( + out_mask_dir, 'val2017', + osp.basename(maskpath).split('.')[0] + '_labelTrainIds.png') + Image.fromarray(mask_copy).save(seg_filename, 'PNG') + + +def parse_args(): + parser = argparse.ArgumentParser( + description=\ + 'Convert COCO Stuff 164k annotations to mmsegmentation format') # noqa + parser.add_argument('coco_path', help='coco stuff path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=16, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + coco_path = args.coco_path + nproc = args.nproc + + out_dir = args.out_dir or coco_path + out_img_dir = osp.join(out_dir, 'images') + out_mask_dir = osp.join(out_dir, 'annotations') + + mkdir_or_exist(osp.join(out_mask_dir, 'train2017')) + mkdir_or_exist(osp.join(out_mask_dir, 'val2017')) + + if out_dir != coco_path: + shutil.copytree(osp.join(coco_path, 'images'), out_img_dir) + + train_list = glob(osp.join(coco_path, 'annotations', 'train2017', '*.png')) + train_list = [file for file in train_list if '_labelTrainIds' not in file] + test_list = glob(osp.join(coco_path, 'annotations', 'val2017', '*.png')) + test_list = [file for file in test_list if '_labelTrainIds' not in file] + assert (len(train_list) + + len(test_list)) == COCO_LEN, 'Wrong length of list {} & {}'.format( + len(train_list), len(test_list)) + + if args.nproc > 1: + track_parallel_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=True), + train_list, + nproc=nproc) + track_parallel_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=False), + test_list, + nproc=nproc) + else: + track_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=True), + train_list) + track_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=False), + test_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/drive.py b/third-party/InterFormer/tools/dataset_converters/drive.py new file mode 100644 index 0000000000000000000000000000000000000000..076fd05a2029216e0f1a1494610181fdaa7fbef9 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/drive.py @@ -0,0 +1,114 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import cv2 +import mmcv +from mmengine.utils import mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert DRIVE dataset to mmsegmentation format') + parser.add_argument( + 'training_path', help='the training part of DRIVE dataset') + parser.add_argument( + 'testing_path', help='the testing part of DRIVE dataset') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + training_path = args.training_path + testing_path = args.testing_path + if args.out_dir is None: + out_dir = osp.join('data', 'DRIVE') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + print('Extracting training.zip...') + zip_file = zipfile.ZipFile(training_path) + zip_file.extractall(tmp_dir) + + print('Generating training dataset...') + now_dir = osp.join(tmp_dir, 'training', 'images') + for img_name in os.listdir(now_dir): + img = mmcv.imread(osp.join(now_dir, img_name)) + mmcv.imwrite( + img, + osp.join( + out_dir, 'images', 'training', + osp.splitext(img_name)[0].replace('_training', '') + + '.png')) + + now_dir = osp.join(tmp_dir, 'training', '1st_manual') + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(img_name)[0] + '.png')) + + print('Extracting test.zip...') + zip_file = zipfile.ZipFile(testing_path) + zip_file.extractall(tmp_dir) + + print('Generating validation dataset...') + now_dir = osp.join(tmp_dir, 'test', 'images') + for img_name in os.listdir(now_dir): + img = mmcv.imread(osp.join(now_dir, img_name)) + mmcv.imwrite( + img, + osp.join( + out_dir, 'images', 'validation', + osp.splitext(img_name)[0].replace('_test', '') + '.png')) + + now_dir = osp.join(tmp_dir, 'test', '1st_manual') + if osp.exists(now_dir): + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + now_dir = osp.join(tmp_dir, 'test', '2nd_manual') + if osp.exists(now_dir): + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/hrf.py b/third-party/InterFormer/tools/dataset_converters/hrf.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfd80c9ee42e3b5cba4a12a6c8b32ddbb2f1f11 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/hrf.py @@ -0,0 +1,112 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +from mmengine.utils import mkdir_or_exist + +HRF_LEN = 15 +TRAINING_LEN = 5 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert HRF dataset to mmsegmentation format') + parser.add_argument('healthy_path', help='the path of healthy.zip') + parser.add_argument( + 'healthy_manualsegm_path', help='the path of healthy_manualsegm.zip') + parser.add_argument('glaucoma_path', help='the path of glaucoma.zip') + parser.add_argument( + 'glaucoma_manualsegm_path', help='the path of glaucoma_manualsegm.zip') + parser.add_argument( + 'diabetic_retinopathy_path', + help='the path of diabetic_retinopathy.zip') + parser.add_argument( + 'diabetic_retinopathy_manualsegm_path', + help='the path of diabetic_retinopathy_manualsegm.zip') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + images_path = [ + args.healthy_path, args.glaucoma_path, args.diabetic_retinopathy_path + ] + annotations_path = [ + args.healthy_manualsegm_path, args.glaucoma_manualsegm_path, + args.diabetic_retinopathy_manualsegm_path + ] + if args.out_dir is None: + out_dir = osp.join('data', 'HRF') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + print('Generating images...') + for now_path in images_path: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(now_path) + zip_file.extractall(tmp_dir) + + assert len(os.listdir(tmp_dir)) == HRF_LEN, \ + f'len(os.listdir(tmp_dir)) != {HRF_LEN}' + + for filename in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(filename)[0] + '.png')) + for filename in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Generating annotations...') + for now_path in annotations_path: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(now_path) + zip_file.extractall(tmp_dir) + + assert len(os.listdir(tmp_dir)) == HRF_LEN, \ + f'len(os.listdir(tmp_dir)) != {HRF_LEN}' + + for filename in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + for filename in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/isaid.py b/third-party/InterFormer/tools/dataset_converters/isaid.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5ccd9c776e9621c261e6d168bf6aa4f7b451f6 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/isaid.py @@ -0,0 +1,246 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import os +import os.path as osp +import shutil +import tempfile +import zipfile + +import mmcv +import numpy as np +from mmengine.utils import ProgressBar, mkdir_or_exist +from PIL import Image + +iSAID_palette = \ + { + 0: (0, 0, 0), + 1: (0, 0, 63), + 2: (0, 63, 63), + 3: (0, 63, 0), + 4: (0, 63, 127), + 5: (0, 63, 191), + 6: (0, 63, 255), + 7: (0, 127, 63), + 8: (0, 127, 127), + 9: (0, 0, 127), + 10: (0, 0, 191), + 11: (0, 0, 255), + 12: (0, 191, 127), + 13: (0, 127, 191), + 14: (0, 127, 255), + 15: (0, 100, 155) + } + +iSAID_invert_palette = {v: k for k, v in iSAID_palette.items()} + + +def iSAID_convert_from_color(arr_3d, palette=iSAID_invert_palette): + """RGB-color encoding to grayscale labels.""" + arr_2d = np.zeros((arr_3d.shape[0], arr_3d.shape[1]), dtype=np.uint8) + + for c, i in palette.items(): + m = np.all(arr_3d == np.array(c).reshape(1, 1, 3), axis=2) + arr_2d[m] = i + + return arr_2d + + +def slide_crop_image(src_path, out_dir, mode, patch_H, patch_W, overlap): + img = np.asarray(Image.open(src_path).convert('RGB')) + + img_H, img_W, _ = img.shape + + if img_H < patch_H and img_W > patch_W: + + img = mmcv.impad(img, shape=(patch_H, img_W), pad_val=0) + + img_H, img_W, _ = img.shape + + elif img_H > patch_H and img_W < patch_W: + + img = mmcv.impad(img, shape=(img_H, patch_W), pad_val=0) + + img_H, img_W, _ = img.shape + + elif img_H < patch_H and img_W < patch_W: + + img = mmcv.impad(img, shape=(patch_H, patch_W), pad_val=0) + + img_H, img_W, _ = img.shape + + for x in range(0, img_W, patch_W - overlap): + for y in range(0, img_H, patch_H - overlap): + x_str = x + x_end = x + patch_W + if x_end > img_W: + diff_x = x_end - img_W + x_str -= diff_x + x_end = img_W + y_str = y + y_end = y + patch_H + if y_end > img_H: + diff_y = y_end - img_H + y_str -= diff_y + y_end = img_H + + img_patch = img[y_str:y_end, x_str:x_end, :] + img_patch = Image.fromarray(img_patch.astype(np.uint8)) + image = osp.basename(src_path).split('.')[0] + '_' + str( + y_str) + '_' + str(y_end) + '_' + str(x_str) + '_' + str( + x_end) + '.png' + # print(image) + save_path_image = osp.join(out_dir, 'img_dir', mode, str(image)) + img_patch.save(save_path_image, format='BMP') + + +def slide_crop_label(src_path, out_dir, mode, patch_H, patch_W, overlap): + label = mmcv.imread(src_path, channel_order='rgb') + label = iSAID_convert_from_color(label) + img_H, img_W = label.shape + + if img_H < patch_H and img_W > patch_W: + + label = mmcv.impad(label, shape=(patch_H, img_W), pad_val=255) + + img_H = patch_H + + elif img_H > patch_H and img_W < patch_W: + + label = mmcv.impad(label, shape=(img_H, patch_W), pad_val=255) + + img_W = patch_W + + elif img_H < patch_H and img_W < patch_W: + + label = mmcv.impad(label, shape=(patch_H, patch_W), pad_val=255) + + img_H = patch_H + img_W = patch_W + + for x in range(0, img_W, patch_W - overlap): + for y in range(0, img_H, patch_H - overlap): + x_str = x + x_end = x + patch_W + if x_end > img_W: + diff_x = x_end - img_W + x_str -= diff_x + x_end = img_W + y_str = y + y_end = y + patch_H + if y_end > img_H: + diff_y = y_end - img_H + y_str -= diff_y + y_end = img_H + + lab_patch = label[y_str:y_end, x_str:x_end] + lab_patch = Image.fromarray(lab_patch.astype(np.uint8), mode='P') + + image = osp.basename(src_path).split('.')[0].split( + '_')[0] + '_' + str(y_str) + '_' + str(y_end) + '_' + str( + x_str) + '_' + str(x_end) + '_instance_color_RGB' + '.png' + lab_patch.save(osp.join(out_dir, 'ann_dir', mode, str(image))) + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert iSAID dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='iSAID folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + + parser.add_argument( + '--patch_width', + default=896, + type=int, + help='Width of the cropped image patch') + parser.add_argument( + '--patch_height', + default=896, + type=int, + help='Height of the cropped image patch') + parser.add_argument( + '--overlap_area', default=384, type=int, help='Overlap area') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + # image patch width and height + patch_H, patch_W = args.patch_width, args.patch_height + + overlap = args.overlap_area # overlap area + + if args.out_dir is None: + out_dir = osp.join('data', 'iSAID') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'test')) + + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'test')) + + assert os.path.exists(os.path.join(dataset_path, 'train')), \ + f'train is not in {dataset_path}' + assert os.path.exists(os.path.join(dataset_path, 'val')), \ + f'val is not in {dataset_path}' + assert os.path.exists(os.path.join(dataset_path, 'test')), \ + f'test is not in {dataset_path}' + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for dataset_mode in ['train', 'val', 'test']: + + # for dataset_mode in [ 'test']: + print(f'Extracting {dataset_mode}ing.zip...') + img_zipp_list = glob.glob( + os.path.join(dataset_path, dataset_mode, 'images', '*.zip')) + print('Find the data', img_zipp_list) + for img_zipp in img_zipp_list: + zip_file = zipfile.ZipFile(img_zipp) + zip_file.extractall(os.path.join(tmp_dir, dataset_mode, 'img')) + src_path_list = glob.glob( + os.path.join(tmp_dir, dataset_mode, 'img', 'images', '*.png')) + + src_prog_bar = ProgressBar(len(src_path_list)) + for i, img_path in enumerate(src_path_list): + if dataset_mode != 'test': + slide_crop_image(img_path, out_dir, dataset_mode, patch_H, + patch_W, overlap) + + else: + shutil.move(img_path, + os.path.join(out_dir, 'img_dir', dataset_mode)) + src_prog_bar.update() + + if dataset_mode != 'test': + label_zipp_list = glob.glob( + os.path.join(dataset_path, dataset_mode, 'Semantic_masks', + '*.zip')) + for label_zipp in label_zipp_list: + zip_file = zipfile.ZipFile(label_zipp) + zip_file.extractall( + os.path.join(tmp_dir, dataset_mode, 'lab')) + + lab_path_list = glob.glob( + os.path.join(tmp_dir, dataset_mode, 'lab', 'images', + '*.png')) + lab_prog_bar = ProgressBar(len(lab_path_list)) + for i, lab_path in enumerate(lab_path_list): + slide_crop_label(lab_path, out_dir, dataset_mode, patch_H, + patch_W, overlap) + lab_prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/levircd.py b/third-party/InterFormer/tools/dataset_converters/levircd.py new file mode 100644 index 0000000000000000000000000000000000000000..8717f3e856ba3f171b511f34d0217e1fda87ccb6 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/levircd.py @@ -0,0 +1,99 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import math +import os +import os.path as osp + +import mmcv +import numpy as np +from mmengine.utils import ProgressBar + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert levir-cd dataset to mmsegmentation format') + parser.add_argument('--dataset_path', help='potsdam folder path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--clip_size', + type=int, + help='clipped size of image after preparation', + default=256) + parser.add_argument( + '--stride_size', + type=int, + help='stride of clipping original images', + default=256) + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + input_folder = args.dataset_path + png_files = glob.glob( + os.path.join(input_folder, '**/*.png'), recursive=True) + output_folder = args.out_dir + prog_bar = ProgressBar(len(png_files)) + for png_file in png_files: + new_path = os.path.join( + output_folder, + os.path.relpath(os.path.dirname(png_file), input_folder)) + os.makedirs(os.path.dirname(new_path), exist_ok=True) + label = False + if 'label' in png_file: + label = True + clip_big_image(png_file, new_path, args, label) + prog_bar.update() + + +def clip_big_image(image_path, clip_save_dir, args, to_label=False): + image = mmcv.imread(image_path) + + h, w, c = image.shape + clip_size = args.clip_size + stride_size = args.stride_size + + num_rows = math.ceil((h - clip_size) / stride_size) if math.ceil( + (h - clip_size) / + stride_size) * stride_size + clip_size >= h else math.ceil( + (h - clip_size) / stride_size) + 1 + num_cols = math.ceil((w - clip_size) / stride_size) if math.ceil( + (w - clip_size) / + stride_size) * stride_size + clip_size >= w else math.ceil( + (w - clip_size) / stride_size) + 1 + + x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1)) + xmin = x * clip_size + ymin = y * clip_size + + xmin = xmin.ravel() + ymin = ymin.ravel() + xmin_offset = np.where(xmin + clip_size > w, w - xmin - clip_size, + np.zeros_like(xmin)) + ymin_offset = np.where(ymin + clip_size > h, h - ymin - clip_size, + np.zeros_like(ymin)) + boxes = np.stack([ + xmin + xmin_offset, ymin + ymin_offset, + np.minimum(xmin + clip_size, w), + np.minimum(ymin + clip_size, h) + ], + axis=1) + + if to_label: + image[image == 255] = 1 + image = image[:, :, 0] + for box in boxes: + start_x, start_y, end_x, end_y = box + clipped_image = image[start_y:end_y, start_x:end_x] \ + if to_label else image[start_y:end_y, start_x:end_x, :] + idx = osp.basename(image_path).split('.')[0] + mmcv.imwrite( + clipped_image.astype(np.uint8), + osp.join(clip_save_dir, + f'{idx}_{start_x}_{start_y}_{end_x}_{end_y}.png')) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/loveda.py b/third-party/InterFormer/tools/dataset_converters/loveda.py new file mode 100644 index 0000000000000000000000000000000000000000..5b0ef4bb8bbd07f60dfc0397e9659f0200b96f5d --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/loveda.py @@ -0,0 +1,73 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import shutil +import tempfile +import zipfile + +from mmengine.utils import mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert LoveDA dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='LoveDA folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'loveDA') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'img_dir')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'test')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + assert 'Train.zip' in os.listdir(dataset_path), \ + f'Train.zip is not in {dataset_path}' + assert 'Val.zip' in os.listdir(dataset_path), \ + f'Val.zip is not in {dataset_path}' + assert 'Test.zip' in os.listdir(dataset_path), \ + f'Test.zip is not in {dataset_path}' + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for dataset in ['Train', 'Val', 'Test']: + zip_file = zipfile.ZipFile( + os.path.join(dataset_path, dataset + '.zip')) + zip_file.extractall(tmp_dir) + data_type = dataset.lower() + for location in ['Rural', 'Urban']: + for image_type in ['images_png', 'masks_png']: + if image_type == 'images_png': + dst = osp.join(out_dir, 'img_dir', data_type) + else: + dst = osp.join(out_dir, 'ann_dir', data_type) + if dataset == 'Test' and image_type == 'masks_png': + continue + else: + src_dir = osp.join(tmp_dir, dataset, location, + image_type) + src_lst = os.listdir(src_dir) + for file in src_lst: + shutil.move(osp.join(src_dir, file), dst) + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/nyu.py b/third-party/InterFormer/tools/dataset_converters/nyu.py new file mode 100644 index 0000000000000000000000000000000000000000..49e09e7af6844b709e681f6d9f4df14ed547a00c --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/nyu.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import shutil +import tempfile +import zipfile + +from mmengine.utils import mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert NYU Depth dataset to mmsegmentation format') + parser.add_argument('raw_data', help='the path of raw data') + parser.add_argument( + '-o', '--out_dir', help='output path', default='./data/nyu') + args = parser.parse_args() + return args + + +def reorganize(raw_data_dir: str, out_dir: str): + """Reorganize NYU Depth dataset files into the required directory + structure. + + Args: + raw_data_dir (str): Path to the raw data directory. + out_dir (str): Output directory for the organized dataset. + """ + + def move_data(data_list, dst_prefix, fname_func): + """Move data files from source to destination directory. + + Args: + data_list (list): List of data file paths. + dst_prefix (str): Prefix to be added to destination paths. + fname_func (callable): Function to process file names + """ + for data_item in data_list: + data_item = data_item.strip().strip('/') + new_item = fname_func(data_item) + shutil.move( + osp.join(raw_data_dir, data_item), + osp.join(out_dir, dst_prefix, new_item)) + + def process_phase(phase): + """Process a dataset phase (e.g., 'train' or 'test').""" + with open(osp.join(raw_data_dir, f'nyu_{phase}.txt')) as f: + data = filter(lambda x: len(x.strip()) > 0, f.readlines()) + data = map(lambda x: x.split()[:2], data) + images, annos = zip(*data) + + move_data(images, f'images/{phase}', + lambda x: x.replace('/rgb', '')) + move_data(annos, f'annotations/{phase}', + lambda x: x.replace('/sync_depth', '')) + + process_phase('train') + process_phase('test') + + +def main(): + args = parse_args() + + print('Making directories...') + mkdir_or_exist(args.out_dir) + for subdir in [ + 'images/train', 'images/test', 'annotations/train', + 'annotations/test' + ]: + mkdir_or_exist(osp.join(args.out_dir, subdir)) + + print('Generating images and annotations...') + + if args.raw_data.endswith('.zip'): + with tempfile.TemporaryDirectory() as tmp_dir: + zip_file = zipfile.ZipFile(args.raw_data) + zip_file.extractall(tmp_dir) + reorganize(osp.join(tmp_dir, 'nyu'), args.out_dir) + else: + assert osp.isdir( + args.raw_data + ), 'the argument --raw-data should be either a zip file or directory.' + reorganize(args.raw_data, args.out_dir) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/pascal_context.py b/third-party/InterFormer/tools/dataset_converters/pascal_context.py new file mode 100644 index 0000000000000000000000000000000000000000..a92d1dc6411137b92fe67fbde0fc554060194085 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/pascal_context.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from functools import partial + +import numpy as np +from detail import Detail +from mmengine.utils import mkdir_or_exist, track_progress +from PIL import Image + +_mapping = np.sort( + np.array([ + 0, 2, 259, 260, 415, 324, 9, 258, 144, 18, 19, 22, 23, 397, 25, 284, + 158, 159, 416, 33, 162, 420, 454, 295, 296, 427, 44, 45, 46, 308, 59, + 440, 445, 31, 232, 65, 354, 424, 68, 326, 72, 458, 34, 207, 80, 355, + 85, 347, 220, 349, 360, 98, 187, 104, 105, 366, 189, 368, 113, 115 + ])) +_key = np.array(range(len(_mapping))).astype('uint8') + + +def generate_labels(img_id, detail, out_dir): + + def _class_to_index(mask, _mapping, _key): + # assert the values + values = np.unique(mask) + for i in range(len(values)): + assert (values[i] in _mapping) + index = np.digitize(mask.ravel(), _mapping, right=True) + return _key[index].reshape(mask.shape) + + mask = Image.fromarray( + _class_to_index(detail.getMask(img_id), _mapping=_mapping, _key=_key)) + filename = img_id['file_name'] + mask.save(osp.join(out_dir, filename.replace('jpg', 'png'))) + return osp.splitext(osp.basename(filename))[0] + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert PASCAL VOC annotations to mmsegmentation format') + parser.add_argument('devkit_path', help='pascal voc devkit path') + parser.add_argument('json_path', help='annoation json filepath') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + devkit_path = args.devkit_path + if args.out_dir is None: + out_dir = osp.join(devkit_path, 'VOC2010', 'SegmentationClassContext') + else: + out_dir = args.out_dir + json_path = args.json_path + mkdir_or_exist(out_dir) + img_dir = osp.join(devkit_path, 'VOC2010', 'JPEGImages') + + train_detail = Detail(json_path, img_dir, 'train') + train_ids = train_detail.getImgs() + + val_detail = Detail(json_path, img_dir, 'val') + val_ids = val_detail.getImgs() + + mkdir_or_exist( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext')) + + train_list = track_progress( + partial(generate_labels, detail=train_detail, out_dir=out_dir), + train_ids) + with open( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext', + 'train.txt'), 'w') as f: + f.writelines(line + '\n' for line in sorted(train_list)) + + val_list = track_progress( + partial(generate_labels, detail=val_detail, out_dir=out_dir), val_ids) + with open( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext', + 'val.txt'), 'w') as f: + f.writelines(line + '\n' for line in sorted(val_list)) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/potsdam.py b/third-party/InterFormer/tools/dataset_converters/potsdam.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c713ee2a08d2f6eaf68fb225899504b8f4e829 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/potsdam.py @@ -0,0 +1,158 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import math +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +import numpy as np +from mmengine.utils import ProgressBar, mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert potsdam dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='potsdam folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--clip_size', + type=int, + help='clipped size of image after preparation', + default=512) + parser.add_argument( + '--stride_size', + type=int, + help='stride of clipping original images', + default=256) + args = parser.parse_args() + return args + + +def clip_big_image(image_path, clip_save_dir, args, to_label=False): + # Original image of Potsdam dataset is very large, thus pre-processing + # of them is adopted. Given fixed clip size and stride size to generate + # clipped image, the intersection of width and height is determined. + # For example, given one 5120 x 5120 original image, the clip size is + # 512 and stride size is 256, thus it would generate 20x20 = 400 images + # whose size are all 512x512. + image = mmcv.imread(image_path) + + h, w, c = image.shape + clip_size = args.clip_size + stride_size = args.stride_size + + num_rows = math.ceil((h - clip_size) / stride_size) if math.ceil( + (h - clip_size) / + stride_size) * stride_size + clip_size >= h else math.ceil( + (h - clip_size) / stride_size) + 1 + num_cols = math.ceil((w - clip_size) / stride_size) if math.ceil( + (w - clip_size) / + stride_size) * stride_size + clip_size >= w else math.ceil( + (w - clip_size) / stride_size) + 1 + + x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1)) + xmin = x * clip_size + ymin = y * clip_size + + xmin = xmin.ravel() + ymin = ymin.ravel() + xmin_offset = np.where(xmin + clip_size > w, w - xmin - clip_size, + np.zeros_like(xmin)) + ymin_offset = np.where(ymin + clip_size > h, h - ymin - clip_size, + np.zeros_like(ymin)) + boxes = np.stack([ + xmin + xmin_offset, ymin + ymin_offset, + np.minimum(xmin + clip_size, w), + np.minimum(ymin + clip_size, h) + ], + axis=1) + + if to_label: + color_map = np.array([[0, 0, 0], [255, 255, 255], [255, 0, 0], + [255, 255, 0], [0, 255, 0], [0, 255, 255], + [0, 0, 255]]) + flatten_v = np.matmul( + image.reshape(-1, c), + np.array([2, 3, 4]).reshape(3, 1)) + out = np.zeros_like(flatten_v) + for idx, class_color in enumerate(color_map): + value_idx = np.matmul(class_color, + np.array([2, 3, 4]).reshape(3, 1)) + out[flatten_v == value_idx] = idx + image = out.reshape(h, w) + + for box in boxes: + start_x, start_y, end_x, end_y = box + clipped_image = image[start_y:end_y, + start_x:end_x] if to_label else image[ + start_y:end_y, start_x:end_x, :] + idx_i, idx_j = osp.basename(image_path).split('_')[2:4] + mmcv.imwrite( + clipped_image.astype(np.uint8), + osp.join( + clip_save_dir, + f'{idx_i}_{idx_j}_{start_x}_{start_y}_{end_x}_{end_y}.png')) + + +def main(): + args = parse_args() + splits = { + 'train': [ + '2_10', '2_11', '2_12', '3_10', '3_11', '3_12', '4_10', '4_11', + '4_12', '5_10', '5_11', '5_12', '6_10', '6_11', '6_12', '6_7', + '6_8', '6_9', '7_10', '7_11', '7_12', '7_7', '7_8', '7_9' + ], + 'val': [ + '5_15', '6_15', '6_13', '3_13', '4_14', '6_14', '5_14', '2_13', + '4_15', '2_14', '5_13', '4_13', '3_14', '7_13' + ] + } + + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'potsdam') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + zipp_list = glob.glob(os.path.join(dataset_path, '*.zip')) + print('Find the data', zipp_list) + + for zipp in zipp_list: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(zipp) + zip_file.extractall(tmp_dir) + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + if not len(src_path_list): + sub_tmp_dir = os.path.join(tmp_dir, os.listdir(tmp_dir)[0]) + src_path_list = glob.glob(os.path.join(sub_tmp_dir, '*.tif')) + + prog_bar = ProgressBar(len(src_path_list)) + for i, src_path in enumerate(src_path_list): + idx_i, idx_j = osp.basename(src_path).split('_')[2:4] + data_type = 'train' if f'{idx_i}_{idx_j}' in splits[ + 'train'] else 'val' + if 'label' in src_path: + dst_dir = osp.join(out_dir, 'ann_dir', data_type) + clip_big_image(src_path, dst_dir, args, to_label=True) + else: + dst_dir = osp.join(out_dir, 'img_dir', data_type) + clip_big_image(src_path, dst_dir, args, to_label=False) + prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/refuge.py b/third-party/InterFormer/tools/dataset_converters/refuge.py new file mode 100644 index 0000000000000000000000000000000000000000..1186866ab3fd58c4d72e5f573938053a8d7c80b2 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/refuge.py @@ -0,0 +1,110 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +import numpy as np +from mmengine.utils import mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert REFUGE dataset to mmsegmentation format') + parser.add_argument('--raw_data_root', help='the root path of raw data') + + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def extract_img(root: str, + cur_dir: str, + out_dir: str, + mode: str = 'train', + file_type: str = 'img') -> None: + """_summary_ + + Args: + Args: + root (str): root where the extracted data is saved + cur_dir (cur_dir): dir where the zip_file exists + out_dir (str): root dir where the data is saved + + mode (str, optional): Defaults to 'train'. + file_type (str, optional): Defaults to 'img',else to 'mask'. + """ + zip_file = zipfile.ZipFile(cur_dir) + zip_file.extractall(root) + for cur_dir, dirs, files in os.walk(root): + # filter child dirs and directories with "Illustration" and "MACOSX" + if len(dirs) == 0 and \ + cur_dir.split('\\')[-1].find('Illustration') == -1 and \ + cur_dir.find('MACOSX') == -1: + + file_names = [ + file for file in files + if file.endswith('.jpg') or file.endswith('.bmp') + ] + for filename in sorted(file_names): + img = mmcv.imread(osp.join(cur_dir, filename)) + + if file_type == 'annotations': + img = img[:, :, 0] + img[np.where(img == 0)] = 1 + img[np.where(img == 128)] = 2 + img[np.where(img == 255)] = 0 + mmcv.imwrite( + img, + osp.join(out_dir, file_type, mode, + osp.splitext(filename)[0] + '.png')) + + +def main(): + args = parse_args() + + raw_data_root = args.raw_data_root + if args.out_dir is None: + out_dir = osp.join('./data', 'REFUGE') + + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'images', 'test')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'test')) + + print('Generating images and annotations...') + # process data from the child dir on the first rank + cur_dir, dirs, files = list(os.walk(raw_data_root))[0] + print('====================') + + files = list(filter(lambda x: x.endswith('.zip'), files)) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for file in files: + # search data folders for training,validation,test + mode = list( + filter(lambda x: file.lower().find(x) != -1, + ['training', 'test', 'validation']))[0] + file_root = osp.join(tmp_dir, file[:-4]) + file_type = 'images' if file.find('Anno') == -1 and file.find( + 'GT') == -1 else 'annotations' + extract_img(file_root, osp.join(cur_dir, file), out_dir, mode, + file_type) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/stare.py b/third-party/InterFormer/tools/dataset_converters/stare.py new file mode 100644 index 0000000000000000000000000000000000000000..4a23ba4dd8a4744bca9d1a506c79131c0e42c73d --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/stare.py @@ -0,0 +1,167 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import gzip +import os +import os.path as osp +import tarfile +import tempfile + +import mmcv +from mmengine.utils import mkdir_or_exist + +STARE_LEN = 20 +TRAINING_LEN = 10 + + +def un_gz(src, dst): + g_file = gzip.GzipFile(src) + with open(dst, 'wb+') as f: + f.write(g_file.read()) + g_file.close() + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert STARE dataset to mmsegmentation format') + parser.add_argument('image_path', help='the path of stare-images.tar') + parser.add_argument('labels_ah', help='the path of labels-ah.tar') + parser.add_argument('labels_vk', help='the path of labels-vk.tar') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + image_path = args.image_path + labels_ah = args.labels_ah + labels_vk = args.labels_vk + if args.out_dir is None: + out_dir = osp.join('data', 'STARE') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting stare-images.tar...') + with tarfile.open(image_path) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + f'len(os.listdir(now_dir)) != {STARE_LEN}' + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting labels-ah.tar...') + with tarfile.open(labels_ah) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + f'len(os.listdir(now_dir)) != {STARE_LEN}' + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a threshold + # to convert the nonstandard annotation imgs. The value divided by + # 128 equivalent to '1 if value >= 128 else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting labels-vk.tar...') + with tarfile.open(labels_vk) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + f'len(os.listdir(now_dir)) != {STARE_LEN}' + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/synapse.py b/third-party/InterFormer/tools/dataset_converters/synapse.py new file mode 100644 index 0000000000000000000000000000000000000000..42dac6b7eff94107b8b3a59984622cb1fd2e7599 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/synapse.py @@ -0,0 +1,155 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import nibabel as nib +import numpy as np +from mmengine.utils import mkdir_or_exist +from PIL import Image + + +def read_files_from_txt(txt_path): + with open(txt_path) as f: + files = f.readlines() + files = [file.strip() for file in files] + return files + + +def read_nii_file(nii_path): + img = nib.load(nii_path).get_fdata() + return img + + +def split_3d_image(img): + c, _, _ = img.shape + res = [] + for i in range(c): + res.append(img[i, :, :]) + return res + + +def label_mapping(label): + """Label mapping from TransUNet paper setting. It only has 9 classes, which + are 'background', 'aorta', 'gallbladder', 'left_kidney', 'right_kidney', + 'liver', 'pancreas', 'spleen', 'stomach', respectively. Other foreground + classes in original dataset are all set to background. + + More details could be found here: https://arxiv.org/abs/2102.04306 + """ + maped_label = np.zeros_like(label) + maped_label[label == 8] = 1 + maped_label[label == 4] = 2 + maped_label[label == 3] = 3 + maped_label[label == 2] = 4 + maped_label[label == 6] = 5 + maped_label[label == 11] = 6 + maped_label[label == 1] = 7 + maped_label[label == 7] = 8 + return maped_label + + +def pares_args(): + parser = argparse.ArgumentParser( + description='Convert synapse dataset to mmsegmentation format') + parser.add_argument( + '--dataset-path', type=str, help='synapse dataset path.') + parser.add_argument( + '--save-path', + default='data/synapse', + type=str, + help='save path of the dataset.') + args = parser.parse_args() + return args + + +def main(): + args = pares_args() + dataset_path = args.dataset_path + save_path = args.save_path + + if not osp.exists(dataset_path): + raise ValueError('The dataset path does not exist. ' + 'Please enter a correct dataset path.') + if not osp.exists(osp.join(dataset_path, 'img')) \ + or not osp.exists(osp.join(dataset_path, 'label')): + raise FileNotFoundError('The dataset structure is incorrect. ' + 'Please check your dataset.') + + train_id = read_files_from_txt(osp.join(dataset_path, 'train.txt')) + train_id = [idx[3:7] for idx in train_id] + + test_id = read_files_from_txt(osp.join(dataset_path, 'val.txt')) + test_id = [idx[3:7] for idx in test_id] + + mkdir_or_exist(osp.join(save_path, 'img_dir/train')) + mkdir_or_exist(osp.join(save_path, 'img_dir/val')) + mkdir_or_exist(osp.join(save_path, 'ann_dir/train')) + mkdir_or_exist(osp.join(save_path, 'ann_dir/val')) + + # It follows data preparation pipeline from here: + # https://github.com/Beckschen/TransUNet/tree/main/datasets + for i, idx in enumerate(train_id): + img_3d = read_nii_file( + osp.join(dataset_path, 'img', 'img' + idx + '.nii.gz')) + label_3d = read_nii_file( + osp.join(dataset_path, 'label', 'label' + idx + '.nii.gz')) + + img_3d = np.clip(img_3d, -125, 275) + img_3d = (img_3d + 125) / 400 + img_3d *= 255 + img_3d = np.transpose(img_3d, [2, 0, 1]) + img_3d = np.flip(img_3d, 2) + + label_3d = np.transpose(label_3d, [2, 0, 1]) + label_3d = np.flip(label_3d, 2) + label_3d = label_mapping(label_3d) + + for c in range(img_3d.shape[0]): + img = img_3d[c] + label = label_3d[c] + + img = Image.fromarray(img).convert('RGB') + label = Image.fromarray(label).convert('L') + img.save( + osp.join( + save_path, 'img_dir/train', 'case' + idx.zfill(4) + + '_slice' + str(c).zfill(3) + '.jpg')) + label.save( + osp.join( + save_path, 'ann_dir/train', 'case' + idx.zfill(4) + + '_slice' + str(c).zfill(3) + '.png')) + + for i, idx in enumerate(test_id): + img_3d = read_nii_file( + osp.join(dataset_path, 'img', 'img' + idx + '.nii.gz')) + label_3d = read_nii_file( + osp.join(dataset_path, 'label', 'label' + idx + '.nii.gz')) + + img_3d = np.clip(img_3d, -125, 275) + img_3d = (img_3d + 125) / 400 + img_3d *= 255 + img_3d = np.transpose(img_3d, [2, 0, 1]) + img_3d = np.flip(img_3d, 2) + + label_3d = np.transpose(label_3d, [2, 0, 1]) + label_3d = np.flip(label_3d, 2) + label_3d = label_mapping(label_3d) + + for c in range(img_3d.shape[0]): + img = img_3d[c] + label = label_3d[c] + + img = Image.fromarray(img).convert('RGB') + label = Image.fromarray(label).convert('L') + img.save( + osp.join( + save_path, 'img_dir/val', 'case' + idx.zfill(4) + + '_slice' + str(c).zfill(3) + '.jpg')) + label.save( + osp.join( + save_path, 'ann_dir/val', 'case' + idx.zfill(4) + + '_slice' + str(c).zfill(3) + '.png')) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/dataset_converters/vaihingen.py b/third-party/InterFormer/tools/dataset_converters/vaihingen.py new file mode 100644 index 0000000000000000000000000000000000000000..db980144eb491846a844b0a374bb7a01d5509265 --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/vaihingen.py @@ -0,0 +1,156 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import math +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +import numpy as np +from mmengine.utils import ProgressBar, mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert vaihingen dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='vaihingen folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--clip_size', + type=int, + help='clipped size of image after preparation', + default=512) + parser.add_argument( + '--stride_size', + type=int, + help='stride of clipping original images', + default=256) + args = parser.parse_args() + return args + + +def clip_big_image(image_path, clip_save_dir, to_label=False): + # Original image of Vaihingen dataset is very large, thus pre-processing + # of them is adopted. Given fixed clip size and stride size to generate + # clipped image, the intersection of width and height is determined. + # For example, given one 5120 x 5120 original image, the clip size is + # 512 and stride size is 256, thus it would generate 20x20 = 400 images + # whose size are all 512x512. + image = mmcv.imread(image_path) + + h, w, c = image.shape + cs = args.clip_size + ss = args.stride_size + + num_rows = math.ceil((h - cs) / ss) if math.ceil( + (h - cs) / ss) * ss + cs >= h else math.ceil((h - cs) / ss) + 1 + num_cols = math.ceil((w - cs) / ss) if math.ceil( + (w - cs) / ss) * ss + cs >= w else math.ceil((w - cs) / ss) + 1 + + x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1)) + xmin = x * cs + ymin = y * cs + + xmin = xmin.ravel() + ymin = ymin.ravel() + xmin_offset = np.where(xmin + cs > w, w - xmin - cs, np.zeros_like(xmin)) + ymin_offset = np.where(ymin + cs > h, h - ymin - cs, np.zeros_like(ymin)) + boxes = np.stack([ + xmin + xmin_offset, ymin + ymin_offset, + np.minimum(xmin + cs, w), + np.minimum(ymin + cs, h) + ], + axis=1) + + if to_label: + color_map = np.array([[0, 0, 0], [255, 255, 255], [255, 0, 0], + [255, 255, 0], [0, 255, 0], [0, 255, 255], + [0, 0, 255]]) + flatten_v = np.matmul( + image.reshape(-1, c), + np.array([2, 3, 4]).reshape(3, 1)) + out = np.zeros_like(flatten_v) + for idx, class_color in enumerate(color_map): + value_idx = np.matmul(class_color, + np.array([2, 3, 4]).reshape(3, 1)) + out[flatten_v == value_idx] = idx + image = out.reshape(h, w) + + for box in boxes: + start_x, start_y, end_x, end_y = box + clipped_image = image[start_y:end_y, + start_x:end_x] if to_label else image[ + start_y:end_y, start_x:end_x, :] + area_idx = osp.basename(image_path).split('_')[3].strip('.tif') + mmcv.imwrite( + clipped_image.astype(np.uint8), + osp.join(clip_save_dir, + f'{area_idx}_{start_x}_{start_y}_{end_x}_{end_y}.png')) + + +def main(): + splits = { + 'train': [ + 'area1', 'area11', 'area13', 'area15', 'area17', 'area21', + 'area23', 'area26', 'area28', 'area3', 'area30', 'area32', + 'area34', 'area37', 'area5', 'area7' + ], + 'val': [ + 'area6', 'area24', 'area35', 'area16', 'area14', 'area22', + 'area10', 'area4', 'area2', 'area20', 'area8', 'area31', 'area33', + 'area27', 'area38', 'area12', 'area29' + ], + } + + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'vaihingen') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + zipp_list = glob.glob(os.path.join(dataset_path, '*.zip')) + print('Find the data', zipp_list) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for zipp in zipp_list: + zip_file = zipfile.ZipFile(zipp) + zip_file.extractall(tmp_dir) + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + if 'ISPRS_semantic_labeling_Vaihingen' in zipp: + src_path_list = glob.glob( + os.path.join(os.path.join(tmp_dir, 'top'), '*.tif')) + if 'ISPRS_semantic_labeling_Vaihingen_ground_truth_eroded_COMPLETE' in zipp: # noqa + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + # delete unused area9 ground truth + for area_ann in src_path_list: + if 'area9' in area_ann: + src_path_list.remove(area_ann) + prog_bar = ProgressBar(len(src_path_list)) + for i, src_path in enumerate(src_path_list): + area_idx = osp.basename(src_path).split('_')[3].strip('.tif') + data_type = 'train' if area_idx in splits['train'] else 'val' + if 'noBoundary' in src_path: + dst_dir = osp.join(out_dir, 'ann_dir', data_type) + clip_big_image(src_path, dst_dir, to_label=True) + else: + dst_dir = osp.join(out_dir, 'img_dir', data_type) + clip_big_image(src_path, dst_dir, to_label=False) + prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + args = parse_args() + main() diff --git a/third-party/InterFormer/tools/dataset_converters/voc_aug.py b/third-party/InterFormer/tools/dataset_converters/voc_aug.py new file mode 100644 index 0000000000000000000000000000000000000000..a536f4290d06e4a6c3c9fa8dbadfda847fec583b --- /dev/null +++ b/third-party/InterFormer/tools/dataset_converters/voc_aug.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from functools import partial + +import numpy as np +from mmengine.utils import mkdir_or_exist, scandir, track_parallel_progress +from PIL import Image +from scipy.io import loadmat + +AUG_LEN = 10582 + + +def convert_mat(mat_file, in_dir, out_dir): + data = loadmat(osp.join(in_dir, mat_file)) + mask = data['GTcls'][0]['Segmentation'][0].astype(np.uint8) + seg_filename = osp.join(out_dir, mat_file.replace('.mat', '.png')) + Image.fromarray(mask).save(seg_filename, 'PNG') + + +def generate_aug_list(merged_list, excluded_list): + return list(set(merged_list) - set(excluded_list)) + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert PASCAL VOC annotations to mmsegmentation format') + parser.add_argument('devkit_path', help='pascal voc devkit path') + parser.add_argument('aug_path', help='pascal voc aug path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=1, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + devkit_path = args.devkit_path + aug_path = args.aug_path + nproc = args.nproc + if args.out_dir is None: + out_dir = osp.join(devkit_path, 'VOC2012', 'SegmentationClassAug') + else: + out_dir = args.out_dir + mkdir_or_exist(out_dir) + in_dir = osp.join(aug_path, 'dataset', 'cls') + + track_parallel_progress( + partial(convert_mat, in_dir=in_dir, out_dir=out_dir), + list(scandir(in_dir, suffix='.mat')), + nproc=nproc) + + full_aug_list = [] + with open(osp.join(aug_path, 'dataset', 'train.txt')) as f: + full_aug_list += [line.strip() for line in f] + with open(osp.join(aug_path, 'dataset', 'val.txt')) as f: + full_aug_list += [line.strip() for line in f] + + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'train.txt')) as f: + ori_train_list = [line.strip() for line in f] + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'val.txt')) as f: + val_list = [line.strip() for line in f] + + aug_train_list = generate_aug_list(ori_train_list + full_aug_list, + val_list) + assert len(aug_train_list) == AUG_LEN, 'len(aug_train_list) != {}'.format( + AUG_LEN) + + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'trainaug.txt'), 'w') as f: + f.writelines(line + '\n' for line in aug_train_list) + + aug_list = generate_aug_list(full_aug_list, ori_train_list + val_list) + assert len(aug_list) == AUG_LEN - len( + ori_train_list), 'len(aug_list) != {}'.format(AUG_LEN - + len(ori_train_list)) + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', 'aug.txt'), + 'w') as f: + f.writelines(line + '\n' for line in aug_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/deployment/pytorch2torchscript.py b/third-party/InterFormer/tools/deployment/pytorch2torchscript.py new file mode 100644 index 0000000000000000000000000000000000000000..e69e705bb13ff3cca233534c34fcdaaeda02825b --- /dev/null +++ b/third-party/InterFormer/tools/deployment/pytorch2torchscript.py @@ -0,0 +1,185 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse + +import numpy as np +import torch +import torch._C +import torch.serialization +from mmengine import Config +from mmengine.runner import load_checkpoint +from torch import nn + +from mmseg.models import build_segmentor + +torch.manual_seed(3) + + +def digit_version(version_str): + digit_version = [] + for x in version_str.split('.'): + if x.isdigit(): + digit_version.append(int(x)) + elif x.find('rc') != -1: + patch_version = x.split('rc') + digit_version.append(int(patch_version[0]) - 1) + digit_version.append(int(patch_version[1])) + return digit_version + + +def check_torch_version(): + torch_minimum_version = '1.8.0' + torch_version = digit_version(torch.__version__) + + assert (torch_version >= digit_version(torch_minimum_version)), \ + f'Torch=={torch.__version__} is not support for converting to ' \ + f'torchscript. Please install pytorch>={torch_minimum_version}.' + + +def _convert_batchnorm(module): + module_output = module + if isinstance(module, torch.nn.SyncBatchNorm): + module_output = torch.nn.BatchNorm2d(module.num_features, module.eps, + module.momentum, module.affine, + module.track_running_stats) + if module.affine: + module_output.weight.data = module.weight.data.clone().detach() + module_output.bias.data = module.bias.data.clone().detach() + # keep requires_grad unchanged + module_output.weight.requires_grad = module.weight.requires_grad + module_output.bias.requires_grad = module.bias.requires_grad + module_output.running_mean = module.running_mean + module_output.running_var = module.running_var + module_output.num_batches_tracked = module.num_batches_tracked + for name, child in module.named_children(): + module_output.add_module(name, _convert_batchnorm(child)) + del module + return module_output + + +def _demo_mm_inputs(input_shape, num_classes): + """Create a superset of inputs needed to run test or train batches. + + Args: + input_shape (tuple): + input batch dimensions + num_classes (int): + number of semantic classes + """ + (N, C, H, W) = input_shape + rng = np.random.RandomState(0) + imgs = rng.rand(*input_shape) + segs = rng.randint( + low=0, high=num_classes - 1, size=(N, 1, H, W)).astype(np.uint8) + img_metas = [{ + 'img_shape': (H, W, C), + 'ori_shape': (H, W, C), + 'pad_shape': (H, W, C), + 'filename': '.png', + 'scale_factor': 1.0, + 'flip': False, + } for _ in range(N)] + mm_inputs = { + 'imgs': torch.FloatTensor(imgs).requires_grad_(True), + 'img_metas': img_metas, + 'gt_semantic_seg': torch.LongTensor(segs) + } + return mm_inputs + + +def pytorch2libtorch(model, + input_shape, + show=False, + output_file='tmp.pt', + verify=False): + """Export Pytorch model to TorchScript model and verify the outputs are + same between Pytorch and TorchScript. + + Args: + model (nn.Module): Pytorch model we want to export. + input_shape (tuple): Use this input shape to construct + the corresponding dummy input and execute the model. + show (bool): Whether print the computation graph. Default: False. + output_file (string): The path to where we store the + output TorchScript model. Default: `tmp.pt`. + verify (bool): Whether compare the outputs between + Pytorch and TorchScript. Default: False. + """ + if isinstance(model.decode_head, nn.ModuleList): + num_classes = model.decode_head[-1].num_classes + else: + num_classes = model.decode_head.num_classes + + mm_inputs = _demo_mm_inputs(input_shape, num_classes) + + imgs = mm_inputs.pop('imgs') + + # replace the original forword with forward_dummy + model.forward = model.forward_dummy + model.eval() + traced_model = torch.jit.trace( + model, + example_inputs=imgs, + check_trace=verify, + ) + + if show: + print(traced_model.graph) + + traced_model.save(output_file) + print(f'Successfully exported TorchScript model: {output_file}') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert MMSeg to TorchScript') + parser.add_argument('config', help='test config file path') + parser.add_argument('--checkpoint', help='checkpoint file', default=None) + parser.add_argument( + '--show', action='store_true', help='show TorchScript graph') + parser.add_argument( + '--verify', action='store_true', help='verify the TorchScript model') + parser.add_argument('--output-file', type=str, default='tmp.pt') + parser.add_argument( + '--shape', + type=int, + nargs='+', + default=[512, 512], + help='input image size (height, width)') + args = parser.parse_args() + return args + + +if __name__ == '__main__': + args = parse_args() + check_torch_version() + + if len(args.shape) == 1: + input_shape = (1, 3, args.shape[0], args.shape[0]) + elif len(args.shape) == 2: + input_shape = ( + 1, + 3, + ) + tuple(args.shape) + else: + raise ValueError('invalid input shape') + + cfg = Config.fromfile(args.config) + cfg.model.pretrained = None + + # build the model and load checkpoint + cfg.model.train_cfg = None + segmentor = build_segmentor( + cfg.model, train_cfg=None, test_cfg=cfg.get('test_cfg')) + # convert SyncBN to BN + segmentor = _convert_batchnorm(segmentor) + + if args.checkpoint: + load_checkpoint(segmentor, args.checkpoint, map_location='cpu') + + # convert the PyTorch model to LibTorch model + pytorch2libtorch( + segmentor, + input_shape, + show=args.show, + output_file=args.output_file, + verify=args.verify) diff --git a/third-party/InterFormer/tools/dist_test.sh b/third-party/InterFormer/tools/dist_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..89711fd5c02cfc1f0386e5354506d4b74ecac251 --- /dev/null +++ b/third-party/InterFormer/tools/dist_test.sh @@ -0,0 +1,20 @@ +CONFIG=$1 +CHECKPOINT=$2 +GPUS=$3 +NNODES=${NNODES:-1} +NODE_RANK=${NODE_RANK:-0} +PORT=${PORT:-29500} +MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +python -m torch.distributed.launch \ + --nnodes=$NNODES \ + --node_rank=$NODE_RANK \ + --master_addr=$MASTER_ADDR \ + --nproc_per_node=$GPUS \ + --master_port=$PORT \ + $(dirname "$0")/test.py \ + $CONFIG \ + $CHECKPOINT \ + --launcher pytorch \ + ${@:4} diff --git a/third-party/InterFormer/tools/dist_train.sh b/third-party/InterFormer/tools/dist_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..a857df78788edb8841b6f67d74dd0e6cfb77d8ab --- /dev/null +++ b/third-party/InterFormer/tools/dist_train.sh @@ -0,0 +1,17 @@ +CONFIG=$1 +GPUS=$2 +NNODES=${NNODES:-1} +NODE_RANK=${NODE_RANK:-0} +PORT=${PORT:-29500} +MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +python -m torch.distributed.launch \ + --nnodes=$NNODES \ + --node_rank=$NODE_RANK \ + --master_addr=$MASTER_ADDR \ + --nproc_per_node=$GPUS \ + --master_port=$PORT \ + $(dirname "$0")/train.py \ + $CONFIG \ + --launcher pytorch ${@:3} diff --git a/third-party/InterFormer/tools/misc/browse_dataset.py b/third-party/InterFormer/tools/misc/browse_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..7863eb74f2cab53d025afad347f7886a5ce29919 --- /dev/null +++ b/third-party/InterFormer/tools/misc/browse_dataset.py @@ -0,0 +1,73 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +from mmengine import Config, DictAction +from mmengine.registry import init_default_scope +from mmengine.utils import ProgressBar + +from mmseg.registry import DATASETS, VISUALIZERS + + +def parse_args(): + parser = argparse.ArgumentParser(description='Browse a dataset') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--output-dir', + default=None, + type=str, + help='If there is no display interface, you can save it') + parser.add_argument('--not-show', default=False, action='store_true') + parser.add_argument( + '--show-interval', + type=float, + default=2, + help='the interval of show (s)') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # register all modules in mmseg into the registries + init_default_scope('mmseg') + + dataset = DATASETS.build(cfg.train_dataloader.dataset) + cfg.visualizer['save_dir'] = args.output_dir + visualizer = VISUALIZERS.build(cfg.visualizer) + visualizer.dataset_meta = dataset.METAINFO + + progress_bar = ProgressBar(len(dataset)) + for item in dataset: + img = item['inputs'].permute(1, 2, 0).numpy() + data_sample = item['data_samples'].numpy() + img_path = osp.basename(item['data_samples'].img_path) + + img = img[..., [2, 1, 0]] # bgr to rgb + + visualizer.add_datasample( + osp.basename(img_path), + img, + data_sample, + show=not args.not_show, + wait_time=args.show_interval) + + progress_bar.update() + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/misc/print_config.py b/third-party/InterFormer/tools/misc/print_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1c024a6a44157a0b0d4d6213d18d67f57a33c5 --- /dev/null +++ b/third-party/InterFormer/tools/misc/print_config.py @@ -0,0 +1,69 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import warnings + +from mmengine import Config, DictAction + +from mmseg.apis import init_model + + +def parse_args(): + parser = argparse.ArgumentParser(description='Print the whole config') + parser.add_argument('config', help='config file path') + parser.add_argument( + '--graph', action='store_true', help='print the models graph') + parser.add_argument( + '--options', + nargs='+', + action=DictAction, + help="--options is deprecated in favor of --cfg_options' and it will " + 'not be supported in version v0.22.0. Override some settings in the ' + 'used config, the key-value pair in xxx=yyy format will be merged ' + 'into config file. If the value to be overwritten is a list, it ' + 'should be like key="[a,b]" or key=a,b It also allows nested ' + 'list/tuple values, e.g. key="[(a,b),(c,d)]" Note that the quotation ' + 'marks are necessary and that no white space is allowed.') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + + if args.options and args.cfg_options: + raise ValueError( + '--options and --cfg-options cannot be both ' + 'specified, --options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + if args.options: + warnings.warn('--options is deprecated in favor of --cfg-options, ' + '--options will not be supported in version v0.22.0.') + args.cfg_options = args.options + + return args + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + print(f'Config:\n{cfg.pretty_text}') + # dump config + cfg.dump('example.py') + # dump models graph + if args.graph: + model = init_model(args.config, device='cpu') + print(f'Model graph:\n{str(model)}') + with open('example-graph.txt', 'w') as f: + f.writelines(str(model)) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/misc/publish_model.py b/third-party/InterFormer/tools/misc/publish_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e035ad90e85e0e03d8304c1d5b524c5ac322c644 --- /dev/null +++ b/third-party/InterFormer/tools/misc/publish_model.py @@ -0,0 +1,50 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import subprocess +from hashlib import sha256 + +import torch + +BLOCK_SIZE = 128 * 1024 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Process a checkpoint to be published') + parser.add_argument('in_file', help='input checkpoint filename') + parser.add_argument('out_file', help='output checkpoint filename') + args = parser.parse_args() + return args + + +def sha256sum(filename: str) -> str: + """Compute SHA256 message digest from a file.""" + hash_func = sha256() + byte_array = bytearray(BLOCK_SIZE) + memory_view = memoryview(byte_array) + with open(filename, 'rb', buffering=0) as file: + for block in iter(lambda: file.readinto(memory_view), 0): + hash_func.update(memory_view[:block]) + return hash_func.hexdigest() + + +def process_checkpoint(in_file, out_file): + checkpoint = torch.load(in_file, map_location='cpu') + # remove optimizer for smaller file size + if 'optimizer' in checkpoint: + del checkpoint['optimizer'] + # if it is necessary to remove some sensitive data in checkpoint['meta'], + # add the code here. + torch.save(checkpoint, out_file) + sha = sha256sum(in_file) + final_file = out_file.rstrip('.pth') + f'-{sha[:8]}.pth' + subprocess.Popen(['mv', out_file, final_file]) + + +def main(): + args = parse_args() + process_checkpoint(args.in_file, args.out_file) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/beit2mmseg.py b/third-party/InterFormer/tools/model_converters/beit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..20f8f0f4509f93291782ca152bf04ab019b0e0ff --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/beit2mmseg.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_beit(ckpt): + new_ckpt = OrderedDict() + + for k, v in ckpt.items(): + if k.startswith('patch_embed'): + new_key = k.replace('patch_embed.proj', 'patch_embed.projection') + new_ckpt[new_key] = v + if k.startswith('blocks'): + new_key = k.replace('blocks', 'layers') + if 'norm' in new_key: + new_key = new_key.replace('norm', 'ln') + elif 'mlp.fc1' in new_key: + new_key = new_key.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in new_key: + new_key = new_key.replace('mlp.fc2', 'ffn.layers.1') + new_ckpt[new_key] = v + else: + new_key = k + new_ckpt[new_key] = v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained beit models to' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_beit(state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/clip2mmseg.py b/third-party/InterFormer/tools/model_converters/clip2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..9a97e4b04ab45740ee37149d30a85b67245868f5 --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/clip2mmseg.py @@ -0,0 +1,163 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_vitlayer(paras): + new_para_name = '' + if paras[0] == 'ln_1': + new_para_name = '.'.join(['ln1'] + paras[1:]) + elif paras[0] == 'attn': + new_para_name = '.'.join(['attn.attn'] + paras[1:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['ln2'] + paras[1:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffn.layers.0.0'] + paras[-1:]) + else: + new_para_name = '.'.join(['ffn.layers.1'] + paras[-1:]) + else: + print(f'Wrong for {paras}') + return new_para_name + + +def convert_translayer(paras): + new_para_name = '' + if paras[0] == 'attn': + new_para_name = '.'.join(['attentions.0.attn'] + paras[1:]) + elif paras[0] == 'ln_1': + new_para_name = '.'.join(['norms.0'] + paras[1:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['norms.1'] + paras[1:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffns.0.layers.0.0'] + paras[2:]) + elif paras[1] == 'c_proj': + new_para_name = '.'.join(['ffns.0.layers.1'] + paras[2:]) + else: + print(f'Wrong for {paras}') + else: + print(f'Wrong for {paras}') + return new_para_name + + +def convert_key_name(ckpt, visual_split): + new_ckpt = OrderedDict() + for k, v in ckpt.items(): + key_list = k.split('.') + if key_list[0] == 'visual': + new_transform_name = 'image_encoder' + if key_list[1] == 'class_embedding': + new_name = '.'.join([new_transform_name, 'cls_token']) + elif key_list[1] == 'positional_embedding': + new_name = '.'.join([new_transform_name, 'pos_embed']) + elif key_list[1] == 'conv1': + new_name = '.'.join([ + new_transform_name, 'patch_embed.projection', key_list[2] + ]) + elif key_list[1] == 'ln_pre': + new_name = '.'.join( + [new_transform_name, key_list[1], key_list[2]]) + elif key_list[1] == 'transformer': + new_layer_name = 'layers' + layer_index = key_list[3] + paras = key_list[4:] + if int(layer_index) < visual_split: + new_para_name = convert_vitlayer(paras) + new_name = '.'.join([ + new_transform_name, new_layer_name, layer_index, + new_para_name + ]) + else: + new_para_name = convert_translayer(paras) + new_transform_name = 'decode_head.rec_with_attnbias' + new_layer_name = 'layers' + layer_index = str(int(layer_index) - visual_split) + new_name = '.'.join([ + new_transform_name, new_layer_name, layer_index, + new_para_name + ]) + elif key_list[1] == 'proj': + new_name = 'decode_head.rec_with_attnbias.proj.weight' + elif key_list[1] == 'ln_post': + new_name = k.replace('visual', 'decode_head.rec_with_attnbias') + else: + print(f'pop parameter: {k}') + continue + else: + text_encoder_name = 'text_encoder' + if key_list[0] == 'transformer': + layer_name = 'transformer' + layer_index = key_list[2] + paras = key_list[3:] + new_para_name = convert_translayer(paras) + new_name = '.'.join([ + text_encoder_name, layer_name, layer_index, new_para_name + ]) + elif key_list[0] in [ + 'positional_embedding', 'text_projection', 'bg_embed', + 'attn_mask', 'logit_scale', 'token_embedding', 'ln_final' + ]: + new_name = 'text_encoder.' + k + else: + print(f'pop parameter: {k}') + continue + new_ckpt[new_name] = v + + return new_ckpt + + +def convert_tensor(ckpt): + cls_token = ckpt['image_encoder.cls_token'] + new_cls_token = cls_token.unsqueeze(0).unsqueeze(0) + ckpt['image_encoder.cls_token'] = new_cls_token + pos_embed = ckpt['image_encoder.pos_embed'] + new_pos_embed = pos_embed.unsqueeze(0) + ckpt['image_encoder.pos_embed'] = new_pos_embed + proj_weight = ckpt['decode_head.rec_with_attnbias.proj.weight'] + new_proj_weight = proj_weight.transpose(1, 0) + ckpt['decode_head.rec_with_attnbias.proj.weight'] = new_proj_weight + return ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + if any([s in args.src for s in ['B-16', 'b16', 'base_patch16']]): + visual_split = 9 + elif any([s in args.src for s in ['L-14', 'l14', 'large_patch14']]): + visual_split = 18 + else: + print('Make sure the clip model is ViT-B/16 or ViT-L/14!') + visual_split = -1 + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if isinstance(checkpoint, torch.jit.RecursiveScriptModule): + state_dict = checkpoint.state_dict() + else: + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + # deit checkpoint + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_key_name(state_dict, visual_split) + weight = convert_tensor(weight) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/mit2mmseg.py b/third-party/InterFormer/tools/model_converters/mit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..f10cbbf9d40d3656be0d447460c12fc83771c14c --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/mit2mmseg.py @@ -0,0 +1,82 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_mit(ckpt): + new_ckpt = OrderedDict() + # Process the concat between q linear weights and kv linear weights + for k, v in ckpt.items(): + if k.startswith('head'): + continue + # patch embedding conversion + elif k.startswith('patch_embed'): + stage_i = int(k.split('.')[0].replace('patch_embed', '')) + new_k = k.replace(f'patch_embed{stage_i}', f'layers.{stage_i-1}.0') + new_v = v + if 'proj.' in new_k: + new_k = new_k.replace('proj.', 'projection.') + # transformer encoder layer conversion + elif k.startswith('block'): + stage_i = int(k.split('.')[0].replace('block', '')) + new_k = k.replace(f'block{stage_i}', f'layers.{stage_i-1}.1') + new_v = v + if 'attn.q.' in new_k: + sub_item_k = k.replace('q.', 'kv.') + new_k = new_k.replace('q.', 'attn.in_proj_') + new_v = torch.cat([v, ckpt[sub_item_k]], dim=0) + elif 'attn.kv.' in new_k: + continue + elif 'attn.proj.' in new_k: + new_k = new_k.replace('proj.', 'attn.out_proj.') + elif 'attn.sr.' in new_k: + new_k = new_k.replace('sr.', 'sr.') + elif 'mlp.' in new_k: + string = f'{new_k}-' + new_k = new_k.replace('mlp.', 'ffn.layers.') + if 'fc1.weight' in new_k or 'fc2.weight' in new_k: + new_v = v.reshape((*v.shape, 1, 1)) + new_k = new_k.replace('fc1.', '0.') + new_k = new_k.replace('dwconv.dwconv.', '1.') + new_k = new_k.replace('fc2.', '4.') + string += f'{new_k} {v.shape}-{new_v.shape}' + # norm layer conversion + elif k.startswith('norm'): + stage_i = int(k.split('.')[0].replace('norm', '')) + new_k = k.replace(f'norm{stage_i}', f'layers.{stage_i-1}.2') + new_v = v + else: + new_k = k + new_v = v + new_ckpt[new_k] = new_v + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained segformer to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_mit(state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/san2mmseg.py b/third-party/InterFormer/tools/model_converters/san2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..301a46608e0f14df17138922ae3a747aee105372 --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/san2mmseg.py @@ -0,0 +1,220 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_key_name(ckpt): + new_ckpt = OrderedDict() + + for k, v in ckpt.items(): + key_list = k.split('.') + if key_list[0] == 'clip_visual_extractor': + new_transform_name = 'image_encoder' + if key_list[1] == 'class_embedding': + new_name = '.'.join([new_transform_name, 'cls_token']) + elif key_list[1] == 'positional_embedding': + new_name = '.'.join([new_transform_name, 'pos_embed']) + elif key_list[1] == 'conv1': + new_name = '.'.join([ + new_transform_name, 'patch_embed.projection', key_list[2] + ]) + elif key_list[1] == 'ln_pre': + new_name = '.'.join( + [new_transform_name, key_list[1], key_list[2]]) + elif key_list[1] == 'resblocks': + new_layer_name = 'layers' + layer_index = key_list[2] + paras = key_list[3:] + if paras[0] == 'ln_1': + new_para_name = '.'.join(['ln1'] + key_list[4:]) + elif paras[0] == 'attn': + new_para_name = '.'.join(['attn.attn'] + key_list[4:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['ln2'] + key_list[4:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffn.layers.0.0'] + + key_list[-1:]) + else: + new_para_name = '.'.join(['ffn.layers.1'] + + key_list[-1:]) + new_name = '.'.join([ + new_transform_name, new_layer_name, layer_index, + new_para_name + ]) + elif key_list[0] == 'side_adapter_network': + decode_head_name = 'decode_head' + module_name = 'side_adapter_network' + if key_list[1] == 'vit_model': + if key_list[2] == 'blocks': + layer_name = 'encode_layers' + layer_index = key_list[3] + paras = key_list[4:] + if paras[0] == 'norm1': + new_para_name = '.'.join(['ln1'] + key_list[5:]) + elif paras[0] == 'attn': + new_para_name = '.'.join(key_list[4:]) + new_para_name = new_para_name.replace( + 'attn.qkv.', 'attn.attn.in_proj_') + new_para_name = new_para_name.replace( + 'attn.proj', 'attn.attn.out_proj') + elif paras[0] == 'norm2': + new_para_name = '.'.join(['ln2'] + key_list[5:]) + elif paras[0] == 'mlp': + new_para_name = '.'.join(['ffn'] + key_list[5:]) + new_para_name = new_para_name.replace( + 'fc1', 'layers.0.0') + new_para_name = new_para_name.replace( + 'fc2', 'layers.1') + else: + print(f'Wrong for {k}') + new_name = '.'.join([ + decode_head_name, module_name, layer_name, layer_index, + new_para_name + ]) + elif key_list[2] == 'pos_embed': + new_name = '.'.join( + [decode_head_name, module_name, 'pos_embed']) + elif key_list[2] == 'patch_embed': + new_name = '.'.join([ + decode_head_name, module_name, 'patch_embed', + 'projection', key_list[4] + ]) + else: + print(f'Wrong for {k}') + elif key_list[1] == 'query_embed' or key_list[ + 1] == 'query_pos_embed': + new_name = '.'.join( + [decode_head_name, module_name, key_list[1]]) + elif key_list[1] == 'fusion_layers': + layer_name = 'conv_clips' + layer_index = key_list[2][-1] + paras = '.'.join(key_list[3:]) + new_para_name = paras.replace('input_proj.0', '0') + new_para_name = new_para_name.replace('input_proj.1', '1.conv') + new_name = '.'.join([ + decode_head_name, module_name, layer_name, layer_index, + new_para_name + ]) + elif key_list[1] == 'mask_decoder': + new_name = 'decode_head.' + k + else: + print(f'Wrong for {k}') + elif key_list[0] == 'clip_rec_head': + module_name = 'rec_with_attnbias' + if key_list[1] == 'proj': + new_name = '.'.join( + [decode_head_name, module_name, 'proj.weight']) + elif key_list[1] == 'ln_post': + new_name = '.'.join( + [decode_head_name, module_name, 'ln_post', key_list[2]]) + elif key_list[1] == 'resblocks': + new_layer_name = 'layers' + layer_index = key_list[2] + paras = key_list[3:] + if paras[0] == 'ln_1': + new_para_name = '.'.join(['norms.0'] + paras[1:]) + elif paras[0] == 'attn': + new_para_name = '.'.join(['attentions.0.attn'] + paras[1:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['norms.1'] + paras[1:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffns.0.layers.0.0'] + + paras[2:]) + elif paras[1] == 'c_proj': + new_para_name = '.'.join(['ffns.0.layers.1'] + + paras[2:]) + else: + print(f'Wrong for {k}') + new_name = '.'.join([ + decode_head_name, module_name, new_layer_name, layer_index, + new_para_name + ]) + else: + print(f'Wrong for {k}') + elif key_list[0] == 'ov_classifier': + text_encoder_name = 'text_encoder' + if key_list[1] == 'transformer': + layer_name = 'transformer' + layer_index = key_list[3] + paras = key_list[4:] + if paras[0] == 'attn': + new_para_name = '.'.join(['attentions.0.attn'] + paras[1:]) + elif paras[0] == 'ln_1': + new_para_name = '.'.join(['norms.0'] + paras[1:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['norms.1'] + paras[1:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffns.0.layers.0.0'] + + paras[2:]) + elif paras[1] == 'c_proj': + new_para_name = '.'.join(['ffns.0.layers.1'] + + paras[2:]) + else: + print(f'Wrong for {k}') + else: + print(f'Wrong for {k}') + new_name = '.'.join([ + text_encoder_name, layer_name, layer_index, new_para_name + ]) + elif key_list[1] in [ + 'positional_embedding', 'text_projection', 'bg_embed', + 'attn_mask', 'logit_scale', 'token_embedding', 'ln_final' + ]: + new_name = k.replace('ov_classifier', 'text_encoder') + else: + print(f'Wrong for {k}') + elif key_list[0] == 'criterion': + new_name = k + else: + print(f'Wrong for {k}') + new_ckpt[new_name] = v + return new_ckpt + + +def convert_tensor(ckpt): + cls_token = ckpt['image_encoder.cls_token'] + new_cls_token = cls_token.unsqueeze(0).unsqueeze(0) + ckpt['image_encoder.cls_token'] = new_cls_token + pos_embed = ckpt['image_encoder.pos_embed'] + new_pos_embed = pos_embed.unsqueeze(0) + ckpt['image_encoder.pos_embed'] = new_pos_embed + proj_weight = ckpt['decode_head.rec_with_attnbias.proj.weight'] + new_proj_weight = proj_weight.transpose(1, 0) + ckpt['decode_head.rec_with_attnbias.proj.weight'] = new_proj_weight + return ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + # deit checkpoint + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_key_name(state_dict) + weight = convert_tensor(weight) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/stdc2mmseg.py b/third-party/InterFormer/tools/model_converters/stdc2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea3b8342f546692f50a8e3c0b740f881058229c --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/stdc2mmseg.py @@ -0,0 +1,71 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_stdc(ckpt, stdc_type): + new_state_dict = {} + if stdc_type == 'STDC1': + stage_lst = ['0', '1', '2.0', '2.1', '3.0', '3.1', '4.0', '4.1'] + else: + stage_lst = [ + '0', '1', '2.0', '2.1', '2.2', '2.3', '3.0', '3.1', '3.2', '3.3', + '3.4', '4.0', '4.1', '4.2' + ] + for k, v in ckpt.items(): + ori_k = k + flag = False + if 'cp.' in k: + k = k.replace('cp.', '') + if 'features.' in k: + num_layer = int(k.split('.')[1]) + feature_key_lst = 'features.' + str(num_layer) + '.' + stages_key_lst = 'stages.' + stage_lst[num_layer] + '.' + k = k.replace(feature_key_lst, stages_key_lst) + flag = True + if 'conv_list' in k: + k = k.replace('conv_list', 'layers') + flag = True + if 'avd_layer.' in k: + if 'avd_layer.0' in k: + k = k.replace('avd_layer.0', 'downsample.conv') + elif 'avd_layer.1' in k: + k = k.replace('avd_layer.1', 'downsample.bn') + flag = True + if flag: + new_state_dict[k] = ckpt[ori_k] + + return new_state_dict + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained STDC1/2 to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + parser.add_argument('type', help='model type: STDC1 or STDC2') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + + assert args.type in ['STDC1', + 'STDC2'], 'STD type should be STDC1 or STDC2!' + weight = convert_stdc(state_dict, args.type) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/swin2mmseg.py b/third-party/InterFormer/tools/model_converters/swin2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..d434f9465bbdad6bebc7d5962e8bfaf63c7c9e72 --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/swin2mmseg.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_swin(ckpt): + new_ckpt = OrderedDict() + + def correct_unfold_reduction_order(x): + out_channel, in_channel = x.shape + x = x.reshape(out_channel, 4, in_channel // 4) + x = x[:, [0, 2, 1, 3], :].transpose(1, + 2).reshape(out_channel, in_channel) + return x + + def correct_unfold_norm_order(x): + in_channel = x.shape[0] + x = x.reshape(4, in_channel // 4) + x = x[[0, 2, 1, 3], :].transpose(0, 1).reshape(in_channel) + return x + + for k, v in ckpt.items(): + if k.startswith('head'): + continue + elif k.startswith('layers'): + new_v = v + if 'attn.' in k: + new_k = k.replace('attn.', 'attn.w_msa.') + elif 'mlp.' in k: + if 'mlp.fc1.' in k: + new_k = k.replace('mlp.fc1.', 'ffn.layers.0.0.') + elif 'mlp.fc2.' in k: + new_k = k.replace('mlp.fc2.', 'ffn.layers.1.') + else: + new_k = k.replace('mlp.', 'ffn.') + elif 'downsample' in k: + new_k = k + if 'reduction.' in k: + new_v = correct_unfold_reduction_order(v) + elif 'norm.' in k: + new_v = correct_unfold_norm_order(v) + else: + new_k = k + new_k = new_k.replace('layers', 'stages', 1) + elif k.startswith('patch_embed'): + new_v = v + if 'proj' in k: + new_k = k.replace('proj', 'projection') + else: + new_k = k + else: + new_v = v + new_k = k + + new_ckpt[new_k] = new_v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained swin models to' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_swin(state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/twins2mmseg.py b/third-party/InterFormer/tools/model_converters/twins2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..647d41784aa07468be4b3f2e183064ad55266ad1 --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/twins2mmseg.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_twins(args, ckpt): + + new_ckpt = OrderedDict() + + for k, v in list(ckpt.items()): + new_v = v + if k.startswith('head'): + continue + elif k.startswith('patch_embeds'): + if 'proj.' in k: + new_k = k.replace('proj.', 'projection.') + else: + new_k = k + elif k.startswith('blocks'): + # Union + if 'attn.q.' in k: + new_k = k.replace('q.', 'attn.in_proj_') + new_v = torch.cat([v, ckpt[k.replace('attn.q.', 'attn.kv.')]], + dim=0) + elif 'mlp.fc1' in k: + new_k = k.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in k: + new_k = k.replace('mlp.fc2', 'ffn.layers.1') + # Only pcpvt + elif args.model == 'pcpvt': + if 'attn.proj.' in k: + new_k = k.replace('proj.', 'attn.out_proj.') + else: + new_k = k + + # Only svt + else: + if 'attn.proj.' in k: + k_lst = k.split('.') + if int(k_lst[2]) % 2 == 1: + new_k = k.replace('proj.', 'attn.out_proj.') + else: + new_k = k + else: + new_k = k + new_k = new_k.replace('blocks.', 'layers.') + elif k.startswith('pos_block'): + new_k = k.replace('pos_block', 'position_encodings') + if 'proj.0.' in new_k: + new_k = new_k.replace('proj.0.', 'proj.') + else: + new_k = k + if 'attn.kv.' not in k: + new_ckpt[new_k] = new_v + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + parser.add_argument('model', help='model: pcpvt or svt') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + + weight = convert_twins(args, state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/vit2mmseg.py b/third-party/InterFormer/tools/model_converters/vit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1f8a427e232290c6dcf490e33f777275dd238a --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/vit2mmseg.py @@ -0,0 +1,70 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_vit(ckpt): + + new_ckpt = OrderedDict() + + for k, v in ckpt.items(): + if k.startswith('head'): + continue + if k.startswith('norm'): + new_k = k.replace('norm.', 'ln1.') + elif k.startswith('patch_embed'): + if 'proj' in k: + new_k = k.replace('proj', 'projection') + else: + new_k = k + elif k.startswith('blocks'): + if 'norm' in k: + new_k = k.replace('norm', 'ln') + elif 'mlp.fc1' in k: + new_k = k.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in k: + new_k = k.replace('mlp.fc2', 'ffn.layers.1') + elif 'attn.qkv' in k: + new_k = k.replace('attn.qkv.', 'attn.attn.in_proj_') + elif 'attn.proj' in k: + new_k = k.replace('attn.proj', 'attn.attn.out_proj') + else: + new_k = k + new_k = new_k.replace('blocks.', 'layers.') + else: + new_k = k + new_ckpt[new_k] = v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + # deit checkpoint + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_vit(state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/model_converters/vitjax2mmseg.py b/third-party/InterFormer/tools/model_converters/vitjax2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..81bc2ea020e32d086fc4ce2153cc2bf51edd4d48 --- /dev/null +++ b/third-party/InterFormer/tools/model_converters/vitjax2mmseg.py @@ -0,0 +1,123 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import mmengine +import numpy as np +import torch + + +def vit_jax_to_torch(jax_weights, num_layer=12): + torch_weights = dict() + + # patch embedding + conv_filters = jax_weights['embedding/kernel'] + conv_filters = conv_filters.permute(3, 2, 0, 1) + torch_weights['patch_embed.projection.weight'] = conv_filters + torch_weights['patch_embed.projection.bias'] = jax_weights[ + 'embedding/bias'] + + # pos embedding + torch_weights['pos_embed'] = jax_weights[ + 'Transformer/posembed_input/pos_embedding'] + + # cls token + torch_weights['cls_token'] = jax_weights['cls'] + + # head + torch_weights['ln1.weight'] = jax_weights['Transformer/encoder_norm/scale'] + torch_weights['ln1.bias'] = jax_weights['Transformer/encoder_norm/bias'] + + # transformer blocks + for i in range(num_layer): + jax_block = f'Transformer/encoderblock_{i}' + torch_block = f'layers.{i}' + + # attention norm + torch_weights[f'{torch_block}.ln1.weight'] = jax_weights[ + f'{jax_block}/LayerNorm_0/scale'] + torch_weights[f'{torch_block}.ln1.bias'] = jax_weights[ + f'{jax_block}/LayerNorm_0/bias'] + + # attention + query_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/query/kernel'] + query_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/query/bias'] + key_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/key/kernel'] + key_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/key/bias'] + value_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/value/kernel'] + value_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/value/bias'] + + qkv_weight = torch.from_numpy( + np.stack((query_weight, key_weight, value_weight), 1)) + qkv_weight = torch.flatten(qkv_weight, start_dim=1) + qkv_bias = torch.from_numpy( + np.stack((query_bias, key_bias, value_bias), 0)) + qkv_bias = torch.flatten(qkv_bias, start_dim=0) + + torch_weights[f'{torch_block}.attn.attn.in_proj_weight'] = qkv_weight + torch_weights[f'{torch_block}.attn.attn.in_proj_bias'] = qkv_bias + to_out_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/out/kernel'] + to_out_weight = torch.flatten(to_out_weight, start_dim=0, end_dim=1) + torch_weights[ + f'{torch_block}.attn.attn.out_proj.weight'] = to_out_weight + torch_weights[f'{torch_block}.attn.attn.out_proj.bias'] = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/out/bias'] + + # mlp norm + torch_weights[f'{torch_block}.ln2.weight'] = jax_weights[ + f'{jax_block}/LayerNorm_2/scale'] + torch_weights[f'{torch_block}.ln2.bias'] = jax_weights[ + f'{jax_block}/LayerNorm_2/bias'] + + # mlp + torch_weights[f'{torch_block}.ffn.layers.0.0.weight'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_0/kernel'] + torch_weights[f'{torch_block}.ffn.layers.0.0.bias'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_0/bias'] + torch_weights[f'{torch_block}.ffn.layers.1.weight'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_1/kernel'] + torch_weights[f'{torch_block}.ffn.layers.1.bias'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_1/bias'] + + # transpose weights + for k, v in torch_weights.items(): + if 'weight' in k and 'patch_embed' not in k and 'ln' not in k: + v = v.permute(1, 0) + torch_weights[k] = v + + return torch_weights + + +def main(): + # stole refactoring code from Robin Strudel, thanks + parser = argparse.ArgumentParser( + description='Convert keys from jax official pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + jax_weights = np.load(args.src) + jax_weights_tensor = {} + for key in jax_weights.files: + value = torch.from_numpy(jax_weights[key]) + jax_weights_tensor[key] = value + if 'L_16-i21k' in args.src: + num_layer = 24 + else: + num_layer = 12 + torch_weights = vit_jax_to_torch(jax_weights_tensor, num_layer) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(torch_weights, args.dst) + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/slurm_test.sh b/third-party/InterFormer/tools/slurm_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e6f7bf4e33267f269cf0f455924cb70166ccd4b --- /dev/null +++ b/third-party/InterFormer/tools/slurm_test.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -x + +PARTITION=$1 +JOB_NAME=$2 +CONFIG=$3 +CHECKPOINT=$4 +GPUS=${GPUS:-4} +GPUS_PER_NODE=${GPUS_PER_NODE:-4} +CPUS_PER_TASK=${CPUS_PER_TASK:-5} +PY_ARGS=${@:5} +SRUN_ARGS=${SRUN_ARGS:-""} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +srun -p ${PARTITION} \ + --job-name=${JOB_NAME} \ + --gres=gpu:${GPUS_PER_NODE} \ + --ntasks=${GPUS} \ + --ntasks-per-node=${GPUS_PER_NODE} \ + --cpus-per-task=${CPUS_PER_TASK} \ + --kill-on-bad-exit=1 \ + ${SRUN_ARGS} \ + python -u tools/test.py ${CONFIG} ${CHECKPOINT} --launcher="slurm" ${PY_ARGS} diff --git a/third-party/InterFormer/tools/slurm_train.sh b/third-party/InterFormer/tools/slurm_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab232105f0309c720ed81a522eca14b6fbd64afd --- /dev/null +++ b/third-party/InterFormer/tools/slurm_train.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -x + +PARTITION=$1 +JOB_NAME=$2 +CONFIG=$3 +GPUS=${GPUS:-4} +GPUS_PER_NODE=${GPUS_PER_NODE:-4} +CPUS_PER_TASK=${CPUS_PER_TASK:-5} +SRUN_ARGS=${SRUN_ARGS:-""} +PY_ARGS=${@:4} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +srun -p ${PARTITION} \ + --job-name=${JOB_NAME} \ + --gres=gpu:${GPUS_PER_NODE} \ + --ntasks=${GPUS} \ + --ntasks-per-node=${GPUS_PER_NODE} \ + --cpus-per-task=${CPUS_PER_TASK} \ + --kill-on-bad-exit=1 \ + ${SRUN_ARGS} \ + python -u tools/train.py ${CONFIG} --launcher="slurm" ${PY_ARGS} diff --git a/third-party/InterFormer/tools/test.py b/third-party/InterFormer/tools/test.py new file mode 100644 index 0000000000000000000000000000000000000000..0d7f39b3a8b5f94d33ce8529755013451184d5ed --- /dev/null +++ b/third-party/InterFormer/tools/test.py @@ -0,0 +1,123 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp + +from mmengine.config import Config, DictAction +from mmengine.runner import Runner + + +# TODO: support fuse_conv_bn, visualization, and format_only +def parse_args(): + parser = argparse.ArgumentParser( + description='MMSeg test (and eval) a model') + parser.add_argument('config', help='train config file path') + parser.add_argument('checkpoint', help='checkpoint file') + parser.add_argument( + '--work-dir', + help=('if specified, the evaluation metric results will be dumped' + 'into the directory as json')) + parser.add_argument( + '--out', + type=str, + help='The directory to save output prediction for offline evaluation') + parser.add_argument( + '--show', action='store_true', help='show prediction results') + parser.add_argument( + '--show-dir', + help='directory where painted images will be saved. ' + 'If specified, it will be automatically saved ' + 'to the work_dir/timestamp/show_dir') + parser.add_argument( + '--wait-time', type=float, default=2, help='the interval of show (s)') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--launcher', + choices=['none', 'pytorch', 'slurm', 'mpi'], + default='none', + help='job launcher') + parser.add_argument( + '--tta', action='store_true', help='Test time augmentation') + # When using PyTorch version >= 2.0.0, the `torch.distributed.launch` + # will pass the `--local-rank` parameter to `tools/train.py` instead + # of `--local_rank`. + parser.add_argument('--local_rank', '--local-rank', type=int, default=0) + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + + return args + + +def trigger_visualization_hook(cfg, args): + default_hooks = cfg.default_hooks + if 'visualization' in default_hooks: + visualization_hook = default_hooks['visualization'] + # Turn on visualization + visualization_hook['draw'] = True + if args.show: + visualization_hook['show'] = True + visualization_hook['wait_time'] = args.wait_time + if args.show_dir: + visualizer = cfg.visualizer + visualizer['save_dir'] = args.show_dir + else: + raise RuntimeError( + 'VisualizationHook must be included in default_hooks.' + 'refer to usage ' + '"visualization=dict(type=\'VisualizationHook\')"') + + return cfg + + +def main(): + args = parse_args() + + # load config + cfg = Config.fromfile(args.config) + cfg.launcher = args.launcher + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # work_dir is determined in this priority: CLI > segment in file > filename + if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir + elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + + cfg.load_from = args.checkpoint + + if args.show or args.show_dir: + cfg = trigger_visualization_hook(cfg, args) + + if args.tta: + cfg.test_dataloader.dataset.pipeline = cfg.tta_pipeline + cfg.tta_model.module = cfg.model + cfg.model = cfg.tta_model + + # add output_dir in metric + if args.out is not None: + cfg.test_evaluator['output_dir'] = args.out + cfg.test_evaluator['keep_results'] = True + + # build the runner from config + runner = Runner.from_cfg(cfg) + + # start testing + runner.test() + + +if __name__ == '__main__': + main() diff --git a/third-party/InterFormer/tools/torchserve/mmseg2torchserve.py b/third-party/InterFormer/tools/torchserve/mmseg2torchserve.py new file mode 100644 index 0000000000000000000000000000000000000000..23f99638e799fd0b37a6737cc833dd7d24f611f8 --- /dev/null +++ b/third-party/InterFormer/tools/torchserve/mmseg2torchserve.py @@ -0,0 +1,112 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from argparse import ArgumentParser, Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + +from mmengine import Config +from mmengine.utils import mkdir_or_exist + +try: + from model_archiver.model_packaging import package_model + from model_archiver.model_packaging_utils import ModelExportUtils +except ImportError: + package_model = None + + +def mmseg2torchserve( + config_file: str, + checkpoint_file: str, + output_folder: str, + model_name: str, + model_version: str = '1.0', + force: bool = False, +): + """Converts mmsegmentation model (config + checkpoint) to TorchServe + `.mar`. + + Args: + config_file: + In MMSegmentation config format. + The contents vary for each task repository. + checkpoint_file: + In MMSegmentation checkpoint format. + The contents vary for each task repository. + output_folder: + Folder where `{model_name}.mar` will be created. + The file created will be in TorchServe archive format. + model_name: + If not None, used for naming the `{model_name}.mar` file + that will be created under `output_folder`. + If None, `{Path(checkpoint_file).stem}` will be used. + model_version: + Model's version. + force: + If True, if there is an existing `{model_name}.mar` + file under `output_folder` it will be overwritten. + """ + mkdir_or_exist(output_folder) + + config = Config.fromfile(config_file) + + with TemporaryDirectory() as tmpdir: + config.dump(f'{tmpdir}/config.py') + + args = Namespace( + **{ + 'model_file': f'{tmpdir}/config.py', + 'serialized_file': checkpoint_file, + 'handler': f'{Path(__file__).parent}/mmseg_handler.py', + 'model_name': model_name or Path(checkpoint_file).stem, + 'version': model_version, + 'export_path': output_folder, + 'force': force, + 'requirements_file': None, + 'extra_files': None, + 'runtime': 'python', + 'archive_format': 'default' + }) + manifest = ModelExportUtils.generate_manifest_json(args) + package_model(args, manifest) + + +def parse_args(): + parser = ArgumentParser( + description='Convert mmseg models to TorchServe `.mar` format.') + parser.add_argument('config', type=str, help='config file path') + parser.add_argument('checkpoint', type=str, help='checkpoint file path') + parser.add_argument( + '--output-folder', + type=str, + required=True, + help='Folder where `{model_name}.mar` will be created.') + parser.add_argument( + '--model-name', + type=str, + default=None, + help='If not None, used for naming the `{model_name}.mar`' + 'file that will be created under `output_folder`.' + 'If None, `{Path(checkpoint_file).stem}` will be used.') + parser.add_argument( + '--model-version', + type=str, + default='1.0', + help='Number used for versioning.') + parser.add_argument( + '-f', + '--force', + action='store_true', + help='overwrite the existing `{model_name}.mar`') + args = parser.parse_args() + + return args + + +if __name__ == '__main__': + args = parse_args() + + if package_model is None: + raise ImportError('`torch-model-archiver` is required.' + 'Try: pip install torch-model-archiver') + + mmseg2torchserve(args.config, args.checkpoint, args.output_folder, + args.model_name, args.model_version, args.force) diff --git a/third-party/InterFormer/tools/torchserve/mmseg_handler.py b/third-party/InterFormer/tools/torchserve/mmseg_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..dbe5ded8482c1113a6adb45a22b650af71f6294e --- /dev/null +++ b/third-party/InterFormer/tools/torchserve/mmseg_handler.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import base64 +import os + +import cv2 +import mmcv +import torch +from mmengine.model.utils import revert_sync_batchnorm +from ts.torch_handler.base_handler import BaseHandler + +from mmseg.apis import inference_model, init_model + + +class MMsegHandler(BaseHandler): + + def initialize(self, context): + properties = context.system_properties + self.map_location = 'cuda' if torch.cuda.is_available() else 'cpu' + self.device = torch.device(self.map_location + ':' + + str(properties.get('gpu_id')) if torch.cuda. + is_available() else self.map_location) + self.manifest = context.manifest + + model_dir = properties.get('model_dir') + serialized_file = self.manifest['model']['serializedFile'] + checkpoint = os.path.join(model_dir, serialized_file) + self.config_file = os.path.join(model_dir, 'config.py') + + self.model = init_model(self.config_file, checkpoint, self.device) + self.model = revert_sync_batchnorm(self.model) + self.initialized = True + + def preprocess(self, data): + images = [] + + for row in data: + image = row.get('data') or row.get('body') + if isinstance(image, str): + image = base64.b64decode(image) + image = mmcv.imfrombytes(image) + images.append(image) + + return images + + def inference(self, data, *args, **kwargs): + results = [inference_model(self.model, img) for img in data] + return results + + def postprocess(self, data): + output = [] + + for image_result in data: + _, buffer = cv2.imencode('.png', image_result[0].astype('uint8')) + content = buffer.tobytes() + output.append(content) + return output diff --git a/third-party/InterFormer/tools/torchserve/test_torchserve.py b/third-party/InterFormer/tools/torchserve/test_torchserve.py new file mode 100644 index 0000000000000000000000000000000000000000..b015b6658556e5045af2daf5d998de0de61e1f6b --- /dev/null +++ b/third-party/InterFormer/tools/torchserve/test_torchserve.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from argparse import ArgumentParser +from io import BytesIO + +import matplotlib.pyplot as plt +import mmcv +import requests + +from mmseg.apis import inference_model, init_model + + +def parse_args(): + parser = ArgumentParser( + description='Compare result of torchserve and pytorch,' + 'and visualize them.') + parser.add_argument('img', help='Image file') + parser.add_argument('config', help='Config file') + parser.add_argument('checkpoint', help='Checkpoint file') + parser.add_argument('model_name', help='The model name in the server') + parser.add_argument( + '--inference-addr', + default='127.0.0.1:8080', + help='Address and port of the inference server') + parser.add_argument( + '--result-image', + type=str, + default=None, + help='save server output in result-image') + parser.add_argument( + '--device', default='cuda:0', help='Device used for inference') + + args = parser.parse_args() + return args + + +def main(args): + url = 'http://' + args.inference_addr + '/predictions/' + args.model_name + with open(args.img, 'rb') as image: + tmp_res = requests.post(url, image) + content = tmp_res.content + if args.result_image: + with open(args.result_image, 'wb') as out_image: + out_image.write(content) + plt.imshow(mmcv.imread(args.result_image, 'grayscale')) + plt.show() + else: + plt.imshow(plt.imread(BytesIO(content))) + plt.show() + model = init_model(args.config, args.checkpoint, args.device) + image = mmcv.imread(args.img) + result = inference_model(model, image) + plt.imshow(result[0]) + plt.show() + + +if __name__ == '__main__': + args = parse_args() + main(args) diff --git a/third-party/InterFormer/tools/train.py b/third-party/InterFormer/tools/train.py new file mode 100644 index 0000000000000000000000000000000000000000..10fdaa1874be0348f3945296a29526236c103d9f --- /dev/null +++ b/third-party/InterFormer/tools/train.py @@ -0,0 +1,104 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import logging +import os +import os.path as osp + +from mmengine.config import Config, DictAction +from mmengine.logging import print_log +from mmengine.runner import Runner + +from mmseg.registry import RUNNERS + + +def parse_args(): + parser = argparse.ArgumentParser(description='Train a segmentor') + parser.add_argument('config', help='train config file path') + parser.add_argument('--work-dir', help='the dir to save logs and models') + parser.add_argument( + '--resume', + action='store_true', + default=False, + help='resume from the latest checkpoint in the work_dir automatically') + parser.add_argument( + '--amp', + action='store_true', + default=False, + help='enable automatic-mixed-precision training') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--launcher', + choices=['none', 'pytorch', 'slurm', 'mpi'], + default='none', + help='job launcher') + # When using PyTorch version >= 2.0.0, the `torch.distributed.launch` + # will pass the `--local-rank` parameter to `tools/train.py` instead + # of `--local_rank`. + parser.add_argument('--local_rank', '--local-rank', type=int, default=0) + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + + return args + + +def main(): + args = parse_args() + + # load config + cfg = Config.fromfile(args.config) + cfg.launcher = args.launcher + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # work_dir is determined in this priority: CLI > segment in file > filename + if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir + elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + + # enable automatic-mixed-precision training + if args.amp is True: + optim_wrapper = cfg.optim_wrapper.type + if optim_wrapper == 'AmpOptimWrapper': + print_log( + 'AMP training is already enabled in your config.', + logger='current', + level=logging.WARNING) + else: + assert optim_wrapper == 'OptimWrapper', ( + '`--amp` is only supported when the optimizer wrapper type is ' + f'`OptimWrapper` but got {optim_wrapper}.') + cfg.optim_wrapper.type = 'AmpOptimWrapper' + cfg.optim_wrapper.loss_scale = 'dynamic' + + # resume training + cfg.resume = args.resume + + # build the runner from config + if 'runner_type' not in cfg: + # build the default runner + runner = Runner.from_cfg(cfg) + else: + # build customized runner from the registry + # if 'runner_type' is set in the cfg + runner = RUNNERS.build(cfg) + + # start training + runner.train() + + +if __name__ == '__main__': + main() diff --git a/third-party/coordex/.gitignore b/third-party/coordex/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ef853185e6b37ca2502c0f4187e2b69ecf590daf --- /dev/null +++ b/third-party/coordex/.gitignore @@ -0,0 +1,26 @@ +# Python bytecode/cache +__pycache__/ +*.py[cod] +*$py.class + +# Python packaging/build artifacts +*.egg-info/ +.eggs/ +build/ +dist/ + +# Local test/type/lint caches +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.coverage +htmlcov/ + +# Local rollout/output artifacts +videos/ +logs/ +outputs/ + +# OS/editor noise +.DS_Store +*~ diff --git a/third-party/coordex/README.md b/third-party/coordex/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9be45cbadfa88b0260891c4eeb1fc2efa32d78f0 --- /dev/null +++ b/third-party/coordex/README.md @@ -0,0 +1,155 @@ +
+ +# CoorDex: Coordinating Body and Hand Priors for Continuous Dexterous Humanoid Loco-Manipulation + +**Sikai Li**1, **Shuning Li**1, **Zhenyu Wei**1, **Yunchao Yao**1, **Chenran Li**2, **Mingyu Ding**1 + +1University of North Carolina at Chapel Hill 2University of California, Berkeley + +[![IsaacSim](https://img.shields.io/badge/IsaacSim-5.0.0-silver.svg)](https://docs.isaacsim.omniverse.nvidia.com/5.0.0/index.html) +[![Isaac Lab](https://img.shields.io/badge/IsaacLab-2.2.0-silver)](https://isaac-sim.github.io/IsaacLab/v2.2.0/index.html) +[![Python](https://img.shields.io/badge/python-3.11-blue.svg)](https://docs.python.org/3/whatsnew/3.11.html) + +[![Paper arXiv](https://img.shields.io/badge/Paper-arXiv-red?style=plastic&logo=arXiv&logoColor=red)](https://arxiv.org/abs/2606.23680) +[![Project Page](https://img.shields.io/badge/Project-Page-blue)](https://skevinci.github.io/coordex/) + +
+ +Teaser + +## Overview +The codebase supports: + +- G1 Wuji loco-manipulation rollout for WalkGrab, OpenFridge, and WalkPickTurn. +- Frozen body/hand priors plus trained coord-residual policy checkpoints. + +## Table of Contents + +- [CoorDex: Coordinating Body and Hand Priors for Continuous Dexterous Humanoid Loco-Manipulation](#coordex-coordinating-body-and-hand-priors-for-continuous-dexterous-humanoid-loco-manipulation) + - [Overview](#overview) + - [Table of Contents](#table-of-contents) + - [Prerequisites](#prerequisites) + - [Installation](#installation) + - [1. Create conda environment](#1-create-conda-environment) + - [2. Install Isaac Sim 5.0](#2-install-isaac-sim-50) + - [3. Install Isaac Lab 2.2.0](#3-install-isaac-lab-220) + - [4. Install this package](#4-install-this-package) + - [Usage](#usage) + - [Locomanip Rollout](#locomanip-rollout) + - [Project Structure](#project-structure) + - [Contact](#contact) + +## Prerequisites +- [Isaac Sim 5.0](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html) +- [Isaac Lab 2.2.0](https://isaac-sim.github.io/IsaacLab/) +- Conda + +## Installation +### 1. Create conda environment +```bash +conda create -n coordex python=3.11 -y +conda activate coordex +``` + +### 2. Install Isaac Sim 5.0 +```bash +pip install torch==2.7.0 torchvision==0.22.0 --index-url https://download.pytorch.org/whl/cu128 +pip install "isaacsim[all,extscache]==5.0.0" --extra-index-url https://pypi.nvidia.com +``` + +### 3. Install Isaac Lab 2.2.0 +```bash +sudo apt install cmake build-essential + +# Clone Isaac Lab +git clone git@github.com:isaac-sim/IsaacLab.git + +cd IsaacLab +git checkout v2.2.0 +./isaaclab.sh --install +``` + + +### 4. Install this package +```bash +# Clone this repository separately from the Isaac Lab installation +git clone git@github.com:Skevinci/CoorDex.git + +cd CoorDex +python -m pip install -e source/coordex +``` + +## Usage +### Locomanip Rollout + +Three public Gym task IDs are registered: + +- `CoorDex-WalkGrab-Wuji-v0` +- `CoorDex-Fridge-Wuji-v0` +- `CoorDex-WalkPickTurn-Wuji-v0` + +The rollout script selects the matching policy, body prior, and hand prior checkpoint from `ckpts/` by default: + +```bash +python scripts/rsl_rl/play_locomanip.py \ + --task CoorDex-WalkGrab-Wuji-v0 \ + --headless --num_envs 1 +``` + +Checkpoint overrides are available when needed: + +```bash +python scripts/rsl_rl/play_locomanip.py \ + --task CoorDex-WalkPickTurn-Wuji-v0 \ + --checkpoint /path/to/policy.pt \ + --body-prior-checkpoint /path/to/body_prior.pt \ + --hand-prior-checkpoint /path/to/hand_prior.pt +``` + +## Project Structure + +```bash +CoorDex +├── assets # Figures and media used by the README/project page +├── ckpts # Released rollout checkpoints and frozen prior checkpoints +│ ├── body_prior # Body prior VAE checkpoints +│ ├── hand_prior # Wuji hand prior VAE checkpoints +│ └── locomanip # Coord-residual policy checkpoints for the three tasks +├── config # Isaac Lab extension metadata +├── scripts +│ └── rsl_rl +│ └── play_locomanip.py # Roll out WalkGrab, Fridge, and WalkPickTurn policies +└── source + └── coordex + ├── setup.py # Python package entry point + ├── pyproject.toml # Package build metadata + └── coordex + ├── assets # USD assets for G1 Wuji, fridge, and condiment object + ├── distillation # Minimal VAE modules used by the frozen priors + ├── policies # Coord-residual actor-critic used for checkpoint loading + ├── robots # G1 Wuji robot configuration + └── tasks + └── locomanip + ├── walkgrab_env_cfg.py # WalkGrab environment config + ├── fridge_env_cfg.py # Fridge environment config + ├── walkpickturn_env_cfg.py # WalkPickTurn environment config + ├── config/g1_wuji # RSL-RL runner and agent config + └── mdp # Actions, commands, observations, rewards, events, and terminations +``` + +## Citation +If you find this work useful, please cite: +```bibtex +@misc{li2026coordexcoordinatingbodyhand, + title={CoorDex: Coordinating Body and Hand Priors for Continuous Dexterous Humanoid Loco-Manipulation}, + author={Sikai Li and Shuning Li and Zhenyu Wei and Yunchao Yao and Chenran Li and Mingyu Ding}, + year={2026}, + eprint={2606.23680}, + archivePrefix={arXiv}, + primaryClass={cs.RO}, + url={https://arxiv.org/abs/2606.23680}, +} +``` + +## Contact +If you have any questions, feel free to contact me through email ([sikaili@cs.unc.edu](mailto:sikaili@cs.unc.edu)). diff --git a/third-party/coordex/assets/Method_final.svg b/third-party/coordex/assets/Method_final.svg new file mode 100644 index 0000000000000000000000000000000000000000..886a0bc7c6f9c2656ff5ec008cb8f7b0003aa3b8 --- /dev/null +++ b/third-party/coordex/assets/Method_final.svg @@ -0,0 +1,2327 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/coordex/config/extension.toml b/third-party/coordex/config/extension.toml new file mode 100644 index 0000000000000000000000000000000000000000..d360eba794b6fb36b6b6f379ccaf7a2b69fefc26 --- /dev/null +++ b/third-party/coordex/config/extension.toml @@ -0,0 +1,15 @@ +[package] +version = "0.1.0" +title = "CoorDex" +description = "CoorDex locomanip rollout tasks for IsaacLab." +category = "robotics" +keywords = ["isaaclab", "locomanip", "coordex"] + +[dependencies] +"isaaclab" = {} +"isaaclab_assets" = {} +"isaaclab_rl" = {} +"isaaclab_tasks" = {} + +[[python.module]] +name = "coordex" diff --git a/third-party/coordex/scripts/rsl_rl/play_locomanip.py b/third-party/coordex/scripts/rsl_rl/play_locomanip.py new file mode 100644 index 0000000000000000000000000000000000000000..733ef25fc39247f04ad726581bfee2802c90fe31 --- /dev/null +++ b/third-party/coordex/scripts/rsl_rl/play_locomanip.py @@ -0,0 +1,193 @@ +from __future__ import annotations + +import argparse +import os +import pathlib +import sys +from math import prod + +REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] +SOURCE_ROOT = REPO_ROOT / "source" / "coordex" +for path in (REPO_ROOT, SOURCE_ROOT): + path_str = str(path) + if path_str not in sys.path: + sys.path.insert(0, path_str) + +from isaaclab.app import AppLauncher + + +DEFAULTS = { + "CoorDex-WalkGrab-Wuji-v0": { + "checkpoint": "ckpts/locomanip/walkgrab_8k.pt", + "body_prior": "ckpts/body_prior/walkgrab_10k.pt", + "hand_prior": "ckpts/hand_prior/kinematic_wrist_16k.pt", + }, + "CoorDex-Fridge-Wuji-v0": { + "checkpoint": "ckpts/locomanip/fridge_10k.pt", + "body_prior": "ckpts/body_prior/fridge_2k.pt", + "hand_prior": "ckpts/hand_prior/kinematic_wrist_16k.pt", + }, + "CoorDex-WalkPickTurn-Wuji-v0": { + "checkpoint": "ckpts/locomanip/walkpickturn_30k.pt", + "body_prior": "ckpts/body_prior/walkpickturn_30k.pt", + "hand_prior": "ckpts/hand_prior/active_wrist_20k.pt", + }, +} + + +parser = argparse.ArgumentParser( + description="Roll out a CoorDex locomanip checkpoint.") +parser.add_argument( + "--task", default="CoorDex-WalkGrab-Wuji-v0", choices=tuple(DEFAULTS)) +parser.add_argument("--checkpoint", default=None, + help="Policy checkpoint. Defaults are selected from --task.") +parser.add_argument("--body-prior-checkpoint", default=None, + help="Frozen body prior checkpoint override.") +parser.add_argument("--hand-prior-checkpoint", default=None, + help="Frozen hand prior checkpoint override.") +parser.add_argument("--num_envs", type=int, default=1, + help="Number of parallel environments.") +parser.add_argument("--seed", type=int, default=None, help="Environment seed.") +parser.add_argument("--max_steps", type=int, default=None, + help="Optional rollout step limit.") +parser.add_argument("--video", action="store_true", + help="Record a video from the rollout.") +parser.add_argument("--video_length", type=int, default=500, + help="Number of sim steps to record.") +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = parser.parse_known_args() +sys.argv = [sys.argv[0], *hydra_args] +if args_cli.video: + args_cli.enable_cameras = True + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + + +import gymnasium as gym +import torch +from coordex.policies import ActorCriticCoordResidual +from isaaclab.envs import DirectMARLEnv, multi_agent_to_single_agent +from isaaclab.utils.dict import print_dict +from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper +from isaaclab_tasks.utils.hydra import hydra_task_config +from rsl_rl.runners.on_policy_runner import OnPolicyRunner + +import coordex.tasks.locomanip # noqa: F401 + + +def _resolve_path(path: str | os.PathLike[str]) -> str: + candidate = pathlib.Path(path).expanduser() + if not candidate.is_absolute(): + candidate = REPO_ROOT / candidate + candidate = candidate.resolve() + if not candidate.is_file(): + raise FileNotFoundError(f"Checkpoint not found: {candidate}") + return str(candidate) + + +def _term_dim_to_int(dim) -> int: + if isinstance(dim, int): + return int(dim) + if isinstance(dim, tuple): + return int(prod(dim)) + return int(prod(int(value) for value in dim)) + + +def _inject_coord_residual_actor_metadata(env, agent_cfg) -> None: + policy_cfg = getattr(agent_cfg, "policy", None) + if getattr(policy_cfg, "class_name", "") != "ActorCriticCoordResidual": + return + obs_mgr = getattr(env.unwrapped, "observation_manager", None) + if obs_mgr is None: + raise RuntimeError( + "CoordResidual policy requires a ManagerBased env observation manager.") + policy_cfg.actor_obs_term_names = tuple( + obs_mgr._group_obs_term_names["policy"]) + policy_cfg.actor_obs_term_dims = [_term_dim_to_int( + dim) for dim in obs_mgr._group_obs_term_dim["policy"]] + + +def _register_policy_classes() -> None: + from rsl_rl import modules as rsl_modules + from rsl_rl.runners import on_policy_runner as runner_module + + runner_module.ActorCriticCoordResidual = ActorCriticCoordResidual + rsl_modules.ActorCriticCoordResidual = ActorCriticCoordResidual + + +@hydra_task_config(args_cli.task, "rsl_rl_cfg_entry_point") +def main(env_cfg, agent_cfg): + defaults = DEFAULTS[args_cli.task] + checkpoint = _resolve_path(args_cli.checkpoint or defaults["checkpoint"]) + body_prior = _resolve_path( + args_cli.body_prior_checkpoint or defaults["body_prior"]) + hand_prior = _resolve_path( + args_cli.hand_prior_checkpoint or defaults["hand_prior"]) + + if args_cli.num_envs is not None: + env_cfg.scene.num_envs = args_cli.num_envs + if args_cli.seed is not None: + env_cfg.seed = args_cli.seed + agent_cfg.seed = args_cli.seed + if hasattr(args_cli, "device") and args_cli.device is not None: + env_cfg.sim.device = args_cli.device + agent_cfg.device = args_cli.device + + joint_action_cfg = getattr( + getattr(env_cfg, "actions", None), "joint_pos", None) + if joint_action_cfg is None: + raise RuntimeError("Locomanip env is missing actions.joint_pos.") + joint_action_cfg.body_prior_checkpoint = body_prior + joint_action_cfg.hand_prior_checkpoint = hand_prior + + print(f"[INFO] Task: {args_cli.task}") + print(f"[INFO] Policy checkpoint: {checkpoint}") + print(f"[INFO] Body prior: {body_prior}") + print(f"[INFO] Hand prior: {hand_prior}") + + env = gym.make(args_cli.task, cfg=env_cfg, + render_mode="rgb_array" if args_cli.video else None) + _inject_coord_residual_actor_metadata(env, agent_cfg) + + if args_cli.video: + video_kwargs = { + "video_folder": str(REPO_ROOT / "videos" / args_cli.task), + "step_trigger": lambda step: step == 0, + "video_length": args_cli.video_length, + "disable_logger": True, + } + print("[INFO] Recording video.") + print_dict(video_kwargs, nesting=4) + env = gym.wrappers.RecordVideo(env, **video_kwargs) + + if isinstance(env.unwrapped, DirectMARLEnv): + env = multi_agent_to_single_agent(env) + + env = RslRlVecEnvWrapper(env) + _register_policy_classes() + runner = OnPolicyRunner(env, agent_cfg.to_dict(), + log_dir=None, device=agent_cfg.device) + runner.load(checkpoint, load_optimizer=False) + policy = runner.get_inference_policy(device=env.unwrapped.device) + + rollout_steps = args_cli.max_steps + if args_cli.video and rollout_steps is None: + rollout_steps = args_cli.video_length + + obs, _ = env.get_observations() + step = 0 + while simulation_app.is_running(): + with torch.inference_mode(): + actions = policy(obs) + obs, _, _, _ = env.step(actions) + step += 1 + if rollout_steps is not None and step >= rollout_steps: + break + + env.close() + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/third-party/coordex/source/coordex/coordex/__init__.py b/third-party/coordex/source/coordex/coordex/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc03566e331c7989fcd2dfd84fb4ce2ee597ac4 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/__init__.py @@ -0,0 +1,2 @@ +"""CoorDex IsaacLab tasks and assets.""" + diff --git a/third-party/coordex/source/coordex/coordex/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93557ad7a651e1bd94f8214c7bfb86ddbed3c6f1 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/assets/__init__.py b/third-party/coordex/source/coordex/coordex/assets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8560b524372a634e2f99998e64735f7f6e17c93d --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/assets/__init__.py @@ -0,0 +1,8 @@ +"""Asset paths used by CoorDex tasks.""" + +from __future__ import annotations + +import os + +ASSET_DIR = os.path.abspath(os.path.dirname(__file__)) + diff --git a/third-party/coordex/source/coordex/coordex/assets/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/assets/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3e4a41c5be196fc56f7cd7e6ff413822972c5d7 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/assets/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/assets/g1_wuji/.asset_hash b/third-party/coordex/source/coordex/coordex/assets/g1_wuji/.asset_hash new file mode 100644 index 0000000000000000000000000000000000000000..a5321dfd4891bfc852d9e7a138298ae92237d78d --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/assets/g1_wuji/.asset_hash @@ -0,0 +1 @@ +cd6d21fe95e9074f9f395d843936a1d2 \ No newline at end of file diff --git a/third-party/coordex/source/coordex/coordex/assets/g1_wuji/config.yaml b/third-party/coordex/source/coordex/coordex/assets/g1_wuji/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2689ef7766aed89414237816a7b4b1148c5c0aa --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/assets/g1_wuji/config.yaml @@ -0,0 +1,23 @@ +asset_path: source/coordex/coordex/assets/g1_wuji/g1_wuji.urdf +usd_dir: source/coordex/coordex/assets/g1_wuji +usd_file_name: g1_wuji_no_merge.usd +force_usd_conversion: true +make_instanceable: true +fix_base: false +root_link_name: null +link_density: 0.0 +merge_fixed_joints: false +convert_mimic_joints_to_normal_joints: true +joint_drive: + drive_type: force + target_type: position + gains: + stiffness: 100.0 + damping: 1.0 +collider_type: convex_hull +self_collision: false +replace_cylinders_with_capsules: false +collision_from_visuals: false +## +# Generated by UrdfConverter on 2026-04-04 at 21:25:34. +## diff --git a/third-party/coordex/source/coordex/coordex/assets/g1_wuji/g1_wuji.urdf b/third-party/coordex/source/coordex/coordex/assets/g1_wuji/g1_wuji.urdf new file mode 100644 index 0000000000000000000000000000000000000000..2a956ec13540997a833f7436d98a65a168605ee4 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/assets/g1_wuji/g1_wuji.urdf @@ -0,0 +1,3182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/coordex/source/coordex/coordex/assets/g1_wuji/g1_wuji_fixed.urdf b/third-party/coordex/source/coordex/coordex/assets/g1_wuji/g1_wuji_fixed.urdf new file mode 100644 index 0000000000000000000000000000000000000000..d9afaf7134969ef6214f5b4a33afd2bf282b4083 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/assets/g1_wuji/g1_wuji_fixed.urdf @@ -0,0 +1,3182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/coordex/source/coordex/coordex/assets/objects/condiment/resource/v_69323/element_path.json b/third-party/coordex/source/coordex/coordex/assets/objects/condiment/resource/v_69323/element_path.json new file mode 100644 index 0000000000000000000000000000000000000000..1713e7b37440629db731cd24a7a0d054cf3fd44d --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/assets/objects/condiment/resource/v_69323/element_path.json @@ -0,0 +1,7 @@ +{ + "169": "/root/E_body_169", + "199": "/root/E_body_169/E_part1_199", + "200": "/root/E_knob_200", + "203": "/root/E_knob_200/E_part1_1_203", + "204": "/root/E_body_169/E_part2_204" +} \ No newline at end of file diff --git a/third-party/coordex/source/coordex/coordex/assets/objects/fridge/Isaac Sim 4.5/isaac-sim-assets/Materials/2023_2_1/Base/Glass/Clear_Glass.mdl b/third-party/coordex/source/coordex/coordex/assets/objects/fridge/Isaac Sim 4.5/isaac-sim-assets/Materials/2023_2_1/Base/Glass/Clear_Glass.mdl new file mode 100644 index 0000000000000000000000000000000000000000..d6c08a66ec3d6465474bf1e93968a42c369059a1 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/assets/objects/fridge/Isaac Sim 4.5/isaac-sim-assets/Materials/2023_2_1/Base/Glass/Clear_Glass.mdl @@ -0,0 +1,43 @@ +mdl 1.3; + +import ::OmniGlass::OmniGlass; +import ::tex::gamma_mode; +import ::state::normal; + +export material Clear_Glass(*) + = OmniGlass::OmniGlass( + absorption_coeff: color(1.f, 1.f, 1.f), + glass_color: color(1.f, 1.f, 1.f), + use_glass_color_texture: false, + glass_color_texture: texture_2d(), + frosting_roughness: 0.f, + glass_ior: 1.52f, + thin_walled: true, + project_uvw: false, + world_or_object: false, + uv_space_index: 0, + texture_translate: float2(0.f), + texture_rotate: 0.f, + texture_scale: float2(1.f)); + +/* +mdl 1.5; + +import ::Library::AEC::Materials::Templates::GlassWithVolume::GlassWithVolume; +import ::tex::gamma_mode; +import ::state::normal; + +export material Clear_Glass(*) + = ::Library::AEC::Materials::Templates::GlassWithVolume::GlassWithVolume( + thin_walled: true, + transmission_color: color(1.f, 1.f, 1.f), + roughness_texture: texture_2d(), + ior: 1.52f, + transmission_color_texture: texture_2d(), + roughness_texture_influence: 0.f, + roughness: 0.f, + reflection_color_texture: texture_2d(), + reflection_color: color(1.f, 1.f, 1.f), + depth: 0.0001f, + normal_map_texture: texture_2d()); +*/ diff --git a/third-party/coordex/source/coordex/coordex/distillation/__init__.py b/third-party/coordex/source/coordex/coordex/distillation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..772a636cba0bd221a20eef366f19750a50c65f97 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/distillation/__init__.py @@ -0,0 +1,5 @@ +"""Distillation policy modules used by frozen priors.""" + +from .vae import StudentTeacherVAE + +__all__ = ["StudentTeacherVAE"] diff --git a/third-party/coordex/source/coordex/coordex/distillation/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/distillation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80d00da83d5829d047127916aceadd6877d37acc Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/distillation/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/distillation/__pycache__/vae.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/distillation/__pycache__/vae.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fe2c87934b3c9998ba18957bde1e41a2057c30c Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/distillation/__pycache__/vae.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/distillation/vae.py b/third-party/coordex/source/coordex/coordex/distillation/vae.py new file mode 100644 index 0000000000000000000000000000000000000000..1b34d50ecbd3f642b0e786b15068932ed8178811 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/distillation/vae.py @@ -0,0 +1,1020 @@ +from __future__ import annotations + +import math +from typing import Dict, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.distributions import Normal + +from rsl_rl.utils import resolve_nn_activation +from rsl_rl.algorithms.distillation import Distillation +from rsl_rl.storage import RolloutStorage + + +def _build_mlp(input_dim: int, hidden_dims: Tuple[int, ...], output_dim: int, activation: nn.Module) -> nn.Sequential: + layers: list[nn.Module] = [] + prev_dim = input_dim + for hidden_dim in hidden_dims: + layers.append(nn.Linear(prev_dim, hidden_dim)) + layers.append(activation) + prev_dim = hidden_dim + layers.append(nn.Linear(prev_dim, output_dim)) + return nn.Sequential(*layers) + + +def _gaussian_kl( + posterior_mean: torch.Tensor, + posterior_log_std: torch.Tensor, + prior_mean: torch.Tensor, + prior_log_std: torch.Tensor, +) -> torch.Tensor: + """Closed-form KL divergence between two diagonal Gaussians.""" + posterior_var = torch.exp(2.0 * posterior_log_std) + prior_var = torch.exp(2.0 * prior_log_std) + squared_mean_diff = (posterior_mean - prior_mean) ** 2 + kl = prior_log_std - posterior_log_std + kl += (posterior_var + squared_mean_diff) / (2.0 * prior_var) + kl -= 0.5 + return kl.sum(dim=-1).mean() + + +def _gaussian_kl_per_env( + posterior_mean: torch.Tensor, + posterior_log_std: torch.Tensor, + prior_mean: torch.Tensor, + prior_log_std: torch.Tensor, +) -> torch.Tensor: + """Closed-form KL divergence between two diagonal Gaussians for each sample.""" + posterior_var = torch.exp(2.0 * posterior_log_std) + prior_var = torch.exp(2.0 * prior_log_std) + squared_mean_diff = (posterior_mean - prior_mean) ** 2 + kl = prior_log_std - posterior_log_std + kl += (posterior_var + squared_mean_diff) / (2.0 * prior_var) + kl -= 0.5 + return kl.sum(dim=-1) + + +def _masked_mean(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + """Mean over the leading batch dimension using a boolean mask.""" + if values.ndim == 0: + return values + if mask.ndim > 1: + mask = mask.view(mask.shape[0], -1).all(dim=-1) + mask = mask.to(dtype=torch.bool, device=values.device) + if values.shape[0] != mask.shape[0]: + raise ValueError( + f"Masked mean expected matching batch dimensions, got values={values.shape}, mask={mask.shape}." + ) + if not torch.any(mask): + return values.sum() * 0.0 + return values[mask].mean() + + +class SafeRolloutStorage(RolloutStorage): + """Rollout storage that tracks per-env sample validity for distillation.""" + + def __init__( + self, + training_type, + num_envs, + num_transitions_per_env, + obs_shape, + privileged_obs_shape, + actions_shape, + rnd_state_shape=None, + device="cpu", + ): + super().__init__( + training_type, + num_envs, + num_transitions_per_env, + obs_shape, + privileged_obs_shape, + actions_shape, + rnd_state_shape=rnd_state_shape, + device=device, + ) + self.valid_masks = torch.ones( + num_transitions_per_env, + num_envs, + 1, + dtype=torch.bool, + device=self.device, + ) + + def add_transitions(self, transition: RolloutStorage.Transition): + valid_mask = getattr(transition, "valid_mask", None) + if valid_mask is None: + self.valid_masks[self.step].fill_(True) + else: + self.valid_masks[self.step].copy_( + valid_mask.view(-1, 1).to(device=self.device, dtype=torch.bool)) + super().add_transitions(transition) + + def generator(self): + if self.training_type != "distillation": + raise ValueError( + "This function is only available for distillation training.") + + for i in range(self.num_transitions_per_env): + if self.privileged_observations is not None: + privileged_observations = self.privileged_observations[i] + else: + privileged_observations = self.observations[i] + yield ( + self.observations[i], + privileged_observations, + self.actions[i], + self.privileged_actions[i], + self.dones[i], + self.valid_masks[i], + ) + + +class StudentTeacherVAE(nn.Module): + """Student-teacher policy with a VAE-style latent bottleneck for the student.""" + + is_recurrent = False + + def __init__( + self, + num_student_obs: int, + num_teacher_obs: int, + num_actions: int, + *, + activation: str, + init_noise_std: float, + teacher_hidden_dims: Tuple[int, ...], + latent_dim: int, + encoder_hidden_dims: Tuple[int, ...], + decoder_hidden_dims: Tuple[int, ...], + prior_hidden_dims: Tuple[int, ...], + posterior_std_min: float = 1.0e-4, + posterior_std_max: float = 3, + prior_std_min: float = 1.0e-4, + prior_std_max: float = 3, + latent_dropout: float = 0.0, + tanh_actions: bool = False, + proprio_dim: int | None = None, + **kwargs, + ): + super().__init__() + + action_loss_mask = kwargs.pop("action_loss_mask", None) + wrist_action_dim = int(kwargs.pop("wrist_action_dim", 0) or 0) + use_teacher_wrist = bool(kwargs.pop("use_teacher_wrist", False)) + mask_wrist_in_loss = bool(kwargs.pop("mask_wrist_in_loss", False)) + proprio_source_dim = kwargs.pop("proprio_source_dim", None) + action_tail_dim = int(kwargs.pop("action_tail_dim", 0) or 0) + action_keep_dim = int(kwargs.pop("action_keep_dim", 0) or 0) + proprio_term_indices = tuple( + int(value) for value in kwargs.pop("proprio_term_indices", ())) + proprio_observation_term_dims = tuple( + int(value) for value in kwargs.pop("proprio_observation_term_dims", ())) + proprio_term_names = tuple(kwargs.pop("proprio_term_names", ())) + proprio_flat_suffix_dim = int( + kwargs.pop("proprio_flat_suffix_dim", 0) or 0) + proprio_history_length = int(kwargs.pop("proprio_history_length", 1)) + proprio_frame_dim = int(kwargs.pop("proprio_frame_dim", 0) or 0) + + student_dims_alias = tuple(kwargs.pop("student_hidden_dims", ())) + kwargs.pop("noise_std_type", None) + if student_dims_alias: + decoder_hidden_dims = tuple(student_dims_alias) + + self.loaded_teacher = False + self.latent_dim = latent_dim + self.posterior_std_min = posterior_std_min + self.posterior_std_max = posterior_std_max + self.prior_std_min = prior_std_min + self.prior_std_max = prior_std_max + self.proprio_history_length = max(1, proprio_history_length) + self.proprio_dim = proprio_dim if proprio_dim is not None else num_student_obs + self.proprio_frame_dim = proprio_frame_dim if proprio_frame_dim > 0 else 0 + self.proprio_source_dim = int( + proprio_source_dim) if proprio_source_dim is not None else None + self.tanh_actions = tanh_actions + self.wrist_action_dim = max( + 0, min(int(wrist_action_dim), int(num_actions))) + self.use_teacher_wrist = use_teacher_wrist and self.wrist_action_dim > 0 + self._cached_stats: Dict[str, torch.Tensor] | None = None + self.action_tail_dim = max(0, action_tail_dim) + self.action_keep_dim = max(0, action_keep_dim) + self.proprio_flat_suffix_dim = max(0, proprio_flat_suffix_dim) + self._explicit_proprio_term_slices: tuple[tuple[int, int], ...] = () + self._proprio_term_layout_dim: int | None = None + self._proprio_observation_term_dims: tuple[int, ...] = () + self._proprio_term_offsets: tuple[int, ...] = () + self._proprio_term_names: tuple[str, ...] = () + self._explicit_proprio_block_start = 0 + self._explicit_proprio_block_end = 0 + self._explicit_proprio_block_is_suffix = False + + if self.proprio_frame_dim <= 0 and self.proprio_history_length > 1 and self.proprio_dim > 0: + if self.proprio_dim % self.proprio_history_length == 0: + self.proprio_frame_dim = self.proprio_dim // self.proprio_history_length + else: + self.proprio_frame_dim = self.proprio_dim + + if proprio_term_indices or proprio_observation_term_dims: + if not proprio_term_indices or not proprio_observation_term_dims: + raise ValueError( + "proprio_term_indices and proprio_observation_term_dims must be provided together." + ) + if self.proprio_flat_suffix_dim > 0: + raise ValueError( + "Cannot combine proprio_flat_suffix_dim with explicit proprio term slicing." + ) + if self.action_tail_dim > 0 or self.action_keep_dim > 0: + raise ValueError( + "Cannot combine explicit proprio term slicing with action_tail_dim/action_keep_dim slicing." + ) + if self.proprio_history_length <= 0: + raise ValueError("proprio_history_length must be >= 1.") + + if any(index < 0 for index in proprio_term_indices): + raise ValueError("proprio_term_indices must be non-negative.") + if any(dim < 0 for dim in proprio_observation_term_dims): + raise ValueError( + "proprio_observation_term_dims must be non-negative.") + if proprio_term_names and len(proprio_term_names) != len(proprio_observation_term_dims): + raise ValueError( + "proprio_term_names length must match proprio_observation_term_dims length.") + + max_term_index = max(proprio_term_indices) + if max_term_index >= len(proprio_observation_term_dims): + raise ValueError( + "proprio_term_indices contain an index outside the range of " + f"proprio_observation_term_dims (len={len(proprio_observation_term_dims)})." + ) + + term_offsets: list[int] = [0] + for dim in proprio_observation_term_dims: + term_offsets.append(term_offsets[-1] + dim) + if not term_offsets or term_offsets[-1] <= 0: + raise ValueError( + "proprio_observation_term_dims must contain at least one positive term dimension.") + + self._proprio_observation_term_dims = tuple( + proprio_observation_term_dims) + self._proprio_term_offsets = tuple(term_offsets) + if proprio_term_names: + self._proprio_term_names = tuple( + str(value) for value in proprio_term_names) + else: + self._proprio_term_names = tuple( + f"term_{index}" for index in range(len(term_offsets) - 1)) + + explicit_slices: list[tuple[int, int]] = [] + for term_index in proprio_term_indices: + start = int(term_offsets[term_index]) + end = int(term_offsets[term_index + 1]) + if end <= start: + raise ValueError( + f"Term index {term_index} has zero width in proprio_observation_term_dims.") + explicit_slices.append((start, end)) + + selected_frame_dim = sum( + end - start for start, end in explicit_slices) + if selected_frame_dim <= 0: + raise ValueError( + "Selected proprioception frame dim must be positive.") + + self._explicit_proprio_term_slices = tuple(explicit_slices) + explicit_slices_sorted = tuple( + sorted(explicit_slices, key=lambda item: item[0])) + if explicit_slices_sorted: + self._explicit_proprio_block_start = int( + explicit_slices_sorted[0][0]) + self._explicit_proprio_block_end = int( + explicit_slices_sorted[-1][1]) + self._explicit_proprio_block_is_suffix = False + contiguous = True + for index in range(1, len(explicit_slices_sorted)): + if explicit_slices_sorted[index][0] != explicit_slices_sorted[index - 1][1]: + contiguous = False + break + if ( + contiguous + and self._explicit_proprio_block_end >= self._explicit_proprio_block_start + and term_offsets[-1] > 0 + ): + # Select by term indices gives the tail block of a per-frame layout. + # In that case we can directly take the last proprio_frame_dim values from each frame. + self._explicit_proprio_block_is_suffix = ( + self._explicit_proprio_block_end == term_offsets[-1] + ) + self._proprio_term_layout_dim = term_offsets[-1] + self.proprio_frame_dim = selected_frame_dim + self.proprio_dim = selected_frame_dim * \ + max(1, self.proprio_history_length) + + if proprio_dim is not None and int(proprio_dim) > 0 and self.proprio_dim != int(proprio_dim): + raise ValueError( + "Explicit proprio term slicing expects proprio_dim to match selected_dim * proprio_history_length = " + f"{self.proprio_dim}, but configured proprio_dim={proprio_dim}." + ) + if proprio_frame_dim > 0 and self.proprio_frame_dim != proprio_frame_dim: + raise ValueError( + "Explicit proprio term slicing expects proprio_frame_dim to match selected frame dim " + f"{self.proprio_frame_dim}, but configured proprio_frame_dim={proprio_frame_dim}." + ) + + if self.action_tail_dim > 0 or self.action_keep_dim > 0: + if self.action_tail_dim <= 0 or self.action_keep_dim <= 0: + raise ValueError( + "Both action_tail_dim and action_keep_dim must be positive when action slicing is enabled." + ) + if self.proprio_source_dim is None: + raise ValueError( + "proprio_source_dim must be provided when action slicing is enabled.") + if self.action_keep_dim > self.action_tail_dim: + raise ValueError("action_keep_dim must be <= action_tail_dim.") + if self.proprio_source_dim < self.action_tail_dim: + raise ValueError( + "proprio_source_dim must be >= action_tail_dim.") + expected_dim = self.proprio_source_dim - \ + self.action_tail_dim + self.action_keep_dim + if expected_dim != int(self.proprio_dim): + raise ValueError( + "Invalid split dims: expected output " + f"{expected_dim} from source={self.proprio_source_dim}, " + f"tail={self.action_tail_dim}, keep={self.action_keep_dim}, " + f"but proprio_dim={self.proprio_dim}." + ) + + if self.proprio_flat_suffix_dim > 0: + if self.proprio_source_dim is not None and self.proprio_source_dim > 0: + raise ValueError( + "Cannot combine proprio_flat_suffix_dim with proprio_source_dim.") + if self.proprio_dim <= 0: + self.proprio_dim = self.proprio_flat_suffix_dim + elif self.proprio_dim != self.proprio_flat_suffix_dim: + raise ValueError( + "Cannot combine proprio_flat_suffix_dim with different proprio_dim. " + f"Configured proprio_dim={self.proprio_dim}, proprio_flat_suffix_dim={self.proprio_flat_suffix_dim}." + ) + + if action_loss_mask is not None: + self.action_loss_mask = torch.tensor( + action_loss_mask, dtype=torch.float32) + elif mask_wrist_in_loss and self.wrist_action_dim > 0: + mask = torch.ones(num_actions, dtype=torch.float32) + mask[: self.wrist_action_dim] = 0.0 + self.action_loss_mask = mask + else: + self.action_loss_mask = None + + activation_layer = resolve_nn_activation(activation) + encoder_hidden_dims = tuple(encoder_hidden_dims) + decoder_hidden_dims = tuple(decoder_hidden_dims) + prior_hidden_dims = tuple(prior_hidden_dims) + + # Teacher branch (same as the RL actor head). + teacher_hidden_dims = tuple(teacher_hidden_dims) + teacher_layers = [] + prev_dim = num_teacher_obs + teacher_layers.append(nn.Linear(prev_dim, teacher_hidden_dims[0])) + teacher_layers.append(activation_layer) + for index in range(len(teacher_hidden_dims)): + if index == len(teacher_hidden_dims) - 1: + teacher_layers.append( + nn.Linear(teacher_hidden_dims[index], num_actions)) + else: + teacher_layers.append( + nn.Linear(teacher_hidden_dims[index], teacher_hidden_dims[index + 1])) + teacher_layers.append(activation_layer) + self.teacher = nn.Sequential(*teacher_layers) + self.teacher.eval() + + # Student VAE components. + self.encoder = _build_mlp( + num_student_obs, encoder_hidden_dims, 2 * latent_dim, activation_layer) + self.prior_net = _build_mlp( + self.proprio_dim, prior_hidden_dims, 2 * latent_dim, activation_layer) + self.decoder = _build_mlp( + self.proprio_dim + latent_dim, decoder_hidden_dims, num_actions, activation_layer) + + self.latent_dropout = nn.Dropout( + p=latent_dropout) if latent_dropout > 0.0 else nn.Identity() + self.log_std = nn.Parameter(torch.full( + (num_actions,), math.log(max(init_noise_std, 1.0e-6)))) + self.distribution: Normal | None = None + + def _split_observations(self, observations: torch.Tensor) -> torch.Tensor: + if self.proprio_dim is None or self.proprio_dim <= 0: + return observations + + total_dim = observations.shape[-1] + if self.proprio_flat_suffix_dim > 0: + if observations.ndim > 2: + flat_obs = observations.reshape( + *observations.shape[:-2], observations.shape[-2] * observations.shape[-1]) + else: + flat_obs = observations + if flat_obs.shape[-1] < self.proprio_flat_suffix_dim: + raise ValueError( + "Proprioceptive flat-suffix slicing failed: " + f"observation dim={flat_obs.shape[-1]} is smaller than suffix_dim={self.proprio_flat_suffix_dim}." + ) + return flat_obs[..., flat_obs.shape[-1] - self.proprio_flat_suffix_dim:] + + def _infer_history_sequence( + data: torch.Tensor, + *, + expected_frame_dim: int | None = None, + min_frame_dim: int | None = None, + ) -> tuple[torch.Tensor, int]: + """Reshape proprioception observations into [*, H, frame_dim].""" + history_length = self.proprio_history_length + if history_length <= 1: + raise ValueError( + "History length must be >= 2 when inferring temporally stacked observations.") + + if data.ndim > 2: + if data.shape[-2] != history_length: + raise ValueError( + "Explicit proprio term slicing failed: history axis does not match configured history length. " + f"Expected shape[-2]={history_length}, got {data.shape[-2]}." + ) + frame_dim = data.shape[-1] + if min_frame_dim is not None and frame_dim < min_frame_dim: + raise ValueError( + "Explicit proprio term slicing failed: " + f"inferred frame_dim={frame_dim} is smaller than required minimum={min_frame_dim}." + ) + return data, frame_dim + + candidate_dim = data.shape[-1] + candidates: list[tuple[int, int]] = [] + + if candidate_dim > history_length and candidate_dim % history_length == 0: + candidates.append( + (candidate_dim // history_length, candidate_dim)) + + if ( + candidate_dim > history_length + 1 + and (candidate_dim - history_length) % history_length == 0 + ): + candidates.append(((candidate_dim - history_length) // + history_length, candidate_dim - history_length)) + + if not candidates: + raise ValueError( + "Explicit proprio term slicing failed: cannot infer frame dimension from observations.") + + if expected_frame_dim is not None and expected_frame_dim > 0: + for frame_dim, usable_dim in candidates: + if frame_dim == expected_frame_dim: + trimmed = data[..., :usable_dim] + return trimmed.reshape(*trimmed.shape[:-1], history_length, frame_dim), frame_dim + + selected_frame_dim = None + selected_usable_dim = None + if min_frame_dim is not None and min_frame_dim > 0: + filtered = [(frame_dim, usable_dim) for frame_dim, + usable_dim in candidates if frame_dim >= min_frame_dim] + if filtered: + filtered.sort(key=lambda item: item[0]) + selected_frame_dim, selected_usable_dim = filtered[0] + if selected_frame_dim is None: + selected_frame_dim, selected_usable_dim = sorted( + candidates, key=lambda item: item[0])[0] + + trimmed = data[..., :selected_usable_dim] + return trimmed.reshape(*trimmed.shape[:-1], history_length, selected_frame_dim), selected_frame_dim + + if self._explicit_proprio_term_slices: + if self.proprio_history_length <= 1: + if self._explicit_proprio_block_is_suffix: + return observations[..., total_dim - self.proprio_dim:] + chunks = [] + for start, end in self._explicit_proprio_term_slices: + if total_dim < end: + raise ValueError( + "Explicit proprio term slicing failed: " + f"observation dim={total_dim} is smaller than slice end={end}." + ) + chunks.append(observations[..., start:end]) + return torch.cat(chunks, dim=-1) + + sequence, frame_dim = _infer_history_sequence( + observations, + expected_frame_dim=self.proprio_frame_dim, + min_frame_dim=self._proprio_term_layout_dim, + ) + if self._proprio_term_layout_dim is None or frame_dim < self._proprio_term_layout_dim: + raise ValueError( + "Explicit proprio term slicing failed: " + f"inferred frame_dim={frame_dim} is smaller than configured term layout total=" + f"{self._proprio_term_layout_dim}." + ) + + if self._explicit_proprio_block_is_suffix: + proprio_sequence = sequence[..., -self.proprio_frame_dim:] + return proprio_sequence.reshape( + *observations.shape[:-1], self.proprio_history_length * self.proprio_frame_dim + ) + + chunks = [sequence[..., start:end] + for start, end in self._explicit_proprio_term_slices] + proprio_sequence = torch.cat(chunks, dim=-1) + return proprio_sequence.reshape(*observations.shape[:-1], self.proprio_history_length * self.proprio_frame_dim) + + if self.action_tail_dim > 0 and self.action_keep_dim > 0: + source_dim = int( + self.proprio_source_dim if self.proprio_source_dim is not None else self.proprio_dim) + source_dim = min(source_dim, total_dim) + source = observations[..., total_dim - source_dim:] + action_tail_dim = min(self.action_tail_dim, source.shape[-1]) + keep_dim = min(self.action_keep_dim, action_tail_dim) + non_action_dim = source.shape[-1] - action_tail_dim + return torch.cat((source[..., :non_action_dim], source[..., -keep_dim:]), dim=-1) + + proprio_dim = min(self.proprio_dim, total_dim) + if self.proprio_history_length > 1 and self.proprio_frame_dim > 0: + sequence, frame_dim = _infer_history_sequence( + observations, + expected_frame_dim=self.proprio_frame_dim, + min_frame_dim=self.proprio_frame_dim, + ) + if frame_dim >= self.proprio_frame_dim: + start = frame_dim - self.proprio_frame_dim + proprio_sequence = sequence[..., start:frame_dim] + return proprio_sequence.reshape( + *observations.shape[:-1], self.proprio_history_length * self.proprio_frame_dim + ) + + return observations[..., total_dim - proprio_dim:] + + def _encode_from_safe(self, observations: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + stats = self.encoder(observations) + return torch.chunk(stats, 2, dim=-1) + + def _prior_from_safe(self, observations: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + stats = self.prior_net(self._split_observations(observations)) + return torch.chunk(stats, 2, dim=-1) + + def _decode_from_safe(self, observations: torch.Tensor, latent: torch.Tensor) -> torch.Tensor: + decoder_input = torch.cat( + [self._split_observations(observations), latent], dim=-1) + decoded = self.decoder(decoder_input) + return decoded + + def _mix_actions(self, observations: torch.Tensor, student_actions: torch.Tensor) -> torch.Tensor: + if not self.use_teacher_wrist: + return student_actions + with torch.no_grad(): + teacher_actions = self.evaluate(observations) + if teacher_actions.shape[-1] != student_actions.shape[-1]: + return student_actions + if self.wrist_action_dim >= student_actions.shape[-1]: + return teacher_actions + return torch.cat( + ( + teacher_actions[..., : self.wrist_action_dim], + student_actions[..., self.wrist_action_dim:], + ), + dim=-1, + ) + + def encode(self, observations: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Return posterior mean and log std of q(z | obs).""" + posterior_mean, posterior_log_std = self._encode_from_safe( + observations) + posterior_log_std = torch.clamp( + posterior_log_std, + min=math.log(self.posterior_std_min), + max=math.log(self.posterior_std_max), + ) + return posterior_mean, posterior_log_std + + def prior(self, observations: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Return prior mean and log std of p(z | proprio).""" + prior_mean, prior_log_std = self._prior_from_safe(observations) + prior_log_std = torch.clamp( + prior_log_std, + min=math.log(self.prior_std_min), + max=math.log(self.prior_std_max), + ) + return prior_mean, prior_log_std + + def decode(self, observations: torch.Tensor, latent: torch.Tensor) -> torch.Tensor: + latent = self.latent_dropout(latent) + return self._decode_from_safe(observations, latent) + + @staticmethod + def _sample_gaussian(mean: torch.Tensor, log_std: torch.Tensor) -> torch.Tensor: + std = torch.exp(log_std) + eps = torch.randn_like(mean) + return mean + std * eps + + def latent_forward(self, observations: torch.Tensor, sample_latent: bool = True) -> dict[str, torch.Tensor]: + posterior_mean, posterior_log_std = self.encode(observations) + if sample_latent: + latent = self._sample_gaussian(posterior_mean, posterior_log_std) + else: + latent = posterior_mean + prior_mean, prior_log_std = self.prior(observations) + action_mean = self._decode_from_safe(observations, latent) + stats = { + "action_mean": action_mean, + "posterior_mean": posterior_mean, + "posterior_log_std": posterior_log_std, + "prior_mean": prior_mean, + "prior_log_std": prior_log_std, + } + self._cached_stats = stats + return stats + + def reset(self, dones=None, hidden_states=None): + del dones, hidden_states + + def update_distribution(self, observations: torch.Tensor): + stats = self.latent_forward(observations, sample_latent=True) + action_std = torch.exp(self.log_std).expand_as(stats["action_mean"]) + action_std = torch.clamp(action_std, min=1.0e-6) + action_mean = stats["action_mean"] + self.distribution = Normal(action_mean, action_std) + + def act(self, observations: torch.Tensor): + self.update_distribution(observations) + assert self.distribution is not None + actions = self.distribution.mean + actions = self._mix_actions(observations, actions) + + if self.tanh_actions: + actions = torch.tanh(actions) + return actions + + def act_inference(self, observations: torch.Tensor): + stats = self.latent_forward(observations, sample_latent=False) + return self._mix_actions(observations, stats["action_mean"]) + + def evaluate(self, teacher_observations: torch.Tensor): + with torch.no_grad(): + return self.teacher(teacher_observations) + + @property + def action_mean(self): + if self.distribution is None: + raise RuntimeError( + "Distribution not initialized. Call act() or update_distribution() first.") + return self.distribution.mean + + @property + def action_std(self): + if self.distribution is not None: + return self.distribution.stddev + return torch.exp(self.log_std) + + @property + def entropy(self): + if self.distribution is None: + raise RuntimeError( + "Distribution not initialized. Call act() or update_distribution() first.") + return self.distribution.entropy().sum(dim=-1) + + def get_hidden_states(self): + return None + + def detach_hidden_states(self, dones=None): + del dones + + # type: ignore[override] + def load_state_dict(self, state_dict, strict: bool = True): + """Load parameters for teacher and student networks. + + Returns: + bool: True if this resumes distillation, False if only the teacher weights were loaded. + """ + if any("actor." in key for key in state_dict.keys()): + teacher_state_dict = { + key.replace("actor.", ""): value for key, value in state_dict.items() if "actor." in key + } + self.teacher.load_state_dict(teacher_state_dict, strict=strict) + self.loaded_teacher = True + self.teacher.eval() + return False + + nn.Module.load_state_dict(self, state_dict, strict=strict) + self.loaded_teacher = True + self.teacher.eval() + return True + + +class DistillationVAE(Distillation): + """Distillation algorithm with additional VAE-based losses.""" + + def __init__( + self, + policy, + *, + num_learning_epochs: int = 1, + gradient_length: int = 15, + learning_rate: float = 1e-3, + max_grad_norm: float | None = None, + loss_type: str = "mse", + action_loss_coef: float = 1.0, + regularization_loss_coef: float = 0.1, + kl_loss_coef: float = 0.01, + kl_anneal_iters: int = 0, + adaptive_kl_loss_coef: bool = False, + adaptive_kl_target: float = 20.0, + adaptive_kl_eta: float = 1.0e-4, + adaptive_kl_min_coef: float = 1.0e-5, + adaptive_kl_max_coef: float = 5.0e-3, + kl_final_coef: float | None = None, + kl_anneal_start_iter: int = 0, + kl_anneal_end_iter: int = 0, + device: str = "cpu", + multi_gpu_cfg: dict | None = None, + ): + super().__init__( + policy, + num_learning_epochs=num_learning_epochs, + gradient_length=gradient_length, + learning_rate=learning_rate, + max_grad_norm=max_grad_norm, + loss_type=loss_type, + device=device, + multi_gpu_cfg=multi_gpu_cfg, + ) + self.action_loss_coef = action_loss_coef + self.regularization_loss_coef = regularization_loss_coef + self.kl_loss_coef = kl_loss_coef + self.kl_anneal_iters = kl_anneal_iters + self.adaptive_kl_loss_coef = adaptive_kl_loss_coef + self.adaptive_kl_target = adaptive_kl_target + self.adaptive_kl_eta = adaptive_kl_eta + self.adaptive_kl_min_coef = adaptive_kl_min_coef + self.adaptive_kl_max_coef = adaptive_kl_max_coef + self.kl_final_coef = kl_final_coef + self.kl_anneal_start_iter = kl_anneal_start_iter + self.kl_anneal_end_iter = kl_anneal_end_iter + + def init_storage( + self, + training_type, + num_envs, + num_transitions_per_env, + student_obs_shape, + teacher_obs_shape, + actions_shape, + ): + self.storage = SafeRolloutStorage( + training_type, + num_envs, + num_transitions_per_env, + student_obs_shape, + teacher_obs_shape, + actions_shape, + None, + self.device, + ) + + def process_env_step(self, rewards, dones, infos): + valid_mask = getattr(self.transition, "valid_mask", None) + if valid_mask is None: + valid_mask = torch.ones_like(dones, dtype=torch.bool) + self.transition.valid_mask = valid_mask + else: + valid_mask = valid_mask.to(device=dones.device, dtype=torch.bool) + + if not torch.all(valid_mask): + rewards = rewards.clone() + dones = dones.clone() + rewards[~valid_mask] = 0.0 + dones[~valid_mask] = 1 + + self.transition.rewards = rewards + self.transition.dones = dones + self.storage.add_transitions(self.transition) + self.transition.clear() + self.policy.reset(dones) + + def _current_kl_coef(self) -> float: + if self.adaptive_kl_loss_coef: + return self.kl_loss_coef + if ( + self.kl_final_coef is not None + and self.kl_anneal_end_iter > self.kl_anneal_start_iter + and self.kl_anneal_start_iter >= 0 + ): + if self.num_updates < self.kl_anneal_start_iter: + return self.kl_loss_coef + if self.num_updates >= self.kl_anneal_end_iter: + return self.kl_final_coef + span = self.kl_anneal_end_iter - self.kl_anneal_start_iter + frac = (self.num_updates - self.kl_anneal_start_iter) / float(span) + return (1.0 - frac) * self.kl_loss_coef + frac * self.kl_final_coef + if self.kl_anneal_iters <= 0: + return self.kl_loss_coef + progress = min(1.0, self.num_updates / float(self.kl_anneal_iters)) + return self.kl_loss_coef * progress + + def _maybe_update_adaptive_kl(self, kl_value: float) -> None: + if not self.adaptive_kl_loss_coef: + return + updated_coef = self.kl_loss_coef * \ + math.exp(self.adaptive_kl_eta * + (kl_value - self.adaptive_kl_target)) + if not math.isfinite(updated_coef): + updated_coef = self.adaptive_kl_min_coef + updated_coef = min( + max(updated_coef, self.adaptive_kl_min_coef), self.adaptive_kl_max_coef) + self.kl_loss_coef = float(updated_coef) + + def update(self): + self.num_updates += 1 + mean_behavior_loss = 0.0 + mean_reg_loss = 0.0 + mean_kl_loss = 0.0 + mean_total_loss = 0.0 + total_loss_accumulator: torch.Tensor | None = None + accumulation_count = 0 + cnt = 0 + post_sum = 0.0 + post_count = 0.0 + post_max = float("-inf") + post_min = float("inf") + prior_sum = 0.0 + prior_count = 0.0 + prior_max = float("-inf") + prior_min = float("inf") + + current_kl = self._current_kl_coef() + + for _ in range(self.num_learning_epochs): + prev_posterior_mean: torch.Tensor | None = None + prev_dones: torch.Tensor | None = None + prev_valid_mask: torch.Tensor | None = None + self.policy.reset(hidden_states=self.last_hidden_states) + self.policy.detach_hidden_states() + for batch in self.storage.generator(): + if len(batch) == 6: + obs, _, _, privileged_actions, dones, valid_mask = batch + else: + obs, _, _, privileged_actions, dones = batch + valid_mask = torch.ones_like(dones, dtype=torch.bool) + valid_mask = valid_mask.view(-1).to( + device=obs.device, dtype=torch.bool) + # alive_mask = (dones.view(-1) == 0) + stats = self.policy.latent_forward(obs, sample_latent=True) + action_mean = stats["action_mean"] + posterior_mean = stats["posterior_mean"] + posterior_log_std = stats["posterior_log_std"] + prior_mean = stats["prior_mean"] + prior_log_std = stats["prior_log_std"] + if posterior_log_std.numel() > 0: + valid_posterior_log_std = posterior_log_std[valid_mask] + if valid_posterior_log_std.numel() > 0: + post_sum += valid_posterior_log_std.sum().item() + post_count += valid_posterior_log_std.numel() + post_max = max( + post_max, valid_posterior_log_std.max().item()) + post_min = min( + post_min, valid_posterior_log_std.min().item()) + if prior_log_std.numel() > 0: + valid_prior_log_std = prior_log_std[valid_mask] + if valid_prior_log_std.numel() > 0: + prior_sum += valid_prior_log_std.sum().item() + prior_count += valid_prior_log_std.numel() + prior_max = max( + prior_max, valid_prior_log_std.max().item()) + prior_min = min( + prior_min, valid_prior_log_std.min().item()) + + action_mask = getattr(self.policy, "action_loss_mask", None) + if action_mask is not None: + mask = action_mask.to(action_mean.device) + if mask.ndim == 1: + mask = mask.unsqueeze(0) + if mask.shape[-1] == action_mean.shape[-1]: + diff = (action_mean - privileged_actions) * mask + denom = mask.sum(dim=-1).clamp(min=1.0) + behavior_loss = _masked_mean( + diff.pow(2).sum(dim=-1) / denom, valid_mask) + else: + per_env_behavior = ( + action_mean - privileged_actions).pow(2).mean(dim=-1) + behavior_loss = _masked_mean( + per_env_behavior, valid_mask) + else: + per_env_behavior = ( + action_mean - privileged_actions).pow(2).mean(dim=-1) + behavior_loss = _masked_mean(per_env_behavior, valid_mask) + + if prev_posterior_mean is None or prev_dones is None or prev_valid_mask is None: + regularization_loss = torch.zeros( + (), device=obs.device, dtype=behavior_loss.dtype) + else: + # Only compare consecutive timesteps within the same env (skip resets). + pair_mask = valid_mask & prev_valid_mask & ( + ~prev_dones.view(-1).bool()) + if pair_mask.shape[0] != posterior_mean.shape[0]: + regularization_loss = torch.zeros( + (), device=obs.device, dtype=behavior_loss.dtype) + else: + if torch.any(pair_mask): + regularization_loss = ( + posterior_mean[pair_mask] - prev_posterior_mean[pair_mask]).pow(2).mean() + else: + regularization_loss = torch.zeros( + (), device=obs.device, dtype=behavior_loss.dtype) + + kl_loss = _masked_mean( + _gaussian_kl_per_env( + posterior_mean, posterior_log_std, prior_mean, prior_log_std), + valid_mask, + ) + + total_loss = ( + self.action_loss_coef * behavior_loss + + self.regularization_loss_coef * regularization_loss + + current_kl * kl_loss + ) + + if total_loss_accumulator is None: + total_loss_accumulator = total_loss + else: + total_loss_accumulator = total_loss_accumulator + total_loss + accumulation_count += 1 + mean_behavior_loss += behavior_loss.item() + mean_reg_loss += regularization_loss.item() + mean_kl_loss += kl_loss.item() + mean_total_loss += total_loss.item() + cnt += 1 + + if cnt % self.gradient_length == 0: + if total_loss_accumulator is None or accumulation_count <= 0: + continue + self.optimizer.zero_grad() + (total_loss_accumulator / float(accumulation_count)).backward() + if self.is_multi_gpu: + self.reduce_parameters() + if self.max_grad_norm is not None: + nn.utils.clip_grad_norm_( + self.policy.parameters(), self.max_grad_norm) + self.optimizer.step() + self.policy.detach_hidden_states() + total_loss_accumulator = None + accumulation_count = 0 + + self.policy.reset(dones.view(-1)) + self.policy.detach_hidden_states(dones.view(-1)) + + prev_posterior_mean = posterior_mean.detach() + prev_dones = dones.detach() + prev_valid_mask = valid_mask.detach() + + if total_loss_accumulator is not None and accumulation_count > 0: + self.optimizer.zero_grad() + (total_loss_accumulator / float(accumulation_count)).backward() + if self.is_multi_gpu: + self.reduce_parameters() + if self.max_grad_norm is not None: + nn.utils.clip_grad_norm_( + self.policy.parameters(), self.max_grad_norm) + self.optimizer.step() + self.policy.detach_hidden_states() + total_loss_accumulator = None + accumulation_count = 0 + + if cnt > 0: + mean_behavior_loss /= cnt + mean_reg_loss /= cnt + mean_kl_loss /= cnt + mean_total_loss /= cnt + self._maybe_update_adaptive_kl(mean_kl_loss) + self.storage.clear() + self.last_hidden_states = self.policy.get_hidden_states() + self.policy.detach_hidden_states() + if post_count > 0: + post_mean = post_sum / post_count + else: + post_mean = 0.0 + post_max = 0.0 + post_min = 0.0 + if prior_count > 0: + prior_mean = prior_sum / prior_count + else: + prior_mean = 0.0 + prior_max = 0.0 + prior_min = 0.0 + + return { + "behavior": mean_behavior_loss, + "regularization": mean_reg_loss, + "kl": mean_kl_loss, + "total": mean_total_loss, + "posterior_log_std_max": post_max, + "posterior_log_std_min": post_min, + "posterior_log_std_mean": post_mean, + "prior_log_std_max": prior_max, + "prior_log_std_min": prior_min, + "prior_log_std_mean": prior_mean, + "kl_coef": self.kl_loss_coef, + } diff --git a/third-party/coordex/source/coordex/coordex/policies/__init__.py b/third-party/coordex/source/coordex/coordex/policies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a74999afc1e1606f8d83da805c087112bd8cf01a --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/policies/__init__.py @@ -0,0 +1,5 @@ +"""Policy modules used by CoorDex rollout scripts.""" + +from .actor_critic_coord_residual import ActorCriticCoordResidual + +__all__ = ["ActorCriticCoordResidual"] diff --git a/third-party/coordex/source/coordex/coordex/policies/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/policies/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51b58e82ae9960b2bda23cabff0f60f24d558da7 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/policies/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/policies/__pycache__/actor_critic_coord_residual.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/policies/__pycache__/actor_critic_coord_residual.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ee945462d3f61bac5cb63fe6c0771e0ffb8e089 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/policies/__pycache__/actor_critic_coord_residual.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/policies/actor_critic_coord_residual.py b/third-party/coordex/source/coordex/coordex/policies/actor_critic_coord_residual.py new file mode 100644 index 0000000000000000000000000000000000000000..1a2e2d56e0b1182990878ddc28205bc25a37f66e --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/policies/actor_critic_coord_residual.py @@ -0,0 +1,333 @@ +from __future__ import annotations + +import numbers +from collections.abc import Sequence + +import torch +import torch.nn as nn +from torch.distributions import Normal + +from rsl_rl.utils import resolve_nn_activation + + +def _term_dim_to_int(dim: int | Sequence[int]) -> int: + if isinstance(dim, numbers.Integral): + return int(dim) + size = 1 + for value in dim: + size *= int(value) + return size + + +def _expected_dim_matches(actual_dim: int, expected_dim: int | Sequence[int]) -> bool: + if isinstance(expected_dim, numbers.Integral): + return actual_dim == int(expected_dim) + return actual_dim in {int(value) for value in expected_dim} + + +def _format_expected_dim(expected_dim: int | Sequence[int]) -> str: + if isinstance(expected_dim, numbers.Integral): + return str(int(expected_dim)) + return "one of " + ", ".join(str(int(value)) for value in expected_dim) + + +def _build_mlp(input_dim: int, hidden_dims: Sequence[int], output_dim: int, activation: str) -> nn.Sequential: + layers: list[nn.Module] = [] + current_dim = input_dim + for hidden_dim in hidden_dims: + layers.append(nn.Linear(current_dim, hidden_dim)) + layers.append(resolve_nn_activation(activation)) + current_dim = hidden_dim + layers.append(nn.Linear(current_dim, output_dim)) + return nn.Sequential(*layers) + + +class _CoordResidualActor(nn.Module): + """Locomanip actor with a shared coordination bottleneck and body/hand heads.""" + + _EXPECTED_TERM_DIMS = { + "projected_gravity": 3, + "humanoid_prior": (450, 465), + "right_hand_prior": 66, + "body_prior_mean": 16, + "hand_prior_mean": 12, + "last_latent": 28, + "fingertip_cube_forces": 15, + "cube_pose": 9, + "source_table_pose": 9, + "cube_pose_in_hand": 9, + } + _OPTIONAL_TERM_DIMS = { + "target_table_pose": 9, + "target_region_pose": 9, + } + _KNOWN_TERM_DIMS = {**_EXPECTED_TERM_DIMS, **_OPTIONAL_TERM_DIMS} + + def __init__( + self, + num_actor_obs: int, + *, + actor_obs_term_names: Sequence[str], + actor_obs_term_dims: Sequence[int | Sequence[int]], + coord_trunk_hidden_dims: Sequence[int], + body_head_hidden_dims: Sequence[int], + hand_head_hidden_dims: Sequence[int], + activation: str, + body_residual_scale: float, + hand_residual_scale: float, + ) -> None: + super().__init__() + + term_names = [str(name) for name in actor_obs_term_names] + term_dims = [_term_dim_to_int(dim) for dim in actor_obs_term_dims] + if len(term_names) != len(term_dims): + raise ValueError( + "ActorCriticCoordResidual received mismatched actor term metadata: " + f"{len(term_names)} names vs {len(term_dims)} dims." + ) + + current = 0 + self._term_slices: dict[str, slice] = {} + self._term_dims: dict[str, int] = {} + for name, dim in zip(term_names, term_dims): + self._term_slices[name] = slice(current, current + dim) + self._term_dims[name] = dim + current += dim + if current != int(num_actor_obs): + raise ValueError( + "Actor observation metadata does not match num_actor_obs: " + f"metadata total={current}, num_actor_obs={num_actor_obs}." + ) + + missing = sorted(set(self._EXPECTED_TERM_DIMS) - set(self._term_slices)) + if missing: + raise ValueError( + "ActorCriticCoordResidual is missing required actor observation terms: " + ", ".join(missing) + ) + for name, expected_dim in self._KNOWN_TERM_DIMS.items(): + if name not in self._term_dims: + continue + actual_dim = self._term_dims[name] + if not _expected_dim_matches(actual_dim, expected_dim): + raise ValueError( + f"Actor observation term '{name}' must have dim {_format_expected_dim(expected_dim)}, got {actual_dim}." + ) + + self.num_prop = int(num_actor_obs) + self.stage_dim = self._term_dims.get("stage", 0) + self.body_latent_dim = self._term_dims["body_prior_mean"] + self.hand_latent_dim = self._term_dims["hand_prior_mean"] + self.num_actions = self.body_latent_dim + self.hand_latent_dim + self.body_residual_scale = float(body_residual_scale) + self.hand_residual_scale = float(hand_residual_scale) + + x_ctx_dim = ( + self.stage_dim + + self._term_dims["projected_gravity"] + + self._term_dims["last_latent"] + + self._term_dims["cube_pose"] + + self._term_dims["source_table_pose"] + + self._term_dims["cube_pose_in_hand"] + + self._term_dims["fingertip_cube_forces"] + + sum(self._term_dims[name] for name in self._OPTIONAL_TERM_DIMS if name in self._term_dims) + ) + coord_input_dim = x_ctx_dim + self.body_latent_dim + self.hand_latent_dim + coord_feature_dim = int(coord_trunk_hidden_dims[-1]) + body_input_dim = coord_feature_dim + self._term_dims["humanoid_prior"] + self.body_latent_dim + hand_input_dim = ( + coord_feature_dim + + self._term_dims["right_hand_prior"] + + self.hand_latent_dim + + self._term_dims["cube_pose_in_hand"] + + self._term_dims["fingertip_cube_forces"] + ) + + self.coord_trunk = _build_mlp(coord_input_dim, coord_trunk_hidden_dims[:-1], coord_feature_dim, activation) + body_feature_dim = int(body_head_hidden_dims[-1]) + hand_feature_dim = int(hand_head_hidden_dims[-1]) + self.body_head_backbone = _build_mlp(body_input_dim, body_head_hidden_dims[:-1], body_feature_dim, activation) + self.hand_head_backbone = _build_mlp(hand_input_dim, hand_head_hidden_dims[:-1], hand_feature_dim, activation) + self.body_residual_linear = nn.Linear(body_feature_dim, self.body_latent_dim) + self.hand_residual_linear = nn.Linear(hand_feature_dim, self.hand_latent_dim) + + self.last_body_residual: torch.Tensor | None = None + self.last_hand_residual: torch.Tensor | None = None + # Preserve runner compatibility when old gate logging is still enabled. + self.last_body_gate: torch.Tensor | None = None + self.last_hand_gate: torch.Tensor | None = None + + def _slice(self, observations: torch.Tensor, term_name: str) -> torch.Tensor: + return observations[:, self._term_slices[term_name]] + + def forward(self, observations: torch.Tensor) -> torch.Tensor: + if observations.ndim != 2: + observations = observations.view(observations.shape[0], -1) + + mu_b = self._slice(observations, "body_prior_mean") + mu_h = self._slice(observations, "hand_prior_mean") + cube_pose_in_hand = self._slice(observations, "cube_pose_in_hand") + fingertip_cube_forces = self._slice(observations, "fingertip_cube_forces") + + x_ctx_terms = [] + if self.stage_dim: + x_ctx_terms.append(self._slice(observations, "stage")) + x_ctx_terms.extend( + [ + self._slice(observations, "projected_gravity"), + self._slice(observations, "last_latent"), + self._slice(observations, "cube_pose"), + self._slice(observations, "source_table_pose"), + ] + ) + for optional_name in self._OPTIONAL_TERM_DIMS: + if optional_name in self._term_slices: + x_ctx_terms.append(self._slice(observations, optional_name)) + x_ctx_terms.extend([cube_pose_in_hand, fingertip_cube_forces]) + x_ctx = torch.cat(x_ctx_terms, dim=-1) + coordination_input = torch.cat((x_ctx, mu_b, mu_h), dim=-1) + c_t = self.coord_trunk(coordination_input) + + body_input = torch.cat((c_t, self._slice(observations, "humanoid_prior"), mu_b), dim=-1) + body_features = self.body_head_backbone(body_input) + raw_dz_b = self.body_residual_linear(body_features) + dz_b = self.body_residual_scale * torch.tanh(raw_dz_b) + + hand_input = torch.cat( + (c_t, self._slice(observations, "right_hand_prior"), mu_h, cube_pose_in_hand, fingertip_cube_forces), + dim=-1, + ) + hand_features = self.hand_head_backbone(hand_input) + raw_dz_h = self.hand_residual_linear(hand_features) + dz_h = self.hand_residual_scale * torch.tanh(raw_dz_h) + + self.last_body_residual = dz_b.detach() + self.last_hand_residual = dz_h.detach() + self.last_body_gate = None + self.last_hand_gate = None + return torch.cat((dz_b, dz_h), dim=-1) + + +class ActorCriticCoordResidual(nn.Module): + """Locomanip actor-critic with a shared coordination bottleneck for residual latents.""" + + is_recurrent = False + + def __init__( + self, + num_actor_obs: int, + num_critic_obs: int, + num_actions: int, + actor_hidden_dims: Sequence[int] | None = None, + critic_hidden_dims: Sequence[int] = (1024, 512, 256), + activation: str = "elu", + init_noise_std: float | Sequence[float] | torch.Tensor = 0.22, + noise_std_type: str = "log", + coord_trunk_hidden_dims: Sequence[int] = (512, 256), + body_head_hidden_dims: Sequence[int] = (256, 128), + hand_head_hidden_dims: Sequence[int] = (256, 128), + body_residual_scale: float = 1.0, + hand_residual_scale: float = 1.0, + fixed_log_std: bool = True, + actor_obs_term_names: Sequence[str] = (), + actor_obs_term_dims: Sequence[int | Sequence[int]] = (), + **kwargs, + ) -> None: + del kwargs + super().__init__() + del actor_hidden_dims + + self.actor = _CoordResidualActor( + num_actor_obs, + actor_obs_term_names=actor_obs_term_names, + actor_obs_term_dims=actor_obs_term_dims, + coord_trunk_hidden_dims=coord_trunk_hidden_dims, + body_head_hidden_dims=body_head_hidden_dims, + hand_head_hidden_dims=hand_head_hidden_dims, + activation=activation, + body_residual_scale=body_residual_scale, + hand_residual_scale=hand_residual_scale, + ) + if self.actor.num_actions != int(num_actions): + raise ValueError( + "ActorCriticCoordResidual action dim mismatch: " + f"actor produces {self.actor.num_actions}, env expects {num_actions}." + ) + self.critic = _build_mlp(int(num_critic_obs), critic_hidden_dims[:-1], int(critic_hidden_dims[-1]), activation) + self.critic_output_activation = resolve_nn_activation(activation) + self.value_head = nn.Linear(int(critic_hidden_dims[-1]), 1) + + if noise_std_type != "log": + raise ValueError("ActorCriticCoordResidual expects noise_std_type='log'.") + self.noise_std_type = noise_std_type + self.fixed_log_std = bool(fixed_log_std) + self.log_std = nn.Parameter(torch.zeros(int(num_actions))) + std_tensor = torch.as_tensor(init_noise_std, device=self.log_std.device, dtype=self.log_std.dtype) + if std_tensor.numel() == 1: + std_tensor = std_tensor.expand_as(self.log_std) + elif std_tensor.numel() != self.log_std.numel(): + raise ValueError( + f"init_noise_std has {std_tensor.numel()} values, but {self.log_std.numel()} actions are expected." + ) + std_tensor = std_tensor.view_as(self.log_std) + with torch.no_grad(): + self.log_std.copy_(torch.log(torch.clamp(std_tensor, min=1.0e-6))) + self.log_std.requires_grad_(not self.fixed_log_std) + + self.distribution: Normal | None = None + Normal.set_default_validate_args(False) + + def reset(self, dones: torch.Tensor | None = None) -> None: + return None + + def forward(self): + raise NotImplementedError + + @property + def action_mean(self): + if self.distribution is None: + raise RuntimeError("Distribution not updated. Call update_distribution first.") + return self.distribution.mean + + @property + def action_std(self): + if self.distribution is None: + raise RuntimeError("Distribution not updated. Call update_distribution first.") + return self.distribution.stddev + + @property + def entropy(self): + if self.distribution is None: + raise RuntimeError("Distribution not updated. Call update_distribution first.") + return self.distribution.entropy().sum(dim=-1) + + def update_distribution(self, observations: torch.Tensor) -> None: + mean = self.actor(observations) + std = torch.exp(self.log_std).expand_as(mean) + self.distribution = Normal(mean, std) + + def act(self, observations: torch.Tensor, **kwargs) -> torch.Tensor: + self.update_distribution(observations) + return self.distribution.sample() + + def get_actions_log_prob(self, actions: torch.Tensor) -> torch.Tensor: + if self.distribution is None: + raise RuntimeError("Distribution not updated. Call update_distribution first.") + return self.distribution.log_prob(actions).sum(dim=-1) + + def act_inference(self, observations: torch.Tensor) -> torch.Tensor: + return self.actor(observations) + + def evaluate(self, critic_observations: torch.Tensor, **kwargs) -> torch.Tensor: + return self.value_head(self.critic_output_activation(self.critic(critic_observations))) + + def load_state_dict(self, state_dict, strict: bool = True): + gate_suffixes = ( + "body_gate_linear.weight", + "body_gate_linear.bias", + "hand_gate_linear.weight", + "hand_gate_linear.bias", + ) + if any(str(key).endswith(gate_suffixes) for key in state_dict): + state_dict = {key: value for key, value in state_dict.items() if not str(key).endswith(gate_suffixes)} + super().load_state_dict(state_dict, strict=strict) + return True diff --git a/third-party/coordex/source/coordex/coordex/robots/__init__.py b/third-party/coordex/source/coordex/coordex/robots/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..686bc9bb1ecf4e66bb71ac22f8b759dbaa36e30f --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/robots/__init__.py @@ -0,0 +1,2 @@ +"""Robot configurations used by CoorDex.""" + diff --git a/third-party/coordex/source/coordex/coordex/robots/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/robots/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9db18371d0674debb1872af607a1403ff639432f Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/robots/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/robots/__pycache__/g1_wuji.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/robots/__pycache__/g1_wuji.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4930efcd210286d57df9d1fcc53e9013ff35966d Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/robots/__pycache__/g1_wuji.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/robots/g1_wuji.py b/third-party/coordex/source/coordex/coordex/robots/g1_wuji.py new file mode 100644 index 0000000000000000000000000000000000000000..d55057283d5601b2854c123c9a3cc9616eb342c6 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/robots/g1_wuji.py @@ -0,0 +1,405 @@ +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets.articulation import ArticulationCfg + +from coordex.assets import ASSET_DIR + +ARMATURE_5020 = 0.003609725 +ARMATURE_7520_14 = 0.010177520 +ARMATURE_7520_22 = 0.025101925 +ARMATURE_4010 = 0.00425 + +NATURAL_FREQ = 10 * 2.0 * 3.1415926535 +DAMPING_RATIO = 2.0 + +STIFFNESS_5020 = ARMATURE_5020 * NATURAL_FREQ**2 +STIFFNESS_7520_14 = ARMATURE_7520_14 * NATURAL_FREQ**2 +STIFFNESS_7520_22 = ARMATURE_7520_22 * NATURAL_FREQ**2 +STIFFNESS_4010 = ARMATURE_4010 * NATURAL_FREQ**2 + +DAMPING_5020 = 2.0 * DAMPING_RATIO * ARMATURE_5020 * NATURAL_FREQ +DAMPING_7520_14 = 2.0 * DAMPING_RATIO * ARMATURE_7520_14 * NATURAL_FREQ +DAMPING_7520_22 = 2.0 * DAMPING_RATIO * ARMATURE_7520_22 * NATURAL_FREQ +DAMPING_4010 = 2.0 * DAMPING_RATIO * ARMATURE_4010 * NATURAL_FREQ + +WUJI_LH_ACTIVE_JOINT_NAMES = [ + f"left_finger{finger_idx}_joint{joint_idx}" + for finger_idx in range(1, 6) + for joint_idx in range(1, 5) +] +WUJI_RH_ACTIVE_JOINT_NAMES = [ + f"right_finger{finger_idx}_joint{joint_idx}" + for finger_idx in range(1, 6) + for joint_idx in range(1, 5) +] + +G1_WUJI_CFG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ASSET_DIR}/g1_wuji/g1_wuji_no_merge.usd", + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + retain_accelerations=False, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=1000.0, + max_depenetration_velocity=1.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, + solver_position_iteration_count=8, + solver_velocity_iteration_count=4, + ), + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 0.76), + joint_pos={ + ".*_hip_pitch_joint": -0.312, + ".*_knee_joint": 0.669, + ".*_ankle_pitch_joint": -0.363, + ".*_elbow_joint": 0.6, + "left_shoulder_roll_joint": 0.2, + "left_shoulder_pitch_joint": 0.2, + "right_shoulder_roll_joint": -0.2, + "right_shoulder_pitch_joint": 0.2, + **{name: 0.0 for name in WUJI_RH_ACTIVE_JOINT_NAMES}, + **{name: 0.0 for name in WUJI_LH_ACTIVE_JOINT_NAMES}, + "left_finger1_joint1": 0.05, + "right_finger1_joint1": 0.05, + }, + joint_vel={".*": 0.0}, + ), + soft_joint_pos_limit_factor=0.9, + actuators={ + # Mode_12 legs/waist tuning. + "legs": ImplicitActuatorCfg( + joint_names_expr=[ + ".*_hip_yaw_joint", + ".*_hip_roll_joint", + ".*_hip_pitch_joint", + ".*_knee_joint", + ], + effort_limit_sim={ + ".*_hip_yaw_joint": 88.0, + ".*_hip_roll_joint": 139.0, + ".*_hip_pitch_joint": 139.0, + ".*_knee_joint": 139.0, + }, + velocity_limit_sim={ + ".*_hip_yaw_joint": 32.0, + ".*_hip_roll_joint": 20.0, + ".*_hip_pitch_joint": 20.0, + ".*_knee_joint": 20.0, + }, + stiffness={ + ".*_hip_pitch_joint": STIFFNESS_7520_22, + ".*_hip_roll_joint": STIFFNESS_7520_22, + ".*_hip_yaw_joint": STIFFNESS_7520_14, + ".*_knee_joint": STIFFNESS_7520_22, + }, + damping={ + ".*_hip_pitch_joint": DAMPING_7520_22, + ".*_hip_roll_joint": DAMPING_7520_22, + ".*_hip_yaw_joint": DAMPING_7520_14, + ".*_knee_joint": DAMPING_7520_22, + }, + armature={ + ".*_hip_pitch_joint": ARMATURE_7520_22, + ".*_hip_roll_joint": ARMATURE_7520_22, + ".*_hip_yaw_joint": ARMATURE_7520_14, + ".*_knee_joint": ARMATURE_7520_22, + }, + ), + "feet": ImplicitActuatorCfg( + effort_limit_sim=35.0, + velocity_limit_sim=30.0, + joint_names_expr=[".*_ankle_pitch_joint", ".*_ankle_roll_joint"], + stiffness=2.0 * STIFFNESS_5020, + damping=2.0 * DAMPING_5020, + armature=2.0 * ARMATURE_5020, + ), + "waist": ImplicitActuatorCfg( + effort_limit_sim=35, + velocity_limit_sim=30.0, + joint_names_expr=["waist_roll_joint", "waist_pitch_joint"], + stiffness=2.0 * STIFFNESS_5020, + damping=2.0 * DAMPING_5020, + armature=2.0 * ARMATURE_5020, + ), + "waist_yaw": ImplicitActuatorCfg( + effort_limit_sim=88, + velocity_limit_sim=32.0, + joint_names_expr=["waist_yaw_joint"], + stiffness=STIFFNESS_7520_14, + damping=DAMPING_7520_14, + armature=ARMATURE_7520_14, + ), + "arms": ImplicitActuatorCfg( + joint_names_expr=[ + ".*_shoulder_pitch_joint", + ".*_shoulder_roll_joint", + ".*_shoulder_yaw_joint", + ".*_elbow_joint", + ".*_wrist_roll_joint", + ".*_wrist_pitch_joint", + ".*_wrist_yaw_joint", + ], + effort_limit_sim={ + ".*_shoulder_pitch_joint": 25.0, + ".*_shoulder_roll_joint": 25.0, + ".*_shoulder_yaw_joint": 25.0, + ".*_elbow_joint": 25.0, + ".*_wrist_roll_joint": 25.0, + ".*_wrist_pitch_joint": 5.0, + ".*_wrist_yaw_joint": 5.0, + }, + velocity_limit_sim={ + ".*_shoulder_pitch_joint": 37.0, + ".*_shoulder_roll_joint": 37.0, + ".*_shoulder_yaw_joint": 37.0, + ".*_elbow_joint": 37.0, + ".*_wrist_roll_joint": 37.0, + ".*_wrist_pitch_joint": 22.0, + ".*_wrist_yaw_joint": 22.0, + }, + stiffness={ + ".*_shoulder_pitch_joint": STIFFNESS_5020, + ".*_shoulder_roll_joint": STIFFNESS_5020, + ".*_shoulder_yaw_joint": STIFFNESS_5020, + ".*_elbow_joint": STIFFNESS_5020, + ".*_wrist_roll_joint": STIFFNESS_5020, + ".*_wrist_pitch_joint": STIFFNESS_4010, + ".*_wrist_yaw_joint": STIFFNESS_4010, + }, + damping={ + ".*_shoulder_pitch_joint": DAMPING_5020, + ".*_shoulder_roll_joint": DAMPING_5020, + ".*_shoulder_yaw_joint": DAMPING_5020, + ".*_elbow_joint": DAMPING_5020, + ".*_wrist_roll_joint": DAMPING_5020, + ".*_wrist_pitch_joint": DAMPING_4010, + ".*_wrist_yaw_joint": DAMPING_4010, + }, + armature={ + ".*_shoulder_pitch_joint": ARMATURE_5020, + ".*_shoulder_roll_joint": ARMATURE_5020, + ".*_shoulder_yaw_joint": ARMATURE_5020, + ".*_elbow_joint": ARMATURE_5020, + ".*_wrist_roll_joint": ARMATURE_5020, + ".*_wrist_pitch_joint": ARMATURE_4010, + ".*_wrist_yaw_joint": ARMATURE_4010, + }, + ), + # Wuji hand finger drives (all joints on both hands). + "wuji_hands": ImplicitActuatorCfg( + joint_names_expr=[ + *WUJI_RH_ACTIVE_JOINT_NAMES, + *WUJI_LH_ACTIVE_JOINT_NAMES, + ], + effort_limit_sim=30.0, + velocity_limit_sim=10.0, + stiffness=10.0, + damping=0.2, + armature=0.001, + ), + }, +) + +G1_WUJI_FIX_CFG = ArticulationCfg( + spawn=sim_utils.UrdfFileCfg( + fix_base=False, + replace_cylinders_with_capsules=True, + merge_fixed_joints=True, + asset_path=f"{ASSET_DIR}/g1_wuji/g1_wuji_fixed.urdf", + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + retain_accelerations=False, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=1000.0, + max_depenetration_velocity=1.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, + solver_position_iteration_count=8, + solver_velocity_iteration_count=4, + ), + joint_drive=sim_utils.UrdfConverterCfg.JointDriveCfg( + gains=sim_utils.UrdfConverterCfg.JointDriveCfg.PDGainsCfg( + stiffness=0, damping=0) + ), + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 0.76), + joint_pos={ + ".*_hip_pitch_joint": -0.312, + ".*_knee_joint": 0.669, + ".*_ankle_pitch_joint": -0.363, + ".*_elbow_joint": 0.6, + "left_shoulder_roll_joint": 0.2, + "left_shoulder_pitch_joint": 0.2, + "right_shoulder_roll_joint": -0.2, + "right_shoulder_pitch_joint": 0.2, + }, + joint_vel={".*": 0.0}, + ), + soft_joint_pos_limit_factor=0.9, + actuators={ + # Mode_12 legs/waist tuning. + "legs": ImplicitActuatorCfg( + joint_names_expr=[ + ".*_hip_yaw_joint", + ".*_hip_roll_joint", + ".*_hip_pitch_joint", + ".*_knee_joint", + ], + effort_limit_sim={ + ".*_hip_yaw_joint": 88.0, + ".*_hip_roll_joint": 139.0, + ".*_hip_pitch_joint": 139.0, + ".*_knee_joint": 139.0, + }, + velocity_limit_sim={ + ".*_hip_yaw_joint": 32.0, + ".*_hip_roll_joint": 20.0, + ".*_hip_pitch_joint": 20.0, + ".*_knee_joint": 20.0, + }, + stiffness={ + ".*_hip_pitch_joint": STIFFNESS_7520_22, + ".*_hip_roll_joint": STIFFNESS_7520_22, + ".*_hip_yaw_joint": STIFFNESS_7520_14, + ".*_knee_joint": STIFFNESS_7520_22, + }, + damping={ + ".*_hip_pitch_joint": DAMPING_7520_22, + ".*_hip_roll_joint": DAMPING_7520_22, + ".*_hip_yaw_joint": DAMPING_7520_14, + ".*_knee_joint": DAMPING_7520_22, + }, + armature={ + ".*_hip_pitch_joint": ARMATURE_7520_22, + ".*_hip_roll_joint": ARMATURE_7520_22, + ".*_hip_yaw_joint": ARMATURE_7520_14, + ".*_knee_joint": ARMATURE_7520_22, + }, + ), + "feet": ImplicitActuatorCfg( + effort_limit_sim=35.0, + velocity_limit_sim=30.0, + joint_names_expr=[".*_ankle_pitch_joint", ".*_ankle_roll_joint"], + stiffness=2.0 * STIFFNESS_5020, + damping=2.0 * DAMPING_5020, + armature=2.0 * ARMATURE_5020, + ), + "waist": ImplicitActuatorCfg( + effort_limit_sim=35, + velocity_limit_sim=30.0, + joint_names_expr=["waist_roll_joint", "waist_pitch_joint"], + stiffness=2.0 * STIFFNESS_5020, + damping=2.0 * DAMPING_5020, + armature=2.0 * ARMATURE_5020, + ), + "waist_yaw": ImplicitActuatorCfg( + effort_limit_sim=88, + velocity_limit_sim=32.0, + joint_names_expr=["waist_yaw_joint"], + stiffness=STIFFNESS_7520_14, + damping=DAMPING_7520_14, + armature=ARMATURE_7520_14, + ), + "arms": ImplicitActuatorCfg( + joint_names_expr=[ + ".*_shoulder_pitch_joint", + ".*_shoulder_roll_joint", + ".*_shoulder_yaw_joint", + ".*_elbow_joint", + ".*_wrist_roll_joint", + ".*_wrist_pitch_joint", + ".*_wrist_yaw_joint", + ], + effort_limit_sim={ + ".*_shoulder_pitch_joint": 25.0, + ".*_shoulder_roll_joint": 25.0, + ".*_shoulder_yaw_joint": 25.0, + ".*_elbow_joint": 25.0, + ".*_wrist_roll_joint": 25.0, + ".*_wrist_pitch_joint": 5.0, + ".*_wrist_yaw_joint": 5.0, + }, + velocity_limit_sim={ + ".*_shoulder_pitch_joint": 37.0, + ".*_shoulder_roll_joint": 37.0, + ".*_shoulder_yaw_joint": 37.0, + ".*_elbow_joint": 37.0, + ".*_wrist_roll_joint": 37.0, + ".*_wrist_pitch_joint": 22.0, + ".*_wrist_yaw_joint": 22.0, + }, + stiffness={ + ".*_shoulder_pitch_joint": STIFFNESS_5020, + ".*_shoulder_roll_joint": STIFFNESS_5020, + ".*_shoulder_yaw_joint": STIFFNESS_5020, + ".*_elbow_joint": STIFFNESS_5020, + ".*_wrist_roll_joint": STIFFNESS_5020, + ".*_wrist_pitch_joint": STIFFNESS_4010, + ".*_wrist_yaw_joint": STIFFNESS_4010, + }, + damping={ + ".*_shoulder_pitch_joint": DAMPING_5020, + ".*_shoulder_roll_joint": DAMPING_5020, + ".*_shoulder_yaw_joint": DAMPING_5020, + ".*_elbow_joint": DAMPING_5020, + ".*_wrist_roll_joint": DAMPING_5020, + ".*_wrist_pitch_joint": DAMPING_4010, + ".*_wrist_yaw_joint": DAMPING_4010, + }, + armature={ + ".*_shoulder_pitch_joint": ARMATURE_5020, + ".*_shoulder_roll_joint": ARMATURE_5020, + ".*_shoulder_yaw_joint": ARMATURE_5020, + ".*_elbow_joint": ARMATURE_5020, + ".*_wrist_roll_joint": ARMATURE_5020, + ".*_wrist_pitch_joint": ARMATURE_4010, + ".*_wrist_yaw_joint": ARMATURE_4010, + }, + ), + }, +) + +_WUJI_HAND_ACTION_SCALE = 0.1 + +G1_WUJI_ACTION_SCALE = {} +for name, actuator in G1_WUJI_CFG.actuators.items(): + if name == "wuji_hands": + for n in actuator.joint_names_expr: + G1_WUJI_ACTION_SCALE[n] = _WUJI_HAND_ACTION_SCALE + continue + + eff = actuator.effort_limit_sim + stiff = actuator.stiffness + names = actuator.joint_names_expr + if not isinstance(eff, dict): + eff = {n: eff for n in names} + if not isinstance(stiff, dict): + stiff = {n: stiff for n in names} + for n in names: + if n in eff and n in stiff and stiff[n]: + G1_WUJI_ACTION_SCALE[n] = 0.25 * eff[n] / stiff[n] + + +G1_WUJI_FIX_ACTION_SCALE = {} +for name, actuator in G1_WUJI_FIX_CFG.actuators.items(): + eff = actuator.effort_limit_sim + stiff = actuator.stiffness + names = actuator.joint_names_expr + if not isinstance(eff, dict): + eff = {n: eff for n in names} + if not isinstance(stiff, dict): + stiff = {n: stiff for n in names} + for n in names: + if n in eff and n in stiff and stiff[n]: + G1_WUJI_FIX_ACTION_SCALE[n] = 0.25 * eff[n] / stiff[n] diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/__init__.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..99427e575322655623157d899dda81dbe4492a0d --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__init__.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import gymnasium as gym + +from coordex.tasks.locomanip.config.g1_wuji import agents + + +gym.register( + id="CoorDex-WalkGrab-Wuji-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": "coordex.tasks.locomanip.walkgrab_env_cfg:WalkgrabEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:LocomanipCoordResidualPPORunnerCfg", + }, +) + +gym.register( + id="CoorDex-Fridge-Wuji-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": "coordex.tasks.locomanip.fridge_env_cfg:FridgeEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:LocomanipCoordResidualPPORunnerCfg", + }, +) + +gym.register( + id="CoorDex-WalkPickTurn-Wuji-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": "coordex.tasks.locomanip.walkpickturn_env_cfg:WalkPickTurnEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:LocomanipCoordResidualPPORunnerCfg", + }, +) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4e87383a13381ab16a06f13d82b6965fb7000f6 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/constants.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07383c8818dc1861db37807f46e98c20d41d6c7e Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/constants.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/rsi_buffer.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/rsi_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48751a65381271a11ce70804b060783b4ea8a003 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/rsi_buffer.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/walkgrab_env_cfg.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/walkgrab_env_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7842b7180dfb29a1ba842f69e4037c5366e12264 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/__pycache__/walkgrab_env_cfg.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/__init__.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14cc86f830926aaf275dbb9c95c6f827d811b04a Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/__init__.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ed6cb6c05227b4d0635b1f5d6916a1a7595fa9d Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/__init__.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7f2348cb652d3762779de5fc8f5354e0f6bfb88 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/__pycache__/rsl_rl_ppo_cfg.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/__pycache__/rsl_rl_ppo_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a21e050b0d0910874cfb5a18b152e015486f0248 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/__pycache__/rsl_rl_ppo_cfg.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/rsl_rl_ppo_cfg.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/rsl_rl_ppo_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..392c1b118f6085c4a79826a316c109f49f242283 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/agents/rsl_rl_ppo_cfg.py @@ -0,0 +1,47 @@ +from dataclasses import field + +from isaaclab.utils import configclass +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlPpoActorCriticCfg, RslRlPpoAlgorithmCfg + + +@configclass +class CoordResidualActorCriticCfg(RslRlPpoActorCriticCfg): + class_name: str = "ActorCriticCoordResidual" + coord_trunk_hidden_dims: tuple[int, ...] = (512, 256) + body_head_hidden_dims: tuple[int, ...] = (256, 128) + hand_head_hidden_dims: tuple[int, ...] = (256, 128) + body_residual_scale: float = 1.0 + hand_residual_scale: float = 1.0 + fixed_log_std: bool = True + actor_obs_term_names: tuple[str, ...] = () + actor_obs_term_dims: list[int] = field(default_factory=list) + + +@configclass +class LocomanipCoordResidualPPORunnerCfg(RslRlOnPolicyRunnerCfg): + num_steps_per_env = 24 + max_iterations = 100000 + save_interval = 1000 + experiment_name = "coordex_locomanip" + empirical_normalization = True + policy = CoordResidualActorCriticCfg( + init_noise_std=0.22, + noise_std_type="log", + actor_hidden_dims=[1024, 512, 256], + critic_hidden_dims=[1024, 512, 256], + activation="elu", + ) + algorithm = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.005, + num_learning_epochs=5, + num_mini_batches=4, + learning_rate=1.0e-3, + schedule="adaptive", + gamma=0.99, + lam=0.95, + desired_kl=0.01, + max_grad_norm=1.0, + ) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/locomanip_env_cfg.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/locomanip_env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..0cbc3ab90807aaf49aa4761fcc0f7b2eb8a2f0dd --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/config/g1_wuji/locomanip_env_cfg.py @@ -0,0 +1,5 @@ +from coordex.tasks.locomanip.fridge_env_cfg import FridgeEnvCfg +from coordex.tasks.locomanip.walkgrab_env_cfg import WalkgrabEnvCfg +from coordex.tasks.locomanip.walkpickturn_env_cfg import WalkPickTurnEnvCfg + +__all__ = ["WalkgrabEnvCfg", "FridgeEnvCfg", "WalkPickTurnEnvCfg"] diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/constants.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..581ec1747d9e1a421445440dfcb00a2fefa6ff6d --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/constants.py @@ -0,0 +1,45 @@ +MODE12_JOINT_ORDER = [ + "left_hip_pitch_joint", + "left_hip_roll_joint", + "left_hip_yaw_joint", + "left_knee_joint", + "left_ankle_pitch_joint", + "left_ankle_roll_joint", + "right_hip_pitch_joint", + "right_hip_roll_joint", + "right_hip_yaw_joint", + "right_knee_joint", + "right_ankle_pitch_joint", + "right_ankle_roll_joint", + "waist_yaw_joint", + "waist_roll_joint", + "waist_pitch_joint", + "left_shoulder_pitch_joint", + "left_shoulder_roll_joint", + "left_shoulder_yaw_joint", + "left_elbow_joint", + "left_wrist_roll_joint", + "left_wrist_pitch_joint", + "left_wrist_yaw_joint", + "right_shoulder_pitch_joint", + "right_shoulder_roll_joint", + "right_shoulder_yaw_joint", + "right_elbow_joint", + "right_wrist_roll_joint", + "right_wrist_pitch_joint", + "right_wrist_yaw_joint", +] + +RIGHT_HAND_JOINT_PATTERNS = [ + f"right_finger{finger_idx}_joint{joint_idx}" + for finger_idx in range(1, 6) + for joint_idx in range(1, 5) +] + +RIGHT_HAND_TIP_NAMES = [ + "right_finger1_tip_link", + "right_finger2_tip_link", + "right_finger3_tip_link", + "right_finger4_tip_link", + "right_finger5_tip_link", +] diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/fridge_env_cfg.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/fridge_env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2860d4163cb9ebe1265189ba0c97e984977569 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/fridge_env_cfg.py @@ -0,0 +1,624 @@ +"""Open Fridge environment for G1 Wuji.""" + +from __future__ import annotations + +from dataclasses import MISSING +import math +import re +from pathlib import Path + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import ContactSensorCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass + +import coordex.tasks.locomanip.mdp as mdp +from coordex.assets import ASSET_DIR +from coordex.robots.g1_wuji import G1_WUJI_ACTION_SCALE, G1_WUJI_CFG, WUJI_RH_ACTIVE_JOINT_NAMES +from coordex.tasks.locomanip.constants import MODE12_JOINT_ORDER, RIGHT_HAND_TIP_NAMES + + +REPO_ROOT = Path(__file__).resolve().parents[5] +FRIDGE_DOOR_BODY = "E_door_1" +FRIDGE_DOOR_JOINT = "RevoluteJoint_fridge_1_up" +FRIDGE_HANDLE_LOCAL_POS = (-0.5832248999999999, - + 0.09136289999999997, -0.5385152000000001) +FRIDGE_HELD_OPEN_ANGLE = math.radians(35.0) +FRIDGE_SUCCESS_ANGLE = math.radians(60.0) +FRIDGE_SUCCESS_HOLD_STEPS = 30 +FOOT_BODY_NAMES = ["left_ankle_roll_link", "right_ankle_roll_link"] + + +@configclass +class FridgeSceneCfg(InteractiveSceneCfg): + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="plane", + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + ), + visual_material=sim_utils.MdlFileCfg( + mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl", + project_uvw=True, + ), + ) + + robot: ArticulationCfg = MISSING + + fridge: ArticulationCfg = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Fridge", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ASSET_DIR}/objects/fridge/model_fridge_1.usd", + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=1.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=16, + solver_velocity_iteration_count=4, + fix_root_link=True, + ), + collision_props=sim_utils.CollisionPropertiesCfg( + collision_enabled=True), + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(1.6, 0.0, 0.0), + rot=(0.70710678, 0.0, 0.0, -0.70710678), + joint_pos={".*": 0.0}, + joint_vel={".*": 0.0}, + ), + soft_joint_pos_limit_factor=1.0, + actuators={ + "passive_doors": ImplicitActuatorCfg( + joint_names_expr=[".*"], + effort_limit_sim=200.0, + velocity_limit_sim=10.0, + stiffness=0.0, + damping=2.0, + armature=0.001, + ), + }, + ) + + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DistantLightCfg( + color=(0.75, 0.75, 0.75), intensity=3000.0), + ) + sky_light = AssetBaseCfg( + prim_path="/World/skyLight", + spawn=sim_utils.DomeLightCfg( + color=(0.13, 0.13, 0.13), intensity=1000.0), + ) + contact_forces = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*", + history_length=3, + track_air_time=True, + force_threshold=10.0, + debug_vis=False, + ) + contact_force_thumb = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger1_tip_link", + filter_prim_paths_expr=[ + "{ENV_REGEX_NS}/Fridge/E_door_1", + "{ENV_REGEX_NS}/Fridge/E_handle_1_7", + ], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_index = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger2_tip_link", + filter_prim_paths_expr=[ + "{ENV_REGEX_NS}/Fridge/E_door_1", + "{ENV_REGEX_NS}/Fridge/E_handle_1_7", + ], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_middle = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger3_tip_link", + filter_prim_paths_expr=[ + "{ENV_REGEX_NS}/Fridge/E_door_1", + "{ENV_REGEX_NS}/Fridge/E_handle_1_7", + ], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_ring = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger4_tip_link", + filter_prim_paths_expr=[ + "{ENV_REGEX_NS}/Fridge/E_door_1", + "{ENV_REGEX_NS}/Fridge/E_handle_1_7", + ], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_pinky = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger5_tip_link", + filter_prim_paths_expr=[ + "{ENV_REGEX_NS}/Fridge/E_door_1", + "{ENV_REGEX_NS}/Fridge/E_handle_1_7", + ], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + + +@configclass +class ActionsCfg: + joint_pos = mdp.ResidualLatentActionCfg(asset_name="robot", joint_names=[ + ".*"], use_default_offset=True) + + +@configclass +class ObservationsCfg: + @configclass + class PolicyCfg(ObsGroup): + stage = ObsTerm(func=mdp.stage_one_hot, params={ + "command_name": "stage"}) + + projected_gravity = ObsTerm(func=mdp.projected_gravity) + + humanoid_prior = ObsTerm( + func=mdp.TrackingPriorHistoryTerm, + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=MODE12_JOINT_ORDER, preserve_order=True), + "noise_cfg": mdp.TRACKING_PRIOR_NOISE_CFG, + "history_length": 5, + }, + ) + right_hand_prior = ObsTerm( + func=mdp.right_hand_proprio, + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=WUJI_RH_ACTIVE_JOINT_NAMES, preserve_order=True), + "wrist_body_name": "right_palm_link", + }, + ) + last_latent = ObsTerm( + func=mdp.last_residual_latent, + params={"action_term_name": "joint_pos"}, + ) + fingertip_cube_forces = ObsTerm( + func=mdp.fingertip_force_on_cube, + params={ + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "asset_cfg": SceneEntityCfg("robot"), + "fingertip_body_names": RIGHT_HAND_TIP_NAMES, + "force_scale": 50.0, + "force_clip": 1.0, + }, + ) + + source_table_pose = ObsTerm( + func=mdp.object_pose_in_robot_frame, + params={"target_cfg": SceneEntityCfg("fridge")}, + ) + cube_pose = ObsTerm( + func=mdp.body_offset_pose_in_robot_frame, + params={ + "target_cfg": SceneEntityCfg("fridge"), + "body_name": FRIDGE_DOOR_BODY, + "local_pos": FRIDGE_HANDLE_LOCAL_POS, + }, + ) + target_table_pose = ObsTerm( + func=mdp.body_pose_in_robot_frame, + params={"target_cfg": SceneEntityCfg( + "fridge"), "body_name": FRIDGE_DOOR_BODY}, + ) + cube_pose_in_hand = ObsTerm( + func=mdp.body_offset_pose_in_hand_frame, + params={ + "target_cfg": SceneEntityCfg("fridge"), + "body_name": FRIDGE_DOOR_BODY, + "local_pos": FRIDGE_HANDLE_LOCAL_POS, + "hand_body_name": "right_palm_link", + }, + ) + door_joint_state = ObsTerm( + func=mdp.articulation_joint_state, + params={"asset_cfg": SceneEntityCfg( + "fridge", joint_names=[FRIDGE_DOOR_JOINT], preserve_order=True)}, + ) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + @configclass + class CriticCfg(PolicyCfg): + def __post_init__(self): + self.enable_corruption = False + + policy: PolicyCfg = PolicyCfg() + critic: CriticCfg = CriticCfg() + + +@configclass +class CommandsCfg: + stage = mdp.FridgeStageCommandCfg( + asset_name="robot", + fridge_name="fridge", + handle_local_pos=FRIDGE_HANDLE_LOCAL_POS, + door_body_name=FRIDGE_DOOR_BODY, + door_joint_name=FRIDGE_DOOR_JOINT, + contact_sensor_name=[ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + fingertip_body_names=RIGHT_HAND_TIP_NAMES, + hand_base_body_name="right_palm_link", + contact_force_threshold=1.0, + held_open_angle=FRIDGE_HELD_OPEN_ANGLE, + held_open_require_contact=True, + success_door_angle=FRIDGE_SUCCESS_ANGLE, + success_hold_steps=FRIDGE_SUCCESS_HOLD_STEPS, + min_fingertip_contacts=1, + required_contact_sensors=(), + backward_axis_yaw_offset=math.radians(25.0), + ) + + +@configclass +class RewardsCfg: + robot_fridge_distance = RewTerm( + func=mdp.robot_object_distance_reward, + weight=0.0, + params={ + "command_name": "stage", + "object_name": "fridge", + "target_distance": 0.70, + "scale": 4.0, + }, + ) + forward_progress = RewTerm( + func=mdp.base_target_progress_reward, + weight=0.0, + params={ + "command_name": "stage", + "target_name": "fridge", + "speed_scale": 0.6, + }, + ) + heading_to_fridge = RewTerm( + func=mdp.heading_to_object_penalty, + weight=0.0, + params={"command_name": "stage", "object_name": "fridge"}, + ) + + hand_handle_distance = RewTerm( + func=mdp.hand_body_distance_reward, + weight=30.0, + params={ + "command_name": "stage", + "target_cfg": SceneEntityCfg("fridge"), + "target_body_name": FRIDGE_DOOR_BODY, + "hand_body_names": [*RIGHT_HAND_TIP_NAMES, "right_palm_link"], + "target_body_local_pos": FRIDGE_HANDLE_LOCAL_POS, + "scale": 10.0, + "distance_aggregation": "mean", + }, + ) + + fingertip_contact = RewTerm( + func=mdp.fingertip_contact_reward, + weight=15.0, + params={ + "command_name": "stage", + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "threshold": 1.0, + "bonus_start_contacts": 2, + "bonus_scale": 0.25, + "bonus_power": 2.0, + }, + ) + + thumb_contact = RewTerm( + func=mdp.fingertip_contact_reward, + weight=10.0, + params={ + "command_name": "stage", + "sensor_names": ["contact_force_thumb"], + "threshold": 1.0, + }, + ) + + door_open_amount = RewTerm( + func=mdp.fridge_door_open_with_contact_reward, + weight=30.0, + params={ + "command_name": "stage", + "target_angle": FRIDGE_SUCCESS_ANGLE, + "power": 1.0, + "contact_scale": 1.0, + }, + ) + door_open_progress = RewTerm( + func=mdp.fridge_door_open_progress_reward, + weight=20.0, + params={ + "command_name": "stage", + "progress_scale": 0.02, + "require_contact": True, + }, + ) + door_close_regression = RewTerm( + func=mdp.fridge_door_close_regression_reward, + weight=-20.0, + params={ + "command_name": "stage", + "regression_scale": 0.02, + }, + ) + + door_held_open = RewTerm( + func=mdp.fridge_door_held_open_reward, + weight=100.0, + params={ + "command_name": "stage", + "hold_angle": FRIDGE_HELD_OPEN_ANGLE, + "max_seconds": 1.0, + "require_contact": True, + }, + ) + + backward_progress = RewTerm( + func=mdp.base_backward_progress_reward, + weight=8.0, + params={ + "command_name": "stage", + "speed_scale": 0.25, + "require_contact": True, + }, + ) + + success_bonus = RewTerm( + func=mdp.termination_penalty, + weight=1000.0, + params={"term_name": "success"}, + ) + robot_fall_penalty = RewTerm( + func=mdp.termination_penalty, + weight=-10.0, + params={"term_name": "robot_fall"}, + ) + hand_far_penalty = RewTerm( + func=mdp.termination_penalty, + weight=-20.0, + params={"term_name": "hand_far_from_handle"}, + ) + time_out_penalty = RewTerm( + func=mdp.termination_penalty, + weight=-20.0, + params={"term_name": "time_out"}, + ) + + action_rate_l2 = RewTerm( + func=mdp.action_rate_l2_clipped, + weight=-1.0e-2, + params={"clip_max": 100.0}, + ) + joint_action_rate_l2 = RewTerm( + func=mdp.joint_action_rate_l2_clipped, + weight=-1.0e-2, + params={"clip_max": 50.0}, + ) + dof_velocity_l2 = RewTerm( + func=mdp.joint_velocity_l2_clipped, + weight=-1.0e-2, + params={ + "command_name": "stage", + "asset_cfg": SceneEntityCfg("robot", joint_names=[".*"]), + "clip_max": 200.0, + }, + ) + feet_slip = RewTerm( + func=mdp.feet_slip_penalty_clipped, + weight=-5.0, + params={ + "command_name": "stage", + "sensor_cfg": SceneEntityCfg("contact_forces", body_names=FOOT_BODY_NAMES), + "threshold": 5.0, + "clip_max": 2.0, + }, + ) + large_lin_vx = RewTerm( + func=mdp.base_lin_vel_excess, + weight=-8.0, + params={"command_name": "stage", "axis": 0, "threshold": 0.8, "max_penalty": 2.0}, + ) + large_lin_vy = RewTerm( + func=mdp.base_lin_vel_excess, + weight=-10.0, + params={"command_name": "stage", "axis": 1, "threshold": 0.35, "max_penalty": 2.0}, + ) + large_ang_vel = RewTerm( + func=mdp.base_ang_vel_excess, + weight=-10.0, + params={"command_name": "stage", "axis": 2, "threshold": 0.6, "max_penalty": 5.0}, + ) + + +@configclass +class TerminationsCfg: + time_out = DoneTerm(func=mdp.time_out, time_out=True) + success = DoneTerm(func=mdp.stage_success, params={ + "command_name": "stage"}) + hand_far_from_handle = DoneTerm( + func=mdp.hand_far_from_handle, + params={"command_name": "stage", "max_distance": 0.5}, + ) + robot_fall = DoneTerm( + func=mdp.robot_fall, + params={"asset_cfg": SceneEntityCfg( + "robot"), "body_name": "torso_link", "min_height": 0.35}, + ) + robot_root_state_blowup = DoneTerm( + func=mdp.root_state_blowup, + params={ + "asset_name": "robot", + "max_xy_radius": 6.0, + "max_height": 3.0, + "max_lin_vel": 10.0, + "max_ang_vel": 20.0, + }, + ) + fridge_root_state_blowup = DoneTerm( + func=mdp.root_state_blowup, + params={ + "asset_name": "fridge", + "max_xy_radius": 6.0, + "min_height": -0.5, + "max_height": 3.0, + "max_lin_vel": 5.0, + "max_ang_vel": 10.0, + }, + ) + robot_joint_velocity_blowup = DoneTerm( + func=mdp.joint_velocity_blowup, + params={"asset_name": "robot", "max_abs_joint_vel": 40.0}, + ) + fridge_joint_velocity_blowup = DoneTerm( + func=mdp.joint_velocity_blowup, + params={"asset_name": "fridge", "max_abs_joint_vel": 20.0}, + ) + + +@configclass +class CurriculumCfg: + pass + + +@configclass +class EventCfg: + reset_scene = EventTerm( + func=mdp.reset_fridge_to_pregrasp_demo_frame, + mode="reset", + params={ + "pose_range": None, + "joint_position_range": None, + "reset_joint_targets": True, + }, + ) + physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*"), + "static_friction_range": (0.3, 1.0), + "dynamic_friction_range": (0.3, 1.0), + "restitution_range": (0.0, 0.1), + "num_buckets": 64, + }, + ) + base_com = EventTerm( + func=mdp.randomize_rigid_body_com, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names="torso_link"), + "com_range": {"x": (-0.025, 0.025), "y": (-0.05, 0.05), "z": (-0.05, 0.05)}, + }, + ) + + +@configclass +class FridgeEnvCfg(ManagerBasedRLEnvCfg): + scene: FridgeSceneCfg = FridgeSceneCfg(num_envs=4096, env_spacing=5.0) + commands: CommandsCfg = CommandsCfg() + actions: ActionsCfg = ActionsCfg() + observations: ObservationsCfg = ObservationsCfg() + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + curriculum: CurriculumCfg = CurriculumCfg() + events: EventCfg = EventCfg() + + def __post_init__(self): + + self.decimation = 4 + self.episode_length_s = 7.0 + self.sim.dt = 1.0 / (60.0 * 4) + self.sim.render_interval = self.decimation + self.sim.physics_material = self.scene.terrain.physics_material + self.sim.physx.gpu_max_rigid_patch_count = 10 * 2**15 + self.viewer.eye = (-1.2, 2.1, 2.1) + self.viewer.lookat = (1.0, 0.0, 0.85) + self.viewer.origin_type = "world" + self.scene.robot = G1_WUJI_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot") + action_joint_names = MODE12_JOINT_ORDER + \ + list(WUJI_RH_ACTIVE_JOINT_NAMES) + action_scale = dict(G1_WUJI_ACTION_SCALE) + for joint_name in WUJI_RH_ACTIVE_JOINT_NAMES: + action_scale.setdefault(joint_name, 0.1) + + action = self.actions.joint_pos + action.scale = { + pattern: value + for pattern, value in action_scale.items() + if any(re.fullmatch(pattern, joint_name) for joint_name in action_joint_names) + } + action.joint_names = action_joint_names + action.preserve_order = True + action.clip_actions = False + action.body_prior_checkpoint = str( + REPO_ROOT / "ckpts/body_prior/fridge_2k.pt") + action.hand_prior_checkpoint = str( + REPO_ROOT / "ckpts/hand_prior/kinematic_wrist_16k.pt") + action.body_obs_norm_mode = "rsl_rl" + action.hand_action_moving_average = 0.4 + action.hand_joint_names = tuple(WUJI_RH_ACTIVE_JOINT_NAMES) + action.hand_wrist_body_name = "right_palm_link" + action.hand_prior_variant = "wuji_floating_kinematic_wrist" + + for obs_group in (self.observations.policy, self.observations.critic): + obs_group.humanoid_prior.params["include_base_lin_vel"] = False + + self.observations.policy.body_prior_mean = ObsTerm( + func=mdp.body_prior_mean, + params={"action_term_name": "joint_pos"}, + ) + self.observations.policy.hand_prior_mean = ObsTerm( + func=mdp.hand_prior_mean, + params={"action_term_name": "joint_pos"}, + ) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/fridge_reset_states.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/fridge_reset_states.py new file mode 100644 index 0000000000000000000000000000000000000000..d5b9e3f993e6db369a63e99bfd91e1738f806721 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/fridge_reset_states.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +PREGRASP_ROOT_POS: tuple[float, float, float] = (0.721733, 0.022447, 0.681773) +PREGRASP_ROOT_QUAT_WXYZ: tuple[float, float, float, float] = ( + 0.997233, -0.010191, 0.024375, -0.069481) +PREGRASP_FRIDGE_JOINT_POS: tuple[float, ...] = (0.006576, 0.0, 0.0, 0.0, 0.0) + +# Full 69-joint robot pose (29 body + 20 LH + 20 RH). +PREGRASP_ROBOT_JOINT_POS: tuple[float, ...] = ( + -0.616983, -0.819145, 1.009503, 0.112298, 0.085242, -0.171245, 0.133154, + 0.000569, 0.315594, 1.210788, 1.075565, -0.227997, -1.287148, -0.639507, + -0.323273, 0.371328, -0.193296, 0.024048, -0.151723, 0.001968, -0.494901, + 0.592860, 1.095708, -0.530918, -0.295993, -0.058423, -0.105565, -0.747103, + -1.143090, 1.110330, 0.468933, 0.209316, 0.171950, 0.108140, 1.549881, + 0.790268, 0.942595, 0.915366, 0.630041, 0.616244, 0.322138, 0.370000, + 0.370000, 0.370000, -0.138708, -0.232754, -0.329545, -0.259190, -0.316642, + 0.049260, -0.051877, -0.051005, -0.040991, -0.017841, 0.339548, 0.757542, + 0.505900, 0.343800, 0.279126, 0.043440, 0.082375, 0.083122, 0.083376, + 0.082457, 0.052958, 0.583232, 0.549232, 0.896815, 1.115497, +) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__init__.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46f230e83c278a3925a97ce63ac57c07847ab860 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__init__.py @@ -0,0 +1,9 @@ +from isaaclab.envs.mdp import * # noqa: F401, F403 + +from .actions import * # noqa: F401, F403 +from .commands import * # noqa: F401, F403 +from .events import * # noqa: F401, F403 +from .observations import * # noqa: F401, F403 +from .rewards import * # noqa: F401, F403 +from .rsi import * # noqa: F401, F403 +from .terminations import * # noqa: F401, F403 diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/__init__.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a85c7fe70d3786b04854a3b48aa8b4f4515aa9f9 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/__init__.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/actions.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/actions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..031cdcbaba390877b44a36a74faa195de61e4852 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/actions.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/commands.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/commands.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fc8f26db02ac4d555bef497b6a87e0b36f0a744 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/commands.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/events.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/events.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ca9773324262d15833188f5932651e2f436d481 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/events.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/observations.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/observations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c043577b0a4799ae3a5ecce17dddc8ec34049a22 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/observations.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/rewards.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/rewards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2873572c873881a1240660395d39a5ce98494c3 Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/rewards.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/rsi.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/rsi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6ecb1695280797d7f10479bf3fe151d0a6e3e5c Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/rsi.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/terminations.cpython-312.pyc b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/terminations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f742afcd22e403e2c14f57df1f527fc7ff21e2ec Binary files /dev/null and b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/__pycache__/terminations.cpython-312.pyc differ diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/actions.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..e5191c870becabee7c019c9e8b7212e8c0cf97bc --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/actions.py @@ -0,0 +1,1181 @@ +from __future__ import annotations + +import inspect +import os +from types import SimpleNamespace + +import torch + +from isaaclab.envs.mdp import JointPositionAction, JointPositionActionCfg +from isaaclab.managers.action_manager import ActionTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils import configclass + +from coordex.robots.g1_wuji import WUJI_RH_ACTIVE_JOINT_NAMES +from coordex.distillation.vae import StudentTeacherVAE +from coordex.tasks.locomanip.constants import MODE12_JOINT_ORDER + +from .observations import ( + TRACKING_PRIOR_NOISE_CFG, + clear_prior_obs_step_cache, + reset_tracking_prior_history, + right_hand_proprio, + tracking_prior_history, +) + + +_BODY_PRIOR_FRAME_DIM_WITH_BASE_LIN_VEL = 93 +_BODY_PRIOR_FRAME_DIM_NO_BASE_LIN_VEL = 90 +_BODY_PRIOR_FRAME_DIMS = ( + _BODY_PRIOR_FRAME_DIM_WITH_BASE_LIN_VEL, _BODY_PRIOR_FRAME_DIM_NO_BASE_LIN_VEL) + + +def _distill_cfg( + *, + proprio_dim: int, + latent_dim: int, + posterior_std_max: float, + prior_std_max: float, + proprio_frame_dim: int = 0, + proprio_history_length: int = 1, + proprio_source_dim: int = 0, + action_tail_dim: int = 0, + action_keep_dim: int = 0, +): + return SimpleNamespace( + init_noise_std=0.05, + noise_std_type="log", + student_hidden_dims=[256, 256, 128], + teacher_hidden_dims=(1024, 512, 256), + activation="elu", + tanh_actions=False, + latent_dim=latent_dim, + encoder_hidden_dims=(512, 256, 128), + decoder_hidden_dims=(512, 256, 128), + prior_hidden_dims=(512, 256, 128), + posterior_std_min=1.0e-4, + posterior_std_max=posterior_std_max, + prior_std_min=1.0e-4, + prior_std_max=prior_std_max, + latent_dropout=0.0, + proprio_dim=proprio_dim, + proprio_frame_dim=proprio_frame_dim, + proprio_history_length=proprio_history_length, + proprio_source_dim=proprio_source_dim, + action_tail_dim=action_tail_dim, + action_keep_dim=action_keep_dim, + wrist_action_dim=0, + use_teacher_wrist=False, + mask_wrist_in_loss=False, + ) + + +_BODY_PRIOR_CFG_WITH_BASE_LIN_VEL = _distill_cfg( + proprio_dim=465, + latent_dim=16, + posterior_std_max=5.0, + prior_std_max=5.0, + proprio_frame_dim=93, + proprio_history_length=5, +) +_BODY_PRIOR_CFG_NO_BASE_LIN_VEL = _distill_cfg( + proprio_dim=450, + latent_dim=16, + posterior_std_max=5.0, + prior_std_max=5.0, + proprio_frame_dim=90, + proprio_history_length=5, +) +_WUJI_HAND_ACTIVE_CFG = _distill_cfg( + proprio_dim=66, + latent_dim=12, + posterior_std_max=10.0, + prior_std_max=10.0, + proprio_source_dim=72, + action_tail_dim=26, + action_keep_dim=20, +) +_WUJI_HAND_KINEMATIC_WRIST_CFG = _distill_cfg( + proprio_dim=66, + latent_dim=12, + posterior_std_max=10.0, + prior_std_max=10.0, +) + + +_HAND_PRIOR_VARIANT_SPECS = { + "wuji_floating_active": { + "policy_cfg": _WUJI_HAND_ACTIVE_CFG, + "default_joint_names": tuple(WUJI_RH_ACTIVE_JOINT_NAMES), + "wrist_body_name": "right_palm_link", + "proprio_dim": 66, + "dummy_action_dim": 6, + }, + "wuji_floating_kinematic_wrist": { + "policy_cfg": _WUJI_HAND_KINEMATIC_WRIST_CFG, + "default_joint_names": tuple(WUJI_RH_ACTIVE_JOINT_NAMES), + "wrist_body_name": "right_palm_link", + "proprio_dim": 66, + "dummy_action_dim": 0, + }, +} + + +def _get_hand_prior_variant_spec(hand_prior_variant: str) -> dict[str, object]: + try: + return _HAND_PRIOR_VARIANT_SPECS[hand_prior_variant] + except KeyError as exc: + supported = ", ".join(sorted(_HAND_PRIOR_VARIANT_SPECS)) + raise ValueError( + f"Unsupported hand_prior_variant '{hand_prior_variant}'. Expected one of: {supported}.") from exc + + +def _normalize_hand_joint_names( + hand_joint_names: tuple[str, ...] | list[str] | None, + *, + variant: str, +) -> tuple[str, ...]: + if hand_joint_names: + return tuple(str(name) for name in hand_joint_names) + spec = _get_hand_prior_variant_spec(variant) + return tuple(spec["default_joint_names"]) + + +def get_hand_prior_default_wrist_body_name(hand_prior_variant: str) -> str: + return str(_get_hand_prior_variant_spec(hand_prior_variant)["wrist_body_name"]) + + +def get_hand_prior_expected_dims( + hand_prior_variant: str, + hand_joint_names: tuple[str, ...] | list[str] | None = None, +) -> tuple[int, int]: + spec = _get_hand_prior_variant_spec(hand_prior_variant) + joint_names = _normalize_hand_joint_names( + hand_joint_names, variant=hand_prior_variant) + proprio_dim = int(spec["proprio_dim"]) + action_dim = int(spec["dummy_action_dim"]) + len(joint_names) + return proprio_dim, action_dim + + +class _ObsNormalizer: + def __init__(self, mean: torch.Tensor, var: torch.Tensor, eps: float = 1.0e-8, clip: float | None = None): + self.mean = mean + self.var = var + self.eps = eps + self.clip = clip + + def __call__(self, obs: torch.Tensor) -> torch.Tensor: + normalized = (obs - self.mean) / torch.sqrt(self.var + self.eps) + if self.clip is not None: + normalized = torch.clamp(normalized, -self.clip, self.clip) + return normalized + + +def _infer_prior_input_dim_from_checkpoint(ckpt_path: str | None) -> int | None: + if not ckpt_path or not os.path.isfile(ckpt_path): + return None + checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False) + state_dict, _ = _extract_state_dict(checkpoint) + state_dict = _strip_module_prefix(state_dict) + for key, value in state_dict.items(): + if not isinstance(value, torch.Tensor) or value.ndim != 2: + continue + if key.endswith("prior_net.0.weight") or ".prior_net.0.weight" in key: + return int(value.shape[1]) + return None + + +def _infer_body_prior_frame_dim(proprio_dim: int) -> int: + for frame_dim in _BODY_PRIOR_FRAME_DIMS: + if proprio_dim > 0 and proprio_dim % frame_dim == 0: + return frame_dim + supported = ", ".join(str(value) for value in _BODY_PRIOR_FRAME_DIMS) + raise RuntimeError( + "Body prior proprio dim must be an integer multiple of one supported single-frame proprio size " + f"({supported}); got {proprio_dim}." + ) + + +def _get_body_distill_policy_cfg(ckpt_path: str | None): + input_dim = _infer_prior_input_dim_from_checkpoint(ckpt_path) + if input_dim is not None: + frame_dim = _infer_body_prior_frame_dim(input_dim) + if frame_dim == _BODY_PRIOR_FRAME_DIM_NO_BASE_LIN_VEL: + return _BODY_PRIOR_CFG_NO_BASE_LIN_VEL + return _BODY_PRIOR_CFG_WITH_BASE_LIN_VEL + + +def _strip_module_prefix(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + if any(key.startswith("module.") for key in state_dict): + return {key.removeprefix("module."): value for key, value in state_dict.items()} + return state_dict + + +def _extract_state_dict(checkpoint: object) -> tuple[dict[str, torch.Tensor], dict]: + if isinstance(checkpoint, dict): + for key in ("model_state_dict", "policy_state_dict", "state_dict", "actor_critic_state_dict"): + value = checkpoint.get(key) + if isinstance(value, dict): + return value, checkpoint + if isinstance(checkpoint, dict): + return checkpoint, checkpoint + raise ValueError( + "Unsupported checkpoint format; expected a state_dict or a checkpoint dict.") + + +def _find_module_prefix(state_dict: dict[str, torch.Tensor], module_name: str) -> str | None: + token = f".{module_name}." + for key in state_dict: + if token in key: + return key.split(token)[0] + if key.startswith(f"{module_name}."): + return "" + return None + + +def _strip_key_prefix(key: str, prefix: str | None) -> str: + if not prefix: + return key + prefix_with_dot = f"{prefix}." + if key.startswith(prefix_with_dot): + return key[len(prefix_with_dot):] + return key + + +def _coerce_obs_norm_state(state: object | None) -> dict | None: + if state is None: + return None + if isinstance(state, dict): + if isinstance(state.get("state_dict"), dict): + return state["state_dict"] + return state + if hasattr(state, "state_dict"): + try: + extracted = state.state_dict() + except Exception: + extracted = None + if isinstance(extracted, dict): + return extracted + attr_pairs = ( + ("mean", "var", "mean", "var"), + ("running_mean", "running_var", "running_mean", "running_var"), + ("_mean", "_var", "_mean", "_var"), + ("mean", "std", "mean", "std"), + ("running_mean", "running_std", "running_mean", "running_std"), + ("_mean", "_std", "_mean", "_std"), + ) + for mean_key, var_key, out_mean, out_var in attr_pairs: + if hasattr(state, mean_key) and hasattr(state, var_key): + return {out_mean: getattr(state, mean_key), out_var: getattr(state, var_key)} + return None + + +def _infer_obs_norm_dim(state: dict | None) -> int: + if not state: + return 0 + for key in ( + "mean", + "running_mean", + "_mean", + "var", + "running_var", + "variance", + "_var", + "std", + "running_std", + "_std", + ): + if key in state: + return int(torch.as_tensor(state[key]).view(-1).numel()) + return 0 + + +def _iter_obs_norm_states(checkpoint: dict, _depth: int = 0): + if _depth > 2: + return + candidate_keys = ( + "obs_normalizer_state_dict", + "obs_normalizer", + "normalizer_state_dict", + "obs_norm_state_dict", + "normalizer", + "obs_rms", + "obs_rms_state_dict", + "obs_rms_state", + ) + for key in candidate_keys: + if key in checkpoint: + state = _coerce_obs_norm_state(checkpoint[key]) + if state: + yield key, state + nested_keys = ( + "runner_state_dict", + "runner_state", + "algorithm_state_dict", + "algo_state", + "train_state", + ) + for nested_key in nested_keys: + nested = checkpoint.get(nested_key) + if isinstance(nested, dict): + yield from _iter_obs_norm_states(nested, _depth=_depth + 1) + + +def _select_obs_norm_state(checkpoint: dict, expected_dim: int) -> dict | None: + candidates: list[tuple[int, dict]] = [] + for _, state in _iter_obs_norm_states(checkpoint): + dim = _infer_obs_norm_dim(state) + if dim > 0: + candidates.append((dim, state)) + if not candidates: + return None + if expected_dim > 0: + viable = [entry for entry in candidates if entry[0] >= expected_dim] + if viable: + candidates = viable + candidates.sort(key=lambda entry: entry[0], reverse=True) + return candidates[0][1] + + +def _resolve_obs_norm_hparams(state: dict) -> tuple[float, float]: + if "clip" in state: + clip = state["clip"] + elif "clip_range" in state: + clip = state["clip_range"] + else: + clip = None + default_eps = 1.0e-2 + eps = float(state["eps"] if "eps" in state else state.get( + "epsilon") or default_eps) + clip_value = float(clip) if clip is not None else None + return eps, clip_value + + +def _slice_norm_tensor( + tensor: torch.Tensor, + expected_dim: int, + split_spec: tuple[int, int, int] | None = None, +) -> torch.Tensor: + if tensor.numel() == expected_dim: + return tensor + if tensor.numel() < expected_dim: + raise ValueError( + f"Obs normalizer dimension mismatch: expected {expected_dim}, got {tensor.numel()}." + ) + if split_spec is not None: + src_dim, tail_dim, keep_dim = split_spec + if ( + src_dim > 0 + and tail_dim > 0 + and keep_dim > 0 + and keep_dim <= tail_dim + and tensor.numel() >= src_dim + and (src_dim - tail_dim + keep_dim) == expected_dim + ): + source = tensor[-src_dim:] + return torch.cat((source[: src_dim - tail_dim], source[-keep_dim:])) + return tensor[-expected_dim:] + + +def _prepare_obs_norm_state( + state: dict, + expected_dim: int, + split_spec: tuple[int, int, int] | None = None, +) -> dict: + prepared: dict = {} + slice_keys = ( + "mean", + "running_mean", + "_mean", + "var", + "running_var", + "variance", + "_var", + "std", + "running_std", + "_std", + ) + for key, value in state.items(): + if key in slice_keys: + tensor = torch.as_tensor(value, dtype=torch.float32).view(-1) + prepared[key] = _slice_norm_tensor( + tensor, expected_dim, split_spec) + elif isinstance(value, (torch.Tensor, list, tuple)): + prepared[key] = torch.as_tensor(value, dtype=torch.float32) + else: + prepared[key] = value + return prepared + + +def _build_rsl_obs_normalizer( + state: dict, + expected_dim: int, + device: torch.device, + split_spec: tuple[int, int, int] | None = None, +) -> object | None: + try: + from rsl_rl.modules import EmpiricalNormalization # type: ignore + except Exception as exc: + print(f"[WARN] rsl_rl EmpiricalNormalization not available: {exc}") + return None + + eps, clip_value = _resolve_obs_norm_hparams(state) + prepared_state = _prepare_obs_norm_state( + state, expected_dim, split_spec=split_spec) + + init_kwargs: dict[str, object] = {} + try: + sig = inspect.signature(EmpiricalNormalization.__init__) + except (TypeError, ValueError): + sig = None + if sig is not None: + params = sig.parameters + if "shape" in params: + init_kwargs["shape"] = [expected_dim] + elif "size" in params: + init_kwargs["size"] = [expected_dim] + if "epsilon" in params: + init_kwargs["epsilon"] = eps + elif "eps" in params: + init_kwargs["eps"] = eps + if "clip" in params and clip_value is not None: + init_kwargs["clip"] = clip_value + if "until" in params: + init_kwargs["until"] = 1.0e8 + + try: + normalizer = EmpiricalNormalization(**init_kwargs) + except Exception: + normalizer = EmpiricalNormalization([expected_dim]) + normalizer.to(device) + try: + target_state = normalizer.state_dict() + + def _reshape_to_target(value: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + if value.shape == target.shape: + return value + if value.numel() == target.numel(): + return value.view(target.shape) + if value.ndim == 1 and target.ndim == 2: + if target.shape[0] == 1 and value.shape[0] == target.shape[1]: + return value.unsqueeze(0) + if target.shape[1] == 1 and value.shape[0] == target.shape[0]: + return value.unsqueeze(1) + if value.ndim == 2 and target.ndim == 1: + if value.shape[0] == 1 and value.shape[1] == target.shape[0]: + return value.squeeze(0) + if value.shape[1] == 1 and value.shape[0] == target.shape[0]: + return value.squeeze(1) + return value + + adjusted_state: dict[str, object] = {} + for key, value in prepared_state.items(): + if key in target_state and isinstance(value, torch.Tensor): + adjusted = _reshape_to_target(value, target_state[key]) + if adjusted.shape != target_state[key].shape: + continue + adjusted_state[key] = adjusted + else: + adjusted_state[key] = value + + normalizer.load_state_dict(adjusted_state, strict=False) + except Exception as exc: + print(f"[WARN] Failed to load obs normalizer state: {exc}") + if hasattr(normalizer, "clip"): + normalizer.clip = clip_value + if hasattr(normalizer, "epsilon"): + normalizer.epsilon = eps + if hasattr(normalizer, "eps"): + normalizer.eps = eps + normalizer.eval() + return normalizer + + +def _build_obs_normalizer( + checkpoint: dict, + expected_dim: int, + device: torch.device, + *, + enable: bool, + mode: str = "simple", + split_spec: tuple[int, int, int] | None = None, +) -> _ObsNormalizer | object | None: + if not enable: + return None + state = _coerce_obs_norm_state( + _select_obs_norm_state(checkpoint, expected_dim)) + if not state: + print( + "[WARN] Obs normalizer state not found; prior inputs will be unnormalized.") + return None + if mode == "rsl_rl": + normalizer = _build_rsl_obs_normalizer( + state, expected_dim, device, split_spec=split_spec + ) + if normalizer is not None: + return normalizer + print("[WARN] Falling back to simple obs normalizer.") + + def _maybe_tensor(value: object) -> torch.Tensor | None: + if value is None: + return None + tensor = torch.as_tensor(value, dtype=torch.float32, device=device) + return tensor.view(-1) + + mean = _maybe_tensor(state.get("mean") or state.get( + "running_mean") or state.get("_mean")) + var = _maybe_tensor(state.get("var") or state.get( + "running_var") or state.get("variance") or state.get("_var")) + std = _maybe_tensor(state.get("std") or state.get( + "running_std") or state.get("_std")) + if var is None and std is not None: + var = std.pow(2) + + if mean is None or var is None: + return None + + mean = _slice_norm_tensor(mean, expected_dim, split_spec) + var = _slice_norm_tensor(var, expected_dim, split_spec) + + eps, clip_value = _resolve_obs_norm_hparams(state) + return _ObsNormalizer(mean, var, eps=eps, clip=clip_value) + + +def _load_student_prior( + ckpt_path: str, + *, + policy_cfg: object, + num_actions: int, + device: torch.device, + enable_obs_norm: bool, + obs_norm_mode: str = "simple", + activation_override: str | None = None, + tanh_actions_override: bool | None = None, +) -> tuple[StudentTeacherVAE, _ObsNormalizer | None, int, int, int]: + checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False) + state_dict, checkpoint_dict = _extract_state_dict(checkpoint) + state_dict = _strip_module_prefix(state_dict) + + prior_prefix = _find_module_prefix(state_dict, "prior_net") + decoder_prefix = _find_module_prefix(state_dict, "decoder") + if prior_prefix is None or decoder_prefix is None: + raise ValueError( + f"Checkpoint '{ckpt_path}' does not contain prior/decoder weights.") + + prior_module = f"{prior_prefix}.prior_net" if prior_prefix else "prior_net" + decoder_module = f"{decoder_prefix}.decoder" if decoder_prefix else "decoder" + + policy_cfg = getattr(policy_cfg, "policy", policy_cfg) + proprio_dim = int(getattr(policy_cfg, "proprio_dim", 0) or 0) + latent_dim = int(getattr(policy_cfg, "latent_dim", 0) or 0) + if proprio_dim <= 0 or latent_dim <= 0: + raise ValueError( + "Distillation policy config must define positive proprio_dim and latent_dim.") + + activation = activation_override or getattr( + policy_cfg, "activation", "elu") + if tanh_actions_override is None: + tanh_actions = bool(getattr(policy_cfg, "tanh_actions", False)) + else: + tanh_actions = tanh_actions_override + + proprio_source_dim = int(getattr(policy_cfg, "proprio_source_dim", 0) or 0) + action_tail_dim = int(getattr(policy_cfg, "action_tail_dim", 0) or 0) + action_keep_dim = int(getattr(policy_cfg, "action_keep_dim", 0) or 0) + split_spec: tuple[int, int, int] | None = None + if proprio_source_dim > 0 and action_tail_dim > 0 and action_keep_dim > 0: + expected_split_dim = proprio_source_dim - action_tail_dim + action_keep_dim + if expected_split_dim != proprio_dim: + raise ValueError( + "Policy cfg split spec is inconsistent: " + f"proprio_source_dim({proprio_source_dim}) - action_tail_dim({action_tail_dim}) + " + f"action_keep_dim({action_keep_dim}) = {expected_split_dim}, expected proprio_dim={proprio_dim}." + ) + split_spec = (proprio_source_dim, action_tail_dim, action_keep_dim) + + policy_kwargs: dict[str, object] = {} + student_hidden_dims = tuple(getattr(policy_cfg, "student_hidden_dims", ())) + if student_hidden_dims: + policy_kwargs["student_hidden_dims"] = student_hidden_dims + noise_std_type = getattr(policy_cfg, "noise_std_type", None) + if noise_std_type is not None: + policy_kwargs["noise_std_type"] = noise_std_type + for optional_key in ("wrist_action_dim", "use_teacher_wrist", "mask_wrist_in_loss"): + if hasattr(policy_cfg, optional_key): + policy_kwargs[optional_key] = getattr(policy_cfg, optional_key) + + policy = StudentTeacherVAE( + num_student_obs=proprio_dim, + num_teacher_obs=proprio_dim, + num_actions=num_actions, + activation=activation, + init_noise_std=float(getattr(policy_cfg, "init_noise_std", 1.0)), + teacher_hidden_dims=tuple( + getattr(policy_cfg, "teacher_hidden_dims", ())), + latent_dim=latent_dim, + encoder_hidden_dims=tuple( + getattr(policy_cfg, "encoder_hidden_dims", ())), + decoder_hidden_dims=tuple( + getattr(policy_cfg, "decoder_hidden_dims", ())), + prior_hidden_dims=tuple(getattr(policy_cfg, "prior_hidden_dims", ())), + posterior_std_min=float( + getattr(policy_cfg, "posterior_std_min", 1.0e-4)), + posterior_std_max=float(getattr(policy_cfg, "posterior_std_max", 3.0)), + prior_std_min=float(getattr(policy_cfg, "prior_std_min", 1.0e-4)), + prior_std_max=float(getattr(policy_cfg, "prior_std_max", 3.0)), + latent_dropout=float(getattr(policy_cfg, "latent_dropout", 0.0)), + tanh_actions=tanh_actions, + proprio_dim=proprio_dim, + **policy_kwargs, + ) + + filtered_state: dict[str, torch.Tensor] = {} + for key, value in state_dict.items(): + if key.startswith(prior_module + "."): + filtered_state[_strip_key_prefix(key, prior_prefix)] = value + elif key.startswith(decoder_module + "."): + filtered_state[_strip_key_prefix(key, decoder_prefix)] = value + elif key.endswith("log_std"): + filtered_state[_strip_key_prefix(key, prior_prefix)] = value + + policy.load_state_dict(filtered_state, strict=False) + policy.to(device) + policy.eval() + policy.use_teacher_wrist = False + + obs_normalizer = _build_obs_normalizer( + checkpoint_dict, + proprio_dim, + device, + enable=enable_obs_norm, + mode=obs_norm_mode, + split_spec=split_spec, + ) + return policy, obs_normalizer, proprio_dim, num_actions, latent_dim + + +class _PriorPolicy: + def __init__( + self, + ckpt_path: str, + *, + policy_cfg: object, + action_dim: int, + device: torch.device, + use_obs_norm: bool, + obs_norm_mode: str = "simple", + activation_override: str | None = None, + tanh_actions_override: bool | None = None, + ): + ( + self.policy, + self.normalizer, + self.proprio_dim, + self.action_dim, + self.latent_dim, + ) = _load_student_prior( + ckpt_path, + policy_cfg=policy_cfg, + num_actions=action_dim, + device=device, + enable_obs_norm=use_obs_norm, + obs_norm_mode=obs_norm_mode, + activation_override=activation_override, + tanh_actions_override=tanh_actions_override, + ) + + @torch.no_grad() + def infer_with_delta(self, obs: torch.Tensor, latent_delta: torch.Tensor | None) -> torch.Tensor: + if self.normalizer is not None: + obs = self.normalizer(obs) + latent_mean, _ = self.policy.prior(obs) + if latent_delta is not None: + if latent_delta.shape[-1] != latent_mean.shape[-1]: + raise RuntimeError( + f"Latent residual dim mismatch: expected {latent_mean.shape[-1]}, got {latent_delta.shape[-1]}." + ) + latent_mean = latent_mean + latent_delta + actions = self.policy.decode(obs, latent_mean) + if self.policy.tanh_actions: + actions = torch.tanh(actions) + return actions + + @torch.no_grad() + def prior_mean(self, obs: torch.Tensor) -> torch.Tensor: + if self.normalizer is not None: + obs = self.normalizer(obs) + latent_mean, _ = self.policy.prior(obs) + return latent_mean + + +class ResidualLatentAction(ActionTerm): + """Residual latent action composed with frozen body/hand priors.""" + + cfg: "ResidualLatentActionCfg" + + def __init__(self, cfg: "ResidualLatentActionCfg", env): + self._action_dim = 0 + super().__init__(cfg, env) + self._env = env + self._joint_action = JointPositionAction(cfg, env) + # Expose joint action buffers for event terms that update offsets. + self._offset = self._joint_action._offset + self._joint_ids = self._joint_action._joint_ids + self._body_obs_cfg = SceneEntityCfg( + "robot", joint_names=MODE12_JOINT_ORDER, preserve_order=True) + self._hand_prior_variant = str( + getattr(cfg, "hand_prior_variant", "wuji_floating_kinematic_wrist")) + self._hand_joint_names_cfg = _normalize_hand_joint_names( + getattr(cfg, "hand_joint_names", ()), variant=self._hand_prior_variant) + self._hand_wrist_body_name = str( + getattr(cfg, "hand_wrist_body_name", "") or get_hand_prior_default_wrist_body_name( + self._hand_prior_variant) + ) + self._hand_obs_cfg = SceneEntityCfg("robot", joint_names=list( + self._hand_joint_names_cfg), preserve_order=True) + + body_joint_ids, _ = self._asset.find_joints( + MODE12_JOINT_ORDER, preserve_order=True) + hand_joint_ids, hand_joint_names = self._asset.find_joints( + list(self._hand_joint_names_cfg), preserve_order=True) + if len(hand_joint_ids) != len(self._hand_joint_names_cfg): + missing = sorted(set(self._hand_joint_names_cfg) - + set(hand_joint_names)) + raise RuntimeError( + f"Missing right-hand action joints on '{self._asset.name}': {missing}") + self._body_obs_cfg.joint_ids = list(body_joint_ids) + self._hand_obs_cfg.joint_ids = list(hand_joint_ids) + self._hand_joint_ids = torch.tensor( + hand_joint_ids, dtype=torch.long, device=self.device) + + joint_to_action = self._build_joint_to_action_index() + self._body_action_ids = joint_to_action[torch.as_tensor( + body_joint_ids, device=self.device)] + self._hand_action_ids = joint_to_action[self._hand_joint_ids] + + self._body_policy_cfg = _get_body_distill_policy_cfg( + cfg.body_prior_checkpoint) + hand_variant_spec = _get_hand_prior_variant_spec( + self._hand_prior_variant) + self._hand_policy_cfg = hand_variant_spec["policy_cfg"] + self._hand_dummy_action_dim = int( + hand_variant_spec["dummy_action_dim"]) + self._expected_hand_proprio_dim, self._expected_hand_action_dim = get_hand_prior_expected_dims( + self._hand_prior_variant, + self._hand_joint_names_cfg, + ) + + self._body_prior = self._maybe_load_prior( + cfg.body_prior_checkpoint, + cfg.body_activation, + cfg.body_tanh_actions, + cfg.body_use_obs_norm, + cfg.body_obs_norm_mode, + policy_cfg=self._body_policy_cfg, + action_dim=self._body_action_ids.numel(), + ) + if self._body_prior is not None: + self._body_prior_frame_dim = _infer_body_prior_frame_dim( + self._body_prior.proprio_dim) + self._body_prior_include_base_lin_vel = ( + self._body_prior_frame_dim == _BODY_PRIOR_FRAME_DIM_WITH_BASE_LIN_VEL + ) + else: + self._body_prior_frame_dim = 0 + self._body_prior_include_base_lin_vel = True + + self._hand_prior = self._maybe_load_prior( + cfg.hand_prior_checkpoint, + cfg.hand_activation, + cfg.hand_tanh_actions, + cfg.hand_use_obs_norm, + cfg.hand_obs_norm_mode, + policy_cfg=self._hand_policy_cfg, + action_dim=self._expected_hand_action_dim, + ) + if self._hand_prior is not None and self._hand_prior.proprio_dim != self._expected_hand_proprio_dim: + raise RuntimeError( + f"Floating active hand prior expects proprio dim {self._expected_hand_proprio_dim}, " + f"got {self._hand_prior.proprio_dim}." + ) + + if self._body_prior is not None and (self._body_action_ids < 0).any(): + raise RuntimeError( + "Residual action term could not resolve joint indices for base priors.") + if self._hand_prior is not None and (self._hand_action_ids < 0).any(): + raise RuntimeError( + "Residual action term could not resolve joint indices for base priors.") + if self._hand_prior is None: + self._hand_action_ids = torch.empty( + 0, dtype=torch.long, device=self.device) + self._hand_joint_ids = torch.empty( + 0, dtype=torch.long, device=self.device) + self._hand_obs_cfg.joint_ids = [] + + self._body_history_length = ( + self._body_prior.proprio_dim // self._body_prior_frame_dim + if self._body_prior and self._body_prior_frame_dim > 0 + else 0 + ) + + self._hand_action_alpha = max( + 0.0, min(1.0, float(getattr(cfg, "hand_action_moving_average", 1.0)))) + self._hand_prev_targets = None + self._hand_prior_last_action = None + if self._hand_action_ids.numel() > 0: + self._hand_prev_targets = torch.zeros( + (env.num_envs, self._hand_action_ids.numel()), device=self.device + ) + self._hand_prev_targets[:] = self._asset.data.joint_pos[:, + self._hand_joint_ids] + self._hand_prior_last_action = torch.zeros( + (env.num_envs, self._hand_joint_ids.numel()), device=self.device + ) + + self._body_latent_dim = self._body_prior.latent_dim if self._body_prior is not None else 0 + self._hand_latent_dim = self._hand_prior.latent_dim if self._hand_prior is not None else 0 + self._action_dim = self._body_latent_dim + self._hand_latent_dim + if self._action_dim <= 0: + raise RuntimeError( + "Residual latent action requires at least one prior checkpoint.") + + self._raw_actions = torch.zeros( + (env.num_envs, self.action_dim), device=self.device) + self._combined_action = torch.zeros( + (env.num_envs, self._joint_action.action_dim), device=self.device) + self._last_action = torch.zeros_like(self._combined_action) + self._env._locomanip_last_action = self._last_action + + def _build_joint_to_action_index(self) -> torch.Tensor: + joint_ids = getattr(self._joint_action, "_joint_ids", slice(None)) + if isinstance(joint_ids, slice): + joint_ids = torch.arange( + self._asset.num_joints, device=self.device, dtype=torch.long) + else: + joint_ids = torch.as_tensor( + joint_ids, device=self.device, dtype=torch.long) + joint_to_action = torch.full( + (self._asset.num_joints,), -1, device=self.device, dtype=torch.long) + joint_to_action[joint_ids] = torch.arange( + joint_ids.numel(), device=self.device, dtype=torch.long) + return joint_to_action + + def _maybe_load_prior( + self, + ckpt_path: str | None, + activation: str, + tanh_actions: bool, + use_obs_norm: bool, + obs_norm_mode: str, + policy_cfg: object, + action_dim: int, + ) -> _PriorPolicy | None: + if not ckpt_path: + return None + if not os.path.isfile(ckpt_path): + raise FileNotFoundError(f"Prior checkpoint not found: {ckpt_path}") + return _PriorPolicy( + ckpt_path, + policy_cfg=policy_cfg, + action_dim=action_dim, + device=self.device, + use_obs_norm=use_obs_norm, + obs_norm_mode=obs_norm_mode, + activation_override=activation, + tanh_actions_override=tanh_actions, + ) + + def _hand_targets_to_actions( + self, + hand_targets: torch.Tensor, + env_ids: torch.Tensor | None = None, + ) -> torch.Tensor: + scale = getattr(self._joint_action, "_scale", None) + offset = getattr(self._joint_action, "_offset", None) + if not isinstance(scale, torch.Tensor) or not isinstance(offset, torch.Tensor): + raise RuntimeError( + "Joint action scale/offset tensors are required to map hand targets to actions.") + if env_ids is None: + hand_scale = scale[:, self._hand_action_ids] + hand_offset = offset[:, self._hand_action_ids] + else: + hand_scale = scale[env_ids][:, self._hand_action_ids] + hand_offset = offset[env_ids][:, self._hand_action_ids] + safe_scale = torch.where( + hand_scale.abs() < 1.0e-8, torch.ones_like(hand_scale), hand_scale) + return (hand_targets - hand_offset) / safe_scale + + def _hand_actions_to_targets( + self, + hand_actions: torch.Tensor, + env_ids: torch.Tensor | None = None, + ) -> torch.Tensor: + scale = getattr(self._joint_action, "_scale", None) + offset = getattr(self._joint_action, "_offset", None) + if not isinstance(scale, torch.Tensor) or not isinstance(offset, torch.Tensor): + raise RuntimeError( + "Joint action scale/offset tensors are required to map hand actions to targets.") + if env_ids is None: + hand_scale = scale[:, self._hand_action_ids] + hand_offset = offset[:, self._hand_action_ids] + else: + hand_scale = scale[env_ids][:, self._hand_action_ids] + hand_offset = offset[env_ids][:, self._hand_action_ids] + return hand_offset + hand_scale * hand_actions + + def _decode_hand_output_to_targets(self, decoded_hand: torch.Tensor) -> torch.Tensor: + if decoded_hand.shape[-1] != self._expected_hand_action_dim: + raise RuntimeError( + "Hand prior decoded action dim mismatch: expected " + f"{self._expected_hand_action_dim}, " + f"got {decoded_hand.shape[-1]}." + ) + hand_actions = decoded_hand[:, self._hand_dummy_action_dim:] + return self._hand_actions_to_targets(hand_actions) + + def _get_body_prior_obs(self) -> torch.Tensor: + if self._body_prior is None or self._body_history_length <= 0: + return torch.zeros((self.num_envs, 0), device=self.device) + return tracking_prior_history( + self._env, + asset_cfg=self._body_obs_cfg, + noise_cfg=TRACKING_PRIOR_NOISE_CFG, + history_length=self._body_history_length, + include_base_lin_vel=self._body_prior_include_base_lin_vel, + ) + + def _get_hand_prior_obs(self) -> torch.Tensor: + if self._hand_prior is None: + return torch.zeros((self.num_envs, 0), device=self.device) + obs = right_hand_proprio( + self._env, + asset_cfg=self._hand_obs_cfg, + wrist_body_name=self._hand_wrist_body_name, + ) + return obs + + @torch.no_grad() + def get_body_prior_mean(self) -> torch.Tensor: + if self._body_prior is None: + return torch.zeros((self.num_envs, 0), device=self.device) + return self._body_prior.prior_mean(self._get_body_prior_obs()) + + @torch.no_grad() + def get_hand_prior_mean(self) -> torch.Tensor: + if self._hand_prior is None: + return torch.zeros((self.num_envs, 0), device=self.device) + return self._hand_prior.prior_mean(self._get_hand_prior_obs()) + + def _apply_hand_ema(self, hand_targets: torch.Tensor) -> torch.Tensor: + if self._hand_prev_targets is None: + return hand_targets + target = hand_targets + if self._hand_action_alpha < 1.0: + target = self._hand_action_alpha * target + \ + (1.0 - self._hand_action_alpha) * self._hand_prev_targets + limits = self._asset.data.soft_joint_pos_limits[:, + self._hand_joint_ids] + target = torch.clamp(target, limits[..., 0], limits[..., 1]) + self._hand_prev_targets[:] = target + return target + + def _compute_joint_action(self, residual_latent: torch.Tensor) -> torch.Tensor: + self._combined_action.zero_() + if self._body_prior is not None: + body_obs = self._get_body_prior_obs() + body_delta = residual_latent[:, + : self._body_latent_dim] if self._body_latent_dim > 0 else None + body_action = self._body_prior.infer_with_delta( + body_obs, body_delta) + if body_action.shape[-1] != self._body_action_ids.numel(): + raise RuntimeError( + f"Body prior action dim mismatch: expected {self._body_action_ids.numel()}, got {body_action.shape[-1]}." + ) + self._combined_action[:, self._body_action_ids] = body_action + + if self._hand_prior is not None: + hand_obs = self._get_hand_prior_obs() + hand_delta = residual_latent[:, + self._body_latent_dim: self._body_latent_dim + self._hand_latent_dim] + if self._hand_latent_dim <= 0: + hand_delta = None + hand_action = self._hand_prior.infer_with_delta( + hand_obs, hand_delta) + hand_targets = self._decode_hand_output_to_targets(hand_action) + if self._hand_action_alpha < 1.0 or self._hand_prev_targets is not None: + hand_targets = self._apply_hand_ema(hand_targets) + hand_locomanip_action = self._hand_targets_to_actions(hand_targets) + self._combined_action[:, + self._hand_action_ids] = hand_locomanip_action + if self._hand_prior_last_action is not None: + self._hand_prior_last_action[:] = hand_locomanip_action + + if self.cfg.base_scale != 1.0: + self._combined_action.mul_(float(self.cfg.base_scale)) + if self.cfg.clip_actions: + self._combined_action.clamp_( + self.cfg.clip_action_min, self.cfg.clip_action_max) + return self._combined_action + + @property + def action_dim(self) -> int: + return getattr(self, "_action_dim", 0) + + @property + def raw_actions(self) -> torch.Tensor: + return self._raw_actions + + @property + def processed_actions(self) -> torch.Tensor: + return self._joint_action.processed_actions + + def capture_rsi_aux_state(self, env_ids: torch.Tensor) -> dict[str, torch.Tensor]: + env_ids_t = torch.as_tensor( + env_ids, device=self.device, dtype=torch.long) + state = { + "raw_actions": self._raw_actions[env_ids_t].detach().clone(), + } + if self._hand_prev_targets is not None: + state["hand_prev_targets"] = self._hand_prev_targets[env_ids_t].detach().clone() + return state + + def restore_rsi_aux_state( + self, + env_ids: torch.Tensor, + *, + raw_actions: torch.Tensor | None = None, + hand_prev_targets: torch.Tensor | None = None, + ) -> None: + env_ids_t = torch.as_tensor( + env_ids, device=self.device, dtype=torch.long) + if env_ids_t.numel() == 0: + return + + if raw_actions is not None: + raw_actions_t = torch.as_tensor( + raw_actions, device=self.device, dtype=self._raw_actions.dtype) + if raw_actions_t.ndim != 2 or raw_actions_t.shape[0] != env_ids_t.numel(): + raise ValueError( + f"Expected raw_actions with shape [N, D], got {tuple(raw_actions_t.shape)} for " + f"{env_ids_t.numel()} envs." + ) + if raw_actions_t.shape[1] != self._raw_actions.shape[1]: + raise ValueError( + f"Raw action dim mismatch: expected {self._raw_actions.shape[1]}, got {raw_actions_t.shape[1]}." + ) + self._raw_actions[env_ids_t] = raw_actions_t + + if hand_prev_targets is not None and self._hand_prev_targets is not None: + hand_prev_targets_t = torch.as_tensor( + hand_prev_targets, + device=self.device, + dtype=self._hand_prev_targets.dtype, + ) + if hand_prev_targets_t.ndim != 2 or hand_prev_targets_t.shape[0] != env_ids_t.numel(): + raise ValueError( + f"Expected hand_prev_targets with shape [N, D], got {tuple(hand_prev_targets_t.shape)} for " + f"{env_ids_t.numel()} envs." + ) + if hand_prev_targets_t.shape[1] != self._hand_prev_targets.shape[1]: + raise ValueError( + "Hand previous target dim mismatch: expected " + f"{self._hand_prev_targets.shape[1]}, got {hand_prev_targets_t.shape[1]}." + ) + self._hand_prev_targets[env_ids_t] = hand_prev_targets_t + + if self._combined_action.shape == self._last_action.shape: + self._combined_action[env_ids_t] = self._last_action[env_ids_t] + + def process_actions(self, actions: torch.Tensor): + residual_latent = actions.view(self.num_envs, self.action_dim) + settle_buf = getattr(self._env, "_no_demo_rsi_settle_steps", None) + settle_mask = None + if isinstance(settle_buf, torch.Tensor): + settle_mask = settle_buf > 0 + if settle_mask.any(): + residual_latent = residual_latent.clone() + residual_latent[settle_mask] = 0.0 + settle_buf[settle_mask] = torch.clamp( + settle_buf[settle_mask] - 1, min=0) + + self._raw_actions.copy_(residual_latent) + joint_actions = self._compute_joint_action(residual_latent) + if settle_mask is not None and settle_mask.any(): + joint_actions = joint_actions.clone() + joint_actions[settle_mask] = 0.0 + self._last_action.copy_(joint_actions.detach()) + self._joint_action.process_actions(joint_actions) + + def apply_actions(self): + self._joint_action.apply_actions() + + def reset(self, env_ids=None): + super().reset(env_ids) + self._joint_action.reset(env_ids) + if env_ids is None: + env_ids_t = torch.arange( + self.num_envs, device=self.device, dtype=torch.long) + elif isinstance(env_ids, slice): + env_ids_t = torch.arange( + self.num_envs, device=self.device, dtype=torch.long)[env_ids] + else: + env_ids_t = torch.as_tensor( + env_ids, device=self.device, dtype=torch.long) + if env_ids_t.numel() == 0: + return + + self._raw_actions[env_ids_t] = 0.0 + self._combined_action[env_ids_t] = 0.0 + self._last_action[env_ids_t] = 0.0 + if hasattr(self._env, "_locomanip_last_action"): + self._env._locomanip_last_action[env_ids_t] = 0.0 + prev_joint_rate_actions = getattr( + self._env, "_locomanip_prev_joint_action_rate_action", None) + if isinstance(prev_joint_rate_actions, torch.Tensor) and prev_joint_rate_actions.shape == self._last_action.shape: + prev_joint_rate_actions[env_ids_t] = 0.0 + + if self._body_prior is not None and self._body_history_length > 0: + clear_prior_obs_step_cache(self._env) + reset_tracking_prior_history( + self._env, + asset_cfg=self._body_obs_cfg, + noise_cfg=TRACKING_PRIOR_NOISE_CFG, + history_length=self._body_history_length, + env_ids=env_ids_t, + include_base_lin_vel=self._body_prior_include_base_lin_vel, + ) + + if self._hand_prev_targets is not None: + hand_targets = self._asset.data.joint_pos[env_ids_t][:, + self._hand_joint_ids] + self._hand_prev_targets[env_ids_t] = hand_targets + + if self._hand_prior_last_action is not None: + self._hand_prior_last_action[env_ids_t] = 0.0 + + if hasattr(self._env, "_locomanip_last_action"): + self._env._locomanip_last_action[env_ids_t] = self._last_action[env_ids_t] + + +@configclass +class ResidualLatentActionCfg(JointPositionActionCfg): + class_type = ResidualLatentAction + + body_prior_checkpoint: str | None = None + hand_prior_checkpoint: str | None = None + hand_joint_names: tuple[str, ...] = tuple(WUJI_RH_ACTIVE_JOINT_NAMES) + hand_wrist_body_name: str = "right_palm_link" + hand_prior_variant: str = "wuji_floating_kinematic_wrist" + body_obs_norm_mode: str = "simple" + hand_obs_norm_mode: str = "simple" + body_activation: str = "elu" + hand_activation: str = "elu" + body_tanh_actions: bool = False + hand_tanh_actions: bool = False + body_use_obs_norm: bool = True + hand_use_obs_norm: bool = True + hand_action_moving_average: float = 1.0 + base_scale: float = 1.0 + clip_actions: bool = False + clip_action_min: float = -1.0 + clip_action_max: float = 1.0 diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/commands.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/commands.py new file mode 100644 index 0000000000000000000000000000000000000000..3a4e2562d515b58250de52d2aa3021594d55ad42 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/commands.py @@ -0,0 +1,1553 @@ +from __future__ import annotations + +from dataclasses import MISSING +import math +from typing import TYPE_CHECKING + +import torch + +from isaaclab.assets import Articulation, RigidObject +from isaaclab.managers import CommandTerm, CommandTermCfg +from isaaclab.utils import configclass +from isaaclab.utils.math import quat_apply, quat_apply_inverse, quat_error_magnitude + +from coordex.tasks.locomanip.constants import RIGHT_HAND_JOINT_PATTERNS, RIGHT_HAND_TIP_NAMES +from coordex.tasks.locomanip.mdp.rsi import ( + capture_locomanip_snapshot, + restore_locomanip_snapshot_aux_state, +) + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +class LocomanipStageCommand(CommandTerm): + """Command term that tracks a 4-stage locomotion-manipulation script.""" + + cfg: "LocomanipStageCommandCfg" + + def __init__(self, cfg: "LocomanipStageCommandCfg", env: "ManagerBasedRLEnv"): + super().__init__(cfg, env) + self._env = env + + self.robot: Articulation = env.scene[cfg.asset_name] + self.cube: RigidObject = env.scene[cfg.cube_name] + self.source_table: RigidObject = env.scene[cfg.source_table_name] + self.target_table: RigidObject | None = env.scene[ + cfg.target_table_name] if cfg.target_table_name else None + self.target_region: RigidObject | None = env.scene[ + cfg.target_region_name] if cfg.target_region_name else None + + fingertip_names = list( + cfg.fingertip_body_names or RIGHT_HAND_TIP_NAMES) + fingertip_ids, fingertip_found = self.robot.find_bodies( + fingertip_names, preserve_order=True) + if len(fingertip_ids) != len(fingertip_names): + missing = sorted(set(fingertip_names) - set(fingertip_found)) + raise RuntimeError( + f"Missing fingertip bodies on '{cfg.asset_name}': {missing}") + self.fingertip_ids = torch.tensor( + fingertip_ids, dtype=torch.long, device=self.device) + + hand_base_name = str( + getattr(cfg, "hand_base_body_name", "right_palm_link")) + hand_base_ids, hand_base_found = self.robot.find_bodies( + [hand_base_name], preserve_order=True) + if len(hand_base_ids) == 0: + raise RuntimeError( + f"Missing hand base body on '{cfg.asset_name}': {set([hand_base_name]) - set(hand_base_found)}") + self.hand_base_id = int(hand_base_ids[0]) + self._hand_base_id_tensor = torch.tensor( + [self.hand_base_id], device=self.device, dtype=torch.long) + + hand_root_names = tuple(getattr(cfg, "hand_root_body_names", ()) or ()) + if hand_root_names: + root_ids, root_found = self.robot.find_bodies( + list(hand_root_names), preserve_order=True) + if len(root_ids) != len(hand_root_names): + missing = sorted(set(hand_root_names) - set(root_found)) + raise RuntimeError( + f"Missing hand-root bodies on '{cfg.asset_name}': {missing}") + self.hand_root_ids = torch.tensor( + root_ids, dtype=torch.long, device=self.device) + else: + self.hand_root_ids = None + + hand_joint_names = list(cfg.hand_joint_names) if getattr( + cfg, "hand_joint_names", ()) else list(RIGHT_HAND_JOINT_PATTERNS) + joint_ids, joint_found = self.robot.find_joints( + hand_joint_names, preserve_order=True) + if len(joint_ids) != len(hand_joint_names): + missing = sorted(set(hand_joint_names) - set(joint_found)) + raise RuntimeError( + f"Missing right-hand joints on '{cfg.asset_name}': {missing}") + self._right_hand_joint_ids = torch.tensor( + joint_ids, dtype=torch.long, device=self.device) + + self._contact_sensor = None + self._contact_sensors: list = [] + self._contact_sensor_names: list[str] = [] + if hasattr(env.scene, "sensors"): + sensors = env.scene.sensors + names = cfg.contact_sensor_name + if isinstance(names, (list, tuple, set)): + for name in names: + if name in sensors: + self._contact_sensors.append(sensors[name]) + self._contact_sensor_names.append(name) + else: + if names in sensors: + self._contact_sensor = sensors[names] + self._contact_sensors.append(sensors[names]) + self._contact_sensor_names.append(names) + + self._table_contact_sensors: list = [] + if hasattr(env.scene, "sensors"): + for name in ("source_table_contact", "target_table_contact"): + sensor = env.scene.sensors.get(name) if isinstance( + env.scene.sensors, dict) else None + if sensor is not None: + self._table_contact_sensors.append(sensor) + + self.stage_id = torch.zeros( + self.num_envs, dtype=torch.long, device=self.device) + self.stage_one_hot = torch.zeros( + (self.num_envs, cfg.num_stages), device=self.device) + self.stage_one_hot[:, 0] = 1.0 + self._stage_steps = torch.zeros( + self.num_envs, dtype=torch.long, device=self.device) + self.actual_time_in_stage_buf = self._stage_steps + self.time_in_stage_buf = torch.zeros( + self.num_envs, dtype=torch.long, device=self.device) + self._max_stage_time = self._resolve_max_stage_time() + self._pending_stage_snapshots = torch.full( + (self.num_envs,), -1, dtype=torch.long, device=self.device) + self.cube_init_z = torch.zeros( + self.num_envs, dtype=torch.float, device=self.device) + self._forward_axis = torch.tensor([1.0, 0.0, 0.0], device=self.device) + self._hand_local_normal = torch.tensor( + getattr(cfg, "hand_palm_axis", (-1.0, 0.0, 0.0)), device=self.device) + + self._hand_prep_height_margin = 0.015 + self._hand_prep_table_top_offset = 0.025 # cube half-height + self._hand_prep_height_offset = float( + getattr(cfg, "hand_prep_height_offset", 0.125)) + self._hand_prep_xy_threshold = float( + getattr(cfg, "hand_prep_xy_threshold", 0.0)) + self._hand_open_tolerance = 0.5 + self._hand_open_fraction = 0.5 + self._hand_flat_angle_tolerance = float( + getattr(cfg, "hand_flat_angle_tolerance", 0.35)) + self._require_stage1_feet_stance = bool( + getattr(cfg, "require_stage1_feet_stance", False)) + self._foot_stagger_x_threshold = float( + getattr(cfg, "foot_stagger_x_threshold", 0.08)) + policy_obs_cfg = getattr( + getattr(env.cfg, "observations", None), "policy", None) + humanoid_prior_cfg = getattr(policy_obs_cfg, "humanoid_prior", None) + humanoid_prior_params = getattr( + humanoid_prior_cfg, "params", {}) if humanoid_prior_cfg is not None else {} + self._snapshot_history_length = max( + 1, int(humanoid_prior_params.get("history_length", 1))) + self.left_foot_id: int | None = None + self.right_foot_id: int | None = None + if self._require_stage1_feet_stance: + left_foot_name = str( + getattr(cfg, "left_foot_body_name", "left_ankle_roll_link")) + left_foot_ids, left_foot_found = self.robot.find_bodies( + [left_foot_name], preserve_order=True) + if len(left_foot_ids) == 0: + raise RuntimeError( + f"Missing left foot body on '{cfg.asset_name}': {set([left_foot_name]) - set(left_foot_found)}" + ) + right_foot_name = str( + getattr(cfg, "right_foot_body_name", "right_ankle_roll_link")) + right_foot_ids, right_foot_found = self.robot.find_bodies( + [right_foot_name], preserve_order=True) + if len(right_foot_ids) == 0: + raise RuntimeError( + f"Missing right foot body on '{cfg.asset_name}': {set([right_foot_name]) - set(right_foot_found)}" + ) + self.left_foot_id = int(left_foot_ids[0]) + self.right_foot_id = int(right_foot_ids[0]) + + self.metrics["stage_id"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["stage_time"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["actual_stage_time"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["stage_time_limit"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["distance_base_source_xy"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["distance_base_target_xy"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["distance_hand_cube"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["cube_lift_height"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["error_heading"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["error_place_pos"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["error_place_ori"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["fingertip_contact"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["foot_stagger_x"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["stage1_ready_history_frac"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["stage1_ready_history_stable"] = torch.zeros( + self.num_envs, device=self.device) + self._stage0_transition_episode_keys = ( + "approach_done", + "hand_height_ok", + "hand_xy_ok", + "hand_flat", + "hand_prepped", + "stage1_ready", + ) + self._stage0_transition_episode_flags = { + key: torch.zeros(self.num_envs, dtype=torch.bool, + device=self.device) + for key in self._stage0_transition_episode_keys + } + self._stage1_ready_history = torch.zeros( + (self.num_envs, self._snapshot_history_length), + dtype=torch.bool, + device=self.device, + ) + + @property + def command(self) -> torch.Tensor: + return self.stage_one_hot + + @property + def stage0_transition_episode_flags(self) -> dict[str, torch.Tensor]: + return self._stage0_transition_episode_flags + + @property + def recent_stage1_ready_history(self) -> torch.Tensor: + return self._stage1_ready_history + + @torch.no_grad() + def _resample_command(self, env_ids): + if len(env_ids) == 0: + return + if isinstance(env_ids, torch.Tensor): + env_ids_t = env_ids + else: + env_ids_t = torch.tensor( + env_ids, device=self.device, dtype=torch.long) + + self.reset_stage0_transition_episode_flags(env_ids_t) + self.reset_stage1_ready_history(env_ids_t) + + stage_overrides = None + override_vals = None + for attr_name in ("_demo_rsi_stage_on_reset", "_no_demo_rsi_stage_on_reset"): + candidate = getattr(self._env, attr_name, None) + if not isinstance(candidate, torch.Tensor) or candidate.numel() < env_ids_t.max().item() + 1: + continue + candidate_vals = candidate[env_ids_t] + if (candidate_vals >= 0).any(): + stage_overrides = candidate + override_vals = candidate_vals + break + + cube_height = self.cube.data.root_pos_w[env_ids_t, 2] + + if override_vals is None: + self.cube_init_z[env_ids_t] = cube_height + self._set_stage(env_ids_t, 0, force_reentry=True, + enqueue_pending=False) + return + + default_mask = override_vals <= 0 + if default_mask.any(): + env_subset = env_ids_t[default_mask] + self.cube_init_z[env_subset] = cube_height[default_mask] + self._set_stage(env_subset, 0, force_reentry=True, + enqueue_pending=False) + + target_mask = override_vals > 0 + if target_mask.any(): + env_subset = env_ids_t[target_mask] + stages = override_vals[target_mask] + for stage_val in torch.unique(stages): + env_stage = env_subset[stages == stage_val] + if env_stage.numel() == 0: + continue + self._set_stage( + env_stage, + int(stage_val.item()), + force_reentry=True, + enqueue_pending=False, + ) + + stage_overrides[env_ids_t] = -1 + restore_locomanip_snapshot_aux_state( + self._env, env_ids_t, command=self) + + @torch.no_grad() + def _update_command(self): + stage1_diag = self.stage1_transition_diagnostics() + self._accumulate_stage0_transition_episode_flags(stage1_diag) + self._update_stage1_ready_history(stage1_diag["stage1_ready"]) + grasp_ready = self.is_grasped() + lift_ready = self.is_lifted() + hand_prepped = stage1_diag["hand_prepped"] + foot_stance_ready = stage1_diag["foot_stance_ready"] + + heading_error = self.heading_error_to_target() + turn_done = heading_error < self.cfg.turn_yaw_threshold + if self.cfg.turn_distance_threshold > 0.0: + turn_done = turn_done & ( + self.base_distance_to_target_xy() < self.cfg.turn_distance_threshold) + + approach_target_done = self.base_distance_to_target_xy( + ) < self.cfg.approach_target_distance_threshold + place_done = self.is_cube_at_target() + + stage0 = self.stage_id == 0 + stage1 = self.stage_id == 1 + stage2 = self.stage_id == 2 + stage3 = self.stage_id == 3 + stage4 = self.stage_id == 4 + + table_collision = stage1_diag["table_collision"] + + to_stage1 = torch.where(stage0 & hand_prepped & + foot_stance_ready & (~table_collision))[0] + to_stage2 = torch.where(stage1 & grasp_ready & lift_ready)[0] + to_stage3 = torch.where(stage2 & turn_done)[0] + to_stage4 = torch.where(stage3 & approach_target_done & grasp_ready)[0] + hold_stage4 = torch.where(stage4 & place_done)[0] + + if to_stage1.numel() > 0: + self._set_stage(to_stage1, 1) + if to_stage2.numel() > 0: + self._set_stage(to_stage2, 2) + if to_stage3.numel() > 0: + self._set_stage(to_stage3, 3) + if to_stage4.numel() > 0: + self._set_stage(to_stage4, 4) + if hold_stage4.numel() > 0: + self._set_stage(hold_stage4, 4) + + advanced_ids = [ids for ids in ( + to_stage1, to_stage2, to_stage3, to_stage4) if ids.numel() > 0] + self._tick_stage_clocks(torch.cat(advanced_ids) + if len(advanced_ids) > 0 else None) + self._flush_pending_stage_snapshots() + + def reset_stage0_transition_episode_flags(self, env_ids: torch.Tensor) -> None: + if env_ids.numel() == 0: + return + for key in self._stage0_transition_episode_keys: + self._stage0_transition_episode_flags[key][env_ids] = False + + def reset_stage1_ready_history(self, env_ids: torch.Tensor) -> None: + if env_ids.numel() == 0: + return + self._stage1_ready_history[env_ids] = False + + def restore_stage1_ready_history(self, env_ids: torch.Tensor, history: torch.Tensor) -> None: + if env_ids.numel() == 0: + return + history_t = torch.as_tensor( + history, device=self.device, dtype=torch.bool) + if history_t.ndim != 2: + raise ValueError( + f"Expected stage1-ready history with shape [N, H], got {tuple(history_t.shape)}.") + if history_t.shape[0] != env_ids.numel(): + raise ValueError( + f"Stage1-ready history batch size ({history_t.shape[0]}) does not match env_ids ({env_ids.numel()})." + ) + if history_t.shape[1] != self._stage1_ready_history.shape[1]: + raise ValueError( + f"Stage1-ready history length ({history_t.shape[1]}) does not match configured length " + f"({self._stage1_ready_history.shape[1]})." + ) + self._stage1_ready_history[env_ids] = history_t + + def _update_stage1_ready_history(self, stage1_ready: torch.Tensor) -> None: + if self._stage1_ready_history.shape[1] <= 1: + self._stage1_ready_history[:, 0] = stage1_ready.bool() + return + self._stage1_ready_history[:, :- + 1] = self._stage1_ready_history[:, 1:].clone() + self._stage1_ready_history[:, -1] = stage1_ready.bool() + + def _stage1_ready_history_stable_mask(self, env_ids: torch.Tensor | None = None) -> torch.Tensor: + stable = self._stage1_ready_history.all(dim=-1) + if env_ids is None: + return stable + return stable[env_ids] + + def _accumulate_stage0_transition_episode_flags(self, diag: dict[str, torch.Tensor]) -> None: + stage0_mask = self.stage_id == 0 + for key in self._stage0_transition_episode_keys: + value = diag.get(key) + if isinstance(value, torch.Tensor) and value.numel() == self.num_envs: + self._stage0_transition_episode_flags[key][stage0_mask] |= value[stage0_mask].bool( + ) + + def hand_above_cube(self, height_offset: float | None = None) -> torch.Tensor: + """Require the hand to stay below the prep-height ceiling over the cube. + + Height and XY both use the mean of base + fingertips to avoid fingertip sagging tricks + and palm-only alignment shortcuts. + """ + height_offset = self._hand_prep_height_offset if height_offset is None else height_offset + hand_z = self._hand_mean_height() + cube_ref = self.cube_init_z if hasattr( + self, "cube_init_z") else self.cube.data.root_pos_w[:, 2] + upper = cube_ref + float(height_offset) + height_ok = hand_z <= upper + + if self._hand_prep_xy_threshold > 0.0: + hand_xy = self._hand_mean_xy() + cube_xy = self.cube.data.root_pos_w[:, :2] + xy_dist = torch.norm(hand_xy - cube_xy, dim=-1) + height_ok = height_ok & (xy_dist <= self._hand_prep_xy_threshold) + + return height_ok + + def is_right_hand_open(self, tolerance: float | None = None, required_fraction: float | None = None) -> torch.Tensor: + """Hand is considered open if most joints stay near their default (open) pose.""" + tolerance = self._hand_open_tolerance if tolerance is None else tolerance + required_fraction = self._hand_open_fraction if required_fraction is None else required_fraction + joint_pos = self.robot.data.joint_pos[:, self._right_hand_joint_ids] + default_pos = self.robot.data.default_joint_pos[:, + self._right_hand_joint_ids] + deviation = torch.abs(joint_pos - default_pos) + open_mask = deviation < float(tolerance) + open_fraction = open_mask.float().mean(dim=-1) + return open_fraction >= float(required_fraction) + + def hand_base_above_cube(self, margin: float = 0.0) -> torch.Tensor: + """Require hand base link to hover above the cube top.""" + hand_z = self.robot.data.body_pos_w[:, self.hand_base_id, 2] + cube_top = self.cube.data.root_pos_w[:, 2] + 0.025 # cube half-height + return hand_z > (cube_top + float(margin)) + + def is_hand_flat(self, angle_tolerance: float | None = None) -> torch.Tensor: + """Hand base link palm normal roughly aligns with world -Z (palm down).""" + angle_tolerance = self._hand_flat_angle_tolerance if angle_tolerance is None else angle_tolerance + angle = self.hand_flat_angle() + return angle < float(angle_tolerance) + + def hand_flat_angle(self) -> torch.Tensor: + """Angle between the configured palm normal and world -Z in radians.""" + hand_quat = self.robot.data.body_quat_w[:, self.hand_base_id] + world_down = torch.tensor( + [0.0, 0.0, -1.0], device=self.device).view(1, 3).expand(hand_quat.shape[0], -1) + hand_normal = quat_apply(hand_quat, self._hand_local_normal.view( + 1, 3).expand(hand_quat.shape[0], -1)) + cos_angle = torch.clamp( + (hand_normal * world_down).sum(dim=-1), -1.0, 1.0) + return torch.acos(cos_angle) + + def stage1_transition_diagnostics(self) -> dict[str, torch.Tensor]: + """Return the live stage-0 -> 1 gate terms and supporting diagnostics.""" + base_distance = self.base_distance_to_source_xy() + approach_done = base_distance < self.cfg.approach_distance_threshold + + hand_mean_z = self._hand_mean_height() + cube_ref = self.cube_init_z if hasattr( + self, "cube_init_z") else self.cube.data.root_pos_w[:, 2] + hand_height_upper = cube_ref + float(self._hand_prep_height_offset) + hand_height_ok = hand_mean_z <= hand_height_upper + + hand_xy = self._hand_mean_xy() + cube_xy = self.cube.data.root_pos_w[:, :2] + hand_xy_dist = torch.norm(hand_xy - cube_xy, dim=-1) + hand_xy_ok = torch.ones_like(hand_xy_dist, dtype=torch.bool) + if self._hand_prep_xy_threshold > 0.0: + hand_xy_ok = hand_xy_dist <= self._hand_prep_xy_threshold + + hand_above_cube = hand_height_ok & hand_xy_ok + hand_flat_angle = self.hand_flat_angle() + hand_flat = hand_flat_angle < float(self._hand_flat_angle_tolerance) + + foot_stance_ready, foot_stagger_x = self._stage1_foot_stance_state() + table_collision = self._table_collision_mask() + + hand_prepped = ( + hand_above_cube + & self.is_right_hand_open() + # & self.is_hand_flat() + ) + stage1_ready = hand_prepped & foot_stance_ready & (~table_collision) + + return { + "approach_done": approach_done, + "base_distance_source_xy": base_distance, + "hand_above_cube": hand_above_cube, + "hand_height_ok": hand_height_ok, + "hand_prepped": hand_prepped, + "hand_mean_z": hand_mean_z, + "hand_height_upper": hand_height_upper, + "hand_xy_dist": hand_xy_dist, + "hand_xy_ok": hand_xy_ok, + "hand_flat": hand_flat, + "hand_flat_angle": hand_flat_angle, + "foot_stance_ready": foot_stance_ready, + "foot_stagger_x": foot_stagger_x, + "table_collision": table_collision, + "stage1_ready": stage1_ready, + } + + def _stage1_foot_stance_state(self) -> tuple[torch.Tensor, torch.Tensor]: + if (not self._require_stage1_feet_stance) or (self.left_foot_id is None) or (self.right_foot_id is None): + zeros = torch.zeros(self.num_envs, device=self.device) + ready = torch.ones( + self.num_envs, dtype=torch.bool, device=self.device) + return ready, zeros + + base_pos = self.robot.data.root_pos_w + base_quat = self.robot.data.root_quat_w + left_rel_b = quat_apply_inverse( + base_quat, self.robot.data.body_pos_w[:, self.left_foot_id] - base_pos) + right_rel_b = quat_apply_inverse( + base_quat, self.robot.data.body_pos_w[:, self.right_foot_id] - base_pos) + stagger_x = torch.abs(left_rel_b[:, 0] - right_rel_b[:, 0]) + ready = stagger_x < self._foot_stagger_x_threshold + + return ready, stagger_x + + def is_stage1_foot_stance_ready(self) -> torch.Tensor: + """Require the feet to avoid a large fore-aft stagger in the robot base frame.""" + ready, _ = self._stage1_foot_stance_state() + return ready + + def _hand_mean_height(self) -> torch.Tensor: + """Mean height of hand base and fingertips.""" + all_ids = torch.cat( + [self._hand_base_id_tensor, self.fingertip_ids.to(self.device)], dim=0) + z_vals = self.robot.data.body_pos_w[:, all_ids, 2] + return z_vals.mean(dim=1) + + def _hand_mean_xy(self) -> torch.Tensor: + """Mean XY position of hand base and fingertips.""" + all_ids = torch.cat( + [self._hand_base_id_tensor, self.fingertip_ids.to(self.device)], dim=0) + xy_vals = self.robot.data.body_pos_w[:, all_ids, :2] + return xy_vals.mean(dim=1) + + def _flush_pending_stage_snapshots(self) -> None: + pending = getattr(self, "_pending_stage_snapshots", None) + if not isinstance(pending, torch.Tensor) or pending.numel() != self.num_envs: + return + + pending_mask = pending >= 1 + if not pending_mask.any(): + return + + # Drop stale requests when the stage changes before we capture. + same_stage = self.stage_id == pending + stale_mask = pending_mask & (~same_stage) + if stale_mask.any(): + pending[stale_mask] = -1 + pending_mask = pending >= 1 + if not pending_mask.any(): + return + + # Iterate over the fixed set of possible stage values instead of using + # torch.unique() + .item(), which forces GPU→CPU syncs on every call. + num_stages = int(getattr(self.cfg, "num_stages", 5)) + for stage_val in range(1, num_stages): + env_mask = pending_mask & (pending == stage_val) + if not env_mask.any(): + continue + env_ids = torch.where(env_mask)[0] + stored = self._maybe_store_stage_snapshots(env_ids, stage_val) + if isinstance(stored, torch.Tensor) and stored.numel() > 0: + pending[stored] = -1 + + def _update_metrics(self): + self.metrics["stage_id"] = self.stage_id.float() + self.metrics["stage_time"] = self.time_in_stage_buf.float() + self.metrics["actual_stage_time"] = self.actual_time_in_stage_buf.float() + self.metrics["stage_time_limit"] = self.max_stage_time_for_current_stage( + ).float() + self.metrics["distance_base_source_xy"] = self.base_distance_to_source_xy() + self.metrics["distance_base_target_xy"] = self.base_distance_to_target_xy() + self.metrics["distance_hand_cube"] = self.hand_cube_distance() + self.metrics["cube_lift_height"] = self.cube.data.root_pos_w[:, + 2] - self.cube_init_z + self.metrics["error_heading"] = self.heading_error_to_target() + + if self.target_region is not None: + cube_pos = self.cube.data.root_pos_w + target_pos = self.target_region.data.root_pos_w + self.metrics["error_place_pos"] = torch.norm( + cube_pos - target_pos, dim=-1) + + cube_quat = self.cube.data.root_quat_w + target_quat = self.target_region.data.root_quat_w + self.metrics["error_place_ori"] = quat_error_magnitude( + cube_quat, target_quat) + else: + self.metrics["error_place_pos"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["error_place_ori"] = torch.zeros( + self.num_envs, device=self.device) + + contact = self.fingertip_contact() + if contact is None: + self.metrics["fingertip_contact"] = torch.zeros( + self.num_envs, device=self.device) + else: + self.metrics["fingertip_contact"] = contact.float() + + _, foot_stagger_x = self._stage1_foot_stance_state() + self.metrics["foot_stagger_x"] = foot_stagger_x + self.metrics["stage1_ready_history_frac"] = self._stage1_ready_history.float( + ).mean(dim=-1) + self.metrics["stage1_ready_history_stable"] = self._stage1_ready_history.all( + dim=-1).float() + + def _table_collision_mask(self) -> torch.Tensor: + """Detect significant contact on source/target tables to gate stage transition.""" + if len(self._table_contact_sensors) == 0: + return torch.zeros(self.num_envs, device=self.device, dtype=torch.bool) + collision = torch.zeros( + self.num_envs, device=self.device, dtype=torch.bool) + for sensor in self._table_contact_sensors: + forces = getattr(sensor.data, "force_matrix_w_history", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w_history", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w", None) + if isinstance(forces, torch.Tensor): + threshold = float( + getattr(getattr(sensor, "cfg", None), "force_threshold", 10.0)) + contact = forces.norm(dim=-1) > threshold + contact = contact.view(contact.shape[0], -1).any(dim=-1) + collision = collision | contact + return collision + + def _maybe_store_stage_snapshots(self, env_ids: torch.Tensor, stage: int) -> torch.Tensor: + if stage <= 0: + return torch.zeros((0,), device=self.device, dtype=torch.long) + env = getattr(self, "_env", None) + if env is None: + return torch.zeros((0,), device=self.device, dtype=torch.long) + reset_cfg = getattr(env.cfg, "events", None) + params_cfg = getattr(reset_cfg, "reset_scene", None) + params_dict = getattr(params_cfg, "params", {}) if params_cfg else {} + rsi_cfg = params_dict.get("rsi_cfg") + if not (rsi_cfg and getattr(rsi_cfg, "enabled", False)): + return torch.zeros((0,), device=self.device, dtype=torch.long) + buffer = getattr(env, "_no_demo_rsi_buffer", None) + if buffer is None: + return torch.zeros((0,), device=self.device, dtype=torch.long) + + env_ids_t = env_ids if isinstance(env_ids, torch.Tensor) else torch.as_tensor( + env_ids, device=self.device, dtype=torch.long) + env_ids_t = env_ids_t.to(device=self.device, dtype=torch.long) + if env_ids_t.numel() == 0: + return env_ids_t + + term_cfg = getattr(env.cfg, "terminations", None) + params_rf = getattr(getattr(term_cfg, "robot_fall", + None), "params", {}) if term_cfg else {} + min_height = float(params_rf.get("min_height", 0.0)) + heights = self.robot.data.root_pos_w[env_ids_t, 2] + keep = heights >= min_height + + stage_steps = getattr(self, "_stage_steps", None) + min_stage_steps_cfg = getattr( + rsi_cfg, "min_stage_steps_before_store", 0) + min_stage_steps = 0 + if isinstance(min_stage_steps_cfg, (list, tuple)) and len(min_stage_steps_cfg) > 0: + min_stage_steps = int( + min_stage_steps_cfg[min(stage, len(min_stage_steps_cfg) - 1)]) + elif isinstance(min_stage_steps_cfg, torch.Tensor) and min_stage_steps_cfg.numel() > 0: + min_stage_steps = int(min_stage_steps_cfg[min( + stage, min_stage_steps_cfg.numel() - 1)].item()) + else: + try: + min_stage_steps = int(min_stage_steps_cfg) + except (TypeError, ValueError): + min_stage_steps = 0 + if stage_steps is not None and min_stage_steps > 0: + steps_here = stage_steps[env_ids_t] + keep = keep & (steps_here >= min_stage_steps) + + if stage == 1 and self._stage1_ready_history.shape[1] > 0: + keep = keep & self._stage1_ready_history_stable_mask(env_ids_t) + + # velocity-based filtering using RSI config + max_root_lin = float(getattr(rsi_cfg, "max_root_lin_vel", 0.0)) if getattr( + rsi_cfg, "max_root_lin_vel", None) is not None else None + max_root_ang = float(getattr(rsi_cfg, "max_root_ang_vel", 0.0)) if getattr( + rsi_cfg, "max_root_ang_vel", None) is not None else None + max_joint_vel = float(getattr(rsi_cfg, "max_joint_vel", 0.0)) if getattr( + rsi_cfg, "max_joint_vel", None) is not None else None + max_cube_lin = float(getattr(rsi_cfg, "max_cube_lin_vel", 0.0)) if getattr( + rsi_cfg, "max_cube_lin_vel", None) is not None else None + max_cube_ang = float(getattr(rsi_cfg, "max_cube_ang_vel", 0.0)) if getattr( + rsi_cfg, "max_cube_ang_vel", None) is not None else None + + if max_root_lin is not None: + root_lin = torch.norm( + self.robot.data.root_lin_vel_w[env_ids_t], dim=-1) + keep = keep & (root_lin <= max_root_lin) + if max_root_ang is not None: + root_ang = torch.norm( + self.robot.data.root_ang_vel_w[env_ids_t], dim=-1) + keep = keep & (root_ang <= max_root_ang) + if max_joint_vel is not None: + joint_vel = torch.norm( + self.robot.data.joint_vel[env_ids_t], dim=-1) + keep = keep & (joint_vel <= max_joint_vel) + if max_cube_lin is not None: + cube_lin = torch.norm( + self.cube.data.root_lin_vel_w[env_ids_t], dim=-1) + keep = keep & (cube_lin <= max_cube_lin) + if max_cube_ang is not None: + cube_ang = torch.norm( + self.cube.data.root_ang_vel_w[env_ids_t], dim=-1) + keep = keep & (cube_ang <= max_cube_ang) + + if stage >= 2: + params_drop = getattr( + getattr(term_cfg, "cube_dropped", None), "params", {}) if term_cfg else {} + drop_height = float(params_drop.get("drop_height", 0.0)) + cube_z = self.cube.data.root_pos_w[env_ids_t, 2] + init_z = self.cube_init_z[env_ids_t] + keep = keep & (cube_z >= (init_z - drop_height)) + + if not keep.any(): + return torch.zeros((0,), device=self.device, dtype=torch.long) + + env_valid = env_ids_t[keep] + snapshot = capture_locomanip_snapshot( + env, env_valid, command_name=getattr(self, "name", "stage")) + if snapshot is None or snapshot.numel() == 0: + return torch.zeros((0,), device=self.device, dtype=torch.long) + buffer.add(stage, env_valid, snapshot) + return env_valid + + def _resolve_max_stage_time(self) -> torch.Tensor | None: + max_stage_time = tuple(getattr(self.cfg, "max_stage_time", ()) or ()) + if len(max_stage_time) == 0: + return None + if len(max_stage_time) != int(self.cfg.num_stages): + raise ValueError( + f"max_stage_time length ({len(max_stage_time)}) must match num_stages ({self.cfg.num_stages})." + ) + max_stage_time_t = torch.as_tensor( + max_stage_time, dtype=torch.long, device=self.device) + if torch.any(max_stage_time_t <= 0): + raise ValueError( + "max_stage_time entries must all be greater than 0 env steps.") + return max_stage_time_t + + def _tick_stage_clocks(self, advanced_env_ids: torch.Tensor | None = None) -> None: + tick_mask = torch.ones( + self.num_envs, dtype=torch.bool, device=self.device) + if isinstance(advanced_env_ids, torch.Tensor) and advanced_env_ids.numel() > 0: + tick_mask[advanced_env_ids.to( + device=self.device, dtype=torch.long)] = False + if tick_mask.any(): + self._stage_steps[tick_mask] += 1 + self.time_in_stage_buf[tick_mask] += 1 + + def max_stage_time_for_current_stage(self) -> torch.Tensor: + if self._max_stage_time is None: + return torch.zeros(self.num_envs, dtype=torch.long, device=self.device) + stage_idx = self.stage_id.clamp( + min=0, max=self._max_stage_time.numel() - 1) + return self._max_stage_time[stage_idx] + + def _set_stage( + self, + env_ids: torch.Tensor, + stage: int, + force_reentry: bool | torch.Tensor = False, + enqueue_pending: bool = True, + ) -> None: + if env_ids.numel() == 0: + return + stage = int(stage) + current_stage = self.stage_id[env_ids] + stage_steps = getattr(self, "_stage_steps", None) + pending = getattr(self, "_pending_stage_snapshots", None) + + force_reentry_mask = torch.zeros( + env_ids.shape[0], device=self.device, dtype=torch.bool) + if isinstance(force_reentry, torch.Tensor): + force_reentry_mask = force_reentry.to( + device=self.device, dtype=torch.bool) + if force_reentry_mask.ndim == 0: + force_reentry_mask = force_reentry_mask.expand( + env_ids.shape[0]) + elif force_reentry_mask.shape[0] != env_ids.shape[0]: + raise ValueError( + "force_reentry tensor must be scalar or match env_ids batch size." + ) + change_mask = (current_stage != stage) | force_reentry_mask + elif force_reentry: + # Scalar True: every env in the batch counts as a reentry. + force_reentry_mask = torch.ones( + env_ids.shape[0], device=self.device, dtype=torch.bool) + change_mask = torch.ones( + env_ids.shape[0], device=self.device, dtype=torch.bool) + else: + # Scalar False (the common path from _update_command): no allocation. + change_mask = current_stage != stage + if not change_mask.any(): + return + + env_changed = env_ids[change_mask] + previous_stage = current_stage[change_mask] + previous_time = self.time_in_stage_buf[env_changed].clone() + changed_force_reentry = force_reentry_mask[change_mask] + self.stage_id[env_changed] = stage + self.stage_one_hot[env_changed] = 0.0 + self.stage_one_hot[env_changed, stage] = 1.0 + if stage_steps is not None: + stage_steps[env_changed] = 0 + new_time = torch.zeros( + env_changed.shape[0], dtype=torch.long, device=self.device) + carry_time = ( + self._max_stage_time is not None + and bool(getattr(self.cfg, "award_remaining_time_on_advance", False)) + ) + if carry_time: + advance_mask = (previous_stage >= 0) & ( + stage > previous_stage) & (~changed_force_reentry) + if advance_mask.any(): + previous_stage_idx = previous_stage[advance_mask].clamp( + min=0, max=self._max_stage_time.numel() - 1) + new_time[advance_mask] = previous_time[advance_mask] - \ + self._max_stage_time[previous_stage_idx] + self.time_in_stage_buf[env_changed] = new_time + if isinstance(pending, torch.Tensor): + if stage <= 0 or not enqueue_pending: + pending[env_changed] = -1 + else: + pending[env_changed] = stage + + def _resolve_goal_pos(self, name: str) -> torch.Tensor: + name = name.lower() + if name in ("cube", "bottle"): + return self.cube.data.root_pos_w + if name == "table": + return self.source_table.data.root_pos_w + if name == "target_table": + if self.target_table is None: + raise ValueError( + "No target_table asset is configured for this command.") + return self.target_table.data.root_pos_w + if name == "target_region": + if self.target_region is None: + raise ValueError( + "No target_region asset is configured for this command.") + return self.target_region.data.root_pos_w + raise ValueError(f"Unknown goal name '{name}'.") + + def base_distance_to_source_xy(self) -> torch.Tensor: + target_pos = self._resolve_goal_pos(self.cfg.source_goal_name) + base_pos = self.robot.data.root_pos_w + delta = base_pos[:, :2] - target_pos[:, :2] + return torch.norm(delta, dim=-1) + + def base_distance_to_target_xy(self) -> torch.Tensor: + target_pos = self._resolve_goal_pos(self.cfg.target_goal_name) + base_pos = self.robot.data.root_pos_w + delta = base_pos[:, :2] - target_pos[:, :2] + return torch.norm(delta, dim=-1) + + def heading_error_to_goal(self, goal_name: str) -> torch.Tensor: + target_pos = self._resolve_goal_pos(goal_name) + base_pos = self.robot.data.root_pos_w + base_quat = self.robot.data.root_quat_w + if target_pos.dim() == 1: + target_pos = target_pos.unsqueeze(0) + if base_pos.dim() == 1: + base_pos = base_pos.unsqueeze(0) + if base_quat.dim() == 1: + base_quat = base_quat.unsqueeze(0) + forward_axis = self._forward_axis + if forward_axis.dim() == 1: + forward_axis = forward_axis.view(1, 3) + forward_axis = forward_axis.expand(base_quat.shape[0], -1) + forward = quat_apply(base_quat, forward_axis) + if forward.dim() == 1: + forward = forward.unsqueeze(0) + forward_xy = forward[:, :2] + target_dir = target_pos[:, :2] - base_pos[:, :2] + forward_xy = forward_xy / \ + (forward_xy.norm(dim=-1, keepdim=True) + 1.0e-6) + target_dir = target_dir / \ + (target_dir.norm(dim=-1, keepdim=True) + 1.0e-6) + cos_heading = torch.sum(forward_xy * target_dir, + dim=-1).clamp(-1.0, 1.0) + return torch.acos(cos_heading) + + def heading_error_to_target(self) -> torch.Tensor: + return self.heading_error_to_goal(self.cfg.target_goal_name) + + def hand_cube_distance(self) -> torch.Tensor: + cube_pos = self.cube.data.root_pos_w[:, None, :] + tip_pos = self.robot.data.body_pos_w[:, self.fingertip_ids] + dist = torch.norm(tip_pos - cube_pos, dim=-1) + return dist.min(dim=-1).values + + def fingertip_contact(self) -> torch.Tensor | None: + if len(self._contact_sensors) == 0: + return None + contacts = [] + for sensor in self._contact_sensors: + forces = getattr(sensor.data, "force_matrix_w", None) + if forces is None: + forces = getattr(sensor.data, "force_matrix_w_history", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w", None) + if isinstance(forces, torch.Tensor): + forces = torch.nan_to_num( + forces, nan=0.0, posinf=0.0, neginf=0.0) + magnitudes = forces.norm(dim=-1) + # Collapse any body/history dimensions: one bool per env per sensor. + magnitudes_flat = magnitudes.view(magnitudes.shape[0], -1) + contact = (magnitudes_flat > + self.cfg.contact_force_threshold).any(dim=-1) + contacts.append(contact) + if len(contacts) == 0: + return None + contact_count = contacts[0].int() + for c in contacts[1:]: + contact_count = contact_count + c.int() + min_required = int(getattr(self.cfg, "min_fingertip_contacts", 1)) + passed_count = contact_count >= min_required + + required_names = getattr(self.cfg, "required_contact_sensors", ()) + for required_name in required_names: + if required_name in self._contact_sensor_names: + idx = self._contact_sensor_names.index(required_name) + passed_count = passed_count & contacts[idx] + return passed_count + + def is_grasped(self) -> torch.Tensor: + dist_ok = self.hand_cube_distance() < self.cfg.grasp_distance_threshold + if not self.cfg.require_contact: + return dist_ok + contact = self.fingertip_contact() + if contact is None: + return dist_ok + return dist_ok & contact + + def is_lifted(self) -> torch.Tensor: + cube_z = self.cube.data.root_pos_w[:, 2] + return cube_z > (self.cube_init_z + self.cfg.lift_height) + + def is_cube_at_target(self) -> torch.Tensor: + cube_pos = self.cube.data.root_pos_w + target_pos = self.target_region.data.root_pos_w + pos_err = torch.norm(cube_pos - target_pos, dim=-1) + cube_quat = self.cube.data.root_quat_w + target_quat = self.target_region.data.root_quat_w + ori_err = quat_error_magnitude(cube_quat, target_quat) + return (pos_err < self.cfg.place_pos_threshold) & (ori_err < self.cfg.place_ori_threshold) + + +@configclass +class LocomanipStageCommandCfg(CommandTermCfg): + class_type: type = LocomanipStageCommand + + asset_name: str = MISSING + resampling_time_range: tuple[float, float] = (1.0e9, 1.0e9) + cube_name: str = "cube" + source_table_name: str = "table" + target_table_name: str = "target_table" + target_region_name: str = "target_region" + + contact_sensor_name: str | tuple[str, ...] = () + fingertip_body_names: tuple[str, ...] = tuple(RIGHT_HAND_TIP_NAMES) + + hand_root_body_names: tuple[str, ...] = () + hand_base_body_name: str = "right_palm_link" + hand_joint_names: tuple[str, ...] = () + hand_palm_axis: tuple[float, float, float] = (1.0, 0.0, 0.0) + hand_prep_xy_threshold: float = 0.0 + hand_flat_angle_tolerance: float = 0.35 + require_stage1_feet_stance: bool = False + left_foot_body_name: str = "left_ankle_roll_link" + right_foot_body_name: str = "right_ankle_roll_link" + foot_stagger_x_threshold: float = 0.08 + contact_force_threshold: float = 1.0 + min_fingertip_contacts: int = 1 + required_contact_sensors: tuple[str, ...] = () + require_contact: bool = False + + num_stages: int = 5 + max_stage_time: tuple[int, ...] = () + award_remaining_time_on_advance: bool = False + reset_on_overtime: bool = True + source_goal_name: str = "cube" + target_goal_name: str = "target_table" + + approach_distance_threshold: float = 0.5 + approach_target_distance_threshold: float = 0.5 + grasp_distance_threshold: float = 0.08 + grasp_root_distance_threshold: float | None = None + lift_height: float = 0.1 + hand_prep_height_offset: float = 0.125 + turn_yaw_threshold: float = 0.4 + turn_distance_threshold: float = 0.0 + place_pos_threshold: float = 0.06 + place_ori_threshold: float = 0.35 + + +class WalkPickTurnStageCommand(LocomanipStageCommand): + cfg: "WalkPickTurnStageCommandCfg" + + def __init__(self, cfg: "WalkPickTurnStageCommandCfg", env: "ManagerBasedRLEnv"): + super().__init__(cfg, env) + self._turn_entry_yaw = self._current_yaw() + + def _current_yaw(self) -> torch.Tensor: + forward = quat_apply(self.robot.data.root_quat_w, + self._forward_axis.expand(self.num_envs, -1)) + return torch.atan2(forward[:, 1], forward[:, 0]) + + def _turn_delta(self) -> torch.Tensor: + delta = self._current_yaw() - self._turn_entry_yaw + return torch.atan2(torch.sin(delta), torch.cos(delta)) + + def _turn_done(self) -> torch.Tensor: + return torch.abs(self._turn_delta()) >= (math.pi - float(self.cfg.turn_yaw_threshold)) + + def _set_stage( + self, + env_ids: torch.Tensor, + stage: int, + force_reentry: bool | torch.Tensor = False, + enqueue_pending: bool = True, + ) -> None: + super()._set_stage(env_ids, stage, force_reentry=force_reentry, + enqueue_pending=enqueue_pending) + if int(stage) == 2 and env_ids.numel() > 0: + self._turn_entry_yaw[env_ids.to(device=self.device, dtype=torch.long)] = self._current_yaw()[ + env_ids.to(device=self.device, dtype=torch.long) + ] + + def _resample_command(self, env_ids): + super()._resample_command(env_ids) + env_ids_t = torch.as_tensor( + env_ids, device=self.device, dtype=torch.long) + if env_ids_t.numel() > 0: + self._turn_entry_yaw[env_ids_t] = self._current_yaw()[env_ids_t] + + def _update_command(self): + stage1_diag = self.stage1_transition_diagnostics() + self._accumulate_stage0_transition_episode_flags(stage1_diag) + self._update_stage1_ready_history(stage1_diag["stage1_ready"]) + + stage0 = self.stage_id == 0 + stage1 = self.stage_id == 1 + table_collision = stage1_diag["table_collision"] + to_stage1 = torch.where( + stage0 & stage1_diag["hand_prepped"] & stage1_diag["foot_stance_ready"] & ( + ~table_collision) + )[0] + to_stage2 = torch.where( + stage1 & self.is_grasped() & self.is_lifted())[0] + + if to_stage1.numel() > 0: + self._set_stage(to_stage1, 1) + if to_stage2.numel() > 0: + self._set_stage(to_stage2, 2) + + advanced_ids = [ids for ids in ( + to_stage1, to_stage2) if ids.numel() > 0] + self._tick_stage_clocks(torch.cat(advanced_ids) + if len(advanced_ids) > 0 else None) + self._flush_pending_stage_snapshots() + + def is_success(self) -> torch.Tensor: + return (self.stage_id == 2) & self.is_grasped() & self.is_lifted() & self._turn_done() + + def _update_metrics(self): + self.metrics["stage_id"] = self.stage_id.float() + self.metrics["stage_time"] = self.time_in_stage_buf.float() + self.metrics["actual_stage_time"] = self.actual_time_in_stage_buf.float() + self.metrics["stage_time_limit"] = self.max_stage_time_for_current_stage( + ).float() + self.metrics["distance_base_source_xy"] = self.base_distance_to_source_xy() + self.metrics["distance_hand_cube"] = self.hand_cube_distance() + self.metrics["cube_lift_height"] = self.cube.data.root_pos_w[:, + 2] - self.cube_init_z + self.metrics["turn_delta_abs"] = torch.abs(self._turn_delta()) + self.metrics["walkpickturn_success"] = self.is_success().float() + contact = self.fingertip_contact() + self.metrics["fingertip_contact"] = ( + torch.zeros( + self.num_envs, device=self.device) if contact is None else contact.float() + ) + _, foot_stagger_x = self._stage1_foot_stance_state() + self.metrics["foot_stagger_x"] = foot_stagger_x + self.metrics["stage1_ready_history_frac"] = self._stage1_ready_history.float( + ).mean(dim=-1) + self.metrics["stage1_ready_history_stable"] = self._stage1_ready_history.all( + dim=-1).float() + + +@configclass +class WalkPickTurnStageCommandCfg(LocomanipStageCommandCfg): + class_type: type = WalkPickTurnStageCommand + + num_stages: int = 5 + target_table_name: str | None = None + target_region_name: str | None = None + target_goal_name: str = "table" + turn_yaw_threshold: float = 0.4 + + +class WalkgrabStageCommand(LocomanipStageCommand): + """Single-stage walk-grab-carry command.""" + + cfg: "WalkgrabStageCommandCfg" + + def __init__(self, cfg: "WalkgrabStageCommandCfg", env: "ManagerBasedRLEnv"): + super().__init__(cfg, env) + self._success_root_x_threshold = float( + getattr(cfg, "success_root_x_threshold", 2.0)) + self._success_lift_threshold = float( + getattr(cfg, "success_lift_threshold", 0.02)) + + self.metrics["walkgrab_success"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["walkgrab_root_x"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["stage_fingertip_bottle_mean_distance"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["stage_bottle_lift_height"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["right_arm_qpos_tracking_error"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["right_hand_qpos_tracking_error"] = torch.zeros( + self.num_envs, device=self.device) + + @torch.no_grad() + def _update_command(self): + self._tick_stage_clocks() + self._flush_pending_stage_snapshots() + + def fingertip_mean_distance_to_cube(self) -> torch.Tensor: + cube_pos = self.cube.data.root_pos_w[:, None, :] + tip_pos = self.robot.data.body_pos_w[:, self.fingertip_ids] + dist = torch.norm(tip_pos - cube_pos, dim=-1) + return dist.mean(dim=-1) + + def hand_root_mean_distance_to_cube(self) -> torch.Tensor | None: + """Mean distance to cube over the finger-proximal + palm bodies. + + Returns None when ``hand_root_body_names`` was not configured. Used by + ``is_grasped`` as a curl-invariant cross-check (and by the + ``right_hand_others_open`` gate) so the policy can't fake a grasp by + curling its fingertips into the bottle while keeping the palm far + away. + """ + if self.hand_root_ids is None: + return None + cube_pos = self.cube.data.root_pos_w[:, None, :] + root_pos = self.robot.data.body_pos_w[:, self.hand_root_ids] + dist = torch.norm(root_pos - cube_pos, dim=-1) + return dist.mean(dim=-1) + + def is_grasped(self) -> torch.Tensor: + dist_ok = self.fingertip_mean_distance_to_cube() < self.cfg.grasp_distance_threshold + + root_thr = getattr(self.cfg, "grasp_root_distance_threshold", None) + root_dist = self.hand_root_mean_distance_to_cube() if root_thr is not None else None + if root_dist is not None: + dist_ok = dist_ok & (root_dist < float(root_thr)) + + if not self.cfg.require_contact: + return dist_ok + contact = self.fingertip_contact() + if contact is None: + return dist_ok + return dist_ok & contact + + def root_x_from_initial(self) -> torch.Tensor: + root_x = self.robot.data.root_pos_w[:, + 0] - self._env.scene.env_origins[:, 0] + return root_x - self.robot.data.default_root_state[:, 0] + + def is_success_condition(self) -> torch.Tensor: + bottle_lift = self.cube.data.root_pos_w[:, 2] - self.cube_init_z + return ( + (self.root_x_from_initial() > self._success_root_x_threshold) + & self.is_grasped() + & (bottle_lift > self._success_lift_threshold) + ) + + def bottle_upright_angle(self) -> torch.Tensor: + bottle_axis = torch.tensor( + [0.0, 0.0, 1.0], device=self.device).view(1, 3) + world_axis = quat_apply( + self.cube.data.root_quat_w, bottle_axis.expand(self.num_envs, -1)) + cos_angle = world_axis[:, 2].clamp(-1.0, 1.0) + return torch.acos(cos_angle) + + def is_cube_at_target(self) -> torch.Tensor: + return self.is_success_condition() + + def is_success(self) -> torch.Tensor: + return self.is_success_condition() + + def _update_metrics(self): + super()._update_metrics() + bottle_lift = self.cube.data.root_pos_w[:, 2] - self.cube_init_z + self.metrics["walkgrab_success"] = self.is_success().float() + self.metrics["walkgrab_root_x"] = self.root_x_from_initial() + self.metrics["stage_fingertip_bottle_mean_distance"] = self.fingertip_mean_distance_to_cube() + self.metrics["stage_bottle_lift_height"] = bottle_lift + + +@configclass +class WalkgrabStageCommandCfg(LocomanipStageCommandCfg): + class_type: type = WalkgrabStageCommand + + cube_name: str = "bottle" + target_table_name: str | None = None + target_region_name: str | None = None + num_stages: int = 1 + max_stage_time: tuple[int, ...] = () + award_remaining_time_on_advance: bool = False + reset_on_overtime: bool = False + source_goal_name: str = "bottle" + target_goal_name: str = "bottle" + approach_target_distance_threshold: float = 0.45 + grasp_distance_threshold: float = 0.4 + lift_height: float = 0.08 + require_contact: bool = True + success_root_x_threshold: float = 2.0 + success_lift_threshold: float = 0.02 + + +class FridgeStageCommand(CommandTerm): + """Single-stage command for opening a fridge door.""" + + cfg: "FridgeStageCommandCfg" + + def __init__(self, cfg: "FridgeStageCommandCfg", env: "ManagerBasedRLEnv"): + super().__init__(cfg, env) + self._env = env + + self.robot: Articulation = env.scene[cfg.asset_name] + self.fridge: Articulation = env.scene[cfg.fridge_name] + + fingertip_names = list( + cfg.fingertip_body_names or RIGHT_HAND_TIP_NAMES) + fingertip_ids, fingertip_found = self.robot.find_bodies( + fingertip_names, preserve_order=True) + if len(fingertip_ids) != len(fingertip_names): + missing = sorted(set(fingertip_names) - set(fingertip_found)) + raise RuntimeError( + f"Missing fingertip bodies on '{cfg.asset_name}': {missing}") + self.fingertip_ids = torch.as_tensor( + fingertip_ids, dtype=torch.long, device=self.device) + + hand_base_ids, hand_base_found = self.robot.find_bodies( + [cfg.hand_base_body_name], preserve_order=True) + if len(hand_base_ids) == 0: + raise RuntimeError( + f"Missing hand base body on '{cfg.asset_name}': {set([cfg.hand_base_body_name]) - set(hand_base_found)}" + ) + self.hand_base_id = int(hand_base_ids[0]) + + door_ids, door_found = self.fridge.find_bodies( + [cfg.door_body_name], preserve_order=True) + if len(door_ids) == 0: + raise RuntimeError( + f"Missing door body on '{cfg.fridge_name}': {set([cfg.door_body_name]) - set(door_found)}" + ) + self.door_body_id = int(door_ids[0]) + + handle_reference_body_name = getattr( + cfg, "handle_reference_body_name", None) or cfg.door_body_name + handle_reference_ids, handle_reference_found = self.fridge.find_bodies( + [handle_reference_body_name], preserve_order=True + ) + if len(handle_reference_ids) == 0: + raise RuntimeError( + f"Missing handle reference body on '{cfg.fridge_name}': " + f"{set([handle_reference_body_name]) - set(handle_reference_found)}" + ) + self.handle_reference_body_id = int(handle_reference_ids[0]) + self._handle_local_pos = torch.tensor( + cfg.handle_local_pos, dtype=torch.float, device=self.device).view(1, 3) + + joint_ids, joint_found = self.fridge.find_joints( + [cfg.door_joint_name], preserve_order=True) + if len(joint_ids) == 0: + raise RuntimeError( + f"Missing door joint on '{cfg.fridge_name}': {set([cfg.door_joint_name]) - set(joint_found)}" + ) + self.door_joint_id = int(joint_ids[0]) + + self._contact_sensors: list = [] + self._contact_sensor_names: list[str] = [] + if hasattr(env.scene, "sensors"): + sensors = env.scene.sensors + names = cfg.contact_sensor_name + if isinstance(names, (list, tuple, set)): + for name in names: + if name in sensors: + self._contact_sensors.append(sensors[name]) + self._contact_sensor_names.append(name) + elif names in sensors: + self._contact_sensors.append(sensors[names]) + self._contact_sensor_names.append(names) + + self.stage_id = torch.zeros( + self.num_envs, dtype=torch.long, device=self.device) + self.stage_one_hot = torch.zeros( + (self.num_envs, 1), device=self.device) + self.stage_one_hot[:, 0] = 1.0 + self._stage_steps = torch.zeros( + self.num_envs, dtype=torch.long, device=self.device) + self._door_initial_pos = torch.zeros( + self.num_envs, dtype=torch.float, device=self.device) + self._prev_door_angle = torch.zeros( + self.num_envs, dtype=torch.float, device=self.device) + self._door_angle_progress = torch.zeros( + self.num_envs, dtype=torch.float, device=self.device) + self._door_angle_regression = torch.zeros( + self.num_envs, dtype=torch.float, device=self.device) + self._stage3_start_pos_w = torch.zeros( + (self.num_envs, 3), dtype=torch.float, device=self.device) + self._stage3_forward_axis_w = torch.zeros( + (self.num_envs, 3), dtype=torch.float, device=self.device) + self._forward_axis = torch.tensor( + (1.0, 0.0, 0.0), dtype=torch.float, device=self.device) + + self.metrics["stage_id"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["distance_base_fridge_xy"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["distance_hand_handle"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["door_open_angle"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["door_open_progress"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["backward_distance"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["backward_velocity"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["fingertip_contact"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["fridge_success"] = torch.zeros( + self.num_envs, device=self.device) + self._held_open_steps = torch.zeros( + self.num_envs, dtype=torch.long, device=self.device) + self.metrics["door_held_open_steps"] = torch.zeros( + self.num_envs, device=self.device) + self.metrics["door_held_open_seconds"] = torch.zeros( + self.num_envs, device=self.device) + + @property + def command(self) -> torch.Tensor: + return self.stage_one_hot + + @torch.no_grad() + def _resample_command(self, env_ids): + if len(env_ids) == 0: + return + env_ids_t = env_ids if isinstance( + env_ids, torch.Tensor) else torch.as_tensor(env_ids, device=self.device) + env_ids_t = env_ids_t.to(device=self.device, dtype=torch.long) + + door_pos = self.fridge.data.joint_pos[env_ids_t, self.door_joint_id] + self._door_initial_pos[env_ids_t] = door_pos + self._prev_door_angle[env_ids_t] = torch.zeros_like(door_pos) + self._door_angle_progress[env_ids_t] = 0.0 + self._door_angle_regression[env_ids_t] = 0.0 + self._stage3_start_pos_w[env_ids_t] = self.robot.data.root_pos_w[env_ids_t] + self._stage3_forward_axis_w[env_ids_t] = self.robot_forward_axis_w()[ + env_ids_t] + self.stage_id[env_ids_t] = 0 + self.stage_one_hot[env_ids_t] = 0.0 + self.stage_one_hot[env_ids_t, 0] = 1.0 + self._stage_steps[env_ids_t] = 0 + self._held_open_steps[env_ids_t] = 0 + + @torch.no_grad() + def _update_command(self): + door_angle = self.door_open_angle() + delta = door_angle - self._prev_door_angle + self._door_angle_progress = torch.clamp(delta, min=0.0) + self._door_angle_regression = torch.clamp(-delta, min=0.0) + self._prev_door_angle = door_angle.clone() + self._stage_steps.add_(1) + + held = door_angle >= float(self.cfg.held_open_angle) + if self.cfg.held_open_require_contact: + contact = self.fingertip_contact() + if isinstance(contact, torch.Tensor) and contact.shape[0] == self.num_envs: + held = held & contact.to(torch.bool) + self._held_open_steps = torch.where( + held, + self._held_open_steps + 1, + torch.zeros_like(self._held_open_steps), + ) + + def _update_metrics(self): + self.metrics["stage_id"] = self.stage_id.float() + self.metrics["distance_base_fridge_xy"] = self.base_distance_to_fridge_xy() + self.metrics["distance_hand_handle"] = self.hand_handle_distance() + self.metrics["door_open_angle"] = self.door_open_angle() + self.metrics["door_open_progress"] = self.door_open_progress() + self.metrics["backward_distance"] = self.backward_distance() + self.metrics["backward_velocity"] = self.backward_velocity() + contact = self.fingertip_contact() + self.metrics["fingertip_contact"] = torch.zeros( + self.num_envs, device=self.device) if contact is None else contact.float() + self.metrics["fridge_success"] = self.is_success().float() + self.metrics["door_held_open_steps"] = self._held_open_steps.float() + self.metrics["door_held_open_seconds"] = self.held_open_seconds() + + def robot_forward_axis_w(self) -> torch.Tensor: + axis = self._forward_axis.view(1, 3).expand(self.num_envs, -1) + return quat_apply(self.robot.data.root_quat_w, axis) + + def base_distance_to_fridge_xy(self) -> torch.Tensor: + delta = self.robot.data.root_pos_w[:, + :2] - self.fridge.data.root_pos_w[:, :2] + return torch.norm(delta, dim=-1) + + def hand_handle_distance(self) -> torch.Tensor: + hand_pos = self.robot.data.body_pos_w[:, self.hand_base_id] + handle_pos = self.handle_pos_w() + return torch.norm(hand_pos - handle_pos, dim=-1) + + def fingertip_handle_distance(self) -> torch.Tensor: + handle_pos = self.handle_pos_w().unsqueeze(1) + tip_pos = self.robot.data.body_pos_w[:, self.fingertip_ids] + return torch.norm(tip_pos - handle_pos, dim=-1).min(dim=-1).values + + def handle_pos_w(self) -> torch.Tensor: + door_pos_w = self.fridge.data.body_pos_w[:, + self.handle_reference_body_id] + door_quat_w = self.fridge.data.body_quat_w[:, + self.handle_reference_body_id] + handle_local_pos = self._handle_local_pos.expand(self.num_envs, -1) + return door_pos_w + quat_apply(door_quat_w, handle_local_pos) + + def door_joint_pos(self) -> torch.Tensor: + return self.fridge.data.joint_pos[:, self.door_joint_id] + + def door_open_angle(self) -> torch.Tensor: + return torch.abs(self.door_joint_pos() - self._door_initial_pos) + + def door_open_progress(self) -> torch.Tensor: + return self._door_angle_progress + + def door_close_regression(self) -> torch.Tensor: + return self._door_angle_regression + + def _retreat_forward_axis_xy(self) -> torch.Tensor: + forward_xy = self._stage3_forward_axis_w[:, :2] + forward_xy = forward_xy / \ + (forward_xy.norm(dim=-1, keepdim=True) + 1.0e-6) + yaw_off = float(getattr(self.cfg, "backward_axis_yaw_offset", 0.0)) + if yaw_off == 0.0: + return forward_xy + cos_t = math.cos(yaw_off) + sin_t = math.sin(yaw_off) + fx = forward_xy[:, 0] + fy = forward_xy[:, 1] + rot_x = cos_t * fx + sin_t * fy + rot_y = -sin_t * fx + cos_t * fy + return torch.stack([rot_x, rot_y], dim=-1) + + def backward_distance(self) -> torch.Tensor: + delta = self._stage3_start_pos_w - self.robot.data.root_pos_w + forward_xy = self._retreat_forward_axis_xy() + return torch.sum(delta[:, :2] * forward_xy, dim=-1) + + def backward_velocity(self) -> torch.Tensor: + forward_xy = self._retreat_forward_axis_xy() + vel_xy = self.robot.data.root_lin_vel_w[:, :2] + return -torch.sum(vel_xy * forward_xy, dim=-1) + + def fingertip_contact(self) -> torch.Tensor | None: + if len(self._contact_sensors) == 0: + return None + contacts: list[torch.Tensor] = [] + for sensor in self._contact_sensors: + forces = getattr(sensor.data, "force_matrix_w", None) + if forces is None: + forces = getattr(sensor.data, "force_matrix_w_history", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w_history", None) + if isinstance(forces, torch.Tensor): + forces = torch.nan_to_num( + forces, nan=0.0, posinf=0.0, neginf=0.0) + contact = forces.norm( + dim=-1) > self.cfg.contact_force_threshold + contacts.append(contact.view(contact.shape[0], -1).any(dim=-1)) + if len(contacts) == 0: + return None + + stacked = torch.stack(contacts, dim=0) + contact_count = stacked.sum(dim=0) + min_required = int(getattr(self.cfg, "min_fingertip_contacts", 1)) + result = contact_count >= int(max(1, min_required)) + + required_names = tuple( + getattr(self.cfg, "required_contact_sensors", ()) or ()) + if required_names: + for req_name in required_names: + if req_name in self._contact_sensor_names: + idx = self._contact_sensor_names.index(req_name) + result = result & contacts[idx] + return result + + def held_open_seconds(self) -> torch.Tensor: + return self._held_open_steps.float() * float(self._env.step_dt) + + def is_success(self) -> torch.Tensor: + door_ok = self.door_open_angle() >= float(self.cfg.success_door_angle) + hold_ok = self._held_open_steps >= int(self.cfg.success_hold_steps) + return door_ok & hold_ok + + +@configclass +class FridgeStageCommandCfg(CommandTermCfg): + class_type: type = FridgeStageCommand + + asset_name: str = MISSING + resampling_time_range: tuple[float, float] = (1.0e9, 1.0e9) + fridge_name: str = "fridge" + handle_reference_body_name: str | None = None + handle_local_pos: tuple[float, float, float] = ( + -0.5832248999999999, -0.09136289999999997, -0.5385152000000001) + door_body_name: str = "E_door_1" + door_joint_name: str = "RevoluteJoint" + + contact_sensor_name: str | tuple[str, ...] = () + fingertip_body_names: tuple[str, ...] = tuple(RIGHT_HAND_TIP_NAMES) + hand_base_body_name: str = "right_palm_link" + contact_force_threshold: float = 1.0 + + held_open_angle: float = math.radians(60.0) + held_open_require_contact: bool = True + success_door_angle: float = math.radians(70.0) + success_hold_steps: int = 30 + min_fingertip_contacts: int = 1 + required_contact_sensors: tuple[str, ...] = () + backward_axis_yaw_offset: float = 0.0 diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/events.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/events.py new file mode 100644 index 0000000000000000000000000000000000000000..b33b4fb19c6ac500aa0944165e065bb51c90bbd8 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/events.py @@ -0,0 +1,1227 @@ +from __future__ import annotations + +import math +import torch +from typing import TYPE_CHECKING, Literal + +from isaaclab.assets import Articulation +from isaaclab.envs.mdp.events import reset_scene_to_default, _randomize_prop_by_op +from isaaclab.managers import SceneEntityCfg +import isaaclab.utils.math as math_utils +from isaaclab.utils.math import quat_from_euler_xyz, quat_mul, sample_uniform + +from coordex.tasks.locomanip.rsi_buffer import NoDemoRSIBuffer +from coordex.tasks.locomanip.mdp.observations import clear_prior_obs_step_cache +from coordex.tasks.locomanip.mdp.rsi import ( + NoDemoRSICfg, + apply_locomanip_snapshot, +) + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +STAGE0_TO_STAGE1_RATE_SPECS = ( + ("approach_done", "approach_done"), + ("hand_height_ok", "hand_height_ok"), + ("hand_xy_ok", "hand_xy_ok"), + ("hand_flat", "hand_flat"), + ("hand_prepped", "hand_prepped"), + ("stage1_ready", "ready"), +) + + +def _resolve_env_ids(env, env_ids) -> torch.Tensor: + if env_ids is None: + return torch.arange(env.scene.num_envs, device=env.device) + if isinstance(env_ids, torch.Tensor): + return env_ids.to(device=env.device) + return torch.as_tensor(env_ids, device=env.device, dtype=torch.long) + + +def _sample_root_pose_noise( + device: torch.device, + count: int, + pose_range: dict[str, tuple[float, float]] | None, +) -> tuple[torch.Tensor, torch.Tensor]: + if not pose_range: + pos_noise = torch.zeros((count, 3), device=device) + ori_noise = torch.zeros((count, 3), device=device) + return pos_noise, ori_noise + range_list = [pose_range.get(key, (0.0, 0.0)) + for key in ["x", "y", "z", "roll", "pitch", "yaw"]] + ranges = torch.tensor(range_list, device=device, dtype=torch.float32) + rand_samples = sample_uniform( + ranges[:, 0], ranges[:, 1], (count, 6), device=device) + pos_noise = rand_samples[:, 0:3] + ori_noise = rand_samples[:, 3:6] + return pos_noise, ori_noise + + +def _ensure_no_demo_rsi_tensor( + env, + attr_name: str, + shape, + dtype: torch.dtype, + *, + device=None, + fill_value=0, +) -> torch.Tensor: + """Ensure a tensor attribute exists with the requested shape/dtype/device.""" + if shape == (): + target_shape = torch.Size(()) + elif isinstance(shape, int): + target_shape = torch.Size((shape,)) + else: + target_shape = torch.Size(shape) + + target_device = None if device is None else torch.device(device) + tensor = getattr(env, attr_name, None) + if ( + not isinstance(tensor, torch.Tensor) + or tensor.shape != target_shape + or tensor.dtype != dtype + or (target_device is not None and tensor.device != target_device) + ): + kwargs = {"dtype": dtype} + if target_device is not None: + kwargs["device"] = target_device + tensor = torch.full(target_shape, fill_value, **kwargs) + setattr(env, attr_name, tensor) + return tensor + + +def _prepare_no_demo_rsi_state(env, num_stages: int, capacity: int, settle_steps: int, stage0_rate_count: int): + """Ensure RSI buffers and adaptive trackers exist and match the environment shape.""" + _ = settle_steps + buffer = getattr(env, "_no_demo_rsi_buffer", None) + if not isinstance(buffer, NoDemoRSIBuffer) or buffer.num_stages != num_stages or buffer.capacity_per_stage != capacity: + buffer = NoDemoRSIBuffer( + num_stages=num_stages, capacity_per_stage=capacity, device=env.device) + setattr(env, "_no_demo_rsi_buffer", buffer) + + device = env.device + cpu_device = torch.device("cpu") + + stage_overrides = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_stage_on_reset", (env.num_envs,), torch.long, device=device, fill_value=-1 + ) + settle_buf = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_settle_steps", (env.num_envs,), torch.long, device=device, fill_value=0 + ) + last_reset_stage = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_last_reset_stage", (env.num_envs,), torch.long, device=device, fill_value=0 + ) + last_reset_valid = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_last_reset_valid", (env.num_envs,), torch.bool, device=device, fill_value=False + ) + + reset_counts = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_reset_stage_counts", (num_stages,), torch.long, device=cpu_device, fill_value=0 + ) + attempt_ema = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_attempt_ema", (num_stages,), torch.float32, device=cpu_device, fill_value=0.0 + ) + success_ema = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_success_ema", (num_stages,), torch.float32, device=cpu_device, fill_value=0.0 + ) + success_rate = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_success_rate", (num_stages,), torch.float32, device=cpu_device, fill_value=0.0 + ) + stage0_transition_attempt_ema = _ensure_no_demo_rsi_tensor( + env, + "_no_demo_rsi_stage0_to_stage1_attempt_ema", + (stage0_rate_count,), + torch.float32, + device=cpu_device, + fill_value=0.0, + ) + stage0_transition_success_ema = _ensure_no_demo_rsi_tensor( + env, + "_no_demo_rsi_stage0_to_stage1_success_ema", + (stage0_rate_count,), + torch.float32, + device=cpu_device, + fill_value=0.0, + ) + stage0_transition_rate = _ensure_no_demo_rsi_tensor( + env, + "_no_demo_rsi_stage0_to_stage1_rate", + (stage0_rate_count,), + torch.float32, + device=cpu_device, + fill_value=0.0, + ) + current_sample_prob = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_current_sample_prob", (num_stages,), torch.float32, device=cpu_device, fill_value=0.0 + ) + consolidation_mode = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_adaptive_consolidation_mode", (), torch.bool, device=cpu_device, fill_value=False + ) + unlocked_mask = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_warmup_unlocked_mask", (num_stages,), torch.bool, device=cpu_device, fill_value=False + ) + unlocked_mask[0] = True + ramp_attempt_count = _ensure_no_demo_rsi_tensor( + env, "_no_demo_rsi_warmup_ramp_attempt_count", (num_stages,), torch.long, device=cpu_device, fill_value=0 + ) + + return ( + buffer, + stage_overrides, + settle_buf, + reset_counts, + last_reset_stage, + last_reset_valid, + attempt_ema, + success_ema, + success_rate, + stage0_transition_attempt_ema, + stage0_transition_success_ema, + stage0_transition_rate, + current_sample_prob, + consolidation_mode, + unlocked_mask, + ramp_attempt_count, + ) + + +def _refresh_no_demo_rsi_success_rates( + success_rate: torch.Tensor, + success_ema: torch.Tensor, + attempt_ema: torch.Tensor, + success_prior: float, +) -> None: + prior = max(float(success_prior), 0.0) + denom = torch.clamp(attempt_ema + prior, min=1.0e-6) + numer = success_ema + (0.5 * prior) + success_rate.copy_(torch.clamp(numer / denom, min=0.0, max=1.0)) + + +def _score_no_demo_rsi_previous_episodes( + env_ids: torch.Tensor, + command, + last_reset_stage: torch.Tensor, + last_reset_valid: torch.Tensor, + attempt_ema: torch.Tensor, + success_ema: torch.Tensor, + success_rate: torch.Tensor, + tracked_stage_max: int, + stats_decay: float, + success_prior: float, +) -> None: + _refresh_no_demo_rsi_success_rates( + success_rate, success_ema, attempt_ema, success_prior) + if tracked_stage_max < 0 or env_ids.numel() == 0: + return + + prev_stage_subset = last_reset_stage[env_ids] + valid_mask = last_reset_valid[env_ids] & (prev_stage_subset >= 0) & ( + prev_stage_subset <= tracked_stage_max) + last_reset_valid[env_ids] = False + + num_stages = int(attempt_ema.numel()) + previous_stage = prev_stage_subset[valid_mask] + current_stage = command.stage_id[env_ids][valid_mask] + success_mask = current_stage >= (previous_stage + 1) + final_stage = int(getattr(command.cfg, "num_stages", 1)) - 1 + if final_stage >= 0: + final_success = command.is_cube_at_target()[env_ids][valid_mask] + success_mask = success_mask | ( + (previous_stage == final_stage) & final_success) + + attempts_device = torch.bincount(previous_stage, minlength=num_stages) + successes_device = torch.bincount( + previous_stage[success_mask], minlength=num_stages) + counts_cpu = torch.stack([attempts_device, successes_device]).to( + device=torch.device("cpu"), dtype=torch.float32 + ) + attempts_f = counts_cpu[0] + successes_f = counts_cpu[1] + touched_cpu = attempts_f > 0 + if touched_cpu.any(): + decay = float(stats_decay) + attempt_ema[touched_cpu] = attempt_ema[touched_cpu] * \ + decay + attempts_f[touched_cpu] + success_ema[touched_cpu] = success_ema[touched_cpu] * \ + decay + successes_f[touched_cpu] + _refresh_no_demo_rsi_success_rates( + success_rate, success_ema, attempt_ema, success_prior) + + +def _score_no_demo_rsi_stage0_transition_metrics( + env_ids: torch.Tensor, + command, + last_reset_stage: torch.Tensor, + last_reset_valid: torch.Tensor, + attempt_ema: torch.Tensor, + success_ema: torch.Tensor, + success_rate: torch.Tensor, + stats_decay: float, + success_prior: float, +) -> None: + _refresh_no_demo_rsi_success_rates( + success_rate, success_ema, attempt_ema, success_prior) + if env_ids.numel() == 0: + return + + prev_stage_subset = last_reset_stage[env_ids] + valid_env_ids = env_ids[last_reset_valid[env_ids] + & (prev_stage_subset == 0)] + if valid_env_ids.numel() == 0: + return + + flags = getattr(command, "stage0_transition_episode_flags", None) + if not isinstance(flags, dict): + return + + success_counts = [] + for key, _ in STAGE0_TO_STAGE1_RATE_SPECS: + value = flags.get(key) + if not isinstance(value, torch.Tensor) or value.numel() != command.num_envs: + success_counts.append(torch.zeros( + (), device=env_ids.device, dtype=torch.float32)) + continue + success_counts.append(value[valid_env_ids].float().sum()) + + successes_f = torch.stack(success_counts).to( + device=torch.device("cpu"), dtype=torch.float32) + attempts_f = torch.full_like(successes_f, float(valid_env_ids.numel())) + touched_cpu = attempts_f > 0 + if touched_cpu.any(): + decay = float(stats_decay) + attempt_ema[touched_cpu] = attempt_ema[touched_cpu] * \ + decay + attempts_f[touched_cpu] + success_ema[touched_cpu] = success_ema[touched_cpu] * \ + decay + successes_f[touched_cpu] + _refresh_no_demo_rsi_success_rates( + success_rate, success_ema, attempt_ema, success_prior) + + +def _compute_no_demo_rsi_availability_weight( + *, + stage: int, + size_k: int, + min_req: int, + buffer_capacity: int, + alpha: float, +) -> float: + """Compressed availability weight shared by stage-0 and RSI-buffer stages. + """ + + cap = max(int(buffer_capacity), 1) + if stage == 0: + effective_size = cap + else: + if size_k < min_req or size_k <= 0: + return 0.0 + effective_size = min(max(int(size_k), 1), cap) + + if alpha == 0.0: + return 1.0 + return float(math.log1p(float(effective_size)) ** float(alpha)) + + +def _compute_no_demo_rsi_adaptive_probabilities( + *, + num_stages: int, + adaptive_stage_max: int, + max_stage_allowed: int, + min_samples: list[int], + buffer_sizes_list: list[int], + buffer_capacity: int, + alpha: float, + success_rate: torch.Tensor, + difficulty_power: float, + difficulty_floor: float, + consolidation_mode: bool, + consolidation_stage0_share: float, +) -> torch.Tensor: + probs = torch.zeros(num_stages, dtype=torch.float32) + if num_stages <= 0: + return probs + + floor = max(float(difficulty_floor), 0.0) + power = float(difficulty_power) + stage0_difficulty = max( + 1.0 - float(success_rate[0].item()), floor) ** power + stage0_availability = _compute_no_demo_rsi_availability_weight( + stage=0, + size_k=0, + min_req=0, + buffer_capacity=buffer_capacity, + alpha=alpha, + ) + + eligible_stages: list[int] = [] + eligible_weights: list[float] = [] + for stage in range(1, adaptive_stage_max + 1): + if stage > max_stage_allowed: + continue + min_req = min_samples[stage] if stage < len( + min_samples) else min_samples[-1] + size_k = buffer_sizes_list[stage] if stage < len( + buffer_sizes_list) else 0 + difficulty = max( + 1.0 - float(success_rate[stage].item()), floor) ** power + size_weight = _compute_no_demo_rsi_availability_weight( + stage=stage, + size_k=size_k, + min_req=min_req, + buffer_capacity=buffer_capacity, + alpha=alpha, + ) + raw_weight = difficulty * size_weight + if raw_weight <= 0.0: + continue + eligible_stages.append(stage) + eligible_weights.append(raw_weight) + + if consolidation_mode and eligible_stages: + stage0_share = min(max(float(consolidation_stage0_share), 0.0), 1.0) + probs[0] = stage0_share + residual_mass = max(0.0, 1.0 - stage0_share) + total_weight = sum(eligible_weights) + if total_weight <= 0.0: + for stage in eligible_stages: + probs[stage] = residual_mass / len(eligible_stages) + else: + for stage, raw_weight in zip(eligible_stages, eligible_weights, strict=True): + probs[stage] = residual_mass * (raw_weight / total_weight) + return probs + + raw_weights = [(0, stage0_difficulty * stage0_availability)] + raw_weights.extend(zip(eligible_stages, eligible_weights, strict=True)) + total_weight = sum(weight for _, weight in raw_weights if weight > 0.0) + if total_weight <= 0.0: + probs[0] = 1.0 + return probs + + for stage, raw_weight in raw_weights: + if raw_weight > 0.0: + probs[stage] = raw_weight / total_weight + return probs + + +def _compute_no_demo_rsi_nonadaptive_probabilities( + *, + num_stages: int, + min_samples: list[int], + buffer_sizes_list: list[int], + alpha: float, + p_stage0: float, + stage_weights: list[float], +) -> torch.Tensor: + probs = torch.zeros(num_stages, dtype=torch.float32) + if num_stages <= 0: + return probs + + eligible: list[int] = [] + weights: list[float] = [] + for stage in range(1, num_stages): + min_req = min_samples[stage] if stage < len( + min_samples) else min_samples[-1] + size_k = buffer_sizes_list[stage] if stage < len( + buffer_sizes_list) else 0 + required_samples = max(int(min_req), 1) + if size_k < required_samples: + continue + stage_weight = float(stage_weights[stage]) if stage < len( + stage_weights) else 1.0 + if stage_weight <= 0.0: + continue + weight = (float(size_k**alpha) if alpha != 0.0 else 1.0) * stage_weight + if weight <= 0.0: + continue + eligible.append(stage) + weights.append(weight) + + if not eligible: + probs[0] = 1.0 + return probs + + stage0_share = min(max(float(p_stage0), 0.0), 1.0) + probs[0] = stage0_share + residual_mass = max(0.0, 1.0 - stage0_share) + total_weight = sum(weights) + if total_weight <= 0.0: + probs[0] = 1.0 + return probs + for stage, weight in zip(eligible, weights, strict=True): + probs[stage] = residual_mass * (weight / total_weight) + return probs + + +def _compute_no_demo_rsi_reward_metric_unlocked_mask( + *, + env, + rsi_cfg: NoDemoRSICfg, + num_stages: int, + reset_counts: torch.Tensor, +) -> torch.Tensor: + unlocked_mask = torch.zeros((num_stages,), dtype=torch.bool) + if num_stages <= 0: + return unlocked_mask + + max_stage_allowed = 0 + total_resets = int(reset_counts.sum().item()) if isinstance( + reset_counts, torch.Tensor) else 0 + key_s1 = getattr(rsi_cfg, "warmup_stage1_reward_key", + "episode_reward/robot_object_distance") + thr_s1 = float(getattr(rsi_cfg, "warmup_stage1_threshold", 7.0)) + val_s1 = _get_episode_reward_metric(env, key_s1) + allow_stage1 = val_s1 is not None and val_s1 > thr_s1 + allow_stage1 = allow_stage1 or (total_resets >= int( + getattr(rsi_cfg, "warmup_stage1_min_resets", 0))) + + key_s2 = getattr(rsi_cfg, "warmup_stage2_reward_key", + "episode_reward/cube_lift_height") + thr_s2 = float(getattr(rsi_cfg, "warmup_stage2_threshold", 1.0)) + val_s2 = _get_episode_reward_metric(env, key_s2) + allow_stage2_plus = val_s2 is not None and val_s2 > thr_s2 + allow_stage2_plus = allow_stage2_plus or (total_resets >= int( + getattr(rsi_cfg, "warmup_stage2_min_resets", 0))) + + if allow_stage1: + max_stage_allowed = max(max_stage_allowed, 1) + if allow_stage2_plus: + max_stage_allowed = num_stages - 1 + + unlocked_mask[: max_stage_allowed + 1] = True + return unlocked_mask + + +def _update_no_demo_rsi_prev_stage_unlocks( + *, + unlocked_mask: torch.Tensor, + success_rate: torch.Tensor, + buffer_sizes_list: list[int], + min_samples: list[int], + success_threshold: float, +) -> None: + if unlocked_mask.numel() == 0: + return + + unlocked_mask[0] = True + for stage in range(1, int(unlocked_mask.numel())): + if bool(unlocked_mask[stage].item()): + continue + if not bool(unlocked_mask[stage - 1].item()): + break + min_req = min_samples[stage] if stage < len( + min_samples) else min_samples[-1] + size_k = buffer_sizes_list[stage] if stage < len( + buffer_sizes_list) else 0 + required_samples = max(int(min_req), 1) + if size_k < required_samples: + break + if float(success_rate[stage - 1].item()) < float(success_threshold): + break + unlocked_mask[stage] = True + + +def _normalize_no_demo_rsi_probabilities(probs: torch.Tensor) -> torch.Tensor: + if probs.numel() == 0: + return probs + total = float(probs.sum().item()) + if total <= 0.0: + probs.zero_() + probs[0] = 1.0 + return probs + probs /= total + return probs + + +def _apply_no_demo_rsi_stage_sampling_constraints( + *, + raw_probs: torch.Tensor, + unlocked_mask: torch.Tensor, + apply_ramp: bool, + ramp_attempt_count: torch.Tensor | None, + ramp_initial_share: float, + ramp_attempts: int, +) -> torch.Tensor: + probs = raw_probs.clone() + if probs.numel() == 0: + return probs + + gate_mask = unlocked_mask.to(device=probs.device, dtype=torch.bool) + if gate_mask.numel() != probs.numel(): + raise ValueError( + "Warmup unlocked mask shape does not match RSI stage probability shape.") + gate_mask[0] = True + probs[~gate_mask] = 0.0 + _normalize_no_demo_rsi_probabilities(probs) + if not apply_ramp or ramp_attempt_count is None: + return probs + + initial_share = min(max(float(ramp_initial_share), 0.0), 1.0) + ramp_span = int(ramp_attempts) + if ramp_span <= 0: + return probs + + caps = torch.ones_like(probs) + counts = ramp_attempt_count.to(device=probs.device, dtype=torch.float32) + progress = torch.clamp(counts / float(ramp_span), min=0.0, max=1.0) + caps[1:] = initial_share + (1.0 - initial_share) * progress[1:] + caps[~gate_mask] = 0.0 + + base_weights = probs.clone() + for _ in range(int(probs.numel())): + overflow_mask = probs > (caps + 1.0e-6) + if not bool(overflow_mask.any().item()): + break + + excess = torch.clamp(probs[overflow_mask] - + caps[overflow_mask], min=0.0).sum() + probs[overflow_mask] = caps[overflow_mask] + recipient_mask = gate_mask & (~overflow_mask) + weights = torch.where(recipient_mask, base_weights, + torch.zeros_like(base_weights)) + weight_sum = float(weights.sum().item()) + if weight_sum <= 0.0: + if bool(recipient_mask[0].item()): + probs[0] += excess + else: + probs.zero_() + probs[0] = 1.0 + break + probs += excess * (weights / weight_sum) + + return _normalize_no_demo_rsi_probabilities(probs) + + +def _get_episode_reward_metric(env, key: str) -> float | None: + """Fetch an episode-level reward metric from env.extras, if present.""" + extras = getattr(env, "extras", None) + if not isinstance(extras, dict): + return None + candidates = [key, key.lower()] + if "/" in key: + suffix = key.split("/", 1)[1] + candidates.extend( + [ + suffix, + suffix.lower(), + f"episode_reward/{suffix}", + f"Episode_Reward/{suffix}", + ] + ) + containers = [extras] + episode_dict = extras.get("episode") if isinstance(extras, dict) else None + if isinstance(episode_dict, dict): + containers.append(episode_dict) + reward_dict = episode_dict.get("reward") + if isinstance(reward_dict, dict): + containers.append(reward_dict) + for container in containers: + if not isinstance(container, dict): + continue + for name in candidates: + if name in container: + val = container[name] + if isinstance(val, torch.Tensor): + val = val.item() + try: + return float(val) + except (TypeError, ValueError): + continue + return None + + +def reset_scene_with_no_demo_rsi( + env, + env_ids: torch.Tensor | None, + rsi_cfg: NoDemoRSICfg, + base_reset_func=reset_scene_to_default, + reset_joint_targets: bool = True, + command_name: str = "stage", + fixed_stage: int | None = None, + **base_reset_kwargs, +): + """Reset scene with optional no-demo RSI sampling.""" + env_ids_t = _resolve_env_ids(env, env_ids) + if env_ids_t.numel() == 0: + return + if fixed_stage is not None: + fixed_stage = int(fixed_stage) + if fixed_stage < 0: + fixed_stage = None + + base_kwargs = dict(base_reset_kwargs) + nested_base_kwargs = base_kwargs.pop("base_reset_kwargs", None) + if isinstance(nested_base_kwargs, dict): + base_kwargs.update(nested_base_kwargs) + base_kwargs.setdefault("reset_joint_targets", reset_joint_targets) + + stage_overrides = getattr(env, "_no_demo_rsi_stage_on_reset", None) + settle_buf = getattr(env, "_no_demo_rsi_settle_steps", None) + last_reset_stage = getattr(env, "_no_demo_rsi_last_reset_stage", None) + last_reset_valid = getattr(env, "_no_demo_rsi_last_reset_valid", None) + current_sample_prob = getattr( + env, "_no_demo_rsi_current_sample_prob", None) + consolidation_mode = getattr( + env, "_no_demo_rsi_adaptive_consolidation_mode", None) + + if fixed_stage is not None and fixed_stage > 0 and not (rsi_cfg and getattr(rsi_cfg, "enabled", False)): + raise ValueError("fixed_stage > 0 requires an enabled NoDemoRSICfg.") + + if not (rsi_cfg and getattr(rsi_cfg, "enabled", False)): + if isinstance(stage_overrides, torch.Tensor): + stage_overrides[env_ids_t] = 0 + if isinstance(settle_buf, torch.Tensor): + settle_buf[env_ids_t] = 0 + if isinstance(last_reset_stage, torch.Tensor): + last_reset_stage[env_ids_t] = 0 + if isinstance(last_reset_valid, torch.Tensor): + last_reset_valid[env_ids_t] = False + if isinstance(current_sample_prob, torch.Tensor): + current_sample_prob.zero_() + if isinstance(consolidation_mode, torch.Tensor): + consolidation_mode.fill_(False) + base_reset_func(env, env_ids_t, **base_kwargs) + return + + command = env.command_manager.get_term(command_name) + num_stages = int(getattr(command.cfg, "num_stages", len( + getattr(rsi_cfg, "min_samples_to_enable", [])) or 0)) + if num_stages <= 0: + num_stages = max(1, len(getattr(rsi_cfg, "min_samples_to_enable", []))) + if fixed_stage is not None and fixed_stage >= num_stages: + raise ValueError( + f"fixed_stage must be in [0, {num_stages - 1}], got {fixed_stage}.") + stage0_rate_specs = STAGE0_TO_STAGE1_RATE_SPECS + + ( + buffer, + stage_overrides, + settle_buf, + reset_counts, + last_reset_stage, + last_reset_valid, + attempt_ema, + success_ema, + success_rate, + stage0_transition_attempt_ema, + stage0_transition_success_ema, + stage0_transition_rate, + current_sample_prob, + consolidation_mode, + warmup_unlocked_mask, + ramp_attempt_count, + ) = _prepare_no_demo_rsi_state( + env, + num_stages=num_stages, + capacity=int(rsi_cfg.capacity_per_stage), + settle_steps=int(rsi_cfg.settle_steps), + stage0_rate_count=len(stage0_rate_specs), + ) + forced_stage_enabled = fixed_stage is not None + adaptive_enabled = bool(getattr( + rsi_cfg, "adaptive_stage_sampling_enabled", False)) and (not forced_stage_enabled) + warmup_enabled = bool(getattr(rsi_cfg, "warmup_enabled", False)) + warmup_mode = str(getattr(rsi_cfg, "warmup_mode", "reward_metric")) + use_prev_stage_success_warmup = warmup_enabled and ( + warmup_mode == "prev_stage_success") and (not forced_stage_enabled) + adaptive_stage_cap = int(getattr(rsi_cfg, "adaptive_stage_max", 3)) + adaptive_stage_max = min(num_stages - 1, max(adaptive_stage_cap, 0)) + tracked_stage_max = ( + num_stages - 1) if use_prev_stage_success_warmup else adaptive_stage_max + success_tracking_enabled = ( + adaptive_enabled or use_prev_stage_success_warmup) and tracked_stage_max >= 0 + success_prior = float(getattr(rsi_cfg, "adaptive_success_prior", 16.0)) + _score_no_demo_rsi_stage0_transition_metrics( + env_ids_t, + command, + last_reset_stage, + last_reset_valid, + stage0_transition_attempt_ema, + stage0_transition_success_ema, + stage0_transition_rate, + stats_decay=float(getattr(rsi_cfg, "adaptive_stats_decay", 0.995)), + success_prior=success_prior, + ) + if success_tracking_enabled: + _score_no_demo_rsi_previous_episodes( + env_ids_t, + command, + last_reset_stage, + last_reset_valid, + attempt_ema, + success_ema, + success_rate, + tracked_stage_max=tracked_stage_max, + stats_decay=float(getattr(rsi_cfg, "adaptive_stats_decay", 0.995)), + success_prior=success_prior, + ) + else: + _refresh_no_demo_rsi_success_rates( + success_rate, success_ema, attempt_ema, success_prior) + success_rate.zero_() + last_reset_valid[env_ids_t] = False + if not adaptive_enabled: + consolidation_mode.fill_(False) + + min_samples = list(getattr(rsi_cfg, "min_samples_to_enable", [])) + if len(min_samples) < num_stages: + if min_samples: + min_samples.extend([min_samples[-1]] * + (num_stages - len(min_samples))) + else: + min_samples = [0] * num_stages + + alpha = float(getattr(rsi_cfg, "alpha", 1.0)) + buffer_sizes_list = [int(x) for x in buffer.sizes().tolist()] + unlocked_mask = torch.ones((num_stages,), dtype=torch.bool) + apply_warmup_ramp = False + if warmup_enabled and not forced_stage_enabled: + if use_prev_stage_success_warmup: + _update_no_demo_rsi_prev_stage_unlocks( + unlocked_mask=warmup_unlocked_mask, + success_rate=success_rate, + buffer_sizes_list=buffer_sizes_list, + min_samples=min_samples, + success_threshold=float( + getattr(rsi_cfg, "warmup_success_threshold", 0.6)), + ) + unlocked_mask = warmup_unlocked_mask.clone() + apply_warmup_ramp = True + else: + unlocked_mask = _compute_no_demo_rsi_reward_metric_unlocked_mask( + env=env, + rsi_cfg=rsi_cfg, + num_stages=num_stages, + reset_counts=reset_counts, + ) + + if forced_stage_enabled: + stage_choices = torch.full( + (env_ids_t.numel(),), int(fixed_stage), device=env.device, dtype=torch.long + ) + current_sample_prob.zero_() + current_sample_prob[fixed_stage] = 1.0 + last_reset_valid[env_ids_t] = False + consolidation_mode.fill_(False) + else: + if adaptive_enabled: + tracked_stage_count = min(num_stages, adaptive_stage_max + 1) + enter_threshold = float( + getattr(rsi_cfg, "adaptive_consolidation_enter", 0.80)) + exit_threshold = float( + getattr(rsi_cfg, "adaptive_consolidation_exit", 0.75)) + # success_rate, consolidation_mode are CPU tensors → .item() is sync-free. + consolidation_active = bool(consolidation_mode.item()) + if tracked_stage_count > 0: + tracked_rates = success_rate[:tracked_stage_count] + if consolidation_active: + if bool((tracked_rates < exit_threshold).any().item()): + consolidation_mode.fill_(False) + consolidation_active = False + else: + if bool((tracked_rates >= enter_threshold).all().item()): + consolidation_mode.fill_(True) + consolidation_active = True + + raw_stage_probs = _compute_no_demo_rsi_adaptive_probabilities( + num_stages=num_stages, + adaptive_stage_max=adaptive_stage_max, + max_stage_allowed=num_stages - 1, + min_samples=min_samples, + buffer_sizes_list=buffer_sizes_list, + buffer_capacity=int(getattr(rsi_cfg, "capacity_per_stage", 1)), + alpha=alpha, + success_rate=success_rate, + difficulty_power=float( + getattr(rsi_cfg, "adaptive_difficulty_power", 1.0)), + difficulty_floor=float( + getattr(rsi_cfg, "adaptive_difficulty_floor", 0.10)), + consolidation_mode=consolidation_active, + consolidation_stage0_share=float( + getattr(rsi_cfg, "adaptive_consolidation_stage0_share", 0.85)), + ) + else: + stage_weights = list(getattr(rsi_cfg, "stage_sampling_weight", [])) + if len(stage_weights) < num_stages: + if stage_weights: + stage_weights.extend( + [stage_weights[-1]] * (num_stages - len(stage_weights))) + else: + stage_weights = [1.0] * num_stages + raw_stage_probs = _compute_no_demo_rsi_nonadaptive_probabilities( + num_stages=num_stages, + min_samples=min_samples, + buffer_sizes_list=buffer_sizes_list, + alpha=alpha, + p_stage0=float(getattr(rsi_cfg, "p_stage0", 0.0)), + stage_weights=stage_weights, + ) + + sampled_stage_probs = _apply_no_demo_rsi_stage_sampling_constraints( + raw_probs=raw_stage_probs, + unlocked_mask=unlocked_mask, + apply_ramp=apply_warmup_ramp, + ramp_attempt_count=ramp_attempt_count if apply_warmup_ramp else None, + ramp_initial_share=float( + getattr(rsi_cfg, "warmup_ramp_initial_share", 0.05)), + ramp_attempts=int(getattr(rsi_cfg, "warmup_ramp_attempts", 1000)), + ) + current_sample_prob.copy_(sampled_stage_probs) + sampled_probs_gpu = sampled_stage_probs.to( + device=env.device, non_blocking=True) + stage_choices = torch.multinomial( + sampled_probs_gpu, env_ids_t.numel(), replacement=True + ).to(dtype=torch.long) + + stage_overrides[env_ids_t] = stage_choices + last_reset_stage[env_ids_t] = stage_choices + if forced_stage_enabled: + last_reset_valid[env_ids_t] = False + elif success_tracking_enabled: + last_reset_valid[env_ids_t] = stage_choices <= tracked_stage_max + else: + last_reset_valid[env_ids_t] = False + if hasattr(command, "reset_stage0_transition_episode_flags"): + command.reset_stage0_transition_episode_flags(env_ids_t) + settle_steps_val = int(rsi_cfg.settle_steps) + if settle_steps_val > 0: + settle_buf[env_ids_t] = torch.where( + stage_choices > 0, settle_steps_val, 0) + else: + settle_buf[env_ids_t] = 0 + + counts_cpu = torch.bincount(stage_choices, minlength=num_stages).cpu() + reset_counts[: counts_cpu.numel()] += counts_cpu + if apply_warmup_ramp and not forced_stage_enabled: + ramp_attempt_count += counts_cpu + + stage0_envs_tensor = env_ids_t[stage_choices == 0] if int( + counts_cpu[0]) > 0 else env_ids_t[:0] + rsi_stage_map: dict[int, torch.Tensor] = {} + for stage in range(1, num_stages): + if int(counts_cpu[stage]) == 0: + continue + rsi_stage_map[stage] = env_ids_t[stage_choices == stage] + + if stage0_envs_tensor.numel() > 0: + env_subset = stage0_envs_tensor + base_reset_func(env, env_subset, **base_kwargs) + + for stage, env_subset in rsi_stage_map.items(): + if env_subset.numel() == 0: + continue + try: + snapshots = buffer.sample( + stage, env_subset.numel(), device=env.device) + except Exception as err: + if forced_stage_enabled: + print( + f"[WARN] Requested reset_stage={stage}, but its RSI buffer is empty or unavailable " + f"({err}). Falling back to stage 0 reset." + ) + stage_overrides[env_subset] = 0 + settle_buf[env_subset] = 0 + last_reset_stage[env_subset] = 0 + if success_tracking_enabled: + last_reset_valid[env_subset] = True + else: + last_reset_valid[env_subset] = False + n_fallback = int(env_subset.numel()) + reset_counts[stage] -= n_fallback + reset_counts[0] += n_fallback + base_reset_func(env, env_subset, **base_kwargs) + continue + apply_locomanip_snapshot( + env, + env_subset, + snapshots, + command_name=command_name, + reset_joint_targets=reset_joint_targets, + ) + + +def reset_fridge_to_pregrasp_demo_frame( + env, + env_ids, + *, + pose_range: dict[str, tuple[float, float]] | None = None, + joint_position_range: tuple[float, float] | None = None, + reset_joint_targets: bool = True, +): + """Reset the fridge env to the static pre-grasp pose in fridge_reset_states.""" + from coordex.tasks.locomanip.fridge_reset_states import ( + PREGRASP_FRIDGE_JOINT_POS, + PREGRASP_ROBOT_JOINT_POS, + PREGRASP_ROOT_POS, + PREGRASP_ROOT_QUAT_WXYZ, + ) + + env_ids = _resolve_env_ids(env, env_ids) + if env_ids.numel() == 0: + return + + robot: Articulation = env.scene["robot"] + fridge: Articulation = env.scene["fridge"] + device = env.device + n = int(env_ids.numel()) + env_origins = env.scene.env_origins[env_ids] + + # Robot root pose in world frame. + root_pos = torch.tensor(PREGRASP_ROOT_POS, device=device, + dtype=torch.float32).expand(n, 3).clone() + root_pos = root_pos + env_origins + root_quat = torch.tensor( + PREGRASP_ROOT_QUAT_WXYZ, device=device, dtype=torch.float32).expand(n, 4).clone() + if pose_range is not None: + pos_noise, ori_noise = _sample_root_pose_noise(device, n, pose_range) + root_pos = root_pos + pos_noise + noise_quat = quat_from_euler_xyz( + ori_noise[:, 0], ori_noise[:, 1], ori_noise[:, 2]) + root_quat = quat_mul(root_quat, noise_quat) + root_pose = torch.cat([root_pos, root_quat], dim=-1) + robot.write_root_pose_to_sim(root_pose, env_ids=env_ids) + robot.write_root_velocity_to_sim(torch.zeros( + (n, 6), device=device), env_ids=env_ids) + + # Robot joint state. + joint_pos = ( + torch.tensor(PREGRASP_ROBOT_JOINT_POS, + device=device, dtype=torch.float32) + .unsqueeze(0) + .expand(n, -1) + .clone() + ) + if joint_position_range is not None: + lo, hi = float(joint_position_range[0]), float(joint_position_range[1]) + joint_pos = joint_pos + torch.empty_like(joint_pos).uniform_(lo, hi) + joint_vel = torch.zeros_like(joint_pos) + robot.write_joint_state_to_sim(joint_pos, joint_vel, env_ids=env_ids) + if reset_joint_targets: + robot.set_joint_position_target(joint_pos, env_ids=env_ids) + robot.set_joint_velocity_target(joint_vel, env_ids=env_ids) + robot.write_data_to_sim() + + # Fridge joint state. + fridge_joint_pos = ( + torch.tensor(PREGRASP_FRIDGE_JOINT_POS, + device=device, dtype=torch.float32) + .unsqueeze(0) + .expand(n, -1) + .clone() + ) + fridge_joint_vel = torch.zeros_like(fridge_joint_pos) + fridge.write_joint_state_to_sim( + fridge_joint_pos, fridge_joint_vel, env_ids=env_ids) + if reset_joint_targets: + fridge.set_joint_position_target(fridge_joint_pos, env_ids=env_ids) + fridge.set_joint_velocity_target(fridge_joint_vel, env_ids=env_ids) + fridge.write_data_to_sim() + + clear_prior_obs_step_cache(env) + + +def randomize_joint_default_pos( + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + asset_cfg: SceneEntityCfg, + pos_distribution_params: tuple[float, float] | None = None, + operation: Literal["add", "scale", "abs"] = "abs", + distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform", + offset_sync_mode: Literal["action", "legacy_body"] = "action", +): + """ + Randomize the joint default positions which may be different from URDF due to calibration errors. + """ + asset: Articulation = env.scene[asset_cfg.name] + + asset.data.default_joint_pos_nominal = torch.clone( + asset.data.default_joint_pos[0]) + + # resolve environment ids + if env_ids is None: + env_ids = torch.arange(env.scene.num_envs, device=asset.device) + env_ids_action = env_ids if isinstance(env_ids, slice) else env_ids.clone() + + # resolve joint indices + if asset_cfg.joint_ids == slice(None): + joint_ids = slice(None) # for optimization purposes + else: + joint_ids = torch.tensor( + asset_cfg.joint_ids, dtype=torch.int, device=asset.device) + + if pos_distribution_params is not None: + pos = asset.data.default_joint_pos.to(asset.device).clone() + pos = _randomize_prop_by_op( + pos, pos_distribution_params, env_ids, joint_ids, operation=operation, distribution=distribution + )[env_ids][:, joint_ids] + + if env_ids != slice(None) and joint_ids != slice(None): + env_ids = env_ids[:, None] + asset.data.default_joint_pos[env_ids, joint_ids] = pos + # update the offset in action since it is not updated automatically + action_term = env.action_manager.get_term("joint_pos") + + offset = action_term._offset + action_joint_ids = getattr(action_term, "_joint_ids", slice(None)) + # normalize joint id containers to tensors when needed + + def _to_tensor_ids(ids, device): + if isinstance(ids, slice): + return None + if isinstance(ids, torch.Tensor): + return ids.to(device=device, dtype=torch.long) + return torch.tensor(list(ids), device=device, dtype=torch.long) + + action_env_ids = env_ids_action + if not isinstance(action_env_ids, slice) and action_env_ids.ndim > 1: + action_env_ids = action_env_ids.squeeze(-1) + + rand_joint_ids = _to_tensor_ids(joint_ids, offset.device) + # action index -> joint id mapping for the action term + if isinstance(action_joint_ids, slice): + action_joint_ids_tensor = torch.arange( + offset.shape[1], device=offset.device, dtype=torch.long) + else: + action_joint_ids_tensor = _to_tensor_ids( + action_joint_ids, offset.device) + if action_joint_ids_tensor is None: + action_joint_ids_tensor = torch.arange( + offset.shape[1], device=offset.device, dtype=torch.long) + + # choose the action indices that correspond to randomized joint ids + if rand_joint_ids is None: + action_idx = torch.arange( + action_joint_ids_tensor.numel(), device=offset.device, dtype=torch.long) + else: + mask = torch.isin(action_joint_ids_tensor, rand_joint_ids) + action_idx = torch.nonzero(mask, as_tuple=False).squeeze(-1) + if action_idx.numel() == 0: + return + + if offset_sync_mode == "legacy_body": + # Apply offsets in ascending joint-id order to preserve legacy body-only behavior. + action_idx_sorted = torch.sort(action_idx).values + legacy_joint_ids = torch.sort( + action_joint_ids_tensor[action_idx]).values + if isinstance(action_env_ids, slice): + new_offset = asset.data.default_joint_pos[:, legacy_joint_ids].to( + offset.device) + offset[:, action_idx_sorted] = new_offset + else: + new_offset = asset.data.default_joint_pos[action_env_ids][:, legacy_joint_ids].to( + offset.device) + offset[action_env_ids[:, None], action_idx_sorted] = new_offset + return + + joint_ids_update = action_joint_ids_tensor[action_idx] + if isinstance(action_env_ids, slice): + new_offset = asset.data.default_joint_pos[:, joint_ids_update].to( + offset.device) + offset[:, action_idx] = new_offset + else: + new_offset = asset.data.default_joint_pos[action_env_ids][:, joint_ids_update].to( + offset.device) + offset[action_env_ids[:, None], action_idx] = new_offset + + +def randomize_rigid_object_default_pose( + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + pose_range: dict[str, tuple[float, float]], + asset_cfg: SceneEntityCfg, +): + """Persistently perturb a rigid object's default root pose per env. + + Designed for startup-mode randomization: each env's bottle (or other rigid + object) gets its own spawn offset, fixed across all episode resets within + that env. The function modifies ``asset.data.default_root_state`` directly, + so subsequent ``reset_scene_to_default`` calls read the perturbed pose + rather than the original spawn pose. The perturbed pose is also written + into the live sim so the very first observation already reflects it. + + ``pose_range`` follows the same key convention as IsaacLab's + ``reset_root_state_uniform`` (``x``, ``y``, ``z``, ``roll``, ``pitch``, + ``yaw``); values are tuples ``(min, max)`` interpreted in env-local + coordinates. Velocities are not perturbed. + """ + from isaaclab.assets import RigidObject + + asset: RigidObject = env.scene[asset_cfg.name] + if env_ids is None: + env_ids_t = torch.arange( + env.scene.num_envs, device=asset.device, dtype=torch.long) + elif isinstance(env_ids, torch.Tensor): + env_ids_t = env_ids.to(device=asset.device, dtype=torch.long) + else: + env_ids_t = torch.as_tensor( + env_ids, device=asset.device, dtype=torch.long) + if env_ids_t.numel() == 0: + return + + keys = ("x", "y", "z", "roll", "pitch", "yaw") + range_list = [pose_range.get(key, (0.0, 0.0)) for key in keys] + ranges = torch.tensor(range_list, device=asset.device) + rand_samples = sample_uniform( + ranges[:, 0], ranges[:, 1], (env_ids_t.numel(), 6), device=asset.device + ) + + # Position: in-place add to env-local default position. + asset.data.default_root_state[env_ids_t, 0:3] += rand_samples[:, 0:3] + # Orientation: compose only if any rotation range is non-zero (the common + # bottle-on-table case is position-only, so we skip the quat math then). + has_rotation = any(abs(low) > 0.0 or abs( + high) > 0.0 for low, high in range_list[3:]) + if has_rotation: + delta = quat_from_euler_xyz( + rand_samples[:, 3], rand_samples[:, 4], rand_samples[:, 5]) + asset.data.default_root_state[env_ids_t, 3:7] = quat_mul( + asset.data.default_root_state[env_ids_t, 3:7], delta + ) + + # Push the perturbed default pose into sim (in world frame). + pose = asset.data.default_root_state[env_ids_t, :7].clone() + pose[:, 0:3] = pose[:, 0:3] + env.scene.env_origins[env_ids_t] + asset.write_root_pose_to_sim(pose, env_ids=env_ids_t) + + +def randomize_rigid_body_com( + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + com_range: dict[str, tuple[float, float]], + asset_cfg: SceneEntityCfg, +): + """Randomize the center of mass (CoM) of rigid bodies by adding a random value sampled from the given ranges. + + .. note:: + This function uses CPU tensors to assign the CoM. It is recommended to use this function + only during the initialization of the environment. + """ + # extract the used quantities (to enable type-hinting) + asset: Articulation = env.scene[asset_cfg.name] + # resolve environment ids + if env_ids is None: + env_ids = torch.arange(env.scene.num_envs, device="cpu") + else: + env_ids = env_ids.cpu() + + # resolve body indices + if asset_cfg.body_ids == slice(None): + body_ids = torch.arange( + asset.num_bodies, dtype=torch.int, device="cpu") + else: + body_ids = torch.tensor( + asset_cfg.body_ids, dtype=torch.int, device="cpu") + + # sample random CoM values + range_list = [com_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z"]] + ranges = torch.tensor(range_list, device="cpu") + rand_samples = math_utils.sample_uniform( + ranges[:, 0], ranges[:, 1], (len(env_ids), 3), device="cpu").unsqueeze(1) + + # get the current com of the bodies (num_assets, num_bodies) + coms = asset.root_physx_view.get_coms().clone() + + # Randomize the com in range + coms[:, body_ids, :3] += rand_samples + + # Set the new coms + asset.root_physx_view.set_coms(coms, env_ids) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/observations.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/observations.py new file mode 100644 index 0000000000000000000000000000000000000000..9028f23905d7fd5a4b0cff1e92673e494607f383 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/observations.py @@ -0,0 +1,1032 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.assets import Articulation +from isaaclab.envs.mdp import base_ang_vel, base_lin_vel, joint_pos_rel, joint_vel_rel +from isaaclab.managers import ManagerTermBase, SceneEntityCfg +from isaaclab.utils.math import matrix_from_quat, quat_apply, quat_inv, subtract_frame_transforms + +from coordex.tasks.locomanip.constants import RIGHT_HAND_TIP_NAMES + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +TRACKING_PRIOR_NOISE_CFG: dict[str, tuple[float, float]] = { + "lin_vel": (-0.5, 0.5), + "ang_vel": (-0.2, 0.2), + "joint_pos": (-0.01, 0.01), + "joint_vel": (-0.5, 0.5), +} + +_TRACKING_PRIOR_LIN_VEL_DIM = 3 +_TRACKING_PRIOR_ANG_VEL_DIM = 3 + + +def _current_step_tag(env: ManagerBasedRLEnv) -> int: + return int(getattr(env, "common_step_counter", -1)) + + +def _prior_obs_step_cache(env: ManagerBasedRLEnv) -> dict: + cache = getattr(env, "_locomanip_prior_obs_cache", None) + if not isinstance(cache, dict): + cache = {} + setattr(env, "_locomanip_prior_obs_cache", cache) + return cache + + +def clear_prior_obs_step_cache(env: ManagerBasedRLEnv) -> None: + setattr(env, "_locomanip_prior_obs_cache", {}) + + +def _get_cached_step_tensor(env: ManagerBasedRLEnv, cache_key: tuple) -> torch.Tensor | None: + cache = getattr(env, "_locomanip_prior_obs_cache", None) + if not isinstance(cache, dict): + return None + cached = cache.get(cache_key) + if not isinstance(cached, tuple) or len(cached) != 2: + return None + step_tag, tensor = cached + if step_tag != _current_step_tag(env) or not isinstance(tensor, torch.Tensor): + return None + return tensor + + +def _set_cached_step_tensor(env: ManagerBasedRLEnv, cache_key: tuple, tensor: torch.Tensor) -> torch.Tensor: + _prior_obs_step_cache(env)[cache_key] = (_current_step_tag(env), tensor) + return tensor + + +def _joint_ids_cache_key(joint_ids: list[int] | slice | torch.Tensor | None) -> tuple | None: + if joint_ids is None: + return None + if isinstance(joint_ids, slice): + return ("slice", joint_ids.start, joint_ids.stop, joint_ids.step) + if isinstance(joint_ids, torch.Tensor): + joint_ids = joint_ids.tolist() + return tuple(int(joint_id) for joint_id in joint_ids) + + +def _resolve_env_ids_tensor( + env: ManagerBasedRLEnv, + env_ids, + *, + device: torch.device | None = None, +) -> torch.Tensor: + target_device = env.device if device is None else device + if env_ids is None: + return torch.arange(env.num_envs, device=target_device, dtype=torch.long) + if isinstance(env_ids, slice): + return torch.arange(env.num_envs, device=target_device, dtype=torch.long)[env_ids] + return torch.as_tensor(env_ids, device=target_device, dtype=torch.long) + + +def _noise_cfg_cache_key(noise_cfg: dict[str, tuple[float, float]] | None) -> tuple | None: + if noise_cfg is None: + return None + return tuple( + (str(name), tuple(float(value) for value in values)) + for name, values in sorted(noise_cfg.items(), key=lambda item: item[0]) + ) + + +def _tracking_prior_frame_cache_key( + asset_cfg: SceneEntityCfg, + noise_cfg: dict[str, tuple[float, float]] | None, + include_base_lin_vel: bool = True, +) -> tuple: + return ( + "tracking_prior_frame", + asset_cfg.name, + _joint_ids_cache_key(asset_cfg.joint_ids), + _noise_cfg_cache_key(noise_cfg), + bool(include_base_lin_vel), + ) + + +def _tracking_prior_history_cache_key( + asset_cfg: SceneEntityCfg, + noise_cfg: dict[str, tuple[float, float]] | None, + history_length: int, + include_base_lin_vel: bool = True, +) -> tuple: + return ( + "tracking_prior_history", + asset_cfg.name, + _joint_ids_cache_key(asset_cfg.joint_ids), + _noise_cfg_cache_key(noise_cfg), + int(history_length), + bool(include_base_lin_vel), + ) + + +def _right_hand_prior_cache_key(asset_cfg: SceneEntityCfg, wrist_body_name: str) -> tuple: + return ( + "right_hand_prior", + asset_cfg.name, + _joint_ids_cache_key(asset_cfg.joint_ids), + wrist_body_name, + ) + + +def _tracking_prior_history_state( + env: ManagerBasedRLEnv, + cache_key: tuple, + history_length: int, + frame_obs: torch.Tensor, +) -> dict[str, torch.Tensor | int]: + history_state = getattr( + env, "_locomanip_tracking_prior_history_state", None) + if not isinstance(history_state, dict): + history_state = {} + setattr(env, "_locomanip_tracking_prior_history_state", history_state) + + state = history_state.get(cache_key) + frame_dim = int(frame_obs.shape[-1]) + if ( + not isinstance(state, dict) + or int(state.get("history_length", -1)) != history_length + or int(state.get("frame_dim", -1)) != frame_dim + or not isinstance(state.get("skip_update_once"), torch.Tensor) + ): + state = { + "history_length": history_length, + "frame_dim": frame_dim, + "frame_history": torch.zeros( + (env.num_envs, history_length, + frame_dim), device=frame_obs.device, dtype=frame_obs.dtype + ), + "initialized": torch.zeros((env.num_envs,), device=frame_obs.device, dtype=torch.bool), + "skip_update_once": torch.zeros((env.num_envs,), device=frame_obs.device, dtype=torch.bool), + "last_step": None, + } + history_state[cache_key] = state + return state + + +def _add_uniform_noise(tensor: torch.Tensor, noise_range: tuple[float, float] | None) -> torch.Tensor: + if noise_range is None: + return tensor + low, high = noise_range + if low == 0.0 and high == 0.0: + return tensor + noise = (high - low) * torch.rand_like(tensor) + low + return tensor + noise + + +def _resolve_body_indices( + env: ManagerBasedRLEnv, + asset: Articulation, + body_names: list[str], + cache_attr: str, +) -> torch.Tensor: + cached = getattr(env, cache_attr, None) + if isinstance(cached, torch.Tensor): + return cached + body_ids, body_found = asset.find_bodies(body_names, preserve_order=True) + if len(body_ids) != len(body_names): + missing = sorted(set(body_names) - set(body_found)) + raise RuntimeError(f"Missing bodies on '{asset.name}': {missing}") + ids = torch.as_tensor( + body_ids, device=asset.data.body_pos_w.device, dtype=torch.long) + setattr(env, cache_attr, ids) + return ids + + +def _resolve_body_index(env: ManagerBasedRLEnv, asset: Articulation, body_name: str, cache_attr: str) -> int: + cached = getattr(env, cache_attr, None) + if cached is not None: + return int(cached) + body_ids, _ = asset.find_bodies([body_name], preserve_order=True) + if len(body_ids) == 0: + raise RuntimeError( + f"Body '{body_name}' not found on asset '{asset.name}'.") + body_id = int(body_ids[0]) + setattr(env, cache_attr, body_id) + return body_id + + +def _resolve_action_ids( + env: ManagerBasedRLEnv, + joint_ids: list[int] | slice | torch.Tensor, + device: torch.device, + *, + action_term_name: str = "joint_pos", +) -> slice | torch.Tensor: + if isinstance(joint_ids, slice): + return slice(None) + + if isinstance(joint_ids, torch.Tensor): + joint_ids_list = joint_ids.tolist() + else: + joint_ids_list = list(joint_ids) + + if len(joint_ids_list) == 0: + return torch.zeros((0,), device=device, dtype=torch.long) + + cache = getattr(env, "_locomanip_action_id_cache", None) + if not isinstance(cache, dict): + cache = {} + setattr(env, "_locomanip_action_id_cache", cache) + + cache_key = (action_term_name, tuple(int(j) for j in joint_ids_list)) + cached = cache.get(cache_key) + if isinstance(cached, torch.Tensor): + return cached + + term = env.action_manager.get_term(action_term_name) + if hasattr(term, "_joint_action"): + joint_ids_all = getattr(term._joint_action, "_joint_ids", slice(None)) + else: + joint_ids_all = getattr(term, "_joint_ids", slice(None)) + + if isinstance(joint_ids_all, slice): + action_ids = torch.as_tensor( + joint_ids_list, device=device, dtype=torch.long) + else: + joint_ids_all = torch.as_tensor( + joint_ids_all, device=device, dtype=torch.long) + max_joint_id = int(joint_ids_all.max().item()) + joint_to_action = torch.full( + (max_joint_id + 1,), -1, device=device, dtype=torch.long) + joint_to_action[joint_ids_all] = torch.arange( + joint_ids_all.numel(), device=device, dtype=torch.long) + joint_ids_tensor = torch.as_tensor( + joint_ids_list, device=device, dtype=torch.long) + if int(joint_ids_tensor.max().item()) >= joint_to_action.numel(): + action_ids = torch.full_like(joint_ids_tensor, -1) + else: + action_ids = joint_to_action[joint_ids_tensor] + + cache[cache_key] = action_ids + return action_ids + + +def _get_last_joint_actions( + env: ManagerBasedRLEnv, + joint_ids: list[int] | slice | torch.Tensor, + action_dim: int, + device: torch.device, + dtype: torch.dtype, + *, + action_term_name: str = "joint_pos", +) -> torch.Tensor: + actions_full = getattr(env, "_locomanip_last_action", None) + if actions_full is None: + return torch.zeros((env.num_envs, action_dim), device=device, dtype=dtype) + + action_ids = _resolve_action_ids( + env, joint_ids, device, action_term_name=action_term_name) + if isinstance(action_ids, slice): + if actions_full.shape[-1] == action_dim: + return actions_full + return torch.zeros((env.num_envs, action_dim), device=device, dtype=dtype) + + if action_ids.numel() == 0: + return torch.zeros((env.num_envs, action_dim), device=device, dtype=dtype) + if (action_ids < 0).any(): + return torch.zeros((env.num_envs, action_dim), device=device, dtype=dtype) + + max_id = int(action_ids.max().item()) + if actions_full.shape[-1] <= max_id: + return torch.zeros((env.num_envs, action_dim), device=device, dtype=dtype) + return actions_full[:, action_ids] + + +def _tracking_prior_joint_dim(frame_obs_dim: int, include_base_lin_vel: bool = True) -> int: + velocity_dim = _TRACKING_PRIOR_ANG_VEL_DIM + if include_base_lin_vel: + velocity_dim += _TRACKING_PRIOR_LIN_VEL_DIM + residual = frame_obs_dim - velocity_dim + if residual <= 0 or residual % 3 != 0: + layout = ( + "[lin_vel, ang_vel, joint_pos, joint_vel, actions]" + if include_base_lin_vel + else "[ang_vel, joint_pos, joint_vel, actions]" + ) + raise ValueError( + f"Tracking prior frame dim is incompatible with {layout} layout: " + f"got {frame_obs_dim}." + ) + return residual // 3 + + +def tracking_prior_history_flat(frame_history: torch.Tensor, include_base_lin_vel: bool = True) -> torch.Tensor: + """Flatten [env, history, frame] tracking prior history using tracking-task term-major ordering.""" + + if frame_history.ndim != 3: + raise ValueError( + f"Expected tracking prior history with shape [N, H, D], got {tuple(frame_history.shape)}.") + + frame_dim = int(frame_history.shape[-1]) + joint_dim = _tracking_prior_joint_dim( + frame_dim, include_base_lin_vel=include_base_lin_vel) + lin_end = _TRACKING_PRIOR_LIN_VEL_DIM if include_base_lin_vel else 0 + ang_end = lin_end + _TRACKING_PRIOR_ANG_VEL_DIM + joint_pos_end = ang_end + joint_dim + joint_vel_end = joint_pos_end + joint_dim + + parts: list[torch.Tensor] = [] + if include_base_lin_vel: + parts.append(frame_history[..., :lin_end].reshape( + frame_history.shape[0], -1)) + parts.extend( + ( + frame_history[..., lin_end:ang_end].reshape( + frame_history.shape[0], -1), + frame_history[..., ang_end:joint_pos_end].reshape( + frame_history.shape[0], -1), + frame_history[..., joint_pos_end:joint_vel_end].reshape( + frame_history.shape[0], -1), + frame_history[..., joint_vel_end:].reshape( + frame_history.shape[0], -1), + ) + ) + return torch.cat(parts, dim=-1) + + +def _tracking_prior_frame_terms( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg, + noise_cfg: dict[str, tuple[float, float]] | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + lin_vel = base_lin_vel(env, asset_cfg=asset_cfg) + ang_vel = base_ang_vel(env, asset_cfg=asset_cfg) + joint_pos = joint_pos_rel(env, asset_cfg=asset_cfg) + joint_vel = joint_vel_rel(env, asset_cfg=asset_cfg) + if noise_cfg: + lin_vel = _add_uniform_noise(lin_vel, noise_cfg.get("lin_vel")) + ang_vel = _add_uniform_noise(ang_vel, noise_cfg.get("ang_vel")) + joint_pos = _add_uniform_noise(joint_pos, noise_cfg.get("joint_pos")) + joint_vel = _add_uniform_noise(joint_vel, noise_cfg.get("joint_vel")) + action_dim = joint_pos.shape[-1] + actions = _get_last_joint_actions( + env, + asset_cfg.joint_ids, + action_dim, + joint_pos.device, + joint_pos.dtype, + ) + return lin_vel, ang_vel, joint_pos, joint_vel, actions + + +def tracking_prior_proprio( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + noise_cfg: dict[str, tuple[float, float]] | None = None, + use_cache: bool = True, + include_base_lin_vel: bool = True, +) -> torch.Tensor: + """Proprioception stack expected by the humanoid prior (G1 tracking distill).""" + + cache_key = _tracking_prior_frame_cache_key( + asset_cfg, noise_cfg, include_base_lin_vel) + if use_cache: + cached = _get_cached_step_tensor(env, cache_key) + if cached is not None: + return cached + + lin_vel, ang_vel, joint_pos, joint_vel, actions = _tracking_prior_frame_terms( + env, + asset_cfg=asset_cfg, + noise_cfg=noise_cfg, + ) + if include_base_lin_vel: + obs = torch.cat((lin_vel, ang_vel, joint_pos, + joint_vel, actions), dim=-1) + else: + obs = torch.cat((ang_vel, joint_pos, joint_vel, actions), dim=-1) + if use_cache: + return _set_cached_step_tensor(env, cache_key, obs) + return obs + + +def reset_tracking_prior_history( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + noise_cfg: dict[str, tuple[float, float]] | None = None, + history_length: int = 5, + env_ids=None, + include_base_lin_vel: bool = True, +) -> None: + clear_prior_obs_step_cache(env) + cache_key = _tracking_prior_history_cache_key( + asset_cfg, noise_cfg, history_length, include_base_lin_vel) + history_state = getattr( + env, "_locomanip_tracking_prior_history_state", None) + if not isinstance(history_state, dict): + return + state = history_state.get(cache_key) + if not isinstance(state, dict): + return + + initialized = state.get("initialized") + frame_history = state.get("frame_history") + skip_update_once = state.get("skip_update_once") + if ( + not isinstance(initialized, torch.Tensor) + or not isinstance(frame_history, torch.Tensor) + or not isinstance(skip_update_once, torch.Tensor) + ): + return + + if env_ids is None: + env_ids_t = torch.arange( + env.num_envs, device=initialized.device, dtype=torch.long) + elif isinstance(env_ids, slice): + env_ids_t = torch.arange( + env.num_envs, device=initialized.device, dtype=torch.long)[env_ids] + else: + env_ids_t = torch.as_tensor( + env_ids, device=initialized.device, dtype=torch.long) + if env_ids_t.numel() == 0: + return + + initialized[env_ids_t] = False + frame_history[env_ids_t] = 0.0 + skip_update_once[env_ids_t] = False + state["last_step"] = None + + +def capture_tracking_prior_frame_history( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + noise_cfg: dict[str, tuple[float, float]] | None = None, + history_length: int = 5, + env_ids=None, + include_base_lin_vel: bool = True, +) -> torch.Tensor: + """Capture the raw [history, frame] tracking-prior state for the requested environments.""" + + history_length = max(1, int(history_length)) + _ = tracking_prior_history( + env, + asset_cfg=asset_cfg, + noise_cfg=noise_cfg, + history_length=history_length, + include_base_lin_vel=include_base_lin_vel, + ) + cache_key = _tracking_prior_history_cache_key( + asset_cfg, noise_cfg, history_length, include_base_lin_vel) + history_state = getattr( + env, "_locomanip_tracking_prior_history_state", None) + if not isinstance(history_state, dict): + return torch.zeros((0, history_length, 0), device=env.device) + + state = history_state.get(cache_key) + if not isinstance(state, dict): + return torch.zeros((0, history_length, 0), device=env.device) + + frame_history = state.get("frame_history") + if not isinstance(frame_history, torch.Tensor): + return torch.zeros((0, history_length, 0), device=env.device) + + env_ids_t = _resolve_env_ids_tensor( + env, env_ids, device=frame_history.device) + if env_ids_t.numel() == 0: + return frame_history[:0].clone() + return frame_history[env_ids_t].clone() + + +def restore_tracking_prior_frame_history( + env: ManagerBasedRLEnv, + frame_history: torch.Tensor, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + noise_cfg: dict[str, tuple[float, float]] | None = None, + history_length: int = 5, + env_ids=None, + mark_current_step: bool = True, + include_base_lin_vel: bool = True, +) -> None: + """Restore raw [history, frame] tracking-prior state for the requested environments.""" + + history_length = max(1, int(history_length)) + frame_history_t = torch.as_tensor( + frame_history, device=env.device, dtype=torch.float32) + if frame_history_t.ndim != 3: + raise ValueError( + f"Expected tracking prior frame history with shape [N, H, D], got {tuple(frame_history_t.shape)}." + ) + + env_ids_t = _resolve_env_ids_tensor( + env, env_ids, device=frame_history_t.device) + if env_ids_t.numel() == 0: + return + if frame_history_t.shape[0] != env_ids_t.numel(): + raise ValueError( + f"Frame history batch size ({frame_history_t.shape[0]}) does not match env_ids ({env_ids_t.numel()})." + ) + if frame_history_t.shape[1] != history_length: + raise ValueError( + f"Frame history length ({frame_history_t.shape[1]}) does not match requested history_length ({history_length})." + ) + + clear_prior_obs_step_cache(env) + cache_key = _tracking_prior_history_cache_key( + asset_cfg, noise_cfg, history_length, include_base_lin_vel) + dummy_frame = torch.zeros( + (env.num_envs, frame_history_t.shape[-1]), device=env.device, dtype=frame_history_t.dtype) + state = _tracking_prior_history_state( + env, cache_key, history_length, dummy_frame) + state["frame_history"][env_ids_t] = frame_history_t + state["initialized"][env_ids_t] = True + state["skip_update_once"][env_ids_t] = bool(mark_current_step) + state["last_step"] = None + + +def tracking_prior_history( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + noise_cfg: dict[str, tuple[float, float]] | None = None, + history_length: int = 5, + include_base_lin_vel: bool = True, +) -> torch.Tensor: + history_length = max(1, int(history_length)) + cache_key = _tracking_prior_history_cache_key( + asset_cfg, noise_cfg, history_length, include_base_lin_vel) + cached = _get_cached_step_tensor(env, cache_key) + if cached is not None: + return cached + + frame_obs = tracking_prior_proprio( + env, + asset_cfg=asset_cfg, + noise_cfg=noise_cfg, + include_base_lin_vel=include_base_lin_vel, + ) + state = _tracking_prior_history_state( + env, cache_key, history_length, frame_obs) + frame_history = state["frame_history"] + initialized = state["initialized"] + skip_update_once = state["skip_update_once"] + step_tag = _current_step_tag(env) + if state.get("last_step") != step_tag: + needs_init = ~initialized + skip_mask = skip_update_once.bool() + if needs_init.any(): + repeated = frame_obs[needs_init].unsqueeze( + 1).repeat(1, history_length, 1) + frame_history[needs_init] = repeated + initialized[needs_init] = True + active = ~(needs_init | skip_mask) + if active.any(): + frame_history[active, :-1] = frame_history[active, 1:].clone() + frame_history[active, -1] = frame_obs[active] + if skip_mask.any(): + skip_update_once[skip_mask] = False + state["last_step"] = step_tag + + history_obs = tracking_prior_history_flat( + frame_history, include_base_lin_vel=include_base_lin_vel) + return _set_cached_step_tensor(env, cache_key, history_obs) + + +class TrackingPriorHistoryTerm(ManagerTermBase): + """Stateful 5-step humanoid proprio history with tracking-task term-major flattening.""" + + def __init__(self, cfg, env): + super().__init__(cfg, env) + + def reset(self, env_ids=None): + params = getattr(self.cfg, "params", {}) if getattr( + self, "cfg", None) is not None else {} + asset_cfg = params.get("asset_cfg", SceneEntityCfg("robot")) + noise_cfg = params.get("noise_cfg") + history_length = params.get("history_length", 5) + include_base_lin_vel = params.get("include_base_lin_vel", True) + reset_tracking_prior_history( + self._env, + asset_cfg=asset_cfg, + noise_cfg=noise_cfg, + history_length=history_length, + env_ids=env_ids, + include_base_lin_vel=include_base_lin_vel, + ) + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + noise_cfg: dict[str, tuple[float, float]] | None = None, + history_length: int = 5, + include_base_lin_vel: bool = True, + ) -> torch.Tensor: + return tracking_prior_history( + env, + asset_cfg=asset_cfg, + noise_cfg=noise_cfg, + history_length=history_length, + include_base_lin_vel=include_base_lin_vel, + ) + + +def right_hand_proprio( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + wrist_body_name: str = "right_palm_link", + use_cache: bool = True, +) -> torch.Tensor: + """Right-hand proprioception stack for floating-hand priors (adds last action slice).""" + + cache_key = _right_hand_prior_cache_key(asset_cfg, wrist_body_name) + if use_cache: + cached = _get_cached_step_tensor(env, cache_key) + if cached is not None: + return cached + + asset: Articulation = env.scene[asset_cfg.name] + + # Cache the wrist index on the environment to avoid repeated lookups. + wrist_idx: int + cache_attr = "_locomanip_right_wrist_id" + if hasattr(env, cache_attr): + wrist_idx = int(getattr(env, cache_attr)) + else: + wrist_ids, _ = asset.find_bodies( + [wrist_body_name], preserve_order=True) + if len(wrist_ids) == 0: + raise RuntimeError( + f"Wrist body '{wrist_body_name}' not found on asset '{asset_cfg.name}'.") + wrist_idx = int(wrist_ids[0]) + setattr(env, cache_attr, wrist_idx) + + wrist_quat = asset.data.body_quat_w[:, wrist_idx] + wrist_lin_vel_b = quat_apply( + quat_inv(wrist_quat), asset.data.body_lin_vel_w[:, wrist_idx]) + wrist_ang_vel_b = quat_apply( + quat_inv(wrist_quat), asset.data.body_ang_vel_w[:, wrist_idx]) + + joint_pos_rel = asset.data.joint_pos[:, asset_cfg.joint_ids] - \ + asset.data.default_joint_pos[:, asset_cfg.joint_ids] + joint_vel_rel = asset.data.joint_vel[:, asset_cfg.joint_ids] - \ + asset.data.default_joint_vel[:, asset_cfg.joint_ids] + + action_dim = joint_pos_rel.shape[-1] + actions = _get_last_joint_actions( + env, + asset_cfg.joint_ids, + action_dim, + joint_pos_rel.device, + joint_pos_rel.dtype, + ) + obs = torch.cat((wrist_lin_vel_b, wrist_ang_vel_b, + joint_pos_rel, joint_vel_rel, actions), dim=-1) + if use_cache: + return _set_cached_step_tensor(env, cache_key, obs) + return obs + + +def object_pose_in_robot_frame( + env: ManagerBasedRLEnv, + target_cfg: SceneEntityCfg, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Relative pose of a target rigid object in the robot root frame (pos + first 2 rotation columns).""" + + robot: Articulation = env.scene[robot_cfg.name] + target = env.scene[target_cfg.name] + + rel_pos, rel_quat = subtract_frame_transforms( + robot.data.root_pos_w, + robot.data.root_quat_w, + target.data.root_pos_w, + target.data.root_quat_w, + ) + rel_rot_cols = matrix_from_quat( + rel_quat)[..., :2].reshape(env.num_envs, -1) + return torch.cat((rel_pos, rel_rot_cols), dim=-1) + + +def virtual_pose_in_robot_frame( + env: ManagerBasedRLEnv, + pos: tuple[float, float, float], + quat: tuple[float, float, float, float] = (1.0, 0.0, 0.0, 0.0), + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + robot: Articulation = env.scene[robot_cfg.name] + target_pos = torch.tensor(pos, device=robot.device, + dtype=robot.data.root_pos_w.dtype).unsqueeze(0) + target_pos = target_pos + env.scene.env_origins + target_quat = torch.tensor( + quat, device=robot.device, dtype=robot.data.root_quat_w.dtype).unsqueeze(0) + target_quat = target_quat.expand(env.num_envs, -1) + rel_pos, rel_quat = subtract_frame_transforms( + robot.data.root_pos_w, + robot.data.root_quat_w, + target_pos, + target_quat, + ) + rel_rot_cols = matrix_from_quat( + rel_quat)[..., :2].reshape(env.num_envs, -1) + return torch.cat((rel_pos, rel_rot_cols), dim=-1) + + +def cube_pose_in_hand_frame( + env: ManagerBasedRLEnv, + target_cfg: SceneEntityCfg, + hand_body_name: str = "right_palm_link", + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Cube pose relative to the right hand frame (pos + first 2 rotation columns).""" + + robot: Articulation = env.scene[robot_cfg.name] + target = env.scene[target_cfg.name] + + hand_idx = _resolve_body_index( + env, robot, hand_body_name, "_locomanip_right_hand_body_idx") + hand_pos = robot.data.body_pos_w[:, hand_idx] + hand_quat = robot.data.body_quat_w[:, hand_idx] + + rel_pos, rel_quat = subtract_frame_transforms( + hand_pos, + hand_quat, + target.data.root_pos_w, + target.data.root_quat_w, + ) + rel_rot_cols = matrix_from_quat( + rel_quat)[..., :2].reshape(env.num_envs, -1) + return torch.cat((rel_pos, rel_rot_cols), dim=-1) + + +def body_pose_in_robot_frame( + env: ManagerBasedRLEnv, + target_cfg: SceneEntityCfg, + body_name: str, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Relative pose of a named articulation body in the robot root frame.""" + + robot: Articulation = env.scene[robot_cfg.name] + target: Articulation = env.scene[target_cfg.name] + + body_idx = _resolve_body_index( + env, target, body_name, f"_locomanip_body_pose_robot_{target_cfg.name}_{body_name}") + rel_pos, rel_quat = subtract_frame_transforms( + robot.data.root_pos_w, + robot.data.root_quat_w, + target.data.body_pos_w[:, body_idx], + target.data.body_quat_w[:, body_idx], + ) + rel_rot_cols = matrix_from_quat( + rel_quat)[..., :2].reshape(env.num_envs, -1) + return torch.cat((rel_pos, rel_rot_cols), dim=-1) + + +def body_offset_pose_in_robot_frame( + env: ManagerBasedRLEnv, + target_cfg: SceneEntityCfg, + body_name: str, + local_pos: tuple[float, float, float], + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Relative pose of a local point on a named articulation body in the robot root frame.""" + + robot: Articulation = env.scene[robot_cfg.name] + target: Articulation = env.scene[target_cfg.name] + + body_idx = _resolve_body_index( + env, target, body_name, f"_locomanip_body_offset_pose_robot_{target_cfg.name}_{body_name}") + body_pos_w = target.data.body_pos_w[:, body_idx] + body_quat_w = target.data.body_quat_w[:, body_idx] + local_pos_t = torch.tensor( + local_pos, device=body_pos_w.device, dtype=body_pos_w.dtype).view(1, 3) + point_pos_w = body_pos_w + \ + quat_apply(body_quat_w, local_pos_t.expand(env.num_envs, -1)) + rel_pos, rel_quat = subtract_frame_transforms( + robot.data.root_pos_w, + robot.data.root_quat_w, + point_pos_w, + body_quat_w, + ) + rel_rot_cols = matrix_from_quat( + rel_quat)[..., :2].reshape(env.num_envs, -1) + return torch.cat((rel_pos, rel_rot_cols), dim=-1) + + +def body_pose_in_hand_frame( + env: ManagerBasedRLEnv, + target_cfg: SceneEntityCfg, + body_name: str, + hand_body_name: str = "right_palm_link", + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Relative pose of a named articulation body in the right-hand frame.""" + + robot: Articulation = env.scene[robot_cfg.name] + target: Articulation = env.scene[target_cfg.name] + + hand_idx = _resolve_body_index( + env, robot, hand_body_name, f"_locomanip_body_pose_hand_{robot_cfg.name}_{hand_body_name}") + body_idx = _resolve_body_index( + env, target, body_name, f"_locomanip_body_pose_hand_{target_cfg.name}_{body_name}") + rel_pos, rel_quat = subtract_frame_transforms( + robot.data.body_pos_w[:, hand_idx], + robot.data.body_quat_w[:, hand_idx], + target.data.body_pos_w[:, body_idx], + target.data.body_quat_w[:, body_idx], + ) + rel_rot_cols = matrix_from_quat( + rel_quat)[..., :2].reshape(env.num_envs, -1) + return torch.cat((rel_pos, rel_rot_cols), dim=-1) + + +def body_offset_pose_in_hand_frame( + env: ManagerBasedRLEnv, + target_cfg: SceneEntityCfg, + body_name: str, + local_pos: tuple[float, float, float], + hand_body_name: str = "right_palm_link", + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Relative pose of a local point on a named articulation body in the right-hand frame.""" + + robot: Articulation = env.scene[robot_cfg.name] + target: Articulation = env.scene[target_cfg.name] + + hand_idx = _resolve_body_index( + env, robot, hand_body_name, f"_locomanip_body_offset_pose_hand_{robot_cfg.name}_{hand_body_name}") + body_idx = _resolve_body_index( + env, target, body_name, f"_locomanip_body_offset_pose_hand_{target_cfg.name}_{body_name}") + body_pos_w = target.data.body_pos_w[:, body_idx] + body_quat_w = target.data.body_quat_w[:, body_idx] + local_pos_t = torch.tensor( + local_pos, device=body_pos_w.device, dtype=body_pos_w.dtype).view(1, 3) + point_pos_w = body_pos_w + \ + quat_apply(body_quat_w, local_pos_t.expand(env.num_envs, -1)) + rel_pos, rel_quat = subtract_frame_transforms( + robot.data.body_pos_w[:, hand_idx], + robot.data.body_quat_w[:, hand_idx], + point_pos_w, + body_quat_w, + ) + rel_rot_cols = matrix_from_quat( + rel_quat)[..., :2].reshape(env.num_envs, -1) + return torch.cat((rel_pos, rel_rot_cols), dim=-1) + + +def articulation_joint_state( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg, +) -> torch.Tensor: + """Selected articulation joint position and velocity.""" + + asset: Articulation = env.scene[asset_cfg.name] + joint_ids = getattr(asset_cfg, "joint_ids", None) + if isinstance(joint_ids, slice): + return torch.cat((asset.data.joint_pos[:, joint_ids], asset.data.joint_vel[:, joint_ids]), dim=-1) + if joint_ids is None: + joint_names = list(getattr(asset_cfg, "joint_names", ()) or ()) + cache_attr = f"_locomanip_articulation_joint_state_{asset_cfg.name}_{'_'.join(joint_names)}" + cached = getattr(env, cache_attr, None) + if isinstance(cached, torch.Tensor): + joint_ids_t = cached + else: + joint_ids, joint_found = asset.find_joints( + joint_names, preserve_order=True) + if len(joint_ids) != len(joint_names): + missing = sorted(set(joint_names) - set(joint_found)) + raise RuntimeError( + f"Missing joints on '{asset_cfg.name}': {missing}") + joint_ids_t = torch.as_tensor( + joint_ids, device=asset.data.joint_pos.device, dtype=torch.long) + setattr(env, cache_attr, joint_ids_t) + else: + joint_ids_t = torch.as_tensor( + joint_ids, device=asset.data.joint_pos.device, dtype=torch.long) + + return torch.cat((asset.data.joint_pos[:, joint_ids_t], asset.data.joint_vel[:, joint_ids_t]), dim=-1) + + +def fingertip_force_on_cube( + env: ManagerBasedRLEnv, + sensor_names: Iterable[str] | str | None = None, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + fingertip_body_names: tuple[str, ...] | list[str] = tuple( + RIGHT_HAND_TIP_NAMES), + force_scale: float | None = None, + force_clip: float | None = None, +) -> torch.Tensor: + """Net contact forces on right-hand fingertips; sensor is filtered to cube contacts. + """ + + sensors = getattr(env.scene, "sensors", {}) + sensor_list: list = [] + if isinstance(sensor_names, str): + sensor = sensors.get(sensor_names) if isinstance( + sensors, dict) else None + if sensor is not None: + sensor_list.append(sensor) + elif sensor_names is not None: + for name in sensor_names: + sensor = sensors.get(name) if isinstance(sensors, dict) else None + if sensor is not None: + sensor_list.append(sensor) + if len(sensor_list) == 0: + return torch.zeros((env.num_envs, len(fingertip_body_names) * 3), device=env.device) + + forces_accum = [] + for sensor in sensor_list: + forces = getattr(sensor.data, "force_matrix_w", None) + if forces is None: + forces = getattr(sensor.data, "force_matrix_w_history", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w", None) + if isinstance(forces, torch.Tensor): + forces = torch.nan_to_num(forces, nan=0.0, posinf=0.0, neginf=0.0) + forces = torch.nan_to_num(forces, nan=0.0, posinf=0.0, neginf=0.0) + if force_scale is not None and force_scale > 0.0: + forces = forces / float(force_scale) + if force_clip is not None and force_clip > 0.0: + clip = float(force_clip) + forces = torch.clamp(forces, -clip, clip) + if forces.ndim > 2: + forces = forces.reshape(env.num_envs, -1, 3).sum(dim=1) + forces_accum.append(forces) + if len(forces_accum) == 0: + return torch.zeros((env.num_envs, len(fingertip_body_names) * 3), device=env.device) + + forces_cat = torch.cat(forces_accum, dim=1) + return forces_cat.view(env.num_envs, -1) + + +def last_residual_latent( + env: ManagerBasedRLEnv, + action_term_name: str = "joint_pos", +) -> torch.Tensor: + """Last emitted residual latent (raw action) from the action term.""" + + try: + term = env.action_manager.get_term(action_term_name) + except Exception: + return torch.zeros((env.num_envs, 0), device=env.device) + raw = getattr(term, "raw_actions", None) + if isinstance(raw, torch.Tensor): + return raw + return torch.zeros((env.num_envs, 0), device=env.device) + + +def zero_last_residual_latent( + env: ManagerBasedRLEnv, + action_term_name: str = "joint_pos", +) -> torch.Tensor: + try: + term = env.action_manager.get_term(action_term_name) + except Exception: + return torch.zeros((env.num_envs, 0), device=env.device) + raw = getattr(term, "raw_actions", None) + if isinstance(raw, torch.Tensor): + return torch.zeros_like(raw) + action_dim = int(getattr(term, "action_dim", 0)) + return torch.zeros((env.num_envs, action_dim), device=env.device) + + +def zeros_obs(env: ManagerBasedRLEnv, dim: int) -> torch.Tensor: + """Constant zero observation of the given dim — used as a stub for obs terms + that an actor expects by name (e.g. CoordResidual's bottle/table terms) but + that aren't physically present in a minimal env.""" + return torch.zeros((env.num_envs, int(dim)), device=env.device) + + +def body_prior_mean( + env: ManagerBasedRLEnv, + action_term_name: str = "joint_pos", +) -> torch.Tensor: + """Current frozen body prior mean used by the residual action term.""" + + try: + term = env.action_manager.get_term(action_term_name) + except Exception: + return torch.zeros((env.num_envs, 0), device=env.device) + getter = getattr(term, "get_body_prior_mean", None) + if callable(getter): + value = getter() + if isinstance(value, torch.Tensor): + return value + return torch.zeros((env.num_envs, 0), device=env.device) + + +def hand_prior_mean( + env: ManagerBasedRLEnv, + action_term_name: str = "joint_pos", +) -> torch.Tensor: + """Current frozen hand prior mean used by the residual action term.""" + + try: + term = env.action_manager.get_term(action_term_name) + except Exception: + return torch.zeros((env.num_envs, 0), device=env.device) + getter = getattr(term, "get_hand_prior_mean", None) + if callable(getter): + value = getter() + if isinstance(value, torch.Tensor): + return value + return torch.zeros((env.num_envs, 0), device=env.device) + + +def stage_one_hot(env: ManagerBasedRLEnv, command_name: str) -> torch.Tensor: + """One-hot stage buffer from the locomanip stage command.""" + command = env.command_manager.get_term(command_name) + return command.command diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/rewards.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..14ea4e1db394a69f2d54c0a0ac2cf95403707291 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/rewards.py @@ -0,0 +1,1696 @@ +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.envs.mdp import base_ang_vel, base_lin_vel +from isaaclab.managers import SceneEntityCfg +from isaaclab.sensors import ContactSensor +from isaaclab.utils.math import quat_apply, quat_apply_inverse + +from coordex.tasks.locomanip.constants import RIGHT_HAND_TIP_NAMES + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def _sanitize_non_negative(value: torch.Tensor, clip_fill: float) -> torch.Tensor: + """Keep penalties finite and non-negative before optional clipping.""" + value = torch.nan_to_num(value, nan=float(clip_fill), posinf=float(clip_fill), neginf=0.0) + return torch.clamp(value, min=0.0) + + +def _stage_mask(command, stage_id) -> torch.Tensor: + if stage_id is None: + return torch.ones_like(command.stage_id, dtype=torch.float32) + if isinstance(stage_id, torch.Tensor): + stage_ids = stage_id.to(device=command.stage_id.device, dtype=command.stage_id.dtype).view(-1) + elif isinstance(stage_id, (list, tuple, set)): + if len(stage_id) == 0: + return torch.zeros_like(command.stage_id, dtype=torch.float32) + stage_ids = torch.tensor(list(stage_id), device=command.stage_id.device, dtype=command.stage_id.dtype) + else: + return (command.stage_id == int(stage_id)).float() + + if stage_ids.numel() == 1: + return (command.stage_id == int(stage_ids.item())).float() + return (command.stage_id[:, None] == stage_ids[None, :]).any(dim=-1).float() + + +def _reduce_joint_metric(values: torch.Tensor, aggregation: str) -> torch.Tensor: + """Reduce per-joint values into a single scalar per environment.""" + if values.ndim <= 1: + return values + if aggregation == "mean": + return values.mean(dim=-1) + if aggregation in ("max", "worst_joint"): + return values.max(dim=-1).values + if aggregation == "sum": + return values.sum(dim=-1) + raise ValueError(f"Unsupported joint aggregation '{aggregation}'. Expected one of: mean, max, sum.") + + +def _resolve_joint_indices(env: ManagerBasedRLEnv, asset, joint_names: list[str], cache_attr: str) -> torch.Tensor: + cached = getattr(env, cache_attr, None) + if isinstance(cached, torch.Tensor): + return cached + joint_ids, _ = asset.find_joints(joint_names, preserve_order=True) + if len(joint_ids) == 0: + raise RuntimeError(f"No joints found for patterns {joint_names}.") + joint_ids_tensor = torch.as_tensor(joint_ids, device=asset.data.joint_pos.device, dtype=torch.long) + setattr(env, cache_attr, joint_ids_tensor) + return joint_ids_tensor + + +def _resolve_body_index(env: ManagerBasedRLEnv, asset, body_name: str, cache_attr: str) -> int: + cached = getattr(env, cache_attr, None) + if cached is not None: + return int(cached) + body_ids, _ = asset.find_bodies([body_name], preserve_order=True) + if len(body_ids) == 0: + raise RuntimeError(f"Body '{body_name}' not found on asset '{asset.name}'.") + body_id = int(body_ids[0]) + setattr(env, cache_attr, body_id) + return body_id + + +def _resolve_body_indices(env: ManagerBasedRLEnv, asset, body_names: list[str], cache_attr: str) -> torch.Tensor: + cached = getattr(env, cache_attr, None) + if isinstance(cached, torch.Tensor): + return cached + body_ids, body_found = asset.find_bodies(body_names, preserve_order=True) + if len(body_ids) != len(body_names): + missing = sorted(set(body_names) - set(body_found)) + raise RuntimeError(f"Missing bodies on '{asset.name}': {missing}") + ids = torch.as_tensor(body_ids, device=asset.data.body_pos_w.device, dtype=torch.long) + setattr(env, cache_attr, ids) + return ids + + +def _get_contact_sensor_list(env: ManagerBasedRLEnv, sensor_names: Iterable[str] | str | None) -> list: + sensors = getattr(env.scene, "sensors", {}) + sensor_list: list = [] + if sensor_names is None: + return sensor_list + if isinstance(sensor_names, str): + sensor = sensors.get(sensor_names) if isinstance(sensors, dict) else None + if sensor is not None: + sensor_list.append(sensor) + return sensor_list + + for name in sensor_names: + sensor = sensors.get(name) if isinstance(sensors, dict) else None + if sensor is not None: + sensor_list.append(sensor) + return sensor_list + + +def _sensor_forces(sensor): + forces = getattr(sensor.data, "force_matrix_w", None) + if forces is None: + forces = getattr(sensor.data, "force_matrix_w_history", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w_history", None) + if isinstance(forces, torch.Tensor): + return torch.nan_to_num(forces, nan=0.0, posinf=0.0, neginf=0.0) + return None + + +def _cube_lift_from_reference( + env: ManagerBasedRLEnv, + command, + cube_name: str = "cube", + table_name: str | None = None, + table_top_offset: float | None = None, +) -> torch.Tensor: + cube = env.scene[cube_name] + if table_name is not None: + table = env.scene[table_name] + reference = table.data.root_pos_w[:, 2] + if table_top_offset is not None: + reference = reference + float(table_top_offset) + else: + reference = torch.as_tensor(command.cube_init_z, device=cube.data.root_pos_w.device, dtype=cube.data.root_pos_w.dtype) + if reference.ndim == 0: + reference = torch.full_like(cube.data.root_pos_w[:, 2], float(reference.item())) + else: + reference = reference.to(device=cube.data.root_pos_w.device, dtype=cube.data.root_pos_w.dtype) + + return torch.clamp(cube.data.root_pos_w[:, 2] - reference, min=0.0) + + +def _new_episode_mask(env: ManagerBasedRLEnv, command) -> torch.Tensor: + mask = torch.zeros(env.num_envs, device=env.device, dtype=torch.bool) + stage_steps = getattr(command, "_stage_steps", None) + if isinstance(stage_steps, torch.Tensor) and stage_steps.shape[0] == env.num_envs: + mask = mask | (stage_steps.to(device=env.device) <= 1) + episode_length_buf = getattr(env, "episode_length_buf", None) + if isinstance(episode_length_buf, torch.Tensor) and episode_length_buf.shape[0] == env.num_envs: + mask = mask | (episode_length_buf.to(device=env.device) <= 1) + return mask + + +def stage_transition_bonus(env: ManagerBasedRLEnv, command_name: str, bonus: float = 1.0) -> torch.Tensor: + """One-time bonus when the stage id increases.""" + + command = env.command_manager.get_term(command_name) + current_stage = command.stage_id + last_stage = getattr(env, "_locomanip_last_stage_reward_stage_id", None) + + if (not isinstance(last_stage, torch.Tensor)) or last_stage.shape != current_stage.shape: + env._locomanip_last_stage_reward_stage_id = current_stage.clone() + return torch.zeros_like(current_stage, dtype=torch.float32) + + progressed = (current_stage > last_stage).float() * bonus + env._locomanip_last_stage_reward_stage_id = current_stage.clone() + return progressed + + +def robot_object_distance_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + object_name: str = "cube", + target_distance: float = 0.45, + scale: float = 4.0, +) -> torch.Tensor: + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + obj = env.scene[object_name] + delta = robot.data.root_pos_w[:, :2] - obj.data.root_pos_w[:, :2] + dist = torch.norm(delta, dim=-1) + reward = torch.exp(-scale * (dist - target_distance).pow(2)) + return reward * _stage_mask(command, stage_id) + + +def robot_grasp_gated_forward_target_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + post_grasp_target_x: float = 2.0, + pre_grasp_target_x: float | None = None, + pre_grasp_x_offset: float = 0.0, + target_y: float | None = 0.0, + scale: float = 1.0, + cube_name: str = "bottle", +) -> torch.Tensor: + """Reward root x target tracking, switching target after grasp.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + root_xy = robot.data.root_pos_w[:, :2] - env.scene.env_origins[:, :2] + + if hasattr(command, "is_grasped"): + grasped = command.is_grasped().to(root_xy.dtype) + else: + grasped = torch.zeros(env.num_envs, device=env.device, dtype=root_xy.dtype) + + post_x = root_xy.new_full((env.num_envs,), float(post_grasp_target_x)) + if pre_grasp_target_x is not None: + pre_x = root_xy.new_full((env.num_envs,), float(pre_grasp_target_x)) + else: + cube = env.scene[cube_name] + pre_x = cube.data.root_pos_w[:, 0] - env.scene.env_origins[:, 0] + float(pre_grasp_x_offset) + + target_x = torch.where(grasped > 0.5, post_x, pre_x) + + x_error = root_xy[:, 0] - target_x + if target_y is None: + dist_sq = x_error.pow(2) + else: + y_error = root_xy[:, 1] - float(target_y) + dist_sq = x_error.pow(2) + y_error.pow(2) + reward = torch.exp(-float(scale) * dist_sq) + return reward * _stage_mask(command, stage_id) + + +def base_target_progress_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + target_name: str = "target_region", + speed_scale: float = 1.0, +) -> torch.Tensor: + """Reward world-frame root velocity projected toward a target object.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + target = env.scene[target_name] + delta_xy = target.data.root_pos_w[:, :2] - robot.data.root_pos_w[:, :2] + direction = delta_xy / (delta_xy.norm(dim=-1, keepdim=True) + 1.0e-6) + vel_xy = robot.data.root_lin_vel_w[:, :2] + progress = torch.sum(vel_xy * direction, dim=-1) + reward = torch.clamp(progress / float(speed_scale), min=0.0, max=1.0) + return reward * _stage_mask(command, stage_id) + + +def bottle_forward_progress_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "bottle", + speed_scale: float = 1.0, + require_grasp: bool = True, + min_lift: float | None = None, + table_name: str | None = None, + table_top_offset: float | None = None, +) -> torch.Tensor: + """Reward positive bottle velocity along env x, optionally gated by grasp/lift.""" + + command = env.command_manager.get_term(command_name) + cube = env.scene[cube_name] + root_lin_vel_w = getattr(getattr(cube, "data", None), "root_lin_vel_w", None) + if not isinstance(root_lin_vel_w, torch.Tensor): + reward = torch.zeros(env.num_envs, device=env.device) + else: + reward = torch.clamp(root_lin_vel_w[:, 0] / float(speed_scale), min=0.0, max=1.0) + + if require_grasp and hasattr(command, "is_grasped"): + reward = reward * command.is_grasped().to(reward.dtype) + + if min_lift is not None: + lift_height = _cube_lift_from_reference( + env, + command, + cube_name=cube_name, + table_name=table_name, + table_top_offset=table_top_offset, + ) + reward = reward * (lift_height > float(min_lift)).to(reward.dtype) + + return reward * _stage_mask(command, stage_id) + + +def bottle_upright_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + scale: float = 4.0, + gate_until_lift: float | None = None, +) -> torch.Tensor: + command = env.command_manager.get_term(command_name) + if hasattr(command, "bottle_upright_angle"): + angle = command.bottle_upright_angle() + else: + cube = env.scene[command.cfg.cube_name] + axis = cube.data.root_pos_w.new_tensor((0.0, 0.0, 1.0)).view(1, 3).expand(cube.data.root_quat_w.shape[0], -1) + world_axis = quat_apply(cube.data.root_quat_w, axis) + angle = torch.acos(world_axis[:, 2].clamp(-1.0, 1.0)) + reward = torch.exp(-float(scale) * angle.square()) + if gate_until_lift is not None: + cube = env.scene[getattr(command.cfg, "cube_name", "bottle")] + lift_height = cube.data.root_pos_w[:, 2] - command.cube_init_z + reward = reward * (lift_height <= float(gate_until_lift)).to(reward.dtype) + return reward * _stage_mask(command, stage_id) + + +def upright_orientation_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + std: float = 0.5, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + command = env.command_manager.get_term(command_name) + asset = env.scene[asset_cfg.name] + + body_ids = None + if getattr(asset_cfg, "body_names", None): + body_ids = _resolve_body_indices( + env, + asset, + list(asset_cfg.body_names), + "_locomanip_upright_orientation_body_ids", + ) + elif getattr(asset_cfg, "body_ids", None): + body_ids = asset_cfg.body_ids + + if body_ids is not None: + body_quat = asset.data.body_quat_w[:, body_ids] + if body_quat.ndim == 2: + body_quat = body_quat.unsqueeze(1) + gravity_dir = asset.data.GRAVITY_VEC_W.unsqueeze(1).expand(-1, body_quat.shape[1], -1) + projected = quat_apply_inverse(body_quat, gravity_dir) + xy_squared = torch.sum(projected[..., :2] ** 2, dim=-1) + if xy_squared.ndim > 1: + xy_squared = xy_squared.mean(dim=-1) + else: + xy_squared = torch.sum(asset.data.projected_gravity_b[:, :2] ** 2, dim=-1) + + reward = torch.exp(-xy_squared / (std * std)) + return reward * _stage_mask(command, stage_id) + + +def heading_forward_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + std: float = 0.3, + target_yaw: float = 0.0, +) -> torch.Tensor: + """Reward the robot root facing the configured yaw.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + forward_axis = torch.tensor((1.0, 0.0, 0.0), device=env.device).view(1, 3) + forward = quat_apply(robot.data.root_quat_w, forward_axis.expand(env.num_envs, -1)) + yaw = torch.atan2(forward[:, 1], forward[:, 0]) + error = yaw - float(target_yaw) + error = torch.atan2(torch.sin(error), torch.cos(error)) + reward = torch.exp(-error.pow(2) / (float(std) ** 2)) + return reward * _stage_mask(command, stage_id) + + +def root_y_below_zero_penalty( + env: ManagerBasedRLEnv, + command_name: str, + threshold: float = 0.0, + max_penalty: float | None = None, +) -> torch.Tensor: + """Penalty for root y drifting below the threshold in env frame.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + root_y = robot.data.root_pos_w[:, 1] - env.scene.env_origins[:, 1] + excess = (float(threshold) - root_y).clamp(min=0.0) + if max_penalty is not None and max_penalty > 0.0: + excess = excess.clamp(max=float(max_penalty)) + return excess + + +def heading_to_object_penalty( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + object_name: str = "cube", +) -> torch.Tensor: + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + obj = env.scene[object_name] + + delta = obj.data.root_pos_w[:, :2] - robot.data.root_pos_w[:, :2] + psi_obj = torch.atan2(delta[:, 1], delta[:, 0]) + + quat = robot.data.root_quat_w + w, x, y, z = quat[:, 0], quat[:, 1], quat[:, 2], quat[:, 3] + psi_robot = torch.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z)) + + diff = psi_obj - psi_robot + diff = torch.atan2(torch.sin(diff), torch.cos(diff)) + penalty = (diff / torch.pi) ** 2 + return penalty * _stage_mask(command, stage_id) + + +def right_hand_height_direction_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + hand_body: str = "right_palm_link", + fingertip_body_names: Iterable[str] | None = None, + target_name: str = "cube", + height_offset: float = 0.07, + height_scale: float = 40.0, + gate_far: float | None = 0.6, + gate_near: float | None = 0.45, +) -> torch.Tensor: + """Reward the hand mean position tracking a point above the cube.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + target = env.scene[target_name] + + hand_idx = _resolve_body_index(env, robot, hand_body, "_locomanip_rhand_height_dir_idx") + tip_ids = getattr(command, "fingertip_ids", None) + if not isinstance(tip_ids, torch.Tensor): + tip_names = list(fingertip_body_names) if fingertip_body_names is not None else list(RIGHT_HAND_TIP_NAMES) + tip_ids = _resolve_body_indices(env, robot, tip_names, "_locomanip_rhand_height_dir_tip_ids") + body_ids = torch.cat( + [torch.as_tensor([hand_idx], device=tip_ids.device, dtype=tip_ids.dtype), tip_ids], dim=0 + ) + hand_pos = robot.data.body_pos_w[:, body_ids].mean(dim=1) + target_pos = target.data.root_pos_w + target_pos = target_pos.clone() + target_pos[:, 2] = command.cube_init_z + height_offset + + pos_error_sq = torch.sum((hand_pos - target_pos) ** 2, dim=-1) + pos_reward = torch.exp(-height_scale * pos_error_sq) + gate = torch.ones_like(pos_reward) + + if gate_far is not None and gate_far > 0.0: + delta = robot.data.root_pos_w[:, :2] - target.data.root_pos_w[:, :2] + dist = torch.norm(delta, dim=-1) + if gate_near is not None and gate_far > gate_near: + gate = torch.clamp((float(gate_far) - dist) / (float(gate_far) - float(gate_near)), 0.0, 1.0) + else: + gate = (dist <= float(gate_far)).to(pos_reward.dtype) + pos_reward = pos_reward * gate + + return pos_reward * _stage_mask(command, stage_id) + + +def right_hand_prep_region_penalty( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + hand_body: str = "right_palm_link", + fingertip_body_names: Iterable[str] | None = None, + target_name: str = "cube", + xy_scale: float = 60.0, + z_scale: float = 20.0, +) -> torch.Tensor: + """Penalty for the hand mean position being outside the prep region.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + target = env.scene[target_name] + + hand_idx = _resolve_body_index(env, robot, hand_body, "_locomanip_rhand_prep_region_idx") + tip_ids = getattr(command, "fingertip_ids", None) + if not isinstance(tip_ids, torch.Tensor): + tip_names = list(fingertip_body_names) if fingertip_body_names is not None else list(RIGHT_HAND_TIP_NAMES) + tip_ids = _resolve_body_indices(env, robot, tip_names, "_locomanip_rhand_prep_region_tip_ids") + + body_ids = torch.cat( + [torch.as_tensor([hand_idx], device=tip_ids.device, dtype=tip_ids.dtype), tip_ids], dim=0 + ) + hand_pos = robot.data.body_pos_w[:, body_ids].mean(dim=1) + + hand_xy = hand_pos[:, :2] + target_xy = target.data.root_pos_w[:, :2] + hand_xy_dist = torch.norm(hand_xy - target_xy, dim=-1) + + xy_threshold = max(float(getattr(command, "_hand_prep_xy_threshold", 0.0)), 0.0) + if xy_threshold > 0.0: + xy_excess = torch.clamp(hand_xy_dist - xy_threshold, min=0.0) + else: + xy_excess = torch.zeros_like(hand_xy_dist) + + cube_ref = command.cube_init_z if hasattr(command, "cube_init_z") else target.data.root_pos_w[:, 2] + height_upper = cube_ref + float(getattr(command, "_hand_prep_height_offset", 0.125)) + z_excess = torch.clamp(hand_pos[:, 2] - height_upper, min=0.0) + + excess = float(xy_scale) * xy_excess.square() + float(z_scale) * z_excess.square() + penalty = 1.0 - torch.exp(-excess) + return penalty * _stage_mask(command, stage_id) + + +def right_hand_flat_penalty( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + hand_body: str = "right_palm_link", + angle_tolerance: float = 0.35, + scale: float = 8.0, + palm_axis: tuple[float, float, float] = (1.0, 0.0, 0.0), + target_name: str | None = None, + height_offset: float | None = None, + pos_gate_far: float | None = None, +) -> torch.Tensor: + """Bounded penalty for non-flat palm orientation.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + + hand_idx = _resolve_body_index(env, robot, hand_body, "_locomanip_rhand_flat_penalty_idx") + hand_quat = robot.data.body_quat_w[:, hand_idx] + + hand_palm_axis = hand_quat.new_tensor(palm_axis).view(1, 3).expand(hand_quat.shape[0], -1) + world_down = hand_palm_axis.new_tensor((0.0, 0.0, -1.0)).view(1, 3).expand(hand_quat.shape[0], -1) + + hand_normal = quat_apply(hand_quat, hand_palm_axis) + cos_angle = torch.clamp((hand_normal * world_down).sum(dim=-1), -1.0, 1.0) + angle = torch.acos(cos_angle) + penalty = 1.0 - torch.exp(-(angle / angle_tolerance) ** 2) + + if target_name is not None and pos_gate_far is not None and pos_gate_far > 0.0: + target = env.scene[target_name] + pos_dist = torch.norm(robot.data.root_pos_w[:, :2] - target.data.root_pos_w[:, :2], dim=-1) + pos_gate = (pos_dist <= float(pos_gate_far)).float() + penalty = penalty * pos_gate + + return penalty * _stage_mask(command, stage_id) + + +def base_lin_vel_excess( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + axis: int = 0, + threshold: float = 0.5, + max_penalty: float | None = None, +) -> torch.Tensor: + command = env.command_manager.get_term(command_name) + vel = base_lin_vel(env) + excess = torch.clamp(torch.abs(vel[:, axis]) - threshold, min=0.0) + excess = torch.nan_to_num(excess, nan=0.0, posinf=float(max_penalty) if max_penalty else 0.0) + if max_penalty is not None and max_penalty > 0.0: + excess = excess.clamp(max=float(max_penalty)) + return excess * _stage_mask(command, stage_id) + + +def base_ang_vel_excess( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + axis: int = 2, + threshold: float = 0.5, + max_penalty: float | None = None, +) -> torch.Tensor: + command = env.command_manager.get_term(command_name) + ang = base_ang_vel(env) + excess = torch.clamp(torch.abs(ang[:, axis]) - threshold, min=0.0) + excess = torch.nan_to_num(excess, nan=0.0, posinf=float(max_penalty) if max_penalty else 0.0) + if max_penalty is not None and max_penalty > 0.0: + excess = excess.clamp(max=float(max_penalty)) + return excess * _stage_mask(command, stage_id) + + +def base_velocity_l1( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + linear_axes: list[int] | tuple[int, ...] = (0, 1), + angular_axis: int | None = None, + soft_cap: float | None = None, + max_penalty: float | None = None, +) -> torch.Tensor: + command = env.command_manager.get_term(command_name) + vel = base_lin_vel(env) + if linear_axes: + lin = torch.sum(torch.abs(vel[:, list(linear_axes)]), dim=-1) + else: + lin = torch.zeros(env.num_envs, device=vel.device) + if angular_axis is not None: + ang = torch.abs(base_ang_vel(env)[:, angular_axis]) + lin = lin + ang + lin = torch.nan_to_num(lin, nan=0.0, posinf=float(soft_cap or max_penalty or 0.0), neginf=0.0) + if soft_cap is not None and soft_cap > 0.0: + lin = float(soft_cap) * torch.tanh(lin / float(soft_cap)) + if max_penalty is not None and max_penalty > 0.0: + lin = lin.clamp(max=float(max_penalty)) + return lin * _stage_mask(command, stage_id) + + +def hand_default_pose_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + asset_cfg: SceneEntityCfg, + tolerance: float = 0.01, + scale: float = 6.0, + progress_scale: float = 1.0, + progress_clip: float | None = None, + aggregation: str = "mean", + gate_pre_grasp: bool = False, +) -> torch.Tensor: + """Reward staying near and moving toward the default hand pose.""" + + command = env.command_manager.get_term(command_name) + stage_mask = _stage_mask(command, stage_id) + asset = env.scene[asset_cfg.name] + joint_ids = _resolve_joint_indices(env, asset, asset_cfg.joint_names, "_locomanip_hand_default_joint_ids") + joint_pos = asset.data.joint_pos[:, joint_ids] + default_pos = asset.data.default_joint_pos[:, joint_ids] + + deviation = torch.abs(joint_pos - default_pos) - float(tolerance) + deviation = torch.clamp(deviation, min=0.0) + reward_pos = torch.exp(-scale * _reduce_joint_metric(deviation, aggregation)) + + err = _reduce_joint_metric(torch.abs(joint_pos - default_pos), aggregation) + prev_err = getattr(env, "_locomanip_hand_default_prev_err", None) + if (not isinstance(prev_err, torch.Tensor)) or prev_err.shape != err.shape: + prev_err = err.detach().clone() + + reset_buf = getattr(env, "reset_buf", None) + if isinstance(reset_buf, torch.Tensor) and reset_buf.shape == err.shape: + prev_err = torch.where(reset_buf.bool(), err.detach(), prev_err) + + progress = prev_err - err + if progress_clip is not None and progress_clip > 0.0: + progress = progress.clamp(min=-float(progress_clip), max=float(progress_clip)) + reward_progress = progress_scale * progress + + env._locomanip_hand_default_prev_err = err.detach() + + reward = reward_pos + reward_progress + if gate_pre_grasp and hasattr(command, "is_grasped"): + reward = reward * (~command.is_grasped()).to(reward.dtype) + + return reward * stage_mask + + +def undesired_table_contacts( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + sensor_names: Iterable[str], + threshold: float = 1.0, +) -> torch.Tensor: + command = env.command_manager.get_term(command_name) + if isinstance(sensor_names, str): + sensor_names = [sensor_names] + + penalty = torch.zeros(env.num_envs, device=env.device) + for name in sensor_names: + sensor = env.scene.sensors[name] + forces = sensor.data.force_matrix_w_history + if forces is None: + forces = sensor.data.net_forces_w_history + if forces is None: + continue + contact = forces.norm(dim=-1) > threshold + in_contact = contact.any(dim=(1, 2)) + else: + contact = forces.norm(dim=-1) > threshold + in_contact = contact.any(dim=(1, 2, 3)) + penalty = penalty + in_contact.float() + + return penalty * _stage_mask(command, stage_id) + + +def termination_penalty(env: ManagerBasedRLEnv, term_name: str) -> torch.Tensor: + term_mgr = getattr(env, "termination_manager", None) + if term_mgr is None: + return torch.zeros(env.num_envs, device=env.device) + try: + term = term_mgr.get_term(term_name) + except KeyError: + return torch.zeros(env.num_envs, device=env.device) + return term.float() + + +def joint_action_rate_l2(env: ManagerBasedRLEnv, action_term_name: str = "joint_pos") -> torch.Tensor: + """Penalize the rate of change of decoded joint-space actions.""" + + actions = getattr(env, "_locomanip_last_action", None) + if actions is None: + actions = env.action_manager.get_term(action_term_name).processed_actions + + prev_actions = getattr(env, "_locomanip_prev_joint_action_rate_action", None) + if (not isinstance(prev_actions, torch.Tensor)) or prev_actions.shape != actions.shape: + env._locomanip_prev_joint_action_rate_action = actions.detach().clone() + return torch.zeros(actions.shape[0], device=actions.device, dtype=actions.dtype) + + reset_buf = getattr(env, "reset_buf", None) + if isinstance(reset_buf, torch.Tensor) and reset_buf.shape[0] == actions.shape[0]: + reset_mask = reset_buf.to(device=actions.device, dtype=torch.bool) + if reset_mask.any(): + prev_actions = prev_actions.clone() + prev_actions[reset_mask] = actions[reset_mask].detach() + + rate = torch.sum(torch.square(actions - prev_actions), dim=1) + env._locomanip_prev_joint_action_rate_action = actions.detach().clone() + return rate + + +def action_rate_l2_clipped( + env: ManagerBasedRLEnv, + clip_max: float = 100.0, +) -> torch.Tensor: + """Bound raw latent action-rate penalties to avoid catastrophic critic targets.""" + + from isaaclab.envs.mdp.rewards import action_rate_l2 as base_fn + + raw = _sanitize_non_negative(base_fn(env), clip_fill=clip_max) + return torch.clamp(raw, max=float(clip_max)) + + +def joint_action_rate_l2_clipped( + env: ManagerBasedRLEnv, + action_term_name: str = "joint_pos", + clip_max: float = 50.0, +) -> torch.Tensor: + """Bound decoded joint-action rate penalties while preserving normal-range gradients.""" + + raw = _sanitize_non_negative(joint_action_rate_l2(env, action_term_name=action_term_name), clip_fill=clip_max) + return torch.clamp(raw, max=float(clip_max)) + + +def joint_velocity_l2( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Penalize squared joint velocity magnitude over the selected joints.""" + + command = env.command_manager.get_term(command_name) + asset = env.scene[asset_cfg.name] + joint_ids = _resolve_joint_indices( + env, + asset, + list(asset_cfg.joint_names), + f"_locomanip_joint_velocity_l2_{asset_cfg.name}_{'_'.join(str(name) for name in asset_cfg.joint_names)}", + ) + joint_vel = asset.data.joint_vel[:, joint_ids] + penalty = torch.sum(torch.square(joint_vel), dim=-1) + return penalty * _stage_mask(command, stage_id) + + +def joint_velocity_l2_clipped( + env: ManagerBasedRLEnv, + command_name: str, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + stage_id=None, + clip_max: float = 200.0, +) -> torch.Tensor: + """Bound squared joint-velocity penalties to keep rare physics spikes finite.""" + + raw = _sanitize_non_negative( + joint_velocity_l2(env, command_name=command_name, stage_id=stage_id, asset_cfg=asset_cfg), + clip_fill=clip_max, + ) + return torch.clamp(raw, max=float(clip_max)) + + +def feet_slip_penalty( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + sensor_cfg: SceneEntityCfg, + threshold: float, +) -> torch.Tensor: + """Penalize horizontal foot sliding while the foot is in contact.""" + + command = env.command_manager.get_term(command_name) + contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] + net_forces = contact_sensor.data.net_forces_w[:, sensor_cfg.body_ids] + in_contact = net_forces.norm(dim=-1) > threshold + + robot = env.scene["robot"] + feet_vel = robot.data.body_lin_vel_w[:, sensor_cfg.body_ids] + slip_speed = torch.norm(feet_vel[..., :2], dim=-1) + penalty = (in_contact * slip_speed).sum(dim=-1) + return penalty * _stage_mask(command, stage_id) + + +def feet_slip_penalty_clipped( + env: ManagerBasedRLEnv, + command_name: str, + sensor_cfg: SceneEntityCfg, + threshold: float, + stage_id=None, + clip_max: float = 2.0, +) -> torch.Tensor: + """Bound foot-slip penalties so a single bad state cannot dominate returns.""" + + raw = _sanitize_non_negative( + feet_slip_penalty( + env, + command_name=command_name, + stage_id=stage_id, + sensor_cfg=sensor_cfg, + threshold=threshold, + ), + clip_fill=clip_max, + ) + return torch.clamp(raw, max=float(clip_max)) + + +def palm_facing_object_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "bottle", + hand_body: str = "right_palm_link", + palm_axis: tuple[float, float, float] = (1.0, 0.0, 0.0), + axis: str = "xy", + cos_cap: float = 1.0, + target_cos: float | None = None, + target_cos_std: float = 0.25, + gate_pre_grasp: bool = False, +) -> torch.Tensor: + """Reward the palm normal pointing toward the object.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + cube = env.scene[cube_name] + + hand_idx = _resolve_body_index(env, robot, hand_body, "_locomanip_palm_facing_idx") + hand_pos = robot.data.body_pos_w[:, hand_idx] + hand_quat = robot.data.body_quat_w[:, hand_idx] + + palm_axis_t = hand_quat.new_tensor(palm_axis).view(1, 3).expand(hand_quat.shape[0], -1) + palm_normal = quat_apply(hand_quat, palm_axis_t) + + h2o = cube.data.root_pos_w - hand_pos + if axis == "xy": + palm_n = palm_normal[:, :2] + h2o = h2o[:, :2] + else: + palm_n = palm_normal + palm_n = palm_n / (palm_n.norm(dim=-1, keepdim=True) + 1.0e-6) + h2o = h2o / (h2o.norm(dim=-1, keepdim=True) + 1.0e-6) + + cos_angle = (palm_n * h2o).sum(dim=-1) + if target_cos is not None: + reward = torch.exp(-(((cos_angle - float(target_cos)) / float(target_cos_std)) ** 2)) + else: + reward = torch.clamp(cos_angle, min=0.0, max=float(cos_cap)) + if gate_pre_grasp and hasattr(command, "is_grasped"): + reward = reward * (~command.is_grasped()).to(reward.dtype) + return reward * _stage_mask(command, stage_id) + + +def hand_cube_distance_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "cube", + fingertip_body_names: Iterable[str] = RIGHT_HAND_TIP_NAMES, + scale: float = 10.0, + distance_aggregation: str = "hybrid", +) -> torch.Tensor: + """Reward for keeping the specified hand bodies close to the cube.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + cube = env.scene[cube_name] + + fingertip_ids = _resolve_body_indices( + env, robot, list(fingertip_body_names), "_locomanip_fingertip_ids_reward" + ) + tip_pos = robot.data.body_pos_w[:, fingertip_ids] + cube_pos = cube.data.root_pos_w[:, None, :] + + dists = torch.norm(tip_pos - cube_pos, dim=-1) + if distance_aggregation == "mean": + agg_dist = dists.mean(dim=-1) + elif distance_aggregation == "softmin": + beta = 5.0 + agg_dist = -torch.logsumexp(-beta * dists, dim=-1) / beta + else: + mean_dist = dists.mean(dim=-1) + beta = 5.0 + softmin_dist = -torch.logsumexp(-beta * dists, dim=-1) / beta + agg_dist = 0.5 * mean_dist + 0.5 * softmin_dist + reward = torch.exp(-scale * agg_dist) + return reward * _stage_mask(command, stage_id) + + +def _aggregate_distance(dists: torch.Tensor, distance_aggregation: str) -> torch.Tensor: + """Aggregate a (N, K) per-body distance tensor to (N,).""" + if distance_aggregation == "mean": + return dists.mean(dim=-1) + if distance_aggregation == "softmin": + beta = 5.0 + return -torch.logsumexp(-beta * dists, dim=-1) / beta + mean_dist = dists.mean(dim=-1) + beta = 5.0 + softmin_dist = -torch.logsumexp(-beta * dists, dim=-1) / beta + return 0.5 * mean_dist + 0.5 * softmin_dist + + +def hand_cube_grasp_pose_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "cube", + body_groups: Sequence[Sequence[str]] = (), + target_distances: Sequence[float] = (), + scale: float = 10.0, + distance_aggregation: str = "mean", + group_aggregations: Sequence[str] | None = None, + group_modes: Sequence[str] | None = None, + body_overshoot_margin: float | None = None, + metric_name: str | None = None, +) -> torch.Tensor: + """Reward grouped hand bodies reaching configured object standoff distances.""" + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + cube = env.scene[cube_name] + + groups = [list(group) for group in body_groups] + targets = [float(t) for t in target_distances] + if len(groups) == 0: + raise ValueError("hand_cube_grasp_pose_reward requires at least one body group.") + if len(targets) != len(groups): + raise ValueError( + f"target_distances ({len(targets)}) must match body_groups ({len(groups)})." + ) + if group_modes is None: + modes = ["target"] * len(groups) + else: + modes = [str(m) for m in group_modes] + if len(modes) != len(groups): + raise ValueError( + f"group_modes ({len(modes)}) must match body_groups ({len(groups)})." + ) + for m in modes: + if m not in ("target", "monotonic"): + raise ValueError( + f"hand_cube_grasp_pose_reward: unknown group_mode '{m}' " + "(expected 'target' or 'monotonic')." + ) + + if group_aggregations is None: + aggregations = [distance_aggregation] * len(groups) + else: + aggregations = [str(a) for a in group_aggregations] + if len(aggregations) != len(groups): + raise ValueError( + f"group_aggregations ({len(aggregations)}) must match body_groups ({len(groups)})." + ) + + cube_pos = cube.data.root_pos_w[:, None, :] + per_group_reward: list[torch.Tensor] = [] + for group_index, (names, target, mode, agg) in enumerate( + zip(groups, targets, modes, aggregations) + ): + body_ids = _resolve_body_indices( + env, robot, names, f"_locomanip_grasp_pose_ids_{group_index}" + ) + body_pos = robot.data.body_pos_w[:, body_ids] + dists = torch.norm(body_pos - cube_pos, dim=-1) + agg_dist = _aggregate_distance(dists, agg) + if mode == "monotonic": + per_group_reward.append(torch.exp(-float(scale) * agg_dist)) + else: + per_group_reward.append(torch.exp(-float(scale) * (agg_dist - target).abs())) + if metric_name and hasattr(command, "metrics"): + command.metrics[f"{metric_name}_g{group_index}_dist"] = agg_dist.detach() + + reward = torch.stack(per_group_reward, dim=0).mean(dim=0) + + if body_overshoot_margin is not None: + overshoot = robot.data.root_pos_w[:, 0] - cube.data.root_pos_w[:, 0] + reward = reward * (overshoot <= float(body_overshoot_margin)).to(reward.dtype) + + return reward * _stage_mask(command, stage_id) + + +def hand_body_distance_reward( + env: ManagerBasedRLEnv, + command_name: str, + target_cfg: SceneEntityCfg, + target_body_name: str, + hand_body_names: Iterable[str], + stage_id=None, + target_body_local_pos: tuple[float, float, float] | None = None, + scale: float = 10.0, + distance_aggregation: str = "mean", +) -> torch.Tensor: + """Reward keeping selected hand bodies close to a target articulation body.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + target = env.scene[target_cfg.name] + + hand_body_names = list(hand_body_names) + hand_ids = _resolve_body_indices( + env, + robot, + hand_body_names, + f"_locomanip_hand_body_distance_ids_{'_'.join(hand_body_names)}", + ) + target_id = _resolve_body_index( + env, + target, + target_body_name, + f"_locomanip_target_body_distance_id_{target_cfg.name}_{target_body_name}", + ) + + hand_pos = robot.data.body_pos_w[:, hand_ids] + target_pos = target.data.body_pos_w[:, target_id] + if target_body_local_pos is not None: + local_pos = torch.tensor(target_body_local_pos, device=target_pos.device, dtype=target_pos.dtype).view(1, 3) + target_quat = target.data.body_quat_w[:, target_id] + target_pos = target_pos + quat_apply(target_quat, local_pos.expand(env.num_envs, -1)) + target_pos = target_pos.unsqueeze(1) + dists = torch.norm(hand_pos - target_pos, dim=-1) + if distance_aggregation == "mean": + agg_dist = dists.mean(dim=-1) + elif distance_aggregation == "softmin": + beta = 5.0 + agg_dist = -torch.logsumexp(-beta * dists, dim=-1) / beta + elif distance_aggregation in ("min", "closest"): + agg_dist = dists.min(dim=-1).values + else: + raise ValueError(f"Unsupported distance aggregation '{distance_aggregation}'.") + reward = torch.exp(-float(scale) * agg_dist) + return reward * _stage_mask(command, stage_id) + + +def fridge_door_open_progress_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + progress_scale: float = 0.02, + require_contact: bool = False, +) -> torch.Tensor: + """Reward positive per-step door opening progress.""" + + command = env.command_manager.get_term(command_name) + if hasattr(command, "door_open_progress"): + progress = command.door_open_progress() + else: + progress = torch.zeros(env.num_envs, device=env.device) + if progress_scale > 0.0: + progress = torch.clamp(progress / float(progress_scale), min=0.0, max=1.0) + if require_contact and hasattr(command, "fingertip_contact"): + contact = command.fingertip_contact() + if isinstance(contact, torch.Tensor) and contact.shape[0] == env.num_envs: + progress = progress * contact.to(progress.dtype) + return progress * _stage_mask(command, stage_id) + + +def fridge_door_close_regression_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + regression_scale: float = 0.02, +) -> torch.Tensor: + """Return positive per-step door closing regression.""" + + command = env.command_manager.get_term(command_name) + if hasattr(command, "door_close_regression"): + regression = command.door_close_regression() + else: + regression = torch.zeros(env.num_envs, device=env.device) + if regression_scale > 0.0: + regression = torch.clamp(regression / float(regression_scale), min=0.0, max=1.0) + return regression * _stage_mask(command, stage_id) + + +def base_backward_progress_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + speed_scale: float = 0.25, + require_contact: bool = False, +) -> torch.Tensor: + """Reward backward root velocity along the command retreat axis.""" + + command = env.command_manager.get_term(command_name) + if hasattr(command, "backward_velocity"): + backward_speed = command.backward_velocity() + else: + backward_speed = torch.zeros(env.num_envs, device=env.device) + if speed_scale > 0.0: + reward = torch.clamp(backward_speed / float(speed_scale), min=0.0, max=1.0) + else: + reward = torch.clamp(backward_speed, min=0.0) + if require_contact and hasattr(command, "fingertip_contact"): + contact = command.fingertip_contact() + if isinstance(contact, torch.Tensor) and contact.shape[0] == env.num_envs: + reward = reward * contact.to(reward.dtype) + return reward * _stage_mask(command, stage_id) + + +def fridge_door_held_open_reward( + env: ManagerBasedRLEnv, + command_name: str, + hold_angle: float, + stage_id=None, + max_seconds: float = 1.0, + require_contact: bool = True, +) -> torch.Tensor: + """Reward consecutive time with the door held open.""" + + command = env.command_manager.get_term(command_name) + if hasattr(command, "door_open_angle"): + angle = command.door_open_angle() + else: + angle = torch.zeros(env.num_envs, device=env.device) + held = angle >= float(hold_angle) + if require_contact and hasattr(command, "fingertip_contact"): + contact = command.fingertip_contact() + if isinstance(contact, torch.Tensor) and contact.shape[0] == env.num_envs: + held = held & contact.to(torch.bool) + + counter_attr = f"_locomanip_{command_name}_door_held_open_counter" + counter = getattr(env, counter_attr, None) + if not isinstance(counter, torch.Tensor) or counter.shape[0] != env.num_envs: + counter = torch.zeros(env.num_envs, device=env.device, dtype=torch.float32) + counter = torch.where(held, counter + float(env.step_dt), torch.zeros_like(counter)) + reset_buf = getattr(env, "reset_buf", None) + if isinstance(reset_buf, torch.Tensor) and reset_buf.shape == counter.shape: + counter = torch.where(reset_buf.bool(), torch.zeros_like(counter), counter) + setattr(env, counter_attr, counter.detach()) + + max_s = max(float(max_seconds), 1.0e-6) + reward = (counter / max_s).clamp(min=0.0, max=1.0) + return reward * _stage_mask(command, stage_id) + + +def fridge_door_open_with_contact_reward( + env: ManagerBasedRLEnv, + command_name: str, + target_angle: float, + stage_id=None, + power: float = 1.0, + contact_scale: float = 1.0, +) -> torch.Tensor: + """Reward door opening gated by fingertip contact.""" + + command = env.command_manager.get_term(command_name) + if hasattr(command, "door_open_angle"): + angle = command.door_open_angle() + else: + angle = torch.zeros(env.num_envs, device=env.device) + if target_angle <= 0.0: + return torch.zeros_like(angle) * _stage_mask(command, stage_id) + open_amount = torch.clamp(angle / float(target_angle), min=0.0, max=1.0) + if power != 1.0: + open_amount = torch.pow(open_amount, float(power)) + + if hasattr(command, "fingertip_contact_count"): + n_contact = command.fingertip_contact_count().to(open_amount.dtype) + elif hasattr(command, "fingertip_contact"): + contact = command.fingertip_contact() + if isinstance(contact, torch.Tensor) and contact.shape[0] == env.num_envs: + n_contact = contact.to(open_amount.dtype) + else: + n_contact = torch.zeros_like(open_amount) + else: + n_contact = torch.zeros_like(open_amount) + gate = (n_contact / max(float(contact_scale), 1.0e-6)).clamp(min=0.0, max=1.0) + return open_amount * gate * _stage_mask(command, stage_id) + + +def grasp_force_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + sensor_names: Iterable[str] | str | None = None, + fingertip_body_names: Iterable[str] = RIGHT_HAND_TIP_NAMES, + force_scale: float | None = None, + force_clip: float | None = None, + tanh_scale: float | None = 20.0, + max_force: float | None = 50.0, + aggregation: str = "sum", + output_clip: float | None = None, + gate_min_lift: float | None = None, + cube_name: str = "cube", + table_name: str | None = None, + table_top_offset: float | None = None, +) -> torch.Tensor: + """Reward fingertip contact force magnitudes.""" + + command = env.command_manager.get_term(command_name) + sensor_list = _get_contact_sensor_list(env, sensor_names) + if len(sensor_list) == 0: + return torch.zeros(env.num_envs, device=env.device) + + forces_accum = [] + for sensor in sensor_list: + forces = _sensor_forces(sensor) + if isinstance(forces, torch.Tensor): + magnitudes = forces.norm(dim=-1) + history_len = getattr(getattr(sensor, "cfg", None), "history_length", None) + if magnitudes.ndim >= 3 and history_len is not None and magnitudes.shape[1] == int(history_len): + magnitudes = magnitudes.mean(dim=1) + magnitudes_flat = magnitudes.view(magnitudes.shape[0], -1) + forces_accum.append(magnitudes_flat.sum(dim=-1)) + if len(forces_accum) == 0: + return torch.zeros(env.num_envs, device=env.device) + + stacked_forces = torch.stack(forces_accum, dim=0) + if aggregation == "sum": + force_sum = stacked_forces.sum(dim=0) + elif aggregation == "mean": + force_sum = stacked_forces.mean(dim=0) + else: + raise ValueError("aggregation must be 'sum' or 'mean'.") + if max_force is not None and max_force > 0.0: + force_sum = force_sum.clamp(max=float(max_force)) + if force_scale is not None and force_scale > 0.0: + force_sum = force_sum / float(force_scale) + if force_clip is not None and force_clip > 0.0: + clip = float(force_clip) + force_sum = torch.clamp(force_sum, -clip, clip) + if tanh_scale is not None and tanh_scale > 0.0: + force_sum = torch.tanh(force_sum / float(tanh_scale)) + if output_clip is not None and output_clip > 0.0: + force_sum = torch.clamp(force_sum, min=0.0, max=float(output_clip)) + if gate_min_lift is not None and gate_min_lift > 0.0: + lift = _cube_lift_from_reference( + env, + command, + cube_name=cube_name, + table_name=table_name, + table_top_offset=table_top_offset, + ) + force_sum = force_sum * (lift >= float(gate_min_lift)).to(force_sum.dtype) + return force_sum * _stage_mask(command, stage_id) + + +def grasp_based_on_obj_finger_dir_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "bottle", + thumb_body_name: str = RIGHT_HAND_TIP_NAMES[0], + index_body_names: Iterable[str] | str = RIGHT_HAND_TIP_NAMES[1], + normalize_to_unit: bool = False, + eps: float = 1.0e-6, + project_plane: str | None = None, + reward_shape: str = "cos", + gate_pre_grasp: bool = False, + gate_fingertip_cube_distance: float | None = None, + metric_name: str | None = None, +) -> torch.Tensor: + """Reward opposing thumb and finger directions around the object.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + cube = env.scene[cube_name] + + thumb_ids = getattr(env, "_locomanip_grasp_dir_thumb_ids", None) + if not isinstance(thumb_ids, torch.Tensor): + ids, found = robot.find_bodies([thumb_body_name], preserve_order=True) + if len(ids) != 1: + raise RuntimeError(f"Missing thumb body '{thumb_body_name}' for grasp direction reward. Found: {found}") + thumb_ids = torch.as_tensor(ids, device=robot.data.body_pos_w.device, dtype=torch.long) + setattr(env, "_locomanip_grasp_dir_thumb_ids", thumb_ids) + + if isinstance(index_body_names, str): + index_names = [index_body_names] + else: + index_names = list(index_body_names) + index_ids = getattr(env, "_locomanip_grasp_dir_index_ids", None) + if not isinstance(index_ids, torch.Tensor): + ids, found = robot.find_bodies(index_names, preserve_order=True) + if len(ids) != len(index_names): + missing = sorted(set(index_names) - set(found)) + raise RuntimeError(f"Missing index bodies for grasp direction reward: {missing}") + index_ids = torch.as_tensor(ids, device=robot.data.body_pos_w.device, dtype=torch.long) + setattr(env, "_locomanip_grasp_dir_index_ids", index_ids) + + obj_pos = cube.data.root_pos_w + thumb_pos = robot.data.body_pos_w[:, thumb_ids].mean(dim=1) + index_pos = robot.data.body_pos_w[:, index_ids].mean(dim=1) + obj_to_thumb = thumb_pos - obj_pos + obj_to_index = index_pos - obj_pos + if project_plane == "xy": + obj_to_thumb[:, 2] = 0.0 + obj_to_index[:, 2] = 0.0 + elif project_plane is not None: + raise ValueError( + f"grasp_based_on_obj_finger_dir_reward: unknown project_plane '{project_plane}'." + ) + obj_to_thumb = obj_to_thumb / (obj_to_thumb.norm(dim=-1, keepdim=True) + float(eps)) + obj_to_index = obj_to_index / (obj_to_index.norm(dim=-1, keepdim=True) + float(eps)) + cos_opp = torch.sum(obj_to_thumb * obj_to_index, dim=-1) + if reward_shape == "cos": + reward = -cos_opp + if normalize_to_unit: + reward = 0.5 * (reward + 1.0) + elif reward_shape == "angle": + theta = torch.acos(cos_opp.clamp(-1.0, 1.0)) + reward = theta / torch.pi + if not normalize_to_unit: + reward = 2.0 * reward - 1.0 + else: + raise ValueError( + f"grasp_based_on_obj_finger_dir_reward: unknown reward_shape '{reward_shape}'." + ) + + if metric_name and hasattr(command, "metrics"): + command.metrics[str(metric_name)] = cos_opp.detach() + + if gate_pre_grasp and hasattr(command, "is_grasped"): + reward = reward * (~command.is_grasped()).to(reward.dtype) + + if ( + gate_fingertip_cube_distance is not None + and gate_fingertip_cube_distance > 0.0 + and hasattr(command, "fingertip_mean_distance_to_cube") + ): + tip_dist = command.fingertip_mean_distance_to_cube() + reward = reward * (tip_dist >= float(gate_fingertip_cube_distance)).to(reward.dtype) + + return reward * _stage_mask(command, stage_id) + + +def fingertip_centroid_on_cube_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "bottle", + fingertip_body_names: Iterable[str] = RIGHT_HAND_TIP_NAMES, + decay_scale: float = 20.0, + gate_pre_grasp: bool = False, + gate_fingertip_cube_distance: float | None = None, + metric_name: str | None = None, +) -> torch.Tensor: + """Reward the fingertip centroid being close to the object.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + cube = env.scene[cube_name] + + tip_ids = _resolve_body_indices( + env, robot, list(fingertip_body_names), "_locomanip_fingertip_centroid_tip_ids" + ) + tip_pos = robot.data.body_pos_w[:, tip_ids] + centroid = tip_pos.mean(dim=1) + offset = torch.norm(centroid - cube.data.root_pos_w, dim=-1) + + reward = torch.exp(-float(decay_scale) * offset) + + if metric_name and hasattr(command, "metrics"): + command.metrics[str(metric_name)] = offset.detach() + + if gate_pre_grasp and hasattr(command, "is_grasped"): + reward = reward * (~command.is_grasped()).to(reward.dtype) + + if ( + gate_fingertip_cube_distance is not None + and gate_fingertip_cube_distance > 0.0 + and hasattr(command, "fingertip_mean_distance_to_cube") + ): + tip_dist = command.fingertip_mean_distance_to_cube() + reward = reward * (tip_dist >= float(gate_fingertip_cube_distance)).to(reward.dtype) + + return reward * _stage_mask(command, stage_id) + + +def fingertip_contact_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id=None, + sensor_names: Iterable[str] | str | None = None, + threshold: float = 1.0, + bonus_start_contacts: int | None = None, + bonus_scale: float = 0.0, + bonus_power: float = 2.0, + gate_min_lift: float | None = None, + cube_name: str = "cube", + table_name: str | None = None, + table_top_offset: float | None = None, +) -> torch.Tensor: + """Reward fingertip contact ratio with optional dexhand-style bonus and lift gate.""" + + command = env.command_manager.get_term(command_name) + if sensor_names is None: + contact = command.fingertip_contact() + if contact is None: + return torch.zeros(env.num_envs, device=env.device) + return contact.float() * _stage_mask(command, stage_id) + + sensor_list = _get_contact_sensor_list(env, sensor_names) + if len(sensor_list) == 0: + return torch.zeros(env.num_envs, device=env.device) + + contacts = [] + for sensor in sensor_list: + forces = _sensor_forces(sensor) + if not isinstance(forces, torch.Tensor): + continue + contact = forces.norm(dim=-1) > float(threshold) + in_contact = contact.view(contact.shape[0], -1).any(dim=-1) + contacts.append(in_contact.float()) + + if len(contacts) == 0: + return torch.zeros(env.num_envs, device=env.device) + + stacked = torch.stack(contacts, dim=0) + reward = stacked.mean(dim=0) + + if bonus_start_contacts is not None and bonus_scale > 0.0: + num_sensors = stacked.shape[0] + start_contacts = int(max(0, min(int(bonus_start_contacts), int(num_sensors)))) + if start_contacts < num_sensors: + contact_count = stacked.sum(dim=0) + surplus_contacts = torch.clamp(contact_count - float(start_contacts), min=0.0) + normalizer = float(max(1, num_sensors - start_contacts)) + reward = reward + float(bonus_scale) * torch.pow(surplus_contacts / normalizer, float(bonus_power)) + + if gate_min_lift is not None and gate_min_lift > 0.0: + lift = _cube_lift_from_reference( + env, + command, + cube_name=cube_name, + table_name=table_name, + table_top_offset=table_top_offset, + ) + reward = reward * (lift >= float(gate_min_lift)).to(reward.dtype) + + return reward * _stage_mask(command, stage_id) + + +def cube_lift_height_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "cube", + table_name: str | None = None, + table_top_offset: float | None = None, + cap: float = 0.15, + require_grasp: bool = True, + yank_penalty_beta: float | None = None, +) -> torch.Tensor: + """Reward lifting the object above its reference height.""" + + command = env.command_manager.get_term(command_name) + lift_height = _cube_lift_from_reference( + env, + command, + cube_name=cube_name, + table_name=table_name, + table_top_offset=table_top_offset, + ) + cap_t = torch.as_tensor(cap, device=lift_height.device, dtype=lift_height.dtype) + lift_height = torch.minimum(lift_height, cap_t) + if cap > 0.0: + reward = lift_height / cap_t + else: + reward = torch.zeros_like(lift_height) + if require_grasp: + reward = reward * command.is_grasped().float() + if yank_penalty_beta is not None and yank_penalty_beta > 0.0: + cube = env.scene[cube_name] + v_z = cube.data.root_lin_vel_w[:, 2] + yank_factor = torch.exp(-float(yank_penalty_beta) * v_z * v_z) + reward = reward * yank_factor + return reward * _stage_mask(command, stage_id) + + +def sustained_grasp_bonus_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "cube", + table_name: str | None = None, + table_top_offset: float | None = None, + max_seconds: float = 1.5, + min_lift: float | None = None, + min_forward_speed: float | None = None, +) -> torch.Tensor: + """Reward consecutive grasp duration, optionally gated by lift or forward motion.""" + + command = env.command_manager.get_term(command_name) + is_grasped = command.is_grasped() if hasattr(command, "is_grasped") else torch.zeros( + env.num_envs, device=env.device, dtype=torch.bool + ) + if min_lift is not None and min_lift > 0.0: + lift_height = _cube_lift_from_reference( + env, + command, + cube_name=cube_name, + table_name=table_name, + table_top_offset=table_top_offset, + ) + is_grasped = is_grasped & (lift_height > float(min_lift)) + if min_forward_speed is not None: + cube = env.scene[cube_name] + cube_vel = getattr(getattr(cube, "data", None), "root_lin_vel_w", None) + if isinstance(cube_vel, torch.Tensor): + is_grasped = is_grasped & (cube_vel[:, 0] > float(min_forward_speed)) + + step_dt = float(env.step_dt) + counter = getattr(env, "_locomanip_sustained_grasp_counter", None) + if not isinstance(counter, torch.Tensor) or counter.shape[0] != env.num_envs: + counter = torch.zeros(env.num_envs, device=env.device, dtype=torch.float32) + + counter = torch.where(is_grasped, counter + step_dt, torch.zeros_like(counter)) + + reset_buf = getattr(env, "reset_buf", None) + if isinstance(reset_buf, torch.Tensor) and reset_buf.shape == counter.shape: + counter = torch.where(reset_buf.bool(), torch.zeros_like(counter), counter) + + env._locomanip_sustained_grasp_counter = counter.detach() + + max_s = max(float(max_seconds), 1.0e-6) + reward = (counter / max_s).clamp(min=0.0, max=1.0) + return reward * _stage_mask(command, stage_id) + + +def object_hold_reward( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str | None = None, + table_name: str | None = None, + table_top_offset: float | None = None, + min_lift: float | None = None, +) -> torch.Tensor: + """Reward the current grasp predicate, optionally gated by object lift.""" + + command = env.command_manager.get_term(command_name) + if cube_name is None and table_name is None and table_top_offset is None and min_lift is None: + return command.is_grasped().float() * _stage_mask(command, stage_id) + if cube_name is None: + cube_name = "cube" + lift_height = _cube_lift_from_reference( + env, + command, + cube_name=cube_name, + table_name=table_name, + table_top_offset=table_top_offset, + ) + if min_lift is None: + min_lift = float(command.cfg.lift_height) + return command.is_grasped().float() * (lift_height > float(min_lift)).float() * _stage_mask(command, stage_id) + + +def cube_not_lifted_penalty( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "cube", + table_name: str | None = None, + table_top_offset: float | None = None, + target_lift: float = 0.1, + gate_fingertip_cube_distance: float | None = None, + gate_use_hand_root: bool = False, +) -> torch.Tensor: + """Penalty while the object remains close to its resting height.""" + + command = env.command_manager.get_term(command_name) + lift_height = _cube_lift_from_reference( + env, + command, + cube_name=cube_name, + table_name=table_name, + table_top_offset=table_top_offset, + ) + if target_lift <= 0.0: + penalty = torch.ones(env.num_envs, device=env.device) + else: + penalty = 1.0 - torch.clamp(lift_height / float(target_lift), min=0.0, max=1.0) + + if gate_fingertip_cube_distance is not None and gate_fingertip_cube_distance > 0.0: + gate_dist = None + if gate_use_hand_root and hasattr(command, "hand_root_mean_distance_to_cube"): + gate_dist = command.hand_root_mean_distance_to_cube() + if gate_dist is None and hasattr(command, "fingertip_mean_distance_to_cube"): + gate_dist = command.fingertip_mean_distance_to_cube() + if gate_dist is not None: + penalty = penalty * (gate_dist < float(gate_fingertip_cube_distance)).to(penalty.dtype) + + return penalty * _stage_mask(command, stage_id) + + +def cube_dropped_phase_penalty( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "bottle", + drop_height: float = 0.05, + min_lift_before_large_penalty: float = 0.02, + pre_lift_scale: float = 1.0, + post_lift_scale: float = 5.0, + sensor_names: Iterable[str] | str | None = None, + contact_threshold: float = 1.0, +) -> torch.Tensor: + """Penalty for dropping the object, with a larger value after it has been lifted once.""" + + command = env.command_manager.get_term(command_name) + cube = env.scene[cube_name] + cube_z = cube.data.root_pos_w[:, 2] + dropped = cube_z < (command.cube_init_z - float(drop_height)) + + if sensor_names is not None: + sensor_list = _get_contact_sensor_list(env, sensor_names) + if len(sensor_list) > 0: + in_contact = torch.zeros(env.num_envs, device=env.device, dtype=torch.bool) + for sensor in sensor_list: + forces = _sensor_forces(sensor) + if not isinstance(forces, torch.Tensor): + continue + contact = forces.norm(dim=-1) > float(contact_threshold) + in_contact = in_contact | contact.view(contact.shape[0], -1).any(dim=-1) + dropped = dropped & ~in_contact + + attr = f"_locomanip_{command_name}_{cube_name}_lifted_before_drop" + lifted_before = getattr(env, attr, None) + if not isinstance(lifted_before, torch.Tensor) or lifted_before.shape[0] != env.num_envs: + lifted_before = torch.zeros(env.num_envs, device=env.device, dtype=torch.bool) + else: + lifted_before = lifted_before.to(device=env.device, dtype=torch.bool) + lifted_before = torch.where(_new_episode_mask(env, command), torch.zeros_like(lifted_before), lifted_before) + + lifted_before = lifted_before | ((cube_z - command.cube_init_z) > float(min_lift_before_large_penalty)) + setattr(env, attr, lifted_before.detach()) + + penalty_scale = torch.where( + lifted_before, + torch.full_like(cube_z, float(post_lift_scale)), + torch.full_like(cube_z, float(pre_lift_scale)), + ) + return dropped.to(cube_z.dtype) * penalty_scale * _stage_mask(command, stage_id) + + +def cube_table_contact_move_penalty( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + sensor_name: str = "cube_table_contact", + cube_name: str = "cube", + threshold: float = 1.0, +) -> torch.Tensor: + """Penalize cube sliding on the table (xy speed when in contact).""" + + command = env.command_manager.get_term(command_name) + sensors = getattr(env.scene, "sensors", {}) + sensor = sensors.get(sensor_name) if isinstance(sensors, dict) else None + if sensor is None: + contact_mask = torch.zeros(env.num_envs, device=env.device) + else: + forces = getattr(sensor.data, "force_matrix_w_history", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w_history", None) + if forces is None: + forces = getattr(sensor.data, "force_matrix_w", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w", None) + if isinstance(forces, torch.Tensor): + contact = forces.norm(dim=-1) > threshold + if contact.ndim > 2: + contact = contact.any(dim=tuple(range(1, contact.ndim))) + contact_mask = contact.float() + else: + contact_mask = torch.zeros(env.num_envs, device=env.device) + + cube = env.scene[cube_name] + speed_xy = torch.norm(cube.data.root_lin_vel_w[:, :2], dim=-1) + penalty = speed_xy * contact_mask + return penalty * _stage_mask(command, stage_id) + + +def cube_hand_rel_move_penalty( + env: ManagerBasedRLEnv, + command_name: str, + stage_id, + cube_name: str = "cube", + hand_body: str = "right_palm_link", +) -> torch.Tensor: + """Penalize mismatch between cube and hand vertical velocity once the cube is grasped and lifted.""" + + command = env.command_manager.get_term(command_name) + robot = env.scene[command.cfg.asset_name] + cube = env.scene[cube_name] + + hand_idx = _resolve_body_index(env, robot, hand_body, "_locomanip_hand_body_idx") + hand_vel_z = robot.data.body_lin_vel_w[:, hand_idx, 2] + cube_vel_z = cube.data.root_lin_vel_w[:, 2] + + grasp_mask = (command.is_grasped() & command.is_lifted()).float() + penalty = torch.abs(cube_vel_z - hand_vel_z) * grasp_mask + return penalty * _stage_mask(command, stage_id) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/rsi.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/rsi.py new file mode 100644 index 0000000000000000000000000000000000000000..ecefaf8682e777ae359d759310e816a9d585bbb0 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/rsi.py @@ -0,0 +1,681 @@ +from __future__ import annotations + +from typing import Iterable + +import torch +from isaaclab.utils import configclass + +from coordex.tasks.locomanip.mdp.observations import ( + capture_tracking_prior_frame_history, + restore_tracking_prior_frame_history, +) + + +_RSI_SNAPSHOT_EXTRA_MARKER = -12345.0 +_RSI_SNAPSHOT_EXTRA_META_V1_DIM = 5 +_RSI_SNAPSHOT_EXTRA_META_V2_DIM = 8 +_RSI_SNAPSHOT_EXTRA_VERSION_V2 = 2.0 + + +@configclass +class NoDemoRSICfg: + enabled: bool = False + capacity_per_stage: int = 512 + min_samples_to_enable: tuple[int, ...] = (0, 128, 128, 128, 128) + p_stage0: float = 0.3 + stage_sampling_weight: tuple[float, ...] = (0.0, 1.0, 1.0, 1.0, 1.0) + alpha: float = 1.0 + adaptive_stage_sampling_enabled: bool = False + adaptive_stage_max: int = 3 + adaptive_stats_decay: float = 0.995 + adaptive_success_prior: float = 16.0 + adaptive_difficulty_power: float = 1.0 + adaptive_difficulty_floor: float = 0.10 + adaptive_consolidation_enter: float = 0.80 + adaptive_consolidation_exit: float = 0.75 + adaptive_consolidation_stage0_share: float = 0.85 + settle_steps: int = 3 + max_root_lin_vel: float | None = 0.4 + max_root_ang_vel: float | None = 0.75 + max_joint_vel: float | None = 10.0 + max_cube_lin_vel: float | None = 1.0 + max_cube_ang_vel: float | None = 1.0 + min_stage_steps_before_store: tuple[int, ...] = (0, 12, 6, 6, 6) + warmup_enabled: bool = True + warmup_mode: str = "reward_metric" + warmup_success_threshold: float = 0.6 + warmup_ramp_initial_share: float = 0.05 + warmup_ramp_attempts: int = 1000 + warmup_stage1_reward_key: str = "episode_reward/robot_object_distance" + warmup_stage1_threshold: float = 7.0 + warmup_stage2_reward_key: str = "episode_reward/cube_lift_height" + warmup_stage2_threshold: float = 1.0 + warmup_stage1_min_resets: int = 1000 + warmup_stage2_min_resets: int = 2000 + + +def _to_env_ids(env, env_ids: Iterable[int] | torch.Tensor | None) -> torch.Tensor: + if env_ids is None: + return torch.arange(env.scene.num_envs, device=env.device, dtype=torch.long) + if isinstance(env_ids, torch.Tensor): + return env_ids.to(device=env.device, dtype=torch.long) + return torch.as_tensor(list(env_ids), device=env.device, dtype=torch.long) + + +def _humanoid_prior_history_cfg(env) -> tuple[object | None, dict | None, int, bool]: + observations_cfg = getattr(env.cfg, "observations", None) + policy_cfg = getattr(observations_cfg, "policy", None) + term_cfg = getattr(policy_cfg, "humanoid_prior", None) + params = getattr(term_cfg, "params", {}) if term_cfg is not None else {} + if not isinstance(params, dict): + return None, None, 0, True + + asset_cfg = params.get("asset_cfg") + history_length = int(params.get("history_length", 0) or 0) + if asset_cfg is None or history_length <= 0: + return None, None, 0, True + return asset_cfg, params.get("noise_cfg"), history_length, bool(params.get("include_base_lin_vel", True)) + + +def _snapshot_action_term_name(env) -> str: + observations_cfg = getattr(env.cfg, "observations", None) + policy_cfg = getattr(observations_cfg, "policy", None) + term_cfg = getattr(policy_cfg, "last_latent", None) + params = getattr(term_cfg, "params", {}) if term_cfg is not None else {} + if isinstance(params, dict): + return str(params.get("action_term_name", "joint_pos")) + return "joint_pos" + + +def _capture_residual_action_aux_state( + env, + env_ids_t: torch.Tensor, + *, + action_term_name: str, +) -> dict[str, torch.Tensor]: + if env_ids_t.numel() == 0: + return {} + action_manager = getattr(env, "action_manager", None) + if action_manager is None: + return {} + try: + term = action_manager.get_term(action_term_name) + except Exception: + return {} + + getter = getattr(term, "capture_rsi_aux_state", None) + if callable(getter): + state = getter(env_ids_t) + return state if isinstance(state, dict) else {} + + state: dict[str, torch.Tensor] = {} + raw_actions = getattr(term, "raw_actions", None) + if isinstance(raw_actions, torch.Tensor) and raw_actions.ndim == 2 and raw_actions.shape[0] == env.scene.num_envs: + state["raw_actions"] = raw_actions[env_ids_t].detach( + ).clone().to(dtype=torch.float32) + hand_prev_targets = getattr(term, "_hand_prev_targets", None) + if ( + isinstance(hand_prev_targets, torch.Tensor) + and hand_prev_targets.ndim == 2 + and hand_prev_targets.shape[0] == env.scene.num_envs + ): + state["hand_prev_targets"] = hand_prev_targets[env_ids_t].detach( + ).clone().to(dtype=torch.float32) + return state + + +def _pending_obs_restore_state(env) -> dict: + state = getattr(env, "_no_demo_rsi_pending_obs_restore", None) + if not isinstance(state, dict): + state = {} + setattr(env, "_no_demo_rsi_pending_obs_restore", state) + return state + + +def _ensure_pending_tensor( + state: dict, + key: str, + shape: tuple[int, ...], + *, + device: torch.device, + dtype: torch.dtype, +) -> torch.Tensor: + tensor = state.get(key) + if not isinstance(tensor, torch.Tensor) or tensor.shape != shape or tensor.device != device or tensor.dtype != dtype: + tensor = torch.zeros(shape, device=device, dtype=dtype) + state[key] = tensor + return tensor + + +def _stash_locomanip_snapshot_aux_state( + env, + env_ids_t: torch.Tensor, + *, + last_action: torch.Tensor | None = None, + prior_frame_history: torch.Tensor | None = None, + stage1_ready_history: torch.Tensor | None = None, + raw_actions: torch.Tensor | None = None, + hand_prev_targets: torch.Tensor | None = None, +) -> None: + if env_ids_t.numel() == 0: + return + + state = _pending_obs_restore_state(env) + num_envs = int(env.scene.num_envs) + + last_action_valid = _ensure_pending_tensor( + state, + "last_action_valid", + (num_envs,), + device=env.device, + dtype=torch.bool, + ) + last_action_valid[env_ids_t] = False + if isinstance(last_action, torch.Tensor) and last_action.ndim == 2 and last_action.shape[0] == env_ids_t.numel(): + last_action_t = torch.as_tensor( + last_action, device=env.device, dtype=torch.float32) + last_action_buf = _ensure_pending_tensor( + state, + "last_action", + (num_envs, last_action_t.shape[1]), + device=env.device, + dtype=torch.float32, + ) + last_action_buf[env_ids_t] = last_action_t + last_action_valid[env_ids_t] = True + + prior_history_valid = _ensure_pending_tensor( + state, + "prior_history_valid", + (num_envs,), + device=env.device, + dtype=torch.bool, + ) + prior_history_valid[env_ids_t] = False + if ( + isinstance(prior_frame_history, torch.Tensor) + and prior_frame_history.ndim == 3 + and prior_frame_history.shape[0] == env_ids_t.numel() + ): + prior_frame_history_t = torch.as_tensor( + prior_frame_history, device=env.device, dtype=torch.float32) + prior_history_buf = _ensure_pending_tensor( + state, + "prior_history", + (num_envs, + prior_frame_history_t.shape[1], prior_frame_history_t.shape[2]), + device=env.device, + dtype=torch.float32, + ) + prior_history_buf[env_ids_t] = prior_frame_history_t + prior_history_valid[env_ids_t] = True + + stage1_ready_valid = _ensure_pending_tensor( + state, + "stage1_ready_history_valid", + (num_envs,), + device=env.device, + dtype=torch.bool, + ) + stage1_ready_valid[env_ids_t] = False + if ( + isinstance(stage1_ready_history, torch.Tensor) + and stage1_ready_history.ndim == 2 + and stage1_ready_history.shape[0] == env_ids_t.numel() + ): + ready_history_t = torch.as_tensor( + stage1_ready_history, device=env.device, dtype=torch.bool) + ready_history_buf = _ensure_pending_tensor( + state, + "stage1_ready_history", + (num_envs, ready_history_t.shape[1]), + device=env.device, + dtype=torch.bool, + ) + ready_history_buf[env_ids_t] = ready_history_t + stage1_ready_valid[env_ids_t] = True + + raw_actions_valid = _ensure_pending_tensor( + state, + "raw_actions_valid", + (num_envs,), + device=env.device, + dtype=torch.bool, + ) + raw_actions_valid[env_ids_t] = False + if isinstance(raw_actions, torch.Tensor) and raw_actions.ndim == 2 and raw_actions.shape[0] == env_ids_t.numel(): + raw_actions_t = torch.as_tensor( + raw_actions, device=env.device, dtype=torch.float32) + raw_actions_buf = _ensure_pending_tensor( + state, + "raw_actions", + (num_envs, raw_actions_t.shape[1]), + device=env.device, + dtype=torch.float32, + ) + raw_actions_buf[env_ids_t] = raw_actions_t + raw_actions_valid[env_ids_t] = True + + hand_prev_targets_valid = _ensure_pending_tensor( + state, + "hand_prev_targets_valid", + (num_envs,), + device=env.device, + dtype=torch.bool, + ) + hand_prev_targets_valid[env_ids_t] = False + if ( + isinstance(hand_prev_targets, torch.Tensor) + and hand_prev_targets.ndim == 2 + and hand_prev_targets.shape[0] == env_ids_t.numel() + ): + hand_prev_targets_t = torch.as_tensor( + hand_prev_targets, device=env.device, dtype=torch.float32) + hand_prev_targets_buf = _ensure_pending_tensor( + state, + "hand_prev_targets", + (num_envs, hand_prev_targets_t.shape[1]), + device=env.device, + dtype=torch.float32, + ) + hand_prev_targets_buf[env_ids_t] = hand_prev_targets_t + hand_prev_targets_valid[env_ids_t] = True + + +def restore_locomanip_snapshot_aux_state( + env, + env_ids: Iterable[int] | torch.Tensor | None, + *, + command=None, + action_term_name: str | None = None, +) -> None: + env_ids_t = _to_env_ids(env, env_ids) + if env_ids_t.numel() == 0: + return + + state = getattr(env, "_no_demo_rsi_pending_obs_restore", None) + if not isinstance(state, dict): + return + + last_action_valid = state.get("last_action_valid") + last_action = state.get("last_action") + env_last_action = getattr(env, "_locomanip_last_action", None) + if ( + isinstance(last_action_valid, torch.Tensor) + and isinstance(last_action, torch.Tensor) + and isinstance(env_last_action, torch.Tensor) + and env_last_action.ndim == 2 + and last_action.shape[1] == env_last_action.shape[1] + ): + restore_mask = last_action_valid[env_ids_t] + if restore_mask.any(): + env_restore = env_ids_t[restore_mask] + env_last_action[env_restore] = last_action[env_restore] + prev_actions = getattr( + env, "_locomanip_prev_joint_action_rate_action", None) + if isinstance(prev_actions, torch.Tensor) and prev_actions.shape == env_last_action.shape: + prev_actions[env_restore] = last_action[env_restore] + if isinstance(last_action_valid, torch.Tensor): + last_action_valid[env_ids_t] = False + + prior_history_valid = state.get("prior_history_valid") + prior_history = state.get("prior_history") + asset_cfg, noise_cfg, history_length, include_base_lin_vel = _humanoid_prior_history_cfg( + env) + if ( + isinstance(prior_history_valid, torch.Tensor) + and isinstance(prior_history, torch.Tensor) + and asset_cfg is not None + and history_length > 0 + and prior_history.shape[1] == history_length + ): + restore_mask = prior_history_valid[env_ids_t] + if restore_mask.any(): + env_restore = env_ids_t[restore_mask] + restore_tracking_prior_frame_history( + env, + prior_history[env_restore], + asset_cfg=asset_cfg, + noise_cfg=noise_cfg, + history_length=history_length, + env_ids=env_restore, + mark_current_step=True, + include_base_lin_vel=include_base_lin_vel, + ) + if isinstance(prior_history_valid, torch.Tensor): + prior_history_valid[env_ids_t] = False + + ready_history_valid = state.get("stage1_ready_history_valid") + ready_history = state.get("stage1_ready_history") + if ( + command is not None + and hasattr(command, "restore_stage1_ready_history") + and isinstance(ready_history_valid, torch.Tensor) + and isinstance(ready_history, torch.Tensor) + ): + restore_mask = ready_history_valid[env_ids_t] + if restore_mask.any(): + env_restore = env_ids_t[restore_mask] + command.restore_stage1_ready_history( + env_restore, ready_history[env_restore]) + if isinstance(ready_history_valid, torch.Tensor): + ready_history_valid[env_ids_t] = False + + raw_actions_valid = state.get("raw_actions_valid") + raw_actions = state.get("raw_actions") + hand_prev_targets_valid = state.get("hand_prev_targets_valid") + hand_prev_targets = state.get("hand_prev_targets") + restore_raw_actions = None + restore_hand_prev_targets = None + if ( + isinstance(raw_actions_valid, torch.Tensor) + and isinstance(raw_actions, torch.Tensor) + ): + restore_mask = raw_actions_valid[env_ids_t] + if restore_mask.any(): + env_restore = env_ids_t[restore_mask] + restore_raw_actions = raw_actions[env_restore] + if ( + isinstance(hand_prev_targets_valid, torch.Tensor) + and isinstance(hand_prev_targets, torch.Tensor) + ): + restore_mask = hand_prev_targets_valid[env_ids_t] + if restore_mask.any(): + env_restore = env_ids_t[restore_mask] + restore_hand_prev_targets = hand_prev_targets[env_restore] + + if restore_raw_actions is not None or restore_hand_prev_targets is not None: + action_manager = getattr(env, "action_manager", None) + term_name = _snapshot_action_term_name( + env) if action_term_name is None else action_term_name + if action_manager is not None: + try: + term = action_manager.get_term(term_name) + except Exception: + term = None + if term is not None: + restorer = getattr(term, "restore_rsi_aux_state", None) + if callable(restorer): + restore_mask = None + if restore_raw_actions is not None and isinstance(raw_actions_valid, torch.Tensor): + restore_mask = raw_actions_valid[env_ids_t] + elif restore_hand_prev_targets is not None and isinstance(hand_prev_targets_valid, torch.Tensor): + restore_mask = hand_prev_targets_valid[env_ids_t] + if isinstance(restore_mask, torch.Tensor): + env_restore = env_ids_t[restore_mask] + restorer( + env_restore, + raw_actions=restore_raw_actions, + hand_prev_targets=restore_hand_prev_targets, + ) + + if isinstance(raw_actions_valid, torch.Tensor): + raw_actions_valid[env_ids_t] = False + if isinstance(hand_prev_targets_valid, torch.Tensor): + hand_prev_targets_valid[env_ids_t] = False + + +def capture_locomanip_snapshot(env, env_ids: Iterable[int] | torch.Tensor | None, command_name: str = "stage") -> torch.Tensor: + """Capture robot + cube state along with stage metadata for the given environments.""" + env_ids_t = _to_env_ids(env, env_ids) + if env_ids_t.numel() == 0: + return torch.zeros((0, 0), device=env.device) + + command = env.command_manager.get_term(command_name) + robot = command.robot + cube = command.cube + env_origins = env.scene.env_origins[env_ids_t] + + robot_root_pos = robot.data.root_pos_w[env_ids_t] - env_origins + robot_root_quat = robot.data.root_quat_w[env_ids_t] + robot_lin_vel = robot.data.root_lin_vel_w[env_ids_t] + robot_ang_vel = robot.data.root_ang_vel_w[env_ids_t] + robot_root_state = torch.cat( + [robot_root_pos, robot_root_quat, robot_lin_vel, robot_ang_vel], dim=-1) + + robot_joint_pos = robot.data.joint_pos[env_ids_t] + robot_joint_vel = robot.data.joint_vel[env_ids_t] + + cube_root_pos = cube.data.root_pos_w[env_ids_t] - env_origins + cube_root_quat = cube.data.root_quat_w[env_ids_t] + cube_lin_vel = cube.data.root_lin_vel_w[env_ids_t] + cube_ang_vel = cube.data.root_ang_vel_w[env_ids_t] + cube_root_state = torch.cat( + [cube_root_pos, cube_root_quat, cube_lin_vel, cube_ang_vel], dim=-1) + + stage_id = command.stage_id[env_ids_t].to( + dtype=torch.float32).unsqueeze(-1) + cube_init_z = ( + command.cube_init_z[env_ids_t] - env_origins[:, 2]).unsqueeze(-1) + + snapshot_parts = [ + robot_root_state, + robot_joint_pos, + robot_joint_vel, + cube_root_state, + stage_id, + cube_init_z, + ] + meta = torch.zeros((_RSI_SNAPSHOT_EXTRA_META_V2_DIM,), + device=env.device, dtype=torch.float32) + meta[0] = _RSI_SNAPSHOT_EXTRA_MARKER + meta[1] = _RSI_SNAPSHOT_EXTRA_VERSION_V2 + + last_action = getattr(env, "_locomanip_last_action", None) + if isinstance(last_action, torch.Tensor) and last_action.ndim == 2 and last_action.shape[0] == env.scene.num_envs: + last_action_snapshot = last_action[env_ids_t].detach( + ).clone().to(dtype=torch.float32) + meta[2] = float(last_action_snapshot.shape[1]) + snapshot_parts.append(last_action_snapshot) + + asset_cfg, noise_cfg, history_length, include_base_lin_vel = _humanoid_prior_history_cfg( + env) + if asset_cfg is not None and history_length > 0: + prior_frame_history = capture_tracking_prior_frame_history( + env, + asset_cfg=asset_cfg, + noise_cfg=noise_cfg, + history_length=history_length, + env_ids=env_ids_t, + include_base_lin_vel=include_base_lin_vel, + ) + if prior_frame_history.numel() > 0: + meta[3] = float(prior_frame_history.shape[1]) + meta[4] = float(prior_frame_history.shape[2]) + snapshot_parts.append(prior_frame_history.reshape( + prior_frame_history.shape[0], -1)) + + stage1_ready_history = getattr( + command, "recent_stage1_ready_history", None) + if ( + isinstance(stage1_ready_history, torch.Tensor) + and stage1_ready_history.ndim == 2 + and stage1_ready_history.shape[0] == env.scene.num_envs + ): + stage1_ready_snapshot = stage1_ready_history[env_ids_t].to( + dtype=torch.float32) + meta[5] = float(stage1_ready_snapshot.shape[1]) + snapshot_parts.append(stage1_ready_snapshot) + + action_aux_state = _capture_residual_action_aux_state( + env, + env_ids_t, + action_term_name=_snapshot_action_term_name(env), + ) + raw_actions_snapshot = action_aux_state.get("raw_actions") + if isinstance(raw_actions_snapshot, torch.Tensor) and raw_actions_snapshot.ndim == 2: + meta[6] = float(raw_actions_snapshot.shape[1]) + snapshot_parts.append(raw_actions_snapshot) + hand_prev_targets_snapshot = action_aux_state.get("hand_prev_targets") + if isinstance(hand_prev_targets_snapshot, torch.Tensor) and hand_prev_targets_snapshot.ndim == 2: + meta[7] = float(hand_prev_targets_snapshot.shape[1]) + snapshot_parts.append(hand_prev_targets_snapshot) + + meta_batch = meta.unsqueeze(0).expand(env_ids_t.shape[0], -1) + snapshot_parts.append(meta_batch) + return torch.cat(snapshot_parts, dim=-1) + + +def apply_locomanip_snapshot( + env, + env_ids: Iterable[int] | torch.Tensor | None, + snapshot: torch.Tensor, + command_name: str = "stage", + reset_joint_targets: bool = True, +) -> None: + """Write a cached snapshot back into the simulator for the provided environments.""" + env_ids_t = _to_env_ids(env, env_ids) + if snapshot is None: + return + snap = torch.as_tensor(snapshot, device=env.device, dtype=torch.float32) + if snap.ndim == 1: + snap = snap.unsqueeze(0) + if snap.shape[0] != env_ids_t.numel(): + raise ValueError( + f"Snapshot batch size ({snap.shape[0]}) does not match env_ids ({env_ids_t.numel()})." + ) + + command = env.command_manager.get_term(command_name) + robot = command.robot + cube = command.cube + env_origins = env.scene.env_origins[env_ids_t] + num_joints = robot.num_joints + + idx = 0 + robot_root_state = snap[:, idx: idx + 13].clone() + idx += 13 + robot_joint_pos = snap[:, idx: idx + num_joints] + idx += num_joints + robot_joint_vel = snap[:, idx: idx + num_joints] + idx += num_joints + cube_root_state = snap[:, idx: idx + 13].clone() + idx += 13 + stage_id = snap[:, idx].to(dtype=torch.long) + idx += 1 + cube_init_z = snap[:, idx] + idx += 1 + + last_action = None + prior_frame_history = None + stage1_ready_history = None + raw_actions = None + hand_prev_targets = None + meta_dim = 0 + version = 0.0 + if snap.shape[1] >= idx + _RSI_SNAPSHOT_EXTRA_META_V2_DIM: + meta_v2 = snap[:, -_RSI_SNAPSHOT_EXTRA_META_V2_DIM:] + if float(meta_v2[0, 0].item()) == _RSI_SNAPSHOT_EXTRA_MARKER: + meta = meta_v2 + meta_dim = _RSI_SNAPSHOT_EXTRA_META_V2_DIM + version = float(meta[0, 1].item()) + else: + meta = None + else: + meta = None + + if meta is None and snap.shape[1] >= idx + _RSI_SNAPSHOT_EXTRA_META_V1_DIM: + meta_v1 = snap[:, -_RSI_SNAPSHOT_EXTRA_META_V1_DIM:] + if float(meta_v1[0, 0].item()) == _RSI_SNAPSHOT_EXTRA_MARKER: + meta = meta_v1 + meta_dim = _RSI_SNAPSHOT_EXTRA_META_V1_DIM + version = 1.0 + + if meta is not None: + if version >= _RSI_SNAPSHOT_EXTRA_VERSION_V2 and meta_dim == _RSI_SNAPSHOT_EXTRA_META_V2_DIM: + last_action_dim = max(0, int(round(float(meta[0, 2].item())))) + history_length = max(0, int(round(float(meta[0, 3].item())))) + frame_dim = max(0, int(round(float(meta[0, 4].item())))) + ready_history_length = max(0, int(round(float(meta[0, 5].item())))) + raw_action_dim = max(0, int(round(float(meta[0, 6].item())))) + hand_prev_targets_dim = max( + 0, int(round(float(meta[0, 7].item())))) + payload = snap[:, idx: snap.shape[1] - meta_dim] + expected_payload_dim = ( + last_action_dim + + history_length * frame_dim + + ready_history_length + + raw_action_dim + + hand_prev_targets_dim + ) + if payload.shape[1] != expected_payload_dim: + raise ValueError( + "Malformed RSI snapshot payload: " + f"expected {expected_payload_dim} aux values, got {payload.shape[1]}." + ) + payload_idx = 0 + if last_action_dim > 0: + last_action = payload[:, + payload_idx: payload_idx + last_action_dim] + payload_idx += last_action_dim + if history_length > 0 and frame_dim > 0: + history_flat_dim = history_length * frame_dim + prior_frame_history = payload[:, + payload_idx: payload_idx + history_flat_dim] + prior_frame_history = prior_frame_history.reshape( + snap.shape[0], history_length, frame_dim) + payload_idx += history_flat_dim + if ready_history_length > 0: + stage1_ready_history = payload[:, + payload_idx: payload_idx + ready_history_length] > 0.5 + payload_idx += ready_history_length + if raw_action_dim > 0: + raw_actions = payload[:, + payload_idx: payload_idx + raw_action_dim] + payload_idx += raw_action_dim + if hand_prev_targets_dim > 0: + hand_prev_targets = payload[:, + payload_idx: payload_idx + hand_prev_targets_dim] + else: + last_action_dim = max(0, int(round(float(meta[0, 1].item())))) + history_length = max(0, int(round(float(meta[0, 2].item())))) + frame_dim = max(0, int(round(float(meta[0, 3].item())))) + ready_history_length = max(0, int(round(float(meta[0, 4].item())))) + payload = snap[:, idx: snap.shape[1] - meta_dim] + expected_payload_dim = last_action_dim + \ + history_length * frame_dim + ready_history_length + if payload.shape[1] != expected_payload_dim: + raise ValueError( + "Malformed RSI snapshot payload: " + f"expected {expected_payload_dim} aux values, got {payload.shape[1]}." + ) + payload_idx = 0 + if last_action_dim > 0: + last_action = payload[:, + payload_idx: payload_idx + last_action_dim] + payload_idx += last_action_dim + if history_length > 0 and frame_dim > 0: + history_flat_dim = history_length * frame_dim + prior_frame_history = payload[:, + payload_idx: payload_idx + history_flat_dim] + prior_frame_history = prior_frame_history.reshape( + snap.shape[0], history_length, frame_dim) + payload_idx += history_flat_dim + if ready_history_length > 0: + stage1_ready_history = payload[:, + payload_idx: payload_idx + ready_history_length] > 0.5 + + robot_root_state[:, 0:3] += env_origins + cube_root_state[:, 0:3] += env_origins + cube_init_z_world = cube_init_z + env_origins[:, 2] + + robot.write_root_state_to_sim(robot_root_state, env_ids=env_ids_t) + robot.write_joint_state_to_sim( + robot_joint_pos, robot_joint_vel, env_ids=env_ids_t) + cube.write_root_state_to_sim(cube_root_state, env_ids=env_ids_t) + + if reset_joint_targets: + robot.set_joint_position_target(robot_joint_pos, env_ids=env_ids_t) + + robot.set_joint_velocity_target( + torch.zeros_like(robot_joint_vel), env_ids=env_ids_t) + + command.cube_init_z[env_ids_t] = cube_init_z_world + _stash_locomanip_snapshot_aux_state( + env, + env_ids_t, + last_action=last_action, + prior_frame_history=prior_frame_history, + stage1_ready_history=stage1_ready_history, + raw_actions=raw_actions, + hand_prev_targets=hand_prev_targets, + ) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/terminations.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/terminations.py new file mode 100644 index 0000000000000000000000000000000000000000..e01132f3d17a12d9f90502ff093024f116e05231 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/mdp/terminations.py @@ -0,0 +1,303 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Iterable + +import torch + +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils.math import quat_apply + +from coordex.tasks.locomanip.mdp.commands import LocomanipStageCommand + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def _get_command(env: ManagerBasedRLEnv, command_name: str) -> LocomanipStageCommand: + return env.command_manager.get_term(command_name) + + +def _get_contact_sensor_list(env: ManagerBasedRLEnv, sensor_names: Iterable[str] | str | None) -> list: + sensors = getattr(env.scene, "sensors", {}) + sensor_list: list = [] + if sensor_names is None: + return sensor_list + if isinstance(sensor_names, str): + sensor = sensors.get(sensor_names) if isinstance( + sensors, dict) else None + if sensor is not None: + sensor_list.append(sensor) + return sensor_list + + for name in sensor_names: + sensor = sensors.get(name) if isinstance(sensors, dict) else None + if sensor is not None: + sensor_list.append(sensor) + return sensor_list + + +def _sensor_forces(sensor): + forces = getattr(sensor.data, "force_matrix_w", None) + if forces is None: + forces = getattr(sensor.data, "force_matrix_w_history", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w", None) + if forces is None: + forces = getattr(sensor.data, "net_forces_w_history", None) + if isinstance(forces, torch.Tensor): + return torch.nan_to_num(forces, nan=0.0, posinf=0.0, neginf=0.0) + return None + + +def _new_episode_mask(env: ManagerBasedRLEnv, command: LocomanipStageCommand) -> torch.Tensor: + mask = torch.zeros(env.num_envs, device=env.device, dtype=torch.bool) + stage_steps = getattr(command, "_stage_steps", None) + if isinstance(stage_steps, torch.Tensor) and stage_steps.shape[0] == env.num_envs: + mask = mask | (stage_steps.to(device=env.device) <= 1) + episode_length_buf = getattr(env, "episode_length_buf", None) + if isinstance(episode_length_buf, torch.Tensor) and episode_length_buf.shape[0] == env.num_envs: + mask = mask | (episode_length_buf.to(device=env.device) <= 1) + return mask + + +def stage_success(env: ManagerBasedRLEnv, command_name: str) -> torch.Tensor: + command = _get_command(env, command_name) + if hasattr(command, "is_success"): + return command.is_success() + final_stage = int(command.cfg.num_stages) - 1 + success = command.is_cube_at_target() + return (command.stage_id == final_stage) & success + + +def cube_dropped( + env: ManagerBasedRLEnv, + command_name: str, + drop_height: float, + min_stage: int = 0, + sensor_names: Iterable[str] | str | None = None, + contact_threshold: float = 1.0, + min_lift_before_drop: float | None = None, + max_tilt_angle: float | None = None, +) -> torch.Tensor: + command = _get_command(env, command_name) + cube_z = command.cube.data.root_pos_w[:, 2] + threshold = command.cube_init_z - float(drop_height) + dropped = cube_z < threshold + + if sensor_names is not None: + sensor_list = _get_contact_sensor_list(env, sensor_names) + if len(sensor_list) > 0: + in_contact = torch.zeros( + env.num_envs, device=env.device, dtype=torch.bool) + for sensor in sensor_list: + forces = _sensor_forces(sensor) + if not isinstance(forces, torch.Tensor): + continue + contact = forces.norm(dim=-1) > float(contact_threshold) + in_contact = in_contact | contact.view( + contact.shape[0], -1).any(dim=-1) + dropped = dropped & ~in_contact + + if min_stage > 0: + dropped = dropped & (command.stage_id >= int(min_stage)) + if min_lift_before_drop is not None: + attr = f"_locomanip_{command_name}_{getattr(command.cfg, 'cube_name', 'cube')}_lifted_before_drop" + lifted_before = getattr(env, attr, None) + if not isinstance(lifted_before, torch.Tensor) or lifted_before.shape[0] != env.num_envs: + lifted_before = torch.zeros( + env.num_envs, device=env.device, dtype=torch.bool) + else: + lifted_before = lifted_before.to( + device=env.device, dtype=torch.bool) + lifted_before = torch.where(_new_episode_mask( + env, command), torch.zeros_like(lifted_before), lifted_before) + lifted_before = lifted_before | ( + (cube_z - command.cube_init_z) > float(min_lift_before_drop)) + setattr(env, attr, lifted_before.detach()) + dropped = dropped & lifted_before + + if max_tilt_angle is not None: + if hasattr(command, "bottle_upright_angle"): + tilt = command.bottle_upright_angle() + else: + cube = command.cube + up = cube.data.root_quat_w.new_tensor((0.0, 0.0, 1.0)).view( + 1, 3).expand(cube.data.root_quat_w.shape[0], -1) + world_up = quat_apply(cube.data.root_quat_w, up) + tilt = torch.acos(world_up[:, 2].clamp(-1.0, 1.0)) + dropped = dropped | (tilt > float(max_tilt_angle)) + + return dropped.to(torch.bool) + + +def hand_far_from_handle( + env: ManagerBasedRLEnv, + command_name: str, + max_distance: float = 0.5, + use_fingertip: bool = False, +) -> torch.Tensor: + """Terminate when the hand drifts too far from the manipulation target. + """ + + command = _get_command(env, command_name) + if use_fingertip and hasattr(command, "fingertip_handle_distance"): + dist = command.fingertip_handle_distance() + elif hasattr(command, "hand_handle_distance"): + dist = command.hand_handle_distance() + elif hasattr(command, "fingertip_handle_distance"): + dist = command.fingertip_handle_distance() + else: + return torch.zeros(env.num_envs, device=env.device, dtype=torch.bool) + return (dist > float(max_distance)).to(torch.bool) + + +def robot_passed_object_without_grasp( + env: ManagerBasedRLEnv, + command_name: str, + cube_name: str | None = None, + x_margin: float = 0.5, +) -> torch.Tensor: + """Terminate if the robot walks past the object before grasping it.""" + + command = _get_command(env, command_name) + robot = env.scene[command.cfg.asset_name] + object_name = cube_name or getattr(command.cfg, "cube_name", "bottle") + cube = env.scene[object_name] + + passed_object = robot.data.root_pos_w[:, 0] > ( + cube.data.root_pos_w[:, 0] + float(x_margin)) + if not hasattr(command, "is_grasped"): + raise RuntimeError( + f"Command term '{command_name}' does not expose an is_grasped() predicate.") + object_grasped = command.is_grasped().to(torch.bool) + return (passed_object & ~object_grasped).to(torch.bool) + + +def robot_fall( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg, + min_height: float, + body_name: str | None = None, +) -> torch.Tensor: + asset = env.scene[asset_cfg.name] + if body_name: + body_ids, _ = asset.find_bodies([body_name], preserve_order=True) + if len(body_ids) == 0: + raise RuntimeError( + f"Body '{body_name}' not found on asset '{asset_cfg.name}'.") + height = asset.data.body_pos_w[:, body_ids[0], 2] + elif getattr(asset_cfg, "body_names", None): + body_ids, _ = asset.find_bodies( + list(asset_cfg.body_names), preserve_order=True) + if len(body_ids) == 0: + raise RuntimeError( + f"No bodies found for {asset_cfg.body_names} on '{asset_cfg.name}'.") + height = asset.data.body_pos_w[:, body_ids[0], 2] + else: + height = asset.data.root_pos_w[:, 2] + return (height < float(min_height)).to(torch.bool) + + +def _get_root_state_tensor(env: ManagerBasedRLEnv, asset_name: str, attr_name: str) -> torch.Tensor: + asset = env.scene[asset_name] + data = getattr(asset, "data", None) + value = getattr(data, attr_name, None) if data is not None else None + if not isinstance(value, torch.Tensor): + raise RuntimeError( + f"Asset '{asset_name}' does not expose root state tensor '{attr_name}'.") + return value + + +def root_state_blowup( + env: ManagerBasedRLEnv, + asset_name: str, + max_xy_radius: float | None = None, + min_height: float | None = None, + max_height: float | None = None, + max_lin_vel: float | None = None, + max_ang_vel: float | None = None, +) -> torch.Tensor: + """Terminate when an asset root pose or velocity becomes non-finite or clearly unreasonable.""" + + root_pos_w = _get_root_state_tensor(env, asset_name, "root_pos_w") + env_origins = getattr(env.scene, "env_origins", None) + if isinstance(env_origins, torch.Tensor) and env_origins.shape == root_pos_w.shape: + rel_pos = root_pos_w - env_origins + else: + rel_pos = root_pos_w + + blowup = ~torch.isfinite(rel_pos).all(dim=-1) + + if max_xy_radius is not None: + xy_radius = torch.linalg.norm(torch.nan_to_num( + rel_pos[:, :2], nan=0.0, posinf=0.0, neginf=0.0), dim=-1) + blowup = blowup | (xy_radius > float(max_xy_radius)) + + z = rel_pos[:, 2] + blowup = blowup | ~torch.isfinite(z) + if min_height is not None: + blowup = blowup | (z < float(min_height)) + if max_height is not None: + blowup = blowup | (z > float(max_height)) + + if max_lin_vel is not None: + root_lin_vel_w = _get_root_state_tensor( + env, asset_name, "root_lin_vel_w") + blowup = blowup | ~torch.isfinite(root_lin_vel_w).all(dim=-1) + lin_speed = torch.linalg.norm( + torch.nan_to_num(root_lin_vel_w, nan=0.0, posinf=0.0, neginf=0.0), + dim=-1, + ) + blowup = blowup | (lin_speed > float(max_lin_vel)) + + if max_ang_vel is not None: + root_ang_vel_w = _get_root_state_tensor( + env, asset_name, "root_ang_vel_w") + blowup = blowup | ~torch.isfinite(root_ang_vel_w).all(dim=-1) + ang_speed = torch.linalg.norm( + torch.nan_to_num(root_ang_vel_w, nan=0.0, posinf=0.0, neginf=0.0), + dim=-1, + ) + blowup = blowup | (ang_speed > float(max_ang_vel)) + + return blowup.to(torch.bool) + + +def root_y_deviation( + env: ManagerBasedRLEnv, + asset_name: str = "robot", + max_abs_y: float = 1.5, +) -> torch.Tensor: + """Terminate when an asset root y position leaves the env-local corridor.""" + + root_pos_w = _get_root_state_tensor(env, asset_name, "root_pos_w") + env_origins = getattr(env.scene, "env_origins", None) + if isinstance(env_origins, torch.Tensor) and env_origins.shape == root_pos_w.shape: + rel_pos = root_pos_w - env_origins + else: + rel_pos = root_pos_w + + y = rel_pos[:, 1] + invalid = ~torch.isfinite(y) + abs_y = torch.abs(torch.nan_to_num(y, nan=0.0, posinf=0.0, neginf=0.0)) + return (invalid | (abs_y > float(max_abs_y))).to(torch.bool) + + +def joint_velocity_blowup( + env: ManagerBasedRLEnv, + asset_name: str = "robot", + max_abs_joint_vel: float = 40.0, +) -> torch.Tensor: + """Terminate when any joint velocity becomes non-finite or unrealistically large.""" + + asset = env.scene[asset_name] + joint_vel = getattr(getattr(asset, "data", None), "joint_vel", None) + if not isinstance(joint_vel, torch.Tensor): + raise RuntimeError( + f"Asset '{asset_name}' does not expose joint velocities.") + + blowup = ~torch.isfinite(joint_vel).all(dim=-1) + max_joint_speed = torch.abs(torch.nan_to_num( + joint_vel, nan=0.0, posinf=0.0, neginf=0.0)).max(dim=-1).values + blowup = blowup | (max_joint_speed > float(max_abs_joint_vel)) + return blowup.to(torch.bool) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/rsi_buffer.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/rsi_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..7d619c30cd0ff7d43ee74ee935e19d8f8a084128 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/rsi_buffer.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import torch + + +class NoDemoRSIBuffer: + """Simple per-stage ring buffer for reset state snapshots. + """ + + def __init__(self, num_stages: int, capacity_per_stage: int, device: str = "cpu"): + if num_stages <= 0: + raise ValueError(f"num_stages must be positive, got {num_stages}.") + if capacity_per_stage <= 0: + raise ValueError( + f"capacity_per_stage must be positive, got {capacity_per_stage}.") + self.num_stages = int(num_stages) + self.capacity_per_stage = int(capacity_per_stage) + self.storage_device = torch.device(device) + self.dtype = torch.float32 + + self._storage: list[torch.Tensor | None] = [None] * self.num_stages + self._write_ptr = torch.zeros(self.num_stages, dtype=torch.long) + self._size = torch.zeros(self.num_stages, dtype=torch.long) + self._add_count = torch.zeros(self.num_stages, dtype=torch.long) + + def add(self, stage: int, env_ids: torch.Tensor, snapshot: torch.Tensor) -> None: + """Insert snapshot(s) for a given stage.""" + stage_idx = int(stage) + if stage_idx < 0 or stage_idx >= self.num_stages: + return + if snapshot is None: + return + + _ = env_ids + + snap = snapshot.to(device=self.storage_device, dtype=self.dtype) + if snap.ndim == 1: + snap = snap.unsqueeze(0) + if snap.numel() == 0 or snap.shape[0] == 0: + return + + cap = self.capacity_per_stage + if snap.shape[0] > cap: + snap = snap[-cap:] + + if self._storage[stage_idx] is None or self._storage[stage_idx].shape[1] != snap.shape[1]: + self._storage[stage_idx] = torch.zeros( + (cap, snap.shape[1] + ), device=self.storage_device, dtype=self.dtype + ) + self._write_ptr[stage_idx] = 0 + self._size[stage_idx] = 0 + + size = int(self._size[stage_idx].item()) + ptr = int(self._write_ptr[stage_idx].item()) + count = snap.shape[0] + + # Build index tensor on the storage device to avoid cross-device indexing. + indices = (torch.arange(count, device=self.storage_device) + ptr) % cap + self._storage[stage_idx][indices] = snap + self._write_ptr[stage_idx] = (ptr + count) % cap + self._size[stage_idx] = min(cap, size + count) + self._add_count[stage_idx] += count + + def sample(self, stage: int, n: int, device: torch.device | str | None = None) -> torch.Tensor: + """Sample ``n`` snapshots (with replacement) from the buffer for the given stage.""" + stage_idx = int(stage) + if stage_idx < 0 or stage_idx >= self.num_stages: + raise IndexError(f"Stage index out of range: {stage_idx}.") + size = int(self._size[stage_idx].item()) + if size == 0: + raise RuntimeError( + f"No snapshots available for stage {stage_idx}.") + if self._storage[stage_idx] is None: + raise RuntimeError( + f"Storage for stage {stage_idx} not initialized.") + + n = int(n) + if n <= 0: + return torch.zeros( + (0, self._storage[stage_idx].shape[1]), dtype=self.dtype, device=self.storage_device + ) + + indices = torch.randint(0, size, (n,), device=self.storage_device) + samples = self._storage[stage_idx][indices] + + target_device = self.storage_device if device is None else torch.device( + device) + + return samples.to(device=target_device) + + def size(self, stage: int) -> int: + """Return the number of stored snapshots for a given stage.""" + stage_idx = int(stage) + if stage_idx < 0 or stage_idx >= self.num_stages: + return 0 + return int(self._size[stage_idx].item()) + + def sizes(self) -> torch.Tensor: + """Return a CPU tensor of sizes for all stages (no CUDA sync).""" + return self._size.clone() + + def add_count(self, stage: int) -> int: + """Return the cumulative number of inserted snapshots for a given stage.""" + stage_idx = int(stage) + if stage_idx < 0 or stage_idx >= self.num_stages: + return 0 + return int(self._add_count[stage_idx].item()) + + def add_counts(self) -> torch.Tensor: + """Return cumulative inserted snapshot counts for all stages.""" + return self._add_count.clone() diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/walkgrab_env_cfg.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/walkgrab_env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..a6d27bc61c20e4141b2b6a0d551e808cc7b8aa2e --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/walkgrab_env_cfg.py @@ -0,0 +1,673 @@ +"""WalkGrab environment for G1 Wuji.""" + +from __future__ import annotations + +from dataclasses import MISSING +import re +from pathlib import Path + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import ContactSensorCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass + +import coordex.tasks.locomanip.mdp as mdp +from coordex.robots.g1_wuji import G1_WUJI_ACTION_SCALE, G1_WUJI_CFG, WUJI_RH_ACTIVE_JOINT_NAMES +from coordex.tasks.locomanip.constants import MODE12_JOINT_ORDER, RIGHT_HAND_TIP_NAMES + + +REPO_ROOT = Path(__file__).resolve().parents[5] +FOOT_BODY_NAMES = ["left_ankle_roll_link", "right_ankle_roll_link"] + + +@configclass +class WalkgrabSceneCfg(InteractiveSceneCfg): + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="plane", + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + ), + visual_material=sim_utils.MdlFileCfg( + mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl", + project_uvw=True, + ), + ) + + robot: ArticulationCfg = MISSING + + table: RigidObjectCfg = RigidObjectCfg( + prim_path="/World/envs/env_.*/source_table", + spawn=sim_utils.CuboidCfg( + size=(0.25, 0.5, 0.04), + visual_material=sim_utils.MdlFileCfg( + mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Wood/Oak_Planks.mdl", + project_uvw=True, + ), + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + kinematic_enabled=True, + max_depenetration_velocity=1.0, + ), + collision_props=sim_utils.CollisionPropertiesCfg(), + visible=True, + ), + init_state=RigidObjectCfg.InitialStateCfg( + pos=(1.5, -0.55, 0.635), + rot=(1.0, 0.0, 0.0, 0.0), + ), + ) + + bottle: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Bottle", + spawn=sim_utils.CylinderCfg( + radius=0.035, + height=0.3, + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=16, + solver_velocity_iteration_count=4, + disable_gravity=False, + max_depenetration_velocity=1.0, + ), + collision_props=sim_utils.CollisionPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=0.1), + ), + init_state=RigidObjectCfg.InitialStateCfg( + pos=(1.5, -0.35, 0.730), + rot=(1.0, 0.0, 0.0, 0.0), + ), + ) + + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DistantLightCfg( + color=(0.75, 0.75, 0.75), intensity=3000.0), + ) + sky_light = AssetBaseCfg( + prim_path="/World/skyLight", + spawn=sim_utils.DomeLightCfg( + color=(0.13, 0.13, 0.13), intensity=1000.0), + ) + contact_forces = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*", + history_length=3, + track_air_time=True, + force_threshold=10.0, + debug_vis=False, + ) + contact_force_thumb = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger1_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Bottle"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_index = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger2_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Bottle"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_middle = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger3_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Bottle"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_ring = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger4_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Bottle"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_pinky = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger5_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Bottle"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_palm = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_palm_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Bottle"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + source_table_contact = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/source_table", + history_length=3, + track_air_time=True, + force_threshold=5.0, + debug_vis=False, + ) + + +@configclass +class ActionsCfg: + joint_pos = mdp.ResidualLatentActionCfg(asset_name="robot", joint_names=[ + ".*"], use_default_offset=True) + + +@configclass +class ObservationsCfg: + @configclass + class PolicyCfg(ObsGroup): + stage = ObsTerm(func=mdp.stage_one_hot, params={ + "command_name": "stage"}) + + projected_gravity = ObsTerm(func=mdp.projected_gravity) + + humanoid_prior = ObsTerm( + func=mdp.TrackingPriorHistoryTerm, + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=MODE12_JOINT_ORDER, preserve_order=True), + "noise_cfg": mdp.TRACKING_PRIOR_NOISE_CFG, + "history_length": 5, + }, + ) + + right_hand_prior = ObsTerm( + func=mdp.right_hand_proprio, + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=WUJI_RH_ACTIVE_JOINT_NAMES, preserve_order=True), + "wrist_body_name": "right_palm_link", + }, + ) + last_latent = ObsTerm( + func=mdp.last_residual_latent, + params={"action_term_name": "joint_pos"}, + ) + + fingertip_cube_forces = ObsTerm( + func=mdp.fingertip_force_on_cube, + params={ + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "asset_cfg": SceneEntityCfg("robot"), + "fingertip_body_names": RIGHT_HAND_TIP_NAMES, + "force_scale": 50.0, + "force_clip": 1.0, + }, + ) + + cube_pose = ObsTerm(func=mdp.object_pose_in_robot_frame, params={ + "target_cfg": SceneEntityCfg("bottle")}) + source_table_pose = ObsTerm( + func=mdp.object_pose_in_robot_frame, params={ + "target_cfg": SceneEntityCfg("table")} + ) + cube_pose_in_hand = ObsTerm( + func=mdp.cube_pose_in_hand_frame, + params={"target_cfg": SceneEntityCfg( + "bottle"), "hand_body_name": "right_palm_link"}, + ) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + @configclass + class CriticCfg(PolicyCfg): + def __post_init__(self): + self.enable_corruption = False + + policy: PolicyCfg = PolicyCfg() + critic: CriticCfg = CriticCfg() + + +@configclass +class CurriculumCfg: + pass + + +@configclass +class CommandsCfg: + stage = mdp.WalkgrabStageCommandCfg( + asset_name="robot", + cube_name="bottle", + source_table_name="table", + contact_sensor_name=[ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + "contact_force_palm", + ], + fingertip_body_names=RIGHT_HAND_TIP_NAMES, + hand_base_body_name="right_palm_link", + hand_joint_names=tuple(WUJI_RH_ACTIVE_JOINT_NAMES), + require_contact=True, + source_goal_name="bottle", + target_goal_name="bottle", + min_fingertip_contacts=2, + required_contact_sensors=("contact_force_thumb",), + grasp_distance_threshold=0.10, + lift_height=0.08, + success_root_x_threshold=2.0, + ) + + +@configclass +class RewardsCfg: + forward_target = RewTerm( + func=mdp.robot_grasp_gated_forward_target_reward, + weight=25.0, + params={ + "command_name": "stage", + "stage_id": [0], + "post_grasp_target_x": 2.0, + "pre_grasp_target_x": 2.0, + "target_y": 0.0, + "scale": 1.0, + "cube_name": "bottle", + }, + ) + + right_hand_pre_grasp_pos = None + + hand_bottle_distance = RewTerm( + func=mdp.hand_cube_grasp_pose_reward, + weight=50.0, + params={ + "command_name": "stage", + "stage_id": [0], + "cube_name": "bottle", + "body_groups": ( + [*RIGHT_HAND_TIP_NAMES, "right_palm_link"], + list(RIGHT_HAND_TIP_NAMES), + ), + "target_distances": (0.09, 0.046), + "scale": 8.5, + "distance_aggregation": "mean", + "group_aggregations": ("mean", "max"), + "group_modes": ("monotonic", "monotonic"), + "metric_name": "hand_bottle", + }, + ) + + palm_facing_object = RewTerm( + func=mdp.palm_facing_object_reward, + weight=15.0, + params={ + "command_name": "stage", + "stage_id": [0], + "cube_name": "bottle", + "hand_body": "right_palm_link", + "palm_axis": (1.0, 0.0, 0.0), + "axis": "xy", + "target_cos": 0.47, + "target_cos_std": 0.25, + "gate_pre_grasp": True, + }, + ) + + fingertip_contact = RewTerm( + func=mdp.fingertip_contact_reward, + weight=15.0, + params={ + "command_name": "stage", + "stage_id": [0], + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "threshold": 1.0, + "cube_name": "bottle", + }, + ) + + fingertip_centroid_on_cube = RewTerm( + func=mdp.fingertip_centroid_on_cube_reward, + weight=0.0, + params={ + "command_name": "stage", + "stage_id": [0], + "cube_name": "bottle", + "fingertip_body_names": RIGHT_HAND_TIP_NAMES, + "decay_scale": 20.0, + "gate_pre_grasp": True, + "metric_name": "fingertip_centroid_to_bottle", + }, + ) + + grasp_force = RewTerm( + func=mdp.grasp_force_reward, + weight=15.0, + params={ + "command_name": "stage", + "stage_id": [0], + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "fingertip_body_names": RIGHT_HAND_TIP_NAMES, + "aggregation": "mean", + "tanh_scale": None, + "max_force": None, + "output_clip": 2.0, + }, + ) + + grasp_based_on_obj_finger_dir = RewTerm( + func=mdp.grasp_based_on_obj_finger_dir_reward, + weight=40.0, + params={ + "command_name": "stage", + "stage_id": [0], + "cube_name": "bottle", + "thumb_body_name": RIGHT_HAND_TIP_NAMES[0], + "index_body_names": list(RIGHT_HAND_TIP_NAMES[1:]), + "normalize_to_unit": True, + "project_plane": "xy", + "reward_shape": "angle", + "gate_pre_grasp": False, + "metric_name": "thumb_oppose_cos", + }, + ) + + hand_aperture_preshape = None + + right_hand_qpos_tracking_front_object = None + right_hand_thumb_oppose = None + right_hand_others_open = None + + bottle_lift_height = RewTerm( + func=mdp.cube_lift_height_reward, + weight=100.0, + params={ + "command_name": "stage", + "stage_id": [0], + "cube_name": "bottle", + "cap": 0.05, + "require_grasp": True, + "yank_penalty_beta": 2.0, + }, + ) + + hold_bottle = RewTerm( + func=mdp.object_hold_reward, + weight=100.0, + params={ + "command_name": "stage", + "stage_id": [0], + }, + ) + + sustained_grasp_bonus = RewTerm( + func=mdp.sustained_grasp_bonus_reward, + weight=100.0, + params={ + "command_name": "stage", + "stage_id": [0], + "cube_name": "bottle", + "max_seconds": 1.5, + "min_lift": 0.01, + }, + ) + + bottle_forward_progress = RewTerm( + func=mdp.bottle_forward_progress_reward, + weight=100.0, + params={ + "command_name": "stage", + "stage_id": [0], + "cube_name": "bottle", + "speed_scale": 1.0, + "require_grasp": True, + "min_lift": 0.01, + }, + ) + + bottle_upright_pre_lift = RewTerm( + func=mdp.bottle_upright_reward, + weight=0.0, + params={"command_name": "stage", "stage_id": [ + 0], "scale": 4.0, "gate_until_lift": 0.01}, + ) + + upright_orientation = RewTerm( + func=mdp.upright_orientation_reward, + weight=5.0, + params={ + "command_name": "stage", + "stage_id": [0], + "std": 0.2, + "asset_cfg": SceneEntityCfg("robot", body_names="torso_link"), + }, + ) + + heading_forward = RewTerm( + func=mdp.heading_forward_reward, + weight=10.0, + params={"command_name": "stage", "stage_id": [ + 0], "std": 0.3, "target_yaw": 0.0}, + ) + + root_y_below_zero_penalty = RewTerm( + func=mdp.root_y_below_zero_penalty, + weight=-10.0, + params={"command_name": "stage", "threshold": 0.0, "max_penalty": 0.5}, + ) + + success_bonus = RewTerm( + func=mdp.termination_penalty, + weight=500.0, + params={"term_name": "success"}, + ) + + action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-1.0e-2) + undesired_table_contacts = RewTerm( + func=mdp.undesired_table_contacts, + weight=-20.0, + params={ + "command_name": "stage", + "stage_id": [0], + "sensor_names": ["source_table_contact"], + "threshold": 5.0, + }, + ) + robot_fall_penalty = RewTerm( + func=mdp.termination_penalty, + weight=-10.0, + params={"term_name": "robot_fall"}, + ) + time_out_penalty = RewTerm( + func=mdp.termination_penalty, + weight=-20.0, + params={"term_name": "time_out"}, + ) + bottle_dropped_penalty = RewTerm( + func=mdp.cube_dropped_phase_penalty, + weight=-1.0, + params={ + "command_name": "stage", + "stage_id": [0], + "cube_name": "bottle", + "drop_height": 0.05, + "min_lift_before_large_penalty": 0.02, + "pre_lift_scale": 0.0, + "post_lift_scale": 5.0, + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "contact_threshold": 1.0, + }, + ) + passed_without_grasp_penalty = RewTerm( + func=mdp.termination_penalty, + weight=-20.0, + params={"term_name": "robot_passed_bottle_without_grasp"}, + ) + + +@configclass +class EventCfg: + reset_scene = EventTerm( + func=mdp.reset_scene_to_default, + mode="reset", + params={"reset_joint_targets": True}, + ) + physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*"), + "static_friction_range": (0.3, 1.0), + "dynamic_friction_range": (0.3, 1.0), + "restitution_range": (0.0, 0.1), + "num_buckets": 64, + }, + ) + base_com = EventTerm( + func=mdp.randomize_rigid_body_com, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names="torso_link"), + "com_range": {"x": (-0.025, 0.025), "y": (-0.05, 0.05), "z": (-0.05, 0.05)}, + }, + ) + + +@configclass +class TerminationsCfg: + time_out = DoneTerm(func=mdp.time_out, time_out=True) + success = DoneTerm(func=mdp.stage_success, params={ + "command_name": "stage"}) + bottle_dropped = DoneTerm( + func=mdp.cube_dropped, + params={ + "command_name": "stage", + "drop_height": 0.05, + "min_stage": 0, + "min_lift_before_drop": 0.02, + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "contact_threshold": 1.0, + }, + ) + robot_fall = DoneTerm( + func=mdp.robot_fall, + params={"asset_cfg": SceneEntityCfg( + "robot"), "body_name": "torso_link", "min_height": 0.35}, + ) + robot_y_deviation = DoneTerm( + func=mdp.root_y_deviation, + params={"asset_name": "robot", "max_abs_y": 0.5}, + ) + robot_passed_bottle_without_grasp = DoneTerm( + func=mdp.robot_passed_object_without_grasp, + params={"command_name": "stage", + "cube_name": "bottle", "x_margin": 0.5}, + ) + robot_root_state_blowup = DoneTerm( + func=mdp.root_state_blowup, + params={"asset_name": "robot", "max_xy_radius": 6.0, + "max_height": 3.0, "max_lin_vel": 10.0, "max_ang_vel": 20.0}, + ) + + +@configclass +class WalkgrabEnvCfg(ManagerBasedRLEnvCfg): + scene: WalkgrabSceneCfg = WalkgrabSceneCfg(num_envs=4096, env_spacing=5.0) + commands: CommandsCfg = CommandsCfg() + actions: ActionsCfg = ActionsCfg() + observations: ObservationsCfg = ObservationsCfg() + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + curriculum: CurriculumCfg = CurriculumCfg() + events: EventCfg = EventCfg() + + def __post_init__(self): + + self.decimation = 4 + self.episode_length_s = 15.0 + self.sim.dt = 1.0 / (60.0 * 4) + self.sim.render_interval = self.decimation + self.sim.physics_material = self.scene.terrain.physics_material + self.sim.physx.gpu_max_rigid_patch_count = 10 * 2**15 + self.viewer.eye = (1.5, 1.5, 1.5) + self.viewer.origin_type = "asset_root" + self.viewer.asset_name = "robot" + self.scene.robot = G1_WUJI_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot") + action_joint_names = MODE12_JOINT_ORDER + \ + list(WUJI_RH_ACTIVE_JOINT_NAMES) + action_scale = dict(G1_WUJI_ACTION_SCALE) + for joint_name in WUJI_RH_ACTIVE_JOINT_NAMES: + action_scale.setdefault(joint_name, 0.1) + + action = self.actions.joint_pos + action.scale = { + pattern: value + for pattern, value in action_scale.items() + if any(re.fullmatch(pattern, joint_name) for joint_name in action_joint_names) + } + action.joint_names = action_joint_names + action.preserve_order = True + action.clip_actions = False + action.body_prior_checkpoint = str( + REPO_ROOT / "ckpts/body_prior/walkgrab_10k.pt") + action.hand_prior_checkpoint = str( + REPO_ROOT / "ckpts/hand_prior/kinematic_wrist_16k.pt") + action.body_obs_norm_mode = "rsl_rl" + action.hand_action_moving_average = 0.4 + action.hand_joint_names = tuple(WUJI_RH_ACTIVE_JOINT_NAMES) + action.hand_wrist_body_name = "right_palm_link" + action.hand_prior_variant = "wuji_floating_kinematic_wrist" + + for obs_group in (self.observations.policy, self.observations.critic): + obs_group.humanoid_prior.params["include_base_lin_vel"] = False + + self.observations.policy.body_prior_mean = ObsTerm( + func=mdp.body_prior_mean, + params={"action_term_name": "joint_pos"}, + ) + self.observations.policy.hand_prior_mean = ObsTerm( + func=mdp.hand_prior_mean, + params={"action_term_name": "joint_pos"}, + ) diff --git a/third-party/coordex/source/coordex/coordex/tasks/locomanip/walkpickturn_env_cfg.py b/third-party/coordex/source/coordex/coordex/tasks/locomanip/walkpickturn_env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..c56763c33d9494a4a168d1aae7437d2392ec5a23 --- /dev/null +++ b/third-party/coordex/source/coordex/coordex/tasks/locomanip/walkpickturn_env_cfg.py @@ -0,0 +1,764 @@ +from __future__ import annotations + +from dataclasses import MISSING +import re +from pathlib import Path + +import isaaclab.sim as sim_utils +import torch +from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import ContactSensorCfg +from isaaclab.terrains import TerrainImporterCfg + +from isaaclab.utils import configclass +from isaaclab.utils.noise import AdditiveUniformNoiseCfg as Unoise + +import coordex.tasks.locomanip.mdp as mdp +from coordex.robots.g1_wuji import G1_WUJI_ACTION_SCALE, G1_WUJI_CFG, WUJI_RH_ACTIVE_JOINT_NAMES +from coordex.tasks.locomanip.constants import ( + MODE12_JOINT_ORDER, + RIGHT_HAND_TIP_NAMES, +) + +REPO_ROOT = Path(__file__).resolve().parents[5] +FOOT_BODY_NAMES = [ + "left_ankle_roll_link", + "right_ankle_roll_link", +] +LEFT_ARM_JOINT_PATTERNS = [ + "left_shoulder_.*", + "left_elbow_joint", + "left_wrist_.*", +] + +HAND_PREP_HEIGHT_OFFSET = 0.16 + + +@configclass +class WalkPickTurnSceneCfg(InteractiveSceneCfg): + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="plane", + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + ), + visual_material=sim_utils.MdlFileCfg( + mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl", + project_uvw=True, + ), + ) + + robot: ArticulationCfg = MISSING + + table: RigidObjectCfg = RigidObjectCfg( + prim_path="/World/envs/env_.*/source_table", + spawn=sim_utils.CuboidCfg( + size=(0.6, 0.8, 0.04), + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + kinematic_enabled=True, + max_depenetration_velocity=1.0, + ), + collision_props=sim_utils.CollisionPropertiesCfg(), + visible=True, + ), + init_state=RigidObjectCfg.InitialStateCfg( + pos=(1.5, 0.0, 0.635), + # pos=(0.65, 0.0, 0.535), + rot=(1.0, 0.0, 0.0, 0.0), + ), + ) + + target_table: RigidObjectCfg | None = None + + cube: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.04, 0.04, 0.04), + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=16, + solver_velocity_iteration_count=4, + disable_gravity=False, + max_depenetration_velocity=1.0, + ), + collision_props=sim_utils.CollisionPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=0.2), + ), + init_state=RigidObjectCfg.InitialStateCfg( + pos=(1.3, 0.0, 0.675), + # pos=(0.45, 0.0, 0.58), + rot=(1.0, 0.0, 0.0, 0.0), + ), + ) + + target_region: RigidObjectCfg | None = None + + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DistantLightCfg( + color=(0.75, 0.75, 0.75), intensity=3000.0), + ) + sky_light = AssetBaseCfg( + prim_path="/World/skyLight", + spawn=sim_utils.DomeLightCfg( + color=(0.13, 0.13, 0.13), intensity=1000.0), + ) + contact_forces = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*", + history_length=3, + track_air_time=True, + force_threshold=10.0, + debug_vis=False, + ) + contact_force_thumb = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger1_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Cube"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_index = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger2_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Cube"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_middle = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger3_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Cube"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_ring = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger4_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Cube"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + contact_force_pinky = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/right_finger5_tip_link", + filter_prim_paths_expr=["{ENV_REGEX_NS}/Cube"], + history_length=3, + track_air_time=True, + force_threshold=1.0, + debug_vis=False, + ) + cube_table_contact = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Cube", + filter_prim_paths_expr=["{ENV_REGEX_NS}/source_table"], + history_length=3, + track_air_time=True, + force_threshold=10.0, + debug_vis=False, + ) + source_table_contact = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/source_table", + # No filter to avoid GPU contact filter warnings; cube contact is negligible + # versus the threshold, so only significant robot impacts trigger this. + history_length=3, + track_air_time=True, + force_threshold=5.0, + debug_vis=False, + ) + target_table_contact: ContactSensorCfg | None = None + + +@configclass +class CommandsCfg: + stage = mdp.WalkPickTurnStageCommandCfg( + asset_name="robot", + cube_name="cube", + source_table_name="table", + target_table_name=None, + target_region_name=None, + contact_sensor_name=[ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + fingertip_body_names=RIGHT_HAND_TIP_NAMES, + hand_base_body_name="right_palm_link", + hand_joint_names=tuple(WUJI_RH_ACTIVE_JOINT_NAMES), + hand_palm_axis=(1.0, 0.0, 0.0), + require_stage1_feet_stance=True, + left_foot_body_name="left_ankle_roll_link", + right_foot_body_name="right_ankle_roll_link", + foot_stagger_x_threshold=0.4, + require_contact=True, + num_stages=5, + source_goal_name="cube", + target_goal_name="table", + approach_distance_threshold=0.6, + approach_target_distance_threshold=0.5, + grasp_distance_threshold=0.08, + lift_height=0.1, + hand_prep_height_offset=HAND_PREP_HEIGHT_OFFSET, + turn_yaw_threshold=0.4, + turn_distance_threshold=0.0, + place_pos_threshold=0.02, + place_ori_threshold=0.35, + ) + + +@configclass +class ActionsCfg: + joint_pos = mdp.ResidualLatentActionCfg(asset_name="robot", joint_names=[ + ".*"], use_default_offset=True) + + +@configclass +class ObservationsCfg: + @configclass + class PolicyCfg(ObsGroup): + stage = ObsTerm(func=mdp.stage_one_hot, params={ + "command_name": "stage"}) + + projected_gravity = ObsTerm(func=mdp.projected_gravity) + + humanoid_prior = ObsTerm( + func=mdp.TrackingPriorHistoryTerm, + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=MODE12_JOINT_ORDER, preserve_order=True), + "noise_cfg": mdp.TRACKING_PRIOR_NOISE_CFG, + "history_length": 5, + }, + ) + + right_hand_prior = ObsTerm( + func=mdp.right_hand_proprio, + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=WUJI_RH_ACTIVE_JOINT_NAMES, preserve_order=True), + "wrist_body_name": "right_palm_link", + }, + ) + last_latent = ObsTerm( + func=mdp.last_residual_latent, + params={"action_term_name": "joint_pos"}, + ) + + fingertip_cube_forces = ObsTerm( + func=mdp.fingertip_force_on_cube, + params={ + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "asset_cfg": SceneEntityCfg("robot"), + "fingertip_body_names": RIGHT_HAND_TIP_NAMES, + "force_scale": 50.0, + "force_clip": 1.0, + }, + ) + + cube_pose = ObsTerm(func=mdp.object_pose_in_robot_frame, params={ + "target_cfg": SceneEntityCfg("cube")}) + source_table_pose = ObsTerm( + func=mdp.object_pose_in_robot_frame, params={ + "target_cfg": SceneEntityCfg("table")} + ) + target_table_pose = ObsTerm( + func=mdp.virtual_pose_in_robot_frame, + params={"pos": (-1.5, 0.0, 0.635)}, + ) + target_region_pose = ObsTerm( + func=mdp.virtual_pose_in_robot_frame, + params={"pos": (-1.3, 0.0, 0.65)}, + ) + cube_pose_in_hand = ObsTerm( + func=mdp.cube_pose_in_hand_frame, + params={"target_cfg": SceneEntityCfg( + "cube"), "hand_body_name": "right_palm_link"}, + ) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + @configclass + class CriticCfg(PolicyCfg): + def __post_init__(self): + super().__post_init__() + self.enable_corruption = False + + policy: PolicyCfg = PolicyCfg() + critic: CriticCfg = CriticCfg() + + +@configclass +class EventCfg: + reset_scene = EventTerm( + func=mdp.reset_scene_with_no_demo_rsi, + mode="reset", + params={ + "rsi_cfg": mdp.NoDemoRSICfg(), + "base_reset_func": mdp.reset_scene_to_default, + "base_reset_kwargs": {"reset_joint_targets": True}, + "reset_joint_targets": True, + "command_name": "stage", + }, + ) + physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*"), + "static_friction_range": (0.3, 1.0), + "dynamic_friction_range": (0.3, 1.0), + "restitution_range": (0.0, 0.1), + "num_buckets": 64, + }, + ) + base_com = EventTerm( + func=mdp.randomize_rigid_body_com, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names="torso_link"), + "com_range": {"x": (-0.025, 0.025), "y": (-0.05, 0.05), "z": (-0.05, 0.05)}, + }, + ) + + +@configclass +class RewardsCfg: + # All stages' rewards. + robot_object_distance = RewTerm( + func=mdp.robot_object_distance_reward, + weight=15.0, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "object_name": "cube", + "target_distance": 0.5, + "scale": 4.0, + }, + ) + + # Stage progression bonus. + stage_progress_bonus = RewTerm( + func=mdp.stage_transition_bonus, + weight=50.0, + params={"command_name": "stage"}, + ) + + # Stage 0 (approach) specific rewards. + heading_to_object = RewTerm( + func=mdp.heading_to_object_penalty, + weight=-10.0, + params={"command_name": "stage", "stage_id": 0, "object_name": "cube"}, + ) + + # Keep the right hand pre-shaped and above the cube during the approach. + right_hand_target_pose = RewTerm( + func=mdp.right_hand_height_direction_reward, + weight=15.0, + params={ + "command_name": "stage", + "stage_id": 0, + "hand_body": "right_palm_link", + "target_name": "cube", + "height_offset": 0.16, + "height_scale": 25.0, + "gate_far": None, + "gate_near": None, + }, + ) + + right_hand_prep_region_penalty = RewTerm( + func=mdp.right_hand_prep_region_penalty, + weight=-5.0, + params={ + "command_name": "stage", + "stage_id": 0, + "hand_body": "right_palm_link", + "target_name": "cube", + "xy_scale": 60.0, + "z_scale": 20.0, + }, + ) + + right_hand_flat_stage0 = RewTerm( + func=mdp.right_hand_flat_penalty, + weight=-5.0, + params={ + "command_name": "stage", + "stage_id": 0, + "hand_body": "right_palm_link", + "angle_tolerance": 0.35, + "palm_axis": (1.0, 0.0, 0.0), + }, + ) + + keep_hand_origin = RewTerm( + func=mdp.hand_default_pose_reward, + weight=5.0, + params={ + "command_name": "stage", + "stage_id": 0, + "asset_cfg": SceneEntityCfg("robot", joint_names=WUJI_RH_ACTIVE_JOINT_NAMES), + "tolerance": 0.05, + "scale": 3.0, + }, + ) + + # grasp related specific rewards. + hand_cube_distance = RewTerm( + func=mdp.hand_cube_distance_reward, + weight=20.0, + params={ + "command_name": "stage", + "stage_id": [1, 2, 3], + "cube_name": "cube", + "fingertip_body_names": [*RIGHT_HAND_TIP_NAMES, "right_palm_link"], + "scale": 10.0, + "distance_aggregation": "mean", + }, + ) + fingertip_contact = RewTerm( + func=mdp.fingertip_contact_reward, + weight=10.0, + params={ + "command_name": "stage", + "stage_id": [1, 2, 3], + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "threshold": 1.0, + "bonus_start_contacts": 3, + "bonus_scale": 0.25, + "bonus_power": 2.0, + "gate_min_lift": 0.01, + "cube_name": "cube", + "table_name": "table", + "table_top_offset": 0.04, + }, + ) + grasp_force = RewTerm( + func=mdp.grasp_force_reward, + weight=10.0, + params={ + "command_name": "stage", + "stage_id": [1, 2, 3], + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "fingertip_body_names": RIGHT_HAND_TIP_NAMES, + "force_scale": 10.0, + "force_clip": 20.0, + "tanh_scale": 2.0, + "max_force": 75.0, + }, + ) + cube_lift_height = RewTerm( + func=mdp.cube_lift_height_reward, + weight=50.0, + params={ + "command_name": "stage", + "stage_id": [1, 2, 3], + "cube_name": "cube", + "table_name": "table", + "table_top_offset": 0.04, + "cap": 0.12, + "require_grasp": False, + }, + ) + hold_object = RewTerm( + func=mdp.object_hold_reward, + weight=20.0, + params={ + "command_name": "stage", + "stage_id": [1, 2, 3], + }, + ) + cube_not_lifted = RewTerm( + func=mdp.cube_not_lifted_penalty, + weight=-10.0, + params={ + "command_name": "stage", + "stage_id": [1, 2, 3], + "cube_name": "cube", + "table_name": "table", + "table_top_offset": 0.04, + "target_lift": 0.1, + }, + ) + cube_table_contact_move = RewTerm( + func=mdp.cube_table_contact_move_penalty, + weight=-5.0, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2], + "sensor_name": "cube_table_contact", + "cube_name": "cube", + "threshold": 1.0, + }, + ) + cube_hand_rel_move = RewTerm( + func=mdp.cube_hand_rel_move_penalty, + weight=-5.0, + params={ + "command_name": "stage", + "stage_id": [1, 2, 3], + "cube_name": "cube", + "hand_body": "right_palm_link", + }, + ) + + upright_orientation = RewTerm( + func=mdp.upright_orientation_reward, + weight=5.0, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "std": 0.2, + "asset_cfg": SceneEntityCfg("robot", body_names="torso_link"), + }, + ) + + success_bonus = RewTerm( + func=mdp.termination_penalty, + weight=1000.0, + params={"term_name": "success"}, + ) + + action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-1.0e-2) + joint_action_rate_l2 = RewTerm( + func=mdp.joint_action_rate_l2, weight=-1.0e-2) + + left_arm_joint_velocity_l2 = RewTerm( + func=mdp.joint_velocity_l2, + weight=-1e-2, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "asset_cfg": SceneEntityCfg("robot", joint_names=LEFT_ARM_JOINT_PATTERNS), + }, + ) + dof_velocity_l2 = RewTerm( + func=mdp.joint_velocity_l2, + weight=-1e-2, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "asset_cfg": SceneEntityCfg("robot", joint_names=[".*"]), + }, + ) + + large_lin_vx = RewTerm( + func=mdp.base_lin_vel_excess, + weight=-10.0, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "axis": 0, + "threshold": 0.5, + "max_penalty": 5.0, + }, + ) + large_lin_vy = RewTerm( + func=mdp.base_lin_vel_excess, + weight=-10.0, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "axis": 1, + "threshold": 0.5, + "max_penalty": 5.0, + }, + ) + large_ang_vel = RewTerm( + func=mdp.base_ang_vel_excess, + weight=-5.0, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "axis": 2, + "threshold": 0.5, + "max_penalty": 5.0, + }, + ) + feet_slip = RewTerm( + func=mdp.feet_slip_penalty, + weight=-5.0, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "sensor_cfg": SceneEntityCfg("contact_forces", body_names=FOOT_BODY_NAMES), + "threshold": 5.0, + # "clip_max": 2.0, + }, + ) + undesired_table_contacts = RewTerm( + func=mdp.undesired_table_contacts, + weight=-10.0, + params={ + "command_name": "stage", + "stage_id": [0, 1, 2, 3], + "sensor_names": ["source_table_contact"], + "threshold": 5.0, + }, + ) + robot_fall_penalty = RewTerm( + func=mdp.termination_penalty, + weight=-10.0, + params={"term_name": "robot_fall"}, + ) + + # When grabing and placing, no angular velocity drift + zero_vel_stage_1_4 = RewTerm( + func=mdp.base_velocity_l1, + weight=-10.0, + params={ + "command_name": "stage", + "stage_id": [1], + "linear_axes": [0, 1], + "angular_axis": 2, + "soft_cap": 3.0, + }, + ) + + +@configclass +class TerminationsCfg: + time_out = DoneTerm(func=mdp.time_out, time_out=True) + success = DoneTerm(func=mdp.stage_success, params={ + "command_name": "stage"}) + cube_dropped = DoneTerm( + func=mdp.cube_dropped, + params={ + "command_name": "stage", + "drop_height": 0.3, + "sensor_names": [ + "contact_force_thumb", + "contact_force_index", + "contact_force_middle", + "contact_force_ring", + "contact_force_pinky", + ], + "contact_threshold": 1.0, + }, + ) + # Contain rare physics explosions before they poison PPO rollouts. + robot_root_state_blowup = DoneTerm( + func=mdp.root_state_blowup, + params={ + "asset_name": "robot", + "max_xy_radius": 6.0, + "max_height": 3.0, + "max_lin_vel": 10.0, + "max_ang_vel": 20.0, + }, + ) + robot_joint_velocity_blowup = DoneTerm( + func=mdp.joint_velocity_blowup, + params={ + "asset_name": "robot", + "max_abs_joint_vel": 40.0, + }, + ) + robot_fall = DoneTerm( + func=mdp.robot_fall, + params={"asset_cfg": SceneEntityCfg("robot"), "min_height": 0.5}, + ) + + +@configclass +class CurriculumCfg: + pass + + +@configclass +class WalkPickTurnEnvCfg(ManagerBasedRLEnvCfg): + scene: WalkPickTurnSceneCfg = WalkPickTurnSceneCfg( + num_envs=4096, env_spacing=5.0) + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + commands: CommandsCfg = CommandsCfg() + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + events: EventCfg = EventCfg() + curriculum: CurriculumCfg = CurriculumCfg() + + def __post_init__(self): + # 60 Hz + self.decimation = 4 + self.episode_length_s = 10.0 + self.sim.dt = 1.0 / (60.0 * 4) + self.sim.render_interval = self.decimation + self.sim.physics_material = self.scene.terrain.physics_material + self.sim.physx.gpu_max_rigid_patch_count = 10 * 2**15 + # viewer settings + self.viewer.eye = (1.5, 1.5, 1.5) + self.viewer.origin_type = "asset_root" + self.viewer.asset_name = "robot" + self.scene.robot = G1_WUJI_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot") + + action_joint_names = MODE12_JOINT_ORDER + \ + list(WUJI_RH_ACTIVE_JOINT_NAMES) + action_scale = dict(G1_WUJI_ACTION_SCALE) + for joint_name in WUJI_RH_ACTIVE_JOINT_NAMES: + action_scale.setdefault(joint_name, 0.1) + + action = self.actions.joint_pos + action.scale = { + pattern: value + for pattern, value in action_scale.items() + if any(re.fullmatch(pattern, joint_name) for joint_name in action_joint_names) + } + action.joint_names = action_joint_names + action.preserve_order = True + action.clip_actions = False + action.body_prior_checkpoint = str( + REPO_ROOT / "ckpts/body_prior/walkpickturn_30k.pt") + action.hand_prior_checkpoint = str( + REPO_ROOT / "ckpts/hand_prior/active_wrist_20k.pt") + action.body_obs_norm_mode = "rsl_rl" + action.hand_action_moving_average = 0.4 + action.hand_joint_names = tuple(WUJI_RH_ACTIVE_JOINT_NAMES) + action.hand_wrist_body_name = "right_palm_link" + action.hand_prior_variant = "wuji_floating_active" + + for obs_group in (self.observations.policy, self.observations.critic): + obs_group.humanoid_prior.params["include_base_lin_vel"] = True + + self.observations.policy.body_prior_mean = ObsTerm( + func=mdp.body_prior_mean, + params={"action_term_name": "joint_pos"}, + ) + self.observations.policy.hand_prior_mean = ObsTerm( + func=mdp.hand_prior_mean, + params={"action_term_name": "joint_pos"}, + ) diff --git a/third-party/coordex/source/coordex/pyproject.toml b/third-party/coordex/source/coordex/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1870a2edbf0f9e516b8a25121afcd17a773b47df --- /dev/null +++ b/third-party/coordex/source/coordex/pyproject.toml @@ -0,0 +1,4 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools.build_meta" + diff --git a/third-party/coordex/source/coordex/setup.py b/third-party/coordex/source/coordex/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b23e7d7eb1706b530050c1b462d9e6e39fb2687c --- /dev/null +++ b/third-party/coordex/source/coordex/setup.py @@ -0,0 +1,10 @@ +from setuptools import find_packages, setup + + +setup( + name="coordex", + version="0.1.0", + packages=find_packages(), + include_package_data=True, +) + diff --git a/third-party/do-as-i-do/.gitmodules b/third-party/do-as-i-do/.gitmodules new file mode 100644 index 0000000000000000000000000000000000000000..8bed17844d2675d3ba68175319cf1e45f9f144bb --- /dev/null +++ b/third-party/do-as-i-do/.gitmodules @@ -0,0 +1,15 @@ +[submodule "reconstruction/modules/tapnet"] + path = reconstruction/modules/tapnet + url = https://github.com/malik-group/tapnet.git +[submodule "reconstruction/modules/sam-3d-objects"] + path = reconstruction/modules/sam-3d-objects + url = https://github.com/malik-group/sam-3d-objects.git +[submodule "reconstruction/modules/Fast-SAM3D"] + path = reconstruction/modules/Fast-SAM3D + url = https://github.com/malik-group/Fast-SAM3D.git +[submodule "reconstruction/modules/HaWoR"] + path = reconstruction/modules/HaWoR + url = https://github.com/malik-group/HaWoR.git +[submodule "reconstruction/modules/sam3"] + path = reconstruction/modules/sam3 + url = https://github.com/malik-group/sam3.git diff --git a/third-party/do-as-i-do/LICENSE b/third-party/do-as-i-do/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..15b0641acfd4d2c13554aa1bb7af40970e5506bf --- /dev/null +++ b/third-party/do-as-i-do/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 malik-group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third-party/do-as-i-do/README.md b/third-party/do-as-i-do/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8e96226f40be546ea6ac6f4ce0be35bade58b276 --- /dev/null +++ b/third-party/do-as-i-do/README.md @@ -0,0 +1,22 @@ +Frame 261 + +# Do as I Do + +[**Project Page**](https://do-as-i-do.com/) | [**arXiv**](https://arxiv.org/abs/2606.19333) + +Code release for Do as I Do. + +Each part of our pipeline is contained in its own folder. External code references are provided as git submodules with our changes baked in. + +- **`reconstruction/`** — object + hand reconstruction and 6-DoF pose tracking from a hand-object + demo video (SAM3 → SAM3D mesh → MoGe pointmaps → HaWoR → TAPIR → guided diffusion for tracking → (optionally) projection). + Full details in [`reconstruction/README.md`](reconstruction/README.md). +- **`retargeting/`** — retargets the reconstructed hand-object demo onto a robot hand + (dataset processing → convex decomposition → MJCF scene generation → IK → sampling-based MPC + in MuJoCo Warp). Consumes the reconstruction pipeline's output directly. + Full details in [`retargeting/README.md`](retargeting/README.md). +- **`deployment/`** — replay a retargeted demo on the real robot: a barebones + MuJoCo replay/IK pass turns a retargeting output into a dual-UR3e joint + trajectory, which is then streamed to the UR3e arms + Sharpa Wave hands. + Full details in [`deployment/README.md`](deployment/README.md). + diff --git a/third-party/do-as-i-do/deployment/.gitignore b/third-party/do-as-i-do/deployment/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..250737e8b18d00dc021f4b61dbf6febafbd6ba67 --- /dev/null +++ b/third-party/do-as-i-do/deployment/.gitignore @@ -0,0 +1,11 @@ +# Proprietary Sharpa Wave SDK — drop in locally (see robot_replay/config.example.yaml) +robot_replay/Sharpa/ + +# Machine-specific config: real robot IPs / hand serials +robot_replay/config.yaml + +# Generated artifacts +**/__pycache__/ +*.pyc +*.npz +mujoco_replay/scene.xml diff --git a/third-party/do-as-i-do/deployment/README.md b/third-party/do-as-i-do/deployment/README.md new file mode 100644 index 0000000000000000000000000000000000000000..99067624a33755a3835b57959fd66b3712f043fb --- /dev/null +++ b/third-party/do-as-i-do/deployment/README.md @@ -0,0 +1,87 @@ +# Deployment + +Run a retargeted demo on the real robot. Two stages: + +1. **`mujoco_replay/`** — load a spider `trajectory_mjwp.npz` (from the + `retargeting/` stage), place + IK-solve it onto the dual-UR3e scene with + collision-aware [`mink`](https://github.com/kevinzakka/mink) IK, preview/tune + in a viser GUI, and save `trajectory_dual_ur3e.npz` (arm + finger joint + trajectories). +2. **`robot_replay/`** — stream `trajectory_dual_ur3e.npz` to a real UR3e arm + + Sharpa Wave hand at 50 Hz. + +## Setup + +```bash +conda env create -f env/deployment.yml # see env/README.md +conda activate deployment +``` + +The Sharpa Wave hand SDK is proprietary and not shipped — drop it into +`robot_replay/Sharpa/`, then copy `robot_replay/config.example.yaml` to +`robot_replay/config.yaml` and fill in your robot IPs / hand serials. + +## 1. mujoco_replay (sim → trajectory) + +```bash +cd mujoco_replay +python replay_retarget.py --side left --traj /path/to/trajectory_mjwp.npz +``` + +Opens a viser web GUI at the printed URL. Tune the workspace placement +(x/y/z + yaw/pitch/roll), the start frame, and collision avoidance; hit +**Recompute IK**, then **Save retarget** to write `trajectory_dual_ur3e.npz` +next to the input trajectory. + +When tuning the workspace placement, adjust x/y/z and yaw. Only tune pitch and +roll if the gravity alignment (GeoCalib) from reconstruction was significantly +incorrect — otherwise leave them at zero. + +### Try it on the whisk demo + +Replay the shipped `whisk` retarget (from the [`retargeting/`](../retargeting/README.md) +demo) without re-running anything. The right-arm workspace preset already defaults +to this clip's saved placement, so it comes up positioned in front of the arm: + +```bash +# from deployment/mujoco_replay — right arm + Sharpa hand, 0.25x playback +python replay_retarget.py \ + --side right \ + --traj ../../retargeting/outputs/sharpa/right/whisking/0/trajectory_mjwp.npz \ + --speed 0.25 +``` + +`--speed 0.25` starts the viser playback at quarter speed (change it live with the +Speed buttons). Open the printed URL, then tweak the workspace / collision controls +and **Save retarget** as usual. + +Headless solve (no GUI) to check IK residuals / collision clearance: + +```bash +python replay_retarget.py --side left --traj .../trajectory_mjwp.npz --solve-only +``` + +## 2. robot_replay (trajectory → hardware) + +```bash +cd robot_replay +cp config.example.yaml config.yaml # then edit arm_ip / hand_sn + +python run_npz.py --side left trajectory_dual_ur3e.npz # arm only, real-time +python run_npz.py --side left trajectory_dual_ur3e.npz --both # arm + hand +python run_npz.py --side left trajectory_dual_ur3e.npz --speed 0.5 # half speed +python run_npz.py --side left trajectory_dual_ur3e.npz --dry-run # validate, no hardware +``` + +The script connects, homes, moves to the trajectory start, then waits for Enter +before streaming. Home a robot independently with: + +```bash +python home.py --side left # arm + hand +python home.py --side right --arm-only +``` + +## Safety + +`run_npz.py` and `home.py` command real hardware. Verify the home pose, keep an +e-stop in reach, and start with `--dry-run` then a low `--speed`. diff --git a/third-party/do-as-i-do/deployment/env/README.md b/third-party/do-as-i-do/deployment/env/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7de0417c2cab11c1b214ee756ddcfabc907274c1 --- /dev/null +++ b/third-party/do-as-i-do/deployment/env/README.md @@ -0,0 +1,22 @@ +# Deployment environment + +A single conda env combining the MuJoCo replay/IK stack (`mujoco`, `mink`, +`viser`) with `ur_rtde` for driving the real UR3e arms — everything both stages +(`mujoco_replay/` and `robot_replay/`) need. + +```bash +conda env create -f env/deployment.yml +conda activate deployment +``` + +Notes: +- `env/deployment.yml` is a full `conda env export` of a known-working env + (Python 3.12.13), treated mainly as a version reference. Regenerate it on a + known-good machine with: + ```bash + conda env export -n deployment | grep -v '^prefix:' > env/deployment.yml + ``` +- The Sharpa Wave hand SDK is proprietary and **not** shipped here. Drop it into + `robot_replay/Sharpa/` (the path in `robot_replay/config.example.yaml`). +- `mjviser` is vendored under `mujoco_replay/mjviser/`, so it is not a pip + dependency. diff --git a/third-party/do-as-i-do/deployment/env/deployment.yml b/third-party/do-as-i-do/deployment/env/deployment.yml new file mode 100644 index 0000000000000000000000000000000000000000..f943abb1ec3bf3dde882af13565ae911ca785a10 --- /dev/null +++ b/third-party/do-as-i-do/deployment/env/deployment.yml @@ -0,0 +1,145 @@ +name: deployment +channels: + - conda-forge +dependencies: + - _openmp_mutex=4.5=20_gnu + - bzip2=1.0.8=hda65f42_9 + - ca-certificates=2026.4.22=hbd8a1cb_0 + - ld_impl_linux-64=2.45.1=default_hbd61a6d_102 + - libexpat=2.8.0=hecca717_0 + - libffi=3.5.2=h3435931_0 + - libgcc=15.2.0=he0feb66_19 + - libgcc-ng=15.2.0=h69a702a_19 + - libgomp=15.2.0=he0feb66_19 + - liblzma=5.8.3=hb03c661_0 + - libnsl=2.0.1=hb9d3cd8_1 + - libsqlite=3.53.1=h0c1763c_0 + - libuuid=2.42=h5347b49_0 + - libxcrypt=4.4.36=hd590300_1 + - libzlib=1.3.2=h25fd6f3_2 + - ncurses=6.6=hdb14827_0 + - openssl=3.6.2=h35e630c_0 + - packaging=26.2=pyhc364b38_0 + - pip=26.1.1=pyh8b19718_0 + - python=3.12.13=hd63d673_0_cpython + - readline=8.3=h853b02a_0 + - tk=8.6.13=noxft_h366c992_103 + - tzdata=2025c=hc9c84f9_1 + - wheel=0.47.0=pyhd8ed1ab_0 + - zstd=1.5.7=hb78ec9c_6 + - pip: + - absl-py==2.4.0 + - annotated-types==0.7.0 + - anyio==4.13.0 + - attrs==26.1.0 + - certifi==2026.4.22 + - charset-normalizer==3.4.7 + - click==8.3.3 + - cloudpickle==3.1.2 + - colorlog==6.10.1 + - contourpy==1.3.3 + - cuda-bindings==13.2.0 + - cuda-pathfinder==1.5.4 + - cuda-toolkit==13.0.2 + - cycler==0.12.1 + - daqp==0.8.7 + - embreex==4.4.0 + - etils==1.14.0 + - farama-notifications==0.0.6 + - filelock==3.29.0 + - fonttools==4.62.1 + - fsspec==2026.4.0 + - gitdb==4.0.12 + - gitpython==3.1.50 + - glfw==2.10.0 + - grpcio==1.80.0 + - gymnasium==1.2.3 + - h11==0.16.0 + - httpcore==1.0.9 + - httpx==0.28.1 + - idna==3.14 + - imageio==2.37.3 + - imageio-ffmpeg==0.6.0 + - jinja2==3.1.6 + - jsonschema==4.26.0 + - jsonschema-specifications==2025.9.1 + - kiwisolver==1.5.0 + - lxml==6.1.0 + - manifold3d==3.4.1 + - mapbox-earcut==2.0.0 + - markdown==3.10.2 + - markdown-it-py==4.2.0 + - markupsafe==3.0.3 + - matplotlib==3.10.9 + - mdurl==0.1.2 + - mink==1.1.1 + - mpmath==1.3.0 + - msgspec==0.21.1 + - mujoco==3.8.1 + - networkx==3.6.1 + - numpy==2.4.4 + - nvidia-cublas==13.1.0.3 + - nvidia-cuda-cupti==13.0.85 + - nvidia-cuda-nvrtc==13.0.88 + - nvidia-cuda-runtime==13.0.96 + - nvidia-cudnn-cu13==9.19.0.56 + - nvidia-cufft==12.0.0.61 + - nvidia-cufile==1.15.1.6 + - nvidia-curand==10.4.0.35 + - nvidia-cusolver==12.0.4.66 + - nvidia-cusparse==12.6.3.3 + - nvidia-cusparselt-cu13==0.8.0 + - nvidia-nccl-cu13==2.28.9 + - nvidia-nvjitlink==13.0.88 + - nvidia-nvshmem-cu13==3.4.5 + - nvidia-nvtx==13.0.85 + - opencv-python==4.13.0.92 + - pandas==3.0.3 + - pillow==12.2.0 + - platformdirs==4.9.6 + - protobuf==7.34.1 + - psutil==7.2.2 + - pyarrow==24.0.0 + - pycollada==0.9.3 + - pydantic==2.13.4 + - pydantic-core==2.46.4 + - pygments==2.20.0 + - pyopengl==3.1.10 + - pyparsing==3.3.2 + - python-dateutil==2.9.0.post0 + - pyyaml==6.0.3 + - qpsolvers==4.12.0 + - referencing==0.37.0 + - requests==2.34.0 + - rerun-sdk==0.32.0 + - rich==14.3.4 + - rpds-py==0.30.0 + - rtree==1.4.1 + - scipy==1.17.1 + - sentry-sdk==2.59.0 + - setuptools==81.0.0 + - shapely==2.1.2 + - six==1.17.0 + - smmap==5.0.3 + - stable-baselines3==2.8.0 + - svg-path==7.0 + - sympy==1.14.0 + - tensorboard==2.20.0 + - tensorboard-data-server==0.7.2 + - torch==2.11.0 + - tqdm==4.67.3 + - trimesh==4.12.2 + - triton==3.6.0 + - typing-extensions==4.15.0 + - typing-inspection==0.4.2 + - ur-rtde==1.6.2 + - urllib3==2.7.0 + - vhacdx==0.0.10 + - viser==1.0.27 + - wandb==0.26.1 + - websockets==16.0 + - werkzeug==3.1.8 + - xxhash==3.7.0 + - yourdfpy==0.0.60 + - zipp==3.23.1 + - zstandard==0.25.0 diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/assets/sharpa_assets/SharpaWave_URDF_XML_USD_V3.0.0/src/left_sharpa_wave/left_sharpa_wave.xml b/third-party/do-as-i-do/deployment/mujoco_replay/assets/sharpa_assets/SharpaWave_URDF_XML_USD_V3.0.0/src/left_sharpa_wave/left_sharpa_wave.xml new file mode 100644 index 0000000000000000000000000000000000000000..63a6cd466feb21fd16864fcb77533d17f5acaab0 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/assets/sharpa_assets/SharpaWave_URDF_XML_USD_V3.0.0/src/left_sharpa_wave/left_sharpa_wave.xml @@ -0,0 +1,250 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/assets/sharpa_assets/SharpaWave_URDF_XML_USD_V3.0.0/src/right_sharpa_wave/right_sharpa_wave.xml b/third-party/do-as-i-do/deployment/mujoco_replay/assets/sharpa_assets/SharpaWave_URDF_XML_USD_V3.0.0/src/right_sharpa_wave/right_sharpa_wave.xml new file mode 100644 index 0000000000000000000000000000000000000000..644f8014dbadfffc3979212fd22845c9c89bbef1 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/assets/sharpa_assets/SharpaWave_URDF_XML_USD_V3.0.0/src/right_sharpa_wave/right_sharpa_wave.xml @@ -0,0 +1,250 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/LICENSE.txt b/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..f24e07cb6524f2a5e42a466c27c655a9ceb674a6 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/LICENSE.txt @@ -0,0 +1,26 @@ +Copyright 2018 ROS Industrial Consortium + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/README.md b/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3cf457939c8f521f008725ba8f6bcc0eaf9bc43a --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/README.md @@ -0,0 +1,36 @@ +# Universal Robots UR3e Description (MJCF) + +Requires MuJoCo 2.3.3 or later. + +## Overview + +This package contains a simplified robot description (MJCF) of the +[UR3e](https://www.universal-robots.com/products/ur3-robot/) developed by +[Universal Robots](https://www.universal-robots.com/). It is derived from the +[publicly available URDF description](https://github.com/ros-industrial/universal_robot/tree/kinetic-devel/ur_e_description). + +### URDF → MJCF derivation steps + +1. Converted the DAE [mesh files](https://github.com/ros-industrial/universal_robot/tree/kinetic-devel/ur_e_description/meshes/ur3e/visual) to OBJ format using [Blender](https://www.blender.org/). + - In this process, the Z axis of the joint that a link is connected to should point up. +2. Processed `.obj` files with [`obj2mjcf`](https://github.com/kevinzakka/obj2mjcf). +3. Added ` ` to the URDF's `` clause in order to preserve visual geometries. +4. Loaded the URDF into MuJoCo and saved a corresponding MJCF. +5. Added a tracking light to the base. +6. Manually edited the MJCF to extract common properties into the `` section. +7. Manually edited colors to match UR3 colors. +8. Added position-controlled actuators and joint damping and armature. + Note that these values have not been carefully tuned -- contributions are more than welcome to improve them. +9. Added home joint configuration as a `keyframe`. +10. Manually designed collision geometries to be as realistic as the UR3's shape. +11. Added `scene.xml`, which includes the robot, with a textured ground plane, skybox, and haze. + +### Notes + +Although the model is stable in the `scene.xml`, you might see unstable behavior when combined with +other models (i.e., Robotiq-2F85 gripper). Switching the integrator from `Euler` to `RK4` helps in +these cases. + +## License + +This model is released under a [BSD-3-Clause License](LICENSE) \ No newline at end of file diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/ur3e.xml b/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/ur3e.xml new file mode 100644 index 0000000000000000000000000000000000000000..5f4fe73702af74ea5cd988399925f58c8322e1bc --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/assets/universal_robots_ur3e/ur3e.xml @@ -0,0 +1,137 @@ + + + + diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/build_scene.py b/third-party/do-as-i-do/deployment/mujoco_replay/build_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..91e7772917026844ab8052e49ddc1707850f6579 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/build_scene.py @@ -0,0 +1,341 @@ +"""Build a MuJoCo scene with two UR3e arms side by side. + +Uses MjSpec.attach to namespace each arm (left_/right_) so joint, body, +and actuator names don't collide. Writes the compiled model to scene.xml. +""" + +import math +from pathlib import Path + +import mujoco + +HERE = Path(__file__).resolve().parent +ASSETS = HERE / "assets" +UR3E_DIR = ASSETS / "universal_robots_ur3e" +UR3E_XML = UR3E_DIR / "ur3e.xml" +UR3E_ASSETS = UR3E_DIR / "assets" + +SHARPA_DIR = ( + ASSETS / "sharpa_assets" / "SharpaWave_URDF_XML_USD_V3.0.0" / "src" +) +LEFT_HAND_XML = SHARPA_DIR / "left_sharpa_wave" / "left_sharpa_wave.xml" +RIGHT_HAND_XML = SHARPA_DIR / "right_sharpa_wave" / "right_sharpa_wave.xml" + +# Side-by-side layout: both arms facing +x, separated along y. +# 26 inches base-to-base = 0.6604 m total, so ±0.3302 m from origin. +INCH = 0.0254 +SEPARATION = 26 * INCH + +# Table: 4 ft × 4 ft slab on 4 legs, top face 25 in above the floor. The slab +# is the same thickness as the breadboard so the two are coplanar (aligned +# bottoms and tops) — the breadboard sits flush in the tabletop, not on top. +FOOT = 12 * INCH +TABLE_HEIGHT = 25 * INCH +SLAB_THICKNESS = 0.5 * INCH +TABLE_HALF = (4 * FOOT / 2, 4 * FOOT / 2, SLAB_THICKNESS / 2) +TABLE_TOP_Z = TABLE_HEIGHT +SLAB_CENTER_Z = TABLE_TOP_Z - TABLE_HALF[2] + +# 4 legs (2 in square cross-section), inset 3 in from each tabletop edge. +LEG_HALF_XY = 1 * INCH +LEG_HEIGHT = TABLE_TOP_Z - SLAB_THICKNESS # floor to underside of slab +LEG_HALF = (LEG_HALF_XY, LEG_HALF_XY, LEG_HEIGHT / 2) +LEG_INSET = 3 * INCH +LEG_OFFSET = TABLE_HALF[0] - LEG_INSET - LEG_HALF_XY + +# Corner radius for the rounded tabletop. +CORNER_R = 2 * INCH + +# Optical breadboard sitting ON TOP of the tabletop, with its -x (near) edge +# flush with the table's -x edge. Lifted 1 in off the tabletop on wooden +# support blocks at the 4 corners. +BREADBOARD_HALF = (FOOT / 2, 3 * FOOT / 2, 0.5 * INCH / 2) +BREADBOARD_X = -TABLE_HALF[0] + BREADBOARD_HALF[0] # near-edge alignment +# In y the breadboard is *not* centered: its -y edge sits 18.25 cm from the +# table's -y edge. The whole arm+block+support assembly rides with it. +BREADBOARD_RIGHT_GAP = 0.1825 +BREADBOARD_Y = -TABLE_HALF[1] + BREADBOARD_RIGHT_GAP + BREADBOARD_HALF[1] +BREADBOARD_LIFT = 1 * INCH +BREADBOARD_BOTTOM_Z = TABLE_TOP_Z + BREADBOARD_LIFT +BREADBOARD_CENTER_Z = BREADBOARD_BOTTOM_Z + BREADBOARD_HALF[2] +BREADBOARD_TOP_Z = BREADBOARD_BOTTOM_Z + 2 * BREADBOARD_HALF[2] + +# Wooden support blocks: 4 in × 4 in × 1 in, filling the gap under the +# breadboard's four corners. +SUPPORT_HALF = (2 * INCH, 2 * INCH, BREADBOARD_LIFT / 2) + +# Arms ride with the breadboard; 0.75 in forward of its center in x +# (preserves the previous breadboard-to-arm offset). +ARM_X = BREADBOARD_X + 0.75 * INCH + +# Mounting block under each arm: 18 × 18 × 1 cm, sitting on the breadboard. +BLOCK_HALF = (0.09, 0.09, 0.005) +BLOCK_TOP_Z = BREADBOARD_TOP_Z + 2 * BLOCK_HALF[2] + +LEFT_POS = (ARM_X, BREADBOARD_Y + SEPARATION / 2, BLOCK_TOP_Z) +RIGHT_POS = (ARM_X, BREADBOARD_Y - SEPARATION / 2, BLOCK_TOP_Z) + +LEFT_EULER_DEG = (0.0, 0.0, -68.27) +RIGHT_EULER_DEG = (0.0, 0.0, -111.73) + +# Target joint angles (rad) — order matches the UR3e joint chain: +# shoulder_pan, shoulder_lift, elbow, wrist_1, wrist_2, wrist_3. +LEFT_QPOS = [ + -1.830804173146383, + -1.49032814920459, + -0.2515060305595398, + -2.9926845035948695, + -1.4880836645709437, + 3.9406208992004395, +] +RIGHT_QPOS = [ + 2.0238232612609863, + -1.56756230656568, + 0.104102913533346, + -0.07167549551043706, + 1.6591987609863281, + -3.932023588811056, +] + + +def build() -> mujoco.MjSpec: + parent = mujoco.MjSpec() + parent.modelname = "dual_ur3e" + # Otherwise attach moves the child subtree, preventing a second attach. + parent.copy_during_attach = True + # Absolute meshdir so the saved scene.xml can find the UR3e .obj files + # regardless of where it's loaded from. + parent.compiler.meshdir = str(UR3E_ASSETS) + + # Floor + light. + parent.worldbody.add_light(name="top", pos=[0, 0, 2], dir=[0, 0, -1]) + parent.worldbody.add_geom( + name="floor", + type=mujoco.mjtGeom.mjGEOM_PLANE, + size=[2, 2, 0.1], + rgba=[0.85, 0.85, 0.9, 1], + ) + # Tabletop: rounded-corner slab, decomposed into non-overlapping pieces + # (1 central box + 4 edge strips + 4 corner cylinders) to avoid + # z-fighting and stacked shadows. + a, b, h = TABLE_HALF + top_rgba = [0.95, 0.95, 0.95, 1] + parent.worldbody.add_geom( + name="table_center", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[a - CORNER_R, b - CORNER_R, h], + pos=[0, 0, SLAB_CENTER_Z], + rgba=top_rgba, + ) + # Edge strips (each covers one side of the inner box, between the two + # adjacent corner cylinders). + parent.worldbody.add_geom( + name="table_edge_px", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[CORNER_R, b - CORNER_R, h], + pos=[a - CORNER_R, 0, SLAB_CENTER_Z], + rgba=top_rgba, + ) + parent.worldbody.add_geom( + name="table_edge_nx", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[CORNER_R, b - CORNER_R, h], + pos=[-(a - CORNER_R), 0, SLAB_CENTER_Z], + rgba=top_rgba, + ) + parent.worldbody.add_geom( + name="table_edge_py", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[a - CORNER_R, CORNER_R, h], + pos=[0, b - CORNER_R, SLAB_CENTER_Z], + rgba=top_rgba, + ) + parent.worldbody.add_geom( + name="table_edge_ny", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[a - CORNER_R, CORNER_R, h], + pos=[0, -(b - CORNER_R), SLAB_CENTER_Z], + rgba=top_rgba, + ) + for sx in (-1, 1): + for sy in (-1, 1): + tag = f"{'n' if sx < 0 else 'p'}{'n' if sy < 0 else 'p'}" + parent.worldbody.add_geom( + name=f"table_corner_{tag}", + type=mujoco.mjtGeom.mjGEOM_CYLINDER, + size=[CORNER_R, h, 0], + pos=[sx * (a - CORNER_R), sy * (b - CORNER_R), SLAB_CENTER_Z], + rgba=top_rgba, + ) + # 4 legs supporting the tabletop from underneath. + for sx in (-1, 1): + for sy in (-1, 1): + parent.worldbody.add_geom( + name=f"leg_{'n' if sx < 0 else 'p'}{'n' if sy < 0 else 'p'}", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=list(LEG_HALF), + pos=[sx * LEG_OFFSET, sy * LEG_OFFSET, LEG_HEIGHT / 2], + rgba=[0.75, 0.75, 0.75, 1], + ) + # Room walls. Back wall (white) stands 23.5 cm past the -x edge, behind + # the arms. (Far concrete wall, 17 in past the +x edge, removed for now.) + wall_thickness = 0.05 # half-thickness + wall_half_h = 1.5 + wall_z = wall_half_h + wall_half_span = 2.0 + far_wall_gap = 17 * INCH + back_wall_gap = 0.235 + far_wall_x = TABLE_HALF[0] + far_wall_gap + wall_thickness + back_wall_x = -(TABLE_HALF[0] + back_wall_gap + wall_thickness) + # Far wall removed for now. + # parent.worldbody.add_geom( + # name="far_wall", + # type=mujoco.mjtGeom.mjGEOM_BOX, + # size=[wall_thickness, wall_half_span, wall_half_h], + # pos=[far_wall_x, 0, wall_z], + # rgba=[0.55, 0.55, 0.52, 1], + # ) + parent.worldbody.add_geom( + name="back_wall", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[wall_thickness, wall_half_span, wall_half_h], + pos=[back_wall_x, 0, wall_z], + rgba=[0.98, 0.98, 0.98, 1], + ) + + # Foam pad: 3 ft (x) × 4 ft (y) × 1.5 in, filling the tabletop area + # behind the breadboard (between breadboard's +x edge and table's +x edge). + foam_half = (3 * FOOT / 2, 4 * FOOT / 2, 1.5 * INCH / 2) + breadboard_far_x = BREADBOARD_X + BREADBOARD_HALF[0] + foam_x = breadboard_far_x + foam_half[0] + parent.worldbody.add_geom( + name="foam", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=list(foam_half), + pos=[foam_x, 0, TABLE_TOP_Z + foam_half[2]], + rgba=[0.88, 0.84, 0.72, 1], + ) + + # Wooden support blocks under the breadboard corners (flush inside). + for sx in (-1, 1): + for sy in (-1, 1): + tag = f"{'n' if sx < 0 else 'p'}{'n' if sy < 0 else 'p'}" + bx = BREADBOARD_X + sx * (BREADBOARD_HALF[0] - SUPPORT_HALF[0]) + by = BREADBOARD_Y + sy * (BREADBOARD_HALF[1] - SUPPORT_HALF[1]) + parent.worldbody.add_geom( + name=f"support_{tag}", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=list(SUPPORT_HALF), + pos=[bx, by, TABLE_TOP_Z + SUPPORT_HALF[2]], + rgba=[0.55, 0.4, 0.22, 1], + ) + # Optical breadboard on top of the support blocks, -x edge flush with table -x edge. + parent.worldbody.add_geom( + name="breadboard", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=list(BREADBOARD_HALF), + pos=[BREADBOARD_X, BREADBOARD_Y, BREADBOARD_CENTER_Z], + rgba=[0.12, 0.12, 0.12, 1], + ) + + # Load UR3e and attach twice at prefixed frames. Each frame also carries + # a blue mounting block that shares the arm's xy position and yaw. + arm = mujoco.MjSpec.from_file(str(UR3E_XML)) + for prefix, pos, euler in ( + ("left_", LEFT_POS, LEFT_EULER_DEG), + ("right_", RIGHT_POS, RIGHT_EULER_DEG), + ): + block_pos = (pos[0], pos[1], BREADBOARD_TOP_Z + BLOCK_HALF[2]) + parent.worldbody.add_geom( + name=f"{prefix}block", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=list(BLOCK_HALF), + pos=list(block_pos), + euler=list(euler), + rgba=[32 / 255, 37 / 255, 43 / 255, 1], + ) + frame = parent.worldbody.add_frame(pos=list(pos), euler=list(euler)) + parent.attach(arm, prefix=prefix, frame=frame) + + # Flange-to-hand coupler: a black base cylinder against the arm, + # followed by a silver cylinder against the hand. Both oriented along + # the wrist_3_joint axis (which is +Y in wrist_3_link's frame). + SITE_POS_Y = 0.09215 + BLACK_R, BLACK_H = 0.034, 0.01325 + SILVER_R, SILVER_H = 0.021, 0.0175 + HAND_OFFSET = BLACK_H + SILVER_H # 0.03075 m along site +Z + HAND_RGBA = [0.79216, 0.81961, 0.93333, 1] + SITE_QUAT = [-1, 1, 0, 0] # same as the UR3e attachment_site + + for prefix in ("left", "right"): + wrist = parent.body(f"{prefix}_wrist_3_link") + wrist.add_geom( + name=f"{prefix}_coupler_black", + type=mujoco.mjtGeom.mjGEOM_CYLINDER, + size=[BLACK_R, BLACK_H / 2, 0], + pos=[0, SITE_POS_Y + BLACK_H / 2, 0], + quat=SITE_QUAT, + rgba=[0.05, 0.05, 0.05, 1], + ) + wrist.add_geom( + name=f"{prefix}_coupler_silver", + type=mujoco.mjtGeom.mjGEOM_CYLINDER, + size=[SILVER_R, SILVER_H / 2, 0], + pos=[0, SITE_POS_Y + BLACK_H + SILVER_H / 2, 0], + quat=SITE_QUAT, + rgba=HAND_RGBA, + ) + + # Attach Sharpa Wave hands to each arm's flange (attachment_site). + # The site's +Z axis aligns with the wrist_3_joint axis, so: + # - root pos shift along +Z offsets the hand past the coupler. + # - root quat about Z is the wrist roll (mount rotation). + left_hand = mujoco.MjSpec.from_file(str(LEFT_HAND_XML)) + right_hand = mujoco.MjSpec.from_file(str(RIGHT_HAND_XML)) + + def z_quat(deg): + t = math.radians(deg) + return [math.cos(t / 2), 0, 0, math.sin(t / 2)] + + left_hand.body("left_hand_C_MC").pos = [0, 0, HAND_OFFSET] + left_hand.body("left_hand_C_MC").quat = z_quat(45) + right_hand.body("right_hand_C_MC").pos = [0, 0, HAND_OFFSET] + right_hand.body("right_hand_C_MC").quat = z_quat(135) + + parent.attach( + left_hand, prefix="left_hand_", site=parent.site("left_attachment_site") + ) + parent.attach( + right_hand, prefix="right_hand_", site=parent.site("right_attachment_site") + ) + + # Keyframe: specified arm angles + zero for every hand joint. + # qpos layout follows the body tree (left arm → left hand → right arm → + # right hand), but actuators are grouped by spec attach order + # (both arms, then both hands), so ctrl needs its own layout. + hand_dof = 22 # 22 joints per Sharpa Wave hand + home_qpos = ( + list(LEFT_QPOS) + [0.0] * hand_dof + + list(RIGHT_QPOS) + [0.0] * hand_dof + ) + home_ctrl = ( + list(LEFT_QPOS) + list(RIGHT_QPOS) + + [0.0] * hand_dof + [0.0] * hand_dof + ) + parent.add_key(name="home", qpos=home_qpos, ctrl=home_ctrl) + + return parent + + +def main() -> None: + spec = build() + model = spec.compile() + print(f"Compiled OK — nbody={model.nbody}, nq={model.nq}, nu={model.nu}") + + out = HERE / "scene.xml" + out.write_text(spec.to_xml()) + print(f"Wrote {out}") + + +if __name__ == "__main__": + main() diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/__init__.py b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..80af911475ce4ca985913fca75304d4a3c03b493 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/__init__.py @@ -0,0 +1,4 @@ +"""Web-based MuJoCo viewer powered by viser.""" + +from mjviser.scene import ViserMujocoScene as ViserMujocoScene +from mjviser.viewer import Viewer as Viewer diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/__main__.py b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..a9bbedb04983c0258063edf9c5e3c5a4843ca32e --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/__main__.py @@ -0,0 +1,127 @@ +"""Allow ``python -m mjviser model.xml`` to launch the active viewer.""" + +from __future__ import annotations + +import argparse +import importlib +import sys +from pathlib import Path + +import mujoco +import viser + +from mjviser import Viewer + + +def _pick(prompt: str, options: list[str]) -> int: + """Show a numbered list and return the selected index.""" + for i, opt in enumerate(options, 1): + print(f" [{i}] {opt}") + try: + choice = input(f"{prompt} [1]: ").strip() + return int(choice) - 1 if choice else 0 + except (ValueError, IndexError, KeyboardInterrupt): + sys.exit(1) + + +def _resolve_from_robot_descriptions(name: str) -> Path | None: + """Try to resolve a model name via the robot_descriptions package.""" + try: + from robot_descriptions import DESCRIPTIONS # type: ignore[import-not-found] + except ImportError: + return None + + suffix = "_mj_description" + candidates = { + n.removesuffix(suffix): n for n, d in DESCRIPTIONS.items() if d.has_mjcf + } + + # Exact match: "go1" or "go1_mj_description". + desc_name = candidates.get(name) or candidates.get(name.removesuffix(suffix)) + if desc_name is None: + # Fuzzy substring match. + hits = [(short, full) for short, full in candidates.items() if name in short] + if not hits: + return None + if len(hits) == 1: + desc_name = hits[0][1] + else: + print(f"Multiple robot_descriptions matches for '{name}':") + idx = _pick("Select", [h[0] for h in hits]) + desc_name = hits[idx][1] + + desc = importlib.import_module(f"robot_descriptions.{desc_name}") + # Prefer scene.xml when available. + scene = Path(desc.PACKAGE_PATH) / "scene.xml" + return scene if scene.is_file() else Path(desc.MJCF_PATH) + + +def _resolve_path(arg: str) -> Path: + """Resolve a model path via file, robot_descriptions, or glob search.""" + path = Path(arg) + if path.is_file(): + return path + + # Try robot_descriptions before expensive glob. + rd_path = _resolve_from_robot_descriptions(arg) + if rd_path is not None: + print(f"Found: {rd_path}") + return rd_path + + # Glob search in CWD. + if path.is_dir(): + matches = sorted(path.glob("**/*.xml")) + elif "*" in arg: + matches = sorted(Path.cwd().glob(arg)) + else: + matches = sorted(Path.cwd().glob(f"**/*{arg}*.xml")) + + if not matches: + print(f"No XML files matching '{arg}' found in {Path.cwd()}") + sys.exit(1) + if len(matches) == 1: + print(f"Found: {matches[0]}") + return matches[0] + + print(f"Multiple matches for '{arg}':") + labels = [] + for m in matches: + try: + labels.append(str(m.relative_to(Path.cwd()))) + except ValueError: + labels.append(str(m)) + return matches[_pick("Select", labels)] + + +def main() -> None: + parser = argparse.ArgumentParser( + prog="mjviser", + description=( + "Interactive MuJoCo viewer powered by Viser.\n\n" + "MODEL can be a file path, a robot_descriptions name (e.g. 'go1'),\n" + "or a substring / glob pattern to search under the current directory." + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "model", + metavar="MODEL", + help="path, robot_descriptions name, or search pattern for a .xml model", + ) + parser.add_argument( + "--port", + type=int, + default=8080, + help="port to bind the Viser server to (default: 8080)", + ) + args = parser.parse_args() + + path = _resolve_path(args.model) + model = mujoco.MjModel.from_xml_path(str(path)) + data = mujoco.MjData(model) + server = viser.ViserServer(port=args.port) + Viewer(model, data, server=server).run() + + +if __name__ == "__main__": + main() diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/conversions.py b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..1a9d02c4e5721aebc501722e14e5cee545617194 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/conversions.py @@ -0,0 +1,557 @@ +"""Convert MuJoCo mesh data to trimesh format with texture support.""" + +import mujoco +import numpy as np +import trimesh +import trimesh.visual +import trimesh.visual.material +import viser.transforms as vtf +from mujoco import mj_id2name, mjtGeom, mjtObj +from PIL import Image + +# ------------------------------------------------------------------ +# Color / texture helpers +# ------------------------------------------------------------------ + + +def _get_texture_id(mj_model: mujoco.MjModel, matid: int) -> int: + """Return the RGB or RGBA texture ID for a material, or -1.""" + texid = int(mj_model.mat_texid[matid, int(mujoco.mjtTextureRole.mjTEXROLE_RGB)]) + if texid < 0: + texid = int(mj_model.mat_texid[matid, int(mujoco.mjtTextureRole.mjTEXROLE_RGBA)]) + return texid + + +def _extract_texture_image(mj_model: mujoco.MjModel, texid: int) -> Image.Image | None: + """Extract a 2D texture as a PIL Image, or None for unsupported types.""" + w = mj_model.tex_width[texid] + h = mj_model.tex_height[texid] + nc = mj_model.tex_nchannel[texid] + adr = mj_model.tex_adr[texid] + data = mj_model.tex_data[adr : adr + w * h * nc] + + # MuJoCo uses bottom-left origin; GLTF expects top-left. + if nc == 1: + arr = np.flipud(data.reshape(h, w)) + return Image.fromarray(arr.astype(np.uint8), mode="L") + elif nc in (3, 4): + arr = np.flipud(data.reshape(h, w, nc)) + return Image.fromarray(arr.astype(np.uint8)) + return None + + +def _resolve_flat_rgba(mj_model: mujoco.MjModel, geom_idx: int) -> np.ndarray: + """Resolve the flat RGBA color for a geom as uint8. + + Priority: material rgba > geom rgba. + """ + matid = mj_model.geom_matid[geom_idx] + if matid >= 0 and matid < mj_model.nmat: + rgba = mj_model.mat_rgba[matid] + else: + rgba = mj_model.geom_rgba[geom_idx] + return (np.clip(rgba, 0, 1) * 255).astype(np.uint8) + + +def _apply_flat_color(mesh: trimesh.Trimesh, rgba_uint8: np.ndarray) -> None: + """Apply a uniform RGBA color to all vertices.""" + mesh.visual = trimesh.visual.ColorVisuals( + vertex_colors=np.tile(rgba_uint8, (len(mesh.vertices), 1)) + ) + + +def _cubemap_vertex_colors( + mj_model: mujoco.MjModel, + matid: int, + vertices: np.ndarray, + faces: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray] | None: + """Project a cube map texture onto mesh triangles by normal direction. + + For each triangle, finds the cube map face most aligned with its + normal and assigns that face's average color. If the best face is + empty, falls back to the nearest non-empty face (handles chamfered + edges). + + Returns (new_vertices, new_faces, vertex_colors) with duplicated + vertices so each triangle can have its own color, or None if the + material has no cube map texture. + """ + texid = _get_texture_id(mj_model, matid) + if texid < 0: + return None + + w = mj_model.tex_width[texid] + h = mj_model.tex_height[texid] + nc = mj_model.tex_nchannel[texid] + if int(mj_model.tex_type[texid]) != 1 or h != w * 6: + return None + + adr = mj_model.tex_adr[texid] + data = mj_model.tex_data[adr : adr + w * h * nc].reshape(6, w, w, nc) + + # Average color per cube face. Empty faces stay at [0,0,0,0]. + face_colors = np.zeros((6, 4), dtype=np.uint8) + has_color = np.zeros(6, dtype=bool) + for i in range(6): + mask = data[i, :, :, : min(nc, 3)].sum(axis=2) > 0 + if mask.any(): + avg = data[i][mask].mean(axis=0).astype(np.uint8) + face_colors[i, :nc] = avg[:nc] + if nc < 4: + face_colors[i, 3] = 255 + has_color[i] = True + + if not has_color.any(): + return None + + # Cube map axes: +X, -X, +Y, -Y, +Z, -Z. + axes = np.array( + [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], + dtype=np.float64, + ) + + # Per-triangle normals. + v0, v1, v2 = vertices[faces[:, 0]], vertices[faces[:, 1]], vertices[faces[:, 2]] + normals = np.cross(v1 - v0, v2 - v0) + normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-10) + + # For each triangle, pick the best aligned face that has color. + dots = normals @ axes.T + ranked = np.argsort(-dots, axis=1) + nf = len(faces) + valid = has_color[ranked] # (nf, 6) bool + first_valid = valid.argmax(axis=1) # First True per row. + best_face = ranked[np.arange(nf), first_valid] + tri_colors = face_colors[best_face] + # Zero out rows where no face has color. + tri_colors[~valid.any(axis=1)] = 0 + + # Duplicate vertices so each triangle gets its own color. + new_verts = vertices[faces.ravel()] + new_faces = np.arange(nf * 3).reshape(-1, 3) + vert_colors = np.repeat(tri_colors, 3, axis=0) + + return new_verts, new_faces, vert_colors + + +# ------------------------------------------------------------------ +# Mesh extraction +# ------------------------------------------------------------------ + + +def _extract_mesh_data( + mj_model: mujoco.MjModel, geom_idx: int +) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]: + """Extract vertices, faces, and optional UVs for a mesh geom. + + Returns (vertices, faces, uvs). UVs are None when the mesh has no + texture coordinates. When UVs are present, vertices and faces are + duplicated so each face-vertex gets its own UV. + """ + mesh_id = mj_model.geom_dataid[geom_idx] + vert_start = int(mj_model.mesh_vertadr[mesh_id]) + vert_count = int(mj_model.mesh_vertnum[mesh_id]) + face_start = int(mj_model.mesh_faceadr[mesh_id]) + face_count = int(mj_model.mesh_facenum[mesh_id]) + + vertices = mj_model.mesh_vert[vert_start : vert_start + vert_count] + faces = mj_model.mesh_face[face_start : face_start + face_count] + + texcoord_num = mj_model.mesh_texcoordnum[mesh_id] + if texcoord_num == 0: + return vertices, faces, None + + texcoord_adr = mj_model.mesh_texcoordadr[mesh_id] + texcoords = mj_model.mesh_texcoord[texcoord_adr : texcoord_adr + texcoord_num] + face_tc_idx = mj_model.mesh_facetexcoord[face_start : face_start + face_count] + + # Duplicate vertices so each face-vertex gets its own UV. + new_verts = vertices[faces.flatten()] + new_uvs = texcoords[face_tc_idx.flatten()] + new_faces = np.arange(face_count * 3).reshape(-1, 3) + + return new_verts, new_faces, new_uvs + + +def mujoco_mesh_to_trimesh(mj_model: mujoco.MjModel, geom_idx: int) -> trimesh.Trimesh: + """Convert a MuJoCo mesh geometry to a trimesh with visual appearance. + + Color resolution order: + 1. 2D texture with UVs (PBR material with baseColorTexture) + 2. Cube map texture projected by triangle normals + 3. Flat material color (mat_rgba) + 4. Flat geom color (geom_rgba) + """ + vertices, faces, uvs = _extract_mesh_data(mj_model, geom_idx) + mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) + + matid = mj_model.geom_matid[geom_idx] + + # Path 1: mesh has UVs and material has a 2D texture. + if uvs is not None and matid >= 0: + texid = _get_texture_id(mj_model, matid) + if texid >= 0: + image = _extract_texture_image(mj_model, texid) + if image is not None: + rgba = mj_model.mat_rgba[matid] + material = trimesh.visual.material.PBRMaterial( + baseColorFactor=rgba, + baseColorTexture=image, + metallicFactor=0.0, + roughnessFactor=1.0, + ) + mesh.visual = trimesh.visual.TextureVisuals(uv=uvs, material=material) + return mesh + + # Path 2: no UVs, try cube map projection. + if uvs is None and matid >= 0: + result = _cubemap_vertex_colors(mj_model, matid, vertices, faces) + if result is not None: + new_verts, new_faces, vert_colors = result + mesh = trimesh.Trimesh(vertices=new_verts, faces=new_faces, process=False) + mesh.visual = trimesh.visual.ColorVisuals(vertex_colors=vert_colors) + return mesh + + # Path 3/4: flat color from material or geom. + _apply_flat_color(mesh, _resolve_flat_rgba(mj_model, geom_idx)) + return mesh + + +def _create_shape_mesh(geom_type: int, size: np.ndarray) -> trimesh.Trimesh: + """Create an uncolored mesh for a standard shape type.""" + if geom_type == mjtGeom.mjGEOM_SPHERE: + return trimesh.creation.icosphere(radius=size[0], subdivisions=2) + elif geom_type == mjtGeom.mjGEOM_BOX: + return trimesh.creation.box(extents=2.0 * size) + elif geom_type == mjtGeom.mjGEOM_CAPSULE: + return trimesh.creation.capsule(radius=size[0], height=2.0 * size[1]) + elif geom_type == mjtGeom.mjGEOM_CYLINDER: + return trimesh.creation.cylinder(radius=size[0], height=2.0 * size[1]) + elif geom_type == mjtGeom.mjGEOM_ELLIPSOID: + mesh = trimesh.creation.icosphere(subdivisions=3, radius=1.0) + mesh.apply_scale(size) + return mesh + raise ValueError(f"Unsupported shape type: {geom_type}") + + +def create_primitive_mesh(mj_model: mujoco.MjModel, geom_id: int) -> trimesh.Trimesh: + """Create a mesh for primitive geom types. + + Supports sphere, box, capsule, cylinder, plane, ellipsoid, and + heightfield. + """ + geom_type = mj_model.geom_type[geom_id] + + if geom_type == mjtGeom.mjGEOM_HFIELD: + return _create_heightfield_mesh(mj_model, geom_id) + + if geom_type == mjtGeom.mjGEOM_PLANE: + size = mj_model.geom_size[geom_id] + plane_x = 2.0 * size[0] if size[0] > 0 else 20.0 + plane_y = 2.0 * size[1] if size[1] > 0 else 20.0 + mesh = trimesh.creation.box((plane_x, plane_y, 0.001)) + else: + mesh = _create_shape_mesh(geom_type, mj_model.geom_size[geom_id]) + + _apply_flat_color(mesh, _resolve_flat_rgba(mj_model, geom_id)) + return mesh + + +def _create_heightfield_mesh(mj_model: mujoco.MjModel, geom_id: int) -> trimesh.Trimesh: + """Create a heightfield mesh, using the material texture when available.""" + hfield_id = mj_model.geom_dataid[geom_id] + nrow = mj_model.hfield_nrow[hfield_id] + ncol = mj_model.hfield_ncol[hfield_id] + sx, sy, sz, _base = mj_model.hfield_size[hfield_id] + + offset = 0 + for k in range(hfield_id): + offset += mj_model.hfield_nrow[k] * mj_model.hfield_ncol[k] + hfield = mj_model.hfield_data[offset : offset + nrow * ncol].reshape(nrow, ncol) + + x_arr = np.linspace(-sx, sx, ncol) + y_arr = np.linspace(-sy, sy, nrow) + xx, yy = np.meshgrid(x_arr, y_arr) + zz = hfield * sz + + vertices = np.column_stack((xx.ravel(), yy.ravel(), zz.ravel())) + + ri, ci = np.mgrid[: nrow - 1, : ncol - 1] + i0 = (ri * ncol + ci).ravel() + faces = np.column_stack( + [i0, i0 + 1, i0 + ncol + 1, i0, i0 + ncol + 1, i0 + ncol] + ).reshape(-1, 3) + + # Try to use the material texture for coloring. + matid = mj_model.geom_matid[geom_id] + tex_image = None + if matid >= 0: + texid = _get_texture_id(mj_model, matid) + if texid >= 0: + tex_image = _extract_texture_image(mj_model, texid) + + if tex_image is not None: + # UV-map the texture onto the heightfield grid. + u = np.linspace(0, 1, ncol) + v = np.linspace(0, 1, nrow) + uu, vv = np.meshgrid(u, v) + uv = np.column_stack((uu.ravel(), vv.ravel())) + mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) + rgba = mj_model.mat_rgba[matid] + material = trimesh.visual.material.PBRMaterial( + baseColorFactor=rgba, + baseColorTexture=tex_image, + metallicFactor=0.0, + roughnessFactor=1.0, + ) + mesh.visual = trimesh.visual.TextureVisuals(uv=uv, material=material) + return mesh + + # Fallback: color by height using the geom/material flat color. + mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) + rgba = _resolve_flat_rgba(mj_model, geom_id) + vertex_colors = np.tile(rgba, (vertices.shape[0], 1)) + mesh.visual = trimesh.visual.ColorVisuals(mesh=mesh, vertex_colors=vertex_colors) + return mesh + + +# ------------------------------------------------------------------ +# Texture / visual utilities +# ------------------------------------------------------------------ + + +def get_geom_texture_id(mj_model: mujoco.MjModel, geom_idx: int) -> int: + """Return the texture ID the trimesh conversion will use, or -1. + + Returns -1 when the geom has no texture in the trimesh conversion + path. Mesh geoms require UVs; heightfields use their material texture + directly. + """ + matid = mj_model.geom_matid[geom_idx] + if matid < 0 or matid >= mj_model.nmat: + return -1 + + texid = _get_texture_id(mj_model, matid) + if texid < 0: + return -1 + + geom_type = mj_model.geom_type[geom_idx] + if geom_type == mjtGeom.mjGEOM_HFIELD: + return texid + + if geom_type != mjtGeom.mjGEOM_MESH: + return -1 + + mesh_id = mj_model.geom_dataid[geom_idx] + if mj_model.mesh_texcoordnum[mesh_id] <= 0: + return -1 + + return texid + + +def group_geoms_by_visual_compat( + mj_model: mujoco.MjModel, geom_ids: list[int] +) -> list[list[int]]: + """Partition geom IDs into groups that can be safely merged. + + Geoms sharing the same texture ID are grouped together. All + untextured geoms form a single group. + """ + groups: dict[int, list[int]] = {} + for gid in geom_ids: + tex_id = get_geom_texture_id(mj_model, gid) + groups.setdefault(tex_id, []).append(gid) + return list(groups.values()) + + +# ------------------------------------------------------------------ +# Merge / transform utilities +# ------------------------------------------------------------------ + + +def _can_merge_vertices(mesh: trimesh.Trimesh) -> bool: + """Check whether merge_vertices is safe (won't destroy per-vertex colors). + + trimesh's merge_vertices merges vertices at the same position regardless + of vertex color. This is unsafe when co-located vertices carry different + colors (e.g. cubemap-textured meshes where adjacent faces have different + colors at shared edges). + """ + if not isinstance(mesh.visual, trimesh.visual.ColorVisuals): + return True + vc = mesh.visual.vertex_colors + if vc is None or len(set(map(tuple, vc))) <= 1: + return True + # Check whether co-located vertices carry conflicting colors. + rounded = np.round(mesh.vertices, decimals=6) + _, inverse = np.unique(rounded, axis=0, return_inverse=True) + color_hash = ( + vc[:, 0].astype(np.uint64) << 24 + | vc[:, 1].astype(np.uint64) << 16 + | vc[:, 2].astype(np.uint64) << 8 + | vc[:, 3].astype(np.uint64) + ) + pairs = np.column_stack([inverse, color_hash]) + return len(np.unique(pairs, axis=0)) == len(np.unique(inverse)) + + +def _merge_meshes( + meshes: list[trimesh.Trimesh], + positions: list[np.ndarray], + quats: list[np.ndarray], +) -> trimesh.Trimesh: + """Transform and merge meshes given positions and wxyz quaternions.""" + for mesh, pos, quat in zip(meshes, positions, quats, strict=True): + transform = np.eye(4) + transform[:3, :3] = vtf.SO3(quat).as_matrix() + transform[:3, 3] = pos + mesh.apply_transform(transform) + + result = meshes[0] if len(meshes) == 1 else trimesh.util.concatenate(meshes) + if _can_merge_vertices(result): + result.merge_vertices() + return result + + +def merge_geoms(mj_model: mujoco.MjModel, geom_ids: list[int]) -> trimesh.Trimesh: + """Merge multiple geoms into a single trimesh in local body space.""" + meshes = [] + for geom_id in geom_ids: + if mj_model.geom_type[geom_id] == mjtGeom.mjGEOM_MESH: + meshes.append(mujoco_mesh_to_trimesh(mj_model, geom_id)) + else: + meshes.append(create_primitive_mesh(mj_model, geom_id)) + + return _merge_meshes( + meshes, + [mj_model.geom_pos[gid] for gid in geom_ids], + [mj_model.geom_quat[gid] for gid in geom_ids], + ) + + +def _hull_trimesh_for_mesh_id( + mj_model: mujoco.MjModel, mesh_id: int +) -> trimesh.Trimesh | None: + """Return convex-hull polygon faces for a mesh asset as a trimesh. + + MuJoCo stores mesh hulls as polygon loops. This helper triangulates each + polygon fan-style in the asset's local vertex index space. + """ + if mj_model.nmeshpoly == 0 or int(mj_model.mesh_polynum[mesh_id]) == 0: + return None + + vert_start = int(mj_model.mesh_vertadr[mesh_id]) + vert_count = int(mj_model.mesh_vertnum[mesh_id]) + vertices = mj_model.mesh_vert[vert_start : vert_start + vert_count].copy() + + poly_start = int(mj_model.mesh_polyadr[mesh_id]) + poly_count = int(mj_model.mesh_polynum[mesh_id]) + tri_faces: list[list[int]] = [] + + for poly_id in range(poly_start, poly_start + poly_count): + vert_adr = int(mj_model.mesh_polyvertadr[poly_id]) + vert_num = int(mj_model.mesh_polyvertnum[poly_id]) + poly_vertices = mj_model.mesh_polyvert[vert_adr : vert_adr + vert_num] + for i in range(1, vert_num - 1): + tri_faces.append( + [int(poly_vertices[0]), int(poly_vertices[i]), int(poly_vertices[i + 1])] + ) + + if not tri_faces: + return None + + return trimesh.Trimesh( + vertices=vertices, + faces=np.array(tri_faces, dtype=np.int32), + process=False, + ) + + +def merge_geoms_hull( + mj_model: mujoco.MjModel, geom_ids: list[int] +) -> trimesh.Trimesh | None: + """Merge mesh-geom convex hulls into one trimesh in local body space.""" + meshes: list[trimesh.Trimesh] = [] + positions: list[np.ndarray] = [] + quats: list[np.ndarray] = [] + + for geom_id in geom_ids: + if int(mj_model.geom_type[geom_id]) != int(mjtGeom.mjGEOM_MESH): + continue + + mesh_id = int(mj_model.geom_dataid[geom_id]) + if mesh_id < 0: + continue + + hull = _hull_trimesh_for_mesh_id(mj_model, mesh_id) + if hull is None: + continue + + meshes.append(hull) + positions.append(mj_model.geom_pos[geom_id]) + quats.append(mj_model.geom_quat[geom_id]) + + if not meshes: + return None + + return _merge_meshes(meshes, positions, quats) + + +def rotation_matrix_from_vectors( + from_vec: np.ndarray, to_vec: np.ndarray +) -> np.ndarray: + """3x3 rotation matrix that rotates from_vec to to_vec (Rodrigues).""" + from_vec = from_vec / np.linalg.norm(from_vec) + to_vec = to_vec / np.linalg.norm(to_vec) + + if np.allclose(from_vec, to_vec): + return np.eye(3) + if np.allclose(from_vec, -to_vec): + return np.array([[-1, 0, 0], [0, 1, 0], [0, 0, -1]]) + + v = np.cross(from_vec, to_vec) + s = np.linalg.norm(v) + c = np.dot(from_vec, to_vec) + vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) + return np.eye(3) + vx + vx @ vx * ((1 - c) / (s * s)) + + +def is_fixed_body(mj_model: mujoco.MjModel, body_id: int) -> bool: + """Check if a body is fixed (welded to world, not attached to mocap).""" + is_weld = mj_model.body_weldid[body_id] == 0 + root_id = mj_model.body_rootid[body_id] + return bool(is_weld and mj_model.body_mocapid[root_id] < 0) + + +def get_body_name(mj_model: mujoco.MjModel, body_id: int) -> str: + """Body name with fallback to ``body_{id}``.""" + name = mj_id2name(mj_model, mjtObj.mjOBJ_BODY, body_id) + return name if name else f"body_{body_id}" + + +def create_site_mesh(mj_model: mujoco.MjModel, site_id: int) -> trimesh.Trimesh: + """Create a mesh for a single site.""" + rgba = mj_model.site_rgba[site_id].copy() + if np.all(rgba == 0): + rgba = np.array([0.5, 0.5, 0.5, 1.0]) + rgba_uint8 = (np.clip(rgba, 0, 1) * 255).astype(np.uint8) + + mesh = _create_shape_mesh(mj_model.site_type[site_id], mj_model.site_size[site_id]) + _apply_flat_color(mesh, rgba_uint8) + return mesh + + +def merge_sites(mj_model: mujoco.MjModel, site_ids: list[int]) -> trimesh.Trimesh: + """Merge multiple sites into a single trimesh in local body space.""" + return _merge_meshes( + [create_site_mesh(mj_model, sid) for sid in site_ids], + [mj_model.site_pos[sid] for sid in site_ids], + [mj_model.site_quat[sid] for sid in site_ids], + ) + + +def get_site_name(mj_model: mujoco.MjModel, site_id: int) -> str: + """Site name with fallback to ``site_{id}``.""" + name = mj_id2name(mj_model, mjtObj.mjOBJ_SITE, site_id) + return name if name else f"site_{site_id}" diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/py.typed b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/scene.py b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/scene.py new file mode 100644 index 0000000000000000000000000000000000000000..19a3e64467e6cc058ad6ba4e8a7a45c18e4b6cf3 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/scene.py @@ -0,0 +1,1459 @@ +"""Manages all Viser visualization handles and state for MuJoCo models.""" + +from __future__ import annotations + +import dataclasses +from collections import defaultdict +from collections.abc import Callable +from threading import RLock + +import mujoco +import numpy as np +import trimesh +import viser +import viser.transforms as vtf +from mujoco import mj_id2name, mjtGeom, mjtObj + +from .conversions import ( + get_body_name, + group_geoms_by_visual_compat, + is_fixed_body, + merge_geoms, + merge_geoms_hull, + merge_sites, +) + + +@dataclasses.dataclass +class _MeshGroup: + """A group of bodies sharing identical geometry, rendered as one batched handle.""" + + handle: viser.BatchedGlbHandle + body_ids: np.ndarray # (N,) int32 array of body IDs + group_id: int + mocap_ids: np.ndarray | None # (N,) int32 mocap IDs, or None if non-mocap + + +# Viser visualization defaults. +_DEFAULT_FOV_DEGREES = 60 +_DEFAULT_FOV_MIN = 20 +_DEFAULT_FOV_MAX = 150 +_DEFAULT_ENVIRONMENT_INTENSITY = 0.8 +_DEFAULT_CONTACT_POINT_COLOR = (230, 153, 51) +_DEFAULT_CONTACT_FORCE_COLOR = (255, 0, 0) + +# Map from frame mode name to mjtFrame enum value. +_FRAME_MODES: dict[str, int] = { + "None": int(mujoco.mjtFrame.mjFRAME_NONE), + "Body": int(mujoco.mjtFrame.mjFRAME_BODY), + "Geom": int(mujoco.mjtFrame.mjFRAME_GEOM), + "Site": int(mujoco.mjtFrame.mjFRAME_SITE), +} + +# Geom type constants (avoid repeated int() casts). +_CYLINDER = int(mjtGeom.mjGEOM_CYLINDER) +_CAPSULE = int(mjtGeom.mjGEOM_CAPSULE) +_BOX = int(mjtGeom.mjGEOM_BOX) +_ELLIPSOID = int(mjtGeom.mjGEOM_ELLIPSOID) +_SPHERE = int(mjtGeom.mjGEOM_SPHERE) +_ARROW = int(mjtGeom.mjGEOM_ARROW) +_ARROW1 = int(mjtGeom.mjGEOM_ARROW1) +_ARROW2 = int(mjtGeom.mjGEOM_ARROW2) +_ARROWS = (_ARROW, _ARROW1, _ARROW2) +_ARROW_HEAD = -1 # Synthetic geom type for arrow cone heads. + +_CAT_DECOR = int(mujoco.mjtCatBit.mjCAT_DECOR) +_OBJ_TENDON = int(mujoco.mjtObj.mjOBJ_TENDON) +_OBJ_JOINT = int(mujoco.mjtObj.mjOBJ_JOINT) + +# Cached unit meshes for decor rendering, keyed by mjtGeom int value. +_UNIT_MESHES: dict[int, trimesh.Trimesh] = {} + + +def _get_unit_mesh(geom_type: int) -> trimesh.Trimesh: + """Return a cached unit mesh for the given mjvGeom type.""" + if geom_type not in _UNIT_MESHES: + if geom_type == _CYLINDER: + _UNIT_MESHES[geom_type] = trimesh.creation.cylinder(radius=1.0, height=1.0) + elif geom_type == _CAPSULE: + _UNIT_MESHES[geom_type] = trimesh.creation.capsule(radius=1.0, height=1.0) + elif geom_type == _BOX: + _UNIT_MESHES[geom_type] = trimesh.creation.box(extents=[2.0, 2.0, 2.0]) + elif geom_type in (_ELLIPSOID, _SPHERE): + _UNIT_MESHES[geom_type] = trimesh.creation.icosphere(subdivisions=2, radius=1.0) + elif geom_type in _ARROWS: + # Arrow shaft: cylinder centered at origin, height along Z. + shaft = trimesh.creation.cylinder(radius=1.0, height=1.0, sections=12) + shaft.apply_translation([0, 0, 0.5]) + _UNIT_MESHES[geom_type] = shaft + elif geom_type == _ARROW_HEAD: + _UNIT_MESHES[geom_type] = trimesh.creation.cone( + radius=2.0, height=1.0, sections=12 + ) + else: + _UNIT_MESHES[geom_type] = trimesh.creation.icosphere(subdivisions=1, radius=1.0) + return _UNIT_MESHES[geom_type] + + +class ViserMujocoScene: + """Manages Viser scene handles and visualization state for MuJoCo models. + + This class handles geometry creation, batched rendering of bodies and + sites across multiple environments, contact visualization, and GUI + controls. Users build custom overlays on top using the ``server`` + attribute and viser's native API. + """ + + def __init__( + self, + server: viser.ViserServer, + mj_model: mujoco.MjModel, + num_envs: int, + ) -> None: + """Create and populate a scene with geometry. + + Args: + server: Viser server instance. + mj_model: MuJoCo model. + num_envs: Number of parallel environments. + """ + self.server = server + self.mj_model = mj_model + self.mj_data = mujoco.MjData(mj_model) + self.num_envs = num_envs + + # mjvScene infrastructure for decor visualization. + self._mjv_scene = mujoco.MjvScene(mj_model, maxgeom=max(2000, mj_model.ngeom * 2)) + self._mjv_option = mujoco.MjvOption() + self._mjv_camera = mujoco.MjvCamera() + # Disable all vis flags; properties below enable them on demand. + self._mjv_option.flags[:] = 0 + self._mjv_option.frame = int(mujoco.mjtFrame.mjFRAME_NONE) + + # Handles. + self._mesh_groups: list[_MeshGroup] = [] + self.site_handles_by_group: dict[tuple[int, int], viser.BatchedGlbHandle] = {} + self._decor_handles: dict[tuple[int, bool], viser.BatchedMeshHandle] = {} + self._fixed_geom_handles: dict[tuple[int, int, int], viser.GlbHandle] = {} + self._fixed_site_handles: dict[tuple[int, int], viser.GlbHandle] = {} + self._update_lock = RLock() + self._refresh_handler: Callable[[], None] | None = None + self._hull_body_meshes: dict[int, tuple[np.ndarray, np.ndarray]] = {} + self._hull_mesh_bodies: set[int] = set() + self._hull_fixed_handles: dict[int, viser.BatchedMeshHandle] = {} + self._hull_dynamic_handles: list[tuple[viser.BatchedMeshHandle, int]] = [] + self._hull_color: tuple[int, int, int] = (230, 230, 255) + self._hull_opacity: float = 0.5 + self._show_convex_hull: bool = False + self._hull_hide_meshes: bool = False + self._autoconnect_hide_meshes: bool = False + + # Visualization settings. + self.env_idx = 0 + self.camera_tracking_enabled = True + self.show_only_selected = False + self.geom_groups_visible = [True, True, True, False, False, False] + self.site_groups_visible = [True, True, True, False, False, False] + self.meansize_override: float | None = None + + # Set default colors for decor elements (written to model.vis.rgba). + mj_model.vis.rgba.contactpoint[:] = [ + _DEFAULT_CONTACT_POINT_COLOR[0] / 255, + _DEFAULT_CONTACT_POINT_COLOR[1] / 255, + _DEFAULT_CONTACT_POINT_COLOR[2] / 255, + 0.8, + ] + mj_model.vis.rgba.contactforce[:] = [ + _DEFAULT_CONTACT_FORCE_COLOR[0] / 255, + _DEFAULT_CONTACT_FORCE_COLOR[1] / 255, + _DEFAULT_CONTACT_FORCE_COLOR[2] / 255, + 0.8, + ] + mj_model.vis.rgba.inertia[:] = [1.0, 0.7, 0.24, 0.5] + + # Scale MuJoCo's overlay defaults proportionally so author-specified + # values are preserved rather than replaced outright. + mj_model.vis.scale.framewidth *= 0.3 + mj_model.vis.scale.jointwidth *= 0.3 + mj_model.vis.scale.actuatorlength *= 1.4 + mj_model.vis.scale.actuatorwidth *= 0.15 + mj_model.vis.scale.contactwidth *= 0.5 + mj_model.vis.scale.contactheight *= 0.5 + mj_model.vis.scale.forcewidth *= 0.5 + + self.needs_update = False + self.paused = False + + # Cached visualization state for re-rendering when settings change. + self._tracked_body_id: int | None = None + self._last_body_xpos: np.ndarray | None = None + self._last_body_xmat: np.ndarray | None = None + self._last_mocap_pos: np.ndarray | None = None + self._last_mocap_quat: np.ndarray | None = None + self._last_env_idx = 0 + self._last_mj_data: mujoco.MjData | None = None + self._scene_offset = np.zeros(3) + + # Build the scene. + server.scene.configure_environment_map( + environment_intensity=_DEFAULT_ENVIRONMENT_INTENSITY + ) + self.fixed_bodies_frame = server.scene.add_frame("/fixed_bodies", show_axes=False) + # Populate xpos/xquat so fixed body geometry is placed in world space. + mujoco.mj_kinematics(mj_model, self.mj_data) + self._add_fixed_geometry() + self._create_mesh_handles_by_group() + self._add_fixed_sites() + self._create_site_handles_by_group() + self._compute_hull_body_meshes() + self._build_hull_handles() + + for body_id in range(mj_model.nbody): + if not is_fixed_body(mj_model, body_id): + self._tracked_body_id = body_id + break + + # -- Overlay visibility properties (backed by mjvOption flags) ----------- + + @property + def show_contact_points(self) -> bool: + return bool(self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT]) + + @show_contact_points.setter + def show_contact_points(self, value: bool) -> None: + self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT] = int(value) + + @property + def show_contact_forces(self) -> bool: + return bool(self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTFORCE]) + + @show_contact_forces.setter + def show_contact_forces(self, value: bool) -> None: + self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTFORCE] = int(value) + + @property + def show_tendons(self) -> bool: + return bool(self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_TENDON]) + + @show_tendons.setter + def show_tendons(self, value: bool) -> None: + self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_TENDON] = int(value) + + @property + def show_inertia(self) -> bool: + return bool(self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_INERTIA]) + + @show_inertia.setter + def show_inertia(self, value: bool) -> None: + self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_INERTIA] = int(value) + + @property + def show_actuators(self) -> bool: + return bool(self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_ACTUATOR]) + + @show_actuators.setter + def show_actuators(self, value: bool) -> None: + self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_ACTUATOR] = int(value) + + @property + def show_convex_hull(self) -> bool: + return self._show_convex_hull + + @show_convex_hull.setter + def show_convex_hull(self, value: bool) -> None: + with self._update_lock: + self._show_convex_hull = value + for handle in self._hull_fixed_handles.values(): + handle.visible = value + for handle, _ in self._hull_dynamic_handles: + handle.visible = value + self._sync_visibilities() + + def set_refresh_handler(self, handler: Callable[[], None] | None) -> None: + """Install a callback used to refresh cached visualization state.""" + with self._update_lock: + self._refresh_handler = handler + + def _apply_visualization_change(self, mutator: Callable[[], None]) -> None: + """Apply a GUI-side visualization change and refresh from cached state.""" + refresh_handler: Callable[[], None] | None = None + with self._update_lock: + mutator() + self.needs_update = True + refresh_handler = self._refresh_handler + if refresh_handler is None: + self._refresh_visualization_locked() + return + refresh_handler() + + @property + def frame_mode(self) -> str: + current = int(self._mjv_option.frame) + for name, val in _FRAME_MODES.items(): + if val == current: + return name + return "None" + + @frame_mode.setter + def frame_mode(self, value: str) -> None: + self._mjv_option.frame = _FRAME_MODES.get(value, 0) + + def _any_decor_visible(self) -> bool: + """Return True if any overlay visualization is enabled.""" + if self.frame_mode != "None": + return True + return any(self._mjv_option.flags[i] for i in range(len(self._mjv_option.flags))) + + def _sync_visibilities(self) -> None: + """Synchronize all handle visibilities based on current flags.""" + hidden_bodies: set[int] = set() + if self._show_convex_hull and self._hull_hide_meshes: + hidden_bodies = self._hull_mesh_bodies + if ( + self._mjv_option.flags[mujoco.mjtVisFlag.mjVIS_AUTOCONNECT] + and self._autoconnect_hide_meshes + ): + hidden_bodies |= set(range(self.mj_model.nbody)) + + for mg in self._mesh_groups: + visible = mg.group_id < 6 and self.geom_groups_visible[mg.group_id] + if visible and any(body_id in hidden_bodies for body_id in mg.body_ids): + visible = False + mg.handle.visible = visible + + for (body_id, group_id, _), handle in self._fixed_geom_handles.items(): + visible = group_id < 6 and self.geom_groups_visible[group_id] + if visible and body_id in hidden_bodies: + visible = False + handle.visible = visible + + for (_, group_id), handle in self.site_handles_by_group.items(): + handle.visible = group_id < 6 and self.site_groups_visible[group_id] + + for (_, group_id), handle in self._fixed_site_handles.items(): + handle.visible = group_id < 6 and self.site_groups_visible[group_id] + + if not self._any_decor_visible(): + for handle in self._decor_handles.values(): + handle.visible = False + + def create_scene_gui( + self, + camera_distance: float = -1.0, + camera_azimuth: float = 120.0, + camera_elevation: float = 20.0, + ) -> None: + """Add camera and environment controls into the current GUI context. + + Args: + camera_distance: Default camera distance. If negative, derived + from model extent. + camera_azimuth: Default camera azimuth angle in degrees. + camera_elevation: Default camera elevation angle in degrees. + """ + if self.num_envs > 1: + with self.server.gui.add_folder("Environment"): + env_slider = self.server.gui.add_slider( + "Select", + min=0, + max=self.num_envs - 1, + step=1, + initial_value=self.env_idx, + hint=f"Select environment (0-{self.num_envs - 1})", + ) + + @env_slider.on_update + def _(_) -> None: + self._apply_visualization_change( + lambda: setattr(self, "env_idx", int(env_slider.value)) + ) + + show_only_cb = self.server.gui.add_checkbox( + "Hide others", + initial_value=self.show_only_selected, + hint="Show only the selected environment.", + ) + + @show_only_cb.on_update + def _(_) -> None: + self._apply_visualization_change( + lambda: setattr(self, "show_only_selected", show_only_cb.value) + ) + + _center = self.mj_model.stat.center.copy() + _extent = self.mj_model.stat.extent + if camera_distance <= 0: + camera_distance = 3.0 * _extent + _az_rad = np.deg2rad(camera_azimuth) + _el_rad = np.deg2rad(camera_elevation) + _camera_offset = ( + np.array( + [ + -np.cos(_el_rad) * np.cos(_az_rad), + -np.cos(_el_rad) * np.sin(_az_rad), + np.sin(_el_rad), + ] + ) + * camera_distance + ) + + with self.server.gui.add_folder("Camera"): + cb_camera_tracking = self.server.gui.add_checkbox( + "Track camera", + initial_value=self.camera_tracking_enabled, + hint="Keep tracked body centered.", + ) + + @cb_camera_tracking.on_update + def _(_) -> None: + def _mutate() -> None: + self.camera_tracking_enabled = cb_camera_tracking.value + if self.camera_tracking_enabled: + for client in self.server.get_clients().values(): + client.camera.position = _camera_offset + client.camera.look_at = np.zeros(3) + + self._apply_visualization_change(_mutate) + + slider_fov = self.server.gui.add_slider( + "FOV (\u00b0)", + min=_DEFAULT_FOV_MIN, + max=_DEFAULT_FOV_MAX, + step=1, + initial_value=_DEFAULT_FOV_DEGREES, + hint="Vertical FOV in degrees.", + ) + + @slider_fov.on_update + def _(_) -> None: + for client in self.server.get_clients().values(): + client.camera.fov = np.radians(slider_fov.value) + + @self.server.on_client_connect + def _(client: viser.ClientHandle) -> None: + client.camera.fov = np.radians(slider_fov.value) + client.camera.position = _camera_offset + client.camera.look_at = np.zeros(3) if self.camera_tracking_enabled else _center + + def create_overlay_gui(self) -> None: + """Add overlay visualization controls into the current GUI context. + + Controls are grouped by feature so that toggle, color, opacity, + and scale live together for each overlay type. + """ + _rgba = self.mj_model.vis.rgba + _vis = self.mj_model.vis.scale + _map = self.mj_model.vis.map + _stat = self.mj_model.stat + _opt = self._mjv_option + + def _vis_flag_cb(flag_idx: int, initial: bool = False) -> None: + """Add a vis-flag checkbox at the current GUI level.""" + _opt.flags[flag_idx] = int(initial) + cb = self.server.gui.add_checkbox("Enabled", initial_value=initial) + + @cb.on_update + def _(event, _idx=flag_idx) -> None: + self._apply_visualization_change( + lambda: _opt.flags.__setitem__(_idx, int(event.target.value)) + ) + + def _color_controls(rgba_attr: str) -> None: + """Add color picker + opacity slider for a model.vis.rgba field.""" + rgba_arr = getattr(_rgba, rgba_attr) + rgb_init = ( + int(rgba_arr[0] * 255), + int(rgba_arr[1] * 255), + int(rgba_arr[2] * 255), + ) + cp = self.server.gui.add_rgb("Color", initial_value=rgb_init) + op = self.server.gui.add_slider( + "Opacity", + min=0.0, + max=1.0, + step=0.05, + initial_value=float(rgba_arr[3]), + ) + + def _on_update(_, _a=rgba_attr, _cp=cp, _op=op) -> None: + def _mutate() -> None: + arr = getattr(_rgba, _a) + r, g, b = _cp.value + arr[:] = [r / 255, g / 255, b / 255, _op.value] + + self._apply_visualization_change(_mutate) + + cp.on_update(_on_update) + op.on_update(_on_update) + + def _scale_slider( + label: str, + obj: object, + attr: str, + lo: float, + hi: float, + step: float, + ) -> None: + """Add a scale slider that writes to a model field.""" + lo_r, hi_r = round(lo, 6), round(hi, 6) + step_r = round(step, 6) or round((hi - lo) / 200, 6) + val = max(lo_r, min(hi_r, round(float(getattr(obj, attr)), 6))) + sl = self.server.gui.add_slider( + label, + min=lo_r, + max=hi_r, + step=step_r, + initial_value=val, + ) + + @sl.on_update + def _(_, _obj=obj, _attr=attr, _sl=sl) -> None: + self._apply_visualization_change(lambda: setattr(_obj, _attr, _sl.value)) + + # -- Frames ----------------------------------------------------------- + + frame_dropdown = self.server.gui.add_dropdown( + "Frames", options=["None", "Body", "Geom", "Site"] + ) + + @frame_dropdown.on_update + def _(_) -> None: + self._apply_visualization_change( + lambda: setattr(self, "frame_mode", frame_dropdown.value) + ) + + _scale_slider("Frame length", _vis, "framelength", 0.1, 5.0, 0.05) + _scale_slider("Frame width", _vis, "framewidth", 0.01, 1.0, 0.01) + + # -- Contact points --------------------------------------------------- + + with self.server.gui.add_folder("Contact points"): + _vis_flag_cb(int(mujoco.mjtVisFlag.mjVIS_CONTACTPOINT)) + _color_controls("contactpoint") + _scale_slider("Width", _vis, "contactwidth", 0.01, 2.0, 0.01) + _scale_slider("Height", _vis, "contactheight", 0.01, 1.0, 0.01) + + # -- Contact forces --------------------------------------------------- + + with self.server.gui.add_folder("Contact forces"): + _vis_flag_cb(int(mujoco.mjtVisFlag.mjVIS_CONTACTFORCE)) + _color_controls("contactforce") + _scale_slider("Width", _vis, "forcewidth", 0.01, 1.0, 0.01) + _scale_slider("Force scale", _map, "force", 0.001, 0.1, 0.001) + + cb_split = self.server.gui.add_checkbox( + "Split normal/friction", initial_value=False + ) + + @cb_split.on_update + def _(event) -> None: + self._apply_visualization_change( + lambda: _opt.flags.__setitem__( + mujoco.mjtVisFlag.mjVIS_CONTACTSPLIT, int(event.target.value) + ) + ) + + # -- Inertia ---------------------------------------------------------- + + with self.server.gui.add_folder("Inertia"): + _vis_flag_cb(int(mujoco.mjtVisFlag.mjVIS_INERTIA)) + + inertia_shape = self.server.gui.add_dropdown( + "Shape", + options=["Box", "Ellipsoid"], + initial_value=( + "Ellipsoid" if self.mj_model.vis.global_.ellipsoidinertia else "Box" + ), + ) + + @inertia_shape.on_update + def _(_) -> None: + self._apply_visualization_change( + lambda: setattr( + self.mj_model.vis.global_, + "ellipsoidinertia", + int(inertia_shape.value == "Ellipsoid"), + ) + ) + + _color_controls("inertia") + + # -- Joints ----------------------------------------------------------- + + with self.server.gui.add_folder("Joints"): + _vis_flag_cb(int(mujoco.mjtVisFlag.mjVIS_JOINT)) + _color_controls("joint") + _scale_slider("Length", _vis, "jointlength", 0.1, 5.0, 0.05) + _scale_slider("Width", _vis, "jointwidth", 0.01, 1.0, 0.01) + + # -- Actuators ------------------------------------------------------- + + with self.server.gui.add_folder("Actuators"): + _vis_flag_cb(int(mujoco.mjtVisFlag.mjVIS_ACTUATOR)) + _color_controls("actuator") + _scale_slider("Length", _vis, "actuatorlength", 0.1, 5.0, 0.05) + _scale_slider("Width", _vis, "actuatorwidth", 0.01, 1.0, 0.01) + + # -- Auto-connect ---------------------------------------------------- + + with self.server.gui.add_folder("Auto-connect"): + _vis_flag_cb(int(mujoco.mjtVisFlag.mjVIS_AUTOCONNECT)) + autoconnect_hide_meshes = self.server.gui.add_checkbox( + "Hide meshes", initial_value=False + ) + _color_controls("connect") + _scale_slider("Width", _vis, "connect", 0.01, 1.0, 0.01) + + @autoconnect_hide_meshes.on_update + def _(_) -> None: + def _mutate() -> None: + self._autoconnect_hide_meshes = autoconnect_hide_meshes.value + self._sync_visibilities() + + self._apply_visualization_change(_mutate) + + # -- Convex hull ------------------------------------------------------ + + with self.server.gui.add_folder("Convex hull"): + hull_enabled = self.server.gui.add_checkbox("Enabled", initial_value=False) + hull_hide_meshes = self.server.gui.add_checkbox( + "Hide meshes", initial_value=False + ) + hull_color = self.server.gui.add_rgb("Color", initial_value=self._hull_color) + hull_opacity = self.server.gui.add_slider( + "Opacity", + min=0.0, + max=1.0, + step=0.05, + initial_value=self._hull_opacity, + ) + + @hull_enabled.on_update + def _(_) -> None: + self._apply_visualization_change( + lambda: setattr(self, "show_convex_hull", hull_enabled.value) + ) + + @hull_hide_meshes.on_update + def _(_) -> None: + def _mutate() -> None: + self._hull_hide_meshes = hull_hide_meshes.value + self._sync_visibilities() + + self._apply_visualization_change(_mutate) + + def _rebuild_hulls(_=None) -> None: + def _mutate() -> None: + self._hull_color = hull_color.value + self._hull_opacity = hull_opacity.value + self._clear_hull_handles() + self._build_hull_handles() + self.show_convex_hull = hull_enabled.value + + self._apply_visualization_change(_mutate) + + hull_color.on_update(_rebuild_hulls) + hull_opacity.on_update(_rebuild_hulls) + + # -- Simple toggles --------------------------------------------------- + + _tendon_flag = int(mujoco.mjtVisFlag.mjVIS_TENDON) + _opt.flags[_tendon_flag] = int(self.mj_model.ntendon > 0) + _simple_flags: list[tuple[str, int, bool]] = [ + ("Tendons", _tendon_flag, self.mj_model.ntendon > 0), + ("COM", int(mujoco.mjtVisFlag.mjVIS_COM), False), + ("Constraints", int(mujoco.mjtVisFlag.mjVIS_CONSTRAINT), False), + ] + + for label, flag_idx, initial in _simple_flags: + cb = self.server.gui.add_checkbox(label, initial_value=initial) + + @cb.on_update + def _(event, _idx=flag_idx) -> None: + self._apply_visualization_change( + lambda: _opt.flags.__setitem__(_idx, int(event.target.value)) + ) + + # -- Global scale ----------------------------------------------------- + + _scale_slider( + "Global scale", + _stat, + "meansize", + _stat.meansize * 0.1, + _stat.meansize * 5.0, + _stat.meansize * 0.01, + ) + + def create_groups_gui(self) -> None: + """Add geom and site group visibility checkboxes into the + current GUI context.""" + with self.server.gui.add_folder("Geoms"): + for i in range(6): + cb = self.server.gui.add_checkbox( + f"G{i}", + initial_value=self.geom_groups_visible[i], + hint=f"Show/hide geometry in group {i}", + ) + + @cb.on_update + def _(event, group_idx=i) -> None: + def _mutate() -> None: + self.geom_groups_visible[group_idx] = event.target.value + self._sync_visibilities() + + self._apply_visualization_change(_mutate) + + with self.server.gui.add_folder("Sites"): + for i in range(6): + cb = self.server.gui.add_checkbox( + f"S{i}", + initial_value=self.site_groups_visible[i], + hint=f"Show/hide sites in group {i}", + ) + + @cb.on_update + def _(event, group_idx=i) -> None: + def _mutate() -> None: + self.site_groups_visible[group_idx] = event.target.value + self._sync_visibilities() + + self._apply_visualization_change(_mutate) + + # mjvOption group arrays for decor elements. + _opt_groups: list[tuple[str, str]] = [ + ("Joints", "jointgroup"), + ("Tendons", "tendongroup"), + ("Actuators", "actuatorgroup"), + ] + for folder_name, attr in _opt_groups: + group_arr = getattr(self._mjv_option, attr) + with self.server.gui.add_folder(folder_name): + for i in range(6): + cb = self.server.gui.add_checkbox( + f"{folder_name[0]}{i}", + initial_value=bool(group_arr[i]), + ) + + @cb.on_update + def _(event, _arr=group_arr, _idx=i) -> None: + self._apply_visualization_change( + lambda: _arr.__setitem__(_idx, int(event.target.value)) + ) + + def create_visualization_gui( + self, + camera_distance: float = -1.0, + camera_azimuth: float = 120.0, + camera_elevation: float = 20.0, + ) -> viser.GuiTabGroupHandle: + """Add scene, overlay, and group controls in a tabbed layout. + + Returns the tab group so callers can append additional tabs. + + Args: + camera_distance: Default camera distance. If negative, derived + from model extent. + camera_azimuth: Default camera azimuth angle in degrees. + camera_elevation: Default camera elevation angle in degrees. + """ + tabs = self.server.gui.add_tab_group() + with tabs.add_tab("Scene", icon=viser.Icon.VIDEO): + self.create_scene_gui( + camera_distance=camera_distance, + camera_azimuth=camera_azimuth, + camera_elevation=camera_elevation, + ) + with tabs.add_tab("Visualization", icon=viser.Icon.EYE): + self.create_overlay_gui() + with tabs.add_tab("Groups", icon=viser.Icon.LAYERS_INTERSECT): + self.create_groups_gui() + return tabs + + def update_from_arrays( + self, + body_xpos: np.ndarray, + body_xmat: np.ndarray, + mocap_pos: np.ndarray | None = None, + mocap_quat: np.ndarray | None = None, + env_idx: int | None = None, + qpos: np.ndarray | None = None, + qvel: np.ndarray | None = None, + ctrl: np.ndarray | None = None, + ) -> None: + """Update scene from batched numpy arrays. + + Args: + body_xpos: Body positions, shape ``(num_envs, nbody, 3)``. + body_xmat: Body rotation matrices, shape + ``(num_envs, nbody, 3, 3)``. + mocap_pos: Mocap body positions, shape + ``(num_envs, nmocap, 3)``. + mocap_quat: Mocap body quaternions (wxyz), shape + ``(num_envs, nmocap, 4)``. + env_idx: Environment index to visualize. If None, uses + ``self.env_idx``. + qpos: Joint positions. Required for contact and tendon + visualization in the selected environment. + qvel: Joint velocities. Required for contact and tendon + visualization in the selected environment. + ctrl: Controls for the selected environment. + """ + if env_idx is None: + env_idx = self.env_idx + + if mocap_pos is None: + nworld = body_xpos.shape[0] + mocap_pos = np.zeros((nworld, max(self.mj_model.nmocap, 0), 3)) + if mocap_quat is None: + nworld = body_xpos.shape[0] + mocap_quat = np.zeros((nworld, max(self.mj_model.nmocap, 0), 4)) + + scene_offset = np.zeros(3) + if self.camera_tracking_enabled and self._tracked_body_id is not None: + tracked_pos = body_xpos[env_idx, self._tracked_body_id, :].copy() + scene_offset = -tracked_pos + + mj_data: mujoco.MjData | None = None + if self._any_decor_visible() and qpos is not None and qvel is not None: + self.mj_data.qpos[:] = qpos[env_idx] + self.mj_data.qvel[:] = qvel[env_idx] + if ctrl is not None and self.mj_model.nu > 0: + self.mj_data.ctrl[:] = ctrl[env_idx] + if self.mj_model.nmocap > 0: + self.mj_data.mocap_pos[:] = mocap_pos[env_idx] + self.mj_data.mocap_quat[:] = mocap_quat[env_idx] + mujoco.mj_forward(self.mj_model, self.mj_data) + mj_data = self.mj_data + + self._update_visualization( + body_xpos, + body_xmat, + mocap_pos, + mocap_quat, + env_idx, + scene_offset, + mj_data, + ) + + def update_from_mjdata(self, mj_data: mujoco.MjData) -> None: + """Update scene from single-environment MuJoCo data. + + Args: + mj_data: Single environment MuJoCo data. + """ + body_xpos = mj_data.xpos[None, ...] + body_xmat = mj_data.xmat.reshape(-1, 3, 3)[None, ...] + if self.mj_model.nmocap > 0: + mocap_pos = mj_data.mocap_pos[None, ...] + mocap_quat = mj_data.mocap_quat[None, ...] + else: + mocap_pos = np.zeros((1, 0, 3)) + mocap_quat = np.zeros((1, 0, 4)) + env_idx = 0 + scene_offset = np.zeros(3) + if self.camera_tracking_enabled and self._tracked_body_id is not None: + tracked_pos = mj_data.xpos[self._tracked_body_id, :].copy() + scene_offset = -tracked_pos + + self._update_visualization( + body_xpos, + body_xmat, + mocap_pos, + mocap_quat, + env_idx, + scene_offset, + mj_data, + ) + + def _update_visualization( + self, + body_xpos: np.ndarray, + body_xmat: np.ndarray, + mocap_pos: np.ndarray, + mocap_quat: np.ndarray, + env_idx: int, + scene_offset: np.ndarray, + mj_data: mujoco.MjData | None = None, + ) -> None: + """Shared visualization update logic.""" + with self._update_lock: + self._update_visualization_locked( + body_xpos, + body_xmat, + mocap_pos, + mocap_quat, + env_idx, + scene_offset, + mj_data, + ) + + def _update_visualization_locked( + self, + body_xpos: np.ndarray, + body_xmat: np.ndarray, + mocap_pos: np.ndarray, + mocap_quat: np.ndarray, + env_idx: int, + scene_offset: np.ndarray, + mj_data: mujoco.MjData | None = None, + ) -> None: + """Shared visualization update logic. + + The caller must hold ``self._update_lock``. + """ + self._last_body_xpos = body_xpos + self._last_body_xmat = body_xmat + self._last_mocap_pos = mocap_pos + self._last_mocap_quat = mocap_quat + self._last_env_idx = env_idx + self._scene_offset = scene_offset + if mj_data is not None: + self._last_mj_data = mj_data + + self.fixed_bodies_frame.position = scene_offset + slice_single = self.show_only_selected and self.num_envs > 1 + with self.server.atomic(): + body_xquat = vtf.SO3.from_matrix(body_xmat).wxyz + for mg in self._mesh_groups: + if not mg.handle.visible: + continue + if mg.mocap_ids is not None: + pos, quat = self._batched_transform_group( + mocap_pos, mocap_quat, mg.mocap_ids, env_idx, scene_offset, slice_single + ) + else: + pos, quat = self._batched_transform_group( + body_xpos, body_xquat, mg.body_ids, env_idx, scene_offset, slice_single + ) + mg.handle.batched_positions = pos + mg.handle.batched_wxyzs = quat + + for (body_id, _), handle in self.site_handles_by_group.items(): + if not handle.visible: + continue + pos, quat = self._batched_transform( + body_xpos, body_xquat, body_id, env_idx, scene_offset, slice_single + ) + handle.batched_positions = pos + handle.batched_wxyzs = quat + + if self._show_convex_hull: + for handle, body_id in self._hull_dynamic_handles: + if not handle.visible: + continue + pos, quat = self._batched_transform( + body_xpos, body_xquat, body_id, env_idx, scene_offset, slice_single + ) + handle.batched_positions = pos + handle.batched_wxyzs = quat + + if self._any_decor_visible() and mj_data is not None: + self._update_decor_from_mjvscene(mj_data, scene_offset) + elif not self._any_decor_visible(): + self._clear_decor_handles() + + self.server.flush() + + def _batched_transform( + self, + positions: np.ndarray, + quats: np.ndarray, + idx: int, + env_idx: int, + scene_offset: np.ndarray, + slice_single: bool, + ) -> tuple[np.ndarray, np.ndarray]: + """Return (batched_positions, batched_wxyzs) for a single body.""" + if slice_single: + pos = positions[env_idx : env_idx + 1, idx] + scene_offset + quat = quats[env_idx : env_idx + 1, idx] + else: + pos = positions[..., idx, :] + scene_offset + quat = quats[..., idx, :] + return pos, quat + + def _batched_transform_group( + self, + positions: np.ndarray, + quats: np.ndarray, + ids: np.ndarray, + env_idx: int, + scene_offset: np.ndarray, + slice_single: bool, + ) -> tuple[np.ndarray, np.ndarray]: + """Return (batched_positions, batched_wxyzs) for a group of bodies. + + Gathers transforms for all body IDs in ``ids`` and flattens + the result to ``(num_envs * len(ids), 3/4)``. + """ + if slice_single: + # Show only selected env. + pos = positions[env_idx : env_idx + 1, ids].reshape(-1, 3) + scene_offset + quat = quats[env_idx : env_idx + 1, ids].reshape(-1, 4) + else: + # positions[:, ids, :] → (num_envs, N, 3) → (num_envs * N, 3) + pos = (positions[:, ids, :] + scene_offset).reshape(-1, 3) + quat = quats[:, ids, :].reshape(-1, 4) + return pos, quat + + def request_update(self) -> None: + """Request a visualization update and trigger immediate re-render + from cache.""" + self._apply_visualization_change(lambda: None) + + def refresh_visualization(self) -> None: + """Re-render the scene using cached visualization data.""" + with self._update_lock: + self._refresh_visualization_locked() + + def _refresh_visualization_locked(self) -> None: + """Re-render the scene using cached visualization data. + + The caller must hold ``self._update_lock``. + """ + if ( + self._last_body_xpos is None + or self._last_body_xmat is None + or self._last_mocap_pos is None + or self._last_mocap_quat is None + ): + return + + scene_offset = np.zeros(3) + if self.camera_tracking_enabled and self._tracked_body_id is not None: + tracked_pos = self._last_body_xpos[ + self._last_env_idx, self._tracked_body_id, : + ].copy() + scene_offset = -tracked_pos + + self._update_visualization_locked( + self._last_body_xpos, + self._last_body_xmat, + self._last_mocap_pos, + self._last_mocap_quat, + self._last_env_idx, + scene_offset, + self._last_mj_data, + ) + self.needs_update = self._any_decor_visible() + + def _add_fixed_geometry(self) -> None: + """Add fixed world geometry to the scene.""" + # Group fixed geoms by (body_id, group_id). + body_group_geoms: dict[tuple[int, int], list[int]] = {} + for i in range(self.mj_model.ngeom): + body_id = self.mj_model.geom_bodyid[i] + if not is_fixed_body(self.mj_model, body_id): + continue + if self.mj_model.geom_type[i] == mjtGeom.mjGEOM_PLANE: + body_name = get_body_name(self.mj_model, body_id) + geom_name = mj_id2name(self.mj_model, mjtObj.mjOBJ_GEOM, i) + self.server.scene.add_grid( + f"/fixed_bodies/{body_name}/{geom_name}", + infinite_grid=True, + fade_distance=50.0, + shadow_opacity=0.2, + plane_opacity=0.4, + position=self.mj_model.geom_pos[i], + wxyz=self.mj_model.geom_quat[i], + ) + continue + # Skip fully transparent geoms. + if self.mj_model.geom_rgba[i, 3] == 0: + continue + group_id = int(self.mj_model.geom_group[i]) + body_group_geoms.setdefault((body_id, group_id), []).append(i) + + for (body_id, group_id), geom_ids in body_group_geoms.items(): + body_name = get_body_name(self.mj_model, body_id) + visible = group_id < 6 and self.geom_groups_visible[group_id] + subgroups = group_geoms_by_visual_compat(self.mj_model, geom_ids) + for sub_idx, sub_geom_ids in enumerate(subgroups): + suffix = f"/sub{sub_idx}" if len(subgroups) > 1 else "" + handle = self.server.scene.add_mesh_trimesh( + f"/fixed_bodies/{body_name}/group{group_id}{suffix}", + merge_geoms(self.mj_model, sub_geom_ids), + cast_shadow=False, + receive_shadow=0.2, + position=self.mj_data.xpos[body_id], + wxyz=self.mj_data.xquat[body_id], + visible=visible, + ) + self._fixed_geom_handles[(body_id, group_id, sub_idx)] = handle + + @staticmethod + def _geom_subgroup_fingerprint( + mj_model: mujoco.MjModel, geom_ids: list[int], is_mocap: bool + ) -> tuple[object, ...]: + """Compute a hashable fingerprint for a set of geoms in one body. + + Bodies whose subgroups share a fingerprint have identical local + geometry and can be rendered with a single batched handle. + """ + parts: list[tuple[object, ...]] = [] + for gid in geom_ids: + parts.append( + ( + int(mj_model.geom_type[gid]), + int(mj_model.geom_dataid[gid]), + int(mj_model.geom_matid[gid]), + tuple(mj_model.geom_size[gid].round(6).tolist()), + tuple(mj_model.geom_rgba[gid].round(4).tolist()), + tuple(mj_model.geom_pos[gid].round(6).tolist()), + tuple(mj_model.geom_quat[gid].round(6).tolist()), + ) + ) + return (is_mocap, tuple(sorted(parts))) + + def _create_mesh_handles_by_group(self) -> None: + """Create mesh handles, deduplicating identical geometries across bodies.""" + # Step 1: Group geoms by (body_id, group_id). + body_group_geoms: dict[tuple[int, int], list[int]] = {} + for i in range(self.mj_model.ngeom): + body_id = self.mj_model.geom_bodyid[i] + if is_fixed_body(self.mj_model, body_id): + continue + if self.mj_model.geom_rgba[i, 3] == 0: + continue + geom_group = self.mj_model.geom_group[i] + body_group_geoms.setdefault((body_id, geom_group), []).append(i) + + # Group bodies sharing identical geometry by fingerprint. + fp_info: dict[tuple[object, ...], tuple[list[int], list[int], bool, int, int]] = {} + for (body_id, group_id), geom_indices in body_group_geoms.items(): + subgroups = group_geoms_by_visual_compat(self.mj_model, geom_indices) + is_mocap = bool(self.mj_model.body_mocapid[body_id] >= 0) + for sub_idx, sub_geom_ids in enumerate(subgroups): + fp = self._geom_subgroup_fingerprint(self.mj_model, sub_geom_ids, is_mocap) + key = (fp, group_id, sub_idx) + if key in fp_info: + fp_info[key][0].append(body_id) + else: + fp_info[key] = ([body_id], sub_geom_ids, is_mocap, group_id, sub_idx) + + # Create one batched handle per unique geometry. + with self.server.atomic(): + for body_ids, geom_ids, is_mocap, group_id, sub_idx in fp_info.values(): + mesh = merge_geoms(self.mj_model, geom_ids) + lod_ratio = 1000.0 / mesh.vertices.shape[0] + + batch_count = len(body_ids) * self.num_envs + body_name = get_body_name(self.mj_model, body_ids[0]) + suffix = f"/sub{sub_idx}" if sub_idx > 0 else "" + visible = group_id < 6 and self.geom_groups_visible[group_id] + + handle = self.server.scene.add_batched_meshes_trimesh( + f"/bodies/{body_name}/group{group_id}{suffix}", + mesh, + batched_wxyzs=np.tile([1.0, 0.0, 0.0, 0.0], (batch_count, 1)), + batched_positions=np.zeros((batch_count, 3)), + lod=((2.0, lod_ratio),) if lod_ratio < 0.5 else "off", + visible=visible, + ) + + body_ids_arr = np.array(body_ids, dtype=np.int32) + mocap_ids: np.ndarray | None = None + if is_mocap: + mocap_ids = np.array( + [self.mj_model.body_mocapid[b] for b in body_ids], dtype=np.int32 + ) + self._mesh_groups.append(_MeshGroup(handle, body_ids_arr, group_id, mocap_ids)) + + def _add_fixed_sites(self) -> None: + """Add fixed site geometry to the scene as static nodes.""" + body_group_sites: dict[tuple[int, int], list[int]] = {} + for site_id in range(self.mj_model.nsite): + body_id = self.mj_model.site_bodyid[site_id] + if not is_fixed_body(self.mj_model, body_id): + continue + group_id = int(self.mj_model.site_group[site_id]) + body_group_sites.setdefault((body_id, group_id), []).append(site_id) + + for (body_id, group_id), site_ids in body_group_sites.items(): + body_name = get_body_name(self.mj_model, body_id) + mesh = merge_sites(self.mj_model, site_ids) + visible = group_id < 6 and self.site_groups_visible[group_id] + handle = self.server.scene.add_mesh_trimesh( + f"/fixed_bodies/{body_name}/sites_group{group_id}", + mesh, + cast_shadow=False, + receive_shadow=0.2, + position=self.mj_model.body(body_id).pos, + wxyz=self.mj_model.body(body_id).quat, + visible=visible, + ) + self._fixed_site_handles[(body_id, group_id)] = handle + + def _create_site_handles_by_group(self) -> None: + """Create site handles for each site group.""" + body_group_sites: dict[tuple[int, int], list[int]] = {} + for site_id in range(self.mj_model.nsite): + body_id = self.mj_model.site_bodyid[site_id] + if is_fixed_body(self.mj_model, body_id): + continue + group_id = int(self.mj_model.site_group[site_id]) + body_group_sites.setdefault((body_id, group_id), []).append(site_id) + + with self.server.atomic(): + for (body_id, group_id), site_ids in body_group_sites.items(): + body_name = get_body_name(self.mj_model, body_id) + mesh = merge_sites(self.mj_model, site_ids) + visible = group_id < 6 and self.site_groups_visible[group_id] + handle = self.server.scene.add_batched_meshes_trimesh( + f"/bodies/{body_name}/sites_group{group_id}", + mesh, + batched_wxyzs=np.array([1.0, 0.0, 0.0, 0.0])[None].repeat( + self.num_envs, axis=0 + ), + batched_positions=np.array([0.0, 0.0, 0.0])[None].repeat( + self.num_envs, axis=0 + ), + lod="off", + visible=visible, + ) + self.site_handles_by_group[(body_id, group_id)] = handle + + def _compute_hull_body_meshes(self) -> None: + """Precompute one merged convex hull mesh per body that has mesh geoms.""" + body_geoms: dict[int, list[int]] = {} + for geom_id in range(self.mj_model.ngeom): + if int(self.mj_model.geom_type[geom_id]) != int(mjtGeom.mjGEOM_MESH): + continue + if int(self.mj_model.geom_dataid[geom_id]) < 0: + continue + body_id = int(self.mj_model.geom_bodyid[geom_id]) + body_geoms.setdefault(body_id, []).append(geom_id) + + self._hull_mesh_bodies = set(body_geoms.keys()) + + for body_id, geom_ids in body_geoms.items(): + hull_mesh = merge_geoms_hull(self.mj_model, geom_ids) + if hull_mesh is None: + continue + self._hull_body_meshes[body_id] = ( + hull_mesh.vertices.astype(np.float32), + hull_mesh.faces.astype(np.int32), + ) + + def _build_hull_handles(self) -> None: + """Build fixed and dynamic handles for precomputed body hulls.""" + color = np.array(self._hull_color, dtype=np.uint8) + opacity = np.float32(self._hull_opacity) + fixed_opacities = None if opacity >= 1.0 else np.array([opacity], dtype=np.float32) + dynamic_opacities = ( + None if opacity >= 1.0 else np.full(self.num_envs, opacity, dtype=np.float32) + ) + + for body_id, (vertices, faces) in self._hull_body_meshes.items(): + if is_fixed_body(self.mj_model, body_id): + body = self.mj_model.body(body_id) + handle = self.server.scene.add_batched_meshes_simple( + f"/fixed_bodies/hull/{body_id}", + vertices, + faces, + batched_wxyzs=np.array([[1.0, 0.0, 0.0, 0.0]], dtype=np.float32), + batched_positions=np.zeros((1, 3), dtype=np.float32), + batched_colors=color[None], + batched_opacities=fixed_opacities, + position=body.pos, + wxyz=body.quat, + visible=self._show_convex_hull, + cast_shadow=False, + receive_shadow=False, + lod="off", + ) + self._hull_fixed_handles[body_id] = handle + continue + + handle = self.server.scene.add_batched_meshes_simple( + f"/hull/{body_id}", + vertices, + faces, + batched_wxyzs=np.tile([1.0, 0.0, 0.0, 0.0], (self.num_envs, 1)).astype( + np.float32 + ), + batched_positions=np.zeros((self.num_envs, 3), dtype=np.float32), + batched_colors=np.tile(color, (self.num_envs, 1)), + batched_opacities=dynamic_opacities, + visible=self._show_convex_hull, + cast_shadow=False, + receive_shadow=False, + lod="off", + ) + self._hull_dynamic_handles.append((handle, body_id)) + + def _clear_hull_handles(self) -> None: + """Remove convex hull handles and clear their caches.""" + for handle in self._hull_fixed_handles.values(): + handle.remove() + self._hull_fixed_handles.clear() + + for handle, _ in self._hull_dynamic_handles: + handle.remove() + self._hull_dynamic_handles.clear() + + def _clear_decor_handles(self) -> None: + """Remove decor handles and clear their cache.""" + for handle in self._decor_handles.values(): + handle.remove() + self._decor_handles.clear() + + def _hide_all_decor(self) -> None: + """Hide all decor handles without removing them.""" + for handle in self._decor_handles.values(): + handle.visible = False + + def _update_decor_from_mjvscene( + self, mj_data: mujoco.MjData, scene_offset: np.ndarray + ) -> None: + """Update overlay visualization using mjvScene. + + Calls ``mjv_updateScene`` to generate decorative geoms (contacts, + tendons, frames, inertia) and renders them as batched viser meshes. + """ + mujoco.mjv_updateScene( + self.mj_model, + mj_data, + self._mjv_option, + None, + self._mjv_camera, + int(mujoco.mjtCatBit.mjCAT_ALL), + self._mjv_scene, + ) + + # Group geoms by (type, is_tendon). Tendons are keyed separately so + # connector-style capsules can be rendered with cylinders instead. + geoms_by_key: dict[tuple[int, bool], list[int]] = defaultdict(list) + for i in range(self._mjv_scene.ngeom): + g = self._mjv_scene.geoms[i] + is_tendon = int(g.objtype) == _OBJ_TENDON + if int(g.category) == _CAT_DECOR or is_tendon: + geoms_by_key[(int(g.type), is_tendon)].append(i) + + active_keys: set[tuple[int, bool]] = set() + + # Collect arrow heads across all arrow types. + all_head_positions: list[np.ndarray] = [] + all_head_orientations: list[np.ndarray] = [] + all_head_scales: list[np.ndarray] = [] + all_head_colors: list[np.ndarray] = [] + all_head_opacities: list[float] = [] + + def _update_simple_handle( + key: tuple[int, bool], + path: str, + mesh_type: int, + positions: np.ndarray, + orientations: np.ndarray, + scales: np.ndarray, + colors: np.ndarray, + opacities: np.ndarray, + ) -> None: + active_keys.add(key) + batched_opacities = None if np.all(opacities == 1.0) else opacities + handle = self._decor_handles.get(key) + if handle is not None: + handle.batched_positions = positions + handle.batched_wxyzs = orientations + handle.batched_scales = scales + handle.batched_colors = colors + handle.batched_opacities = batched_opacities + handle.visible = True + return + + unit = _get_unit_mesh(mesh_type) + handle = self.server.scene.add_batched_meshes_simple( + path, + unit.vertices, + unit.faces, + batched_wxyzs=orientations, + batched_positions=positions, + batched_scales=scales, + batched_colors=colors, + batched_opacities=batched_opacities, + lod="off", + cast_shadow=False, + receive_shadow=False, + ) + self._decor_handles[key] = handle + + for (geom_type, is_tendon), indices in geoms_by_key.items(): + n = len(indices) + active_keys.add((geom_type, is_tendon)) + + positions = np.empty((n, 3), dtype=np.float32) + orientations = np.empty((n, 4), dtype=np.float32) + scales = np.empty((n, 3), dtype=np.float32) + colors = np.empty((n, 3), dtype=np.uint8) + opacities = np.empty(n, dtype=np.float32) + + for j, gi in enumerate(indices): + g = self._mjv_scene.geoms[gi] + pos = np.array(g.pos) + scene_offset + mat = np.array(g.mat).reshape(3, 3) + quat = vtf.SO3.from_matrix(mat).wxyz + size = np.array(g.size) + rgba = np.array(g.rgba) + + # MuJoCo ignores user alpha for joint geoms; override it. + if int(g.objtype) == _OBJ_JOINT: + rgba[3] = self.mj_model.vis.rgba.joint[3] + + positions[j] = pos + orientations[j] = quat + colors[j] = (np.clip(rgba[:3], 0, 1) * 255).astype(np.uint8) + opacities[j] = float(rgba[3]) + + # Map mjvGeom size to unit-mesh scale. + if geom_type in (_CYLINDER, _CAPSULE): + height = max(size[2] * 2, size[0]) + scales[j] = [size[0], size[0], height] + elif geom_type in _ARROWS: + # size = [shaft_radius, head_radius, total_length] + # 80% shaft, 20% head (matches mjlab convention). + total_len = size[2] + shaft_len = total_len * 0.8 + head_len = total_len * 0.2 + w = size[0] + scales[j] = [w, w, shaft_len] + # Head: cone at the tip of the shaft. + tip_offset = mat[:, 2] * shaft_len + all_head_positions.append(pos + tip_offset.astype(np.float32)) + all_head_orientations.append(quat) + all_head_scales.append(np.array([w, w, head_len], dtype=np.float32)) + all_head_colors.append(colors[j].copy()) + all_head_opacities.append(opacities[j]) + else: + scales[j] = size + + mesh_type = _CYLINDER if is_tendon or geom_type == _CAPSULE else geom_type + key = (geom_type, is_tendon) + _update_simple_handle( + key, + f"/decor/{geom_type}_{is_tendon}", + mesh_type, + positions, + orientations, + scales, + colors, + opacities, + ) + + # Create arrow heads as a single combined handle. + if all_head_positions: + _update_simple_handle( + (_ARROW_HEAD, False), + "/decor/arrow_heads", + _ARROW_HEAD, + np.array(all_head_positions), + np.array(all_head_orientations), + np.array(all_head_scales), + np.array(all_head_colors), + np.array(all_head_opacities, dtype=np.float32), + ) + + # Hide handles for types not present this frame. + for key, handle in self._decor_handles.items(): + if key not in active_keys: + handle.visible = False diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/viewer.py b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..63345997d1566f3a83070c62f3949104b82d0af9 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/mjviser/viewer.py @@ -0,0 +1,526 @@ +"""Active MuJoCo viewer with realtime pacing and playback controls.""" + +from __future__ import annotations + +import signal +import time +from collections.abc import Callable +from threading import Lock + +import mujoco +import numpy as np +import viser + +from .scene import ViserMujocoScene + +_SPEEDS = [1 / 8, 1 / 4, 1 / 2, 1.0, 2.0, 4.0, 8.0] +_FRAME_TIME = 1.0 / 60.0 # 60 Hz render target. + + +def _format_speed(multiplier: float) -> str: + if multiplier == 1.0: + return "1x" + inv = 1.0 / multiplier + inv_rounded = round(inv) + if abs(inv - inv_rounded) < 1e-9 and inv_rounded > 0: + return f"1/{inv_rounded}x" + return f"{multiplier:.3g}x" + + +class Viewer: + """Active viewer that steps a MuJoCo simulation with realtime pacing. + + Handles the simulation loop, timing, pause/resume, speed controls, + and scene rendering. + + For full control over the loop, use ``ViserMujocoScene`` directly + and call ``update_from_mjdata`` or ``update_from_arrays`` yourself. + """ + + def __init__( + self, + model: mujoco.MjModel, + data: mujoco.MjData, + step_fn: Callable[[mujoco.MjModel, mujoco.MjData], None] | None = None, + render_fn: Callable[[ViserMujocoScene], None] | None = None, + reset_fn: Callable[[mujoco.MjModel, mujoco.MjData], None] | None = None, + num_envs: int = 1, + server: viser.ViserServer | None = None, + ) -> None: + """Create an active viewer. + + Args: + model: MuJoCo model. + data: MuJoCo data (used for keyframes, timestep, and as the + default render/reset source when callbacks are None). + step_fn: Called each simulation step. Signature is + ``step_fn(model, data)``. Defaults to ``mujoco.mj_step``. + render_fn: Called each render frame to push state to the scene. + Signature is ``render_fn(scene)``. Defaults to + ``scene.update_from_mjdata(data)``. Override this for + multi-environment or custom rendering. + reset_fn: Called on reset. Signature is + ``reset_fn(model, data)``. Defaults to + ``mj_resetData + mj_forward``. Override this to reset + custom simulation state (e.g. warp data). + num_envs: Number of parallel environments (passed to + ``ViserMujocoScene``). + server: Optional viser server. If None, one is created. + """ + self.model = model + self.data = data + self._step_fn = step_fn or mujoco.mj_step + self._render_fn = render_fn + self._reset_fn = reset_fn + self._server = server or viser.ViserServer() + self.scene = ViserMujocoScene(self._server, model, num_envs=num_envs) + self._lock = Lock() + self.scene.set_refresh_handler(self._refresh_scene_from_gui) + + # Speed. + self._speed_idx = _SPEEDS.index(1.0) + self._joint_sliders: list = [] # [(slider, qpos_adr), ...] + self._actuator_sliders: list = [] # [(slider, act_id), ...] + + # State. + self._paused = False + self._dirty = True + self._step_count = 0 + + # Timing. + self._budget = 0.0 + self._last_tick = 0.0 + self._was_capped = False + + # Render timer. + self._time_until_next_render = 0.0 + + # Windowed stats, updated every 0.5s. + self._stats_steps = 0 + self._stats_frames = 0 + self._stats_last_time = 0.0 + self._fps = 0.0 + self._sps = 0.0 + + @property + def speed(self) -> float: + return _SPEEDS[self._speed_idx] + + @property + def actual_realtime(self) -> float: + return self._sps * self.model.opt.timestep + + def _render(self) -> None: + """Push current state to the scene.""" + if self._render_fn is not None: + self._render_fn(self.scene) + else: + self.scene.update_from_mjdata(self.data) + + def _refresh_scene_from_gui(self) -> None: + """Refresh cached visualization state under the simulation lock.""" + with self._lock: + self._render() + + def _set_joint_qpos(self, qpos_adr: int, value: float) -> None: + """Set one scalar joint position and refresh the scene immediately.""" + with self._lock: + self.data.qpos[qpos_adr] = value + mujoco.mj_forward(self.model, self.data) + self._render() + + def _sync_sliders(self) -> None: + """Update joint and actuator slider values from current data.""" + for slider, qpos_adr in self._joint_sliders: + val = float(np.clip(self.data.qpos[qpos_adr], slider.min, slider.max)) + slider.value = round(val, 3) + for slider, act_id in self._actuator_sliders: + val = float(np.clip(self.data.ctrl[act_id], slider.min, slider.max)) + slider.value = round(val, 3) + + def _reset(self) -> None: + """Reset the simulation.""" + if self._reset_fn is not None: + self._reset_fn(self.model, self.data) + else: + mujoco.mj_resetData(self.model, self.data) + mujoco.mj_forward(self.model, self.data) + + def run(self) -> None: + """Run the viewer loop until Ctrl+C.""" + self._setup_gui() + + prev_handler = signal.getsignal(signal.SIGINT) + interrupted = False + + def _on_sigint(signum, frame): + nonlocal interrupted + interrupted = True + signal.signal(signal.SIGINT, signal.SIG_DFL) + + signal.signal(signal.SIGINT, _on_sigint) + + if self._render_fn is None: + mujoco.mj_forward(self.model, self.data) + self._render() + + now = time.perf_counter() + self._last_tick = now + self._stats_last_time = now + try: + while not interrupted: + self._tick() + time.sleep(0.001) + finally: + self._server.stop() + signal.signal(signal.SIGINT, prev_handler) + + def _tick(self) -> None: + now = time.perf_counter() + dt = now - self._last_tick + self._last_tick = now + + if not self._paused: + with self._lock: + if self._step_physics(dt): + self._dirty = True + + # Render at fixed frame rate, but only when state changed. + self._time_until_next_render -= dt + if self._time_until_next_render > 0: + return + + self._time_until_next_render += _FRAME_TIME + if self._time_until_next_render < -_FRAME_TIME: + self._time_until_next_render = 0.0 + + if self._dirty or self.scene.needs_update: + self._dirty = False + self._render() + self._stats_frames += 1 + self._update_stats() + + def _step_physics(self, dt: float) -> bool: + """Run physics steps for this frame's sim-time budget. + + Returns True if at least one step was taken. + """ + step_dt = self.model.opt.timestep + self._budget += dt * self.speed + self._was_capped = False + + if self._budget < step_dt: + return False + + deadline = time.perf_counter() + _FRAME_TIME + hit_deadline = False + while self._budget >= step_dt: + self._step_fn(self.model, self.data) + self._budget -= step_dt + self._step_count += 1 + self._stats_steps += 1 + if time.perf_counter() > deadline: + hit_deadline = True + break + + if hit_deadline: + self._was_capped = self._budget >= step_dt + self._budget = min(self._budget, step_dt) + return True + + def _update_stats(self) -> None: + if self._paused: + return + now = time.perf_counter() + dt = now - self._stats_last_time + if dt >= 0.5: + self._fps = self._stats_frames / dt + self._sps = self._stats_steps / dt + self._stats_frames = 0 + self._stats_steps = 0 + self._stats_last_time = now + self._update_status_display() + + def _update_status_display(self) -> None: + actual_rt = self.actual_realtime + rt_display = f"{actual_rt:.2f}x" if actual_rt > 0 else "\u2014" + capped = ' [CAPPED]' if self._was_capped else "" + self._status_html.content = f""" +
+ Status: + {"Paused" if self._paused else "Running"}{capped}
+ Steps: {self._step_count}
+ Speed: {_format_speed(self.speed)}
+ Target RT: {self.speed:.2f}x
+ Actual RT: + {rt_display} ({self._fps:.0f} FPS) +
+ """ + + def _setup_gui(self) -> None: + tabs = self._server.gui.add_tab_group() + + with tabs.add_tab("Controls", icon=viser.Icon.SETTINGS): + self._status_html = self._server.gui.add_html("") + + pause_btn = self._server.gui.add_button( + "Pause" if not self._paused else "Play", + icon=(viser.Icon.PLAYER_PAUSE if not self._paused else viser.Icon.PLAYER_PLAY), + ) + + @pause_btn.on_click + def _(_) -> None: + self._paused = not self._paused + if not self._paused: + self._budget = 0.0 + self._last_tick = time.perf_counter() + pause_btn.label = "Pause" if not self._paused else "Play" + pause_btn.icon = ( + viser.Icon.PLAYER_PAUSE if not self._paused else viser.Icon.PLAYER_PLAY + ) + for sl, _ in self._joint_sliders: + sl.disabled = not self._paused + self._update_status_display() + + step_btn = self._server.gui.add_button("Step", icon=viser.Icon.PLAYER_TRACK_NEXT) + + @step_btn.on_click + def _(_) -> None: + if self._paused: + with self._lock: + self._step_fn(self.model, self.data) + self._step_count += 1 + self._render() + self._update_status_display() + + reset_btn = self._server.gui.add_button("Reset") + + @reset_btn.on_click + def _(_) -> None: + with self._lock: + self._reset() + self._step_count = 0 + self._budget = 0.0 + self._render() + self._update_status_display() + self._sync_sliders() + + speed_btns = self._server.gui.add_button_group( + "Speed", options=["Slower", "1x", "Faster"] + ) + + @speed_btns.on_click + def _(event) -> None: + if event.target.value == "Slower": + self._speed_idx = max(0, self._speed_idx - 1) + elif event.target.value == "Faster": + self._speed_idx = min(len(_SPEEDS) - 1, self._speed_idx + 1) + else: + self._speed_idx = _SPEEDS.index(1.0) + self._update_status_display() + + # Keyframe selector (only if model has keyframes). + if self.model.nkey > 0: + key_names = [] + for i in range(self.model.nkey): + name = mujoco.mj_id2name(self.model, mujoco.mjtObj.mjOBJ_KEY, i) + key_names.append(name if name else f"key_{i}") + + with self._server.gui.add_folder("Keyframes"): + key_dropdown = self._server.gui.add_dropdown( + "Key", options=key_names, initial_value=key_names[0] + ) + load_btn = self._server.gui.add_button( + "Load", icon=viser.Icon.PLAYER_TRACK_NEXT + ) + + def _load_keyframe() -> None: + idx = key_names.index(key_dropdown.value) + with self._lock: + mujoco.mj_resetDataKeyframe(self.model, self.data, idx) + mujoco.mj_forward(self.model, self.data) + if self._reset_fn is not None: + self._reset_fn(self.model, self.data) + self._step_count = 0 + self._budget = 0.0 + self._render() + self._update_status_display() + self._sync_sliders() + + @load_btn.on_click + def _(_) -> None: + _load_keyframe() + + @key_dropdown.on_update + def _(_) -> None: + _load_keyframe() + + # Scene controls (camera, environment). + with self._server.gui.add_folder("Scene"): + self.scene.create_scene_gui() + + # Visualization tab (overlays, colors, scale). + with tabs.add_tab("Visualization", icon=viser.Icon.EYE): + self.scene.create_overlay_gui() + + # Groups tab (geom/site/joint/tendon/actuator visibility). + with tabs.add_tab("Groups", icon=viser.Icon.LAYERS_INTERSECT): + self.scene.create_groups_gui() + + # Actuation tab (joint/actuator sliders). + with tabs.add_tab("Actuation", icon=viser.Icon.ADJUSTMENTS): + self._setup_joint_sliders() + self._setup_actuator_sliders() + + # Physics tab (disable/enable flags). + with tabs.add_tab("Physics", icon=viser.Icon.ATOM): + self._setup_physics_flags() + + _MAX_SLIDERS: int = 200 + + def _setup_joint_sliders(self) -> None: + """Add per-joint sliders for hinge and slide joints.""" + # Only hinge (3) and slide (2) joints get sliders. + joints = [] + for i in range(self.model.njnt): + jtype = int(self.model.jnt_type[i]) + if jtype not in (2, 3): # slide, hinge + continue + name = mujoco.mj_id2name(self.model, mujoco.mjtObj.mjOBJ_JOINT, i) + if not name: + name = f"joint_{i}" + limited = bool(self.model.jnt_limited[i]) + if limited: + lo, hi = self.model.jnt_range[i] + else: + lo, hi = (-np.pi, np.pi) if jtype == 3 else (-1.0, 1.0) + joints.append((i, name, round(float(lo), 3), round(float(hi), 3))) + + if not joints: + return + + if len(joints) > self._MAX_SLIDERS: + self._server.gui.add_markdown( + f"*Joint sliders disabled ({len(joints)} joints exceed limit of" + f" {self._MAX_SLIDERS}).*" + ) + return + + with self._server.gui.add_folder("Joints", expand_by_default=False): + for jnt_id, name, lo, hi in joints: + qpos_adr = int(self.model.jnt_qposadr[jnt_id]) + val = float(np.clip(self.data.qpos[qpos_adr], lo, hi)) + slider = self._server.gui.add_slider( + name, + min=lo, + max=hi, + step=round((hi - lo) / 200, 4), + initial_value=round(val, 3), + disabled=not self._paused, + ) + self._joint_sliders.append((slider, qpos_adr)) + + def _on_update(_, _adr=qpos_adr, _sl=slider) -> None: + self._set_joint_qpos(_adr, _sl.value) + + slider.on_update(_on_update) + + def _setup_actuator_sliders(self) -> None: + """Add per-actuator control sliders.""" + if self.model.nu == 0: + return + + actuators = [] + for i in range(self.model.nu): + name = mujoco.mj_id2name(self.model, mujoco.mjtObj.mjOBJ_ACTUATOR, i) + if not name: + name = f"actuator_{i}" + limited = bool(self.model.actuator_ctrllimited[i]) + if limited: + lo, hi = self.model.actuator_ctrlrange[i] + else: + lo, hi = -1.0, 1.0 + actuators.append((i, name, round(float(lo), 3), round(float(hi), 3))) + + if len(actuators) > self._MAX_SLIDERS: + self._server.gui.add_markdown( + f"*Actuator sliders disabled ({len(actuators)} actuators exceed" + f" limit of {self._MAX_SLIDERS}).*" + ) + return + + with self._server.gui.add_folder("Actuators"): + for act_id, name, lo, hi in actuators: + val = float(np.clip(self.data.ctrl[act_id], lo, hi)) + slider = self._server.gui.add_slider( + name, + min=lo, + max=hi, + step=round((hi - lo) / 200, 4), + initial_value=round(val, 3), + disabled=False, + ) + + self._actuator_sliders.append((slider, act_id)) + + def _on_update(_, _id=act_id, _sl=slider) -> None: + with self._lock: + self.data.ctrl[_id] = _sl.value + + slider.on_update(_on_update) + + def _setup_physics_flags(self) -> None: + """Add checkboxes for MuJoCo disable and enable flags.""" + disable_flags = [ + ("Gravity", mujoco.mjtDisableBit.mjDSBL_GRAVITY), + ("Contact", mujoco.mjtDisableBit.mjDSBL_CONTACT), + ("Constraint", mujoco.mjtDisableBit.mjDSBL_CONSTRAINT), + ("Equality", mujoco.mjtDisableBit.mjDSBL_EQUALITY), + ("Limit", mujoco.mjtDisableBit.mjDSBL_LIMIT), + ("Spring", mujoco.mjtDisableBit.mjDSBL_SPRING), + ("Damper", mujoco.mjtDisableBit.mjDSBL_DAMPER), + ("Friction Loss", mujoco.mjtDisableBit.mjDSBL_FRICTIONLOSS), + ("Actuation", mujoco.mjtDisableBit.mjDSBL_ACTUATION), + ("Sensor", mujoco.mjtDisableBit.mjDSBL_SENSOR), + ("Warmstart", mujoco.mjtDisableBit.mjDSBL_WARMSTART), + ("Filter Parent", mujoco.mjtDisableBit.mjDSBL_FILTERPARENT), + ("Clamp Ctrl", mujoco.mjtDisableBit.mjDSBL_CLAMPCTRL), + ("Euler Damp", mujoco.mjtDisableBit.mjDSBL_EULERDAMP), + ("Refsafe", mujoco.mjtDisableBit.mjDSBL_REFSAFE), + ] + + enable_flags = [ + ("Energy", mujoco.mjtEnableBit.mjENBL_ENERGY), + ("Override", mujoco.mjtEnableBit.mjENBL_OVERRIDE), + ("Fwd Inverse", mujoco.mjtEnableBit.mjENBL_FWDINV), + ("Multi CCD", mujoco.mjtEnableBit.mjENBL_MULTICCD), + ] + + with self._server.gui.add_folder("Disable Flags"): + for label, flag in disable_flags: + bit = int(flag) + active = bool(self.model.opt.disableflags & bit) + cb = self._server.gui.add_checkbox(label, initial_value=active) + + def _on_toggle(_, _bit=bit, _cb=cb) -> None: + if _cb.value: + self.model.opt.disableflags |= _bit + else: + self.model.opt.disableflags &= ~_bit + + cb.on_update(_on_toggle) + + with self._server.gui.add_folder("Enable Flags"): + for label, flag in enable_flags: + bit = int(flag) + active = bool(self.model.opt.enableflags & bit) + cb = self._server.gui.add_checkbox(label, initial_value=active) + + def _on_toggle(_, _bit=bit, _cb=cb) -> None: + if _cb.value: + self.model.opt.enableflags |= _bit + else: + self.model.opt.enableflags &= ~_bit + + cb.on_update(_on_toggle) diff --git a/third-party/do-as-i-do/deployment/mujoco_replay/replay_retarget.py b/third-party/do-as-i-do/deployment/mujoco_replay/replay_retarget.py new file mode 100644 index 0000000000000000000000000000000000000000..ece2a52b8ae20d882990f2a442d067c705dc3e39 --- /dev/null +++ b/third-party/do-as-i-do/deployment/mujoco_replay/replay_retarget.py @@ -0,0 +1,1354 @@ +"""Replay a spider mjwp retarget trajectory on the dual_ur3e scene (mink IK). + +Drives one arm + its Sharpa hand (--side right [default] or left). The +retargeted Sharpa wrist pose lives in spider's world frame; per frame we + + 1. decode the desired Sharpa-root world pose from qpos[0:6] + (3 slide joints + 3 hinge joints = xyz + intrinsic XYZ-Euler), + 2. apply a configurable workspace transform (translate + yaw/pitch/roll + around the start-frame anchor) to land it in the dual_ur3e world, + 3. invert the flange→sharparoot mount used in build_scene.py to get + the target pose for the UR3e attachment_site, + 4. solve IK on the chosen UR3e (6 DOF): a mink QP drives a FrameTask on the + attachment_site while a CollisionAvoidanceLimit keeps the arm from + intersecting itself, the table/breadboard/blocks and (optionally) the + other arm; a DofFreezingTask pins every non-arm dof so only the 6 arm + joints move. + 5. copy the 22 finger joints straight through. + +The other arm and hand stay at the home keyframe. + +Usage: + +python dual_ur3e/replay_retarget.py --side left --traj .../trajectory_mjwp.npz + +# headless: solve + print residuals/collision stats, no viser GUI +python dual_ur3e/replay_retarget.py --side left --traj .../trajectory_mjwp.npz --solve-only +""" + +from __future__ import annotations + +import argparse +import time +from pathlib import Path + +import mink +import mujoco +import numpy as np +import viser + +from build_scene import build + +# Mirrors the HAND_OFFSET constant inside build_scene.build(): +# coupler_black_height (0.01325) + coupler_silver_height (0.0175) m +# along the attachment_site +Z axis. +HAND_OFFSET = 0.03075 +from mjviser import ViserMujocoScene + +# Placeholder default — pass --traj explicitly to point at a spider +# trajectory_mjwp.npz produced by the retargeting stage. +DEFAULT_TRAJ = Path("trajectory_mjwp.npz") + +# Sharpa-root yaw in the flange frame, matching build_scene.z_quat(...) for +# each hand: right_hand_C_MC = z_quat(135), left_hand_C_MC = z_quat(45). +HAND_MOUNT_YAW_DEG = {"right": 135.0, "left": 45.0} + +# Saved preset: world position where the wrist (sharpa root) sits at the +# start_frame. In dual_ur3e world coords: +x toward far wall, +y toward +# the left arm, +z up. Each side's default lands the wrist in front of that +# arm at a comfortable working height. Pass via --workspace-x/-y/-z to +# override. The left preset mirrors the right across the y=center plane +# (right arm sits at -y, left arm at +y) — it's only a starting guess; tune +# yaw/pitch/roll in the GUI. +PRESET_FRONT_OF_ARM = { + "right": { + "x": -0.025, "y": -0.16, "z": 0.875, "yaw": 90.0, "pitch": 0.0, "roll": 0.0, + }, + "left": { + "x": -0.025, "y": 0.16, "z": 0.875, "yaw": -90.0, "pitch": 0.0, "roll": 0.0, + }, +} +DEFAULT_START_FRAME = 600 + +# Filename written by the GUI "Save retarget" button — also the name we +# look for when auto-detecting a reference file next to the input traj. +RETARGET_FILENAME = "trajectory_dual_ur3e.npz" + + +def _load_reference_defaults(path: Path) -> dict | None: + """Read workspace_xyz / workspace_yaw_deg / start_frame from a saved + retarget npz. Returns a dict with keys x, y, z, yaw, pitch, roll, + start_frame, or None if the file can't be parsed. + """ + try: + with np.load(path) as npz: + xyz = np.asarray(npz["workspace_xyz"], dtype=np.float64) + yaw = float(np.asarray(npz["workspace_yaw_deg"])) + start_frame = int(np.asarray(npz["start_frame"])) + # pitch/roll were added after yaw; older retargets default to 0. + pitch = ( + float(np.asarray(npz["workspace_pitch_deg"])) + if "workspace_pitch_deg" in npz.files else 0.0 + ) + roll = ( + float(np.asarray(npz["workspace_roll_deg"])) + if "workspace_roll_deg" in npz.files else 0.0 + ) + except (OSError, KeyError, ValueError) as e: + print(f" warning: could not read reference {path}: {e}") + return None + if xyz.shape != (3,): + print(f" warning: reference {path} has bad workspace_xyz shape {xyz.shape}") + return None + return { + "x": float(xyz[0]), "y": float(xyz[1]), "z": float(xyz[2]), + "yaw": yaw, "pitch": pitch, "roll": roll, "start_frame": start_frame, + } + + +# Spider hand qpos layout (per frame, total 35): +# [0:3] wrist xyz (slide joints) +# [3:6] wrist rotation (hinges Rx, Ry, Rz applied as nested bodies) +# [6:28] 22 finger joints +# [28:35] object free joint (ignored here) +SPIDER_FINGER_SLICE = slice(6, 28) + + +# --------------------------------------------------------------------------- +# Pose helpers +# --------------------------------------------------------------------------- + + +def _quat_mul(a: np.ndarray, b: np.ndarray) -> np.ndarray: + """Hamilton product of two wxyz quaternions.""" + out = np.zeros(4) + mujoco.mju_mulQuat(out, a, b) + return out + + +def _axis_angle_quat(axis: np.ndarray, angle: float) -> np.ndarray: + """Build a wxyz quaternion from axis-angle.""" + out = np.zeros(4) + mujoco.mju_axisAngle2Quat(out, axis, angle) + return out + + +_X_AXIS = np.array([1.0, 0.0, 0.0]) +_Y_AXIS = np.array([0.0, 1.0, 0.0]) +_Z_AXIS = np.array([0.0, 0.0, 1.0]) + + +def _spider_wrist_quat(rx: float, ry: float, rz: float) -> np.ndarray: + """Compose the spider wrist hinge chain into a single wxyz quat. + + Bodies are nested base_roll(Rx) → base_pitch(Ry) → base_yaw(Rz) → + _hand_C_MC, so the root's rotation in world is Rx · Ry · Rz. + """ + qx = _axis_angle_quat(_X_AXIS, rx) + qy = _axis_angle_quat(_Y_AXIS, ry) + qz = _axis_angle_quat(_Z_AXIS, rz) + return _quat_mul(qx, _quat_mul(qy, qz)) + + +def _spider_root_pose(qpos_frame: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + pos = qpos_frame[0:3].copy() + quat = _spider_wrist_quat( + float(qpos_frame[3]), float(qpos_frame[4]), float(qpos_frame[5]) + ) + return pos, quat + + +def _flange_offset_quat(mount_yaw_deg: float) -> np.ndarray: + """Quaternion (wxyz) of the Sharpa root in the flange frame. + + build_scene mounts _hand_C_MC at z_quat(mount_yaw_deg) relative to + the attachment_site (135° right, 45° left). + """ + return _axis_angle_quat(_Z_AXIS, np.deg2rad(mount_yaw_deg)) + + +def _quat_inv(q: np.ndarray) -> np.ndarray: + out = np.zeros(4) + mujoco.mju_negQuat(out, q) + return out + + +def _quat_rotate(q: np.ndarray, v: np.ndarray) -> np.ndarray: + out = np.zeros(3) + mujoco.mju_rotVecQuat(out, v, q) + return out + + +def _flange_target_from_sharpa_root( + pos_root_world: np.ndarray, quat_root_world: np.ndarray, + mount_yaw_deg: float, +) -> tuple[np.ndarray, np.ndarray]: + """Given the desired Sharpa root pose in the dual_ur3e world frame, + compute the corresponding attachment_site (flange) target pose. + + flange = root · inv(flange_to_root_offset) + offset is Translate(0,0,HAND_OFFSET) then RotZ(mount_yaw_deg) in + the flange frame (135° right, 45° left). + """ + q_off_inv = _quat_inv(_flange_offset_quat(mount_yaw_deg)) + quat_flange = _quat_mul(quat_root_world, q_off_inv) + # offset_pos_in_flange = (0, 0, HAND_OFFSET); world offset = R_flange · that + offset_world = _quat_rotate(quat_flange, np.array([0.0, 0.0, HAND_OFFSET])) + pos_flange = pos_root_world - offset_world + return pos_flange, quat_flange + + +# --------------------------------------------------------------------------- +# Collision-aware IK (mink) +# --------------------------------------------------------------------------- + +MINK_SOLVER = "daqp" # the only qpsolvers backend installed in the mujoco env + + +def _collision_geom_ids( + model: mujoco.MjModel, include_prefixes, exclude_prefixes=(), +) -> list[int]: + """Collision-geom ids whose owning body name starts with any of + ``include_prefixes`` and none of ``exclude_prefixes``. + + A geom counts as a collision geom iff (contype | conaffinity) != 0 — this + catches both the UR3e arm capsules (group 3) and the static environment + boxes (group 0, contype=conaffinity=1) while skipping the visual-only + meshes (contype=conaffinity=0, groups 1/2). Geoms are returned by integer + id because the UR3e collision geoms are unnamed. + """ + ids = [] + for g in range(model.ngeom): + if (int(model.geom_contype[g]) | int(model.geom_conaffinity[g])) == 0: + continue + bname = model.body(model.geom_bodyid[g]).name + if not any(bname.startswith(p) for p in include_prefixes): + continue + if any(bname.startswith(p) for p in exclude_prefixes): + continue + ids.append(g) + return ids + + +def _collision_groups(model: mujoco.MjModel, side: str) -> dict: + """Group collision-geom ids for the active ``side`` into + active_arm / active_hand / other_arm / other_hand / env. + + The arm group is the "_..." bodies minus the "_hand_..." + subtree, so the two wrist couplers (which build_scene mounts on + _wrist_3_link) fall into the arm group. ``env`` is every collision + geom owned by the world body (floor, table, legs, walls, foam, + breadboard, supports, both mounting blocks). + """ + other = "right" if side == "left" else "left" + return { + "active_arm": _collision_geom_ids(model, (f"{side}_",), (f"{side}_hand_",)), + "active_hand": _collision_geom_ids(model, (f"{side}_hand_",)), + "other_arm": _collision_geom_ids(model, (f"{other}_",), (f"{other}_hand_",)), + "other_hand": _collision_geom_ids(model, (f"{other}_hand_",)), + "env": [ + g for g in range(model.ngeom) + if model.body(model.geom_bodyid[g]).name == "world" + and (int(model.geom_contype[g]) | int(model.geom_conaffinity[g])) != 0 + ], + } + + +class MinkArmIK: + """mink differential-IK for one UR3e arm (6 DOF) with self/environment + collision avoidance. + + The full dual-arm model is wrapped in a single ``mink.Configuration``. A + ``DofFreezingTask`` (enforced as a hard equality constraint) pins every dof + except the active arm's 6 joints, so the QP only ever moves that arm; the + finger angles and the idle arm are written straight into the configuration + each frame and held there. A ``FrameTask`` drives the + ``_attachment_site`` to the requested world pose, a low-cost + ``PostureTask`` regularises the redundant nullspace, and a (rebuildable) + ``CollisionAvoidanceLimit`` stops the arm from intersecting itself, the + table/blocks and — if enabled — the other arm. + + The solve is an iterated Gauss-Newton step: each iteration moves + Δq ≈ -gain · pose_error, so the FrameTask ``gain`` (≈0.5) is the step + fraction — a full step (gain=1) overshoots and oscillates near the reach + boundary. When a target is unreachable (out of range, or held off by a + collision constraint) the loop stops once the step shrinks below + ``step_tol`` and reports the residual rather than grinding to max_iters. + """ + + def __init__( + self, + model: mujoco.MjModel, + side: str, + arm_qadr: np.ndarray, + finger_qadr: np.ndarray, + site_id: int, + home_qpos: np.ndarray, + *, + position_cost: float = 1.0, + orientation_cost: float = 1.0, + posture_cost: float = 1e-3, + frame_gain: float = 0.5, + lm_damping: float = 1e-3, + config_limit_gain: float = 0.95, + arm_max_vel: float = 1.0, + ) -> None: + self.model = model + self.side = side + self.arm_qadr = np.asarray(arm_qadr, dtype=np.int32) + self.finger_qadr = np.asarray(finger_qadr, dtype=np.int32) + self.site_id = int(site_id) + self.home_qpos = np.asarray(home_qpos, dtype=np.float64).copy() + site_name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_SITE, self.site_id) + # Names of the six arm joints (whose qpos addresses are arm_qadr), used + # to build the per-iteration velocity cap below. + arm_joint_names = [] + for a in self.arm_qadr: + j = int(np.where(model.jnt_qposadr == a)[0][0]) + arm_joint_names.append(mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_JOINT, j)) + + # Hinge joints only: jnt_qposadr == jnt_dofadr for this model, so the + # arm's qpos addresses double as its velocity (dof) indices. + self.arm_dof = [int(d) for d in self.arm_qadr] + + # mink's ConfigurationLimit AND Configuration.check_limits consider + # every *limited* joint. But the retargeted finger angles routinely + # exceed the Sharpa hand's MJCF ranges, and since every non-arm dof is + # hard-frozen the limit would demand a corrective Δq the freeze forbids + # → an infeasible QP (and check_limits, run every solve_ik, would log a + # debug line per out-of-range finger per iteration). Drop the joint + # limits on all non-arm joints (they're pinned anyway) BEFORE building + # the Configuration so its cached limited-joint snapshot also excludes + # them; ConfigurationLimit (built below) then only ever governs the 6 + # active arm joints, which keep their real ranges. + arm_dof_set = set(self.arm_dof) + for j in range(model.njnt): + if int(model.jnt_dofadr[j]) not in arm_dof_set: + model.jnt_limited[j] = 0 + + self.configuration = mink.Configuration(model, q=self.home_qpos) + self.frame_task = mink.FrameTask( + frame_name=site_name, frame_type="site", + position_cost=position_cost, orientation_cost=orientation_cost, + gain=frame_gain, lm_damping=lm_damping, + ) + frozen = [d for d in range(model.nv) if d not in arm_dof_set] + self.frozen_dof = np.asarray(frozen, dtype=np.int32) + self.freeze_task = mink.DofFreezingTask(model=model, dof_indices=frozen) + self.posture_task = mink.PostureTask(model, cost=posture_cost) + self.posture_task.set_target(self.home_qpos) + + self.config_limit = mink.ConfigurationLimit(model, gain=config_limit_gain) + # Per-iteration step cap on the arm joints. Collision avoidance is a + # velocity-level (linearized) constraint: without bounded steps a big + # Gauss-Newton jump leaps straight through a contact before the + # constraint can react. The cap keeps each step small enough that the + # linearization stays valid, so the hard collision constraints actually + # hold. Only applied when collision avoidance is on (see _limits). + self.velocity_limit = mink.VelocityLimit( + model, {name: arm_max_vel for name in arm_joint_names} + ) + self._groups = _collision_groups(model, side) + self.collision_limit = None + self.collision_pairs_n = 0 + # Count of QP iterations where daqp failed and we fell back to the + # collision-free step, and the worst (smallest) signed clearance seen + # across a solve_all_frames pass. Both reset by reset(). + self.qp_failures = 0 + self.worst_clearance = float("inf") + + def configure_collision( + self, + *, + enable: bool = True, + self_collision: bool = True, + env_collision: bool = True, + other_arm_collision: bool = False, + min_distance: float = 0.005, + detection_distance: float = 0.05, + gain: float = 0.85, + ) -> int: + """(Re)build the CollisionAvoidanceLimit; return the number of geom + pairs it tracks (0 when disabled). Cheap enough to call live from the + GUI between solves. + + ``self_collision`` adds active-arm-vs-active-arm (mink auto-drops the + adjacent/welded link pairs); ``env_collision`` adds active arm vs the + static world; ``other_arm_collision`` adds active arm vs the parked + other arm (off by default — the other arm sits far from the workspace). + + Only the arm's collision *primitives* (the UR3e link capsules, the + wrist-3 cylinder and the two couplers) are used — never the Sharpa + hand's detailed collision *meshes*. mujoco.mj_geomDistance silently + returns 0.0 for those meshes against the large table box at the query + margins mink uses, which would make the solver think the hand is + permanently in contact with the world. The wrist-3 cylinder + couplers + already guard the hand base; the frozen fingers are downstream. + """ + g = self._groups + arm = g["active_arm"] + pairs: list = [] + if enable and self_collision and arm: + pairs.append((arm, arm)) + if enable and env_collision and g["env"] and arm: + pairs.append((arm, g["env"])) + if enable and other_arm_collision and g["other_arm"] and arm: + pairs.append((arm, g["other_arm"])) + if not pairs: + self.collision_limit = None + self.collision_pairs_n = 0 + return 0 + self.collision_limit = mink.CollisionAvoidanceLimit( + self.model, pairs, gain=gain, + minimum_distance_from_collisions=min_distance, + collision_detection_distance=detection_distance, + ) + self.collision_pairs_n = int(self.collision_limit.max_num_contacts) + return self.collision_pairs_n + + def _limits(self) -> list: + lims = [self.config_limit] + if self.collision_limit is not None: + # The velocity cap is what makes the linearized collision + # constraints reliable, so pair the two. + lims.append(self.velocity_limit) + lims.append(self.collision_limit) + return lims + + def reset(self, arm_seed: np.ndarray | None = None) -> None: + """Park every dof at the home keyframe; optionally seed the active + arm at ``arm_seed`` (the IK warmstart for the first solved frame).""" + q = self.home_qpos.copy() + if arm_seed is not None: + q[self.arm_qadr] = arm_seed + self.configuration.update(q=q) + self.qp_failures = 0 + self.worst_clearance = float("inf") + + def solve( + self, + target_pos: np.ndarray, + target_quat: np.ndarray, + finger_qpos: np.ndarray, + *, + arm_seed: np.ndarray | None = None, + max_iters: int = 120, + tol_pos: float = 1e-4, + tol_rot: float = 1e-3, + step_tol: float = 1e-6, + dt: float = 0.1, + ) -> tuple[np.ndarray, float, float, int]: + """Solve IK for one frame. + + ``finger_qpos`` (22,) is written into the configuration and frozen; + ``arm_seed`` (6,) optionally re-seeds the active arm (pass it on the + first solved frame, then None to warmstart from the previous frame's + solution). + + ``dt`` cancels out of the task step and the collision *position* bound, + but it is NOT a free knob once collision avoidance is on: the + VelocityLimit caps each step at ``arm_max_vel · dt`` rad and the + CollisionAvoidanceLimit's per-step slack scales as ``1/dt``. The + default 0.1 (→ 0.1 rad/iter cap at arm_max_vel=1.0) is the tested + operating point; change it together with --ik-max-vel. + + ``pos_err`` is the true Euclidean site-position error (m) and + ``rot_err`` the geodesic orientation error (rad). Returns + (arm_qpos(6,), pos_err, rot_err, iters). + """ + data = self.configuration.data + if arm_seed is not None: + data.qpos[self.arm_qadr] = arm_seed + data.qpos[self.finger_qadr] = finger_qpos + self.configuration.update() + + rot = mink.SO3(wxyz=np.asarray(target_quat, dtype=np.float64)).normalize() + target = mink.SE3.from_rotation_and_translation( + rotation=rot, translation=np.asarray(target_pos, dtype=np.float64), + ) + self.frame_task.set_target(target) + target_pos_arr = np.asarray(target_pos, dtype=np.float64) + + limits = self._limits() + # Collision-free limit set, used to recover from a daqp infeasibility + # (collision + joint-range + freeze constraints can conflict right at a + # contact boundary). The dropped step keeps the velocity cap so it + # stays bounded; the collision limit re-engages on the next iteration. + fallback = [self.config_limit] + if self.collision_limit is not None: + fallback.append(self.velocity_limit) + tasks = [self.frame_task, self.posture_task] + pos_err = rot_err = 0.0 + it = 0 + for it in range(max_iters): + err = self.frame_task.compute_error(self.configuration) + # True Cartesian site-position error (not the SE3 twist translation + # component, which differs from Euclidean distance when a rotation + # residual coexists). rot_err is the geodesic angle (twist rotation + # part). + pos_err = float(np.linalg.norm( + target_pos_arr - self.configuration.data.site(self.site_id).xpos + )) + rot_err = float(np.linalg.norm(err[3:])) + if pos_err < tol_pos and rot_err < tol_rot: + break + try: + vel = mink.solve_ik( + self.configuration, tasks, dt, MINK_SOLVER, + limits=limits, constraints=[self.freeze_task], + ) + except mink.exceptions.NoSolutionFound: + self.qp_failures += 1 + try: + vel = mink.solve_ik( + self.configuration, tasks, dt, MINK_SOLVER, + limits=fallback, constraints=[self.freeze_task], + ) + except mink.exceptions.NoSolutionFound: + break # give up on this frame; keep the last feasible pose + # DofFreezingTask drives these to ~0 already; zero them to keep + # float noise from accumulating on the idle dofs. + vel[self.frozen_dof] = 0.0 + self.configuration.integrate_inplace(vel, dt) + if float(np.linalg.norm(vel[self.arm_dof])) * dt < step_tol: + # No further progress (converged, joint-range-limited, or held + # off by a collision constraint): re-read residual and stop. + err = self.frame_task.compute_error(self.configuration) + pos_err = float(np.linalg.norm( + target_pos_arr - self.configuration.data.site(self.site_id).xpos + )) + rot_err = float(np.linalg.norm(err[3:])) + break + return data.qpos[self.arm_qadr].copy(), pos_err, rot_err, it + + def achieved_wrist_world(self) -> np.ndarray: + """World position of the sharpa root for the current configuration: + site_pos + R_site · [0, 0, HAND_OFFSET].""" + site = self.configuration.data.site(self.site_id) + mat = np.asarray(site.xmat).reshape(3, 3) + return np.asarray(site.xpos) + mat @ np.array([0.0, 0.0, HAND_OFFSET]) + + def min_clearance(self, distmax: float = 0.2) -> float: + """Smallest signed distance over all configured collision pairs for the + current configuration (negative = penetration). Diagnostic only; NaN + when collision avoidance is disabled. ``distmax`` is kept modest + because mj_geomDistance loses accuracy for large query margins; pairs + farther apart than this clamp to ``distmax`` (they aren't the min).""" + if self.collision_limit is None: + return float("nan") + data = self.configuration.data + mujoco.mj_forward(self.model, data) + fromto = np.zeros(6) + worst = distmax + for g1, g2 in self.collision_limit.geom_id_pairs: + d = mujoco.mj_geomDistance(self.model, data, int(g1), int(g2), distmax, fromto) + worst = min(worst, d) + return worst + + +# --------------------------------------------------------------------------- +# Index resolution +# --------------------------------------------------------------------------- + + +def _resolve_indices(model: mujoco.MjModel, side: str) -> dict: + """Look up qposadr/site/body indices used by the replay loop. + + ``side`` is "right" or "left"; it selects the arm joints, the Sharpa + finger joints, and the attachment_site by name prefix. + """ + arm_joints = [ + f"{side}_shoulder_pan_joint", + f"{side}_shoulder_lift_joint", + f"{side}_elbow_joint", + f"{side}_wrist_1_joint", + f"{side}_wrist_2_joint", + f"{side}_wrist_3_joint", + ] + arm_qadr = np.array( + [model.jnt_qposadr[mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT, n)] + for n in arm_joints], + dtype=np.int32, + ) + + # Sharpa joint names carry the side prefix and are attached under a + # "_hand_" namespace, e.g. right_hand_right_thumb_CMC_FE. + finger_joints = [ + f"{side}_thumb_CMC_FE", f"{side}_thumb_CMC_AA", f"{side}_thumb_MCP_FE", + f"{side}_thumb_MCP_AA", f"{side}_thumb_IP", + f"{side}_index_MCP_FE", f"{side}_index_MCP_AA", f"{side}_index_PIP", + f"{side}_index_DIP", + f"{side}_middle_MCP_FE", f"{side}_middle_MCP_AA", f"{side}_middle_PIP", + f"{side}_middle_DIP", + f"{side}_ring_MCP_FE", f"{side}_ring_MCP_AA", f"{side}_ring_PIP", + f"{side}_ring_DIP", + f"{side}_pinky_CMC", f"{side}_pinky_MCP_FE", f"{side}_pinky_MCP_AA", + f"{side}_pinky_PIP", f"{side}_pinky_DIP", + ] + finger_qadr = np.array( + [model.jnt_qposadr[mujoco.mj_name2id( + model, mujoco.mjtObj.mjOBJ_JOINT, f"{side}_hand_" + n, + )] for n in finger_joints], + dtype=np.int32, + ) + + site_id = mujoco.mj_name2id( + model, mujoco.mjtObj.mjOBJ_SITE, f"{side}_attachment_site" + ) + return { + "arm_qadr": arm_qadr, "finger_qadr": finger_qadr, "site_id": site_id, + "arm_joint_names": arm_joints, "finger_joint_names": finger_joints, + } + + +# --------------------------------------------------------------------------- +# Workspace placement +# --------------------------------------------------------------------------- + + +def _workspace_rot_quat( + yaw_deg: float, pitch_deg: float = 0.0, roll_deg: float = 0.0 +) -> np.ndarray: + """World-frame workspace rotation RotZ(yaw) · RotY(pitch) · RotX(roll). + + Returned as a wxyz quaternion. With pitch=roll=0 this reduces to the + original yaw-only behavior. + """ + q_yaw = _axis_angle_quat(_Z_AXIS, np.deg2rad(yaw_deg)) + q_pitch = _axis_angle_quat(_Y_AXIS, np.deg2rad(pitch_deg)) + q_roll = _axis_angle_quat(_X_AXIS, np.deg2rad(roll_deg)) + return _quat_mul(q_yaw, _quat_mul(q_pitch, q_roll)) + + +def _workspace_transform( + spider_pos: np.ndarray, + spider_quat: np.ndarray, + *, + offset: np.ndarray, + yaw_deg: float, + pitch_deg: float = 0.0, + roll_deg: float = 0.0, +) -> tuple[np.ndarray, np.ndarray]: + """Apply T_workspace = Translate(offset) · RotZ(yaw)·RotY(pitch)·RotX(roll) + to a spider pose.""" + q_rot = _workspace_rot_quat(yaw_deg, pitch_deg, roll_deg) + new_pos = _quat_rotate(q_rot, spider_pos) + offset + new_quat = _quat_mul(q_rot, spider_quat) + return new_pos, new_quat + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + + +def _resolve_workspace_defaults(args: argparse.Namespace) -> None: + """Fill in workspace/start_frame defaults from a reference retarget npz + if --reference was given (or auto-detected next to --traj). Explicit + CLI overrides (any flag whose value is not None) win unconditionally. + """ + ref_path: Path | None = args.reference + auto = False + if ref_path is None: + candidate = args.traj.parent / RETARGET_FILENAME + if candidate.exists() and candidate.resolve() != args.traj.resolve(): + ref_path = candidate + auto = True + + ref = _load_reference_defaults(ref_path) if ref_path is not None else None + have_reference = ref is not None + if have_reference: + tag = "auto-detected" if auto else "explicit" + print( + f"Using reference retarget ({tag}): {ref_path}\n" + f" workspace=({ref['x']:.3f}, {ref['y']:.3f}, {ref['z']:.3f}) " + f"yaw={ref['yaw']:.1f} pitch={ref['pitch']:.1f} roll={ref['roll']:.1f} " + f"start_frame={ref['start_frame']}" + ) + else: + preset = PRESET_FRONT_OF_ARM[args.side] + ref = { + "x": preset["x"], "y": preset["y"], "z": preset["z"], + "yaw": preset["yaw"], "pitch": preset["pitch"], + "roll": preset["roll"], "start_frame": DEFAULT_START_FRAME, + } + + if args.workspace_x is None: + args.workspace_x = ref["x"] + if args.workspace_y is None: + args.workspace_y = ref["y"] + if args.workspace_z is None: + args.workspace_z = ref["z"] + if args.workspace_yaw is None: + args.workspace_yaw = ref["yaw"] + if args.workspace_pitch is None: + args.workspace_pitch = ref["pitch"] + if args.workspace_roll is None: + args.workspace_roll = ref["roll"] + args.start_frame_from_reference = have_reference and args.start_frame is None + if args.start_frame is None: + args.start_frame = ref["start_frame"] + + +def main(args: argparse.Namespace) -> None: + _resolve_workspace_defaults(args) + + print("Building dual_ur3e scene...") + spec = build() + model = spec.compile() + + home_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_KEY, "home") + data = mujoco.MjData(model) + if home_id >= 0: + mujoco.mj_resetDataKeyframe(model, data, home_id) + else: + mujoco.mj_resetData(model, data) + + idx = _resolve_indices(model, args.side) + arm_qadr = idx["arm_qadr"] + finger_qadr = idx["finger_qadr"] + site_id = idx["site_id"] + arm_joint_names = idx["arm_joint_names"] + finger_joint_names = idx["finger_joint_names"] + mount_yaw_deg = HAND_MOUNT_YAW_DEG[args.side] + print(f"Retargeting onto the {args.side} arm + {args.side} Sharpa hand.") + + print(f"Loading retarget trajectory: {args.traj}") + with np.load(args.traj) as npz: + qpos = np.asarray(npz["qpos"]) + if qpos.ndim == 3: + n_stages, steps_per_stage, _ = qpos.shape + qpos = qpos.reshape(-1, qpos.shape[-1]) + else: + n_stages, steps_per_stage = 1, qpos.shape[0] + n_frames = qpos.shape[0] + print( + f"Trajectory: {n_stages} stage(s) x {steps_per_stage} step(s) " + f"= {n_frames} frames" + ) + + sim_dt = 0.005 # spider config.yaml default + duration = n_frames * sim_dt + + if not (0 <= args.start_frame < n_frames): + if args.start_frame_from_reference: + clamped = max(0, min(args.start_frame, n_frames - 1)) + print( + f" reference start_frame={args.start_frame} out of range " + f"[0, {n_frames}); clamping to {clamped}" + ) + args.start_frame = clamped + else: + raise ValueError( + f"--start-frame={args.start_frame} out of range [0, {n_frames})" + ) + + solved_arm_qpos = np.zeros((n_frames, 6), dtype=np.float64) + home_arm_qpos = data.qpos[arm_qadr].copy() # home keyframe values + + # Build the collision-aware mink IK solver. It wraps the full model in one + # mink.Configuration and only ever moves the active arm. + ik_solver = MinkArmIK( + model, args.side, arm_qadr, finger_qadr, site_id, data.qpos.copy(), + frame_gain=args.ik_gain, lm_damping=args.ik_lm_damping, + posture_cost=args.posture_cost, arm_max_vel=args.ik_max_vel, + ) + npair = ik_solver.configure_collision( + enable=args.collision, + self_collision=not args.no_self_collision, + env_collision=not args.no_env_collision, + other_arm_collision=args.collision_other_arm, + min_distance=args.collision_min_dist, + detection_distance=args.collision_detect_dist, + gain=args.collision_gain, + ) + if args.collision: + bits = [] + if not args.no_self_collision: + bits.append("self") + if not args.no_env_collision: + bits.append("env") + if args.collision_other_arm: + bits.append("other-arm") + print( + f"IK backend: mink — collision avoidance ON " + f"[{'+'.join(bits) or 'none'}], {npair} geom pairs, " + f"clearance>={args.collision_min_dist*1000:.0f}mm, " + f"gain={args.ik_gain}" + ) + else: + print(f"IK backend: mink — collision avoidance OFF, gain={args.ik_gain}") + + def solve_all_frames( + wx: float, wy: float, wz: float, yaw_deg: float, + pitch_deg: float, roll_deg: float, + ik_iters: int, start_frame: int, + ) -> tuple[float, float, float, np.ndarray]: + """Re-run IK for the trajectory at the given workspace transform. + + ``start_frame`` is the frame whose wrist is anchored at + ``(wx, wy, wz)``. IK is solved for f >= start_frame; for + f < start_frame the arm just holds the start_frame pose, so the + arm starts moving from start_frame onwards. Hand finger angles + always come from ``qpos[f, 6:28]`` regardless. + + ``yaw_deg``/``pitch_deg``/``roll_deg`` rotate the rest of the + trajectory around the anchor point (RotZ·RotY·RotX, world frame). + + Returns (start_frame_pos_err, worst_pos_err, worst_rot_err, + start_frame_wrist_world). + """ + offset = np.array([wx, wy, wz], dtype=np.float64) + wrist_anchor_spider = qpos[start_frame, 0:3].copy() + + warmstart = home_arm_qpos.copy() + worst_pos = 0.0 + worst_rot = 0.0 + start_pos_err = 0.0 + start_wrist = np.zeros(3) + # mink warmstarts from the persistent configuration: park every idle + # dof at home before the chain so re-solves (GUI recompute) start clean. + ik_solver.reset() + for f in range(start_frame, n_frames): + spider_pos, spider_quat = _spider_root_pose(qpos[f]) + spider_pos_rel = spider_pos - wrist_anchor_spider + root_world_pos, root_world_quat = _workspace_transform( + spider_pos_rel, spider_quat, offset=offset, + yaw_deg=yaw_deg, pitch_deg=pitch_deg, roll_deg=roll_deg, + ) + flange_pos, flange_quat = _flange_target_from_sharpa_root( + root_world_pos, root_world_quat, mount_yaw_deg + ) + finger_vals = qpos[f, SPIDER_FINGER_SLICE] + # Seed the arm only on the first solved frame; afterwards the + # persistent mink configuration warmstarts from the previous + # solution. Collision/joint limits are baked into the QP. The + # start frame is a big move from home (mink takes small capped + # steps), so give it a larger iteration budget than the cheap + # warmstarted frames. + seed = warmstart if f == start_frame else None + f_iters = max(ik_iters, 200) if f == start_frame else ik_iters + arm_sol, pe, re, _ = ik_solver.solve( + flange_pos, flange_quat, finger_vals, + arm_seed=seed, max_iters=f_iters, + ) + solved_arm_qpos[f] = arm_sol + if ik_solver.collision_limit is not None: + ik_solver.worst_clearance = min( + ik_solver.worst_clearance, ik_solver.min_clearance() + ) + # Mirror into the render `data` so downstream readers stay valid. + data.qpos[arm_qadr] = arm_sol + data.qpos[finger_qadr] = finger_vals + warmstart = solved_arm_qpos[f].copy() + worst_pos = max(worst_pos, pe) + worst_rot = max(worst_rot, re) + if f == start_frame: + start_pos_err = pe + start_wrist = ik_solver.achieved_wrist_world().copy() + # Frames before start_frame just hold the start pose. + if start_frame > 0: + solved_arm_qpos[:start_frame] = solved_arm_qpos[start_frame] + return start_pos_err, worst_pos, worst_rot, start_wrist + + # Pre-solve IK for all frames so playback is smooth and IK errors are + # surfaced once at startup. + print( + f"Solving IK for frames {args.start_frame}..{n_frames - 1} " + f"(arm holds {args.start_frame} for f<{args.start_frame})..." + ) + _t_solve = time.perf_counter() + sf_pos, worst_pos, worst_rot, sf_wrist = solve_all_frames( + args.workspace_x, args.workspace_y, args.workspace_z, + args.workspace_yaw, args.workspace_pitch, args.workspace_roll, + args.ik_iters, args.start_frame, + ) + print( + f" solved {n_frames - args.start_frame} frames in " + f"{time.perf_counter() - _t_solve:.1f}s\n" + f" start_frame ({args.start_frame}) pos_err={sf_pos*1000:.2f} mm " + f"achieved wrist world=({sf_wrist[0]:.3f}, {sf_wrist[1]:.3f}, {sf_wrist[2]:.3f})\n" + f" worst residual across solved frames: " + f"pos={worst_pos*1000:.2f} mm, rot={np.rad2deg(worst_rot):.2f} deg" + ) + if ik_solver.collision_limit is not None: + clr = ik_solver.worst_clearance + flag = " (PENETRATION!)" if clr < -1e-4 else " (collision-free)" + qpf = ( + f", {ik_solver.qp_failures} QP fallbacks" + if ik_solver.qp_failures else "" + ) + print( + f" collision: {ik_solver.collision_pairs_n} geom pairs tracked, " + f"worst signed clearance across all solved frames = " + f"{clr*1000:.1f} mm{flag}{qpf}" + ) + + if args.solve_only: + print("--solve-only: IK solved, skipping the viser GUI.") + return + + # Reset data to home for replay rendering. + if home_id >= 0: + mujoco.mj_resetDataKeyframe(model, data, home_id) + + server = viser.ViserServer() + mj_scene = ViserMujocoScene(server, model, num_envs=1) + # Default camera-tracking shifts the entire scene so the first dynamic + # body sits at the viewer origin — that makes our markers (which we + # place in true world coords) appear in the wrong spot. Disable it so + # what you see matches the underlying world frame. + mj_scene.camera_tracking_enabled = False + + # Parent both reference frames under /fixed_bodies so that if tracking + # ever gets toggled back on (its position is set to the tracking offset + # each frame), our markers slide along with the rest of the scene. + # Static world-origin marker (permanent reference at world (0, 0, 0)). + server.scene.add_frame( + "/fixed_bodies/world_origin", + show_axes=True, + axes_length=0.30, + axes_radius=0.008, + position=(0.0, 0.0, 0.0), + ) + + # Live frame: where the wrist (sharpa root) sits at frame 0 after the + # workspace transform. Position = (ws_x, ws_y, ws_z); RotZ(ws_yaw). + target_frame = server.scene.add_frame( + "/fixed_bodies/workspace_target", + show_axes=True, + axes_length=0.15, + axes_radius=0.004, + position=(args.workspace_x, args.workspace_y, args.workspace_z), + ) + + def update_target_frame() -> None: + target_frame.position = ( + float(ws_x.value), float(ws_y.value), float(ws_z.value), + ) + q = _workspace_rot_quat( + float(ws_yaw.value), float(ws_pitch.value), float(ws_roll.value) + ) + target_frame.wxyz = (float(q[0]), float(q[1]), float(q[2]), float(q[3])) + + frame_idx = [0] + playing = [True] + speed = [float(args.speed)] + looping = [True] + accumulator = [0.0] + needs_render = [True] + + tabs = mj_scene.create_visualization_gui() + with tabs.add_tab("Playback", icon=viser.Icon.PLAYER_PLAY): + timeline = server.gui.add_slider( + "Frame", min=0, max=n_frames - 1, step=1, initial_value=0, + ) + time_label = server.gui.add_html("") + play_btn = server.gui.add_button("Pause", icon=viser.Icon.PLAYER_PAUSE) + + @play_btn.on_click + def _(_) -> None: + playing[0] = not playing[0] + play_btn.label = "Pause" if playing[0] else "Play" + play_btn.icon = ( + viser.Icon.PLAYER_PAUSE if playing[0] else viser.Icon.PLAYER_PLAY + ) + + speed_opts = ["0.25x", "0.5x", "1x", "2x", "4x"] + speed_btns = server.gui.add_button_group("Speed", options=speed_opts) + # Highlight the button matching --speed (e.g. 0.25 -> "0.25x"). Any + # value outside the presets still plays at speed[0]; the buttons just + # won't reflect it. + _speed_label = f"{speed[0]:g}x" + if _speed_label in speed_opts: + speed_btns.value = _speed_label + + @speed_btns.on_click + def _(event) -> None: + speed[0] = float(event.target.value.replace("x", "")) + + loop_cb = server.gui.add_checkbox("Loop", initial_value=True) + + @loop_cb.on_update + def _(_) -> None: + looping[0] = loop_cb.value + + @timeline.on_update + def _(_) -> None: + frame_idx[0] = int(timeline.value) + needs_render[0] = True + + with tabs.add_tab("Workspace", icon=viser.Icon.ADJUSTMENTS): + ws_x = server.gui.add_slider( + "x (m)", min=-0.8, max=0.8, step=0.005, + initial_value=float(args.workspace_x), + ) + ws_y = server.gui.add_slider( + "y (m)", min=-0.8, max=0.8, step=0.005, + initial_value=float(args.workspace_y), + ) + ws_z = server.gui.add_slider( + "z (m)", min=0.0, max=1.6, step=0.005, + initial_value=float(args.workspace_z), + ) + ws_yaw = server.gui.add_slider( + "yaw (deg)", min=-180.0, max=180.0, step=1.0, + initial_value=float(args.workspace_yaw), + ) + ws_pitch = server.gui.add_slider( + "pitch (deg)", min=-180.0, max=180.0, step=1.0, + initial_value=float(args.workspace_pitch), + ) + ws_roll = server.gui.add_slider( + "roll (deg)", min=-180.0, max=180.0, step=1.0, + initial_value=float(args.workspace_roll), + ) + ws_start_frame = server.gui.add_slider( + "start frame (arm holds before)", + min=0, max=n_frames - 1, step=1, + initial_value=int(args.start_frame), + ) + ik_iters_slider = server.gui.add_slider( + "ik iters", min=8, max=256, step=8, + initial_value=int(args.ik_iters), + ) + ik_status = server.gui.add_html("") + + # --- Collision avoidance. These rebuild the mink CollisionAvoidanceLimit + # on the next "Recompute IK". Disable + recompute for a fast workspace + # tune, then re-enable for the final collision-free solve. + col_enable = server.gui.add_checkbox( + "collision avoidance", initial_value=bool(args.collision), + ) + col_self = server.gui.add_checkbox( + "· arm self-collision", initial_value=bool(not args.no_self_collision), + ) + col_env = server.gui.add_checkbox( + "· vs table / blocks", initial_value=bool(not args.no_env_collision), + ) + col_other = server.gui.add_checkbox( + "· vs other arm", initial_value=bool(args.collision_other_arm), + ) + col_min = server.gui.add_slider( + "min clearance (m)", min=0.0, max=0.05, step=0.001, + initial_value=float(args.collision_min_dist), + ) + col_detect = server.gui.add_slider( + "detect distance (m)", min=0.01, max=0.15, step=0.005, + initial_value=float(args.collision_detect_dist), + ) + col_status = server.gui.add_html( + f'{ik_solver.collision_pairs_n} ' + f"geom pairs" + ) + + recompute_btn = server.gui.add_button( + "Recompute IK", icon=viser.Icon.REFRESH + ) + + default_out = str(args.traj.parent / RETARGET_FILENAME) + save_path = server.gui.add_text("output path", initial_value=default_out) + save_status = server.gui.add_html("") + save_btn = server.gui.add_button( + "Save retarget", icon=viser.Icon.DEVICE_FLOPPY + ) + + @save_btn.on_click + def _(_) -> None: + save_btn.disabled = True + try: + out = Path(save_path.value).expanduser() + out.parent.mkdir(parents=True, exist_ok=True) + arm_qpos_out = solved_arm_qpos.copy() + finger_qpos_out = qpos[:, SPIDER_FINGER_SLICE].astype(np.float64) + np.savez( + out, + arm_qpos=arm_qpos_out, + finger_qpos=finger_qpos_out, + arm_joint_names=np.array(arm_joint_names), + finger_joint_names=np.array(finger_joint_names), + dt=np.float64(sim_dt), + start_frame=np.int64(int(ws_start_frame.value)), + workspace_xyz=np.array( + [float(ws_x.value), float(ws_y.value), float(ws_z.value)] + ), + workspace_yaw_deg=np.float64(float(ws_yaw.value)), + workspace_pitch_deg=np.float64(float(ws_pitch.value)), + workspace_roll_deg=np.float64(float(ws_roll.value)), + side=str(args.side), + source_traj=str(args.traj), + ) + save_status.content = ( + f'' + f"saved {arm_qpos_out.shape[0]} frames " + f"({arm_qpos_out.shape[1]} arm + " + f"{finger_qpos_out.shape[1]} finger) → {out}" + f"" + ) + except Exception as e: + save_status.content = ( + f'' + f"save failed: {type(e).__name__}: {e}" + f"" + ) + finally: + save_btn.disabled = False + + for s in (ws_x, ws_y, ws_z, ws_yaw, ws_pitch, ws_roll): + @s.on_update + def _(_) -> None: + update_target_frame() + + @recompute_btn.on_click + def _(_) -> None: + recompute_btn.disabled = True + ik_status.content = ( + 'Solving…' + ) + try: + t0 = time.perf_counter() + # Rebuild the mink collision limit from the live GUI controls + # before re-solving. + npair = ik_solver.configure_collision( + enable=bool(col_enable.value), + self_collision=bool(col_self.value), + env_collision=bool(col_env.value), + other_arm_collision=bool(col_other.value), + min_distance=float(col_min.value), + detection_distance=float(col_detect.value), + gain=float(args.collision_gain), + ) + col_status.content = ( + f'{npair} geom pairs ' + f"{'(on)' if npair else '(off)'}" + ) + sf_idx = int(ws_start_frame.value) + sf_pos, w_pos, w_rot, sf_wrist = solve_all_frames( + float(ws_x.value), float(ws_y.value), float(ws_z.value), + float(ws_yaw.value), float(ws_pitch.value), float(ws_roll.value), + int(ik_iters_slider.value), sf_idx, + ) + dt = time.perf_counter() - t0 + col_line = "" + if ik_solver.collision_limit is not None: + clr = ik_solver.worst_clearance + warn = ' style="color:#c33"' if clr < -1e-4 else "" + col_line = ( + f"
worst clearance " + f"{clr*1000:.1f} mm ({ik_solver.collision_pairs_n} pairs)" + f"" + ) + ik_status.content = ( + f'' + f"solved {n_frames - sf_idx} frames in {dt:.2f}s  ·  " + f"start ({sf_idx}) err {sf_pos*1000:.1f} mm  ·  " + f"worst {w_pos*1000:.1f} mm / {np.rad2deg(w_rot):.1f}°
" + f"start wrist world: " + f"({sf_wrist[0]:.3f}, {sf_wrist[1]:.3f}, {sf_wrist[2]:.3f})" + f"{col_line}" + f"
" + ) + # Snap timeline to the start frame and pause so the user + # sees the held pose right away. + frame_idx[0] = sf_idx + timeline.value = sf_idx + accumulator[0] = 0.0 + if playing[0]: + playing[0] = False + play_btn.label = "Play" + play_btn.icon = viser.Icon.PLAYER_PLAY + needs_render[0] = True + finally: + recompute_btn.disabled = False + + def render_frame(f: int) -> None: + data.qpos[arm_qadr] = solved_arm_qpos[f] + data.qpos[finger_qadr] = qpos[f, SPIDER_FINGER_SLICE] + mujoco.mj_forward(model, data) + mj_scene.update_from_mjdata(data) + stage = f // steps_per_stage if steps_per_stage > 0 else 0 + step_in_stage = f % steps_per_stage if steps_per_stage > 0 else f + t = f * sim_dt + # Per-joint angles in degrees so the user can read the actual values + # off the timeline. + q_deg = np.rad2deg(solved_arm_qpos[f]) + joints_html = "   ".join( + f"j{j}={q_deg[j]:+6.1f}°" for j in range(6) + ) + time_label.content = ( + f'' + f"{t:.2f}s / {duration:.2f}s  ·  " + f"frame {f}/{n_frames - 1}  ·  " + f"stage {stage}/{max(n_stages - 1, 0)} (step {step_in_stage})" + f"
{joints_html}" + f"
" + ) + + render_frame(0) + + last_time = time.perf_counter() + try: + while True: + now = time.perf_counter() + wall_dt = now - last_time + last_time = now + if playing[0]: + accumulator[0] += wall_dt * speed[0] + frames_to_advance = int(accumulator[0] / sim_dt) + if frames_to_advance > 0: + accumulator[0] -= frames_to_advance * sim_dt + new_idx = frame_idx[0] + frames_to_advance + if new_idx >= n_frames: + if looping[0]: + new_idx = new_idx % n_frames + else: + new_idx = n_frames - 1 + playing[0] = False + play_btn.label = "Play" + play_btn.icon = viser.Icon.PLAYER_PLAY + frame_idx[0] = new_idx + timeline.value = new_idx + render_frame(new_idx) + elif needs_render[0]: + render_frame(frame_idx[0]) + needs_render[0] = False + time.sleep(1.0 / 60.0) + except KeyboardInterrupt: + print("\nStopped.") + server.stop() + + +def _parse_args() -> argparse.Namespace: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--traj", type=Path, default=DEFAULT_TRAJ) + p.add_argument( + "--side", choices=("right", "left"), default="right", + help="Which arm + Sharpa hand to retarget onto (default: right).", + ) + p.add_argument( + "--speed", type=float, default=1.0, + help=( + "Initial viser playback speed (default 1.0). Highlights the GUI " + "Speed button when set to 0.25/0.5/1/2/4; other values still play. " + "Ignored with --solve-only." + ), + ) + p.add_argument( + "--reference", type=Path, default=None, + help=( + "Path to a previously-saved trajectory_dual_ur3e.npz. " + "Its workspace_xyz / workspace_yaw_deg / start_frame become the " + "defaults for --workspace-x/-y/-z, --workspace-yaw, --start-frame " + "(any flag passed explicitly still wins). When omitted, the script " + "auto-detects a sibling trajectory_dual_ur3e.npz next to --traj." + ), + ) + # Defaults are resolved in _resolve_workspace_defaults: reference file + # (explicit or auto-detected) → PRESET_FRONT_OF_ARM / DEFAULT_START_FRAME. + p.add_argument( + "--workspace-x", type=float, default=None, + help="dual_ur3e world x (m) of the wrist at frame 0", + ) + p.add_argument( + "--workspace-y", type=float, default=None, + help="dual_ur3e world y (m) of the wrist at frame 0", + ) + p.add_argument( + "--workspace-z", type=float, default=None, + help="dual_ur3e world z (m) of the wrist at frame 0", + ) + p.add_argument( + "--workspace-yaw", type=float, default=None, + help="yaw (deg) rotating the rest of the trajectory around the wrist anchor", + ) + p.add_argument( + "--workspace-pitch", type=float, default=None, + help="pitch (deg) rotating the rest of the trajectory around the wrist anchor", + ) + p.add_argument( + "--workspace-roll", type=float, default=None, + help="roll (deg) rotating the rest of the trajectory around the wrist anchor", + ) + p.add_argument( + "--start-frame", type=int, default=None, + help=( + "Frame whose wrist is anchored at (workspace-x, -y, -z). " + "The arm holds this pose for f~0.7 oscillates near the reach boundary." + ), + ) + p.add_argument("--ik-lm-damping", type=float, default=1e-3, + help="mink FrameTask Levenberg-Marquardt damping (singularity robustness).") + p.add_argument("--posture-cost", type=float, default=1e-3, + help="mink PostureTask cost — weak nullspace bias toward the seed posture.") + p.add_argument( + "--ik-max-vel", type=float, default=1.0, + help=( + "Per-iteration arm joint step cap (the mink VelocityLimit, applied " + "only with collision avoidance). Smaller steps keep the linearized " + "collision constraints accurate — too large and the arm leaps " + "through contacts before they engage. Default 1.0." + ), + ) + # --- Collision avoidance --- + p.add_argument( + "--collision", action=argparse.BooleanOptionalAction, default=True, + help="Enable mink collision avoidance (default on; --no-collision to disable).", + ) + p.add_argument( + "--no-self-collision", action="store_true", + help="Drop arm-vs-arm self-collision constraints (kept on by default).", + ) + p.add_argument( + "--no-env-collision", action="store_true", + help="Drop arm/hand-vs-table/blocks constraints (kept on by default).", + ) + p.add_argument( + "--collision-other-arm", action="store_true", + help=( + "Also avoid the parked other arm+hand (off by default — it roughly " + "doubles the geom-pair count and the other arm sits far from the " + "workspace)." + ), + ) + p.add_argument( + "--collision-min-dist", type=float, default=0.005, + help="Clearance (m) to maintain between collision geoms (default 0.005).", + ) + p.add_argument( + "--collision-detect-dist", type=float, default=0.05, + help=( + "Distance (m) within which a geom pair becomes an active constraint " + "(default 0.05). Larger = smoother avoidance, slower solve." + ), + ) + p.add_argument( + "--collision-gain", type=float, default=0.85, + help="mink CollisionAvoidanceLimit gain in (0,1] — approach speed toward the bound.", + ) + p.add_argument( + "--solve-only", action="store_true", + help="Solve IK, print residual/collision stats, and exit without the viser GUI.", + ) + return p.parse_args() + + +if __name__ == "__main__": + main(_parse_args()) diff --git a/third-party/do-as-i-do/deployment/robot_replay/config.example.yaml b/third-party/do-as-i-do/deployment/robot_replay/config.example.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f3d3f05511686d1b6053a8774635626bae7ceda2 --- /dev/null +++ b/third-party/do-as-i-do/deployment/robot_replay/config.example.yaml @@ -0,0 +1,37 @@ +# Deployment config for robot_replay (UR3e arms + Sharpa Wave hands). +# +# Copy this to config.yaml and fill in your facility's real robot IPs and hand +# serial numbers. config.yaml is gitignored — it holds machine-specific values. +# +# cp config.example.yaml config.yaml # then edit arm_ip / hand_sn + +# Path to the vendored Sharpa Wave SDK python bindings, relative to robot_replay/. +# The SDK is proprietary and NOT shipped in the repo — drop it into +# robot_replay/Sharpa/ (which is gitignored). +sharpa_sdk_path: ./Sharpa/SDK/SharpaWaveSDK_4_3_4/python + +left: + arm_ip: 192.168.x.x # left UR3e RTDE IP + hand_sn: REPLACE_ME # left Sharpa hand serial + servoj_lookahead: 0.1 # ur_rtde servoJ lookahead time (s) + servoj_gain: 300 # ur_rtde servoJ proportional gain + home_arm_q: # 6 joint angles (rad): pan, lift, elbow, w1, w2, w3 + - -1.8307955900775355 + - -1.5707963267948966 + - 0.0 + - -3.141592653589793 + - -1.5707963267948966 + - 3.9269908169872414 + +right: + arm_ip: 192.168.x.x # right UR3e RTDE IP + hand_sn: REPLACE_ME # right Sharpa hand serial + servoj_lookahead: 0.03 + servoj_gain: 600 + home_arm_q: + - 2.023838758468628 + - -1.5707963267948966 + - 0.0 + - 0.0 + - 1.5707963267948966 + - -3.9269908169872414 diff --git a/third-party/do-as-i-do/deployment/robot_replay/executor.py b/third-party/do-as-i-do/deployment/robot_replay/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..165ff5a3d261ef4cf2e9d07ec9a8963d1cdc5a90 --- /dev/null +++ b/third-party/do-as-i-do/deployment/robot_replay/executor.py @@ -0,0 +1,165 @@ +"""Unified UR3e arm + Sharpa Wave hand executor for one side (left or right). + +Merges the former left_executor.py / right_executor.py, which were byte-identical +except for per-side constants (arm IP, hand serial, servoJ tuning, home pose). +Those now live in config.yaml (see config.example.yaml); select a side with the +``side`` argument. + +Command layout (28-dim, all radians): + cmd[0:6] -> UR3e joint angles for servoJ + cmd[6:28] -> Sharpa 22 joint angles for set_joint_position +""" +import sys +import time +from pathlib import Path + +import yaml + +import rtde_control +import rtde_receive + +HERE = Path(__file__).resolve().parent +DEFAULT_CONFIG = HERE / "config.yaml" +EXAMPLE_CONFIG = HERE / "config.example.yaml" +DEFAULT_SHARPA_SDK = HERE / "Sharpa" / "SDK" / "SharpaWaveSDK_4_3_4" / "python" + +CMD_DIM = 28 +ARM_DIM = 6 +HAND_DIM = 22 + + +def load_config(path=None): + """Load the deployment config. + + With no ``path``, uses config.yaml if present, else falls back to the + committed config.example.yaml (placeholder IPs/serials — fine for --dry-run + or inspection, but real values are needed to connect to hardware). + """ + if path is None: + path = DEFAULT_CONFIG if DEFAULT_CONFIG.exists() else EXAMPLE_CONFIG + path = Path(path).expanduser() + if not path.exists(): + raise FileNotFoundError( + f"config not found: {path}. Copy config.example.yaml to config.yaml " + f"and fill in your robot IPs / hand serials." + ) + with open(path) as f: + return yaml.safe_load(f) + + +def _import_sharpa(sdk_path): + """Add the vendored Sharpa SDK python bindings to sys.path and import the + API. Returns (SharpaWaveManager, ControlMode, ControlSource). + + The SDK is not shipped in the repo; drop it into robot_replay/Sharpa/ + (see config.example.yaml: sharpa_sdk_path). + """ + sdk_path = str(Path(sdk_path).expanduser()) + if sdk_path not in sys.path: + sys.path.insert(0, sdk_path) + from sharpa import SharpaWaveManager, ControlMode, ControlSource + return SharpaWaveManager, ControlMode, ControlSource + + +class Controller: + """One UR3e arm (ur_rtde) + one Sharpa hand, selected by ``side``.""" + + def __init__(self, side, cfg, dt, use_arm=True, use_hand=True): + if side not in ("left", "right"): + raise ValueError(f"side must be 'left' or 'right', got {side!r}") + if not (use_arm or use_hand): + raise ValueError("at least one of use_arm/use_hand must be True") + self.side = side + self.dt = dt + self.use_arm = use_arm + self.use_hand = use_hand + + side_cfg = cfg[side] + self.arm_ip = side_cfg["arm_ip"] + self.hand_sn = side_cfg["hand_sn"] + self.servoj_lookahead = float(side_cfg.get("servoj_lookahead", 0.1)) + self.servoj_gain = float(side_cfg.get("servoj_gain", 300)) + self.home_arm_q = list(side_cfg["home_arm_q"]) + self.sharpa_sdk_path = cfg.get("sharpa_sdk_path", str(DEFAULT_SHARPA_SDK)) + + if use_arm: + print(f"Connecting UR3e ({side}) at {self.arm_ip}...") + self.rtde_c = rtde_control.RTDEControlInterface(self.arm_ip) + self.rtde_r = rtde_receive.RTDEReceiveInterface(self.arm_ip) + self.q0 = self.rtde_r.getActualQ() + print(f"Starting arm Q (rad): {self.q0}") + else: + self.rtde_c = None + self.rtde_r = None + self.q0 = None + + if use_hand: + print(f"Connecting Sharpa hand ({side}) {self.hand_sn}...") + self._sharpa = _import_sharpa(self.sharpa_sdk_path) + self.hand = self._connect_hand() + else: + self._sharpa = None + self.hand = None + + def _connect_hand(self): + SharpaWaveManager, ControlMode, ControlSource = self._sharpa + manager = SharpaWaveManager.get_instance() + time.sleep(1.0) + hand = manager.connect(self.hand_sn) + if hand is None: + raise RuntimeError(f"Failed to connect Sharpa hand {self.hand_sn}") + + for fn, val, name in [ + (hand.set_control_mode, ControlMode.POSITION, "control_mode"), + (hand.set_speed_coeff, 0.3, "speed_coeff"), + (hand.set_current_coeff, 0.6, "current_coeff"), + (hand.set_control_source, ControlSource.SDK, "control_source"), + ]: + err = fn(val) + if err.code != 0: + raise RuntimeError(f"Failed to set {name}: {err.message}") + + hand.start() + hand.set_joint_position([0.0] * HAND_DIM, True) + return hand + + def execute(self, cmd): + if len(cmd) != CMD_DIM: + raise ValueError(f"cmd must be {CMD_DIM}-dim, got {len(cmd)}") + + arm_q = list(cmd[:ARM_DIM]) + hand_q = list(cmd[ARM_DIM:]) + + if self.use_arm: + self.rtde_c.servoJ( + arm_q, 0.0, 0.0, self.dt, self.servoj_lookahead, self.servoj_gain + ) + + if self.use_hand: + err = self.hand.set_joint_position(hand_q, True) + if err.code != 0: + print(f"hand set_joint_position error: {err.message}") + + def close(self, reset_hand=True): + if self.use_arm: + try: + self.rtde_c.servoStop() + self.rtde_c.stopScript() + except Exception as e: + print(f"arm stop error: {e}") + if self.use_hand: + try: + if reset_hand: + self.hand.set_joint_position([0.0] * HAND_DIM, True) + time.sleep(0.5) + self.hand.stop() + self._sharpa[0].get_instance().disconnect_all() + except Exception as e: + print(f"hand stop error: {e}") + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + return False diff --git a/third-party/do-as-i-do/deployment/robot_replay/home.py b/third-party/do-as-i-do/deployment/robot_replay/home.py new file mode 100644 index 0000000000000000000000000000000000000000..86c0a14a7b959c45d790a3bca6a6c366103165f8 --- /dev/null +++ b/third-party/do-as-i-do/deployment/robot_replay/home.py @@ -0,0 +1,63 @@ +"""Home one UR3e arm and/or Sharpa hand (merges home_left.py / home_right.py). + + python home.py --side left + python home.py --side right --arm-only + python home.py --side left --hand-only + +The arm home pose comes from config.yaml (per side); the hand homes to zeros. +""" +import argparse +import time + +from executor import Controller, load_config, ARM_DIM, HAND_DIM + + +DT = 1.0 / 50 +HAND_SETTLE_S = 3.0 + +# moveJ defaults are speed=1.05 rad/s, acceleration=1.4 rad/s^2; lower = slower homing. +MOVEJ_SPEED = 0.5 +MOVEJ_ACCEL = 0.5 + +HOME_HAND_Q = [0.0] * 22 + + +def main(): + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("--side", choices=("left", "right"), required=True, + help="Which arm + hand to home.") + parser.add_argument("--config", default=None, + help="Path to config.yaml (default: ./config.yaml, else config.example.yaml).") + group = parser.add_mutually_exclusive_group() + group.add_argument("--arm-only", action="store_true", help="Only home the arm.") + group.add_argument("--hand-only", action="store_true", help="Only home the hand.") + args = parser.parse_args() + + home_arm = not args.hand_only + home_hand = not args.arm_only + + cfg = load_config(args.config) + with Controller(side=args.side, cfg=cfg, dt=DT, use_arm=home_arm, use_hand=home_hand) as ctrl: + assert len(ctrl.home_arm_q) == ARM_DIM + assert len(HOME_HAND_Q) == HAND_DIM + + if home_arm: + print("Homing arm via moveJ...") + ctrl.rtde_c.moveJ(ctrl.home_arm_q, MOVEJ_SPEED, MOVEJ_ACCEL) + print("Arm homed.") + + if home_hand: + print("Homing hand (interpolation mode)...") + enable_interpolation_mode = True + err = ctrl.hand.set_joint_position(HOME_HAND_Q, enable_interpolation_mode) + if err.code != 0: + print(f"hand set_joint_position error: {err.message}") + time.sleep(HAND_SETTLE_S) + + print("Homing complete.") + + +if __name__ == "__main__": + main() diff --git a/third-party/do-as-i-do/deployment/robot_replay/run_npz.py b/third-party/do-as-i-do/deployment/robot_replay/run_npz.py new file mode 100644 index 0000000000000000000000000000000000000000..feaff269e3b3350a00c01d349880bab3102a262e --- /dev/null +++ b/third-party/do-as-i-do/deployment/robot_replay/run_npz.py @@ -0,0 +1,198 @@ +"""Replay a dual_ur3e trajectory on one real arm + hand (left or right). + +Merges the former run_left_npz.py / run_right_npz.py — pick the side with +--side {left,right}. Streams at a fixed 50 Hz; --speed resamples the trajectory +in time (not the streaming rate). --arm/--hand/--both selects which subsystem(s) +to drive. --dry-run loads + resamples without connecting to any hardware. + +Defaults: --speed 1.0 (real-time) + --arm (arm only) + +Quick start (arm only, real-time): + python run_npz.py --side left trajectory_dual_ur3e.npz + +More examples: + python run_npz.py --side right traj.npz --speed 0.5 # arm, half speed + python run_npz.py --side left traj.npz --speed 0.25 --both # arm + hand, quarter speed + python run_npz.py --side left traj.npz --hand # hand only, real-time + python run_npz.py --side left traj.npz --dry-run # validate, no hardware + +The script connects, homes, moves to the trajectory start, then waits for you +to press Enter before streaming. Per-side robot IPs / hand serials / servoJ +tuning / home pose come from config.yaml (see config.example.yaml). + +The npz must contain arm_qpos (N, 6), finger_qpos (N, 22), and dt (scalar, s) — +exactly what mujoco_replay/replay_retarget.py saves. +""" +import argparse +import time + +import numpy as np + +from executor import Controller, load_config, ARM_DIM, HAND_DIM, CMD_DIM + + +DEFAULT_NPZ = "trajectory_dual_ur3e.npz" + +STREAMING_HZ = 50 +DT = 1.0 / STREAMING_HZ + +HOME_SETTLE_S = 3.0 +START_SETTLE_S = 2.0 + +# moveJ speed/acceleration (rad/s, rad/s^2) for positioning moves: homing and +# moving to the trajectory start. ur_rtde defaults are 1.05/1.4; lower = slower/safer. +MOVE_SPEED = 0.5 +MOVE_ACCEL = 0.5 + +# Pause streaming for human confirmation after this NATIVE trajectory frame +# (raw npz row index, before resampling; None to disable). The streamed frame at +# which playback reaches this native frame is computed from --speed. The robot +# holds its last position (servoJ target) while waiting. +PAUSE_AFTER_FRAME = 600 + + +class FrequencyTimer: + def __init__(self, rate_hz): + self.period_ns = int(1e9 / rate_hz) + + def start_loop(self): + self.start_ns = time.time_ns() + + def end_loop(self): + deadline = self.start_ns + self.period_ns + while time.time_ns() < deadline: + pass + + +def parse_args(): + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument('--side', choices=('left', 'right'), required=True, + help='Which arm + hand to drive.') + parser.add_argument('npz', nargs='?', default=DEFAULT_NPZ, + help=f'Path to trajectory npz (default: {DEFAULT_NPZ}).') + parser.add_argument('--speed', type=float, default=1.0, + help='Playback speed multiplier (1.0 = real-time, 0.5 = half speed). Default 1.0.') + parser.add_argument('--config', default=None, + help='Path to config.yaml (default: ./config.yaml, else config.example.yaml).') + parser.add_argument('--dry-run', action='store_true', + help='Load + resample the trajectory and print stats; do NOT connect to hardware.') + + target = parser.add_mutually_exclusive_group() + target.add_argument('--arm', dest='target', action='store_const', const='arm', + help='Run arm only (default).') + target.add_argument('--hand', dest='target', action='store_const', const='hand', + help='Run hand only.') + target.add_argument('--both', dest='target', action='store_const', const='both', + help='Run arm and hand.') + parser.set_defaults(target='arm') + return parser.parse_args() + + +def load_and_resample(npz_path, speed): + data = np.load(npz_path) + arm = data['arm_qpos'] + hand = data['finger_qpos'] + native_dt = float(data['dt']) + + if arm.shape[0] != hand.shape[0]: + raise ValueError(f"arm_qpos ({arm.shape}) and finger_qpos ({hand.shape}) length mismatch") + if arm.shape[1] != ARM_DIM or hand.shape[1] != HAND_DIM: + raise ValueError(f"expected arm (N,{ARM_DIM}) hand (N,{HAND_DIM}); got {arm.shape}, {hand.shape}") + + traj = np.concatenate([arm, hand], axis=1) + assert traj.shape[1] == CMD_DIM + + n_native = traj.shape[0] + duration_native = n_native * native_dt + duration_play = duration_native / speed + n_out = max(2, int(round(duration_play * STREAMING_HZ))) + + t_native = np.arange(n_native) * native_dt + t_play = np.arange(n_out) / STREAMING_HZ + t_query = np.minimum(t_play * speed, t_native[-1]) + + out = np.empty((n_out, CMD_DIM)) + for j in range(CMD_DIM): + out[:, j] = np.interp(t_query, t_native, traj[:, j]) + + # Map the native pause frame to a streamed-frame index via its time on the + # native clock. t_query is non-decreasing, so searchsorted finds the first + # streamed frame that reaches native frame PAUSE_AFTER_FRAME. + pause_idx = None + if PAUSE_AFTER_FRAME is not None and PAUSE_AFTER_FRAME < n_native: + t_pause = PAUSE_AFTER_FRAME * native_dt + pause_idx = min(int(np.searchsorted(t_query, t_pause)), n_out - 1) + + print(f"Loaded {n_native} native frames (dt={native_dt}s, {duration_native:.2f}s @ {1.0/native_dt:.0f} Hz).") + print(f"Resampled to {n_out} frames at {STREAMING_HZ} Hz, speed {speed}x " + f"(playback duration {n_out / STREAMING_HZ:.2f}s).") + if pause_idx is not None: + print(f"Will pause after native frame {PAUSE_AFTER_FRAME} (streamed frame {pause_idx + 1}/{n_out}).") + return out, pause_idx + + +def main(): + args = parse_args() + if args.speed <= 0: + raise ValueError("--speed must be positive") + + commands, pause_idx = load_and_resample(args.npz, args.speed) + + use_arm = args.target in ('arm', 'both') + use_hand = args.target in ('hand', 'both') + print(f"Side: {args.side} Target: {args.target} (arm={use_arm}, hand={use_hand})") + + if args.dry_run: + print("--dry-run: trajectory loaded + resampled OK, no hardware connection. Exiting.") + return + + cfg = load_config(args.config) + ctrl = Controller(side=args.side, cfg=cfg, dt=DT, use_arm=use_arm, use_hand=use_hand) + try: + if use_arm: + print("Homing arm via moveJ...") + ctrl.rtde_c.moveJ(ctrl.home_arm_q, MOVE_SPEED, MOVE_ACCEL) + if use_hand: + print("Homing hand to zeros...") + err = ctrl.hand.set_joint_position([0.0] * HAND_DIM, True) + if err.code != 0: + print(f"hand set_joint_position error: {err.message}") + time.sleep(HOME_SETTLE_S) + + first = commands[0] + if use_arm: + print("Moving arm to trajectory start via moveJ...") + ctrl.rtde_c.moveJ(first[:ARM_DIM].tolist(), MOVE_SPEED, MOVE_ACCEL) + if use_hand: + print("Moving hand to trajectory start...") + err = ctrl.hand.set_joint_position(first[ARM_DIM:].tolist(), True) + if err.code != 0: + print(f"hand set_joint_position error: {err.message}") + time.sleep(START_SETTLE_S) + + input(f"\nReady. Press Enter to execute {commands.shape[0]} frames at " + f"{STREAMING_HZ} Hz ({args.speed}x, ~{commands.shape[0]/STREAMING_HZ:.2f}s, " + f"side={args.side}, target={args.target})... ") + + print("Streaming...") + timer = FrequencyTimer(STREAMING_HZ) + n_frames = len(commands) + for i, cmd in enumerate(commands): + timer.start_loop() + ctrl.execute(cmd.tolist()) + timer.end_loop() + if i == pause_idx and i < n_frames - 1: + input(f"\nPaused at native frame {PAUSE_AFTER_FRAME} " + f"(streamed frame {i + 1}/{n_frames}). Robot holding position. " + f"Press Enter to resume... ") + + print("Done streaming.") + finally: + ctrl.close(reset_hand=False) + + +if __name__ == "__main__": + main() diff --git a/third-party/do-as-i-do/reconstruction/.gitignore b/third-party/do-as-i-do/reconstruction/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..02006b1f130a6550529a8aee1f8992a7fdad7cbf --- /dev/null +++ b/third-party/do-as-i-do/reconstruction/.gitignore @@ -0,0 +1,21 @@ +# Model weights / checkpoints — fetched by setup/02_fetch_weights.sh, never committed +weights/ + +# Weights that live inside the submoduled repos (symlinked/downloaded at setup). +modules/*/checkpoints/ +modules/HaWoR/weights/ +modules/HaWoR/thirdparty/*/weights/ +modules/HaWoR/_DATA/ + +# Python +**/__pycache__/ +*.py[cod] +*.egg-info/ +.ipynb_checkpoints/ + +# Vendored sam3 package: drop generated outputs +modules/sam3/output/ + +# OS / editor +.DS_Store +*.swp diff --git a/third-party/do-as-i-do/reconstruction/README.md b/third-party/do-as-i-do/reconstruction/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c5ade45070d4ad826030c7aa51b4999a63494770 --- /dev/null +++ b/third-party/do-as-i-do/reconstruction/README.md @@ -0,0 +1,129 @@ +# Do as I Do · Reconstruction + +Hand and object **reconstruction + 6-DoF pose tracking** from a single hand-object demo video. Given a +video, a reference frame, an object name, and the anchor hand, the pipeline segments the object +and hand, reconstructs a 3D mesh for the object, estimates per-frame object pose, and reconstructs the hand (HaWoR). + +## Layout + +``` +reconstruction/ +├── run_pipeline.sh # the driver +├── config/paths.sh # ← the ONLY file you edit to relocate things +├── scripts/ # 7 standalone first-party stage scripts +├── modules/ # submodules with our changes +├── weights/ # model weights +├── env/ # conda env docs (see env/README.md) +└── setup/ # 00 submodules · 01 envs · 02 weights +``` + +## Requirements +- An NVIDIA GPU with ≥ 32 GB VRAM. +- HuggingFace auth with access to the repos `facebook/sam-3d-objects` and `facebook/sam3`; Plus a MANO download + (https://mano.is.tue.mpg.de) for HaWoR. +- SAM 3 segmentation is implemented with a click-based GUI needing an X display + (`config/paths.sh` sets `SAM3_DISPLAY=:1`; on a headless host, use forwarding or try text based prompting). + +## Setup (one time) + +```bash +GIT_LFS_SKIP_SMUDGE=1 git clone --recurse-submodules https://github.com/malik-group/do-as-i-do.git +cd do-as-i-do/reconstruction +./setup/00_init_submodules.sh # only needed if you didn't clone with recursive submodules +./setup/01_create_envs.sh # FALLBACK build of all 4 envs (sam3, sam3d, hawor, tapnet) — prefer each fork's own setup, see "Setting up the conda envs" below +./setup/02_fetch_weights.sh --download # fetch weights (needs hf auth) +``` +**Setting up the conda envs.** The recommended route is to build each env by following +its fork's own setup instructions (the repos vendored under `modules/`): + +- `sam3` → [malik-group/sam3](https://github.com/malik-group/sam3) (`modules/sam3`) +- `sam3d` → [malik-group/sam-3d-objects](https://github.com/malik-group/sam-3d-objects) (`modules/sam-3d-objects`, see its `doc/setup.md`) +- `hawor` → [malik-group/HaWoR](https://github.com/malik-group/HaWoR) (`modules/HaWoR`) +- `tapnet` → [malik-group/tapnet](https://github.com/malik-group/tapnet) (`modules/tapnet`) + +See [`env/README.md`](env/README.md) for the per-env cu128 recipes (or `./setup/01_create_envs.sh` to script them). + +After the `sam3d` env is built, two manual Stage-2 steps are needed: un-shadow the repo's +`notebook/` package (`pip uninstall -y notebook`) and build the Mip-Splatting +`diff_gaussian_rasterization` for the renderer's `inria` backend. Commands in +[`env/README.md`](env/README.md). + +Review `config/paths.sh`. + + +## Run + +```bash +./run_pipeline.sh VIDEO_PATH [FRAME_N] [OBJECT] [ANCHOR_HAND] +# e.g. +./run_pipeline.sh whisking/whisking.mp4 125 whisk right +``` + +### Details on Pipeline Stages +| # | stage | script | env | +|---|---|---|---| +| 0 | extract frames | ffmpeg | sam3 | +| 1 | SAM3 segmentation (object click + hand text) | `scripts/run_sam3_video.py` | sam3 | +| 2 | masks → 3D mesh | `modules/sam-3d-objects/generate_mesh_sam3d.py` | sam3d | +| 2 | MoGe pointmaps (reference frame + all frames) | `scripts/get_pointmap_dir.py` | sam3d | +| 2 | hand reconstruction | `modules/HaWoR/demo.py` | hawor | +| 2 | gravity estimation (GeoCalib) | `scripts/predict_video_gravity.py` | sam3d | +| 2.5 | velocity tracking | `scripts/tapir_velocity_tracking.py` | tapnet | +| 3 | guided pose prediction | `modules/Fast-SAM3D/track_object.py` | sam3d | +| 3 | project mesh / to camera frame | `scripts/run_project_mesh_combined.py`, `scripts/convert_layout_to_camera_frame.py` | sam3d | +| 4 | optimize translation/scale | `scripts/optimize_translation_scale.py` | sam3d | +| 4 | (optional) 3D viser viz | `scripts/visualize_3d.py` | sam3d | + + +### Outputs (under the video's directory) +`video_segmentation/masks/…`, per-object `.obj` meshes, `*_pointmap.npy` / `*_intrinsics.txt`, +HaWoR `all_hand_meshes.npz`, `gravity.json` (camera-frame up direction from GeoCalib), +and `obj_tracking_out//combined_visualization/` +with `layout.json → layout_camera_frame.json → layout_camera_frame_optimized.json` and projected +frames. This directory is the input to the [`retargeting/`](../retargeting/README.md) pipeline. + + +### Visualize the processed output yourself + +To explore the processed `whisk` demo (`whisking/`) in an interactive 3D (viser) viewer +without re-running the pipeline, first extract the video frames. Use the **same** ffmpeg +invocation as the pipeline's Step 0 so the frame numbering matches the tracking output: + +```bash +# from the reconstruction/ directory — same flags as run_pipeline.sh Step 0 +VIDEO_DIR=whisking +mkdir -p "$VIDEO_DIR/all_frames" +ffmpeg -i "$VIDEO_DIR/whisking.mp4" -vsync 0 -start_number 0 "$VIDEO_DIR/all_frames/%06d.png" +``` + +Then launch the viewer: + +```bash +conda activate sam3d +VIDEO_DIR=whisking +OBJECT_ID=whisk +LAYOUT_JSON_OPT="$VIDEO_DIR/obj_tracking_out/$OBJECT_ID/combined_visualization/layout_camera_frame_optimized.json" +python scripts/visualize_3d.py \ + --frames-dir "$VIDEO_DIR/all_frames" \ + --layout-json "$LAYOUT_JSON_OPT" \ + --mesh "$VIDEO_DIR/video_segmentation/masks/frame_000125_masks/$OBJECT_ID/$OBJECT_ID.obj" \ + --hand-meshes "$VIDEO_DIR/whisking/all_hand_meshes.npz" \ + --scale 0.1808 \ + --translation-scale 1.0 \ + --hands both \ + --port 8080 +``` + + +## Credits & licenses +The `modules/` contain external references with our changes to the sources, and each of them retain their upstream `LICENSE`. We gratefully +acknowledge the original authors. + +| fork | upstream @ pinned commit | fork commit | license | +|---|---|---|---| +| `malik-group/sam-3d-objects` | facebookresearch/sam-3d-objects @ `81a8237` | `875b010` | SAM License (Meta) | +| `malik-group/Fast-SAM3D` | wlfeng0509/Fast-SAM3D @ `c0f99e8` | `823d478` | MIT (+ embedded SAM-3D under SAM License) | +| `malik-group/HaWoR` | ThunderVVV/HaWoR @ `de90272` | `2c3fa0c` | CC BY-NC-ND 4.0 | +| `malik-group/tapnet` | google-deepmind/tapnet @ `96d3f84` | `f2f8888` | Apache-2.0 | +| `malik-group/sam3` | facebookresearch/sam3 @ `757bbb0` | `b8e18f5` | SAM License (Meta) | + diff --git a/third-party/do-as-i-do/reconstruction/config/paths.sh b/third-party/do-as-i-do/reconstruction/config/paths.sh new file mode 100644 index 0000000000000000000000000000000000000000..6b29dc94d6701048ca9fcd250ac469931e99530e --- /dev/null +++ b/third-party/do-as-i-do/reconstruction/config/paths.sh @@ -0,0 +1,36 @@ +# ───────────────────────── reconstruction pipeline paths ───────────────────────── +# Sourced by run_pipeline.sh; the Python scripts read these via os.environ + +# Root of this extracted project +RECON_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +export RECON_ROOT + +# ── Modules ── +export SAM3D_DIR="$RECON_ROOT/modules/sam-3d-objects" +export FASTSAM3D_DIR="$RECON_ROOT/modules/Fast-SAM3D" +export HAWOR_DIR="$RECON_ROOT/modules/HaWoR" +export TAPNET_DIR="$RECON_ROOT/modules/tapnet" +export SAM3_PKG_DIR="$RECON_ROOT/modules/sam3" + +export SCRIPTS_DIR="$RECON_ROOT/scripts" + +# ── Which repo root the MoGe pointmap script imports from ── +export SAM3D_REPO_ROOT="$FASTSAM3D_DIR" + +# ── Weights (populated by setup/02_fetch_weights.sh) ── +export WEIGHTS_DIR="$RECON_ROOT/weights" +export TAPNET_CKPT="$WEIGHTS_DIR/tapnet/bootstapir_checkpoint_v2.pt" + +# ── Conda env names (4 separate environments) ── +# Defaults match what `setup/01_create_envs.sh` creates. If you are reusing the +# pre-existing local envs, your sam3d env may be named differently +# (sam3 / hawor / tapnet already match) — set ENV_SAM3D accordingly. +export ENV_SAM3=sam3 +export ENV_SAM3D=sam3d +export ENV_HAWOR=hawor +export ENV_TAPNET=tapnet + +# ── Host / GPU ── +export CUDA_VISIBLE_DEVICES=0 +# X display used by the click-based SAM3 segmentation UI (Stage 1). +export SAM3_DISPLAY=:1 diff --git a/third-party/do-as-i-do/reconstruction/env/README.md b/third-party/do-as-i-do/reconstruction/env/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a0d9e952a7a434898f0c2f09a6194d9b65484330 --- /dev/null +++ b/third-party/do-as-i-do/reconstruction/env/README.md @@ -0,0 +1,54 @@ +# Conda environments + +The pipeline switches between **4 conda envs** (names set in `config/paths.sh`). + +**Recommended:** build each env by following its fork's own setup instructions — +[`malik-group/sam3`](https://github.com/malik-group/sam3) (`sam3`), +[`malik-group/sam-3d-objects`](https://github.com/malik-group/sam-3d-objects) (`sam3d`), +[`malik-group/HaWoR`](https://github.com/malik-group/HaWoR) (`hawor`), +[`malik-group/tapnet`](https://github.com/malik-group/tapnet) (`tapnet`). + +The two options below are **fallbacks** (e.g. on Blackwell / RTX 50xx, where the forks' cu117/cu121 pins won't run): + +- **Build fresh** — `./setup/01_create_envs.sh` (or one at a time: `./setup/01_create_envs.sh sam3|sam3d|hawor|tapnet`). Builds each env from the upstream repos' own dependency files + the recipes in the script. +- **From the exact pins here** — the `env/*.yml` files are full `conda env export`s of known-working envs, to be treated mainly as a version reference for manual installation. + +After the `sam3d` env is set up — whether via your own steps or the commands above — +run this once to un-shadow the repo's `notebook/` package: +```bash +pip uninstall -y notebook # ensure `notebook.inference` imports cleanly +``` + +The `sam3d` env also needs GeoCalib for the gravity-estimation step +(`scripts/predict_video_gravity.py`; installed automatically by `01_create_envs.sh`): +```bash +pip install "geocalib @ git+https://github.com/cvg/GeoCalib.git" +``` +Note: `env/sam3d.yml` predates this addition — if installing from the exact pins, add geocalib on top. + +If SAM 3D inference crashes during GLB/texture baking with `NameError: name 'GaussianRasterizationSettings' is not defined` try below: + +```bash +conda activate sam3d +git clone --recursive https://github.com/autonomousvision/mip-splatting.git +cd mip-splatting/submodules/diff-gaussian-rasterization +CUDA_HOME=$CONDA_PREFIX TORCH_CUDA_ARCH_LIST=12.0 FORCE_CUDA=1 python setup.py install +``` + +If building HaWoR's DROID-SLAM / lietorch fails to compile with +`error: cannot convert 'const at::DeprecatedTypeProperties' to 'c10::ScalarType'` in lietorch's `dispatch.h`, +edit `modules/HaWoR/thirdparty/DROID-SLAM/thirdparty/lietorch/lietorch/include/dispatch.h` and rebuild +(`cd modules/HaWoR/thirdparty/DROID-SLAM && python setup.py install`): +```diff +- at::ScalarType _st = ::detail::scalar_type(the_type); ++ at::ScalarType _st = the_type.scalarType(); +``` + +| env (default name) | exact-pin YAML | stages | deps from | +|---|---|---|---| +| `sam3` | `env/sam3.yml` | 1 — SAM3 segmentation | `env/sam3.yml` (or refer to original repository) | +| `sam3d` | `env/sam3d.yml` | 2, 3, 4 — meshes, pose, opt | `modules/sam-3d-objects/environments/default.yml` + `requirements*.txt` | +| `hawor` | `env/hawor.yml` | 2 — hand reconstruction | `modules/HaWoR/requirements.txt` (+ torch cu117) | +| `tapnet` | `env/tapnet.yml` | 2.5 — velocity tracking | `modules/tapnet[torch]` (Python 3.10, torch 2.7 cu128) | + + diff --git a/third-party/do-as-i-do/reconstruction/env/hawor.yml b/third-party/do-as-i-do/reconstruction/env/hawor.yml new file mode 100644 index 0000000000000000000000000000000000000000..c3ee174f5293de49d5159b88015460c168223d3e --- /dev/null +++ b/third-party/do-as-i-do/reconstruction/env/hawor.yml @@ -0,0 +1,294 @@ +name: hawor +channels: + - defaults + - nvidia/label/cuda-12.8.1 +dependencies: + - _libgcc_mutex=0.1=main + - _openmp_mutex=5.1=1_gnu + - binutils_impl_linux-64=2.44=h78f17ca_3 + - binutils_linux-64=2.44=hc03a8fd_3 + - bzip2=1.0.8=h5eee18b_6 + - ca-certificates=2026.3.19=h06a4308_0 + - cuda-cccl_linux-64=12.8.90=0 + - cuda-command-line-tools=12.8.1=0 + - cuda-compiler=12.8.1=0 + - cuda-crt-dev_linux-64=12.8.93=h06a4308_3 + - cuda-crt-tools=12.8.93=h06a4308_3 + - cuda-cudart=12.8.90=0 + - cuda-cudart-dev=12.8.90=0 + - cuda-cudart-dev_linux-64=12.8.90=0 + - cuda-cudart-static=12.8.90=0 + - cuda-cudart-static_linux-64=12.8.90=0 + - cuda-cudart_linux-64=12.8.90=0 + - cuda-cuobjdump=12.8.90=0 + - cuda-cupti=12.8.90=0 + - cuda-cupti-dev=12.8.90=0 + - cuda-cuxxfilt=12.8.90=0 + - cuda-driver-dev=12.8.90=0 + - cuda-driver-dev_linux-64=12.8.90=0 + - cuda-gdb=12.8.90=0 + - cuda-libraries=12.8.1=0 + - cuda-libraries-dev=12.8.1=0 + - cuda-nsight=12.8.90=0 + - cuda-nvcc=12.8.93=0 + - cuda-nvcc-dev_linux-64=12.8.93=he2511ca_3 + - cuda-nvcc-impl=12.8.93=hd1a145a_3 + - cuda-nvcc-tools=12.8.93=hbdd6827_3 + - cuda-nvcc_linux-64=12.8.93=0 + - cuda-nvdisasm=12.8.90=0 + - cuda-nvml-dev=12.8.90=0 + - cuda-nvprof=12.8.90=0 + - cuda-nvprune=12.8.90=0 + - cuda-nvrtc=12.8.93=0 + - cuda-nvrtc-dev=12.8.93=0 + - cuda-nvtx=12.8.90=0 + - cuda-nvvm-dev_linux-64=12.8.93=h06a4308_3 + - cuda-nvvm-impl=12.8.93=hbdd6827_3 + - cuda-nvvm-tools=12.8.93=hbdd6827_3 + - cuda-nvvp=12.8.93=0 + - cuda-opencl=12.8.90=0 + - cuda-opencl-dev=12.8.90=0 + - cuda-profiler-api=12.8.90=0 + - cuda-sanitizer-api=12.8.93=0 + - cuda-toolkit=12.8.1=0 + - cuda-tools=12.8.1=0 + - cuda-version=12.8=3 + - cuda-visual-tools=12.8.1=0 + - dbus=1.16.2=h5bd4931_0 + - expat=2.7.5=h7354ed3_0 + - fontconfig=2.15.0=h2c49b7f_0 + - freetype=2.14.1=hf5b9546_0 + - gcc_impl_linux-64=14.3.0=h4943218_4 + - gcc_linux-64=14.3.0=hda73cce_13 + - gds-tools=1.13.1.3=0 + - gmp=6.3.0=h6a678d5_0 + - gxx_impl_linux-64=14.3.0=he634eba_4 + - gxx_linux-64=14.3.0=hca8765c_13 + - icu=73.1=h6a678d5_0 + - kernel-headers_linux-64=4.18.0=h3108a97_1 + - ld_impl_linux-64=2.44=h9e0c5a2_3 + - libcublas=12.8.4.1=0 + - libcublas-dev=12.8.4.1=0 + - libcufft=11.3.3.83=0 + - libcufft-dev=11.3.3.83=0 + - libcufile=1.13.1.3=0 + - libcufile-dev=1.13.1.3=0 + - libcurand=10.3.9.90=0 + - libcurand-dev=10.3.9.90=0 + - libcusolver=11.7.3.90=0 + - libcusolver-dev=11.7.3.90=0 + - libcusparse=12.5.8.93=0 + - libcusparse-dev=12.5.8.93=0 + - libexpat=2.7.5=h7354ed3_0 + - libffi=3.4.4=h6a678d5_1 + - libgcc=15.2.0=h69a1729_7 + - libgcc-devel_linux-64=14.3.0=he7458c1_104 + - libgcc-ng=15.2.0=h166f726_7 + - libglib=2.86.3=h8b17d9a_0 + - libgomp=15.2.0=h4751f2c_7 + - libiconv=1.18=h75a1612_0 + - libnpp=12.3.3.100=0 + - libnpp-dev=12.3.3.100=0 + - libnsl=2.0.0=h5eee18b_0 + - libnvfatbin=12.8.90=0 + - libnvfatbin-dev=12.8.90=0 + - libnvjitlink=12.8.93=1 + - libnvjitlink-dev=12.8.93=1 + - libnvjpeg=12.3.5.92=0 + - libnvjpeg-dev=12.3.5.92=0 + - libpng=1.6.56=h22898a0_0 + - libsanitizer=14.3.0=hd4faa28_4 + - libstdcxx=15.2.0=h39759b7_7 + - libstdcxx-devel_linux-64=14.3.0=he7458c1_104 + - libstdcxx-ng=15.2.0=hc03a8fd_7 + - libuuid=1.41.5=h5eee18b_0 + - libxcb=1.17.0=h9b100fa_0 + - libxkbcommon=1.9.1=h69220b7_0 + - libxml2=2.13.9=h2c43086_0 + - libzlib=1.3.1=hb25bd0a_0 + - ncurses=6.5=h7934f7d_0 + - nsight-compute=2025.1.1.2=0 + - nspr=4.37=h8459abe_0 + - nss=3.121=h5c1ed2d_0 + - ocl-icd=2.3.3=h47b2149_0 + - opencl-headers=2025.07.22=hfb20e49_0 + - openssl=3.5.6=h1b28b03_0 + - packaging=26.0=py310h06a4308_0 + - pcre2=10.46=hf426167_0 + - pip=26.0.1=pyhc872135_1 + - pthread-stubs=0.3=h0ce48e5_1 + - python=3.10.20=h741d88c_0 + - readline=8.3=hc2a1206_0 + - sqlite=3.51.2=h3e8d24a_0 + - sysroot_linux-64=2.28=h3108a97_1 + - tk=8.6.15=h54e0aa7_0 + - wheel=0.46.3=py310h06a4308_0 + - xkeyboard-config=2.44=h382ed1a_1 + - xorg-libx11=1.8.12=h9b100fa_1 + - xorg-libxau=1.0.12=h9b100fa_0 + - xorg-libxdmcp=1.1.5=h9b100fa_0 + - xorg-xorgproto=2024.1=h5eee18b_1 + - xz=5.8.2=h448239c_0 + - zlib=1.3.1=hb25bd0a_0 + - pip: + - --extra-index-url https://download.pytorch.org/whl/cu128 + - addict==2.4.0 + - aitviewer==1.13.0 + - annotated-doc==0.0.4 + - antlr4-python3-runtime==4.9.3 + - anyio==4.13.0 + - argcomplete==3.6.3 + - blinker==1.9.0 + - braceexpand==0.1.7 + - certifi==2026.2.25 + - charset-normalizer==3.4.7 + - chumpy==0.71 + - click==8.3.2 + - cloudpickle==3.1.2 + - colorama==0.4.6 + - colorlog==6.10.1 + - contourpy==1.3.2 + - cycler==0.12.1 + - cython==3.2.4 + - defusedxml==0.7.1 + - dill==0.4.1 + - dominate==2.9.1 + - droid-backends==0.0.0 + - easydict==1.13 + - einops==0.8.2 + - evo==1.35.2 + - exceptiongroup==1.3.1 + - filelock==3.25.2 + - flask==3.1.3 + - fonttools==4.62.1 + - freetype-py==2.5.1 + - fsspec==2026.2.0 + - fvcore==0.1.5.post20221221 + - glcontext==3.0.0 + - h11==0.16.0 + - hf-xet==1.4.3 + - html4vision==0.6.1 + - httpcore==1.0.9 + - httpx==0.28.1 + - huggingface-hub==1.10.1 + - hydra-colorlog==1.2.0 + - hydra-core==1.3.2 + - hydra-submitit-launcher==1.2.0 + - idna==3.11 + - imageio==2.37.3 + - imgui==2.0.0 + - iopath==0.1.10 + - itsdangerous==2.2.0 + - jinja2==3.1.6 + - joblib==1.5.3 + - kiwisolver==1.5.0 + - lapx==0.9.4 + - lazy-loader==0.5 + - lietorch==0.2 + - lightning-utilities==0.15.3 + - loguru==0.7.3 + - lz4==4.4.5 + - markdown-it-py==4.0.0 + - markupsafe==3.0.3 + - matplotlib==3.10.8 + - mdurl==0.1.2 + - mmengine==0.10.4 + - moderngl==5.12.0 + - moderngl-window==2.4.6 + - mpmath==1.3.0 + - multipledispatch==1.0.0 + - natsort==8.4.0 + - networkx==3.4.2 + - ninja==1.13.0 + - numexpr==2.14.1 + - numpy==1.26.4 + - nvidia-cublas-cu12==12.8.4.1 + - nvidia-cuda-cupti-cu12==12.8.90 + - nvidia-cuda-nvrtc-cu12==12.8.93 + - nvidia-cuda-runtime-cu12==12.8.90 + - nvidia-cudnn-cu12==9.10.2.21 + - nvidia-cufft-cu12==11.3.3.83 + - nvidia-cufile-cu12==1.13.1.3 + - nvidia-curand-cu12==10.3.9.90 + - nvidia-cusolver-cu12==11.7.3.90 + - nvidia-cusparse-cu12==12.5.8.93 + - nvidia-cusparselt-cu12==0.7.1 + - nvidia-nccl-cu12==2.27.5 + - nvidia-nvjitlink-cu12==12.8.93 + - nvidia-nvshmem-cu12==3.3.20 + - nvidia-nvtx-cu12==12.8.90 + - omegaconf==2.3.0 + - opencv-contrib-python-headless==4.11.0.86 + - opencv-python==4.11.0.86 + - pandas==2.3.3 + - pillow==12.1.1 + - platformdirs==4.9.6 + - plyfile==1.1.3 + - polars==1.39.3 + - polars-runtime-32==1.39.3 + - portalocker==3.2.0 + - pretty-errors==1.2.25 + - psutil==7.2.2 + - pulp==3.3.0 + - pycocotools==2.0.11 + - pydeprecate==0.5.0 + - pyglet==2.1.14 + - pygments==2.20.0 + - pyopengl==3.1.0 + - pyparsing==3.3.2 + - pyqt5==5.15.11 + - pyqt5-qt5==5.15.18 + - pyqt5-sip==12.18.0 + - pyrender==0.1.45 + - pyrootutils==1.0.4 + - pyrr==0.10.3 + - python-dateutil==2.9.0.post0 + - python-dotenv==1.2.2 + - pytorch-lightning==2.2.4 + - pytorch-minimize==0.1.0 + - pytorch3d==0.7.8 + - pytz==2026.1.post1 + - pyyaml==6.0.3 + - requests==2.33.1 + - rich==14.3.3 + - roma==1.5.6 + - rosbags==0.11.0 + - ruamel-yaml==0.19.1 + - safetensors==0.7.0 + - scikit-image==0.25.2 + - scikit-video==1.1.11 + - scipy==1.15.3 + - seaborn==0.13.2 + - setuptools==80.10.2 + - shellingham==1.5.4 + - six==1.17.0 + - smplx==0.1.28 + - submitit==1.5.4 + - supervision==0.27.0.post2 + - sympy==1.14.0 + - tabulate==0.10.0 + - termcolor==3.3.0 + - tifffile==2025.5.10 + - timm==1.0.26 + - tomli==2.4.1 + - torch==2.9.0+cu128 + - torch-scatter==2.1.2 + - torchmetrics==1.4.0 + - torchvision==0.24.0+cu128 + - tqdm==4.67.3 + - trimesh==3.23.5 + - triton==3.5.0 + - typer==0.24.1 + - typing-extensions==4.15.0 + - tzdata==2026.1 + - ultralytics==8.4.36 + - ultralytics-thop==2.0.18 + - urllib3==2.6.3 + - usd-core==26.3 + - webdataset==1.0.2 + - websockets==16.0 + - werkzeug==3.1.8 + - xtcocotools==1.14.3 + - yacs==0.1.8 + - yapf==0.43.0 + - zstandard==0.25.0