Upload v2d project (excluding data and .venv) (part 7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- reconstruction/modules/InterFormer/mmseg.yaml +257 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/uper_head.cpython-38.pyc +0 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-310.pyc +0 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-38.pyc +0 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/ann_head.py +245 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/apc_head.py +159 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/aspp_head.py +122 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/cascade_decode_head.py +62 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/cc_head.py +43 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/da_head.py +184 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/ddr_head.py +116 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/decode_head.py +366 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/dm_head.py +141 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/dnl_head.py +137 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/dpt_head.py +294 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/ema_head.py +169 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/enc_head.py +196 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/fcn_head.py +96 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/fpn_head.py +68 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/gc_head.py +48 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/ham_head.py +255 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/interformer_decoder.py +921 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/isa_head.py +143 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/knet_head.py +461 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/lraspp_head.py +91 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/mask2former_head.py +163 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/maskformer_head.py +174 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/nl_head.py +50 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/ocr_head.py +127 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/pid_head.py +183 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/point_head.py +367 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/psa_head.py +197 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/psp_head.py +117 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/san_head.py +736 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/segformer_head.py +66 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/segmenter_mask_head.py +132 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_aspp_head.py +102 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_fcn_head.py +60 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_mla_head.py +62 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_up_head.py +81 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/stdc_head.py +97 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/uper_head.py +139 -0
- reconstruction/modules/InterFormer/mmseg/models/decode_heads/vpd_depth_head.py +253 -0
- reconstruction/modules/InterFormer/mmseg/models/losses/__init__.py +21 -0
- reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-310.pyc +0 -0
- reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-38.pyc +0 -0
- reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-310.pyc +0 -0
- reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-38.pyc +0 -0
- reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -62,3 +62,5 @@ checkpoints/hawor/hawor/checkpoints/hawor.ckpt.1 filter=lfs diff=lfs merge=lfs -
|
|
| 62 |
checkpoints/hawor/hawor/checkpoints/infiller.pt.1 filter=lfs diff=lfs merge=lfs -text
|
| 63 |
reconstruction/modules/HaWoR/thirdparty/Metric3D/media/screenshots/challenge.PNG filter=lfs diff=lfs merge=lfs -text
|
| 64 |
reconstruction/modules/HaWoR/thirdparty/Metric3D/training/kitti_json_files/eigen_train.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 62 |
checkpoints/hawor/hawor/checkpoints/infiller.pt.1 filter=lfs diff=lfs merge=lfs -text
|
| 63 |
reconstruction/modules/HaWoR/thirdparty/Metric3D/media/screenshots/challenge.PNG filter=lfs diff=lfs merge=lfs -text
|
| 64 |
reconstruction/modules/HaWoR/thirdparty/Metric3D/training/kitti_json_files/eigen_train.json filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/human.ply filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3Dfy_results/0.glb filter=lfs diff=lfs merge=lfs -text
|
reconstruction/modules/InterFormer/mmseg.yaml
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: mmseg
|
| 2 |
+
channels:
|
| 3 |
+
- pytorch
|
| 4 |
+
- nvidia
|
| 5 |
+
- defaults
|
| 6 |
+
dependencies:
|
| 7 |
+
- _libgcc_mutex=0.1=main
|
| 8 |
+
- _openmp_mutex=5.1=1_gnu
|
| 9 |
+
- blas=1.0=mkl
|
| 10 |
+
- brotlipy=0.7.0=py310h7f8727e_1002
|
| 11 |
+
- bzip2=1.0.8=h7b6447c_0
|
| 12 |
+
- ca-certificates=2023.05.30=h06a4308_0
|
| 13 |
+
- certifi=2023.5.7=py310h06a4308_0
|
| 14 |
+
- cffi=1.15.1=py310h5eee18b_3
|
| 15 |
+
- charset-normalizer=2.0.4=pyhd3eb1b0_0
|
| 16 |
+
- cryptography=39.0.1=py310h9ce1e76_2
|
| 17 |
+
- cuda=11.6.1=0
|
| 18 |
+
- cuda-cccl=11.6.55=hf6102b2_0
|
| 19 |
+
- cuda-command-line-tools=11.6.2=0
|
| 20 |
+
- cuda-compiler=11.6.2=0
|
| 21 |
+
- cuda-cudart=11.6.55=he381448_0
|
| 22 |
+
- cuda-cudart-dev=11.6.55=h42ad0f4_0
|
| 23 |
+
- cuda-cuobjdump=11.6.124=h2eeebcb_0
|
| 24 |
+
- cuda-cupti=11.6.124=h86345e5_0
|
| 25 |
+
- cuda-cuxxfilt=11.6.124=hecbf4f6_0
|
| 26 |
+
- cuda-driver-dev=11.6.55=0
|
| 27 |
+
- cuda-gdb=12.1.105=0
|
| 28 |
+
- cuda-libraries=11.6.1=0
|
| 29 |
+
- cuda-libraries-dev=11.6.1=0
|
| 30 |
+
- cuda-memcheck=11.8.86=0
|
| 31 |
+
- cuda-nsight=12.1.105=0
|
| 32 |
+
- cuda-nsight-compute=12.1.1=0
|
| 33 |
+
- cuda-nvcc=11.6.124=hbba6d2d_0
|
| 34 |
+
- cuda-nvdisasm=12.1.105=0
|
| 35 |
+
- cuda-nvml-dev=11.6.55=haa9ef22_0
|
| 36 |
+
- cuda-nvprof=12.1.105=0
|
| 37 |
+
- cuda-nvprune=11.6.124=he22ec0a_0
|
| 38 |
+
- cuda-nvrtc=11.6.124=h020bade_0
|
| 39 |
+
- cuda-nvrtc-dev=11.6.124=h249d397_0
|
| 40 |
+
- cuda-nvtx=11.6.124=h0630a44_0
|
| 41 |
+
- cuda-nvvp=12.1.105=0
|
| 42 |
+
- cuda-runtime=11.6.1=0
|
| 43 |
+
- cuda-samples=11.6.101=h8efea70_0
|
| 44 |
+
- cuda-sanitizer-api=12.1.105=0
|
| 45 |
+
- cuda-toolkit=11.6.1=0
|
| 46 |
+
- cuda-tools=11.6.1=0
|
| 47 |
+
- cuda-visual-tools=11.6.1=0
|
| 48 |
+
- ffmpeg=4.2.2=h20bf706_0
|
| 49 |
+
- freetype=2.12.1=h4a9f257_0
|
| 50 |
+
- gds-tools=1.6.1.9=0
|
| 51 |
+
- giflib=5.2.1=h5eee18b_3
|
| 52 |
+
- gmp=6.2.1=h295c915_3
|
| 53 |
+
- gnutls=3.6.15=he1e5248_0
|
| 54 |
+
- idna=3.4=py310h06a4308_0
|
| 55 |
+
- intel-openmp=2023.1.0=hdb19cb5_46305
|
| 56 |
+
- jpeg=9e=h5eee18b_1
|
| 57 |
+
- lame=3.100=h7b6447c_0
|
| 58 |
+
- lcms2=2.12=h3be6417_0
|
| 59 |
+
- ld_impl_linux-64=2.38=h1181459_1
|
| 60 |
+
- lerc=3.0=h295c915_0
|
| 61 |
+
- libcublas=11.9.2.110=h5e84587_0
|
| 62 |
+
- libcublas-dev=11.9.2.110=h5c901ab_0
|
| 63 |
+
- libcufft=10.7.1.112=hf425ae0_0
|
| 64 |
+
- libcufft-dev=10.7.1.112=ha5ce4c0_0
|
| 65 |
+
- libcufile=1.6.1.9=0
|
| 66 |
+
- libcufile-dev=1.6.1.9=0
|
| 67 |
+
- libcurand=10.3.2.106=0
|
| 68 |
+
- libcurand-dev=10.3.2.106=0
|
| 69 |
+
- libcusolver=11.3.4.124=h33c3c4e_0
|
| 70 |
+
- libcusparse=11.7.2.124=h7538f96_0
|
| 71 |
+
- libcusparse-dev=11.7.2.124=hbbe9722_0
|
| 72 |
+
- libdeflate=1.17=h5eee18b_0
|
| 73 |
+
- libffi=3.4.4=h6a678d5_0
|
| 74 |
+
- libgcc-ng=11.2.0=h1234567_1
|
| 75 |
+
- libgomp=11.2.0=h1234567_1
|
| 76 |
+
- libidn2=2.3.4=h5eee18b_0
|
| 77 |
+
- libnpp=11.6.3.124=hd2722f0_0
|
| 78 |
+
- libnpp-dev=11.6.3.124=h3c42840_0
|
| 79 |
+
- libnvjpeg=11.6.2.124=hd473ad6_0
|
| 80 |
+
- libnvjpeg-dev=11.6.2.124=hb5906b9_0
|
| 81 |
+
- libopus=1.3.1=h7b6447c_0
|
| 82 |
+
- libpng=1.6.39=h5eee18b_0
|
| 83 |
+
- libstdcxx-ng=11.2.0=h1234567_1
|
| 84 |
+
- libtasn1=4.19.0=h5eee18b_0
|
| 85 |
+
- libtiff=4.5.0=h6a678d5_2
|
| 86 |
+
- libunistring=0.9.10=h27cfd23_0
|
| 87 |
+
- libuuid=1.41.5=h5eee18b_0
|
| 88 |
+
- libvpx=1.7.0=h439df22_0
|
| 89 |
+
- libwebp=1.2.4=h11a3e52_1
|
| 90 |
+
- libwebp-base=1.2.4=h5eee18b_1
|
| 91 |
+
- lz4-c=1.9.4=h6a678d5_0
|
| 92 |
+
- mkl=2023.1.0=h6d00ec8_46342
|
| 93 |
+
- mkl-service=2.4.0=py310h5eee18b_1
|
| 94 |
+
- mkl_fft=1.3.6=py310h1128e8f_1
|
| 95 |
+
- mkl_random=1.2.2=py310h1128e8f_1
|
| 96 |
+
- ncurses=6.4=h6a678d5_0
|
| 97 |
+
- nettle=3.7.3=hbbd107a_1
|
| 98 |
+
- nsight-compute=2023.1.1.4=0
|
| 99 |
+
- numpy=1.25.0=py310h5f9d8c6_0
|
| 100 |
+
- numpy-base=1.25.0=py310hb5e798b_0
|
| 101 |
+
- openh264=2.1.1=h4ff587b_0
|
| 102 |
+
- openssl=3.0.9=h7f8727e_0
|
| 103 |
+
- pillow=9.4.0=py310h6a678d5_0
|
| 104 |
+
- pip=23.1.2=py310h06a4308_0
|
| 105 |
+
- pycparser=2.21=pyhd3eb1b0_0
|
| 106 |
+
- pyopenssl=23.0.0=py310h06a4308_0
|
| 107 |
+
- pysocks=1.7.1=py310h06a4308_0
|
| 108 |
+
- python=3.10.11=h955ad1f_3
|
| 109 |
+
- pytorch=1.13.1=py3.10_cuda11.6_cudnn8.3.2_0
|
| 110 |
+
- pytorch-cuda=11.6=h867d48c_1
|
| 111 |
+
- pytorch-mutex=1.0=cuda
|
| 112 |
+
- readline=8.2=h5eee18b_0
|
| 113 |
+
- sqlite=3.41.2=h5eee18b_0
|
| 114 |
+
- tbb=2021.8.0=hdb19cb5_0
|
| 115 |
+
- tk=8.6.12=h1ccaba5_0
|
| 116 |
+
- torchaudio=0.13.1=py310_cu116
|
| 117 |
+
- torchvision=0.14.1=py310_cu116
|
| 118 |
+
- typing_extensions=4.6.3=py310h06a4308_0
|
| 119 |
+
- urllib3=1.26.16=py310h06a4308_0
|
| 120 |
+
- x264=1!157.20191217=h7b6447c_0
|
| 121 |
+
- xz=5.4.2=h5eee18b_0
|
| 122 |
+
- zlib=1.2.13=h5eee18b_0
|
| 123 |
+
- zstd=1.5.5=hc292b87_0
|
| 124 |
+
- pip:
|
| 125 |
+
- absl-py==2.1.0
|
| 126 |
+
- addict==2.4.0
|
| 127 |
+
- aiohappyeyeballs==2.6.1
|
| 128 |
+
- aiohttp==3.12.15
|
| 129 |
+
- aiosignal==1.4.0
|
| 130 |
+
- aliyun-python-sdk-core==2.15.1
|
| 131 |
+
- aliyun-python-sdk-kms==2.16.3
|
| 132 |
+
- asttokens==2.4.1
|
| 133 |
+
- async-timeout==5.0.1
|
| 134 |
+
- attrs==25.3.0
|
| 135 |
+
- basicsr==0.0.0
|
| 136 |
+
- beautifulsoup4==4.12.3
|
| 137 |
+
- cachetools==5.3.3
|
| 138 |
+
- click==8.1.7
|
| 139 |
+
- colorama==0.4.6
|
| 140 |
+
- contourpy==1.2.1
|
| 141 |
+
- crcmod==1.7
|
| 142 |
+
- cycler==0.12.1
|
| 143 |
+
- datasets==4.0.0
|
| 144 |
+
- decorator==5.1.1
|
| 145 |
+
- dill==0.3.8
|
| 146 |
+
- einops==0.8.0
|
| 147 |
+
- exceptiongroup==1.2.2
|
| 148 |
+
- executing==2.0.1
|
| 149 |
+
- filelock==3.14.0
|
| 150 |
+
- fonttools==4.51.0
|
| 151 |
+
- frozenlist==1.7.0
|
| 152 |
+
- fsspec==2024.5.0
|
| 153 |
+
- ftfy==6.2.0
|
| 154 |
+
- future==1.0.0
|
| 155 |
+
- fvcore==0.1.5.post20221221
|
| 156 |
+
- gdown==5.2.0
|
| 157 |
+
- google-auth==2.29.0
|
| 158 |
+
- google-auth-oauthlib==1.0.0
|
| 159 |
+
- grpcio==1.63.0
|
| 160 |
+
- h5py==3.11.0
|
| 161 |
+
- hf-xet==1.1.7
|
| 162 |
+
- huggingface-hub==0.34.4
|
| 163 |
+
- imageio==2.34.1
|
| 164 |
+
- importlib-metadata==7.1.0
|
| 165 |
+
- iopath==0.1.10
|
| 166 |
+
- ipdb==0.13.13
|
| 167 |
+
- ipython==8.26.0
|
| 168 |
+
- jedi==0.19.1
|
| 169 |
+
- jmespath==0.10.0
|
| 170 |
+
- kiwisolver==1.4.5
|
| 171 |
+
- lazy-loader==0.4
|
| 172 |
+
- lmdb==1.7.2
|
| 173 |
+
- markdown==3.6
|
| 174 |
+
- markdown-it-py==3.0.0
|
| 175 |
+
- markupsafe==2.1.5
|
| 176 |
+
- matplotlib==3.9.0
|
| 177 |
+
- matplotlib-inline==0.1.7
|
| 178 |
+
- mdurl==0.1.2
|
| 179 |
+
- mmcv==2.0.0
|
| 180 |
+
- mmdet==3.3.0
|
| 181 |
+
- mmengine==0.10.4
|
| 182 |
+
- mmsegmentation==1.2.2
|
| 183 |
+
- model-index==0.1.11
|
| 184 |
+
- modelscope==1.30.0
|
| 185 |
+
- multidict==6.6.4
|
| 186 |
+
- multiprocess==0.70.16
|
| 187 |
+
- networkx==3.3
|
| 188 |
+
- oauthlib==3.2.2
|
| 189 |
+
- omegaconf==2.4.0.dev3
|
| 190 |
+
- opencv-python==4.9.0.80
|
| 191 |
+
- opendatalab==0.0.10
|
| 192 |
+
- openmim==0.3.9
|
| 193 |
+
- openxlab==0.0.38
|
| 194 |
+
- ordered-set==4.1.0
|
| 195 |
+
- oss2==2.17.0
|
| 196 |
+
- packaging==24.0
|
| 197 |
+
- pandas==2.2.2
|
| 198 |
+
- parso==0.8.4
|
| 199 |
+
- pexpect==4.9.0
|
| 200 |
+
- platformdirs==4.2.2
|
| 201 |
+
- portalocker==3.2.0
|
| 202 |
+
- prettytable==3.10.0
|
| 203 |
+
- prompt-toolkit==3.0.47
|
| 204 |
+
- propcache==0.3.2
|
| 205 |
+
- protobuf==3.20.3
|
| 206 |
+
- psutil==6.0.0
|
| 207 |
+
- ptyprocess==0.7.0
|
| 208 |
+
- pure-eval==0.2.2
|
| 209 |
+
- pyarrow==21.0.0
|
| 210 |
+
- pyasn1==0.6.0
|
| 211 |
+
- pyasn1-modules==0.4.0
|
| 212 |
+
- pycocotools==2.0.7
|
| 213 |
+
- pycryptodome==3.20.0
|
| 214 |
+
- pygments==2.18.0
|
| 215 |
+
- pyparsing==3.1.2
|
| 216 |
+
- python-dateutil==2.9.0.post0
|
| 217 |
+
- pytz==2023.4
|
| 218 |
+
- pyyaml==6.0.1
|
| 219 |
+
- regex==2024.5.15
|
| 220 |
+
- requests==2.32.4
|
| 221 |
+
- requests-oauthlib==2.0.0
|
| 222 |
+
- rich==13.4.2
|
| 223 |
+
- rsa==4.9
|
| 224 |
+
- safetensors==0.4.3
|
| 225 |
+
- scikit-image==0.23.2
|
| 226 |
+
- scipy==1.13.0
|
| 227 |
+
- seaborn==0.13.2
|
| 228 |
+
- setuptools==60.2.0
|
| 229 |
+
- shapely==2.0.4
|
| 230 |
+
- six==1.16.0
|
| 231 |
+
- smmap==5.0.1
|
| 232 |
+
- soupsieve==2.6
|
| 233 |
+
- stack-data==0.6.3
|
| 234 |
+
- tabulate==0.9.0
|
| 235 |
+
- tb-nightly==2.21.0a20250719
|
| 236 |
+
- tensorboard==2.13.0
|
| 237 |
+
- tensorboard-data-server==0.7.0
|
| 238 |
+
- tensorboardx==2.6
|
| 239 |
+
- termcolor==2.3.0
|
| 240 |
+
- terminaltables==3.1.10
|
| 241 |
+
- thop==0.1.1-2209072238
|
| 242 |
+
- threadpoolctl==3.1.0
|
| 243 |
+
- tifffile==2024.5.10
|
| 244 |
+
- timm==1.0.3
|
| 245 |
+
- tomli==2.0.1
|
| 246 |
+
- tqdm==4.67.1
|
| 247 |
+
- traitlets==5.14.3
|
| 248 |
+
- tzdata==2024.1
|
| 249 |
+
- wcwidth==0.2.13
|
| 250 |
+
- werkzeug==3.0.3
|
| 251 |
+
- wheel==0.26.0
|
| 252 |
+
- xxhash==3.5.0
|
| 253 |
+
- yacs==0.1.8
|
| 254 |
+
- yapf==0.40.2
|
| 255 |
+
- yarl==1.20.1
|
| 256 |
+
- zipp==3.18.2
|
| 257 |
+
prefix: /home/suyuejiao/anaconda3/envs/mmseg
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/uper_head.cpython-38.pyc
ADDED
|
Binary file (3.71 kB). View file
|
|
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-310.pyc
ADDED
|
Binary file (7.73 kB). View file
|
|
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-38.pyc
ADDED
|
Binary file (7.68 kB). View file
|
|
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/ann_head.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
|
| 8 |
+
from .decode_head import BaseDecodeHead
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class PPMConcat(nn.ModuleList):
|
| 12 |
+
"""Pyramid Pooling Module that only concat the features of each layer.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 16 |
+
Module.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, pool_scales=(1, 3, 6, 8)):
|
| 20 |
+
super().__init__(
|
| 21 |
+
[nn.AdaptiveAvgPool2d(pool_scale) for pool_scale in pool_scales])
|
| 22 |
+
|
| 23 |
+
def forward(self, feats):
|
| 24 |
+
"""Forward function."""
|
| 25 |
+
ppm_outs = []
|
| 26 |
+
for ppm in self:
|
| 27 |
+
ppm_out = ppm(feats)
|
| 28 |
+
ppm_outs.append(ppm_out.view(*feats.shape[:2], -1))
|
| 29 |
+
concat_outs = torch.cat(ppm_outs, dim=2)
|
| 30 |
+
return concat_outs
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class SelfAttentionBlock(_SelfAttentionBlock):
|
| 34 |
+
"""Make a ANN used SelfAttentionBlock.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
low_in_channels (int): Input channels of lower level feature,
|
| 38 |
+
which is the key feature for self-attention.
|
| 39 |
+
high_in_channels (int): Input channels of higher level feature,
|
| 40 |
+
which is the query feature for self-attention.
|
| 41 |
+
channels (int): Output channels of key/query transform.
|
| 42 |
+
out_channels (int): Output channels.
|
| 43 |
+
share_key_query (bool): Whether share projection weight between key
|
| 44 |
+
and query projection.
|
| 45 |
+
query_scale (int): The scale of query feature map.
|
| 46 |
+
key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 47 |
+
Module of key feature.
|
| 48 |
+
conv_cfg (dict|None): Config of conv layers.
|
| 49 |
+
norm_cfg (dict|None): Config of norm layers.
|
| 50 |
+
act_cfg (dict|None): Config of activation layers.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, low_in_channels, high_in_channels, channels,
|
| 54 |
+
out_channels, share_key_query, query_scale, key_pool_scales,
|
| 55 |
+
conv_cfg, norm_cfg, act_cfg):
|
| 56 |
+
key_psp = PPMConcat(key_pool_scales)
|
| 57 |
+
if query_scale > 1:
|
| 58 |
+
query_downsample = nn.MaxPool2d(kernel_size=query_scale)
|
| 59 |
+
else:
|
| 60 |
+
query_downsample = None
|
| 61 |
+
super().__init__(
|
| 62 |
+
key_in_channels=low_in_channels,
|
| 63 |
+
query_in_channels=high_in_channels,
|
| 64 |
+
channels=channels,
|
| 65 |
+
out_channels=out_channels,
|
| 66 |
+
share_key_query=share_key_query,
|
| 67 |
+
query_downsample=query_downsample,
|
| 68 |
+
key_downsample=key_psp,
|
| 69 |
+
key_query_num_convs=1,
|
| 70 |
+
key_query_norm=True,
|
| 71 |
+
value_out_num_convs=1,
|
| 72 |
+
value_out_norm=False,
|
| 73 |
+
matmul_norm=True,
|
| 74 |
+
with_out=True,
|
| 75 |
+
conv_cfg=conv_cfg,
|
| 76 |
+
norm_cfg=norm_cfg,
|
| 77 |
+
act_cfg=act_cfg)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class AFNB(nn.Module):
|
| 81 |
+
"""Asymmetric Fusion Non-local Block(AFNB)
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
low_in_channels (int): Input channels of lower level feature,
|
| 85 |
+
which is the key feature for self-attention.
|
| 86 |
+
high_in_channels (int): Input channels of higher level feature,
|
| 87 |
+
which is the query feature for self-attention.
|
| 88 |
+
channels (int): Output channels of key/query transform.
|
| 89 |
+
out_channels (int): Output channels.
|
| 90 |
+
and query projection.
|
| 91 |
+
query_scales (tuple[int]): The scales of query feature map.
|
| 92 |
+
Default: (1,)
|
| 93 |
+
key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 94 |
+
Module of key feature.
|
| 95 |
+
conv_cfg (dict|None): Config of conv layers.
|
| 96 |
+
norm_cfg (dict|None): Config of norm layers.
|
| 97 |
+
act_cfg (dict|None): Config of activation layers.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def __init__(self, low_in_channels, high_in_channels, channels,
|
| 101 |
+
out_channels, query_scales, key_pool_scales, conv_cfg,
|
| 102 |
+
norm_cfg, act_cfg):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.stages = nn.ModuleList()
|
| 105 |
+
for query_scale in query_scales:
|
| 106 |
+
self.stages.append(
|
| 107 |
+
SelfAttentionBlock(
|
| 108 |
+
low_in_channels=low_in_channels,
|
| 109 |
+
high_in_channels=high_in_channels,
|
| 110 |
+
channels=channels,
|
| 111 |
+
out_channels=out_channels,
|
| 112 |
+
share_key_query=False,
|
| 113 |
+
query_scale=query_scale,
|
| 114 |
+
key_pool_scales=key_pool_scales,
|
| 115 |
+
conv_cfg=conv_cfg,
|
| 116 |
+
norm_cfg=norm_cfg,
|
| 117 |
+
act_cfg=act_cfg))
|
| 118 |
+
self.bottleneck = ConvModule(
|
| 119 |
+
out_channels + high_in_channels,
|
| 120 |
+
out_channels,
|
| 121 |
+
1,
|
| 122 |
+
conv_cfg=conv_cfg,
|
| 123 |
+
norm_cfg=norm_cfg,
|
| 124 |
+
act_cfg=None)
|
| 125 |
+
|
| 126 |
+
def forward(self, low_feats, high_feats):
|
| 127 |
+
"""Forward function."""
|
| 128 |
+
priors = [stage(high_feats, low_feats) for stage in self.stages]
|
| 129 |
+
context = torch.stack(priors, dim=0).sum(dim=0)
|
| 130 |
+
output = self.bottleneck(torch.cat([context, high_feats], 1))
|
| 131 |
+
return output
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class APNB(nn.Module):
|
| 135 |
+
"""Asymmetric Pyramid Non-local Block (APNB)
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
in_channels (int): Input channels of key/query feature,
|
| 139 |
+
which is the key feature for self-attention.
|
| 140 |
+
channels (int): Output channels of key/query transform.
|
| 141 |
+
out_channels (int): Output channels.
|
| 142 |
+
query_scales (tuple[int]): The scales of query feature map.
|
| 143 |
+
Default: (1,)
|
| 144 |
+
key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 145 |
+
Module of key feature.
|
| 146 |
+
conv_cfg (dict|None): Config of conv layers.
|
| 147 |
+
norm_cfg (dict|None): Config of norm layers.
|
| 148 |
+
act_cfg (dict|None): Config of activation layers.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
def __init__(self, in_channels, channels, out_channels, query_scales,
|
| 152 |
+
key_pool_scales, conv_cfg, norm_cfg, act_cfg):
|
| 153 |
+
super().__init__()
|
| 154 |
+
self.stages = nn.ModuleList()
|
| 155 |
+
for query_scale in query_scales:
|
| 156 |
+
self.stages.append(
|
| 157 |
+
SelfAttentionBlock(
|
| 158 |
+
low_in_channels=in_channels,
|
| 159 |
+
high_in_channels=in_channels,
|
| 160 |
+
channels=channels,
|
| 161 |
+
out_channels=out_channels,
|
| 162 |
+
share_key_query=True,
|
| 163 |
+
query_scale=query_scale,
|
| 164 |
+
key_pool_scales=key_pool_scales,
|
| 165 |
+
conv_cfg=conv_cfg,
|
| 166 |
+
norm_cfg=norm_cfg,
|
| 167 |
+
act_cfg=act_cfg))
|
| 168 |
+
self.bottleneck = ConvModule(
|
| 169 |
+
2 * in_channels,
|
| 170 |
+
out_channels,
|
| 171 |
+
1,
|
| 172 |
+
conv_cfg=conv_cfg,
|
| 173 |
+
norm_cfg=norm_cfg,
|
| 174 |
+
act_cfg=act_cfg)
|
| 175 |
+
|
| 176 |
+
def forward(self, feats):
|
| 177 |
+
"""Forward function."""
|
| 178 |
+
priors = [stage(feats, feats) for stage in self.stages]
|
| 179 |
+
context = torch.stack(priors, dim=0).sum(dim=0)
|
| 180 |
+
output = self.bottleneck(torch.cat([context, feats], 1))
|
| 181 |
+
return output
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@MODELS.register_module()
|
| 185 |
+
class ANNHead(BaseDecodeHead):
|
| 186 |
+
"""Asymmetric Non-local Neural Networks for Semantic Segmentation.
|
| 187 |
+
|
| 188 |
+
This head is the implementation of `ANNNet
|
| 189 |
+
<https://arxiv.org/abs/1908.07678>`_.
|
| 190 |
+
|
| 191 |
+
Args:
|
| 192 |
+
project_channels (int): Projection channels for Nonlocal.
|
| 193 |
+
query_scales (tuple[int]): The scales of query feature map.
|
| 194 |
+
Default: (1,)
|
| 195 |
+
key_pool_scales (tuple[int]): The pooling scales of key feature map.
|
| 196 |
+
Default: (1, 3, 6, 8).
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
def __init__(self,
|
| 200 |
+
project_channels,
|
| 201 |
+
query_scales=(1, ),
|
| 202 |
+
key_pool_scales=(1, 3, 6, 8),
|
| 203 |
+
**kwargs):
|
| 204 |
+
super().__init__(input_transform='multiple_select', **kwargs)
|
| 205 |
+
assert len(self.in_channels) == 2
|
| 206 |
+
low_in_channels, high_in_channels = self.in_channels
|
| 207 |
+
self.project_channels = project_channels
|
| 208 |
+
self.fusion = AFNB(
|
| 209 |
+
low_in_channels=low_in_channels,
|
| 210 |
+
high_in_channels=high_in_channels,
|
| 211 |
+
out_channels=high_in_channels,
|
| 212 |
+
channels=project_channels,
|
| 213 |
+
query_scales=query_scales,
|
| 214 |
+
key_pool_scales=key_pool_scales,
|
| 215 |
+
conv_cfg=self.conv_cfg,
|
| 216 |
+
norm_cfg=self.norm_cfg,
|
| 217 |
+
act_cfg=self.act_cfg)
|
| 218 |
+
self.bottleneck = ConvModule(
|
| 219 |
+
high_in_channels,
|
| 220 |
+
self.channels,
|
| 221 |
+
3,
|
| 222 |
+
padding=1,
|
| 223 |
+
conv_cfg=self.conv_cfg,
|
| 224 |
+
norm_cfg=self.norm_cfg,
|
| 225 |
+
act_cfg=self.act_cfg)
|
| 226 |
+
self.context = APNB(
|
| 227 |
+
in_channels=self.channels,
|
| 228 |
+
out_channels=self.channels,
|
| 229 |
+
channels=project_channels,
|
| 230 |
+
query_scales=query_scales,
|
| 231 |
+
key_pool_scales=key_pool_scales,
|
| 232 |
+
conv_cfg=self.conv_cfg,
|
| 233 |
+
norm_cfg=self.norm_cfg,
|
| 234 |
+
act_cfg=self.act_cfg)
|
| 235 |
+
|
| 236 |
+
def forward(self, inputs):
|
| 237 |
+
"""Forward function."""
|
| 238 |
+
low_feats, high_feats = self._transform_inputs(inputs)
|
| 239 |
+
output = self.fusion(low_feats, high_feats)
|
| 240 |
+
output = self.dropout(output)
|
| 241 |
+
output = self.bottleneck(output)
|
| 242 |
+
output = self.context(output)
|
| 243 |
+
output = self.cls_seg(output)
|
| 244 |
+
|
| 245 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/apc_head.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from mmcv.cnn import ConvModule
|
| 6 |
+
|
| 7 |
+
from mmseg.registry import MODELS
|
| 8 |
+
from ..utils import resize
|
| 9 |
+
from .decode_head import BaseDecodeHead
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ACM(nn.Module):
|
| 13 |
+
"""Adaptive Context Module used in APCNet.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
pool_scale (int): Pooling scale used in Adaptive Context
|
| 17 |
+
Module to extract region features.
|
| 18 |
+
fusion (bool): Add one conv to fuse residual feature.
|
| 19 |
+
in_channels (int): Input channels.
|
| 20 |
+
channels (int): Channels after modules, before conv_seg.
|
| 21 |
+
conv_cfg (dict | None): Config of conv layers.
|
| 22 |
+
norm_cfg (dict | None): Config of norm layers.
|
| 23 |
+
act_cfg (dict): Config of activation layers.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, pool_scale, fusion, in_channels, channels, conv_cfg,
|
| 27 |
+
norm_cfg, act_cfg):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.pool_scale = pool_scale
|
| 30 |
+
self.fusion = fusion
|
| 31 |
+
self.in_channels = in_channels
|
| 32 |
+
self.channels = channels
|
| 33 |
+
self.conv_cfg = conv_cfg
|
| 34 |
+
self.norm_cfg = norm_cfg
|
| 35 |
+
self.act_cfg = act_cfg
|
| 36 |
+
self.pooled_redu_conv = ConvModule(
|
| 37 |
+
self.in_channels,
|
| 38 |
+
self.channels,
|
| 39 |
+
1,
|
| 40 |
+
conv_cfg=self.conv_cfg,
|
| 41 |
+
norm_cfg=self.norm_cfg,
|
| 42 |
+
act_cfg=self.act_cfg)
|
| 43 |
+
|
| 44 |
+
self.input_redu_conv = ConvModule(
|
| 45 |
+
self.in_channels,
|
| 46 |
+
self.channels,
|
| 47 |
+
1,
|
| 48 |
+
conv_cfg=self.conv_cfg,
|
| 49 |
+
norm_cfg=self.norm_cfg,
|
| 50 |
+
act_cfg=self.act_cfg)
|
| 51 |
+
|
| 52 |
+
self.global_info = ConvModule(
|
| 53 |
+
self.channels,
|
| 54 |
+
self.channels,
|
| 55 |
+
1,
|
| 56 |
+
conv_cfg=self.conv_cfg,
|
| 57 |
+
norm_cfg=self.norm_cfg,
|
| 58 |
+
act_cfg=self.act_cfg)
|
| 59 |
+
|
| 60 |
+
self.gla = nn.Conv2d(self.channels, self.pool_scale**2, 1, 1, 0)
|
| 61 |
+
|
| 62 |
+
self.residual_conv = ConvModule(
|
| 63 |
+
self.channels,
|
| 64 |
+
self.channels,
|
| 65 |
+
1,
|
| 66 |
+
conv_cfg=self.conv_cfg,
|
| 67 |
+
norm_cfg=self.norm_cfg,
|
| 68 |
+
act_cfg=self.act_cfg)
|
| 69 |
+
|
| 70 |
+
if self.fusion:
|
| 71 |
+
self.fusion_conv = ConvModule(
|
| 72 |
+
self.channels,
|
| 73 |
+
self.channels,
|
| 74 |
+
1,
|
| 75 |
+
conv_cfg=self.conv_cfg,
|
| 76 |
+
norm_cfg=self.norm_cfg,
|
| 77 |
+
act_cfg=self.act_cfg)
|
| 78 |
+
|
| 79 |
+
def forward(self, x):
|
| 80 |
+
"""Forward function."""
|
| 81 |
+
pooled_x = F.adaptive_avg_pool2d(x, self.pool_scale)
|
| 82 |
+
# [batch_size, channels, h, w]
|
| 83 |
+
x = self.input_redu_conv(x)
|
| 84 |
+
# [batch_size, channels, pool_scale, pool_scale]
|
| 85 |
+
pooled_x = self.pooled_redu_conv(pooled_x)
|
| 86 |
+
batch_size = x.size(0)
|
| 87 |
+
# [batch_size, pool_scale * pool_scale, channels]
|
| 88 |
+
pooled_x = pooled_x.view(batch_size, self.channels,
|
| 89 |
+
-1).permute(0, 2, 1).contiguous()
|
| 90 |
+
# [batch_size, h * w, pool_scale * pool_scale]
|
| 91 |
+
affinity_matrix = self.gla(x + resize(
|
| 92 |
+
self.global_info(F.adaptive_avg_pool2d(x, 1)), size=x.shape[2:])
|
| 93 |
+
).permute(0, 2, 3, 1).reshape(
|
| 94 |
+
batch_size, -1, self.pool_scale**2)
|
| 95 |
+
affinity_matrix = F.sigmoid(affinity_matrix)
|
| 96 |
+
# [batch_size, h * w, channels]
|
| 97 |
+
z_out = torch.matmul(affinity_matrix, pooled_x)
|
| 98 |
+
# [batch_size, channels, h * w]
|
| 99 |
+
z_out = z_out.permute(0, 2, 1).contiguous()
|
| 100 |
+
# [batch_size, channels, h, w]
|
| 101 |
+
z_out = z_out.view(batch_size, self.channels, x.size(2), x.size(3))
|
| 102 |
+
z_out = self.residual_conv(z_out)
|
| 103 |
+
z_out = F.relu(z_out + x)
|
| 104 |
+
if self.fusion:
|
| 105 |
+
z_out = self.fusion_conv(z_out)
|
| 106 |
+
|
| 107 |
+
return z_out
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@MODELS.register_module()
|
| 111 |
+
class APCHead(BaseDecodeHead):
|
| 112 |
+
"""Adaptive Pyramid Context Network for Semantic Segmentation.
|
| 113 |
+
|
| 114 |
+
This head is the implementation of
|
| 115 |
+
`APCNet <https://openaccess.thecvf.com/content_CVPR_2019/papers/\
|
| 116 |
+
He_Adaptive_Pyramid_Context_Network_for_Semantic_Segmentation_\
|
| 117 |
+
CVPR_2019_paper.pdf>`_.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
pool_scales (tuple[int]): Pooling scales used in Adaptive Context
|
| 121 |
+
Module. Default: (1, 2, 3, 6).
|
| 122 |
+
fusion (bool): Add one conv to fuse residual feature.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
def __init__(self, pool_scales=(1, 2, 3, 6), fusion=True, **kwargs):
|
| 126 |
+
super().__init__(**kwargs)
|
| 127 |
+
assert isinstance(pool_scales, (list, tuple))
|
| 128 |
+
self.pool_scales = pool_scales
|
| 129 |
+
self.fusion = fusion
|
| 130 |
+
acm_modules = []
|
| 131 |
+
for pool_scale in self.pool_scales:
|
| 132 |
+
acm_modules.append(
|
| 133 |
+
ACM(pool_scale,
|
| 134 |
+
self.fusion,
|
| 135 |
+
self.in_channels,
|
| 136 |
+
self.channels,
|
| 137 |
+
conv_cfg=self.conv_cfg,
|
| 138 |
+
norm_cfg=self.norm_cfg,
|
| 139 |
+
act_cfg=self.act_cfg))
|
| 140 |
+
self.acm_modules = nn.ModuleList(acm_modules)
|
| 141 |
+
self.bottleneck = ConvModule(
|
| 142 |
+
self.in_channels + len(pool_scales) * self.channels,
|
| 143 |
+
self.channels,
|
| 144 |
+
3,
|
| 145 |
+
padding=1,
|
| 146 |
+
conv_cfg=self.conv_cfg,
|
| 147 |
+
norm_cfg=self.norm_cfg,
|
| 148 |
+
act_cfg=self.act_cfg)
|
| 149 |
+
|
| 150 |
+
def forward(self, inputs):
|
| 151 |
+
"""Forward function."""
|
| 152 |
+
x = self._transform_inputs(inputs)
|
| 153 |
+
acm_outs = [x]
|
| 154 |
+
for acm_module in self.acm_modules:
|
| 155 |
+
acm_outs.append(acm_module(x))
|
| 156 |
+
acm_outs = torch.cat(acm_outs, dim=1)
|
| 157 |
+
output = self.bottleneck(acm_outs)
|
| 158 |
+
output = self.cls_seg(output)
|
| 159 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/aspp_head.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from ..utils import resize
|
| 8 |
+
from .decode_head import BaseDecodeHead
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ASPPModule(nn.ModuleList):
|
| 12 |
+
"""Atrous Spatial Pyramid Pooling (ASPP) Module.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
dilations (tuple[int]): Dilation rate of each layer.
|
| 16 |
+
in_channels (int): Input channels.
|
| 17 |
+
channels (int): Channels after modules, before conv_seg.
|
| 18 |
+
conv_cfg (dict|None): Config of conv layers.
|
| 19 |
+
norm_cfg (dict|None): Config of norm layers.
|
| 20 |
+
act_cfg (dict): Config of activation layers.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, dilations, in_channels, channels, conv_cfg, norm_cfg,
|
| 24 |
+
act_cfg):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.dilations = dilations
|
| 27 |
+
self.in_channels = in_channels
|
| 28 |
+
self.channels = channels
|
| 29 |
+
self.conv_cfg = conv_cfg
|
| 30 |
+
self.norm_cfg = norm_cfg
|
| 31 |
+
self.act_cfg = act_cfg
|
| 32 |
+
for dilation in dilations:
|
| 33 |
+
self.append(
|
| 34 |
+
ConvModule(
|
| 35 |
+
self.in_channels,
|
| 36 |
+
self.channels,
|
| 37 |
+
1 if dilation == 1 else 3,
|
| 38 |
+
dilation=dilation,
|
| 39 |
+
padding=0 if dilation == 1 else dilation,
|
| 40 |
+
conv_cfg=self.conv_cfg,
|
| 41 |
+
norm_cfg=self.norm_cfg,
|
| 42 |
+
act_cfg=self.act_cfg))
|
| 43 |
+
|
| 44 |
+
def forward(self, x):
|
| 45 |
+
"""Forward function."""
|
| 46 |
+
aspp_outs = []
|
| 47 |
+
for aspp_module in self:
|
| 48 |
+
aspp_outs.append(aspp_module(x))
|
| 49 |
+
|
| 50 |
+
return aspp_outs
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@MODELS.register_module()
|
| 54 |
+
class ASPPHead(BaseDecodeHead):
|
| 55 |
+
"""Rethinking Atrous Convolution for Semantic Image Segmentation.
|
| 56 |
+
|
| 57 |
+
This head is the implementation of `DeepLabV3
|
| 58 |
+
<https://arxiv.org/abs/1706.05587>`_.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
dilations (tuple[int]): Dilation rates for ASPP module.
|
| 62 |
+
Default: (1, 6, 12, 18).
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self, dilations=(1, 6, 12, 18), **kwargs):
|
| 66 |
+
super().__init__(**kwargs)
|
| 67 |
+
assert isinstance(dilations, (list, tuple))
|
| 68 |
+
self.dilations = dilations
|
| 69 |
+
self.image_pool = nn.Sequential(
|
| 70 |
+
nn.AdaptiveAvgPool2d(1),
|
| 71 |
+
ConvModule(
|
| 72 |
+
self.in_channels,
|
| 73 |
+
self.channels,
|
| 74 |
+
1,
|
| 75 |
+
conv_cfg=self.conv_cfg,
|
| 76 |
+
norm_cfg=self.norm_cfg,
|
| 77 |
+
act_cfg=self.act_cfg))
|
| 78 |
+
self.aspp_modules = ASPPModule(
|
| 79 |
+
dilations,
|
| 80 |
+
self.in_channels,
|
| 81 |
+
self.channels,
|
| 82 |
+
conv_cfg=self.conv_cfg,
|
| 83 |
+
norm_cfg=self.norm_cfg,
|
| 84 |
+
act_cfg=self.act_cfg)
|
| 85 |
+
self.bottleneck = ConvModule(
|
| 86 |
+
(len(dilations) + 1) * self.channels,
|
| 87 |
+
self.channels,
|
| 88 |
+
3,
|
| 89 |
+
padding=1,
|
| 90 |
+
conv_cfg=self.conv_cfg,
|
| 91 |
+
norm_cfg=self.norm_cfg,
|
| 92 |
+
act_cfg=self.act_cfg)
|
| 93 |
+
|
| 94 |
+
def _forward_feature(self, inputs):
|
| 95 |
+
"""Forward function for feature maps before classifying each pixel with
|
| 96 |
+
``self.cls_seg`` fc.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
inputs (list[Tensor]): List of multi-level img features.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
feats (Tensor): A tensor of shape (batch_size, self.channels,
|
| 103 |
+
H, W) which is feature map for last layer of decoder head.
|
| 104 |
+
"""
|
| 105 |
+
x = self._transform_inputs(inputs)
|
| 106 |
+
aspp_outs = [
|
| 107 |
+
resize(
|
| 108 |
+
self.image_pool(x),
|
| 109 |
+
size=x.size()[2:],
|
| 110 |
+
mode='bilinear',
|
| 111 |
+
align_corners=self.align_corners)
|
| 112 |
+
]
|
| 113 |
+
aspp_outs.extend(self.aspp_modules(x))
|
| 114 |
+
aspp_outs = torch.cat(aspp_outs, dim=1)
|
| 115 |
+
feats = self.bottleneck(aspp_outs)
|
| 116 |
+
return feats
|
| 117 |
+
|
| 118 |
+
def forward(self, inputs):
|
| 119 |
+
"""Forward function."""
|
| 120 |
+
output = self._forward_feature(inputs)
|
| 121 |
+
output = self.cls_seg(output)
|
| 122 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/cascade_decode_head.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from abc import ABCMeta, abstractmethod
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
|
| 7 |
+
from mmseg.utils import ConfigType
|
| 8 |
+
from .decode_head import BaseDecodeHead
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class BaseCascadeDecodeHead(BaseDecodeHead, metaclass=ABCMeta):
|
| 12 |
+
"""Base class for cascade decode head used in
|
| 13 |
+
:class:`CascadeEncoderDecoder."""
|
| 14 |
+
|
| 15 |
+
def __init__(self, *args, **kwargs):
|
| 16 |
+
super().__init__(*args, **kwargs)
|
| 17 |
+
|
| 18 |
+
@abstractmethod
|
| 19 |
+
def forward(self, inputs, prev_output):
|
| 20 |
+
"""Placeholder of forward function."""
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
def loss(self, inputs: List[Tensor], prev_output: Tensor,
|
| 24 |
+
batch_data_samples: List[dict], train_cfg: ConfigType) -> Tensor:
|
| 25 |
+
"""Forward function for training.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
inputs (List[Tensor]): List of multi-level img features.
|
| 29 |
+
prev_output (Tensor): The output of previous decode head.
|
| 30 |
+
batch_data_samples (List[:obj:`SegDataSample`]): The seg
|
| 31 |
+
data samples. It usually includes information such
|
| 32 |
+
as `metainfo` and `gt_sem_seg`.
|
| 33 |
+
train_cfg (dict): The training config.
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
dict[str, Tensor]: a dictionary of loss components
|
| 37 |
+
"""
|
| 38 |
+
seg_logits = self.forward(inputs, prev_output)
|
| 39 |
+
losses = self.loss_by_feat(seg_logits, batch_data_samples)
|
| 40 |
+
|
| 41 |
+
return losses
|
| 42 |
+
|
| 43 |
+
def predict(self, inputs: List[Tensor], prev_output: Tensor,
|
| 44 |
+
batch_img_metas: List[dict], tese_cfg: ConfigType):
|
| 45 |
+
"""Forward function for testing.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
inputs (List[Tensor]): List of multi-level img features.
|
| 49 |
+
prev_output (Tensor): The output of previous decode head.
|
| 50 |
+
batch_img_metas (dict): List Image info where each dict may also
|
| 51 |
+
contain: 'img_shape', 'scale_factor', 'flip', 'img_path',
|
| 52 |
+
'ori_shape', and 'pad_shape'.
|
| 53 |
+
For details on the values of these keys see
|
| 54 |
+
`mmseg/datasets/pipelines/formatting.py:PackSegInputs`.
|
| 55 |
+
test_cfg (dict): The testing config.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
Tensor: Output segmentation map.
|
| 59 |
+
"""
|
| 60 |
+
seg_logits = self.forward(inputs, prev_output)
|
| 61 |
+
|
| 62 |
+
return self.predict_by_feat(seg_logits, batch_img_metas)
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/cc_head.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from mmseg.registry import MODELS
|
| 5 |
+
from .fcn_head import FCNHead
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from mmcv.ops import CrissCrossAttention
|
| 9 |
+
except ModuleNotFoundError:
|
| 10 |
+
CrissCrossAttention = None
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@MODELS.register_module()
|
| 14 |
+
class CCHead(FCNHead):
|
| 15 |
+
"""CCNet: Criss-Cross Attention for Semantic Segmentation.
|
| 16 |
+
|
| 17 |
+
This head is the implementation of `CCNet
|
| 18 |
+
<https://arxiv.org/abs/1811.11721>`_.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
recurrence (int): Number of recurrence of Criss Cross Attention
|
| 22 |
+
module. Default: 2.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, recurrence=2, **kwargs):
|
| 26 |
+
if CrissCrossAttention is None:
|
| 27 |
+
raise RuntimeError('Please install mmcv-full for '
|
| 28 |
+
'CrissCrossAttention ops')
|
| 29 |
+
super().__init__(num_convs=2, **kwargs)
|
| 30 |
+
self.recurrence = recurrence
|
| 31 |
+
self.cca = CrissCrossAttention(self.channels)
|
| 32 |
+
|
| 33 |
+
def forward(self, inputs):
|
| 34 |
+
"""Forward function."""
|
| 35 |
+
x = self._transform_inputs(inputs)
|
| 36 |
+
output = self.convs[0](x)
|
| 37 |
+
for _ in range(self.recurrence):
|
| 38 |
+
output = self.cca(output)
|
| 39 |
+
output = self.convs[1](output)
|
| 40 |
+
if self.concat_input:
|
| 41 |
+
output = self.conv_cat(torch.cat([x, output], dim=1))
|
| 42 |
+
output = self.cls_seg(output)
|
| 43 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/da_head.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from mmcv.cnn import ConvModule, Scale
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
|
| 9 |
+
from mmseg.registry import MODELS
|
| 10 |
+
from mmseg.utils import SampleList, add_prefix
|
| 11 |
+
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
|
| 12 |
+
from .decode_head import BaseDecodeHead
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class PAM(_SelfAttentionBlock):
|
| 16 |
+
"""Position Attention Module (PAM)
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
in_channels (int): Input channels of key/query feature.
|
| 20 |
+
channels (int): Output channels of key/query transform.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, in_channels, channels):
|
| 24 |
+
super().__init__(
|
| 25 |
+
key_in_channels=in_channels,
|
| 26 |
+
query_in_channels=in_channels,
|
| 27 |
+
channels=channels,
|
| 28 |
+
out_channels=in_channels,
|
| 29 |
+
share_key_query=False,
|
| 30 |
+
query_downsample=None,
|
| 31 |
+
key_downsample=None,
|
| 32 |
+
key_query_num_convs=1,
|
| 33 |
+
key_query_norm=False,
|
| 34 |
+
value_out_num_convs=1,
|
| 35 |
+
value_out_norm=False,
|
| 36 |
+
matmul_norm=False,
|
| 37 |
+
with_out=False,
|
| 38 |
+
conv_cfg=None,
|
| 39 |
+
norm_cfg=None,
|
| 40 |
+
act_cfg=None)
|
| 41 |
+
|
| 42 |
+
self.gamma = Scale(0)
|
| 43 |
+
|
| 44 |
+
def forward(self, x):
|
| 45 |
+
"""Forward function."""
|
| 46 |
+
out = super().forward(x, x)
|
| 47 |
+
|
| 48 |
+
out = self.gamma(out) + x
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class CAM(nn.Module):
|
| 53 |
+
"""Channel Attention Module (CAM)"""
|
| 54 |
+
|
| 55 |
+
def __init__(self):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.gamma = Scale(0)
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
"""Forward function."""
|
| 61 |
+
batch_size, channels, height, width = x.size()
|
| 62 |
+
proj_query = x.view(batch_size, channels, -1)
|
| 63 |
+
proj_key = x.view(batch_size, channels, -1).permute(0, 2, 1)
|
| 64 |
+
energy = torch.bmm(proj_query, proj_key)
|
| 65 |
+
energy_new = torch.max(
|
| 66 |
+
energy, -1, keepdim=True)[0].expand_as(energy) - energy
|
| 67 |
+
attention = F.softmax(energy_new, dim=-1)
|
| 68 |
+
proj_value = x.view(batch_size, channels, -1)
|
| 69 |
+
|
| 70 |
+
out = torch.bmm(attention, proj_value)
|
| 71 |
+
out = out.view(batch_size, channels, height, width)
|
| 72 |
+
|
| 73 |
+
out = self.gamma(out) + x
|
| 74 |
+
return out
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@MODELS.register_module()
|
| 78 |
+
class DAHead(BaseDecodeHead):
|
| 79 |
+
"""Dual Attention Network for Scene Segmentation.
|
| 80 |
+
|
| 81 |
+
This head is the implementation of `DANet
|
| 82 |
+
<https://arxiv.org/abs/1809.02983>`_.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
pam_channels (int): The channels of Position Attention Module(PAM).
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
def __init__(self, pam_channels, **kwargs):
|
| 89 |
+
super().__init__(**kwargs)
|
| 90 |
+
self.pam_channels = pam_channels
|
| 91 |
+
self.pam_in_conv = ConvModule(
|
| 92 |
+
self.in_channels,
|
| 93 |
+
self.channels,
|
| 94 |
+
3,
|
| 95 |
+
padding=1,
|
| 96 |
+
conv_cfg=self.conv_cfg,
|
| 97 |
+
norm_cfg=self.norm_cfg,
|
| 98 |
+
act_cfg=self.act_cfg)
|
| 99 |
+
self.pam = PAM(self.channels, pam_channels)
|
| 100 |
+
self.pam_out_conv = ConvModule(
|
| 101 |
+
self.channels,
|
| 102 |
+
self.channels,
|
| 103 |
+
3,
|
| 104 |
+
padding=1,
|
| 105 |
+
conv_cfg=self.conv_cfg,
|
| 106 |
+
norm_cfg=self.norm_cfg,
|
| 107 |
+
act_cfg=self.act_cfg)
|
| 108 |
+
self.pam_conv_seg = nn.Conv2d(
|
| 109 |
+
self.channels, self.num_classes, kernel_size=1)
|
| 110 |
+
|
| 111 |
+
self.cam_in_conv = ConvModule(
|
| 112 |
+
self.in_channels,
|
| 113 |
+
self.channels,
|
| 114 |
+
3,
|
| 115 |
+
padding=1,
|
| 116 |
+
conv_cfg=self.conv_cfg,
|
| 117 |
+
norm_cfg=self.norm_cfg,
|
| 118 |
+
act_cfg=self.act_cfg)
|
| 119 |
+
self.cam = CAM()
|
| 120 |
+
self.cam_out_conv = ConvModule(
|
| 121 |
+
self.channels,
|
| 122 |
+
self.channels,
|
| 123 |
+
3,
|
| 124 |
+
padding=1,
|
| 125 |
+
conv_cfg=self.conv_cfg,
|
| 126 |
+
norm_cfg=self.norm_cfg,
|
| 127 |
+
act_cfg=self.act_cfg)
|
| 128 |
+
self.cam_conv_seg = nn.Conv2d(
|
| 129 |
+
self.channels, self.num_classes, kernel_size=1)
|
| 130 |
+
|
| 131 |
+
def pam_cls_seg(self, feat):
|
| 132 |
+
"""PAM feature classification."""
|
| 133 |
+
if self.dropout is not None:
|
| 134 |
+
feat = self.dropout(feat)
|
| 135 |
+
output = self.pam_conv_seg(feat)
|
| 136 |
+
return output
|
| 137 |
+
|
| 138 |
+
def cam_cls_seg(self, feat):
|
| 139 |
+
"""CAM feature classification."""
|
| 140 |
+
if self.dropout is not None:
|
| 141 |
+
feat = self.dropout(feat)
|
| 142 |
+
output = self.cam_conv_seg(feat)
|
| 143 |
+
return output
|
| 144 |
+
|
| 145 |
+
def forward(self, inputs):
|
| 146 |
+
"""Forward function."""
|
| 147 |
+
x = self._transform_inputs(inputs)
|
| 148 |
+
pam_feat = self.pam_in_conv(x)
|
| 149 |
+
pam_feat = self.pam(pam_feat)
|
| 150 |
+
pam_feat = self.pam_out_conv(pam_feat)
|
| 151 |
+
pam_out = self.pam_cls_seg(pam_feat)
|
| 152 |
+
|
| 153 |
+
cam_feat = self.cam_in_conv(x)
|
| 154 |
+
cam_feat = self.cam(cam_feat)
|
| 155 |
+
cam_feat = self.cam_out_conv(cam_feat)
|
| 156 |
+
cam_out = self.cam_cls_seg(cam_feat)
|
| 157 |
+
|
| 158 |
+
feat_sum = pam_feat + cam_feat
|
| 159 |
+
pam_cam_out = self.cls_seg(feat_sum)
|
| 160 |
+
|
| 161 |
+
return pam_cam_out, pam_out, cam_out
|
| 162 |
+
|
| 163 |
+
def predict(self, inputs, batch_img_metas: List[dict], test_cfg,
|
| 164 |
+
**kwargs) -> List[Tensor]:
|
| 165 |
+
"""Forward function for testing, only ``pam_cam`` is used."""
|
| 166 |
+
seg_logits = self.forward(inputs)[0]
|
| 167 |
+
return self.predict_by_feat(seg_logits, batch_img_metas, **kwargs)
|
| 168 |
+
|
| 169 |
+
def loss_by_feat(self, seg_logit: Tuple[Tensor],
|
| 170 |
+
batch_data_samples: SampleList, **kwargs) -> dict:
|
| 171 |
+
"""Compute ``pam_cam``, ``pam``, ``cam`` loss."""
|
| 172 |
+
pam_cam_seg_logit, pam_seg_logit, cam_seg_logit = seg_logit
|
| 173 |
+
loss = dict()
|
| 174 |
+
loss.update(
|
| 175 |
+
add_prefix(
|
| 176 |
+
super().loss_by_feat(pam_cam_seg_logit, batch_data_samples),
|
| 177 |
+
'pam_cam'))
|
| 178 |
+
loss.update(
|
| 179 |
+
add_prefix(super().loss_by_feat(pam_seg_logit, batch_data_samples),
|
| 180 |
+
'pam'))
|
| 181 |
+
loss.update(
|
| 182 |
+
add_prefix(super().loss_by_feat(cam_seg_logit, batch_data_samples),
|
| 183 |
+
'cam'))
|
| 184 |
+
return loss
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/ddr_head.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
|
| 8 |
+
from mmseg.models.decode_heads.decode_head import BaseDecodeHead
|
| 9 |
+
from mmseg.models.losses import accuracy
|
| 10 |
+
from mmseg.models.utils import resize
|
| 11 |
+
from mmseg.registry import MODELS
|
| 12 |
+
from mmseg.utils import OptConfigType, SampleList
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@MODELS.register_module()
|
| 16 |
+
class DDRHead(BaseDecodeHead):
|
| 17 |
+
"""Decode head for DDRNet.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
in_channels (int): Number of input channels.
|
| 21 |
+
channels (int): Number of output channels.
|
| 22 |
+
num_classes (int): Number of classes.
|
| 23 |
+
norm_cfg (dict, optional): Config dict for normalization layer.
|
| 24 |
+
Default: dict(type='BN').
|
| 25 |
+
act_cfg (dict, optional): Config dict for activation layer.
|
| 26 |
+
Default: dict(type='ReLU', inplace=True).
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self,
|
| 30 |
+
in_channels: int,
|
| 31 |
+
channels: int,
|
| 32 |
+
num_classes: int,
|
| 33 |
+
norm_cfg: OptConfigType = dict(type='BN'),
|
| 34 |
+
act_cfg: OptConfigType = dict(type='ReLU', inplace=True),
|
| 35 |
+
**kwargs):
|
| 36 |
+
super().__init__(
|
| 37 |
+
in_channels,
|
| 38 |
+
channels,
|
| 39 |
+
num_classes=num_classes,
|
| 40 |
+
norm_cfg=norm_cfg,
|
| 41 |
+
act_cfg=act_cfg,
|
| 42 |
+
**kwargs)
|
| 43 |
+
|
| 44 |
+
self.head = self._make_base_head(self.in_channels, self.channels)
|
| 45 |
+
self.aux_head = self._make_base_head(self.in_channels // 2,
|
| 46 |
+
self.channels)
|
| 47 |
+
self.aux_cls_seg = nn.Conv2d(
|
| 48 |
+
self.channels, self.out_channels, kernel_size=1)
|
| 49 |
+
|
| 50 |
+
def init_weights(self):
|
| 51 |
+
for m in self.modules():
|
| 52 |
+
if isinstance(m, nn.Conv2d):
|
| 53 |
+
nn.init.kaiming_normal_(
|
| 54 |
+
m.weight, mode='fan_out', nonlinearity='relu')
|
| 55 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 56 |
+
nn.init.constant_(m.weight, 1)
|
| 57 |
+
nn.init.constant_(m.bias, 0)
|
| 58 |
+
|
| 59 |
+
def forward(
|
| 60 |
+
self,
|
| 61 |
+
inputs: Union[Tensor,
|
| 62 |
+
Tuple[Tensor]]) -> Union[Tensor, Tuple[Tensor]]:
|
| 63 |
+
if self.training:
|
| 64 |
+
c3_feat, c5_feat = inputs
|
| 65 |
+
x_c = self.head(c5_feat)
|
| 66 |
+
x_c = self.cls_seg(x_c)
|
| 67 |
+
x_s = self.aux_head(c3_feat)
|
| 68 |
+
x_s = self.aux_cls_seg(x_s)
|
| 69 |
+
|
| 70 |
+
return x_c, x_s
|
| 71 |
+
else:
|
| 72 |
+
x_c = self.head(inputs)
|
| 73 |
+
x_c = self.cls_seg(x_c)
|
| 74 |
+
return x_c
|
| 75 |
+
|
| 76 |
+
def _make_base_head(self, in_channels: int,
|
| 77 |
+
channels: int) -> nn.Sequential:
|
| 78 |
+
layers = [
|
| 79 |
+
ConvModule(
|
| 80 |
+
in_channels,
|
| 81 |
+
channels,
|
| 82 |
+
kernel_size=3,
|
| 83 |
+
padding=1,
|
| 84 |
+
norm_cfg=self.norm_cfg,
|
| 85 |
+
act_cfg=self.act_cfg,
|
| 86 |
+
order=('norm', 'act', 'conv')),
|
| 87 |
+
build_norm_layer(self.norm_cfg, channels)[1],
|
| 88 |
+
build_activation_layer(self.act_cfg),
|
| 89 |
+
]
|
| 90 |
+
|
| 91 |
+
return nn.Sequential(*layers)
|
| 92 |
+
|
| 93 |
+
def loss_by_feat(self, seg_logits: Tuple[Tensor],
|
| 94 |
+
batch_data_samples: SampleList) -> dict:
|
| 95 |
+
loss = dict()
|
| 96 |
+
context_logit, spatial_logit = seg_logits
|
| 97 |
+
seg_label = self._stack_batch_gt(batch_data_samples)
|
| 98 |
+
|
| 99 |
+
context_logit = resize(
|
| 100 |
+
context_logit,
|
| 101 |
+
size=seg_label.shape[2:],
|
| 102 |
+
mode='bilinear',
|
| 103 |
+
align_corners=self.align_corners)
|
| 104 |
+
spatial_logit = resize(
|
| 105 |
+
spatial_logit,
|
| 106 |
+
size=seg_label.shape[2:],
|
| 107 |
+
mode='bilinear',
|
| 108 |
+
align_corners=self.align_corners)
|
| 109 |
+
seg_label = seg_label.squeeze(1)
|
| 110 |
+
|
| 111 |
+
loss['loss_context'] = self.loss_decode[0](context_logit, seg_label)
|
| 112 |
+
loss['loss_spatial'] = self.loss_decode[1](spatial_logit, seg_label)
|
| 113 |
+
loss['acc_seg'] = accuracy(
|
| 114 |
+
context_logit, seg_label, ignore_index=self.ignore_index)
|
| 115 |
+
|
| 116 |
+
return loss
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/decode_head.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import warnings
|
| 3 |
+
from abc import ABCMeta, abstractmethod
|
| 4 |
+
from typing import List, Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from mmengine.model import BaseModule
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
|
| 11 |
+
from mmseg.registry import MODELS
|
| 12 |
+
from mmseg.structures import build_pixel_sampler
|
| 13 |
+
from mmseg.utils import ConfigType, SampleList
|
| 14 |
+
from ..losses import accuracy
|
| 15 |
+
from ..utils import resize
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class BaseDecodeHead(BaseModule, metaclass=ABCMeta):
|
| 19 |
+
"""Base class for BaseDecodeHead.
|
| 20 |
+
|
| 21 |
+
1. The ``init_weights`` method is used to initialize decode_head's
|
| 22 |
+
model parameters. After segmentor initialization, ``init_weights``
|
| 23 |
+
is triggered when ``segmentor.init_weights()`` is called externally.
|
| 24 |
+
|
| 25 |
+
2. The ``loss`` method is used to calculate the loss of decode_head,
|
| 26 |
+
which includes two steps: (1) the decode_head model performs forward
|
| 27 |
+
propagation to obtain the feature maps (2) The ``loss_by_feat`` method
|
| 28 |
+
is called based on the feature maps to calculate the loss.
|
| 29 |
+
|
| 30 |
+
.. code:: text
|
| 31 |
+
|
| 32 |
+
loss(): forward() -> loss_by_feat()
|
| 33 |
+
|
| 34 |
+
3. The ``predict`` method is used to predict segmentation results,
|
| 35 |
+
which includes two steps: (1) the decode_head model performs forward
|
| 36 |
+
propagation to obtain the feature maps (2) The ``predict_by_feat`` method
|
| 37 |
+
is called based on the feature maps to predict segmentation results
|
| 38 |
+
including post-processing.
|
| 39 |
+
|
| 40 |
+
.. code:: text
|
| 41 |
+
|
| 42 |
+
predict(): forward() -> predict_by_feat()
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
in_channels (int|Sequence[int]): Input channels.
|
| 46 |
+
channels (int): Channels after modules, before conv_seg.
|
| 47 |
+
num_classes (int): Number of classes.
|
| 48 |
+
out_channels (int): Output channels of conv_seg. Default: None.
|
| 49 |
+
threshold (float): Threshold for binary segmentation in the case of
|
| 50 |
+
`num_classes==1`. Default: None.
|
| 51 |
+
dropout_ratio (float): Ratio of dropout layer. Default: 0.1.
|
| 52 |
+
conv_cfg (dict|None): Config of conv layers. Default: None.
|
| 53 |
+
norm_cfg (dict|None): Config of norm layers. Default: None.
|
| 54 |
+
act_cfg (dict): Config of activation layers.
|
| 55 |
+
Default: dict(type='ReLU')
|
| 56 |
+
in_index (int|Sequence[int]): Input feature index. Default: -1
|
| 57 |
+
input_transform (str|None): Transformation type of input features.
|
| 58 |
+
Options: 'resize_concat', 'multiple_select', None.
|
| 59 |
+
'resize_concat': Multiple feature maps will be resize to the
|
| 60 |
+
same size as first one and than concat together.
|
| 61 |
+
Usually used in FCN head of HRNet.
|
| 62 |
+
'multiple_select': Multiple feature maps will be bundle into
|
| 63 |
+
a list and passed into decode head.
|
| 64 |
+
None: Only one select feature map is allowed.
|
| 65 |
+
Default: None.
|
| 66 |
+
loss_decode (dict | Sequence[dict]): Config of decode loss.
|
| 67 |
+
The `loss_name` is property of corresponding loss function which
|
| 68 |
+
could be shown in training log. If you want this loss
|
| 69 |
+
item to be included into the backward graph, `loss_` must be the
|
| 70 |
+
prefix of the name. Defaults to 'loss_ce'.
|
| 71 |
+
e.g. dict(type='CrossEntropyLoss'),
|
| 72 |
+
[dict(type='CrossEntropyLoss', loss_name='loss_ce'),
|
| 73 |
+
dict(type='DiceLoss', loss_name='loss_dice')]
|
| 74 |
+
Default: dict(type='CrossEntropyLoss').
|
| 75 |
+
ignore_index (int | None): The label index to be ignored. When using
|
| 76 |
+
masked BCE loss, ignore_index should be set to None. Default: 255.
|
| 77 |
+
sampler (dict|None): The config of segmentation map sampler.
|
| 78 |
+
Default: None.
|
| 79 |
+
align_corners (bool): align_corners argument of F.interpolate.
|
| 80 |
+
Default: False.
|
| 81 |
+
init_cfg (dict or list[dict], optional): Initialization config dict.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(self,
|
| 85 |
+
in_channels,
|
| 86 |
+
channels,
|
| 87 |
+
*,
|
| 88 |
+
num_classes,
|
| 89 |
+
out_channels=None,
|
| 90 |
+
threshold=None,
|
| 91 |
+
dropout_ratio=0.1,
|
| 92 |
+
conv_cfg=None,
|
| 93 |
+
norm_cfg=None,
|
| 94 |
+
act_cfg=dict(type='ReLU'),
|
| 95 |
+
in_index=-1,
|
| 96 |
+
input_transform=None,
|
| 97 |
+
loss_decode=dict(
|
| 98 |
+
type='CrossEntropyLoss',
|
| 99 |
+
use_sigmoid=False,
|
| 100 |
+
loss_weight=1.0),
|
| 101 |
+
ignore_index=255,
|
| 102 |
+
sampler=None,
|
| 103 |
+
align_corners=False,
|
| 104 |
+
init_cfg=dict(
|
| 105 |
+
type='Normal', std=0.01, override=dict(name='conv_seg'))):
|
| 106 |
+
super().__init__(init_cfg)
|
| 107 |
+
self._init_inputs(in_channels, in_index, input_transform)
|
| 108 |
+
self.channels = channels
|
| 109 |
+
self.dropout_ratio = dropout_ratio
|
| 110 |
+
self.conv_cfg = conv_cfg
|
| 111 |
+
self.norm_cfg = norm_cfg
|
| 112 |
+
self.act_cfg = act_cfg
|
| 113 |
+
self.in_index = in_index
|
| 114 |
+
|
| 115 |
+
self.ignore_index = ignore_index
|
| 116 |
+
self.align_corners = align_corners
|
| 117 |
+
|
| 118 |
+
if out_channels is None:
|
| 119 |
+
if num_classes == 2:
|
| 120 |
+
warnings.warn('For binary segmentation, we suggest using'
|
| 121 |
+
'`out_channels = 1` to define the output'
|
| 122 |
+
'channels of segmentor, and use `threshold`'
|
| 123 |
+
'to convert `seg_logits` into a prediction'
|
| 124 |
+
'applying a threshold')
|
| 125 |
+
out_channels = num_classes
|
| 126 |
+
|
| 127 |
+
if out_channels != num_classes and out_channels != 1:
|
| 128 |
+
raise ValueError(
|
| 129 |
+
'out_channels should be equal to num_classes,'
|
| 130 |
+
'except binary segmentation set out_channels == 1 and'
|
| 131 |
+
f'num_classes == 2, but got out_channels={out_channels}'
|
| 132 |
+
f'and num_classes={num_classes}')
|
| 133 |
+
|
| 134 |
+
if out_channels == 1 and threshold is None:
|
| 135 |
+
threshold = 0.3
|
| 136 |
+
warnings.warn('threshold is not defined for binary, and defaults'
|
| 137 |
+
'to 0.3')
|
| 138 |
+
self.num_classes = num_classes
|
| 139 |
+
self.out_channels = out_channels
|
| 140 |
+
self.threshold = threshold
|
| 141 |
+
|
| 142 |
+
if isinstance(loss_decode, dict):
|
| 143 |
+
self.loss_decode = MODELS.build(loss_decode)
|
| 144 |
+
elif isinstance(loss_decode, (list, tuple)):
|
| 145 |
+
self.loss_decode = nn.ModuleList()
|
| 146 |
+
for loss in loss_decode:
|
| 147 |
+
self.loss_decode.append(MODELS.build(loss))
|
| 148 |
+
else:
|
| 149 |
+
raise TypeError(f'loss_decode must be a dict or sequence of dict,\
|
| 150 |
+
but got {type(loss_decode)}')
|
| 151 |
+
|
| 152 |
+
if sampler is not None:
|
| 153 |
+
self.sampler = build_pixel_sampler(sampler, context=self)
|
| 154 |
+
else:
|
| 155 |
+
self.sampler = None
|
| 156 |
+
|
| 157 |
+
self.conv_seg = nn.Conv2d(channels, self.out_channels, kernel_size=1)
|
| 158 |
+
if dropout_ratio > 0:
|
| 159 |
+
self.dropout = nn.Dropout2d(dropout_ratio)
|
| 160 |
+
else:
|
| 161 |
+
self.dropout = None
|
| 162 |
+
|
| 163 |
+
def extra_repr(self):
|
| 164 |
+
"""Extra repr."""
|
| 165 |
+
s = f'input_transform={self.input_transform}, ' \
|
| 166 |
+
f'ignore_index={self.ignore_index}, ' \
|
| 167 |
+
f'align_corners={self.align_corners}'
|
| 168 |
+
return s
|
| 169 |
+
|
| 170 |
+
def _init_inputs(self, in_channels, in_index, input_transform):
|
| 171 |
+
"""Check and initialize input transforms.
|
| 172 |
+
|
| 173 |
+
The in_channels, in_index and input_transform must match.
|
| 174 |
+
Specifically, when input_transform is None, only single feature map
|
| 175 |
+
will be selected. So in_channels and in_index must be of type int.
|
| 176 |
+
When input_transform
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
in_channels (int|Sequence[int]): Input channels.
|
| 180 |
+
in_index (int|Sequence[int]): Input feature index.
|
| 181 |
+
input_transform (str|None): Transformation type of input features.
|
| 182 |
+
Options: 'resize_concat', 'multiple_select', None.
|
| 183 |
+
'resize_concat': Multiple feature maps will be resize to the
|
| 184 |
+
same size as first one and than concat together.
|
| 185 |
+
Usually used in FCN head of HRNet.
|
| 186 |
+
'multiple_select': Multiple feature maps will be bundle into
|
| 187 |
+
a list and passed into decode head.
|
| 188 |
+
None: Only one select feature map is allowed.
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
if input_transform is not None:
|
| 192 |
+
assert input_transform in ['resize_concat', 'multiple_select']
|
| 193 |
+
self.input_transform = input_transform
|
| 194 |
+
self.in_index = in_index
|
| 195 |
+
if input_transform is not None:
|
| 196 |
+
assert isinstance(in_channels, (list, tuple))
|
| 197 |
+
assert isinstance(in_index, (list, tuple))
|
| 198 |
+
assert len(in_channels) == len(in_index)
|
| 199 |
+
if input_transform == 'resize_concat':
|
| 200 |
+
self.in_channels = sum(in_channels)
|
| 201 |
+
else:
|
| 202 |
+
self.in_channels = in_channels
|
| 203 |
+
else:
|
| 204 |
+
assert isinstance(in_channels, int)
|
| 205 |
+
assert isinstance(in_index, int)
|
| 206 |
+
self.in_channels = in_channels
|
| 207 |
+
|
| 208 |
+
def _transform_inputs(self, inputs):
|
| 209 |
+
"""Transform inputs for decoder.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
inputs (list[Tensor]): List of multi-level img features.
|
| 213 |
+
|
| 214 |
+
Returns:
|
| 215 |
+
Tensor: The transformed inputs
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
if self.input_transform == 'resize_concat':
|
| 219 |
+
inputs = [inputs[i] for i in self.in_index]
|
| 220 |
+
upsampled_inputs = [
|
| 221 |
+
resize(
|
| 222 |
+
input=x,
|
| 223 |
+
size=inputs[0].shape[2:],
|
| 224 |
+
mode='bilinear',
|
| 225 |
+
align_corners=self.align_corners) for x in inputs
|
| 226 |
+
]
|
| 227 |
+
inputs = torch.cat(upsampled_inputs, dim=1)
|
| 228 |
+
elif self.input_transform == 'multiple_select':
|
| 229 |
+
inputs = [inputs[i] for i in self.in_index]
|
| 230 |
+
else:
|
| 231 |
+
inputs = inputs[self.in_index]
|
| 232 |
+
|
| 233 |
+
return inputs
|
| 234 |
+
|
| 235 |
+
@abstractmethod
|
| 236 |
+
def forward(self, inputs):
|
| 237 |
+
"""Placeholder of forward function."""
|
| 238 |
+
pass
|
| 239 |
+
|
| 240 |
+
def cls_seg(self, feat):
|
| 241 |
+
"""Classify each pixel."""
|
| 242 |
+
if self.dropout is not None:
|
| 243 |
+
feat = self.dropout(feat)
|
| 244 |
+
output = self.conv_seg(feat)
|
| 245 |
+
return output
|
| 246 |
+
|
| 247 |
+
def loss(self, inputs: Tuple[Tensor], batch_data_samples: SampleList,
|
| 248 |
+
train_cfg: ConfigType) -> dict:
|
| 249 |
+
"""Forward function for training.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
inputs (Tuple[Tensor]): List of multi-level img features.
|
| 253 |
+
batch_data_samples (list[:obj:`SegDataSample`]): The seg
|
| 254 |
+
data samples. It usually includes information such
|
| 255 |
+
as `img_metas` or `gt_semantic_seg`.
|
| 256 |
+
train_cfg (dict): The training config.
|
| 257 |
+
|
| 258 |
+
Returns:
|
| 259 |
+
dict[str, Tensor]: a dictionary of loss components
|
| 260 |
+
"""
|
| 261 |
+
seg_logits = self.forward(inputs)
|
| 262 |
+
losses = self.loss_by_feat(seg_logits, batch_data_samples)
|
| 263 |
+
return losses
|
| 264 |
+
|
| 265 |
+
def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict],
|
| 266 |
+
test_cfg: ConfigType) -> Tensor:
|
| 267 |
+
"""Forward function for prediction.
|
| 268 |
+
|
| 269 |
+
Args:
|
| 270 |
+
inputs (Tuple[Tensor]): List of multi-level img features.
|
| 271 |
+
batch_img_metas (dict): List Image info where each dict may also
|
| 272 |
+
contain: 'img_shape', 'scale_factor', 'flip', 'img_path',
|
| 273 |
+
'ori_shape', and 'pad_shape'.
|
| 274 |
+
For details on the values of these keys see
|
| 275 |
+
`mmseg/datasets/pipelines/formatting.py:PackSegInputs`.
|
| 276 |
+
test_cfg (dict): The testing config.
|
| 277 |
+
|
| 278 |
+
Returns:
|
| 279 |
+
Tensor: Outputs segmentation logits map.
|
| 280 |
+
"""
|
| 281 |
+
seg_logits = self.forward(inputs)
|
| 282 |
+
|
| 283 |
+
return self.predict_by_feat(seg_logits, batch_img_metas)
|
| 284 |
+
|
| 285 |
+
def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tensor:
|
| 286 |
+
gt_semantic_segs = [
|
| 287 |
+
data_sample.gt_sem_seg.data for data_sample in batch_data_samples
|
| 288 |
+
]
|
| 289 |
+
return torch.stack(gt_semantic_segs, dim=0)
|
| 290 |
+
|
| 291 |
+
def loss_by_feat(self, seg_logits: Tensor,
|
| 292 |
+
batch_data_samples: SampleList) -> dict:
|
| 293 |
+
"""Compute segmentation loss.
|
| 294 |
+
|
| 295 |
+
Args:
|
| 296 |
+
seg_logits (Tensor): The output from decode head forward function.
|
| 297 |
+
batch_data_samples (List[:obj:`SegDataSample`]): The seg
|
| 298 |
+
data samples. It usually includes information such
|
| 299 |
+
as `metainfo` and `gt_sem_seg`.
|
| 300 |
+
|
| 301 |
+
Returns:
|
| 302 |
+
dict[str, Tensor]: a dictionary of loss components
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
seg_label = self._stack_batch_gt(batch_data_samples)
|
| 306 |
+
loss = dict()
|
| 307 |
+
seg_logits = resize(
|
| 308 |
+
input=seg_logits,
|
| 309 |
+
size=seg_label.shape[2:],
|
| 310 |
+
mode='bilinear',
|
| 311 |
+
align_corners=self.align_corners)
|
| 312 |
+
if self.sampler is not None:
|
| 313 |
+
seg_weight = self.sampler.sample(seg_logits, seg_label)
|
| 314 |
+
else:
|
| 315 |
+
seg_weight = None
|
| 316 |
+
seg_label = seg_label.squeeze(1)
|
| 317 |
+
|
| 318 |
+
if not isinstance(self.loss_decode, nn.ModuleList):
|
| 319 |
+
losses_decode = [self.loss_decode]
|
| 320 |
+
else:
|
| 321 |
+
losses_decode = self.loss_decode
|
| 322 |
+
for loss_decode in losses_decode:
|
| 323 |
+
if loss_decode.loss_name not in loss:
|
| 324 |
+
loss[loss_decode.loss_name] = loss_decode(
|
| 325 |
+
seg_logits,
|
| 326 |
+
seg_label,
|
| 327 |
+
weight=seg_weight,
|
| 328 |
+
ignore_index=self.ignore_index)
|
| 329 |
+
else:
|
| 330 |
+
loss[loss_decode.loss_name] += loss_decode(
|
| 331 |
+
seg_logits,
|
| 332 |
+
seg_label,
|
| 333 |
+
weight=seg_weight,
|
| 334 |
+
ignore_index=self.ignore_index)
|
| 335 |
+
|
| 336 |
+
loss['acc_seg'] = accuracy(
|
| 337 |
+
seg_logits, seg_label, ignore_index=self.ignore_index)
|
| 338 |
+
return loss
|
| 339 |
+
|
| 340 |
+
def predict_by_feat(self, seg_logits: Tensor,
|
| 341 |
+
batch_img_metas: List[dict]) -> Tensor:
|
| 342 |
+
"""Transform a batch of output seg_logits to the input shape.
|
| 343 |
+
|
| 344 |
+
Args:
|
| 345 |
+
seg_logits (Tensor): The output from decode head forward function.
|
| 346 |
+
batch_img_metas (list[dict]): Meta information of each image, e.g.,
|
| 347 |
+
image size, scaling factor, etc.
|
| 348 |
+
|
| 349 |
+
Returns:
|
| 350 |
+
Tensor: Outputs segmentation logits map.
|
| 351 |
+
"""
|
| 352 |
+
|
| 353 |
+
if isinstance(batch_img_metas[0]['img_shape'], torch.Size):
|
| 354 |
+
# slide inference
|
| 355 |
+
size = batch_img_metas[0]['img_shape']
|
| 356 |
+
elif 'pad_shape' in batch_img_metas[0]:
|
| 357 |
+
size = batch_img_metas[0]['pad_shape'][:2]
|
| 358 |
+
else:
|
| 359 |
+
size = batch_img_metas[0]['img_shape']
|
| 360 |
+
|
| 361 |
+
seg_logits = resize(
|
| 362 |
+
input=seg_logits,
|
| 363 |
+
size=size,
|
| 364 |
+
mode='bilinear',
|
| 365 |
+
align_corners=self.align_corners)
|
| 366 |
+
return seg_logits
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/dm_head.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer
|
| 6 |
+
|
| 7 |
+
from mmseg.registry import MODELS
|
| 8 |
+
from .decode_head import BaseDecodeHead
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DCM(nn.Module):
|
| 12 |
+
"""Dynamic Convolutional Module used in DMNet.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
filter_size (int): The filter size of generated convolution kernel
|
| 16 |
+
used in Dynamic Convolutional Module.
|
| 17 |
+
fusion (bool): Add one conv to fuse DCM output feature.
|
| 18 |
+
in_channels (int): Input channels.
|
| 19 |
+
channels (int): Channels after modules, before conv_seg.
|
| 20 |
+
conv_cfg (dict | None): Config of conv layers.
|
| 21 |
+
norm_cfg (dict | None): Config of norm layers.
|
| 22 |
+
act_cfg (dict): Config of activation layers.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, filter_size, fusion, in_channels, channels, conv_cfg,
|
| 26 |
+
norm_cfg, act_cfg):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.filter_size = filter_size
|
| 29 |
+
self.fusion = fusion
|
| 30 |
+
self.in_channels = in_channels
|
| 31 |
+
self.channels = channels
|
| 32 |
+
self.conv_cfg = conv_cfg
|
| 33 |
+
self.norm_cfg = norm_cfg
|
| 34 |
+
self.act_cfg = act_cfg
|
| 35 |
+
self.filter_gen_conv = nn.Conv2d(self.in_channels, self.channels, 1, 1,
|
| 36 |
+
0)
|
| 37 |
+
|
| 38 |
+
self.input_redu_conv = ConvModule(
|
| 39 |
+
self.in_channels,
|
| 40 |
+
self.channels,
|
| 41 |
+
1,
|
| 42 |
+
conv_cfg=self.conv_cfg,
|
| 43 |
+
norm_cfg=self.norm_cfg,
|
| 44 |
+
act_cfg=self.act_cfg)
|
| 45 |
+
|
| 46 |
+
if self.norm_cfg is not None:
|
| 47 |
+
self.norm = build_norm_layer(self.norm_cfg, self.channels)[1]
|
| 48 |
+
else:
|
| 49 |
+
self.norm = None
|
| 50 |
+
self.activate = build_activation_layer(self.act_cfg)
|
| 51 |
+
|
| 52 |
+
if self.fusion:
|
| 53 |
+
self.fusion_conv = ConvModule(
|
| 54 |
+
self.channels,
|
| 55 |
+
self.channels,
|
| 56 |
+
1,
|
| 57 |
+
conv_cfg=self.conv_cfg,
|
| 58 |
+
norm_cfg=self.norm_cfg,
|
| 59 |
+
act_cfg=self.act_cfg)
|
| 60 |
+
|
| 61 |
+
def forward(self, x):
|
| 62 |
+
"""Forward function."""
|
| 63 |
+
generated_filter = self.filter_gen_conv(
|
| 64 |
+
F.adaptive_avg_pool2d(x, self.filter_size))
|
| 65 |
+
x = self.input_redu_conv(x)
|
| 66 |
+
b, c, h, w = x.shape
|
| 67 |
+
# [1, b * c, h, w], c = self.channels
|
| 68 |
+
x = x.view(1, b * c, h, w)
|
| 69 |
+
# [b * c, 1, filter_size, filter_size]
|
| 70 |
+
generated_filter = generated_filter.view(b * c, 1, self.filter_size,
|
| 71 |
+
self.filter_size)
|
| 72 |
+
pad = (self.filter_size - 1) // 2
|
| 73 |
+
if (self.filter_size - 1) % 2 == 0:
|
| 74 |
+
p2d = (pad, pad, pad, pad)
|
| 75 |
+
else:
|
| 76 |
+
p2d = (pad + 1, pad, pad + 1, pad)
|
| 77 |
+
x = F.pad(input=x, pad=p2d, mode='constant', value=0)
|
| 78 |
+
# [1, b * c, h, w]
|
| 79 |
+
output = F.conv2d(input=x, weight=generated_filter, groups=b * c)
|
| 80 |
+
# [b, c, h, w]
|
| 81 |
+
output = output.view(b, c, h, w)
|
| 82 |
+
if self.norm is not None:
|
| 83 |
+
output = self.norm(output)
|
| 84 |
+
output = self.activate(output)
|
| 85 |
+
|
| 86 |
+
if self.fusion:
|
| 87 |
+
output = self.fusion_conv(output)
|
| 88 |
+
|
| 89 |
+
return output
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@MODELS.register_module()
|
| 93 |
+
class DMHead(BaseDecodeHead):
|
| 94 |
+
"""Dynamic Multi-scale Filters for Semantic Segmentation.
|
| 95 |
+
|
| 96 |
+
This head is the implementation of
|
| 97 |
+
`DMNet <https://openaccess.thecvf.com/content_ICCV_2019/papers/\
|
| 98 |
+
He_Dynamic_Multi-Scale_Filters_for_Semantic_Segmentation_\
|
| 99 |
+
ICCV_2019_paper.pdf>`_.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
filter_sizes (tuple[int]): The size of generated convolutional filters
|
| 103 |
+
used in Dynamic Convolutional Module. Default: (1, 3, 5, 7).
|
| 104 |
+
fusion (bool): Add one conv to fuse DCM output feature.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
def __init__(self, filter_sizes=(1, 3, 5, 7), fusion=False, **kwargs):
|
| 108 |
+
super().__init__(**kwargs)
|
| 109 |
+
assert isinstance(filter_sizes, (list, tuple))
|
| 110 |
+
self.filter_sizes = filter_sizes
|
| 111 |
+
self.fusion = fusion
|
| 112 |
+
dcm_modules = []
|
| 113 |
+
for filter_size in self.filter_sizes:
|
| 114 |
+
dcm_modules.append(
|
| 115 |
+
DCM(filter_size,
|
| 116 |
+
self.fusion,
|
| 117 |
+
self.in_channels,
|
| 118 |
+
self.channels,
|
| 119 |
+
conv_cfg=self.conv_cfg,
|
| 120 |
+
norm_cfg=self.norm_cfg,
|
| 121 |
+
act_cfg=self.act_cfg))
|
| 122 |
+
self.dcm_modules = nn.ModuleList(dcm_modules)
|
| 123 |
+
self.bottleneck = ConvModule(
|
| 124 |
+
self.in_channels + len(filter_sizes) * self.channels,
|
| 125 |
+
self.channels,
|
| 126 |
+
3,
|
| 127 |
+
padding=1,
|
| 128 |
+
conv_cfg=self.conv_cfg,
|
| 129 |
+
norm_cfg=self.norm_cfg,
|
| 130 |
+
act_cfg=self.act_cfg)
|
| 131 |
+
|
| 132 |
+
def forward(self, inputs):
|
| 133 |
+
"""Forward function."""
|
| 134 |
+
x = self._transform_inputs(inputs)
|
| 135 |
+
dcm_outs = [x]
|
| 136 |
+
for dcm_module in self.dcm_modules:
|
| 137 |
+
dcm_outs.append(dcm_module(x))
|
| 138 |
+
dcm_outs = torch.cat(dcm_outs, dim=1)
|
| 139 |
+
output = self.bottleneck(dcm_outs)
|
| 140 |
+
output = self.cls_seg(output)
|
| 141 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/dnl_head.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
from mmcv.cnn import NonLocal2d
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from .fcn_head import FCNHead
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class DisentangledNonLocal2d(NonLocal2d):
|
| 11 |
+
"""Disentangled Non-Local Blocks.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
temperature (float): Temperature to adjust attention. Default: 0.05
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, *arg, temperature, **kwargs):
|
| 18 |
+
super().__init__(*arg, **kwargs)
|
| 19 |
+
self.temperature = temperature
|
| 20 |
+
self.conv_mask = nn.Conv2d(self.in_channels, 1, kernel_size=1)
|
| 21 |
+
|
| 22 |
+
def embedded_gaussian(self, theta_x, phi_x):
|
| 23 |
+
"""Embedded gaussian with temperature."""
|
| 24 |
+
|
| 25 |
+
# NonLocal2d pairwise_weight: [N, HxW, HxW]
|
| 26 |
+
pairwise_weight = torch.matmul(theta_x, phi_x)
|
| 27 |
+
if self.use_scale:
|
| 28 |
+
# theta_x.shape[-1] is `self.inter_channels`
|
| 29 |
+
pairwise_weight /= torch.tensor(
|
| 30 |
+
theta_x.shape[-1],
|
| 31 |
+
dtype=torch.float,
|
| 32 |
+
device=pairwise_weight.device)**torch.tensor(
|
| 33 |
+
0.5, device=pairwise_weight.device)
|
| 34 |
+
pairwise_weight /= torch.tensor(
|
| 35 |
+
self.temperature, device=pairwise_weight.device)
|
| 36 |
+
pairwise_weight = pairwise_weight.softmax(dim=-1)
|
| 37 |
+
return pairwise_weight
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
# x: [N, C, H, W]
|
| 41 |
+
n = x.size(0)
|
| 42 |
+
|
| 43 |
+
# g_x: [N, HxW, C]
|
| 44 |
+
g_x = self.g(x).view(n, self.inter_channels, -1)
|
| 45 |
+
g_x = g_x.permute(0, 2, 1)
|
| 46 |
+
|
| 47 |
+
# theta_x: [N, HxW, C], phi_x: [N, C, HxW]
|
| 48 |
+
if self.mode == 'gaussian':
|
| 49 |
+
theta_x = x.view(n, self.in_channels, -1)
|
| 50 |
+
theta_x = theta_x.permute(0, 2, 1)
|
| 51 |
+
if self.sub_sample:
|
| 52 |
+
phi_x = self.phi(x).view(n, self.in_channels, -1)
|
| 53 |
+
else:
|
| 54 |
+
phi_x = x.view(n, self.in_channels, -1)
|
| 55 |
+
elif self.mode == 'concatenation':
|
| 56 |
+
theta_x = self.theta(x).view(n, self.inter_channels, -1, 1)
|
| 57 |
+
phi_x = self.phi(x).view(n, self.inter_channels, 1, -1)
|
| 58 |
+
else:
|
| 59 |
+
theta_x = self.theta(x).view(n, self.inter_channels, -1)
|
| 60 |
+
theta_x = theta_x.permute(0, 2, 1)
|
| 61 |
+
phi_x = self.phi(x).view(n, self.inter_channels, -1)
|
| 62 |
+
|
| 63 |
+
# subtract mean
|
| 64 |
+
theta_x -= theta_x.mean(dim=-2, keepdim=True)
|
| 65 |
+
phi_x -= phi_x.mean(dim=-1, keepdim=True)
|
| 66 |
+
|
| 67 |
+
pairwise_func = getattr(self, self.mode)
|
| 68 |
+
# pairwise_weight: [N, HxW, HxW]
|
| 69 |
+
pairwise_weight = pairwise_func(theta_x, phi_x)
|
| 70 |
+
|
| 71 |
+
# y: [N, HxW, C]
|
| 72 |
+
y = torch.matmul(pairwise_weight, g_x)
|
| 73 |
+
# y: [N, C, H, W]
|
| 74 |
+
y = y.permute(0, 2, 1).contiguous().reshape(n, self.inter_channels,
|
| 75 |
+
*x.size()[2:])
|
| 76 |
+
|
| 77 |
+
# unary_mask: [N, 1, HxW]
|
| 78 |
+
unary_mask = self.conv_mask(x)
|
| 79 |
+
unary_mask = unary_mask.view(n, 1, -1)
|
| 80 |
+
unary_mask = unary_mask.softmax(dim=-1)
|
| 81 |
+
# unary_x: [N, 1, C]
|
| 82 |
+
unary_x = torch.matmul(unary_mask, g_x)
|
| 83 |
+
# unary_x: [N, C, 1, 1]
|
| 84 |
+
unary_x = unary_x.permute(0, 2, 1).contiguous().reshape(
|
| 85 |
+
n, self.inter_channels, 1, 1)
|
| 86 |
+
|
| 87 |
+
output = x + self.conv_out(y + unary_x)
|
| 88 |
+
|
| 89 |
+
return output
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@MODELS.register_module()
|
| 93 |
+
class DNLHead(FCNHead):
|
| 94 |
+
"""Disentangled Non-Local Neural Networks.
|
| 95 |
+
|
| 96 |
+
This head is the implementation of `DNLNet
|
| 97 |
+
<https://arxiv.org/abs/2006.06668>`_.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
reduction (int): Reduction factor of projection transform. Default: 2.
|
| 101 |
+
use_scale (bool): Whether to scale pairwise_weight by
|
| 102 |
+
sqrt(1/inter_channels). Default: False.
|
| 103 |
+
mode (str): The nonlocal mode. Options are 'embedded_gaussian',
|
| 104 |
+
'dot_product'. Default: 'embedded_gaussian.'.
|
| 105 |
+
temperature (float): Temperature to adjust attention. Default: 0.05
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def __init__(self,
|
| 109 |
+
reduction=2,
|
| 110 |
+
use_scale=True,
|
| 111 |
+
mode='embedded_gaussian',
|
| 112 |
+
temperature=0.05,
|
| 113 |
+
**kwargs):
|
| 114 |
+
super().__init__(num_convs=2, **kwargs)
|
| 115 |
+
self.reduction = reduction
|
| 116 |
+
self.use_scale = use_scale
|
| 117 |
+
self.mode = mode
|
| 118 |
+
self.temperature = temperature
|
| 119 |
+
self.dnl_block = DisentangledNonLocal2d(
|
| 120 |
+
in_channels=self.channels,
|
| 121 |
+
reduction=self.reduction,
|
| 122 |
+
use_scale=self.use_scale,
|
| 123 |
+
conv_cfg=self.conv_cfg,
|
| 124 |
+
norm_cfg=self.norm_cfg,
|
| 125 |
+
mode=self.mode,
|
| 126 |
+
temperature=self.temperature)
|
| 127 |
+
|
| 128 |
+
def forward(self, inputs):
|
| 129 |
+
"""Forward function."""
|
| 130 |
+
x = self._transform_inputs(inputs)
|
| 131 |
+
output = self.convs[0](x)
|
| 132 |
+
output = self.dnl_block(output)
|
| 133 |
+
output = self.convs[1](output)
|
| 134 |
+
if self.concat_input:
|
| 135 |
+
output = self.conv_cat(torch.cat([x, output], dim=1))
|
| 136 |
+
output = self.cls_seg(output)
|
| 137 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/dpt_head.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from mmcv.cnn import ConvModule, Linear, build_activation_layer
|
| 7 |
+
from mmengine.model import BaseModule
|
| 8 |
+
|
| 9 |
+
from mmseg.registry import MODELS
|
| 10 |
+
from ..utils import resize
|
| 11 |
+
from .decode_head import BaseDecodeHead
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ReassembleBlocks(BaseModule):
|
| 15 |
+
"""ViTPostProcessBlock, process cls_token in ViT backbone output and
|
| 16 |
+
rearrange the feature vector to feature map.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
in_channels (int): ViT feature channels. Default: 768.
|
| 20 |
+
out_channels (List): output channels of each stage.
|
| 21 |
+
Default: [96, 192, 384, 768].
|
| 22 |
+
readout_type (str): Type of readout operation. Default: 'ignore'.
|
| 23 |
+
patch_size (int): The patch size. Default: 16.
|
| 24 |
+
init_cfg (dict, optional): Initialization config dict. Default: None.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self,
|
| 28 |
+
in_channels=768,
|
| 29 |
+
out_channels=[96, 192, 384, 768],
|
| 30 |
+
readout_type='ignore',
|
| 31 |
+
patch_size=16,
|
| 32 |
+
init_cfg=None):
|
| 33 |
+
super().__init__(init_cfg)
|
| 34 |
+
|
| 35 |
+
assert readout_type in ['ignore', 'add', 'project']
|
| 36 |
+
self.readout_type = readout_type
|
| 37 |
+
self.patch_size = patch_size
|
| 38 |
+
|
| 39 |
+
self.projects = nn.ModuleList([
|
| 40 |
+
ConvModule(
|
| 41 |
+
in_channels=in_channels,
|
| 42 |
+
out_channels=out_channel,
|
| 43 |
+
kernel_size=1,
|
| 44 |
+
act_cfg=None,
|
| 45 |
+
) for out_channel in out_channels
|
| 46 |
+
])
|
| 47 |
+
|
| 48 |
+
self.resize_layers = nn.ModuleList([
|
| 49 |
+
nn.ConvTranspose2d(
|
| 50 |
+
in_channels=out_channels[0],
|
| 51 |
+
out_channels=out_channels[0],
|
| 52 |
+
kernel_size=4,
|
| 53 |
+
stride=4,
|
| 54 |
+
padding=0),
|
| 55 |
+
nn.ConvTranspose2d(
|
| 56 |
+
in_channels=out_channels[1],
|
| 57 |
+
out_channels=out_channels[1],
|
| 58 |
+
kernel_size=2,
|
| 59 |
+
stride=2,
|
| 60 |
+
padding=0),
|
| 61 |
+
nn.Identity(),
|
| 62 |
+
nn.Conv2d(
|
| 63 |
+
in_channels=out_channels[3],
|
| 64 |
+
out_channels=out_channels[3],
|
| 65 |
+
kernel_size=3,
|
| 66 |
+
stride=2,
|
| 67 |
+
padding=1)
|
| 68 |
+
])
|
| 69 |
+
if self.readout_type == 'project':
|
| 70 |
+
self.readout_projects = nn.ModuleList()
|
| 71 |
+
for _ in range(len(self.projects)):
|
| 72 |
+
self.readout_projects.append(
|
| 73 |
+
nn.Sequential(
|
| 74 |
+
Linear(2 * in_channels, in_channels),
|
| 75 |
+
build_activation_layer(dict(type='GELU'))))
|
| 76 |
+
|
| 77 |
+
def forward(self, inputs):
|
| 78 |
+
assert isinstance(inputs, list)
|
| 79 |
+
out = []
|
| 80 |
+
for i, x in enumerate(inputs):
|
| 81 |
+
assert len(x) == 2
|
| 82 |
+
x, cls_token = x[0], x[1]
|
| 83 |
+
feature_shape = x.shape
|
| 84 |
+
if self.readout_type == 'project':
|
| 85 |
+
x = x.flatten(2).permute((0, 2, 1))
|
| 86 |
+
readout = cls_token.unsqueeze(1).expand_as(x)
|
| 87 |
+
x = self.readout_projects[i](torch.cat((x, readout), -1))
|
| 88 |
+
x = x.permute(0, 2, 1).reshape(feature_shape)
|
| 89 |
+
elif self.readout_type == 'add':
|
| 90 |
+
x = x.flatten(2) + cls_token.unsqueeze(-1)
|
| 91 |
+
x = x.reshape(feature_shape)
|
| 92 |
+
else:
|
| 93 |
+
pass
|
| 94 |
+
x = self.projects[i](x)
|
| 95 |
+
x = self.resize_layers[i](x)
|
| 96 |
+
out.append(x)
|
| 97 |
+
return out
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class PreActResidualConvUnit(BaseModule):
|
| 101 |
+
"""ResidualConvUnit, pre-activate residual unit.
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
in_channels (int): number of channels in the input feature map.
|
| 105 |
+
act_cfg (dict): dictionary to construct and config activation layer.
|
| 106 |
+
norm_cfg (dict): dictionary to construct and config norm layer.
|
| 107 |
+
stride (int): stride of the first block. Default: 1
|
| 108 |
+
dilation (int): dilation rate for convs layers. Default: 1.
|
| 109 |
+
init_cfg (dict, optional): Initialization config dict. Default: None.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self,
|
| 113 |
+
in_channels,
|
| 114 |
+
act_cfg,
|
| 115 |
+
norm_cfg,
|
| 116 |
+
stride=1,
|
| 117 |
+
dilation=1,
|
| 118 |
+
init_cfg=None):
|
| 119 |
+
super().__init__(init_cfg)
|
| 120 |
+
|
| 121 |
+
self.conv1 = ConvModule(
|
| 122 |
+
in_channels,
|
| 123 |
+
in_channels,
|
| 124 |
+
3,
|
| 125 |
+
stride=stride,
|
| 126 |
+
padding=dilation,
|
| 127 |
+
dilation=dilation,
|
| 128 |
+
norm_cfg=norm_cfg,
|
| 129 |
+
act_cfg=act_cfg,
|
| 130 |
+
bias=False,
|
| 131 |
+
order=('act', 'conv', 'norm'))
|
| 132 |
+
|
| 133 |
+
self.conv2 = ConvModule(
|
| 134 |
+
in_channels,
|
| 135 |
+
in_channels,
|
| 136 |
+
3,
|
| 137 |
+
padding=1,
|
| 138 |
+
norm_cfg=norm_cfg,
|
| 139 |
+
act_cfg=act_cfg,
|
| 140 |
+
bias=False,
|
| 141 |
+
order=('act', 'conv', 'norm'))
|
| 142 |
+
|
| 143 |
+
def forward(self, inputs):
|
| 144 |
+
inputs_ = inputs.clone()
|
| 145 |
+
x = self.conv1(inputs)
|
| 146 |
+
x = self.conv2(x)
|
| 147 |
+
return x + inputs_
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class FeatureFusionBlock(BaseModule):
|
| 151 |
+
"""FeatureFusionBlock, merge feature map from different stages.
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
in_channels (int): Input channels.
|
| 155 |
+
act_cfg (dict): The activation config for ResidualConvUnit.
|
| 156 |
+
norm_cfg (dict): Config dict for normalization layer.
|
| 157 |
+
expand (bool): Whether expand the channels in post process block.
|
| 158 |
+
Default: False.
|
| 159 |
+
align_corners (bool): align_corner setting for bilinear upsample.
|
| 160 |
+
Default: True.
|
| 161 |
+
init_cfg (dict, optional): Initialization config dict. Default: None.
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
def __init__(self,
|
| 165 |
+
in_channels,
|
| 166 |
+
act_cfg,
|
| 167 |
+
norm_cfg,
|
| 168 |
+
expand=False,
|
| 169 |
+
align_corners=True,
|
| 170 |
+
init_cfg=None):
|
| 171 |
+
super().__init__(init_cfg)
|
| 172 |
+
|
| 173 |
+
self.in_channels = in_channels
|
| 174 |
+
self.expand = expand
|
| 175 |
+
self.align_corners = align_corners
|
| 176 |
+
|
| 177 |
+
self.out_channels = in_channels
|
| 178 |
+
if self.expand:
|
| 179 |
+
self.out_channels = in_channels // 2
|
| 180 |
+
|
| 181 |
+
self.project = ConvModule(
|
| 182 |
+
self.in_channels,
|
| 183 |
+
self.out_channels,
|
| 184 |
+
kernel_size=1,
|
| 185 |
+
act_cfg=None,
|
| 186 |
+
bias=True)
|
| 187 |
+
|
| 188 |
+
self.res_conv_unit1 = PreActResidualConvUnit(
|
| 189 |
+
in_channels=self.in_channels, act_cfg=act_cfg, norm_cfg=norm_cfg)
|
| 190 |
+
self.res_conv_unit2 = PreActResidualConvUnit(
|
| 191 |
+
in_channels=self.in_channels, act_cfg=act_cfg, norm_cfg=norm_cfg)
|
| 192 |
+
|
| 193 |
+
def forward(self, *inputs):
|
| 194 |
+
x = inputs[0]
|
| 195 |
+
if len(inputs) == 2:
|
| 196 |
+
if x.shape != inputs[1].shape:
|
| 197 |
+
res = resize(
|
| 198 |
+
inputs[1],
|
| 199 |
+
size=(x.shape[2], x.shape[3]),
|
| 200 |
+
mode='bilinear',
|
| 201 |
+
align_corners=False)
|
| 202 |
+
else:
|
| 203 |
+
res = inputs[1]
|
| 204 |
+
x = x + self.res_conv_unit1(res)
|
| 205 |
+
x = self.res_conv_unit2(x)
|
| 206 |
+
x = resize(
|
| 207 |
+
x,
|
| 208 |
+
scale_factor=2,
|
| 209 |
+
mode='bilinear',
|
| 210 |
+
align_corners=self.align_corners)
|
| 211 |
+
x = self.project(x)
|
| 212 |
+
return x
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@MODELS.register_module()
|
| 216 |
+
class DPTHead(BaseDecodeHead):
|
| 217 |
+
"""Vision Transformers for Dense Prediction.
|
| 218 |
+
|
| 219 |
+
This head is implemented of `DPT <https://arxiv.org/abs/2103.13413>`_.
|
| 220 |
+
|
| 221 |
+
Args:
|
| 222 |
+
embed_dims (int): The embed dimension of the ViT backbone.
|
| 223 |
+
Default: 768.
|
| 224 |
+
post_process_channels (List): Out channels of post process conv
|
| 225 |
+
layers. Default: [96, 192, 384, 768].
|
| 226 |
+
readout_type (str): Type of readout operation. Default: 'ignore'.
|
| 227 |
+
patch_size (int): The patch size. Default: 16.
|
| 228 |
+
expand_channels (bool): Whether expand the channels in post process
|
| 229 |
+
block. Default: False.
|
| 230 |
+
act_cfg (dict): The activation config for residual conv unit.
|
| 231 |
+
Default dict(type='ReLU').
|
| 232 |
+
norm_cfg (dict): Config dict for normalization layer.
|
| 233 |
+
Default: dict(type='BN').
|
| 234 |
+
"""
|
| 235 |
+
|
| 236 |
+
def __init__(self,
|
| 237 |
+
embed_dims=768,
|
| 238 |
+
post_process_channels=[96, 192, 384, 768],
|
| 239 |
+
readout_type='ignore',
|
| 240 |
+
patch_size=16,
|
| 241 |
+
expand_channels=False,
|
| 242 |
+
act_cfg=dict(type='ReLU'),
|
| 243 |
+
norm_cfg=dict(type='BN'),
|
| 244 |
+
**kwargs):
|
| 245 |
+
super().__init__(**kwargs)
|
| 246 |
+
|
| 247 |
+
self.in_channels = self.in_channels
|
| 248 |
+
self.expand_channels = expand_channels
|
| 249 |
+
self.reassemble_blocks = ReassembleBlocks(embed_dims,
|
| 250 |
+
post_process_channels,
|
| 251 |
+
readout_type, patch_size)
|
| 252 |
+
|
| 253 |
+
self.post_process_channels = [
|
| 254 |
+
channel * math.pow(2, i) if expand_channels else channel
|
| 255 |
+
for i, channel in enumerate(post_process_channels)
|
| 256 |
+
]
|
| 257 |
+
self.convs = nn.ModuleList()
|
| 258 |
+
for channel in self.post_process_channels:
|
| 259 |
+
self.convs.append(
|
| 260 |
+
ConvModule(
|
| 261 |
+
channel,
|
| 262 |
+
self.channels,
|
| 263 |
+
kernel_size=3,
|
| 264 |
+
padding=1,
|
| 265 |
+
act_cfg=None,
|
| 266 |
+
bias=False))
|
| 267 |
+
self.fusion_blocks = nn.ModuleList()
|
| 268 |
+
for _ in range(len(self.convs)):
|
| 269 |
+
self.fusion_blocks.append(
|
| 270 |
+
FeatureFusionBlock(self.channels, act_cfg, norm_cfg))
|
| 271 |
+
self.fusion_blocks[0].res_conv_unit1 = None
|
| 272 |
+
self.project = ConvModule(
|
| 273 |
+
self.channels,
|
| 274 |
+
self.channels,
|
| 275 |
+
kernel_size=3,
|
| 276 |
+
padding=1,
|
| 277 |
+
norm_cfg=norm_cfg)
|
| 278 |
+
self.num_fusion_blocks = len(self.fusion_blocks)
|
| 279 |
+
self.num_reassemble_blocks = len(self.reassemble_blocks.resize_layers)
|
| 280 |
+
self.num_post_process_channels = len(self.post_process_channels)
|
| 281 |
+
assert self.num_fusion_blocks == self.num_reassemble_blocks
|
| 282 |
+
assert self.num_reassemble_blocks == self.num_post_process_channels
|
| 283 |
+
|
| 284 |
+
def forward(self, inputs):
|
| 285 |
+
assert len(inputs) == self.num_reassemble_blocks
|
| 286 |
+
x = self._transform_inputs(inputs)
|
| 287 |
+
x = self.reassemble_blocks(x)
|
| 288 |
+
x = [self.convs[i](feature) for i, feature in enumerate(x)]
|
| 289 |
+
out = self.fusion_blocks[0](x[-1])
|
| 290 |
+
for i in range(1, len(self.fusion_blocks)):
|
| 291 |
+
out = self.fusion_blocks[i](out, x[-(i + 1)])
|
| 292 |
+
out = self.project(out)
|
| 293 |
+
out = self.cls_seg(out)
|
| 294 |
+
return out
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/ema_head.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from mmcv.cnn import ConvModule
|
| 9 |
+
|
| 10 |
+
from mmseg.registry import MODELS
|
| 11 |
+
from .decode_head import BaseDecodeHead
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def reduce_mean(tensor):
|
| 15 |
+
"""Reduce mean when distributed training."""
|
| 16 |
+
if not (dist.is_available() and dist.is_initialized()):
|
| 17 |
+
return tensor
|
| 18 |
+
tensor = tensor.clone()
|
| 19 |
+
dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM)
|
| 20 |
+
return tensor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class EMAModule(nn.Module):
|
| 24 |
+
"""Expectation Maximization Attention Module used in EMANet.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
channels (int): Channels of the whole module.
|
| 28 |
+
num_bases (int): Number of bases.
|
| 29 |
+
num_stages (int): Number of the EM iterations.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, channels, num_bases, num_stages, momentum):
|
| 33 |
+
super().__init__()
|
| 34 |
+
assert num_stages >= 1, 'num_stages must be at least 1!'
|
| 35 |
+
self.num_bases = num_bases
|
| 36 |
+
self.num_stages = num_stages
|
| 37 |
+
self.momentum = momentum
|
| 38 |
+
|
| 39 |
+
bases = torch.zeros(1, channels, self.num_bases)
|
| 40 |
+
bases.normal_(0, math.sqrt(2. / self.num_bases))
|
| 41 |
+
# [1, channels, num_bases]
|
| 42 |
+
bases = F.normalize(bases, dim=1, p=2)
|
| 43 |
+
self.register_buffer('bases', bases)
|
| 44 |
+
|
| 45 |
+
def forward(self, feats):
|
| 46 |
+
"""Forward function."""
|
| 47 |
+
batch_size, channels, height, width = feats.size()
|
| 48 |
+
# [batch_size, channels, height*width]
|
| 49 |
+
feats = feats.view(batch_size, channels, height * width)
|
| 50 |
+
# [batch_size, channels, num_bases]
|
| 51 |
+
bases = self.bases.repeat(batch_size, 1, 1)
|
| 52 |
+
|
| 53 |
+
with torch.no_grad():
|
| 54 |
+
for i in range(self.num_stages):
|
| 55 |
+
# [batch_size, height*width, num_bases]
|
| 56 |
+
attention = torch.einsum('bcn,bck->bnk', feats, bases)
|
| 57 |
+
attention = F.softmax(attention, dim=2)
|
| 58 |
+
# l1 norm
|
| 59 |
+
attention_normed = F.normalize(attention, dim=1, p=1)
|
| 60 |
+
# [batch_size, channels, num_bases]
|
| 61 |
+
bases = torch.einsum('bcn,bnk->bck', feats, attention_normed)
|
| 62 |
+
# l2 norm
|
| 63 |
+
bases = F.normalize(bases, dim=1, p=2)
|
| 64 |
+
|
| 65 |
+
feats_recon = torch.einsum('bck,bnk->bcn', bases, attention)
|
| 66 |
+
feats_recon = feats_recon.view(batch_size, channels, height, width)
|
| 67 |
+
|
| 68 |
+
if self.training:
|
| 69 |
+
bases = bases.mean(dim=0, keepdim=True)
|
| 70 |
+
bases = reduce_mean(bases)
|
| 71 |
+
# l2 norm
|
| 72 |
+
bases = F.normalize(bases, dim=1, p=2)
|
| 73 |
+
self.bases = (1 -
|
| 74 |
+
self.momentum) * self.bases + self.momentum * bases
|
| 75 |
+
|
| 76 |
+
return feats_recon
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@MODELS.register_module()
|
| 80 |
+
class EMAHead(BaseDecodeHead):
|
| 81 |
+
"""Expectation Maximization Attention Networks for Semantic Segmentation.
|
| 82 |
+
|
| 83 |
+
This head is the implementation of `EMANet
|
| 84 |
+
<https://arxiv.org/abs/1907.13426>`_.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
ema_channels (int): EMA module channels
|
| 88 |
+
num_bases (int): Number of bases.
|
| 89 |
+
num_stages (int): Number of the EM iterations.
|
| 90 |
+
concat_input (bool): Whether concat the input and output of convs
|
| 91 |
+
before classification layer. Default: True
|
| 92 |
+
momentum (float): Momentum to update the base. Default: 0.1.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(self,
|
| 96 |
+
ema_channels,
|
| 97 |
+
num_bases,
|
| 98 |
+
num_stages,
|
| 99 |
+
concat_input=True,
|
| 100 |
+
momentum=0.1,
|
| 101 |
+
**kwargs):
|
| 102 |
+
super().__init__(**kwargs)
|
| 103 |
+
self.ema_channels = ema_channels
|
| 104 |
+
self.num_bases = num_bases
|
| 105 |
+
self.num_stages = num_stages
|
| 106 |
+
self.concat_input = concat_input
|
| 107 |
+
self.momentum = momentum
|
| 108 |
+
self.ema_module = EMAModule(self.ema_channels, self.num_bases,
|
| 109 |
+
self.num_stages, self.momentum)
|
| 110 |
+
|
| 111 |
+
self.ema_in_conv = ConvModule(
|
| 112 |
+
self.in_channels,
|
| 113 |
+
self.ema_channels,
|
| 114 |
+
3,
|
| 115 |
+
padding=1,
|
| 116 |
+
conv_cfg=self.conv_cfg,
|
| 117 |
+
norm_cfg=self.norm_cfg,
|
| 118 |
+
act_cfg=self.act_cfg)
|
| 119 |
+
# project (0, inf) -> (-inf, inf)
|
| 120 |
+
self.ema_mid_conv = ConvModule(
|
| 121 |
+
self.ema_channels,
|
| 122 |
+
self.ema_channels,
|
| 123 |
+
1,
|
| 124 |
+
conv_cfg=self.conv_cfg,
|
| 125 |
+
norm_cfg=None,
|
| 126 |
+
act_cfg=None)
|
| 127 |
+
for param in self.ema_mid_conv.parameters():
|
| 128 |
+
param.requires_grad = False
|
| 129 |
+
|
| 130 |
+
self.ema_out_conv = ConvModule(
|
| 131 |
+
self.ema_channels,
|
| 132 |
+
self.ema_channels,
|
| 133 |
+
1,
|
| 134 |
+
conv_cfg=self.conv_cfg,
|
| 135 |
+
norm_cfg=self.norm_cfg,
|
| 136 |
+
act_cfg=None)
|
| 137 |
+
self.bottleneck = ConvModule(
|
| 138 |
+
self.ema_channels,
|
| 139 |
+
self.channels,
|
| 140 |
+
3,
|
| 141 |
+
padding=1,
|
| 142 |
+
conv_cfg=self.conv_cfg,
|
| 143 |
+
norm_cfg=self.norm_cfg,
|
| 144 |
+
act_cfg=self.act_cfg)
|
| 145 |
+
if self.concat_input:
|
| 146 |
+
self.conv_cat = ConvModule(
|
| 147 |
+
self.in_channels + self.channels,
|
| 148 |
+
self.channels,
|
| 149 |
+
kernel_size=3,
|
| 150 |
+
padding=1,
|
| 151 |
+
conv_cfg=self.conv_cfg,
|
| 152 |
+
norm_cfg=self.norm_cfg,
|
| 153 |
+
act_cfg=self.act_cfg)
|
| 154 |
+
|
| 155 |
+
def forward(self, inputs):
|
| 156 |
+
"""Forward function."""
|
| 157 |
+
x = self._transform_inputs(inputs)
|
| 158 |
+
feats = self.ema_in_conv(x)
|
| 159 |
+
identity = feats
|
| 160 |
+
feats = self.ema_mid_conv(feats)
|
| 161 |
+
recon = self.ema_module(feats)
|
| 162 |
+
recon = F.relu(recon, inplace=True)
|
| 163 |
+
recon = self.ema_out_conv(recon)
|
| 164 |
+
output = F.relu(identity + recon, inplace=True)
|
| 165 |
+
output = self.bottleneck(output)
|
| 166 |
+
if self.concat_input:
|
| 167 |
+
output = self.conv_cat(torch.cat([x, output], dim=1))
|
| 168 |
+
output = self.cls_seg(output)
|
| 169 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/enc_head.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from mmcv.cnn import ConvModule, build_norm_layer
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
|
| 10 |
+
from mmseg.registry import MODELS
|
| 11 |
+
from mmseg.utils import ConfigType, SampleList
|
| 12 |
+
from ..utils import Encoding, resize
|
| 13 |
+
from .decode_head import BaseDecodeHead
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class EncModule(nn.Module):
|
| 17 |
+
"""Encoding Module used in EncNet.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
in_channels (int): Input channels.
|
| 21 |
+
num_codes (int): Number of code words.
|
| 22 |
+
conv_cfg (dict|None): Config of conv layers.
|
| 23 |
+
norm_cfg (dict|None): Config of norm layers.
|
| 24 |
+
act_cfg (dict): Config of activation layers.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, in_channels, num_codes, conv_cfg, norm_cfg, act_cfg):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.encoding_project = ConvModule(
|
| 30 |
+
in_channels,
|
| 31 |
+
in_channels,
|
| 32 |
+
1,
|
| 33 |
+
conv_cfg=conv_cfg,
|
| 34 |
+
norm_cfg=norm_cfg,
|
| 35 |
+
act_cfg=act_cfg)
|
| 36 |
+
# TODO: resolve this hack
|
| 37 |
+
# change to 1d
|
| 38 |
+
if norm_cfg is not None:
|
| 39 |
+
encoding_norm_cfg = norm_cfg.copy()
|
| 40 |
+
if encoding_norm_cfg['type'] in ['BN', 'IN']:
|
| 41 |
+
encoding_norm_cfg['type'] += '1d'
|
| 42 |
+
else:
|
| 43 |
+
encoding_norm_cfg['type'] = encoding_norm_cfg['type'].replace(
|
| 44 |
+
'2d', '1d')
|
| 45 |
+
else:
|
| 46 |
+
# fallback to BN1d
|
| 47 |
+
encoding_norm_cfg = dict(type='BN1d')
|
| 48 |
+
self.encoding = nn.Sequential(
|
| 49 |
+
Encoding(channels=in_channels, num_codes=num_codes),
|
| 50 |
+
build_norm_layer(encoding_norm_cfg, num_codes)[1],
|
| 51 |
+
nn.ReLU(inplace=True))
|
| 52 |
+
self.fc = nn.Sequential(
|
| 53 |
+
nn.Linear(in_channels, in_channels), nn.Sigmoid())
|
| 54 |
+
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
"""Forward function."""
|
| 57 |
+
encoding_projection = self.encoding_project(x)
|
| 58 |
+
encoding_feat = self.encoding(encoding_projection).mean(dim=1)
|
| 59 |
+
batch_size, channels, _, _ = x.size()
|
| 60 |
+
gamma = self.fc(encoding_feat)
|
| 61 |
+
y = gamma.view(batch_size, channels, 1, 1)
|
| 62 |
+
output = F.relu_(x + x * y)
|
| 63 |
+
return encoding_feat, output
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@MODELS.register_module()
|
| 67 |
+
class EncHead(BaseDecodeHead):
|
| 68 |
+
"""Context Encoding for Semantic Segmentation.
|
| 69 |
+
|
| 70 |
+
This head is the implementation of `EncNet
|
| 71 |
+
<https://arxiv.org/abs/1803.08904>`_.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
num_codes (int): Number of code words. Default: 32.
|
| 75 |
+
use_se_loss (bool): Whether use Semantic Encoding Loss (SE-loss) to
|
| 76 |
+
regularize the training. Default: True.
|
| 77 |
+
add_lateral (bool): Whether use lateral connection to fuse features.
|
| 78 |
+
Default: False.
|
| 79 |
+
loss_se_decode (dict): Config of decode loss.
|
| 80 |
+
Default: dict(type='CrossEntropyLoss', use_sigmoid=True).
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(self,
|
| 84 |
+
num_codes=32,
|
| 85 |
+
use_se_loss=True,
|
| 86 |
+
add_lateral=False,
|
| 87 |
+
loss_se_decode=dict(
|
| 88 |
+
type='CrossEntropyLoss',
|
| 89 |
+
use_sigmoid=True,
|
| 90 |
+
loss_weight=0.2),
|
| 91 |
+
**kwargs):
|
| 92 |
+
super().__init__(input_transform='multiple_select', **kwargs)
|
| 93 |
+
self.use_se_loss = use_se_loss
|
| 94 |
+
self.add_lateral = add_lateral
|
| 95 |
+
self.num_codes = num_codes
|
| 96 |
+
self.bottleneck = ConvModule(
|
| 97 |
+
self.in_channels[-1],
|
| 98 |
+
self.channels,
|
| 99 |
+
3,
|
| 100 |
+
padding=1,
|
| 101 |
+
conv_cfg=self.conv_cfg,
|
| 102 |
+
norm_cfg=self.norm_cfg,
|
| 103 |
+
act_cfg=self.act_cfg)
|
| 104 |
+
if add_lateral:
|
| 105 |
+
self.lateral_convs = nn.ModuleList()
|
| 106 |
+
for in_channels in self.in_channels[:-1]: # skip the last one
|
| 107 |
+
self.lateral_convs.append(
|
| 108 |
+
ConvModule(
|
| 109 |
+
in_channels,
|
| 110 |
+
self.channels,
|
| 111 |
+
1,
|
| 112 |
+
conv_cfg=self.conv_cfg,
|
| 113 |
+
norm_cfg=self.norm_cfg,
|
| 114 |
+
act_cfg=self.act_cfg))
|
| 115 |
+
self.fusion = ConvModule(
|
| 116 |
+
len(self.in_channels) * self.channels,
|
| 117 |
+
self.channels,
|
| 118 |
+
3,
|
| 119 |
+
padding=1,
|
| 120 |
+
conv_cfg=self.conv_cfg,
|
| 121 |
+
norm_cfg=self.norm_cfg,
|
| 122 |
+
act_cfg=self.act_cfg)
|
| 123 |
+
self.enc_module = EncModule(
|
| 124 |
+
self.channels,
|
| 125 |
+
num_codes=num_codes,
|
| 126 |
+
conv_cfg=self.conv_cfg,
|
| 127 |
+
norm_cfg=self.norm_cfg,
|
| 128 |
+
act_cfg=self.act_cfg)
|
| 129 |
+
if self.use_se_loss:
|
| 130 |
+
self.loss_se_decode = MODELS.build(loss_se_decode)
|
| 131 |
+
self.se_layer = nn.Linear(self.channels, self.num_classes)
|
| 132 |
+
|
| 133 |
+
def forward(self, inputs):
|
| 134 |
+
"""Forward function."""
|
| 135 |
+
inputs = self._transform_inputs(inputs)
|
| 136 |
+
feat = self.bottleneck(inputs[-1])
|
| 137 |
+
if self.add_lateral:
|
| 138 |
+
laterals = [
|
| 139 |
+
resize(
|
| 140 |
+
lateral_conv(inputs[i]),
|
| 141 |
+
size=feat.shape[2:],
|
| 142 |
+
mode='bilinear',
|
| 143 |
+
align_corners=self.align_corners)
|
| 144 |
+
for i, lateral_conv in enumerate(self.lateral_convs)
|
| 145 |
+
]
|
| 146 |
+
feat = self.fusion(torch.cat([feat, *laterals], 1))
|
| 147 |
+
encode_feat, output = self.enc_module(feat)
|
| 148 |
+
output = self.cls_seg(output)
|
| 149 |
+
if self.use_se_loss:
|
| 150 |
+
se_output = self.se_layer(encode_feat)
|
| 151 |
+
return output, se_output
|
| 152 |
+
else:
|
| 153 |
+
return output
|
| 154 |
+
|
| 155 |
+
def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict],
|
| 156 |
+
test_cfg: ConfigType):
|
| 157 |
+
"""Forward function for testing, ignore se_loss."""
|
| 158 |
+
if self.use_se_loss:
|
| 159 |
+
seg_logits = self.forward(inputs)[0]
|
| 160 |
+
else:
|
| 161 |
+
seg_logits = self.forward(inputs)
|
| 162 |
+
return self.predict_by_feat(seg_logits, batch_img_metas)
|
| 163 |
+
|
| 164 |
+
@staticmethod
|
| 165 |
+
def _convert_to_onehot_labels(seg_label, num_classes):
|
| 166 |
+
"""Convert segmentation label to onehot.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
seg_label (Tensor): Segmentation label of shape (N, H, W).
|
| 170 |
+
num_classes (int): Number of classes.
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
Tensor: Onehot labels of shape (N, num_classes).
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
batch_size = seg_label.size(0)
|
| 177 |
+
onehot_labels = seg_label.new_zeros((batch_size, num_classes))
|
| 178 |
+
for i in range(batch_size):
|
| 179 |
+
hist = seg_label[i].float().histc(
|
| 180 |
+
bins=num_classes, min=0, max=num_classes - 1)
|
| 181 |
+
onehot_labels[i] = hist > 0
|
| 182 |
+
return onehot_labels
|
| 183 |
+
|
| 184 |
+
def loss_by_feat(self, seg_logit: Tuple[Tensor],
|
| 185 |
+
batch_data_samples: SampleList, **kwargs) -> dict:
|
| 186 |
+
"""Compute segmentation and semantic encoding loss."""
|
| 187 |
+
seg_logit, se_seg_logit = seg_logit
|
| 188 |
+
loss = dict()
|
| 189 |
+
loss.update(super().loss_by_feat(seg_logit, batch_data_samples))
|
| 190 |
+
|
| 191 |
+
seg_label = self._stack_batch_gt(batch_data_samples)
|
| 192 |
+
se_loss = self.loss_se_decode(
|
| 193 |
+
se_seg_logit,
|
| 194 |
+
self._convert_to_onehot_labels(seg_label, self.num_classes))
|
| 195 |
+
loss['loss_se'] = se_loss
|
| 196 |
+
return loss
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/fcn_head.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from .decode_head import BaseDecodeHead
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@MODELS.register_module()
|
| 11 |
+
class FCNHead(BaseDecodeHead):
|
| 12 |
+
"""Fully Convolution Networks for Semantic Segmentation.
|
| 13 |
+
|
| 14 |
+
This head is implemented of `FCNNet <https://arxiv.org/abs/1411.4038>`_.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
num_convs (int): Number of convs in the head. Default: 2.
|
| 18 |
+
kernel_size (int): The kernel size for convs in the head. Default: 3.
|
| 19 |
+
concat_input (bool): Whether concat the input and output of convs
|
| 20 |
+
before classification layer.
|
| 21 |
+
dilation (int): The dilation rate for convs in the head. Default: 1.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self,
|
| 25 |
+
num_convs=2,
|
| 26 |
+
kernel_size=3,
|
| 27 |
+
concat_input=True,
|
| 28 |
+
dilation=1,
|
| 29 |
+
**kwargs):
|
| 30 |
+
assert num_convs >= 0 and dilation > 0 and isinstance(dilation, int)
|
| 31 |
+
self.num_convs = num_convs
|
| 32 |
+
self.concat_input = concat_input
|
| 33 |
+
self.kernel_size = kernel_size
|
| 34 |
+
super().__init__(**kwargs)
|
| 35 |
+
if num_convs == 0:
|
| 36 |
+
assert self.in_channels == self.channels
|
| 37 |
+
|
| 38 |
+
conv_padding = (kernel_size // 2) * dilation
|
| 39 |
+
convs = []
|
| 40 |
+
convs.append(
|
| 41 |
+
ConvModule(
|
| 42 |
+
self.in_channels,
|
| 43 |
+
self.channels,
|
| 44 |
+
kernel_size=kernel_size,
|
| 45 |
+
padding=conv_padding,
|
| 46 |
+
dilation=dilation,
|
| 47 |
+
conv_cfg=self.conv_cfg,
|
| 48 |
+
norm_cfg=self.norm_cfg,
|
| 49 |
+
act_cfg=self.act_cfg))
|
| 50 |
+
for i in range(num_convs - 1):
|
| 51 |
+
convs.append(
|
| 52 |
+
ConvModule(
|
| 53 |
+
self.channels,
|
| 54 |
+
self.channels,
|
| 55 |
+
kernel_size=kernel_size,
|
| 56 |
+
padding=conv_padding,
|
| 57 |
+
dilation=dilation,
|
| 58 |
+
conv_cfg=self.conv_cfg,
|
| 59 |
+
norm_cfg=self.norm_cfg,
|
| 60 |
+
act_cfg=self.act_cfg))
|
| 61 |
+
if num_convs == 0:
|
| 62 |
+
self.convs = nn.Identity()
|
| 63 |
+
else:
|
| 64 |
+
self.convs = nn.Sequential(*convs)
|
| 65 |
+
if self.concat_input:
|
| 66 |
+
self.conv_cat = ConvModule(
|
| 67 |
+
self.in_channels + self.channels,
|
| 68 |
+
self.channels,
|
| 69 |
+
kernel_size=kernel_size,
|
| 70 |
+
padding=kernel_size // 2,
|
| 71 |
+
conv_cfg=self.conv_cfg,
|
| 72 |
+
norm_cfg=self.norm_cfg,
|
| 73 |
+
act_cfg=self.act_cfg)
|
| 74 |
+
|
| 75 |
+
def _forward_feature(self, inputs):
|
| 76 |
+
"""Forward function for feature maps before classifying each pixel with
|
| 77 |
+
``self.cls_seg`` fc.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
inputs (list[Tensor]): List of multi-level img features.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
feats (Tensor): A tensor of shape (batch_size, self.channels,
|
| 84 |
+
H, W) which is feature map for last layer of decoder head.
|
| 85 |
+
"""
|
| 86 |
+
x = self._transform_inputs(inputs)
|
| 87 |
+
feats = self.convs(x)
|
| 88 |
+
if self.concat_input:
|
| 89 |
+
feats = self.conv_cat(torch.cat([x, feats], dim=1))
|
| 90 |
+
return feats
|
| 91 |
+
|
| 92 |
+
def forward(self, inputs):
|
| 93 |
+
"""Forward function."""
|
| 94 |
+
output = self._forward_feature(inputs)
|
| 95 |
+
output = self.cls_seg(output)
|
| 96 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/fpn_head.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from ..utils import Upsample, resize
|
| 8 |
+
from .decode_head import BaseDecodeHead
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@MODELS.register_module()
|
| 12 |
+
class FPNHead(BaseDecodeHead):
|
| 13 |
+
"""Panoptic Feature Pyramid Networks.
|
| 14 |
+
|
| 15 |
+
This head is the implementation of `Semantic FPN
|
| 16 |
+
<https://arxiv.org/abs/1901.02446>`_.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
feature_strides (tuple[int]): The strides for input feature maps.
|
| 20 |
+
stack_lateral. All strides suppose to be power of 2. The first
|
| 21 |
+
one is of largest resolution.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, feature_strides, **kwargs):
|
| 25 |
+
super().__init__(input_transform='multiple_select', **kwargs)
|
| 26 |
+
assert len(feature_strides) == len(self.in_channels)
|
| 27 |
+
assert min(feature_strides) == feature_strides[0]
|
| 28 |
+
self.feature_strides = feature_strides
|
| 29 |
+
|
| 30 |
+
self.scale_heads = nn.ModuleList()
|
| 31 |
+
for i in range(len(feature_strides)):
|
| 32 |
+
head_length = max(
|
| 33 |
+
1,
|
| 34 |
+
int(np.log2(feature_strides[i]) - np.log2(feature_strides[0])))
|
| 35 |
+
scale_head = []
|
| 36 |
+
for k in range(head_length):
|
| 37 |
+
scale_head.append(
|
| 38 |
+
ConvModule(
|
| 39 |
+
self.in_channels[i] if k == 0 else self.channels,
|
| 40 |
+
self.channels,
|
| 41 |
+
3,
|
| 42 |
+
padding=1,
|
| 43 |
+
conv_cfg=self.conv_cfg,
|
| 44 |
+
norm_cfg=self.norm_cfg,
|
| 45 |
+
act_cfg=self.act_cfg))
|
| 46 |
+
if feature_strides[i] != feature_strides[0]:
|
| 47 |
+
scale_head.append(
|
| 48 |
+
Upsample(
|
| 49 |
+
scale_factor=2,
|
| 50 |
+
mode='bilinear',
|
| 51 |
+
align_corners=self.align_corners))
|
| 52 |
+
self.scale_heads.append(nn.Sequential(*scale_head))
|
| 53 |
+
|
| 54 |
+
def forward(self, inputs):
|
| 55 |
+
|
| 56 |
+
x = self._transform_inputs(inputs)
|
| 57 |
+
|
| 58 |
+
output = self.scale_heads[0](x[0])
|
| 59 |
+
for i in range(1, len(self.feature_strides)):
|
| 60 |
+
# non inplace
|
| 61 |
+
output = output + resize(
|
| 62 |
+
self.scale_heads[i](x[i]),
|
| 63 |
+
size=output.shape[2:],
|
| 64 |
+
mode='bilinear',
|
| 65 |
+
align_corners=self.align_corners)
|
| 66 |
+
|
| 67 |
+
output = self.cls_seg(output)
|
| 68 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/gc_head.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
from mmcv.cnn import ContextBlock
|
| 4 |
+
|
| 5 |
+
from mmseg.registry import MODELS
|
| 6 |
+
from .fcn_head import FCNHead
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@MODELS.register_module()
|
| 10 |
+
class GCHead(FCNHead):
|
| 11 |
+
"""GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond.
|
| 12 |
+
|
| 13 |
+
This head is the implementation of `GCNet
|
| 14 |
+
<https://arxiv.org/abs/1904.11492>`_.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
ratio (float): Multiplier of channels ratio. Default: 1/4.
|
| 18 |
+
pooling_type (str): The pooling type of context aggregation.
|
| 19 |
+
Options are 'att', 'avg'. Default: 'avg'.
|
| 20 |
+
fusion_types (tuple[str]): The fusion type for feature fusion.
|
| 21 |
+
Options are 'channel_add', 'channel_mul'. Default: ('channel_add',)
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self,
|
| 25 |
+
ratio=1 / 4.,
|
| 26 |
+
pooling_type='att',
|
| 27 |
+
fusion_types=('channel_add', ),
|
| 28 |
+
**kwargs):
|
| 29 |
+
super().__init__(num_convs=2, **kwargs)
|
| 30 |
+
self.ratio = ratio
|
| 31 |
+
self.pooling_type = pooling_type
|
| 32 |
+
self.fusion_types = fusion_types
|
| 33 |
+
self.gc_block = ContextBlock(
|
| 34 |
+
in_channels=self.channels,
|
| 35 |
+
ratio=self.ratio,
|
| 36 |
+
pooling_type=self.pooling_type,
|
| 37 |
+
fusion_types=self.fusion_types)
|
| 38 |
+
|
| 39 |
+
def forward(self, inputs):
|
| 40 |
+
"""Forward function."""
|
| 41 |
+
x = self._transform_inputs(inputs)
|
| 42 |
+
output = self.convs[0](x)
|
| 43 |
+
output = self.gc_block(output)
|
| 44 |
+
output = self.convs[1](output)
|
| 45 |
+
if self.concat_input:
|
| 46 |
+
output = self.conv_cat(torch.cat([x, output], dim=1))
|
| 47 |
+
output = self.cls_seg(output)
|
| 48 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/ham_head.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
# Originally from https://github.com/visual-attention-network/segnext
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License")
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from mmcv.cnn import ConvModule
|
| 8 |
+
from mmengine.device import get_device
|
| 9 |
+
|
| 10 |
+
from mmseg.registry import MODELS
|
| 11 |
+
from ..utils import resize
|
| 12 |
+
from .decode_head import BaseDecodeHead
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Matrix_Decomposition_2D_Base(nn.Module):
|
| 16 |
+
"""Base class of 2D Matrix Decomposition.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
MD_S (int): The number of spatial coefficient in
|
| 20 |
+
Matrix Decomposition, it may be used for calculation
|
| 21 |
+
of the number of latent dimension D in Matrix
|
| 22 |
+
Decomposition. Defaults: 1.
|
| 23 |
+
MD_R (int): The number of latent dimension R in
|
| 24 |
+
Matrix Decomposition. Defaults: 64.
|
| 25 |
+
train_steps (int): The number of iteration steps in
|
| 26 |
+
Multiplicative Update (MU) rule to solve Non-negative
|
| 27 |
+
Matrix Factorization (NMF) in training. Defaults: 6.
|
| 28 |
+
eval_steps (int): The number of iteration steps in
|
| 29 |
+
Multiplicative Update (MU) rule to solve Non-negative
|
| 30 |
+
Matrix Factorization (NMF) in evaluation. Defaults: 7.
|
| 31 |
+
inv_t (int): Inverted multiple number to make coefficient
|
| 32 |
+
smaller in softmax. Defaults: 100.
|
| 33 |
+
rand_init (bool): Whether to initialize randomly.
|
| 34 |
+
Defaults: True.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self,
|
| 38 |
+
MD_S=1,
|
| 39 |
+
MD_R=64,
|
| 40 |
+
train_steps=6,
|
| 41 |
+
eval_steps=7,
|
| 42 |
+
inv_t=100,
|
| 43 |
+
rand_init=True):
|
| 44 |
+
super().__init__()
|
| 45 |
+
|
| 46 |
+
self.S = MD_S
|
| 47 |
+
self.R = MD_R
|
| 48 |
+
|
| 49 |
+
self.train_steps = train_steps
|
| 50 |
+
self.eval_steps = eval_steps
|
| 51 |
+
|
| 52 |
+
self.inv_t = inv_t
|
| 53 |
+
|
| 54 |
+
self.rand_init = rand_init
|
| 55 |
+
|
| 56 |
+
def _build_bases(self, B, S, D, R, device=None):
|
| 57 |
+
raise NotImplementedError
|
| 58 |
+
|
| 59 |
+
def local_step(self, x, bases, coef):
|
| 60 |
+
raise NotImplementedError
|
| 61 |
+
|
| 62 |
+
def local_inference(self, x, bases):
|
| 63 |
+
# (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R)
|
| 64 |
+
coef = torch.bmm(x.transpose(1, 2), bases)
|
| 65 |
+
coef = F.softmax(self.inv_t * coef, dim=-1)
|
| 66 |
+
|
| 67 |
+
steps = self.train_steps if self.training else self.eval_steps
|
| 68 |
+
for _ in range(steps):
|
| 69 |
+
bases, coef = self.local_step(x, bases, coef)
|
| 70 |
+
|
| 71 |
+
return bases, coef
|
| 72 |
+
|
| 73 |
+
def compute_coef(self, x, bases, coef):
|
| 74 |
+
raise NotImplementedError
|
| 75 |
+
|
| 76 |
+
def forward(self, x, return_bases=False):
|
| 77 |
+
"""Forward Function."""
|
| 78 |
+
B, C, H, W = x.shape
|
| 79 |
+
|
| 80 |
+
# (B, C, H, W) -> (B * S, D, N)
|
| 81 |
+
D = C // self.S
|
| 82 |
+
N = H * W
|
| 83 |
+
x = x.view(B * self.S, D, N)
|
| 84 |
+
if not self.rand_init and not hasattr(self, 'bases'):
|
| 85 |
+
bases = self._build_bases(1, self.S, D, self.R, device=x.device)
|
| 86 |
+
self.register_buffer('bases', bases)
|
| 87 |
+
|
| 88 |
+
# (S, D, R) -> (B * S, D, R)
|
| 89 |
+
if self.rand_init:
|
| 90 |
+
bases = self._build_bases(B, self.S, D, self.R, device=x.device)
|
| 91 |
+
else:
|
| 92 |
+
bases = self.bases.repeat(B, 1, 1)
|
| 93 |
+
|
| 94 |
+
bases, coef = self.local_inference(x, bases)
|
| 95 |
+
|
| 96 |
+
# (B * S, N, R)
|
| 97 |
+
coef = self.compute_coef(x, bases, coef)
|
| 98 |
+
|
| 99 |
+
# (B * S, D, R) @ (B * S, N, R)^T -> (B * S, D, N)
|
| 100 |
+
x = torch.bmm(bases, coef.transpose(1, 2))
|
| 101 |
+
|
| 102 |
+
# (B * S, D, N) -> (B, C, H, W)
|
| 103 |
+
x = x.view(B, C, H, W)
|
| 104 |
+
|
| 105 |
+
return x
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class NMF2D(Matrix_Decomposition_2D_Base):
|
| 109 |
+
"""Non-negative Matrix Factorization (NMF) module.
|
| 110 |
+
|
| 111 |
+
It is inherited from ``Matrix_Decomposition_2D_Base`` module.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
def __init__(self, args=dict()):
|
| 115 |
+
super().__init__(**args)
|
| 116 |
+
|
| 117 |
+
self.inv_t = 1
|
| 118 |
+
|
| 119 |
+
def _build_bases(self, B, S, D, R, device=None):
|
| 120 |
+
"""Build bases in initialization."""
|
| 121 |
+
if device is None:
|
| 122 |
+
device = get_device()
|
| 123 |
+
bases = torch.rand((B * S, D, R)).to(device)
|
| 124 |
+
bases = F.normalize(bases, dim=1)
|
| 125 |
+
|
| 126 |
+
return bases
|
| 127 |
+
|
| 128 |
+
def local_step(self, x, bases, coef):
|
| 129 |
+
"""Local step in iteration to renew bases and coefficient."""
|
| 130 |
+
# (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R)
|
| 131 |
+
numerator = torch.bmm(x.transpose(1, 2), bases)
|
| 132 |
+
# (B * S, N, R) @ [(B * S, D, R)^T @ (B * S, D, R)] -> (B * S, N, R)
|
| 133 |
+
denominator = coef.bmm(bases.transpose(1, 2).bmm(bases))
|
| 134 |
+
# Multiplicative Update
|
| 135 |
+
coef = coef * numerator / (denominator + 1e-6)
|
| 136 |
+
|
| 137 |
+
# (B * S, D, N) @ (B * S, N, R) -> (B * S, D, R)
|
| 138 |
+
numerator = torch.bmm(x, coef)
|
| 139 |
+
# (B * S, D, R) @ [(B * S, N, R)^T @ (B * S, N, R)] -> (B * S, D, R)
|
| 140 |
+
denominator = bases.bmm(coef.transpose(1, 2).bmm(coef))
|
| 141 |
+
# Multiplicative Update
|
| 142 |
+
bases = bases * numerator / (denominator + 1e-6)
|
| 143 |
+
|
| 144 |
+
return bases, coef
|
| 145 |
+
|
| 146 |
+
def compute_coef(self, x, bases, coef):
|
| 147 |
+
"""Compute coefficient."""
|
| 148 |
+
# (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R)
|
| 149 |
+
numerator = torch.bmm(x.transpose(1, 2), bases)
|
| 150 |
+
# (B * S, N, R) @ (B * S, D, R)^T @ (B * S, D, R) -> (B * S, N, R)
|
| 151 |
+
denominator = coef.bmm(bases.transpose(1, 2).bmm(bases))
|
| 152 |
+
# multiplication update
|
| 153 |
+
coef = coef * numerator / (denominator + 1e-6)
|
| 154 |
+
|
| 155 |
+
return coef
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class Hamburger(nn.Module):
|
| 159 |
+
"""Hamburger Module. It consists of one slice of "ham" (matrix
|
| 160 |
+
decomposition) and two slices of "bread" (linear transformation).
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
ham_channels (int): Input and output channels of feature.
|
| 164 |
+
ham_kwargs (dict): Config of matrix decomposition module.
|
| 165 |
+
norm_cfg (dict | None): Config of norm layers.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
def __init__(self,
|
| 169 |
+
ham_channels=512,
|
| 170 |
+
ham_kwargs=dict(),
|
| 171 |
+
norm_cfg=None,
|
| 172 |
+
**kwargs):
|
| 173 |
+
super().__init__()
|
| 174 |
+
|
| 175 |
+
self.ham_in = ConvModule(
|
| 176 |
+
ham_channels, ham_channels, 1, norm_cfg=None, act_cfg=None)
|
| 177 |
+
|
| 178 |
+
self.ham = NMF2D(ham_kwargs)
|
| 179 |
+
|
| 180 |
+
self.ham_out = ConvModule(
|
| 181 |
+
ham_channels, ham_channels, 1, norm_cfg=norm_cfg, act_cfg=None)
|
| 182 |
+
|
| 183 |
+
def forward(self, x):
|
| 184 |
+
enjoy = self.ham_in(x)
|
| 185 |
+
enjoy = F.relu(enjoy, inplace=True)
|
| 186 |
+
enjoy = self.ham(enjoy)
|
| 187 |
+
enjoy = self.ham_out(enjoy)
|
| 188 |
+
ham = F.relu(x + enjoy, inplace=True)
|
| 189 |
+
|
| 190 |
+
return ham
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@MODELS.register_module()
|
| 194 |
+
class LightHamHead(BaseDecodeHead):
|
| 195 |
+
"""SegNeXt decode head.
|
| 196 |
+
|
| 197 |
+
This decode head is the implementation of `SegNeXt: Rethinking
|
| 198 |
+
Convolutional Attention Design for Semantic
|
| 199 |
+
Segmentation <https://arxiv.org/abs/2209.08575>`_.
|
| 200 |
+
Inspiration from https://github.com/visual-attention-network/segnext.
|
| 201 |
+
|
| 202 |
+
Specifically, LightHamHead is inspired by HamNet from
|
| 203 |
+
`Is Attention Better Than Matrix Decomposition?
|
| 204 |
+
<https://arxiv.org/abs/2109.04553>`.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
ham_channels (int): input channels for Hamburger.
|
| 208 |
+
Defaults: 512.
|
| 209 |
+
ham_kwargs (int): kwagrs for Ham. Defaults: dict().
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
def __init__(self, ham_channels=512, ham_kwargs=dict(), **kwargs):
|
| 213 |
+
super().__init__(input_transform='multiple_select', **kwargs)
|
| 214 |
+
self.ham_channels = ham_channels
|
| 215 |
+
|
| 216 |
+
self.squeeze = ConvModule(
|
| 217 |
+
sum(self.in_channels),
|
| 218 |
+
self.ham_channels,
|
| 219 |
+
1,
|
| 220 |
+
conv_cfg=self.conv_cfg,
|
| 221 |
+
norm_cfg=self.norm_cfg,
|
| 222 |
+
act_cfg=self.act_cfg)
|
| 223 |
+
|
| 224 |
+
self.hamburger = Hamburger(ham_channels, ham_kwargs, **kwargs)
|
| 225 |
+
|
| 226 |
+
self.align = ConvModule(
|
| 227 |
+
self.ham_channels,
|
| 228 |
+
self.channels,
|
| 229 |
+
1,
|
| 230 |
+
conv_cfg=self.conv_cfg,
|
| 231 |
+
norm_cfg=self.norm_cfg,
|
| 232 |
+
act_cfg=self.act_cfg)
|
| 233 |
+
|
| 234 |
+
def forward(self, inputs):
|
| 235 |
+
"""Forward function."""
|
| 236 |
+
inputs = self._transform_inputs(inputs)
|
| 237 |
+
|
| 238 |
+
inputs = [
|
| 239 |
+
resize(
|
| 240 |
+
level,
|
| 241 |
+
size=inputs[0].shape[2:],
|
| 242 |
+
mode='bilinear',
|
| 243 |
+
align_corners=self.align_corners) for level in inputs
|
| 244 |
+
]
|
| 245 |
+
|
| 246 |
+
inputs = torch.cat(inputs, dim=1)
|
| 247 |
+
# apply a conv block to squeeze feature map
|
| 248 |
+
x = self.squeeze(inputs)
|
| 249 |
+
# apply hamburger module
|
| 250 |
+
x = self.hamburger(x)
|
| 251 |
+
|
| 252 |
+
# apply a conv block to align feature map
|
| 253 |
+
output = self.align(x)
|
| 254 |
+
output = self.cls_seg(output)
|
| 255 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/interformer_decoder.py
ADDED
|
@@ -0,0 +1,921 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import List, Tuple, Dict
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from mmengine.model import BaseModule
|
| 8 |
+
from typing import Optional
|
| 9 |
+
import numpy as np
|
| 10 |
+
import cv2
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from mmdet.models.dense_heads import \
|
| 15 |
+
Mask2FormerHead as MMDET_Mask2FormerHead
|
| 16 |
+
except ModuleNotFoundError:
|
| 17 |
+
MMDET_Mask2FormerHead = BaseModule
|
| 18 |
+
|
| 19 |
+
from mmengine.structures import InstanceData
|
| 20 |
+
from torch import Tensor
|
| 21 |
+
|
| 22 |
+
from mmseg.registry import MODELS
|
| 23 |
+
from mmseg.structures.seg_data_sample import SegDataSample
|
| 24 |
+
from mmseg.utils import ConfigType, SampleList
|
| 25 |
+
|
| 26 |
+
# moving from parent classes
|
| 27 |
+
from mmseg.utils import OptConfigType, OptMultiConfig
|
| 28 |
+
import copy
|
| 29 |
+
from mmdet.models.layers import Mask2FormerTransformerDecoder, SinePositionalEncoding
|
| 30 |
+
from mmseg.registry import TASK_UTILS
|
| 31 |
+
from mmengine.model import ModuleList, caffe2_xavier_init
|
| 32 |
+
from mmcv.cnn import Conv2d
|
| 33 |
+
from .decode_head import BaseDecodeHead
|
| 34 |
+
from mmdet.models.utils import multi_apply, get_uncertain_point_coords_with_randomness
|
| 35 |
+
from mmcv.ops import point_sample
|
| 36 |
+
from mmdet.utils import reduce_mean, InstanceList
|
| 37 |
+
from typing import Union
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class UNetDecoder(nn.Module):
|
| 41 |
+
def __init__(self, in_channels_list, out_channels):
|
| 42 |
+
super(UNetDecoder, self).__init__()
|
| 43 |
+
|
| 44 |
+
self.upconv1 = nn.ConvTranspose2d(in_channels_list[3], in_channels_list[2], kernel_size=2, stride=2)
|
| 45 |
+
self.conv1 = nn.Conv2d(in_channels_list[2] * 2, in_channels_list[2], kernel_size=3, padding=1)
|
| 46 |
+
|
| 47 |
+
self.upconv2 = nn.ConvTranspose2d(in_channels_list[2], in_channels_list[1], kernel_size=2, stride=2)
|
| 48 |
+
self.conv2 = nn.Conv2d(in_channels_list[1] * 2, in_channels_list[1], kernel_size=3, padding=1)
|
| 49 |
+
|
| 50 |
+
self.upconv3 = nn.ConvTranspose2d(in_channels_list[1], in_channels_list[0], kernel_size=2, stride=2)
|
| 51 |
+
self.conv3 = nn.Conv2d(in_channels_list[0] * 2, out_channels, kernel_size=3, padding=1)
|
| 52 |
+
|
| 53 |
+
def forward(self, features):
|
| 54 |
+
x1 = features[3]
|
| 55 |
+
x2 = self.upconv1(x1)
|
| 56 |
+
x2 = torch.cat((x2, features[2]), dim=1) # Concatenate
|
| 57 |
+
x2 = self.conv1(x2)
|
| 58 |
+
|
| 59 |
+
x3 = self.upconv2(x2)
|
| 60 |
+
x3 = torch.cat((x3, features[1]), dim=1) # Concatenate
|
| 61 |
+
x3 = self.conv2(x3)
|
| 62 |
+
|
| 63 |
+
x4 = self.upconv3(x3)
|
| 64 |
+
x4 = torch.cat((x4, features[0]), dim=1) # Concatenate
|
| 65 |
+
x4 = self.conv3(x4)
|
| 66 |
+
|
| 67 |
+
return x4, [x1,x2,x3]
|
| 68 |
+
|
| 69 |
+
def _get_activation_fn(activation):
|
| 70 |
+
"""Return an activation function given a string"""
|
| 71 |
+
if activation == "relu":
|
| 72 |
+
return F.relu
|
| 73 |
+
if activation == "gelu":
|
| 74 |
+
return F.gelu
|
| 75 |
+
if activation == "glu":
|
| 76 |
+
return F.glu
|
| 77 |
+
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
|
| 78 |
+
|
| 79 |
+
class CrossAttentionLayer(nn.Module):
|
| 80 |
+
|
| 81 |
+
def __init__(self, d_model=256, nhead=8, dropout=0.0,
|
| 82 |
+
activation="relu"):
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 85 |
+
|
| 86 |
+
self.norm = nn.LayerNorm(d_model)
|
| 87 |
+
self.dropout = nn.Dropout(dropout)
|
| 88 |
+
|
| 89 |
+
self.activation = _get_activation_fn(activation)
|
| 90 |
+
|
| 91 |
+
self._reset_parameters()
|
| 92 |
+
|
| 93 |
+
def _reset_parameters(self):
|
| 94 |
+
for p in self.parameters():
|
| 95 |
+
if p.dim() > 1:
|
| 96 |
+
nn.init.xavier_uniform_(p)
|
| 97 |
+
|
| 98 |
+
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
|
| 99 |
+
return tensor if pos is None else tensor + pos
|
| 100 |
+
|
| 101 |
+
def forward_pre(self, tgt, memory,
|
| 102 |
+
memory_mask: Optional[Tensor] = None,
|
| 103 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 104 |
+
pos: Optional[Tensor] = None,
|
| 105 |
+
query_pos: Optional[Tensor] = None):
|
| 106 |
+
tgt2 = self.norm(tgt)
|
| 107 |
+
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),
|
| 108 |
+
key=self.with_pos_embed(memory, pos),
|
| 109 |
+
value=memory, attn_mask=memory_mask,
|
| 110 |
+
key_padding_mask=memory_key_padding_mask)[0]
|
| 111 |
+
tgt = tgt + self.dropout(tgt2)
|
| 112 |
+
|
| 113 |
+
return tgt
|
| 114 |
+
|
| 115 |
+
def forward(self, tgt, memory,
|
| 116 |
+
memory_mask: Optional[Tensor] = None,
|
| 117 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 118 |
+
pos: Optional[Tensor] = None,
|
| 119 |
+
query_pos: Optional[Tensor] = None):
|
| 120 |
+
|
| 121 |
+
return self.forward_pre(tgt, memory, memory_mask,
|
| 122 |
+
memory_key_padding_mask, pos, query_pos)
|
| 123 |
+
|
| 124 |
+
class Attention(nn.Module):
|
| 125 |
+
def __init__(self, dim=256, heads=8):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.heads = heads
|
| 128 |
+
head_dim = dim // heads
|
| 129 |
+
self.scale = head_dim ** -0.5
|
| 130 |
+
self.attn = None
|
| 131 |
+
|
| 132 |
+
self.qkv = nn.Linear(dim, dim * 3)
|
| 133 |
+
self.proj = nn.Linear(dim, dim)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def unwrapped(self):
|
| 138 |
+
return self
|
| 139 |
+
|
| 140 |
+
def forward(self, x, mask=None):
|
| 141 |
+
B, N, C = x.shape
|
| 142 |
+
qkv = (
|
| 143 |
+
self.qkv(x)
|
| 144 |
+
.reshape(B, N, 3, self.heads, C // self.heads)
|
| 145 |
+
.permute(2, 0, 3, 1, 4)
|
| 146 |
+
)
|
| 147 |
+
q, k, v = (
|
| 148 |
+
qkv[0],
|
| 149 |
+
qkv[1],
|
| 150 |
+
qkv[2],
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
| 154 |
+
attn = attn.softmax(dim=-1)
|
| 155 |
+
|
| 156 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 157 |
+
x = self.proj(x)
|
| 158 |
+
|
| 159 |
+
return x, attn
|
| 160 |
+
|
| 161 |
+
def select_top_k_features_from_regional_similarity(feature_A: torch.Tensor, feature_B: torch.Tensor, k: int = 5):
|
| 162 |
+
|
| 163 |
+
if feature_A.shape[1] != feature_B.shape[1]:
|
| 164 |
+
raise ValueError("Not match")
|
| 165 |
+
|
| 166 |
+
batch_size, channels, h_A, w_A = feature_A.shape
|
| 167 |
+
_, _, h_B, w_B = feature_B.shape
|
| 168 |
+
|
| 169 |
+
if h_B != 2 * h_A or w_B != 2 * w_A:
|
| 170 |
+
raise ValueError("2x times Error")
|
| 171 |
+
|
| 172 |
+
b_top_left = feature_B[:, :, :h_A, :w_A]
|
| 173 |
+
b_top_right = feature_B[:, :, :h_A, w_A:]
|
| 174 |
+
b_bottom_left = feature_B[:, :, h_A:, :w_A]
|
| 175 |
+
b_bottom_right = feature_B[:, :, h_A:, w_A:]
|
| 176 |
+
|
| 177 |
+
b_sub_regions = [b_top_left, b_top_right, b_bottom_left, b_bottom_right]
|
| 178 |
+
|
| 179 |
+
pixelwise_similarities_list = []
|
| 180 |
+
for b_sub in b_sub_regions:
|
| 181 |
+
|
| 182 |
+
cosine_sim_map = F.cosine_similarity(feature_A, b_sub, dim=1)
|
| 183 |
+
pixelwise_similarities_list.append(cosine_sim_map)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
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]
|
| 187 |
+
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]
|
| 188 |
+
|
| 189 |
+
total_similarity_map = torch.cat([sim_map_top, sim_map_bottom], dim=1) # [B, 2*H_A, W_B] = [B, H_B, W_B]
|
| 190 |
+
|
| 191 |
+
final_selected_features = []
|
| 192 |
+
|
| 193 |
+
for b_idx in range(batch_size):
|
| 194 |
+
|
| 195 |
+
batch_similarity = total_similarity_map[b_idx].flatten()
|
| 196 |
+
|
| 197 |
+
_, top_k_indices_flat = torch.topk(batch_similarity, k=k, largest=True, sorted=True)
|
| 198 |
+
|
| 199 |
+
current_batch_top_k_features = []
|
| 200 |
+
for k_idx in range(k):
|
| 201 |
+
flat_idx = top_k_indices_flat[k_idx].item()
|
| 202 |
+
|
| 203 |
+
h_coord = flat_idx // w_B
|
| 204 |
+
w_coord = flat_idx % w_B
|
| 205 |
+
|
| 206 |
+
selected_feature = feature_B[b_idx, :, h_coord, w_coord].unsqueeze(-1).unsqueeze(-1)
|
| 207 |
+
current_batch_top_k_features.append(selected_feature)
|
| 208 |
+
|
| 209 |
+
all_batches_top_k_flat_indices = []
|
| 210 |
+
for b_idx in range(batch_size):
|
| 211 |
+
batch_similarity = total_similarity_map[b_idx].flatten()
|
| 212 |
+
_, top_k_indices_flat = torch.topk(batch_similarity, k=k, largest=True, sorted=True)
|
| 213 |
+
all_batches_top_k_flat_indices.append(top_k_indices_flat)
|
| 214 |
+
|
| 215 |
+
final_selected_features_list = []
|
| 216 |
+
|
| 217 |
+
for k_val_idx in range(k):
|
| 218 |
+
features_for_this_k_across_batches = []
|
| 219 |
+
for b_idx in range(batch_size):
|
| 220 |
+
flat_idx = all_batches_top_k_flat_indices[b_idx][k_val_idx].item()
|
| 221 |
+
h_coord = flat_idx // w_B
|
| 222 |
+
w_coord = flat_idx % w_B
|
| 223 |
+
|
| 224 |
+
selected_feature = feature_B[b_idx, :, h_coord, w_coord].unsqueeze(-1).unsqueeze(-1)
|
| 225 |
+
features_for_this_k_across_batches.append(selected_feature)
|
| 226 |
+
|
| 227 |
+
final_selected_features_list.append(torch.stack(features_for_this_k_across_batches, dim=0))
|
| 228 |
+
|
| 229 |
+
return final_selected_features_list
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@MODELS.register_module()
|
| 233 |
+
class InterFormerDecoder(BaseDecodeHead):
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def __init__(self,
|
| 237 |
+
in_channels: List[int],
|
| 238 |
+
feat_channels: int,
|
| 239 |
+
out_channels: int,
|
| 240 |
+
num_queries: int = 100,
|
| 241 |
+
num_transformer_feat_level: int = 3,
|
| 242 |
+
pixel_decoder: ConfigType = ...,
|
| 243 |
+
enforce_decoder_input_project: bool = False,
|
| 244 |
+
transformer_decoder: ConfigType = ...,
|
| 245 |
+
positional_encoding: ConfigType = dict(
|
| 246 |
+
num_feats=128, normalize=True),
|
| 247 |
+
loss_cls: ConfigType = dict(
|
| 248 |
+
type='CrossEntropyLoss',
|
| 249 |
+
use_sigmoid=False,
|
| 250 |
+
loss_weight=2.0,
|
| 251 |
+
reduction='mean',
|
| 252 |
+
class_weight=[1.0] * 133 + [0.1]),
|
| 253 |
+
loss_mask: ConfigType = dict(
|
| 254 |
+
type='CrossEntropyLoss',
|
| 255 |
+
use_sigmoid=True,
|
| 256 |
+
reduction='mean',
|
| 257 |
+
loss_weight=5.0),
|
| 258 |
+
loss_dice: ConfigType = dict(
|
| 259 |
+
type='DiceLoss',
|
| 260 |
+
use_sigmoid=True,
|
| 261 |
+
activate=True,
|
| 262 |
+
reduction='mean',
|
| 263 |
+
naive_dice=True,
|
| 264 |
+
eps=1.0,
|
| 265 |
+
loss_weight=5.0),
|
| 266 |
+
train_cfg: OptConfigType = None,
|
| 267 |
+
test_cfg: OptConfigType = None,
|
| 268 |
+
init_cfg: OptMultiConfig = None,
|
| 269 |
+
num_classes=10,
|
| 270 |
+
align_corners=False,
|
| 271 |
+
ignore_index=255,
|
| 272 |
+
**kwargs):
|
| 273 |
+
super().__init__(in_channels=3,channels=out_channels,num_classes=num_classes)
|
| 274 |
+
|
| 275 |
+
self.num_classes = num_classes
|
| 276 |
+
self.align_corners = align_corners
|
| 277 |
+
self.out_channels = num_classes
|
| 278 |
+
self.ignore_index = ignore_index
|
| 279 |
+
|
| 280 |
+
feat_channels = feat_channels
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
self.num_queries = num_queries
|
| 284 |
+
self.num_transformer_feat_level = num_transformer_feat_level
|
| 285 |
+
self.num_heads = transformer_decoder.layer_cfg.cross_attn_cfg.num_heads
|
| 286 |
+
self.num_transformer_decoder_layers = transformer_decoder.num_layers
|
| 287 |
+
|
| 288 |
+
assert pixel_decoder.encoder.layer_cfg. \
|
| 289 |
+
self_attn_cfg.num_levels == num_transformer_feat_level
|
| 290 |
+
pixel_decoder_ = copy.deepcopy(pixel_decoder)
|
| 291 |
+
pixel_decoder_.update(
|
| 292 |
+
in_channels=in_channels,
|
| 293 |
+
feat_channels=feat_channels,
|
| 294 |
+
out_channels=out_channels)
|
| 295 |
+
self.pixel_decoder = MODELS.build(pixel_decoder_)
|
| 296 |
+
self.transformer_decoder = Mask2FormerTransformerDecoder(
|
| 297 |
+
**transformer_decoder)
|
| 298 |
+
self.decoder_embed_dims = self.transformer_decoder.embed_dims
|
| 299 |
+
self.decoder_input_projs = ModuleList()
|
| 300 |
+
# from low resolution to high resolution
|
| 301 |
+
for _ in range(num_transformer_feat_level):
|
| 302 |
+
if (self.decoder_embed_dims != feat_channels
|
| 303 |
+
or enforce_decoder_input_project):
|
| 304 |
+
self.decoder_input_projs.append(
|
| 305 |
+
Conv2d(
|
| 306 |
+
feat_channels, self.decoder_embed_dims, kernel_size=1))
|
| 307 |
+
else:
|
| 308 |
+
self.decoder_input_projs.append(nn.Identity())
|
| 309 |
+
self.decoder_positional_encoding = SinePositionalEncoding(
|
| 310 |
+
**positional_encoding)
|
| 311 |
+
self.query_embed = nn.Embedding(self.num_queries, feat_channels) #position
|
| 312 |
+
self.query_feat = nn.Embedding(self.num_queries, feat_channels) #content
|
| 313 |
+
# from low resolution to high resolution
|
| 314 |
+
self.level_embed = nn.Embedding(self.num_transformer_feat_level,
|
| 315 |
+
feat_channels)
|
| 316 |
+
|
| 317 |
+
self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1)
|
| 318 |
+
self.mask_embed = nn.Sequential(
|
| 319 |
+
nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True),
|
| 320 |
+
nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True),
|
| 321 |
+
nn.Linear(feat_channels, out_channels))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
self.mlp = nn.Sequential(nn.Linear(112*112, 256), nn.ReLU(inplace=True),
|
| 325 |
+
nn.Linear(256,128), nn.ReLU(inplace=True),
|
| 326 |
+
nn.Linear(128,5),nn.ReLU(inplace=True))
|
| 327 |
+
|
| 328 |
+
self.test_cfg = test_cfg
|
| 329 |
+
self.train_cfg = train_cfg
|
| 330 |
+
if train_cfg:
|
| 331 |
+
self.assigner = TASK_UTILS.build(self.train_cfg['assigner'])
|
| 332 |
+
self.sampler = TASK_UTILS.build(
|
| 333 |
+
self.train_cfg['sampler'], default_args=dict(context=self))
|
| 334 |
+
self.num_points = self.train_cfg.get('num_points', 12544)
|
| 335 |
+
self.oversample_ratio = self.train_cfg.get('oversample_ratio', 3.0)
|
| 336 |
+
self.importance_sample_ratio = self.train_cfg.get(
|
| 337 |
+
'importance_sample_ratio', 0.75)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
self.class_weight = loss_cls.class_weight
|
| 341 |
+
self.loss_cls = MODELS.build(loss_cls)
|
| 342 |
+
self.loss_mask = MODELS.build(loss_mask)
|
| 343 |
+
self.loss_dice = MODELS.build(loss_dice)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
self.cbdecoder = UNetDecoder(in_channels_list=[128, 256, 512, 1024], out_channels=1)
|
| 347 |
+
self.proj_cb = ModuleList()
|
| 348 |
+
channels = [1024,512,256]
|
| 349 |
+
for i in range(num_transformer_feat_level):
|
| 350 |
+
self.proj_cb.append(
|
| 351 |
+
Conv2d(
|
| 352 |
+
channels[i], self.decoder_embed_dims, kernel_size=1))
|
| 353 |
+
self.cross_attn_cb = CrossAttentionLayer()
|
| 354 |
+
self.self_attn_cb = Attention()
|
| 355 |
+
self.norm_cb = nn.LayerNorm(256)
|
| 356 |
+
|
| 357 |
+
def _seg_data_to_instance_data(self, batch_data_samples: SampleList):
|
| 358 |
+
|
| 359 |
+
batch_img_metas = []
|
| 360 |
+
batch_gt_instances = []
|
| 361 |
+
|
| 362 |
+
for data_sample in batch_data_samples:
|
| 363 |
+
batch_img_metas.append(data_sample.metainfo)
|
| 364 |
+
gt_sem_seg = data_sample.gt_sem_seg.data
|
| 365 |
+
classes = torch.unique(
|
| 366 |
+
gt_sem_seg,
|
| 367 |
+
sorted=False,
|
| 368 |
+
return_inverse=False,
|
| 369 |
+
return_counts=False)
|
| 370 |
+
|
| 371 |
+
gt_labels = classes[classes != self.ignore_index]
|
| 372 |
+
|
| 373 |
+
masks = []
|
| 374 |
+
for class_id in gt_labels:
|
| 375 |
+
masks.append(gt_sem_seg == class_id)
|
| 376 |
+
|
| 377 |
+
if len(masks) == 0:
|
| 378 |
+
gt_masks = torch.zeros(
|
| 379 |
+
(0, gt_sem_seg.shape[-2],
|
| 380 |
+
gt_sem_seg.shape[-1])).to(gt_sem_seg).long()
|
| 381 |
+
else:
|
| 382 |
+
gt_masks = torch.stack(masks).squeeze(1).long()
|
| 383 |
+
|
| 384 |
+
instance_data = InstanceData(labels=gt_labels, masks=gt_masks)
|
| 385 |
+
batch_gt_instances.append(instance_data)
|
| 386 |
+
return batch_gt_instances, batch_img_metas
|
| 387 |
+
|
| 388 |
+
def compute_loss_for_cb(self, cb_pred, batch_data_samples):
|
| 389 |
+
# add supervision for cb prediction
|
| 390 |
+
gt_cbs = []
|
| 391 |
+
for data_sample in batch_data_samples:
|
| 392 |
+
img_path = data_sample.metainfo['img_path']
|
| 393 |
+
filename = img_path.split('.')[0].split('/')[-1]
|
| 394 |
+
cb_gt_path = '/mnt/nvme1/suyuejiao/egohos_split_data/train/label_contact_first/'+filename+'.png'
|
| 395 |
+
cb_gt_np = np.array(Image.open(cb_gt_path).resize((448, 448)))
|
| 396 |
+
gt_cbs.append(torch.from_numpy(cb_gt_np).to(cb_pred))
|
| 397 |
+
|
| 398 |
+
gt_cbs = torch.stack(gt_cbs).squeeze(1).float()
|
| 399 |
+
|
| 400 |
+
criterion = nn.BCEWithLogitsLoss()
|
| 401 |
+
loss = criterion(cb_pred.squeeze(1), gt_cbs)
|
| 402 |
+
return loss
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList,
|
| 407 |
+
train_cfg: ConfigType) -> dict:
|
| 408 |
+
|
| 409 |
+
batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data(
|
| 410 |
+
batch_data_samples)
|
| 411 |
+
|
| 412 |
+
all_cls_scores, all_mask_preds, cb_pred = self.forward(x, batch_data_samples)
|
| 413 |
+
|
| 414 |
+
# add loss for cb prediction
|
| 415 |
+
loss_cb = self.compute_loss_for_cb(cb_pred,batch_data_samples)
|
| 416 |
+
|
| 417 |
+
# loss
|
| 418 |
+
losses = self.loss_by_feat(all_cls_scores, all_mask_preds,
|
| 419 |
+
batch_gt_instances, batch_img_metas)
|
| 420 |
+
losses['cb']=loss_cb
|
| 421 |
+
|
| 422 |
+
# adding the consistency loss
|
| 423 |
+
mask_cls_results = all_cls_scores[-1]
|
| 424 |
+
mask_pred_results = all_mask_preds[-1]
|
| 425 |
+
if 'pad_shape' in batch_img_metas[0]:
|
| 426 |
+
size = batch_img_metas[0]['pad_shape']
|
| 427 |
+
else:
|
| 428 |
+
size = batch_img_metas[0]['img_shape']
|
| 429 |
+
# upsample mask
|
| 430 |
+
mask_pred_results = F.interpolate(
|
| 431 |
+
mask_pred_results, size=size, mode='bilinear', align_corners=False)
|
| 432 |
+
cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1]
|
| 433 |
+
mask_pred = mask_pred_results.sigmoid()
|
| 434 |
+
seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred)
|
| 435 |
+
pred_results_index = torch.argmax(seg_logits,dim=1)
|
| 436 |
+
|
| 437 |
+
left_hand_pred = torch.zeros(pred_results_index.shape)
|
| 438 |
+
left_hand_pred[pred_results_index==1] = 1
|
| 439 |
+
|
| 440 |
+
threshold_left = 150
|
| 441 |
+
if left_hand_pred.sum() >= threshold_left:
|
| 442 |
+
index_left = 1
|
| 443 |
+
else:
|
| 444 |
+
index_left = 0
|
| 445 |
+
|
| 446 |
+
right_hand_pred = torch.zeros(pred_results_index.shape)
|
| 447 |
+
right_hand_pred[pred_results_index==2] = 1
|
| 448 |
+
|
| 449 |
+
threshold_right = threshold_left
|
| 450 |
+
if right_hand_pred.sum() >= threshold_right:
|
| 451 |
+
index_right = 1
|
| 452 |
+
else:
|
| 453 |
+
index_right = 0
|
| 454 |
+
|
| 455 |
+
if index_left == 0 or index_right == 0:
|
| 456 |
+
index_two = 0
|
| 457 |
+
else:
|
| 458 |
+
index_two = 1
|
| 459 |
+
|
| 460 |
+
left_object_pred = torch.zeros(pred_results_index.shape)
|
| 461 |
+
left_object_pred[pred_results_index==3] = 1
|
| 462 |
+
right_object_pred = torch.zeros(pred_results_index.shape)
|
| 463 |
+
right_object_pred[pred_results_index==4] = 1
|
| 464 |
+
two_object_pred = torch.zeros(pred_results_index.shape)
|
| 465 |
+
two_object_pred[pred_results_index==5] = 1
|
| 466 |
+
loss_left = (1-index_left)*(left_object_pred.sum()-left_object_pred.sum()*index_left)
|
| 467 |
+
loss_right = (1-index_right)*(right_object_pred.sum()-right_object_pred.sum()*index_right)
|
| 468 |
+
loss_two = (1-index_two)*(two_object_pred.sum()-two_object_pred.sum()*index_two)
|
| 469 |
+
consistency_loss = loss_left + loss_right + loss_two
|
| 470 |
+
|
| 471 |
+
losses['consistency'] = consistency_loss
|
| 472 |
+
|
| 473 |
+
return losses
|
| 474 |
+
|
| 475 |
+
def loss_by_feat(self, all_cls_scores: Tensor, all_mask_preds: Tensor,
|
| 476 |
+
batch_gt_instances: List[InstanceData],
|
| 477 |
+
batch_img_metas: List[dict]) -> Dict[str, Tensor]:
|
| 478 |
+
|
| 479 |
+
num_dec_layers = len(all_cls_scores)
|
| 480 |
+
batch_gt_instances_list = [
|
| 481 |
+
batch_gt_instances for _ in range(num_dec_layers)
|
| 482 |
+
]
|
| 483 |
+
img_metas_list = [batch_img_metas for _ in range(num_dec_layers)]
|
| 484 |
+
losses_cls, losses_mask, losses_dice = multi_apply(
|
| 485 |
+
self._loss_by_feat_single, all_cls_scores, all_mask_preds,
|
| 486 |
+
batch_gt_instances_list, img_metas_list)
|
| 487 |
+
|
| 488 |
+
loss_dict = dict()
|
| 489 |
+
# loss from the last decoder layer
|
| 490 |
+
loss_dict['loss_cls'] = losses_cls[-1]
|
| 491 |
+
loss_dict['loss_mask'] = losses_mask[-1]
|
| 492 |
+
loss_dict['loss_dice'] = losses_dice[-1]
|
| 493 |
+
# loss from other decoder layers
|
| 494 |
+
num_dec_layer = 0
|
| 495 |
+
for loss_cls_i, loss_mask_i, loss_dice_i in zip(
|
| 496 |
+
losses_cls[:-1], losses_mask[:-1], losses_dice[:-1]):
|
| 497 |
+
loss_dict[f'd{num_dec_layer}.loss_cls'] = loss_cls_i
|
| 498 |
+
loss_dict[f'd{num_dec_layer}.loss_mask'] = loss_mask_i
|
| 499 |
+
loss_dict[f'd{num_dec_layer}.loss_dice'] = loss_dice_i
|
| 500 |
+
num_dec_layer += 1
|
| 501 |
+
return loss_dict
|
| 502 |
+
|
| 503 |
+
def _loss_by_feat_single(self, cls_scores: Tensor, mask_preds: Tensor,
|
| 504 |
+
batch_gt_instances: List[InstanceData],
|
| 505 |
+
batch_img_metas: List[dict]) -> Tuple[Tensor]:
|
| 506 |
+
"""Loss function for outputs from a single decoder layer.
|
| 507 |
+
|
| 508 |
+
Args:
|
| 509 |
+
cls_scores (Tensor): Mask score logits from a single decoder layer
|
| 510 |
+
for all images. Shape (batch_size, num_queries,
|
| 511 |
+
cls_out_channels). Note `cls_out_channels` should includes
|
| 512 |
+
background.
|
| 513 |
+
mask_preds (Tensor): Mask logits for a pixel decoder for all
|
| 514 |
+
images. Shape (batch_size, num_queries, h, w).
|
| 515 |
+
batch_gt_instances (list[obj:`InstanceData`]): each contains
|
| 516 |
+
``labels`` and ``masks``.
|
| 517 |
+
batch_img_metas (list[dict]): List of image meta information.
|
| 518 |
+
|
| 519 |
+
Returns:
|
| 520 |
+
tuple[Tensor]: Loss components for outputs from a single \
|
| 521 |
+
decoder layer.
|
| 522 |
+
"""
|
| 523 |
+
num_imgs = cls_scores.size(0)
|
| 524 |
+
cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
|
| 525 |
+
mask_preds_list = [mask_preds[i] for i in range(num_imgs)]
|
| 526 |
+
(labels_list, label_weights_list, mask_targets_list, mask_weights_list,
|
| 527 |
+
avg_factor) = self.get_targets(cls_scores_list, mask_preds_list,
|
| 528 |
+
batch_gt_instances, batch_img_metas)
|
| 529 |
+
|
| 530 |
+
labels = torch.stack(labels_list, dim=0)
|
| 531 |
+
|
| 532 |
+
label_weights = torch.stack(label_weights_list, dim=0)
|
| 533 |
+
|
| 534 |
+
mask_targets = torch.cat(mask_targets_list, dim=0)
|
| 535 |
+
|
| 536 |
+
mask_weights = torch.stack(mask_weights_list, dim=0)
|
| 537 |
+
|
| 538 |
+
cls_scores = cls_scores.flatten(0, 1)
|
| 539 |
+
labels = labels.flatten(0, 1)
|
| 540 |
+
label_weights = label_weights.flatten(0, 1)
|
| 541 |
+
|
| 542 |
+
class_weight = cls_scores.new_tensor(self.class_weight)
|
| 543 |
+
loss_cls = self.loss_cls(
|
| 544 |
+
cls_scores,
|
| 545 |
+
labels,
|
| 546 |
+
label_weights,
|
| 547 |
+
avg_factor=class_weight[labels].sum())
|
| 548 |
+
|
| 549 |
+
num_total_masks = reduce_mean(cls_scores.new_tensor([avg_factor]))
|
| 550 |
+
num_total_masks = max(num_total_masks, 1)
|
| 551 |
+
|
| 552 |
+
# extract positive ones
|
| 553 |
+
# shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w)
|
| 554 |
+
mask_preds = mask_preds[mask_weights > 0]
|
| 555 |
+
|
| 556 |
+
if mask_targets.shape[0] == 0:
|
| 557 |
+
# zero match
|
| 558 |
+
loss_dice = mask_preds.sum()
|
| 559 |
+
loss_mask = mask_preds.sum()
|
| 560 |
+
return loss_cls, loss_mask, loss_dice
|
| 561 |
+
|
| 562 |
+
with torch.no_grad():
|
| 563 |
+
points_coords = get_uncertain_point_coords_with_randomness(
|
| 564 |
+
mask_preds.unsqueeze(1), None, self.num_points,
|
| 565 |
+
self.oversample_ratio, self.importance_sample_ratio)
|
| 566 |
+
# shape (num_total_gts, h, w) -> (num_total_gts, num_points)
|
| 567 |
+
mask_point_targets = point_sample(
|
| 568 |
+
mask_targets.unsqueeze(1).float(), points_coords).squeeze(1)
|
| 569 |
+
# shape (num_queries, h, w) -> (num_queries, num_points)
|
| 570 |
+
mask_point_preds = point_sample(
|
| 571 |
+
mask_preds.unsqueeze(1), points_coords).squeeze(1)
|
| 572 |
+
|
| 573 |
+
# dice loss
|
| 574 |
+
loss_dice = self.loss_dice(
|
| 575 |
+
mask_point_preds, mask_point_targets, avg_factor=num_total_masks)
|
| 576 |
+
|
| 577 |
+
# mask loss
|
| 578 |
+
# shape (num_queries, num_points) -> (num_queries * num_points, )
|
| 579 |
+
mask_point_preds = mask_point_preds.reshape(-1)
|
| 580 |
+
# shape (num_total_gts, num_points) -> (num_total_gts * num_points, )
|
| 581 |
+
mask_point_targets = mask_point_targets.reshape(-1)
|
| 582 |
+
loss_mask = self.loss_mask(
|
| 583 |
+
mask_point_preds,
|
| 584 |
+
mask_point_targets,
|
| 585 |
+
avg_factor=num_total_masks * self.num_points)
|
| 586 |
+
|
| 587 |
+
return loss_cls, loss_mask, loss_dice
|
| 588 |
+
|
| 589 |
+
def get_targets(
|
| 590 |
+
self,
|
| 591 |
+
cls_scores_list: List[Tensor],
|
| 592 |
+
mask_preds_list: List[Tensor],
|
| 593 |
+
batch_gt_instances: InstanceList,
|
| 594 |
+
batch_img_metas: List[dict],
|
| 595 |
+
return_sampling_results: bool = False
|
| 596 |
+
) -> Tuple[List[Union[Tensor, int]]]:
|
| 597 |
+
"""Compute classification and mask targets for all images for a decoder
|
| 598 |
+
layer.
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
cls_scores_list (list[Tensor]): Mask score logits from a single
|
| 602 |
+
decoder layer for all images. Each with shape (num_queries,
|
| 603 |
+
cls_out_channels).
|
| 604 |
+
mask_preds_list (list[Tensor]): Mask logits from a single decoder
|
| 605 |
+
layer for all images. Each with shape (num_queries, h, w).
|
| 606 |
+
batch_gt_instances (list[obj:`InstanceData`]): each contains
|
| 607 |
+
``labels`` and ``masks``.
|
| 608 |
+
batch_img_metas (list[dict]): List of image meta information.
|
| 609 |
+
return_sampling_results (bool): Whether to return the sampling
|
| 610 |
+
results. Defaults to False.
|
| 611 |
+
|
| 612 |
+
Returns:
|
| 613 |
+
tuple: a tuple containing the following targets.
|
| 614 |
+
|
| 615 |
+
- labels_list (list[Tensor]): Labels of all images.\
|
| 616 |
+
Each with shape (num_queries, ).
|
| 617 |
+
- label_weights_list (list[Tensor]): Label weights\
|
| 618 |
+
of all images. Each with shape (num_queries, ).
|
| 619 |
+
- mask_targets_list (list[Tensor]): Mask targets of\
|
| 620 |
+
all images. Each with shape (num_queries, h, w).
|
| 621 |
+
- mask_weights_list (list[Tensor]): Mask weights of\
|
| 622 |
+
all images. Each with shape (num_queries, ).
|
| 623 |
+
- avg_factor (int): Average factor that is used to average\
|
| 624 |
+
the loss. When using sampling method, avg_factor is
|
| 625 |
+
usually the sum of positive and negative priors. When
|
| 626 |
+
using `MaskPseudoSampler`, `avg_factor` is usually equal
|
| 627 |
+
to the number of positive priors.
|
| 628 |
+
|
| 629 |
+
additional_returns: This function enables user-defined returns from
|
| 630 |
+
`self._get_targets_single`. These returns are currently refined
|
| 631 |
+
to properties at each feature map (i.e. having HxW dimension).
|
| 632 |
+
The results will be concatenated after the end.
|
| 633 |
+
"""
|
| 634 |
+
results = multi_apply(self._get_targets_single, cls_scores_list,
|
| 635 |
+
mask_preds_list, batch_gt_instances,
|
| 636 |
+
batch_img_metas)
|
| 637 |
+
(labels_list, label_weights_list, mask_targets_list, mask_weights_list,
|
| 638 |
+
pos_inds_list, neg_inds_list, sampling_results_list) = results[:7]
|
| 639 |
+
rest_results = list(results[7:])
|
| 640 |
+
|
| 641 |
+
avg_factor = sum(
|
| 642 |
+
[results.avg_factor for results in sampling_results_list])
|
| 643 |
+
|
| 644 |
+
res = (labels_list, label_weights_list, mask_targets_list,
|
| 645 |
+
mask_weights_list, avg_factor)
|
| 646 |
+
if return_sampling_results:
|
| 647 |
+
res = res + (sampling_results_list)
|
| 648 |
+
|
| 649 |
+
return res + tuple(rest_results)
|
| 650 |
+
|
| 651 |
+
def _get_targets_single(self, cls_score: Tensor, mask_pred: Tensor,
|
| 652 |
+
gt_instances: InstanceData,
|
| 653 |
+
img_meta: dict) -> Tuple[Tensor]:
|
| 654 |
+
"""Compute classification and mask targets for one image.
|
| 655 |
+
|
| 656 |
+
Args:
|
| 657 |
+
cls_score (Tensor): Mask score logits from a single decoder layer
|
| 658 |
+
for one image. Shape (num_queries, cls_out_channels).
|
| 659 |
+
mask_pred (Tensor): Mask logits for a single decoder layer for one
|
| 660 |
+
image. Shape (num_queries, h, w).
|
| 661 |
+
gt_instances (:obj:`InstanceData`): It contains ``labels`` and
|
| 662 |
+
``masks``.
|
| 663 |
+
img_meta (dict): Image informtation.
|
| 664 |
+
|
| 665 |
+
Returns:
|
| 666 |
+
tuple[Tensor]: A tuple containing the following for one image.
|
| 667 |
+
|
| 668 |
+
- labels (Tensor): Labels of each image. \
|
| 669 |
+
shape (num_queries, ).
|
| 670 |
+
- label_weights (Tensor): Label weights of each image. \
|
| 671 |
+
shape (num_queries, ).
|
| 672 |
+
- mask_targets (Tensor): Mask targets of each image. \
|
| 673 |
+
shape (num_queries, h, w).
|
| 674 |
+
- mask_weights (Tensor): Mask weights of each image. \
|
| 675 |
+
shape (num_queries, ).
|
| 676 |
+
- pos_inds (Tensor): Sampled positive indices for each \
|
| 677 |
+
image.
|
| 678 |
+
- neg_inds (Tensor): Sampled negative indices for each \
|
| 679 |
+
image.
|
| 680 |
+
- sampling_result (:obj:`SamplingResult`): Sampling results.
|
| 681 |
+
"""
|
| 682 |
+
gt_labels = gt_instances.labels
|
| 683 |
+
gt_masks = gt_instances.masks
|
| 684 |
+
# sample points
|
| 685 |
+
num_queries = cls_score.shape[0]
|
| 686 |
+
num_gts = gt_labels.shape[0]
|
| 687 |
+
|
| 688 |
+
point_coords = torch.rand((1, self.num_points, 2),
|
| 689 |
+
device=cls_score.device)
|
| 690 |
+
# shape (num_queries, num_points)
|
| 691 |
+
mask_points_pred = point_sample(
|
| 692 |
+
mask_pred.unsqueeze(1), point_coords.repeat(num_queries, 1,
|
| 693 |
+
1)).squeeze(1)
|
| 694 |
+
# shape (num_gts, num_points)
|
| 695 |
+
gt_points_masks = point_sample(
|
| 696 |
+
gt_masks.unsqueeze(1).float(), point_coords.repeat(num_gts, 1,
|
| 697 |
+
1)).squeeze(1)
|
| 698 |
+
|
| 699 |
+
sampled_gt_instances = InstanceData(
|
| 700 |
+
labels=gt_labels, masks=gt_points_masks)
|
| 701 |
+
sampled_pred_instances = InstanceData(
|
| 702 |
+
scores=cls_score, masks=mask_points_pred)
|
| 703 |
+
# assign and sample
|
| 704 |
+
assign_result = self.assigner.assign(
|
| 705 |
+
pred_instances=sampled_pred_instances,
|
| 706 |
+
gt_instances=sampled_gt_instances,
|
| 707 |
+
img_meta=img_meta)
|
| 708 |
+
pred_instances = InstanceData(scores=cls_score, masks=mask_pred)
|
| 709 |
+
sampling_result = self.sampler.sample(
|
| 710 |
+
assign_result=assign_result,
|
| 711 |
+
pred_instances=pred_instances,
|
| 712 |
+
gt_instances=gt_instances)
|
| 713 |
+
pos_inds = sampling_result.pos_inds
|
| 714 |
+
neg_inds = sampling_result.neg_inds
|
| 715 |
+
|
| 716 |
+
# label target
|
| 717 |
+
labels = gt_labels.new_full((self.num_queries, ),
|
| 718 |
+
self.num_classes,
|
| 719 |
+
dtype=torch.long)
|
| 720 |
+
labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds]
|
| 721 |
+
label_weights = gt_labels.new_ones((self.num_queries, ))
|
| 722 |
+
|
| 723 |
+
# mask target
|
| 724 |
+
mask_targets = gt_masks[sampling_result.pos_assigned_gt_inds]
|
| 725 |
+
mask_weights = mask_pred.new_zeros((self.num_queries, ))
|
| 726 |
+
mask_weights[pos_inds] = 1.0
|
| 727 |
+
|
| 728 |
+
return (labels, label_weights, mask_targets, mask_weights, pos_inds,
|
| 729 |
+
neg_inds, sampling_result)
|
| 730 |
+
|
| 731 |
+
def _forward_head(self, decoder_out: Tensor, mask_feature: Tensor,
|
| 732 |
+
attn_mask_target_size: Tuple[int, int]) -> Tuple[Tensor]:
|
| 733 |
+
"""Forward for head part which is called after every decoder layer.
|
| 734 |
+
|
| 735 |
+
Args:
|
| 736 |
+
decoder_out (Tensor): in shape (batch_size, num_queries, c).
|
| 737 |
+
mask_feature (Tensor): in shape (batch_size, c, h, w).
|
| 738 |
+
attn_mask_target_size (tuple[int, int]): target attention
|
| 739 |
+
mask size.
|
| 740 |
+
|
| 741 |
+
Returns:
|
| 742 |
+
tuple: A tuple contain three elements.
|
| 743 |
+
|
| 744 |
+
- cls_pred (Tensor): Classification scores in shape \
|
| 745 |
+
(batch_size, num_queries, cls_out_channels). \
|
| 746 |
+
Note `cls_out_channels` should includes background.
|
| 747 |
+
- mask_pred (Tensor): Mask scores in shape \
|
| 748 |
+
(batch_size, num_queries,h, w).
|
| 749 |
+
- attn_mask (Tensor): Attention mask in shape \
|
| 750 |
+
(batch_size * num_heads, num_queries, h, w).
|
| 751 |
+
"""
|
| 752 |
+
|
| 753 |
+
decoder_out = self.transformer_decoder.post_norm(decoder_out)
|
| 754 |
+
# shape (batch_size,num_queries, c)
|
| 755 |
+
cls_pred = self.cls_embed(decoder_out)
|
| 756 |
+
# shape (batch_size,num_queries, num_classes)
|
| 757 |
+
mask_embed = self.mask_embed(decoder_out)
|
| 758 |
+
# shape ( batch_size, num_queries, c)
|
| 759 |
+
mask_pred = torch.einsum('bqc,bchw->bqhw', mask_embed, mask_feature)
|
| 760 |
+
attn_mask = F.interpolate(
|
| 761 |
+
mask_pred,
|
| 762 |
+
attn_mask_target_size,
|
| 763 |
+
mode='bilinear',
|
| 764 |
+
align_corners=False)
|
| 765 |
+
# shape (num_queries, batch_size, h, w) ->
|
| 766 |
+
# (batch_size * num_head, num_queries, h, w)
|
| 767 |
+
attn_mask = attn_mask.flatten(2).unsqueeze(1).repeat(
|
| 768 |
+
(1, self.num_heads, 1, 1)).flatten(0, 1)
|
| 769 |
+
attn_mask = attn_mask.sigmoid() < 0.5
|
| 770 |
+
attn_mask = attn_mask.detach()
|
| 771 |
+
|
| 772 |
+
return cls_pred, mask_pred, attn_mask
|
| 773 |
+
|
| 774 |
+
def forward(self, x: List[Tensor],
|
| 775 |
+
batch_data_samples: SampleList) -> Tuple[List[Tensor]]:
|
| 776 |
+
"""Forward function.
|
| 777 |
+
|
| 778 |
+
Args:
|
| 779 |
+
x (list[Tensor]): Multi scale Features from the
|
| 780 |
+
upstream network, each is a 4D-tensor.
|
| 781 |
+
batch_data_samples (List[:obj:`DetDataSample`]): The Data
|
| 782 |
+
Samples. It usually includes information such as
|
| 783 |
+
`gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`.
|
| 784 |
+
|
| 785 |
+
Returns:
|
| 786 |
+
tuple[list[Tensor]]: A tuple contains two elements.
|
| 787 |
+
|
| 788 |
+
- cls_pred_list (list[Tensor)]: Classification logits \
|
| 789 |
+
for each decoder layer. Each is a 3D-tensor with shape \
|
| 790 |
+
(batch_size, num_queries, cls_out_channels). \
|
| 791 |
+
Note `cls_out_channels` should includes background.
|
| 792 |
+
- mask_pred_list (list[Tensor]): Mask logits for each \
|
| 793 |
+
decoder layer. Each with shape (batch_size, num_queries, \
|
| 794 |
+
h, w).
|
| 795 |
+
"""
|
| 796 |
+
batch_size = x[0].shape[0]
|
| 797 |
+
|
| 798 |
+
mask_features, multi_scale_memorys = self.pixel_decoder(x)
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
# add decoder for CB prediction
|
| 802 |
+
cb_feat, cb_multi_sclae_features = self.cbdecoder(x)
|
| 803 |
+
cb_pred = F.interpolate(
|
| 804 |
+
cb_feat, size=(448,448), mode='bilinear', align_corners=False)
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
decoder_inputs = []
|
| 808 |
+
decoder_positional_encodings = []
|
| 809 |
+
for i in range(self.num_transformer_feat_level):
|
| 810 |
+
decoder_input = self.decoder_input_projs[i](multi_scale_memorys[i])
|
| 811 |
+
# shape (batch_size, c, h, w) -> (batch_size, h*w, c)
|
| 812 |
+
decoder_input = decoder_input.flatten(2).permute(0, 2, 1)
|
| 813 |
+
level_embed = self.level_embed.weight[i].view(1, 1, -1)
|
| 814 |
+
decoder_input = decoder_input + level_embed
|
| 815 |
+
# shape (batch_size, c, h, w) -> (batch_size, h*w, c)
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
cb_feat_align_channel = self.proj_cb[i](cb_multi_sclae_features[i])
|
| 819 |
+
|
| 820 |
+
cb_feat_align_channel = cb_feat_align_channel.flatten(2).permute(0, 2, 1)
|
| 821 |
+
|
| 822 |
+
cb_cross_attn = self.cross_attn_cb(cb_feat_align_channel, decoder_input)
|
| 823 |
+
cb_cross_attn = cb_cross_attn + cb_feat_align_channel
|
| 824 |
+
cb_cross_attn = self.norm_cb(cb_cross_attn)
|
| 825 |
+
cb_attn, A = self.self_attn_cb(cb_cross_attn)
|
| 826 |
+
|
| 827 |
+
cb_attn = cb_cross_attn + cb_attn
|
| 828 |
+
cb_attn = self.norm_cb(cb_attn)
|
| 829 |
+
decoder_input = decoder_input+cb_attn
|
| 830 |
+
|
| 831 |
+
mask = decoder_input.new_zeros(
|
| 832 |
+
(batch_size, ) + multi_scale_memorys[i].shape[-2:],
|
| 833 |
+
dtype=torch.bool)
|
| 834 |
+
decoder_positional_encoding = self.decoder_positional_encoding(mask)
|
| 835 |
+
decoder_positional_encoding = decoder_positional_encoding.flatten(
|
| 836 |
+
2).permute(0, 2, 1)
|
| 837 |
+
|
| 838 |
+
decoder_inputs.append(decoder_input)
|
| 839 |
+
decoder_positional_encodings.append(decoder_positional_encoding)
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
selected_q = select_top_k_features_from_regional_similarity(cb_multi_sclae_features[2], mask_features)
|
| 844 |
+
# Each item is [B, C, 1, 1]. squeeze() drops B when B==1 and breaks cat(dim=2).
|
| 845 |
+
_selected_q = [feat.reshape(feat.shape[0], feat.shape[1], 1) for feat in selected_q]
|
| 846 |
+
selected_q = torch.cat(_selected_q, dim=2)
|
| 847 |
+
selected_q = selected_q.permute(0, 2, 1)
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
query_feat = self.query_feat.weight.unsqueeze(0).repeat((batch_size, 1, 1))
|
| 851 |
+
query_embed = self.query_embed.weight.unsqueeze(0).repeat((batch_size, 1, 1))
|
| 852 |
+
query_feat = query_feat + selected_q
|
| 853 |
+
|
| 854 |
+
cls_pred_list = []
|
| 855 |
+
mask_pred_list = []
|
| 856 |
+
cls_pred, mask_pred, attn_mask = self._forward_head(
|
| 857 |
+
query_feat, mask_features, multi_scale_memorys[0].shape[-2:])
|
| 858 |
+
cls_pred_list.append(cls_pred)
|
| 859 |
+
mask_pred_list.append(mask_pred)
|
| 860 |
+
|
| 861 |
+
for i in range(self.num_transformer_decoder_layers):
|
| 862 |
+
level_idx = i % self.num_transformer_feat_level
|
| 863 |
+
# if a mask is all True(all background), then set it all False.
|
| 864 |
+
mask_sum = (attn_mask.sum(-1) != attn_mask.shape[-1]).unsqueeze(-1)
|
| 865 |
+
attn_mask = attn_mask & mask_sum
|
| 866 |
+
# cross_attn + self_attn
|
| 867 |
+
layer = self.transformer_decoder.layers[i]
|
| 868 |
+
query_feat = layer(
|
| 869 |
+
query=query_feat,
|
| 870 |
+
key=decoder_inputs[level_idx],
|
| 871 |
+
value=decoder_inputs[level_idx],
|
| 872 |
+
query_pos=query_embed,
|
| 873 |
+
key_pos=decoder_positional_encodings[level_idx],
|
| 874 |
+
cross_attn_mask=attn_mask,
|
| 875 |
+
query_key_padding_mask=None,
|
| 876 |
+
# here we do not apply masking on padded region
|
| 877 |
+
key_padding_mask=None)
|
| 878 |
+
|
| 879 |
+
cls_pred, mask_pred, attn_mask = self._forward_head(
|
| 880 |
+
query_feat, mask_features, multi_scale_memorys[(i + 1) % self.num_transformer_feat_level].shape[-2:])
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
cls_pred_list.append(cls_pred)
|
| 885 |
+
mask_pred_list.append(mask_pred)
|
| 886 |
+
|
| 887 |
+
return cls_pred_list, mask_pred_list, cb_pred
|
| 888 |
+
|
| 889 |
+
def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict],
|
| 890 |
+
test_cfg: ConfigType) -> Tuple[Tensor]:
|
| 891 |
+
"""Test without augmentaton.
|
| 892 |
+
|
| 893 |
+
Args:
|
| 894 |
+
x (tuple[Tensor]): Multi-level features from the
|
| 895 |
+
upstream network, each is a 4D-tensor.
|
| 896 |
+
batch_img_metas (List[:obj:`SegDataSample`]): The Data
|
| 897 |
+
Samples. It usually includes information such as
|
| 898 |
+
`gt_sem_seg`.
|
| 899 |
+
test_cfg (ConfigType): Test config.
|
| 900 |
+
|
| 901 |
+
Returns:
|
| 902 |
+
Tensor: A tensor of segmentation mask.
|
| 903 |
+
"""
|
| 904 |
+
batch_data_samples = [
|
| 905 |
+
SegDataSample(metainfo=metainfo) for metainfo in batch_img_metas
|
| 906 |
+
]
|
| 907 |
+
|
| 908 |
+
all_cls_scores, all_mask_preds, _ = self.forward(x, batch_data_samples)
|
| 909 |
+
mask_cls_results = all_cls_scores[-1]
|
| 910 |
+
mask_pred_results = all_mask_preds[-1]
|
| 911 |
+
if 'pad_shape' in batch_img_metas[0]:
|
| 912 |
+
size = batch_img_metas[0]['pad_shape']
|
| 913 |
+
else:
|
| 914 |
+
size = batch_img_metas[0]['img_shape']
|
| 915 |
+
# upsample mask
|
| 916 |
+
mask_pred_results = F.interpolate(
|
| 917 |
+
mask_pred_results, size=size, mode='bilinear', align_corners=False)
|
| 918 |
+
cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1]
|
| 919 |
+
mask_pred = mask_pred_results.sigmoid()
|
| 920 |
+
seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred)
|
| 921 |
+
return seg_logits
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/isa_head.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from mmcv.cnn import ConvModule
|
| 7 |
+
|
| 8 |
+
from mmseg.registry import MODELS
|
| 9 |
+
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
|
| 10 |
+
from .decode_head import BaseDecodeHead
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SelfAttentionBlock(_SelfAttentionBlock):
|
| 14 |
+
"""Self-Attention Module.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
in_channels (int): Input channels of key/query feature.
|
| 18 |
+
channels (int): Output channels of key/query transform.
|
| 19 |
+
conv_cfg (dict | None): Config of conv layers.
|
| 20 |
+
norm_cfg (dict | None): Config of norm layers.
|
| 21 |
+
act_cfg (dict | None): Config of activation layers.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, in_channels, channels, conv_cfg, norm_cfg, act_cfg):
|
| 25 |
+
super().__init__(
|
| 26 |
+
key_in_channels=in_channels,
|
| 27 |
+
query_in_channels=in_channels,
|
| 28 |
+
channels=channels,
|
| 29 |
+
out_channels=in_channels,
|
| 30 |
+
share_key_query=False,
|
| 31 |
+
query_downsample=None,
|
| 32 |
+
key_downsample=None,
|
| 33 |
+
key_query_num_convs=2,
|
| 34 |
+
key_query_norm=True,
|
| 35 |
+
value_out_num_convs=1,
|
| 36 |
+
value_out_norm=False,
|
| 37 |
+
matmul_norm=True,
|
| 38 |
+
with_out=False,
|
| 39 |
+
conv_cfg=conv_cfg,
|
| 40 |
+
norm_cfg=norm_cfg,
|
| 41 |
+
act_cfg=act_cfg)
|
| 42 |
+
|
| 43 |
+
self.output_project = self.build_project(
|
| 44 |
+
in_channels,
|
| 45 |
+
in_channels,
|
| 46 |
+
num_convs=1,
|
| 47 |
+
use_conv_module=True,
|
| 48 |
+
conv_cfg=conv_cfg,
|
| 49 |
+
norm_cfg=norm_cfg,
|
| 50 |
+
act_cfg=act_cfg)
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
"""Forward function."""
|
| 54 |
+
context = super().forward(x, x)
|
| 55 |
+
return self.output_project(context)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@MODELS.register_module()
|
| 59 |
+
class ISAHead(BaseDecodeHead):
|
| 60 |
+
"""Interlaced Sparse Self-Attention for Semantic Segmentation.
|
| 61 |
+
|
| 62 |
+
This head is the implementation of `ISA
|
| 63 |
+
<https://arxiv.org/abs/1907.12273>`_.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
isa_channels (int): The channels of ISA Module.
|
| 67 |
+
down_factor (tuple[int]): The local group size of ISA.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, isa_channels, down_factor=(8, 8), **kwargs):
|
| 71 |
+
super().__init__(**kwargs)
|
| 72 |
+
self.down_factor = down_factor
|
| 73 |
+
|
| 74 |
+
self.in_conv = ConvModule(
|
| 75 |
+
self.in_channels,
|
| 76 |
+
self.channels,
|
| 77 |
+
3,
|
| 78 |
+
padding=1,
|
| 79 |
+
conv_cfg=self.conv_cfg,
|
| 80 |
+
norm_cfg=self.norm_cfg,
|
| 81 |
+
act_cfg=self.act_cfg)
|
| 82 |
+
self.global_relation = SelfAttentionBlock(
|
| 83 |
+
self.channels,
|
| 84 |
+
isa_channels,
|
| 85 |
+
conv_cfg=self.conv_cfg,
|
| 86 |
+
norm_cfg=self.norm_cfg,
|
| 87 |
+
act_cfg=self.act_cfg)
|
| 88 |
+
self.local_relation = SelfAttentionBlock(
|
| 89 |
+
self.channels,
|
| 90 |
+
isa_channels,
|
| 91 |
+
conv_cfg=self.conv_cfg,
|
| 92 |
+
norm_cfg=self.norm_cfg,
|
| 93 |
+
act_cfg=self.act_cfg)
|
| 94 |
+
self.out_conv = ConvModule(
|
| 95 |
+
self.channels * 2,
|
| 96 |
+
self.channels,
|
| 97 |
+
1,
|
| 98 |
+
conv_cfg=self.conv_cfg,
|
| 99 |
+
norm_cfg=self.norm_cfg,
|
| 100 |
+
act_cfg=self.act_cfg)
|
| 101 |
+
|
| 102 |
+
def forward(self, inputs):
|
| 103 |
+
"""Forward function."""
|
| 104 |
+
x_ = self._transform_inputs(inputs)
|
| 105 |
+
x = self.in_conv(x_)
|
| 106 |
+
residual = x
|
| 107 |
+
|
| 108 |
+
n, c, h, w = x.size()
|
| 109 |
+
loc_h, loc_w = self.down_factor # size of local group in H- and W-axes
|
| 110 |
+
glb_h, glb_w = math.ceil(h / loc_h), math.ceil(w / loc_w)
|
| 111 |
+
pad_h, pad_w = glb_h * loc_h - h, glb_w * loc_w - w
|
| 112 |
+
if pad_h > 0 or pad_w > 0: # pad if the size is not divisible
|
| 113 |
+
padding = (pad_w // 2, pad_w - pad_w // 2, pad_h // 2,
|
| 114 |
+
pad_h - pad_h // 2)
|
| 115 |
+
x = F.pad(x, padding)
|
| 116 |
+
|
| 117 |
+
# global relation
|
| 118 |
+
x = x.view(n, c, glb_h, loc_h, glb_w, loc_w)
|
| 119 |
+
# do permutation to gather global group
|
| 120 |
+
x = x.permute(0, 3, 5, 1, 2, 4) # (n, loc_h, loc_w, c, glb_h, glb_w)
|
| 121 |
+
x = x.reshape(-1, c, glb_h, glb_w)
|
| 122 |
+
# apply attention within each global group
|
| 123 |
+
x = self.global_relation(x) # (n * loc_h * loc_w, c, glb_h, glb_w)
|
| 124 |
+
|
| 125 |
+
# local relation
|
| 126 |
+
x = x.view(n, loc_h, loc_w, c, glb_h, glb_w)
|
| 127 |
+
# do permutation to gather local group
|
| 128 |
+
x = x.permute(0, 4, 5, 3, 1, 2) # (n, glb_h, glb_w, c, loc_h, loc_w)
|
| 129 |
+
x = x.reshape(-1, c, loc_h, loc_w)
|
| 130 |
+
# apply attention within each local group
|
| 131 |
+
x = self.local_relation(x) # (n * glb_h * glb_w, c, loc_h, loc_w)
|
| 132 |
+
|
| 133 |
+
# permute each pixel back to its original position
|
| 134 |
+
x = x.view(n, glb_h, glb_w, c, loc_h, loc_w)
|
| 135 |
+
x = x.permute(0, 3, 1, 4, 2, 5) # (n, c, glb_h, loc_h, glb_w, loc_w)
|
| 136 |
+
x = x.reshape(n, c, glb_h * loc_h, glb_w * loc_w)
|
| 137 |
+
if pad_h > 0 or pad_w > 0: # remove padding
|
| 138 |
+
x = x[:, :, pad_h // 2:pad_h // 2 + h, pad_w // 2:pad_w // 2 + w]
|
| 139 |
+
|
| 140 |
+
x = self.out_conv(torch.cat([x, residual], dim=1))
|
| 141 |
+
out = self.cls_seg(x)
|
| 142 |
+
|
| 143 |
+
return out
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/knet_head.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer
|
| 8 |
+
from mmcv.cnn.bricks.transformer import (FFN, MultiheadAttention,
|
| 9 |
+
build_transformer_layer)
|
| 10 |
+
from mmengine.logging import print_log
|
| 11 |
+
from torch import Tensor
|
| 12 |
+
|
| 13 |
+
from mmseg.models.decode_heads.decode_head import BaseDecodeHead
|
| 14 |
+
from mmseg.registry import MODELS
|
| 15 |
+
from mmseg.utils import SampleList
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@MODELS.register_module()
|
| 19 |
+
class KernelUpdator(nn.Module):
|
| 20 |
+
"""Dynamic Kernel Updator in Kernel Update Head.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
in_channels (int): The number of channels of input feature map.
|
| 24 |
+
Default: 256.
|
| 25 |
+
feat_channels (int): The number of middle-stage channels in
|
| 26 |
+
the kernel updator. Default: 64.
|
| 27 |
+
out_channels (int): The number of output channels.
|
| 28 |
+
gate_sigmoid (bool): Whether use sigmoid function in gate
|
| 29 |
+
mechanism. Default: True.
|
| 30 |
+
gate_norm_act (bool): Whether add normalization and activation
|
| 31 |
+
layer in gate mechanism. Default: False.
|
| 32 |
+
activate_out: Whether add activation after gate mechanism.
|
| 33 |
+
Default: False.
|
| 34 |
+
norm_cfg (dict | None): Config of norm layers.
|
| 35 |
+
Default: dict(type='LN').
|
| 36 |
+
act_cfg (dict): Config of activation layers.
|
| 37 |
+
Default: dict(type='ReLU').
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
in_channels=256,
|
| 43 |
+
feat_channels=64,
|
| 44 |
+
out_channels=None,
|
| 45 |
+
gate_sigmoid=True,
|
| 46 |
+
gate_norm_act=False,
|
| 47 |
+
activate_out=False,
|
| 48 |
+
norm_cfg=dict(type='LN'),
|
| 49 |
+
act_cfg=dict(type='ReLU', inplace=True),
|
| 50 |
+
):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.in_channels = in_channels
|
| 53 |
+
self.feat_channels = feat_channels
|
| 54 |
+
self.out_channels_raw = out_channels
|
| 55 |
+
self.gate_sigmoid = gate_sigmoid
|
| 56 |
+
self.gate_norm_act = gate_norm_act
|
| 57 |
+
self.activate_out = activate_out
|
| 58 |
+
self.act_cfg = act_cfg
|
| 59 |
+
self.norm_cfg = norm_cfg
|
| 60 |
+
self.out_channels = out_channels if out_channels else in_channels
|
| 61 |
+
|
| 62 |
+
self.num_params_in = self.feat_channels
|
| 63 |
+
self.num_params_out = self.feat_channels
|
| 64 |
+
self.dynamic_layer = nn.Linear(
|
| 65 |
+
self.in_channels, self.num_params_in + self.num_params_out)
|
| 66 |
+
self.input_layer = nn.Linear(self.in_channels,
|
| 67 |
+
self.num_params_in + self.num_params_out,
|
| 68 |
+
1)
|
| 69 |
+
self.input_gate = nn.Linear(self.in_channels, self.feat_channels, 1)
|
| 70 |
+
self.update_gate = nn.Linear(self.in_channels, self.feat_channels, 1)
|
| 71 |
+
if self.gate_norm_act:
|
| 72 |
+
self.gate_norm = build_norm_layer(norm_cfg, self.feat_channels)[1]
|
| 73 |
+
|
| 74 |
+
self.norm_in = build_norm_layer(norm_cfg, self.feat_channels)[1]
|
| 75 |
+
self.norm_out = build_norm_layer(norm_cfg, self.feat_channels)[1]
|
| 76 |
+
self.input_norm_in = build_norm_layer(norm_cfg, self.feat_channels)[1]
|
| 77 |
+
self.input_norm_out = build_norm_layer(norm_cfg, self.feat_channels)[1]
|
| 78 |
+
|
| 79 |
+
self.activation = build_activation_layer(act_cfg)
|
| 80 |
+
|
| 81 |
+
self.fc_layer = nn.Linear(self.feat_channels, self.out_channels, 1)
|
| 82 |
+
self.fc_norm = build_norm_layer(norm_cfg, self.out_channels)[1]
|
| 83 |
+
|
| 84 |
+
def forward(self, update_feature, input_feature):
|
| 85 |
+
"""Forward function of KernelUpdator.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
update_feature (torch.Tensor): Feature map assembled from
|
| 89 |
+
each group. It would be reshaped with last dimension
|
| 90 |
+
shape: `self.in_channels`.
|
| 91 |
+
input_feature (torch.Tensor): Intermediate feature
|
| 92 |
+
with shape: (N, num_classes, conv_kernel_size**2, channels).
|
| 93 |
+
Returns:
|
| 94 |
+
Tensor: The output tensor of shape (N*C1/C2, K*K, C2), where N is
|
| 95 |
+
the number of classes, C1 and C2 are the feature map channels of
|
| 96 |
+
KernelUpdateHead and KernelUpdator, respectively.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
update_feature = update_feature.reshape(-1, self.in_channels)
|
| 100 |
+
num_proposals = update_feature.size(0)
|
| 101 |
+
# dynamic_layer works for
|
| 102 |
+
# phi_1 and psi_3 in Eq.(4) and (5) of K-Net paper
|
| 103 |
+
parameters = self.dynamic_layer(update_feature)
|
| 104 |
+
param_in = parameters[:, :self.num_params_in].view(
|
| 105 |
+
-1, self.feat_channels)
|
| 106 |
+
param_out = parameters[:, -self.num_params_out:].view(
|
| 107 |
+
-1, self.feat_channels)
|
| 108 |
+
|
| 109 |
+
# input_layer works for
|
| 110 |
+
# phi_2 and psi_4 in Eq.(4) and (5) of K-Net paper
|
| 111 |
+
input_feats = self.input_layer(
|
| 112 |
+
input_feature.reshape(num_proposals, -1, self.feat_channels))
|
| 113 |
+
input_in = input_feats[..., :self.num_params_in]
|
| 114 |
+
input_out = input_feats[..., -self.num_params_out:]
|
| 115 |
+
|
| 116 |
+
# `gate_feats` is F^G in K-Net paper
|
| 117 |
+
gate_feats = input_in * param_in.unsqueeze(-2)
|
| 118 |
+
if self.gate_norm_act:
|
| 119 |
+
gate_feats = self.activation(self.gate_norm(gate_feats))
|
| 120 |
+
|
| 121 |
+
input_gate = self.input_norm_in(self.input_gate(gate_feats))
|
| 122 |
+
update_gate = self.norm_in(self.update_gate(gate_feats))
|
| 123 |
+
if self.gate_sigmoid:
|
| 124 |
+
input_gate = input_gate.sigmoid()
|
| 125 |
+
update_gate = update_gate.sigmoid()
|
| 126 |
+
param_out = self.norm_out(param_out)
|
| 127 |
+
input_out = self.input_norm_out(input_out)
|
| 128 |
+
|
| 129 |
+
if self.activate_out:
|
| 130 |
+
param_out = self.activation(param_out)
|
| 131 |
+
input_out = self.activation(input_out)
|
| 132 |
+
|
| 133 |
+
# Gate mechanism. Eq.(5) in original paper.
|
| 134 |
+
# param_out has shape (batch_size, feat_channels, out_channels)
|
| 135 |
+
features = update_gate * param_out.unsqueeze(
|
| 136 |
+
-2) + input_gate * input_out
|
| 137 |
+
|
| 138 |
+
features = self.fc_layer(features)
|
| 139 |
+
features = self.fc_norm(features)
|
| 140 |
+
features = self.activation(features)
|
| 141 |
+
|
| 142 |
+
return features
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@MODELS.register_module()
|
| 146 |
+
class KernelUpdateHead(nn.Module):
|
| 147 |
+
"""Kernel Update Head in K-Net.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
num_classes (int): Number of classes. Default: 150.
|
| 151 |
+
num_ffn_fcs (int): The number of fully-connected layers in
|
| 152 |
+
FFNs. Default: 2.
|
| 153 |
+
num_heads (int): The number of parallel attention heads.
|
| 154 |
+
Default: 8.
|
| 155 |
+
num_mask_fcs (int): The number of fully connected layers for
|
| 156 |
+
mask prediction. Default: 3.
|
| 157 |
+
feedforward_channels (int): The hidden dimension of FFNs.
|
| 158 |
+
Defaults: 2048.
|
| 159 |
+
in_channels (int): The number of channels of input feature map.
|
| 160 |
+
Default: 256.
|
| 161 |
+
out_channels (int): The number of output channels.
|
| 162 |
+
Default: 256.
|
| 163 |
+
dropout (float): The Probability of an element to be
|
| 164 |
+
zeroed in MultiheadAttention and FFN. Default 0.0.
|
| 165 |
+
act_cfg (dict): Config of activation layers.
|
| 166 |
+
Default: dict(type='ReLU').
|
| 167 |
+
ffn_act_cfg (dict): Config of activation layers in FFN.
|
| 168 |
+
Default: dict(type='ReLU').
|
| 169 |
+
conv_kernel_size (int): The kernel size of convolution in
|
| 170 |
+
Kernel Update Head for dynamic kernel updation.
|
| 171 |
+
Default: 1.
|
| 172 |
+
feat_transform_cfg (dict | None): Config of feature transform.
|
| 173 |
+
Default: None.
|
| 174 |
+
kernel_init (bool): Whether initiate mask kernel in mask head.
|
| 175 |
+
Default: False.
|
| 176 |
+
with_ffn (bool): Whether add FFN in kernel update head.
|
| 177 |
+
Default: True.
|
| 178 |
+
feat_gather_stride (int): Stride of convolution in feature transform.
|
| 179 |
+
Default: 1.
|
| 180 |
+
mask_transform_stride (int): Stride of mask transform.
|
| 181 |
+
Default: 1.
|
| 182 |
+
kernel_updator_cfg (dict): Config of kernel updator.
|
| 183 |
+
Default: dict(
|
| 184 |
+
type='DynamicConv',
|
| 185 |
+
in_channels=256,
|
| 186 |
+
feat_channels=64,
|
| 187 |
+
out_channels=256,
|
| 188 |
+
act_cfg=dict(type='ReLU', inplace=True),
|
| 189 |
+
norm_cfg=dict(type='LN')).
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
def __init__(self,
|
| 193 |
+
num_classes=150,
|
| 194 |
+
num_ffn_fcs=2,
|
| 195 |
+
num_heads=8,
|
| 196 |
+
num_mask_fcs=3,
|
| 197 |
+
feedforward_channels=2048,
|
| 198 |
+
in_channels=256,
|
| 199 |
+
out_channels=256,
|
| 200 |
+
dropout=0.0,
|
| 201 |
+
act_cfg=dict(type='ReLU', inplace=True),
|
| 202 |
+
ffn_act_cfg=dict(type='ReLU', inplace=True),
|
| 203 |
+
conv_kernel_size=1,
|
| 204 |
+
feat_transform_cfg=None,
|
| 205 |
+
kernel_init=False,
|
| 206 |
+
with_ffn=True,
|
| 207 |
+
feat_gather_stride=1,
|
| 208 |
+
mask_transform_stride=1,
|
| 209 |
+
kernel_updator_cfg=dict(
|
| 210 |
+
type='DynamicConv',
|
| 211 |
+
in_channels=256,
|
| 212 |
+
feat_channels=64,
|
| 213 |
+
out_channels=256,
|
| 214 |
+
act_cfg=dict(type='ReLU', inplace=True),
|
| 215 |
+
norm_cfg=dict(type='LN'))):
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.num_classes = num_classes
|
| 218 |
+
self.in_channels = in_channels
|
| 219 |
+
self.out_channels = out_channels
|
| 220 |
+
self.fp16_enabled = False
|
| 221 |
+
self.dropout = dropout
|
| 222 |
+
self.num_heads = num_heads
|
| 223 |
+
self.kernel_init = kernel_init
|
| 224 |
+
self.with_ffn = with_ffn
|
| 225 |
+
self.conv_kernel_size = conv_kernel_size
|
| 226 |
+
self.feat_gather_stride = feat_gather_stride
|
| 227 |
+
self.mask_transform_stride = mask_transform_stride
|
| 228 |
+
|
| 229 |
+
self.attention = MultiheadAttention(in_channels * conv_kernel_size**2,
|
| 230 |
+
num_heads, dropout)
|
| 231 |
+
self.attention_norm = build_norm_layer(
|
| 232 |
+
dict(type='LN'), in_channels * conv_kernel_size**2)[1]
|
| 233 |
+
self.kernel_update_conv = build_transformer_layer(kernel_updator_cfg)
|
| 234 |
+
|
| 235 |
+
if feat_transform_cfg is not None:
|
| 236 |
+
kernel_size = feat_transform_cfg.pop('kernel_size', 1)
|
| 237 |
+
transform_channels = in_channels
|
| 238 |
+
self.feat_transform = ConvModule(
|
| 239 |
+
transform_channels,
|
| 240 |
+
in_channels,
|
| 241 |
+
kernel_size,
|
| 242 |
+
stride=feat_gather_stride,
|
| 243 |
+
padding=int(feat_gather_stride // 2),
|
| 244 |
+
**feat_transform_cfg)
|
| 245 |
+
else:
|
| 246 |
+
self.feat_transform = None
|
| 247 |
+
|
| 248 |
+
if self.with_ffn:
|
| 249 |
+
self.ffn = FFN(
|
| 250 |
+
in_channels,
|
| 251 |
+
feedforward_channels,
|
| 252 |
+
num_ffn_fcs,
|
| 253 |
+
act_cfg=ffn_act_cfg,
|
| 254 |
+
dropout=dropout)
|
| 255 |
+
self.ffn_norm = build_norm_layer(dict(type='LN'), in_channels)[1]
|
| 256 |
+
|
| 257 |
+
self.mask_fcs = nn.ModuleList()
|
| 258 |
+
for _ in range(num_mask_fcs):
|
| 259 |
+
self.mask_fcs.append(
|
| 260 |
+
nn.Linear(in_channels, in_channels, bias=False))
|
| 261 |
+
self.mask_fcs.append(
|
| 262 |
+
build_norm_layer(dict(type='LN'), in_channels)[1])
|
| 263 |
+
self.mask_fcs.append(build_activation_layer(act_cfg))
|
| 264 |
+
|
| 265 |
+
self.fc_mask = nn.Linear(in_channels, out_channels)
|
| 266 |
+
|
| 267 |
+
def init_weights(self):
|
| 268 |
+
"""Use xavier initialization for all weight parameter and set
|
| 269 |
+
classification head bias as a specific value when use focal loss."""
|
| 270 |
+
for p in self.parameters():
|
| 271 |
+
if p.dim() > 1:
|
| 272 |
+
nn.init.xavier_uniform_(p)
|
| 273 |
+
else:
|
| 274 |
+
# adopt the default initialization for
|
| 275 |
+
# the weight and bias of the layer norm
|
| 276 |
+
pass
|
| 277 |
+
if self.kernel_init:
|
| 278 |
+
print_log(
|
| 279 |
+
'mask kernel in mask head is normal initialized by std 0.01')
|
| 280 |
+
nn.init.normal_(self.fc_mask.weight, mean=0, std=0.01)
|
| 281 |
+
|
| 282 |
+
def forward(self, x, proposal_feat, mask_preds, mask_shape=None):
|
| 283 |
+
"""Forward function of Dynamic Instance Interactive Head.
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
x (Tensor): Feature map from FPN with shape
|
| 287 |
+
(batch_size, feature_dimensions, H , W).
|
| 288 |
+
proposal_feat (Tensor): Intermediate feature get from
|
| 289 |
+
diihead in last stage, has shape
|
| 290 |
+
(batch_size, num_proposals, feature_dimensions)
|
| 291 |
+
mask_preds (Tensor): mask prediction from the former stage in shape
|
| 292 |
+
(batch_size, num_proposals, H, W).
|
| 293 |
+
|
| 294 |
+
Returns:
|
| 295 |
+
Tuple: The first tensor is predicted mask with shape
|
| 296 |
+
(N, num_classes, H, W), the second tensor is dynamic kernel
|
| 297 |
+
with shape (N, num_classes, channels, K, K).
|
| 298 |
+
"""
|
| 299 |
+
N, num_proposals = proposal_feat.shape[:2]
|
| 300 |
+
if self.feat_transform is not None:
|
| 301 |
+
x = self.feat_transform(x)
|
| 302 |
+
|
| 303 |
+
C, H, W = x.shape[-3:]
|
| 304 |
+
|
| 305 |
+
mask_h, mask_w = mask_preds.shape[-2:]
|
| 306 |
+
if mask_h != H or mask_w != W:
|
| 307 |
+
gather_mask = F.interpolate(
|
| 308 |
+
mask_preds, (H, W), align_corners=False, mode='bilinear')
|
| 309 |
+
else:
|
| 310 |
+
gather_mask = mask_preds
|
| 311 |
+
|
| 312 |
+
sigmoid_masks = gather_mask.softmax(dim=1)
|
| 313 |
+
|
| 314 |
+
# Group Feature Assembling. Eq.(3) in original paper.
|
| 315 |
+
# einsum is faster than bmm by 30%
|
| 316 |
+
x_feat = torch.einsum('bnhw,bchw->bnc', sigmoid_masks, x)
|
| 317 |
+
|
| 318 |
+
# obj_feat in shape [B, N, C, K, K] -> [B, N, C, K*K] -> [B, N, K*K, C]
|
| 319 |
+
proposal_feat = proposal_feat.reshape(N, num_proposals,
|
| 320 |
+
self.in_channels,
|
| 321 |
+
-1).permute(0, 1, 3, 2)
|
| 322 |
+
obj_feat = self.kernel_update_conv(x_feat, proposal_feat)
|
| 323 |
+
|
| 324 |
+
# [B, N, K*K, C] -> [B, N, K*K*C] -> [N, B, K*K*C]
|
| 325 |
+
obj_feat = obj_feat.reshape(N, num_proposals, -1).permute(1, 0, 2)
|
| 326 |
+
obj_feat = self.attention_norm(self.attention(obj_feat))
|
| 327 |
+
# [N, B, K*K*C] -> [B, N, K*K*C]
|
| 328 |
+
obj_feat = obj_feat.permute(1, 0, 2)
|
| 329 |
+
|
| 330 |
+
# obj_feat in shape [B, N, K*K*C] -> [B, N, K*K, C]
|
| 331 |
+
obj_feat = obj_feat.reshape(N, num_proposals, -1, self.in_channels)
|
| 332 |
+
|
| 333 |
+
# FFN
|
| 334 |
+
if self.with_ffn:
|
| 335 |
+
obj_feat = self.ffn_norm(self.ffn(obj_feat))
|
| 336 |
+
|
| 337 |
+
mask_feat = obj_feat
|
| 338 |
+
|
| 339 |
+
for reg_layer in self.mask_fcs:
|
| 340 |
+
mask_feat = reg_layer(mask_feat)
|
| 341 |
+
|
| 342 |
+
# [B, N, K*K, C] -> [B, N, C, K*K]
|
| 343 |
+
mask_feat = self.fc_mask(mask_feat).permute(0, 1, 3, 2)
|
| 344 |
+
|
| 345 |
+
if (self.mask_transform_stride == 2 and self.feat_gather_stride == 1):
|
| 346 |
+
mask_x = F.interpolate(
|
| 347 |
+
x, scale_factor=0.5, mode='bilinear', align_corners=False)
|
| 348 |
+
H, W = mask_x.shape[-2:]
|
| 349 |
+
else:
|
| 350 |
+
mask_x = x
|
| 351 |
+
# group conv is 5x faster than unfold and uses about 1/5 memory
|
| 352 |
+
# Group conv vs. unfold vs. concat batch, 2.9ms :13.5ms :3.8ms
|
| 353 |
+
# Group conv vs. unfold vs. concat batch, 278 : 1420 : 369
|
| 354 |
+
# but in real training group conv is slower than concat batch
|
| 355 |
+
# so we keep using concat batch.
|
| 356 |
+
# fold_x = F.unfold(
|
| 357 |
+
# mask_x,
|
| 358 |
+
# self.conv_kernel_size,
|
| 359 |
+
# padding=int(self.conv_kernel_size // 2))
|
| 360 |
+
# mask_feat = mask_feat.reshape(N, num_proposals, -1)
|
| 361 |
+
# new_mask_preds = torch.einsum('bnc,bcl->bnl', mask_feat, fold_x)
|
| 362 |
+
# [B, N, C, K*K] -> [B*N, C, K, K]
|
| 363 |
+
mask_feat = mask_feat.reshape(N, num_proposals, C,
|
| 364 |
+
self.conv_kernel_size,
|
| 365 |
+
self.conv_kernel_size)
|
| 366 |
+
# [B, C, H, W] -> [1, B*C, H, W]
|
| 367 |
+
new_mask_preds = []
|
| 368 |
+
for i in range(N):
|
| 369 |
+
new_mask_preds.append(
|
| 370 |
+
F.conv2d(
|
| 371 |
+
mask_x[i:i + 1],
|
| 372 |
+
mask_feat[i],
|
| 373 |
+
padding=int(self.conv_kernel_size // 2)))
|
| 374 |
+
|
| 375 |
+
new_mask_preds = torch.cat(new_mask_preds, dim=0)
|
| 376 |
+
new_mask_preds = new_mask_preds.reshape(N, num_proposals, H, W)
|
| 377 |
+
if self.mask_transform_stride == 2:
|
| 378 |
+
new_mask_preds = F.interpolate(
|
| 379 |
+
new_mask_preds,
|
| 380 |
+
scale_factor=2,
|
| 381 |
+
mode='bilinear',
|
| 382 |
+
align_corners=False)
|
| 383 |
+
|
| 384 |
+
if mask_shape is not None and mask_shape[0] != H:
|
| 385 |
+
new_mask_preds = F.interpolate(
|
| 386 |
+
new_mask_preds,
|
| 387 |
+
mask_shape,
|
| 388 |
+
align_corners=False,
|
| 389 |
+
mode='bilinear')
|
| 390 |
+
|
| 391 |
+
return new_mask_preds, obj_feat.permute(0, 1, 3, 2).reshape(
|
| 392 |
+
N, num_proposals, self.in_channels, self.conv_kernel_size,
|
| 393 |
+
self.conv_kernel_size)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
@MODELS.register_module()
|
| 397 |
+
class IterativeDecodeHead(BaseDecodeHead):
|
| 398 |
+
"""K-Net: Towards Unified Image Segmentation.
|
| 399 |
+
|
| 400 |
+
This head is the implementation of
|
| 401 |
+
`K-Net: <https://arxiv.org/abs/2106.14855>`_.
|
| 402 |
+
|
| 403 |
+
Args:
|
| 404 |
+
num_stages (int): The number of stages (kernel update heads)
|
| 405 |
+
in IterativeDecodeHead. Default: 3.
|
| 406 |
+
kernel_generate_head:(dict): Config of kernel generate head which
|
| 407 |
+
generate mask predictions, dynamic kernels and class predictions
|
| 408 |
+
for next kernel update heads.
|
| 409 |
+
kernel_update_head (dict): Config of kernel update head which refine
|
| 410 |
+
dynamic kernels and class predictions iteratively.
|
| 411 |
+
|
| 412 |
+
"""
|
| 413 |
+
|
| 414 |
+
def __init__(self, num_stages, kernel_generate_head, kernel_update_head,
|
| 415 |
+
**kwargs):
|
| 416 |
+
# ``IterativeDecodeHead`` would skip initialization of
|
| 417 |
+
# ``BaseDecodeHead`` which would be called when building
|
| 418 |
+
# ``self.kernel_generate_head``.
|
| 419 |
+
super(BaseDecodeHead, self).__init__(**kwargs)
|
| 420 |
+
assert num_stages == len(kernel_update_head)
|
| 421 |
+
self.num_stages = num_stages
|
| 422 |
+
self.kernel_generate_head = MODELS.build(kernel_generate_head)
|
| 423 |
+
self.kernel_update_head = nn.ModuleList()
|
| 424 |
+
self.align_corners = self.kernel_generate_head.align_corners
|
| 425 |
+
self.num_classes = self.kernel_generate_head.num_classes
|
| 426 |
+
self.input_transform = self.kernel_generate_head.input_transform
|
| 427 |
+
self.ignore_index = self.kernel_generate_head.ignore_index
|
| 428 |
+
self.out_channels = self.num_classes
|
| 429 |
+
|
| 430 |
+
for head_cfg in kernel_update_head:
|
| 431 |
+
self.kernel_update_head.append(MODELS.build(head_cfg))
|
| 432 |
+
|
| 433 |
+
def forward(self, inputs):
|
| 434 |
+
"""Forward function."""
|
| 435 |
+
feats = self.kernel_generate_head._forward_feature(inputs)
|
| 436 |
+
sem_seg = self.kernel_generate_head.cls_seg(feats)
|
| 437 |
+
seg_kernels = self.kernel_generate_head.conv_seg.weight.clone()
|
| 438 |
+
seg_kernels = seg_kernels[None].expand(
|
| 439 |
+
feats.size(0), *seg_kernels.size())
|
| 440 |
+
|
| 441 |
+
stage_segs = [sem_seg]
|
| 442 |
+
for i in range(self.num_stages):
|
| 443 |
+
sem_seg, seg_kernels = self.kernel_update_head[i](feats,
|
| 444 |
+
seg_kernels,
|
| 445 |
+
sem_seg)
|
| 446 |
+
stage_segs.append(sem_seg)
|
| 447 |
+
if self.training:
|
| 448 |
+
return stage_segs
|
| 449 |
+
# only return the prediction of the last stage during testing
|
| 450 |
+
return stage_segs[-1]
|
| 451 |
+
|
| 452 |
+
def loss_by_feat(self, seg_logits: List[Tensor],
|
| 453 |
+
batch_data_samples: SampleList, **kwargs) -> dict:
|
| 454 |
+
losses = dict()
|
| 455 |
+
for i, logit in enumerate(seg_logits):
|
| 456 |
+
loss = self.kernel_generate_head.loss_by_feat(
|
| 457 |
+
logit, batch_data_samples)
|
| 458 |
+
for k, v in loss.items():
|
| 459 |
+
losses[f'{k}.s{i}'] = v
|
| 460 |
+
|
| 461 |
+
return losses
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/lraspp_head.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
from mmengine.utils import is_tuple_of
|
| 6 |
+
|
| 7 |
+
from mmseg.registry import MODELS
|
| 8 |
+
from ..utils import resize
|
| 9 |
+
from .decode_head import BaseDecodeHead
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@MODELS.register_module()
|
| 13 |
+
class LRASPPHead(BaseDecodeHead):
|
| 14 |
+
"""Lite R-ASPP (LRASPP) head is proposed in Searching for MobileNetV3.
|
| 15 |
+
|
| 16 |
+
This head is the improved implementation of `Searching for MobileNetV3
|
| 17 |
+
<https://ieeexplore.ieee.org/document/9008835>`_.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
branch_channels (tuple[int]): The number of output channels in every
|
| 21 |
+
each branch. Default: (32, 64).
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, branch_channels=(32, 64), **kwargs):
|
| 25 |
+
super().__init__(**kwargs)
|
| 26 |
+
if self.input_transform != 'multiple_select':
|
| 27 |
+
raise ValueError('in Lite R-ASPP (LRASPP) head, input_transform '
|
| 28 |
+
f'must be \'multiple_select\'. But received '
|
| 29 |
+
f'\'{self.input_transform}\'')
|
| 30 |
+
assert is_tuple_of(branch_channels, int)
|
| 31 |
+
assert len(branch_channels) == len(self.in_channels) - 1
|
| 32 |
+
self.branch_channels = branch_channels
|
| 33 |
+
|
| 34 |
+
self.convs = nn.Sequential()
|
| 35 |
+
self.conv_ups = nn.Sequential()
|
| 36 |
+
for i in range(len(branch_channels)):
|
| 37 |
+
self.convs.add_module(
|
| 38 |
+
f'conv{i}',
|
| 39 |
+
nn.Conv2d(
|
| 40 |
+
self.in_channels[i], branch_channels[i], 1, bias=False))
|
| 41 |
+
self.conv_ups.add_module(
|
| 42 |
+
f'conv_up{i}',
|
| 43 |
+
ConvModule(
|
| 44 |
+
self.channels + branch_channels[i],
|
| 45 |
+
self.channels,
|
| 46 |
+
1,
|
| 47 |
+
norm_cfg=self.norm_cfg,
|
| 48 |
+
act_cfg=self.act_cfg,
|
| 49 |
+
bias=False))
|
| 50 |
+
|
| 51 |
+
self.conv_up_input = nn.Conv2d(self.channels, self.channels, 1)
|
| 52 |
+
|
| 53 |
+
self.aspp_conv = ConvModule(
|
| 54 |
+
self.in_channels[-1],
|
| 55 |
+
self.channels,
|
| 56 |
+
1,
|
| 57 |
+
norm_cfg=self.norm_cfg,
|
| 58 |
+
act_cfg=self.act_cfg,
|
| 59 |
+
bias=False)
|
| 60 |
+
self.image_pool = nn.Sequential(
|
| 61 |
+
nn.AvgPool2d(kernel_size=49, stride=(16, 20)),
|
| 62 |
+
ConvModule(
|
| 63 |
+
self.in_channels[2],
|
| 64 |
+
self.channels,
|
| 65 |
+
1,
|
| 66 |
+
act_cfg=dict(type='Sigmoid'),
|
| 67 |
+
bias=False))
|
| 68 |
+
|
| 69 |
+
def forward(self, inputs):
|
| 70 |
+
"""Forward function."""
|
| 71 |
+
inputs = self._transform_inputs(inputs)
|
| 72 |
+
|
| 73 |
+
x = inputs[-1]
|
| 74 |
+
|
| 75 |
+
x = self.aspp_conv(x) * resize(
|
| 76 |
+
self.image_pool(x),
|
| 77 |
+
size=x.size()[2:],
|
| 78 |
+
mode='bilinear',
|
| 79 |
+
align_corners=self.align_corners)
|
| 80 |
+
x = self.conv_up_input(x)
|
| 81 |
+
|
| 82 |
+
for i in range(len(self.branch_channels) - 1, -1, -1):
|
| 83 |
+
x = resize(
|
| 84 |
+
x,
|
| 85 |
+
size=inputs[i].size()[2:],
|
| 86 |
+
mode='bilinear',
|
| 87 |
+
align_corners=self.align_corners)
|
| 88 |
+
x = torch.cat([x, self.convs[i](inputs[i])], 1)
|
| 89 |
+
x = self.conv_ups[i](x)
|
| 90 |
+
|
| 91 |
+
return self.cls_seg(x)
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/mask2former_head.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from mmengine.model import BaseModule
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from mmdet.models.dense_heads import \
|
| 11 |
+
Mask2FormerHead as MMDET_Mask2FormerHead
|
| 12 |
+
except ModuleNotFoundError:
|
| 13 |
+
MMDET_Mask2FormerHead = BaseModule
|
| 14 |
+
|
| 15 |
+
from mmengine.structures import InstanceData
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
|
| 18 |
+
from mmseg.registry import MODELS
|
| 19 |
+
from mmseg.structures.seg_data_sample import SegDataSample
|
| 20 |
+
from mmseg.utils import ConfigType, SampleList
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@MODELS.register_module()
|
| 24 |
+
class Mask2FormerHead(MMDET_Mask2FormerHead):
|
| 25 |
+
"""Implements the Mask2Former head.
|
| 26 |
+
|
| 27 |
+
See `Mask2Former: Masked-attention Mask Transformer for Universal Image
|
| 28 |
+
Segmentation <https://arxiv.org/abs/2112.01527>`_ for details.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
num_classes (int): Number of classes. Default: 150.
|
| 32 |
+
align_corners (bool): align_corners argument of F.interpolate.
|
| 33 |
+
Default: False.
|
| 34 |
+
ignore_index (int): The label index to be ignored. Default: 255.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self,
|
| 38 |
+
num_classes,
|
| 39 |
+
align_corners=False,
|
| 40 |
+
ignore_index=255,
|
| 41 |
+
**kwargs):
|
| 42 |
+
super().__init__(**kwargs)
|
| 43 |
+
|
| 44 |
+
self.num_classes = num_classes
|
| 45 |
+
self.align_corners = align_corners
|
| 46 |
+
self.out_channels = num_classes
|
| 47 |
+
self.ignore_index = ignore_index
|
| 48 |
+
|
| 49 |
+
feat_channels = kwargs['feat_channels']
|
| 50 |
+
self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1)
|
| 51 |
+
|
| 52 |
+
def _seg_data_to_instance_data(self, batch_data_samples: SampleList):
|
| 53 |
+
"""Perform forward propagation to convert paradigm from MMSegmentation
|
| 54 |
+
to MMDetection to ensure ``MMDET_Mask2FormerHead`` could be called
|
| 55 |
+
normally. Specifically, ``batch_gt_instances`` would be added.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
batch_data_samples (List[:obj:`SegDataSample`]): The Data
|
| 59 |
+
Samples. It usually includes information such as
|
| 60 |
+
`gt_sem_seg`.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
tuple[Tensor]: A tuple contains two lists.
|
| 64 |
+
|
| 65 |
+
- batch_gt_instances (list[:obj:`InstanceData`]): Batch of
|
| 66 |
+
gt_instance. It usually includes ``labels``, each is
|
| 67 |
+
unique ground truth label id of images, with
|
| 68 |
+
shape (num_gt, ) and ``masks``, each is ground truth
|
| 69 |
+
masks of each instances of a image, shape (num_gt, h, w).
|
| 70 |
+
- batch_img_metas (list[dict]): List of image meta information.
|
| 71 |
+
"""
|
| 72 |
+
batch_img_metas = []
|
| 73 |
+
batch_gt_instances = []
|
| 74 |
+
|
| 75 |
+
for data_sample in batch_data_samples:
|
| 76 |
+
batch_img_metas.append(data_sample.metainfo)
|
| 77 |
+
gt_sem_seg = data_sample.gt_sem_seg.data
|
| 78 |
+
classes = torch.unique(
|
| 79 |
+
gt_sem_seg,
|
| 80 |
+
sorted=False,
|
| 81 |
+
return_inverse=False,
|
| 82 |
+
return_counts=False)
|
| 83 |
+
|
| 84 |
+
# remove ignored region
|
| 85 |
+
gt_labels = classes[classes != self.ignore_index]
|
| 86 |
+
|
| 87 |
+
masks = []
|
| 88 |
+
for class_id in gt_labels:
|
| 89 |
+
masks.append(gt_sem_seg == class_id)
|
| 90 |
+
|
| 91 |
+
if len(masks) == 0:
|
| 92 |
+
gt_masks = torch.zeros(
|
| 93 |
+
(0, gt_sem_seg.shape[-2],
|
| 94 |
+
gt_sem_seg.shape[-1])).to(gt_sem_seg).long()
|
| 95 |
+
else:
|
| 96 |
+
gt_masks = torch.stack(masks).squeeze(1).long()
|
| 97 |
+
|
| 98 |
+
instance_data = InstanceData(labels=gt_labels, masks=gt_masks)
|
| 99 |
+
batch_gt_instances.append(instance_data)
|
| 100 |
+
return batch_gt_instances, batch_img_metas
|
| 101 |
+
|
| 102 |
+
def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList,
|
| 103 |
+
train_cfg: ConfigType) -> dict:
|
| 104 |
+
"""Perform forward propagation and loss calculation of the decoder head
|
| 105 |
+
on the features of the upstream network.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
x (tuple[Tensor]): Multi-level features from the upstream
|
| 109 |
+
network, each is a 4D-tensor.
|
| 110 |
+
batch_data_samples (List[:obj:`SegDataSample`]): The Data
|
| 111 |
+
Samples. It usually includes information such as
|
| 112 |
+
`gt_sem_seg`.
|
| 113 |
+
train_cfg (ConfigType): Training config.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
dict[str, Tensor]: a dictionary of loss components.
|
| 117 |
+
"""
|
| 118 |
+
# batch SegDataSample to InstanceDataSample
|
| 119 |
+
batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data(
|
| 120 |
+
batch_data_samples)
|
| 121 |
+
|
| 122 |
+
# forward
|
| 123 |
+
all_cls_scores, all_mask_preds = self(x, batch_data_samples)
|
| 124 |
+
|
| 125 |
+
# loss
|
| 126 |
+
losses = self.loss_by_feat(all_cls_scores, all_mask_preds,
|
| 127 |
+
batch_gt_instances, batch_img_metas)
|
| 128 |
+
|
| 129 |
+
return losses
|
| 130 |
+
|
| 131 |
+
def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict],
|
| 132 |
+
test_cfg: ConfigType) -> Tuple[Tensor]:
|
| 133 |
+
"""Test without augmentaton.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
x (tuple[Tensor]): Multi-level features from the
|
| 137 |
+
upstream network, each is a 4D-tensor.
|
| 138 |
+
batch_img_metas (List[:obj:`SegDataSample`]): The Data
|
| 139 |
+
Samples. It usually includes information such as
|
| 140 |
+
`gt_sem_seg`.
|
| 141 |
+
test_cfg (ConfigType): Test config.
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
Tensor: A tensor of segmentation mask.
|
| 145 |
+
"""
|
| 146 |
+
batch_data_samples = [
|
| 147 |
+
SegDataSample(metainfo=metainfo) for metainfo in batch_img_metas
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
all_cls_scores, all_mask_preds = self(x, batch_data_samples)
|
| 151 |
+
mask_cls_results = all_cls_scores[-1]
|
| 152 |
+
mask_pred_results = all_mask_preds[-1]
|
| 153 |
+
if 'pad_shape' in batch_img_metas[0]:
|
| 154 |
+
size = batch_img_metas[0]['pad_shape']
|
| 155 |
+
else:
|
| 156 |
+
size = batch_img_metas[0]['img_shape']
|
| 157 |
+
# upsample mask
|
| 158 |
+
mask_pred_results = F.interpolate(
|
| 159 |
+
mask_pred_results, size=size, mode='bilinear', align_corners=False)
|
| 160 |
+
cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1]
|
| 161 |
+
mask_pred = mask_pred_results.sigmoid()
|
| 162 |
+
seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred)
|
| 163 |
+
return seg_logits
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/maskformer_head.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from mmengine.model import BaseModule
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from mmdet.models.dense_heads import MaskFormerHead as MMDET_MaskFormerHead
|
| 11 |
+
except ModuleNotFoundError:
|
| 12 |
+
MMDET_MaskFormerHead = BaseModule
|
| 13 |
+
|
| 14 |
+
from mmengine.structures import InstanceData
|
| 15 |
+
from torch import Tensor
|
| 16 |
+
|
| 17 |
+
from mmseg.registry import MODELS
|
| 18 |
+
from mmseg.structures.seg_data_sample import SegDataSample
|
| 19 |
+
from mmseg.utils import ConfigType, SampleList
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@MODELS.register_module()
|
| 23 |
+
class MaskFormerHead(MMDET_MaskFormerHead):
|
| 24 |
+
"""Implements the MaskFormer head.
|
| 25 |
+
|
| 26 |
+
See `Per-Pixel Classification is Not All You Need for Semantic Segmentation
|
| 27 |
+
<https://arxiv.org/pdf/2107.06278>`_ for details.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
num_classes (int): Number of classes. Default: 150.
|
| 31 |
+
align_corners (bool): align_corners argument of F.interpolate.
|
| 32 |
+
Default: False.
|
| 33 |
+
ignore_index (int): The label index to be ignored. Default: 255.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self,
|
| 37 |
+
num_classes: int = 150,
|
| 38 |
+
align_corners: bool = False,
|
| 39 |
+
ignore_index: int = 255,
|
| 40 |
+
**kwargs) -> None:
|
| 41 |
+
super().__init__(**kwargs)
|
| 42 |
+
|
| 43 |
+
self.out_channels = kwargs['out_channels']
|
| 44 |
+
self.align_corners = True
|
| 45 |
+
self.num_classes = num_classes
|
| 46 |
+
self.align_corners = align_corners
|
| 47 |
+
self.out_channels = num_classes
|
| 48 |
+
self.ignore_index = ignore_index
|
| 49 |
+
|
| 50 |
+
feat_channels = kwargs['feat_channels']
|
| 51 |
+
self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1)
|
| 52 |
+
|
| 53 |
+
def _seg_data_to_instance_data(self, batch_data_samples: SampleList):
|
| 54 |
+
"""Perform forward propagation to convert paradigm from MMSegmentation
|
| 55 |
+
to MMDetection to ensure ``MMDET_MaskFormerHead`` could be called
|
| 56 |
+
normally. Specifically, ``batch_gt_instances`` would be added.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
batch_data_samples (List[:obj:`SegDataSample`]): The Data
|
| 60 |
+
Samples. It usually includes information such as
|
| 61 |
+
`gt_sem_seg`.
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
tuple[Tensor]: A tuple contains two lists.
|
| 65 |
+
|
| 66 |
+
- batch_gt_instances (list[:obj:`InstanceData`]): Batch of
|
| 67 |
+
gt_instance. It usually includes ``labels``, each is
|
| 68 |
+
unique ground truth label id of images, with
|
| 69 |
+
shape (num_gt, ) and ``masks``, each is ground truth
|
| 70 |
+
masks of each instances of a image, shape (num_gt, h, w).
|
| 71 |
+
- batch_img_metas (list[dict]): List of image meta information.
|
| 72 |
+
"""
|
| 73 |
+
batch_img_metas = []
|
| 74 |
+
batch_gt_instances = []
|
| 75 |
+
for data_sample in batch_data_samples:
|
| 76 |
+
# Add `batch_input_shape` in metainfo of data_sample, which would
|
| 77 |
+
# be used in MaskFormerHead of MMDetection.
|
| 78 |
+
metainfo = data_sample.metainfo
|
| 79 |
+
metainfo['batch_input_shape'] = metainfo['img_shape']
|
| 80 |
+
data_sample.set_metainfo(metainfo)
|
| 81 |
+
batch_img_metas.append(data_sample.metainfo)
|
| 82 |
+
gt_sem_seg = data_sample.gt_sem_seg.data
|
| 83 |
+
classes = torch.unique(
|
| 84 |
+
gt_sem_seg,
|
| 85 |
+
sorted=False,
|
| 86 |
+
return_inverse=False,
|
| 87 |
+
return_counts=False)
|
| 88 |
+
|
| 89 |
+
# remove ignored region
|
| 90 |
+
gt_labels = classes[classes != self.ignore_index]
|
| 91 |
+
|
| 92 |
+
masks = []
|
| 93 |
+
for class_id in gt_labels:
|
| 94 |
+
masks.append(gt_sem_seg == class_id)
|
| 95 |
+
|
| 96 |
+
if len(masks) == 0:
|
| 97 |
+
gt_masks = torch.zeros((0, gt_sem_seg.shape[-2],
|
| 98 |
+
gt_sem_seg.shape[-1])).to(gt_sem_seg)
|
| 99 |
+
else:
|
| 100 |
+
gt_masks = torch.stack(masks).squeeze(1)
|
| 101 |
+
|
| 102 |
+
instance_data = InstanceData(
|
| 103 |
+
labels=gt_labels, masks=gt_masks.long())
|
| 104 |
+
batch_gt_instances.append(instance_data)
|
| 105 |
+
return batch_gt_instances, batch_img_metas
|
| 106 |
+
|
| 107 |
+
def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList,
|
| 108 |
+
train_cfg: ConfigType) -> dict:
|
| 109 |
+
"""Perform forward propagation and loss calculation of the decoder head
|
| 110 |
+
on the features of the upstream network.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
x (tuple[Tensor]): Multi-level features from the upstream
|
| 114 |
+
network, each is a 4D-tensor.
|
| 115 |
+
batch_data_samples (List[:obj:`SegDataSample`]): The Data
|
| 116 |
+
Samples. It usually includes information such as
|
| 117 |
+
`gt_sem_seg`.
|
| 118 |
+
train_cfg (ConfigType): Training config.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
dict[str, Tensor]: a dictionary of loss components.
|
| 122 |
+
"""
|
| 123 |
+
# batch SegDataSample to InstanceDataSample
|
| 124 |
+
batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data(
|
| 125 |
+
batch_data_samples)
|
| 126 |
+
|
| 127 |
+
# forward
|
| 128 |
+
all_cls_scores, all_mask_preds = self(x, batch_data_samples)
|
| 129 |
+
|
| 130 |
+
# loss
|
| 131 |
+
losses = self.loss_by_feat(all_cls_scores, all_mask_preds,
|
| 132 |
+
batch_gt_instances, batch_img_metas)
|
| 133 |
+
|
| 134 |
+
return losses
|
| 135 |
+
|
| 136 |
+
def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict],
|
| 137 |
+
test_cfg: ConfigType) -> Tuple[Tensor]:
|
| 138 |
+
"""Test without augmentaton.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
x (tuple[Tensor]): Multi-level features from the
|
| 142 |
+
upstream network, each is a 4D-tensor.
|
| 143 |
+
batch_img_metas (List[:obj:`SegDataSample`]): The Data
|
| 144 |
+
Samples. It usually includes information such as
|
| 145 |
+
`gt_sem_seg`.
|
| 146 |
+
test_cfg (ConfigType): Test config.
|
| 147 |
+
|
| 148 |
+
Returns:
|
| 149 |
+
Tensor: A tensor of segmentation mask.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
batch_data_samples = []
|
| 153 |
+
for metainfo in batch_img_metas:
|
| 154 |
+
metainfo['batch_input_shape'] = metainfo['img_shape']
|
| 155 |
+
batch_data_samples.append(SegDataSample(metainfo=metainfo))
|
| 156 |
+
# Forward function of MaskFormerHead from MMDetection needs
|
| 157 |
+
# 'batch_data_samples' as inputs, which is image shape actually.
|
| 158 |
+
all_cls_scores, all_mask_preds = self(x, batch_data_samples)
|
| 159 |
+
mask_cls_results = all_cls_scores[-1]
|
| 160 |
+
mask_pred_results = all_mask_preds[-1]
|
| 161 |
+
|
| 162 |
+
# upsample masks
|
| 163 |
+
img_shape = batch_img_metas[0]['batch_input_shape']
|
| 164 |
+
mask_pred_results = F.interpolate(
|
| 165 |
+
mask_pred_results,
|
| 166 |
+
size=img_shape,
|
| 167 |
+
mode='bilinear',
|
| 168 |
+
align_corners=False)
|
| 169 |
+
|
| 170 |
+
# semantic inference
|
| 171 |
+
cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1]
|
| 172 |
+
mask_pred = mask_pred_results.sigmoid()
|
| 173 |
+
seg_logits = torch.einsum('bqc,bqhw->bchw', cls_score, mask_pred)
|
| 174 |
+
return seg_logits
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/nl_head.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
from mmcv.cnn import NonLocal2d
|
| 4 |
+
|
| 5 |
+
from mmseg.registry import MODELS
|
| 6 |
+
from .fcn_head import FCNHead
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@MODELS.register_module()
|
| 10 |
+
class NLHead(FCNHead):
|
| 11 |
+
"""Non-local Neural Networks.
|
| 12 |
+
|
| 13 |
+
This head is the implementation of `NLNet
|
| 14 |
+
<https://arxiv.org/abs/1711.07971>`_.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
reduction (int): Reduction factor of projection transform. Default: 2.
|
| 18 |
+
use_scale (bool): Whether to scale pairwise_weight by
|
| 19 |
+
sqrt(1/inter_channels). Default: True.
|
| 20 |
+
mode (str): The nonlocal mode. Options are 'embedded_gaussian',
|
| 21 |
+
'dot_product'. Default: 'embedded_gaussian.'.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self,
|
| 25 |
+
reduction=2,
|
| 26 |
+
use_scale=True,
|
| 27 |
+
mode='embedded_gaussian',
|
| 28 |
+
**kwargs):
|
| 29 |
+
super().__init__(num_convs=2, **kwargs)
|
| 30 |
+
self.reduction = reduction
|
| 31 |
+
self.use_scale = use_scale
|
| 32 |
+
self.mode = mode
|
| 33 |
+
self.nl_block = NonLocal2d(
|
| 34 |
+
in_channels=self.channels,
|
| 35 |
+
reduction=self.reduction,
|
| 36 |
+
use_scale=self.use_scale,
|
| 37 |
+
conv_cfg=self.conv_cfg,
|
| 38 |
+
norm_cfg=self.norm_cfg,
|
| 39 |
+
mode=self.mode)
|
| 40 |
+
|
| 41 |
+
def forward(self, inputs):
|
| 42 |
+
"""Forward function."""
|
| 43 |
+
x = self._transform_inputs(inputs)
|
| 44 |
+
output = self.convs[0](x)
|
| 45 |
+
output = self.nl_block(output)
|
| 46 |
+
output = self.convs[1](output)
|
| 47 |
+
if self.concat_input:
|
| 48 |
+
output = self.conv_cat(torch.cat([x, output], dim=1))
|
| 49 |
+
output = self.cls_seg(output)
|
| 50 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/ocr_head.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from mmcv.cnn import ConvModule
|
| 6 |
+
|
| 7 |
+
from mmseg.registry import MODELS
|
| 8 |
+
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
|
| 9 |
+
from ..utils import resize
|
| 10 |
+
from .cascade_decode_head import BaseCascadeDecodeHead
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SpatialGatherModule(nn.Module):
|
| 14 |
+
"""Aggregate the context features according to the initial predicted
|
| 15 |
+
probability distribution.
|
| 16 |
+
|
| 17 |
+
Employ the soft-weighted method to aggregate the context.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self, scale):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.scale = scale
|
| 23 |
+
|
| 24 |
+
def forward(self, feats, probs):
|
| 25 |
+
"""Forward function."""
|
| 26 |
+
batch_size, num_classes, height, width = probs.size()
|
| 27 |
+
channels = feats.size(1)
|
| 28 |
+
probs = probs.view(batch_size, num_classes, -1)
|
| 29 |
+
feats = feats.view(batch_size, channels, -1)
|
| 30 |
+
# [batch_size, height*width, num_classes]
|
| 31 |
+
feats = feats.permute(0, 2, 1)
|
| 32 |
+
# [batch_size, channels, height*width]
|
| 33 |
+
probs = F.softmax(self.scale * probs, dim=2)
|
| 34 |
+
# [batch_size, channels, num_classes]
|
| 35 |
+
ocr_context = torch.matmul(probs, feats)
|
| 36 |
+
ocr_context = ocr_context.permute(0, 2, 1).contiguous().unsqueeze(3)
|
| 37 |
+
return ocr_context
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class ObjectAttentionBlock(_SelfAttentionBlock):
|
| 41 |
+
"""Make a OCR used SelfAttentionBlock."""
|
| 42 |
+
|
| 43 |
+
def __init__(self, in_channels, channels, scale, conv_cfg, norm_cfg,
|
| 44 |
+
act_cfg):
|
| 45 |
+
if scale > 1:
|
| 46 |
+
query_downsample = nn.MaxPool2d(kernel_size=scale)
|
| 47 |
+
else:
|
| 48 |
+
query_downsample = None
|
| 49 |
+
super().__init__(
|
| 50 |
+
key_in_channels=in_channels,
|
| 51 |
+
query_in_channels=in_channels,
|
| 52 |
+
channels=channels,
|
| 53 |
+
out_channels=in_channels,
|
| 54 |
+
share_key_query=False,
|
| 55 |
+
query_downsample=query_downsample,
|
| 56 |
+
key_downsample=None,
|
| 57 |
+
key_query_num_convs=2,
|
| 58 |
+
key_query_norm=True,
|
| 59 |
+
value_out_num_convs=1,
|
| 60 |
+
value_out_norm=True,
|
| 61 |
+
matmul_norm=True,
|
| 62 |
+
with_out=True,
|
| 63 |
+
conv_cfg=conv_cfg,
|
| 64 |
+
norm_cfg=norm_cfg,
|
| 65 |
+
act_cfg=act_cfg)
|
| 66 |
+
self.bottleneck = ConvModule(
|
| 67 |
+
in_channels * 2,
|
| 68 |
+
in_channels,
|
| 69 |
+
1,
|
| 70 |
+
conv_cfg=self.conv_cfg,
|
| 71 |
+
norm_cfg=self.norm_cfg,
|
| 72 |
+
act_cfg=self.act_cfg)
|
| 73 |
+
|
| 74 |
+
def forward(self, query_feats, key_feats):
|
| 75 |
+
"""Forward function."""
|
| 76 |
+
context = super().forward(query_feats, key_feats)
|
| 77 |
+
output = self.bottleneck(torch.cat([context, query_feats], dim=1))
|
| 78 |
+
if self.query_downsample is not None:
|
| 79 |
+
output = resize(query_feats)
|
| 80 |
+
|
| 81 |
+
return output
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@MODELS.register_module()
|
| 85 |
+
class OCRHead(BaseCascadeDecodeHead):
|
| 86 |
+
"""Object-Contextual Representations for Semantic Segmentation.
|
| 87 |
+
|
| 88 |
+
This head is the implementation of `OCRNet
|
| 89 |
+
<https://arxiv.org/abs/1909.11065>`_.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
ocr_channels (int): The intermediate channels of OCR block.
|
| 93 |
+
scale (int): The scale of probability map in SpatialGatherModule in
|
| 94 |
+
Default: 1.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
def __init__(self, ocr_channels, scale=1, **kwargs):
|
| 98 |
+
super().__init__(**kwargs)
|
| 99 |
+
self.ocr_channels = ocr_channels
|
| 100 |
+
self.scale = scale
|
| 101 |
+
self.object_context_block = ObjectAttentionBlock(
|
| 102 |
+
self.channels,
|
| 103 |
+
self.ocr_channels,
|
| 104 |
+
self.scale,
|
| 105 |
+
conv_cfg=self.conv_cfg,
|
| 106 |
+
norm_cfg=self.norm_cfg,
|
| 107 |
+
act_cfg=self.act_cfg)
|
| 108 |
+
self.spatial_gather_module = SpatialGatherModule(self.scale)
|
| 109 |
+
|
| 110 |
+
self.bottleneck = ConvModule(
|
| 111 |
+
self.in_channels,
|
| 112 |
+
self.channels,
|
| 113 |
+
3,
|
| 114 |
+
padding=1,
|
| 115 |
+
conv_cfg=self.conv_cfg,
|
| 116 |
+
norm_cfg=self.norm_cfg,
|
| 117 |
+
act_cfg=self.act_cfg)
|
| 118 |
+
|
| 119 |
+
def forward(self, inputs, prev_output):
|
| 120 |
+
"""Forward function."""
|
| 121 |
+
x = self._transform_inputs(inputs)
|
| 122 |
+
feats = self.bottleneck(x)
|
| 123 |
+
context = self.spatial_gather_module(feats, prev_output)
|
| 124 |
+
object_context = self.object_context_block(feats, context)
|
| 125 |
+
output = self.cls_seg(object_context)
|
| 126 |
+
|
| 127 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/pid_head.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer
|
| 7 |
+
from mmengine.model import BaseModule
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
|
| 10 |
+
from mmseg.models.decode_heads.decode_head import BaseDecodeHead
|
| 11 |
+
from mmseg.models.losses import accuracy
|
| 12 |
+
from mmseg.models.utils import resize
|
| 13 |
+
from mmseg.registry import MODELS
|
| 14 |
+
from mmseg.utils import OptConfigType, SampleList
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class BasePIDHead(BaseModule):
|
| 18 |
+
"""Base class for PID head.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
in_channels (int): Number of input channels.
|
| 22 |
+
channels (int): Number of output channels.
|
| 23 |
+
norm_cfg (dict): Config dict for normalization layer.
|
| 24 |
+
Default: dict(type='BN').
|
| 25 |
+
act_cfg (dict): Config dict for activation layer.
|
| 26 |
+
Default: dict(type='ReLU', inplace=True).
|
| 27 |
+
init_cfg (dict or list[dict], optional): Init config dict.
|
| 28 |
+
Default: None.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self,
|
| 32 |
+
in_channels: int,
|
| 33 |
+
channels: int,
|
| 34 |
+
norm_cfg: OptConfigType = dict(type='BN'),
|
| 35 |
+
act_cfg: OptConfigType = dict(type='ReLU', inplace=True),
|
| 36 |
+
init_cfg: OptConfigType = None):
|
| 37 |
+
super().__init__(init_cfg)
|
| 38 |
+
self.conv = ConvModule(
|
| 39 |
+
in_channels,
|
| 40 |
+
channels,
|
| 41 |
+
kernel_size=3,
|
| 42 |
+
padding=1,
|
| 43 |
+
norm_cfg=norm_cfg,
|
| 44 |
+
act_cfg=act_cfg,
|
| 45 |
+
order=('norm', 'act', 'conv'))
|
| 46 |
+
_, self.norm = build_norm_layer(norm_cfg, num_features=channels)
|
| 47 |
+
self.act = build_activation_layer(act_cfg)
|
| 48 |
+
|
| 49 |
+
def forward(self, x: Tensor, cls_seg: Optional[nn.Module]) -> Tensor:
|
| 50 |
+
"""Forward function.
|
| 51 |
+
Args:
|
| 52 |
+
x (Tensor): Input tensor.
|
| 53 |
+
cls_seg (nn.Module, optional): The classification head.
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
Tensor: Output tensor.
|
| 57 |
+
"""
|
| 58 |
+
x = self.conv(x)
|
| 59 |
+
x = self.norm(x)
|
| 60 |
+
x = self.act(x)
|
| 61 |
+
if cls_seg is not None:
|
| 62 |
+
x = cls_seg(x)
|
| 63 |
+
return x
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@MODELS.register_module()
|
| 67 |
+
class PIDHead(BaseDecodeHead):
|
| 68 |
+
"""Decode head for PIDNet.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
in_channels (int): Number of input channels.
|
| 72 |
+
channels (int): Number of output channels.
|
| 73 |
+
num_classes (int): Number of classes.
|
| 74 |
+
norm_cfg (dict): Config dict for normalization layer.
|
| 75 |
+
Default: dict(type='BN').
|
| 76 |
+
act_cfg (dict): Config dict for activation layer.
|
| 77 |
+
Default: dict(type='ReLU', inplace=True).
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def __init__(self,
|
| 81 |
+
in_channels: int,
|
| 82 |
+
channels: int,
|
| 83 |
+
num_classes: int,
|
| 84 |
+
norm_cfg: OptConfigType = dict(type='BN'),
|
| 85 |
+
act_cfg: OptConfigType = dict(type='ReLU', inplace=True),
|
| 86 |
+
**kwargs):
|
| 87 |
+
super().__init__(
|
| 88 |
+
in_channels,
|
| 89 |
+
channels,
|
| 90 |
+
num_classes=num_classes,
|
| 91 |
+
norm_cfg=norm_cfg,
|
| 92 |
+
act_cfg=act_cfg,
|
| 93 |
+
**kwargs)
|
| 94 |
+
self.i_head = BasePIDHead(in_channels, channels, norm_cfg, act_cfg)
|
| 95 |
+
self.p_head = BasePIDHead(in_channels // 2, channels, norm_cfg,
|
| 96 |
+
act_cfg)
|
| 97 |
+
self.d_head = BasePIDHead(
|
| 98 |
+
in_channels // 2,
|
| 99 |
+
in_channels // 4,
|
| 100 |
+
norm_cfg,
|
| 101 |
+
)
|
| 102 |
+
self.p_cls_seg = nn.Conv2d(channels, self.out_channels, kernel_size=1)
|
| 103 |
+
self.d_cls_seg = nn.Conv2d(in_channels // 4, 1, kernel_size=1)
|
| 104 |
+
|
| 105 |
+
def init_weights(self):
|
| 106 |
+
for m in self.modules():
|
| 107 |
+
if isinstance(m, nn.Conv2d):
|
| 108 |
+
nn.init.kaiming_normal_(
|
| 109 |
+
m.weight, mode='fan_out', nonlinearity='relu')
|
| 110 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 111 |
+
nn.init.constant_(m.weight, 1)
|
| 112 |
+
nn.init.constant_(m.bias, 0)
|
| 113 |
+
|
| 114 |
+
def forward(
|
| 115 |
+
self,
|
| 116 |
+
inputs: Union[Tensor,
|
| 117 |
+
Tuple[Tensor]]) -> Union[Tensor, Tuple[Tensor]]:
|
| 118 |
+
"""Forward function.
|
| 119 |
+
Args:
|
| 120 |
+
inputs (Tensor | tuple[Tensor]): Input tensor or tuple of
|
| 121 |
+
Tensor. When training, the input is a tuple of three tensors,
|
| 122 |
+
(p_feat, i_feat, d_feat), and the output is a tuple of three
|
| 123 |
+
tensors, (p_seg_logit, i_seg_logit, d_seg_logit).
|
| 124 |
+
When inference, only the head of integral branch is used, and
|
| 125 |
+
input is a tensor of integral feature map, and the output is
|
| 126 |
+
the segmentation logit.
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
Tensor | tuple[Tensor]: Output tensor or tuple of tensors.
|
| 130 |
+
"""
|
| 131 |
+
if self.training:
|
| 132 |
+
x_p, x_i, x_d = inputs
|
| 133 |
+
x_p = self.p_head(x_p, self.p_cls_seg)
|
| 134 |
+
x_i = self.i_head(x_i, self.cls_seg)
|
| 135 |
+
x_d = self.d_head(x_d, self.d_cls_seg)
|
| 136 |
+
return x_p, x_i, x_d
|
| 137 |
+
else:
|
| 138 |
+
return self.i_head(inputs, self.cls_seg)
|
| 139 |
+
|
| 140 |
+
def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tuple[Tensor]:
|
| 141 |
+
gt_semantic_segs = [
|
| 142 |
+
data_sample.gt_sem_seg.data for data_sample in batch_data_samples
|
| 143 |
+
]
|
| 144 |
+
gt_edge_segs = [
|
| 145 |
+
data_sample.gt_edge_map.data for data_sample in batch_data_samples
|
| 146 |
+
]
|
| 147 |
+
gt_sem_segs = torch.stack(gt_semantic_segs, dim=0)
|
| 148 |
+
gt_edge_segs = torch.stack(gt_edge_segs, dim=0)
|
| 149 |
+
return gt_sem_segs, gt_edge_segs
|
| 150 |
+
|
| 151 |
+
def loss_by_feat(self, seg_logits: Tuple[Tensor],
|
| 152 |
+
batch_data_samples: SampleList) -> dict:
|
| 153 |
+
loss = dict()
|
| 154 |
+
p_logit, i_logit, d_logit = seg_logits
|
| 155 |
+
sem_label, bd_label = self._stack_batch_gt(batch_data_samples)
|
| 156 |
+
p_logit = resize(
|
| 157 |
+
input=p_logit,
|
| 158 |
+
size=sem_label.shape[2:],
|
| 159 |
+
mode='bilinear',
|
| 160 |
+
align_corners=self.align_corners)
|
| 161 |
+
i_logit = resize(
|
| 162 |
+
input=i_logit,
|
| 163 |
+
size=sem_label.shape[2:],
|
| 164 |
+
mode='bilinear',
|
| 165 |
+
align_corners=self.align_corners)
|
| 166 |
+
d_logit = resize(
|
| 167 |
+
input=d_logit,
|
| 168 |
+
size=bd_label.shape[2:],
|
| 169 |
+
mode='bilinear',
|
| 170 |
+
align_corners=self.align_corners)
|
| 171 |
+
sem_label = sem_label.squeeze(1)
|
| 172 |
+
bd_label = bd_label.squeeze(1)
|
| 173 |
+
loss['loss_sem_p'] = self.loss_decode[0](
|
| 174 |
+
p_logit, sem_label, ignore_index=self.ignore_index)
|
| 175 |
+
loss['loss_sem_i'] = self.loss_decode[1](i_logit, sem_label)
|
| 176 |
+
loss['loss_bd'] = self.loss_decode[2](d_logit, bd_label)
|
| 177 |
+
filler = torch.ones_like(sem_label) * self.ignore_index
|
| 178 |
+
sem_bd_label = torch.where(
|
| 179 |
+
torch.sigmoid(d_logit[:, 0, :, :]) > 0.8, sem_label, filler)
|
| 180 |
+
loss['loss_sem_bd'] = self.loss_decode[3](i_logit, sem_bd_label)
|
| 181 |
+
loss['acc_seg'] = accuracy(
|
| 182 |
+
i_logit, sem_label, ignore_index=self.ignore_index)
|
| 183 |
+
return loss
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/point_head.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
# Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend/point_head/point_head.py # noqa
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from mmcv.cnn import ConvModule
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
from mmcv.ops import point_sample
|
| 10 |
+
except ModuleNotFoundError:
|
| 11 |
+
point_sample = None
|
| 12 |
+
|
| 13 |
+
from typing import List
|
| 14 |
+
|
| 15 |
+
from mmseg.registry import MODELS
|
| 16 |
+
from mmseg.utils import SampleList
|
| 17 |
+
from ..losses import accuracy
|
| 18 |
+
from ..utils import resize
|
| 19 |
+
from .cascade_decode_head import BaseCascadeDecodeHead
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def calculate_uncertainty(seg_logits):
|
| 23 |
+
"""Estimate uncertainty based on seg logits.
|
| 24 |
+
|
| 25 |
+
For each location of the prediction ``seg_logits`` we estimate
|
| 26 |
+
uncertainty as the difference between top first and top second
|
| 27 |
+
predicted logits.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
seg_logits (Tensor): Semantic segmentation logits,
|
| 31 |
+
shape (batch_size, num_classes, height, width).
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
scores (Tensor): T uncertainty scores with the most uncertain
|
| 35 |
+
locations having the highest uncertainty score, shape (
|
| 36 |
+
batch_size, 1, height, width)
|
| 37 |
+
"""
|
| 38 |
+
top2_scores = torch.topk(seg_logits, k=2, dim=1)[0]
|
| 39 |
+
return (top2_scores[:, 1] - top2_scores[:, 0]).unsqueeze(1)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@MODELS.register_module()
|
| 43 |
+
class PointHead(BaseCascadeDecodeHead):
|
| 44 |
+
"""A mask point head use in PointRend.
|
| 45 |
+
|
| 46 |
+
This head is implemented of `PointRend: Image Segmentation as
|
| 47 |
+
Rendering <https://arxiv.org/abs/1912.08193>`_.
|
| 48 |
+
``PointHead`` use shared multi-layer perceptron (equivalent to
|
| 49 |
+
nn.Conv1d) to predict the logit of input points. The fine-grained feature
|
| 50 |
+
and coarse feature will be concatenate together for predication.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
num_fcs (int): Number of fc layers in the head. Default: 3.
|
| 54 |
+
in_channels (int): Number of input channels. Default: 256.
|
| 55 |
+
fc_channels (int): Number of fc channels. Default: 256.
|
| 56 |
+
num_classes (int): Number of classes for logits. Default: 80.
|
| 57 |
+
class_agnostic (bool): Whether use class agnostic classification.
|
| 58 |
+
If so, the output channels of logits will be 1. Default: False.
|
| 59 |
+
coarse_pred_each_layer (bool): Whether concatenate coarse feature with
|
| 60 |
+
the output of each fc layer. Default: True.
|
| 61 |
+
conv_cfg (dict|None): Dictionary to construct and config conv layer.
|
| 62 |
+
Default: dict(type='Conv1d'))
|
| 63 |
+
norm_cfg (dict|None): Dictionary to construct and config norm layer.
|
| 64 |
+
Default: None.
|
| 65 |
+
loss_point (dict): Dictionary to construct and config loss layer of
|
| 66 |
+
point head. Default: dict(type='CrossEntropyLoss', use_mask=True,
|
| 67 |
+
loss_weight=1.0).
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self,
|
| 71 |
+
num_fcs=3,
|
| 72 |
+
coarse_pred_each_layer=True,
|
| 73 |
+
conv_cfg=dict(type='Conv1d'),
|
| 74 |
+
norm_cfg=None,
|
| 75 |
+
act_cfg=dict(type='ReLU', inplace=False),
|
| 76 |
+
**kwargs):
|
| 77 |
+
super().__init__(
|
| 78 |
+
input_transform='multiple_select',
|
| 79 |
+
conv_cfg=conv_cfg,
|
| 80 |
+
norm_cfg=norm_cfg,
|
| 81 |
+
act_cfg=act_cfg,
|
| 82 |
+
init_cfg=dict(
|
| 83 |
+
type='Normal', std=0.01, override=dict(name='fc_seg')),
|
| 84 |
+
**kwargs)
|
| 85 |
+
if point_sample is None:
|
| 86 |
+
raise RuntimeError('Please install mmcv-full for '
|
| 87 |
+
'point_sample ops')
|
| 88 |
+
|
| 89 |
+
self.num_fcs = num_fcs
|
| 90 |
+
self.coarse_pred_each_layer = coarse_pred_each_layer
|
| 91 |
+
|
| 92 |
+
fc_in_channels = sum(self.in_channels) + self.num_classes
|
| 93 |
+
fc_channels = self.channels
|
| 94 |
+
self.fcs = nn.ModuleList()
|
| 95 |
+
for k in range(num_fcs):
|
| 96 |
+
fc = ConvModule(
|
| 97 |
+
fc_in_channels,
|
| 98 |
+
fc_channels,
|
| 99 |
+
kernel_size=1,
|
| 100 |
+
stride=1,
|
| 101 |
+
padding=0,
|
| 102 |
+
conv_cfg=conv_cfg,
|
| 103 |
+
norm_cfg=norm_cfg,
|
| 104 |
+
act_cfg=act_cfg)
|
| 105 |
+
self.fcs.append(fc)
|
| 106 |
+
fc_in_channels = fc_channels
|
| 107 |
+
fc_in_channels += self.num_classes if self.coarse_pred_each_layer \
|
| 108 |
+
else 0
|
| 109 |
+
self.fc_seg = nn.Conv1d(
|
| 110 |
+
fc_in_channels,
|
| 111 |
+
self.num_classes,
|
| 112 |
+
kernel_size=1,
|
| 113 |
+
stride=1,
|
| 114 |
+
padding=0)
|
| 115 |
+
if self.dropout_ratio > 0:
|
| 116 |
+
self.dropout = nn.Dropout(self.dropout_ratio)
|
| 117 |
+
delattr(self, 'conv_seg')
|
| 118 |
+
|
| 119 |
+
def cls_seg(self, feat):
|
| 120 |
+
"""Classify each pixel with fc."""
|
| 121 |
+
if self.dropout is not None:
|
| 122 |
+
feat = self.dropout(feat)
|
| 123 |
+
output = self.fc_seg(feat)
|
| 124 |
+
return output
|
| 125 |
+
|
| 126 |
+
def forward(self, fine_grained_point_feats, coarse_point_feats):
|
| 127 |
+
x = torch.cat([fine_grained_point_feats, coarse_point_feats], dim=1)
|
| 128 |
+
for fc in self.fcs:
|
| 129 |
+
x = fc(x)
|
| 130 |
+
if self.coarse_pred_each_layer:
|
| 131 |
+
x = torch.cat((x, coarse_point_feats), dim=1)
|
| 132 |
+
return self.cls_seg(x)
|
| 133 |
+
|
| 134 |
+
def _get_fine_grained_point_feats(self, x, points):
|
| 135 |
+
"""Sample from fine grained features.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
x (list[Tensor]): Feature pyramid from by neck or backbone.
|
| 139 |
+
points (Tensor): Point coordinates, shape (batch_size,
|
| 140 |
+
num_points, 2).
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
fine_grained_feats (Tensor): Sampled fine grained feature,
|
| 144 |
+
shape (batch_size, sum(channels of x), num_points).
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
fine_grained_feats_list = [
|
| 148 |
+
point_sample(_, points, align_corners=self.align_corners)
|
| 149 |
+
for _ in x
|
| 150 |
+
]
|
| 151 |
+
if len(fine_grained_feats_list) > 1:
|
| 152 |
+
fine_grained_feats = torch.cat(fine_grained_feats_list, dim=1)
|
| 153 |
+
else:
|
| 154 |
+
fine_grained_feats = fine_grained_feats_list[0]
|
| 155 |
+
|
| 156 |
+
return fine_grained_feats
|
| 157 |
+
|
| 158 |
+
def _get_coarse_point_feats(self, prev_output, points):
|
| 159 |
+
"""Sample from fine grained features.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
prev_output (list[Tensor]): Prediction of previous decode head.
|
| 163 |
+
points (Tensor): Point coordinates, shape (batch_size,
|
| 164 |
+
num_points, 2).
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
coarse_feats (Tensor): Sampled coarse feature, shape (batch_size,
|
| 168 |
+
num_classes, num_points).
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
coarse_feats = point_sample(
|
| 172 |
+
prev_output, points, align_corners=self.align_corners)
|
| 173 |
+
|
| 174 |
+
return coarse_feats
|
| 175 |
+
|
| 176 |
+
def loss(self, inputs, prev_output, batch_data_samples: SampleList,
|
| 177 |
+
train_cfg, **kwargs):
|
| 178 |
+
"""Forward function for training.
|
| 179 |
+
Args:
|
| 180 |
+
inputs (list[Tensor]): List of multi-level img features.
|
| 181 |
+
prev_output (Tensor): The output of previous decode head.
|
| 182 |
+
batch_data_samples (list[:obj:`SegDataSample`]): The seg
|
| 183 |
+
data samples. It usually includes information such
|
| 184 |
+
as `img_metas` or `gt_semantic_seg`.
|
| 185 |
+
train_cfg (dict): The training config.
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
dict[str, Tensor]: a dictionary of loss components
|
| 189 |
+
"""
|
| 190 |
+
x = self._transform_inputs(inputs)
|
| 191 |
+
with torch.no_grad():
|
| 192 |
+
points = self.get_points_train(
|
| 193 |
+
prev_output, calculate_uncertainty, cfg=train_cfg)
|
| 194 |
+
fine_grained_point_feats = self._get_fine_grained_point_feats(
|
| 195 |
+
x, points)
|
| 196 |
+
coarse_point_feats = self._get_coarse_point_feats(prev_output, points)
|
| 197 |
+
point_logits = self.forward(fine_grained_point_feats,
|
| 198 |
+
coarse_point_feats)
|
| 199 |
+
|
| 200 |
+
losses = self.loss_by_feat(point_logits, points, batch_data_samples)
|
| 201 |
+
|
| 202 |
+
return losses
|
| 203 |
+
|
| 204 |
+
def predict(self, inputs, prev_output, batch_img_metas: List[dict],
|
| 205 |
+
test_cfg, **kwargs):
|
| 206 |
+
"""Forward function for testing.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
inputs (list[Tensor]): List of multi-level img features.
|
| 210 |
+
prev_output (Tensor): The output of previous decode head.
|
| 211 |
+
img_metas (list[dict]): List of image info dict where each dict
|
| 212 |
+
has: 'img_shape', 'scale_factor', 'flip', and may also contain
|
| 213 |
+
'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.
|
| 214 |
+
For details on the values of these keys see
|
| 215 |
+
`mmseg/datasets/pipelines/formatting.py:Collect`.
|
| 216 |
+
test_cfg (dict): The testing config.
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
Tensor: Output segmentation map.
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
x = self._transform_inputs(inputs)
|
| 223 |
+
refined_seg_logits = prev_output.clone()
|
| 224 |
+
for _ in range(test_cfg.subdivision_steps):
|
| 225 |
+
refined_seg_logits = resize(
|
| 226 |
+
refined_seg_logits,
|
| 227 |
+
scale_factor=test_cfg.scale_factor,
|
| 228 |
+
mode='bilinear',
|
| 229 |
+
align_corners=self.align_corners)
|
| 230 |
+
batch_size, channels, height, width = refined_seg_logits.shape
|
| 231 |
+
point_indices, points = self.get_points_test(
|
| 232 |
+
refined_seg_logits, calculate_uncertainty, cfg=test_cfg)
|
| 233 |
+
fine_grained_point_feats = self._get_fine_grained_point_feats(
|
| 234 |
+
x, points)
|
| 235 |
+
coarse_point_feats = self._get_coarse_point_feats(
|
| 236 |
+
prev_output, points)
|
| 237 |
+
point_logits = self.forward(fine_grained_point_feats,
|
| 238 |
+
coarse_point_feats)
|
| 239 |
+
|
| 240 |
+
point_indices = point_indices.unsqueeze(1).expand(-1, channels, -1)
|
| 241 |
+
refined_seg_logits = refined_seg_logits.reshape(
|
| 242 |
+
batch_size, channels, height * width)
|
| 243 |
+
refined_seg_logits = refined_seg_logits.scatter_(
|
| 244 |
+
2, point_indices, point_logits)
|
| 245 |
+
refined_seg_logits = refined_seg_logits.view(
|
| 246 |
+
batch_size, channels, height, width)
|
| 247 |
+
|
| 248 |
+
return self.predict_by_feat(refined_seg_logits, batch_img_metas,
|
| 249 |
+
**kwargs)
|
| 250 |
+
|
| 251 |
+
def loss_by_feat(self, point_logits, points, batch_data_samples, **kwargs):
|
| 252 |
+
"""Compute segmentation loss."""
|
| 253 |
+
gt_semantic_seg = self._stack_batch_gt(batch_data_samples)
|
| 254 |
+
point_label = point_sample(
|
| 255 |
+
gt_semantic_seg.float(),
|
| 256 |
+
points,
|
| 257 |
+
mode='nearest',
|
| 258 |
+
align_corners=self.align_corners)
|
| 259 |
+
point_label = point_label.squeeze(1).long()
|
| 260 |
+
|
| 261 |
+
loss = dict()
|
| 262 |
+
if not isinstance(self.loss_decode, nn.ModuleList):
|
| 263 |
+
losses_decode = [self.loss_decode]
|
| 264 |
+
else:
|
| 265 |
+
losses_decode = self.loss_decode
|
| 266 |
+
for loss_module in losses_decode:
|
| 267 |
+
loss['point' + loss_module.loss_name] = loss_module(
|
| 268 |
+
point_logits, point_label, ignore_index=self.ignore_index)
|
| 269 |
+
|
| 270 |
+
loss['acc_point'] = accuracy(
|
| 271 |
+
point_logits, point_label, ignore_index=self.ignore_index)
|
| 272 |
+
return loss
|
| 273 |
+
|
| 274 |
+
def get_points_train(self, seg_logits, uncertainty_func, cfg):
|
| 275 |
+
"""Sample points for training.
|
| 276 |
+
|
| 277 |
+
Sample points in [0, 1] x [0, 1] coordinate space based on their
|
| 278 |
+
uncertainty. The uncertainties are calculated for each point using
|
| 279 |
+
'uncertainty_func' function that takes point's logit prediction as
|
| 280 |
+
input.
|
| 281 |
+
|
| 282 |
+
Args:
|
| 283 |
+
seg_logits (Tensor): Semantic segmentation logits, shape (
|
| 284 |
+
batch_size, num_classes, height, width).
|
| 285 |
+
uncertainty_func (func): uncertainty calculation function.
|
| 286 |
+
cfg (dict): Training config of point head.
|
| 287 |
+
|
| 288 |
+
Returns:
|
| 289 |
+
point_coords (Tensor): A tensor of shape (batch_size, num_points,
|
| 290 |
+
2) that contains the coordinates of ``num_points`` sampled
|
| 291 |
+
points.
|
| 292 |
+
"""
|
| 293 |
+
num_points = cfg.num_points
|
| 294 |
+
oversample_ratio = cfg.oversample_ratio
|
| 295 |
+
importance_sample_ratio = cfg.importance_sample_ratio
|
| 296 |
+
assert oversample_ratio >= 1
|
| 297 |
+
assert 0 <= importance_sample_ratio <= 1
|
| 298 |
+
batch_size = seg_logits.shape[0]
|
| 299 |
+
num_sampled = int(num_points * oversample_ratio)
|
| 300 |
+
point_coords = torch.rand(
|
| 301 |
+
batch_size, num_sampled, 2, device=seg_logits.device)
|
| 302 |
+
point_logits = point_sample(seg_logits, point_coords)
|
| 303 |
+
# It is crucial to calculate uncertainty based on the sampled
|
| 304 |
+
# prediction value for the points. Calculating uncertainties of the
|
| 305 |
+
# coarse predictions first and sampling them for points leads to
|
| 306 |
+
# incorrect results. To illustrate this: assume uncertainty func(
|
| 307 |
+
# logits)=-abs(logits), a sampled point between two coarse
|
| 308 |
+
# predictions with -1 and 1 logits has 0 logits, and therefore 0
|
| 309 |
+
# uncertainty value. However, if we calculate uncertainties for the
|
| 310 |
+
# coarse predictions first, both will have -1 uncertainty,
|
| 311 |
+
# and sampled point will get -1 uncertainty.
|
| 312 |
+
point_uncertainties = uncertainty_func(point_logits)
|
| 313 |
+
num_uncertain_points = int(importance_sample_ratio * num_points)
|
| 314 |
+
num_random_points = num_points - num_uncertain_points
|
| 315 |
+
idx = torch.topk(
|
| 316 |
+
point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1]
|
| 317 |
+
shift = num_sampled * torch.arange(
|
| 318 |
+
batch_size, dtype=torch.long, device=seg_logits.device)
|
| 319 |
+
idx += shift[:, None]
|
| 320 |
+
point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view(
|
| 321 |
+
batch_size, num_uncertain_points, 2)
|
| 322 |
+
if num_random_points > 0:
|
| 323 |
+
rand_point_coords = torch.rand(
|
| 324 |
+
batch_size, num_random_points, 2, device=seg_logits.device)
|
| 325 |
+
point_coords = torch.cat((point_coords, rand_point_coords), dim=1)
|
| 326 |
+
return point_coords
|
| 327 |
+
|
| 328 |
+
def get_points_test(self, seg_logits, uncertainty_func, cfg):
|
| 329 |
+
"""Sample points for testing.
|
| 330 |
+
|
| 331 |
+
Find ``num_points`` most uncertain points from ``uncertainty_map``.
|
| 332 |
+
|
| 333 |
+
Args:
|
| 334 |
+
seg_logits (Tensor): A tensor of shape (batch_size, num_classes,
|
| 335 |
+
height, width) for class-specific or class-agnostic prediction.
|
| 336 |
+
uncertainty_func (func): uncertainty calculation function.
|
| 337 |
+
cfg (dict): Testing config of point head.
|
| 338 |
+
|
| 339 |
+
Returns:
|
| 340 |
+
point_indices (Tensor): A tensor of shape (batch_size, num_points)
|
| 341 |
+
that contains indices from [0, height x width) of the most
|
| 342 |
+
uncertain points.
|
| 343 |
+
point_coords (Tensor): A tensor of shape (batch_size, num_points,
|
| 344 |
+
2) that contains [0, 1] x [0, 1] normalized coordinates of the
|
| 345 |
+
most uncertain points from the ``height x width`` grid .
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
num_points = cfg.subdivision_num_points
|
| 349 |
+
uncertainty_map = uncertainty_func(seg_logits)
|
| 350 |
+
batch_size, _, height, width = uncertainty_map.shape
|
| 351 |
+
h_step = 1.0 / height
|
| 352 |
+
w_step = 1.0 / width
|
| 353 |
+
|
| 354 |
+
uncertainty_map = uncertainty_map.view(batch_size, height * width)
|
| 355 |
+
num_points = min(height * width, num_points)
|
| 356 |
+
point_indices = uncertainty_map.topk(num_points, dim=1)[1]
|
| 357 |
+
point_coords = torch.zeros(
|
| 358 |
+
batch_size,
|
| 359 |
+
num_points,
|
| 360 |
+
2,
|
| 361 |
+
dtype=torch.float,
|
| 362 |
+
device=seg_logits.device)
|
| 363 |
+
point_coords[:, :, 0] = w_step / 2.0 + (point_indices %
|
| 364 |
+
width).float() * w_step
|
| 365 |
+
point_coords[:, :, 1] = h_step / 2.0 + (point_indices //
|
| 366 |
+
width).float() * h_step
|
| 367 |
+
return point_indices, point_coords
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/psa_head.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from mmcv.cnn import ConvModule
|
| 6 |
+
|
| 7 |
+
from mmseg.registry import MODELS
|
| 8 |
+
from ..utils import resize
|
| 9 |
+
from .decode_head import BaseDecodeHead
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from mmcv.ops import PSAMask
|
| 13 |
+
except ModuleNotFoundError:
|
| 14 |
+
PSAMask = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@MODELS.register_module()
|
| 18 |
+
class PSAHead(BaseDecodeHead):
|
| 19 |
+
"""Point-wise Spatial Attention Network for Scene Parsing.
|
| 20 |
+
|
| 21 |
+
This head is the implementation of `PSANet
|
| 22 |
+
<https://hszhao.github.io/papers/eccv18_psanet.pdf>`_.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
mask_size (tuple[int]): The PSA mask size. It usually equals input
|
| 26 |
+
size.
|
| 27 |
+
psa_type (str): The type of psa module. Options are 'collect',
|
| 28 |
+
'distribute', 'bi-direction'. Default: 'bi-direction'
|
| 29 |
+
compact (bool): Whether use compact map for 'collect' mode.
|
| 30 |
+
Default: True.
|
| 31 |
+
shrink_factor (int): The downsample factors of psa mask. Default: 2.
|
| 32 |
+
normalization_factor (float): The normalize factor of attention.
|
| 33 |
+
psa_softmax (bool): Whether use softmax for attention.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self,
|
| 37 |
+
mask_size,
|
| 38 |
+
psa_type='bi-direction',
|
| 39 |
+
compact=False,
|
| 40 |
+
shrink_factor=2,
|
| 41 |
+
normalization_factor=1.0,
|
| 42 |
+
psa_softmax=True,
|
| 43 |
+
**kwargs):
|
| 44 |
+
if PSAMask is None:
|
| 45 |
+
raise RuntimeError('Please install mmcv-full for PSAMask ops')
|
| 46 |
+
super().__init__(**kwargs)
|
| 47 |
+
assert psa_type in ['collect', 'distribute', 'bi-direction']
|
| 48 |
+
self.psa_type = psa_type
|
| 49 |
+
self.compact = compact
|
| 50 |
+
self.shrink_factor = shrink_factor
|
| 51 |
+
self.mask_size = mask_size
|
| 52 |
+
mask_h, mask_w = mask_size
|
| 53 |
+
self.psa_softmax = psa_softmax
|
| 54 |
+
if normalization_factor is None:
|
| 55 |
+
normalization_factor = mask_h * mask_w
|
| 56 |
+
self.normalization_factor = normalization_factor
|
| 57 |
+
|
| 58 |
+
self.reduce = ConvModule(
|
| 59 |
+
self.in_channels,
|
| 60 |
+
self.channels,
|
| 61 |
+
kernel_size=1,
|
| 62 |
+
conv_cfg=self.conv_cfg,
|
| 63 |
+
norm_cfg=self.norm_cfg,
|
| 64 |
+
act_cfg=self.act_cfg)
|
| 65 |
+
self.attention = nn.Sequential(
|
| 66 |
+
ConvModule(
|
| 67 |
+
self.channels,
|
| 68 |
+
self.channels,
|
| 69 |
+
kernel_size=1,
|
| 70 |
+
conv_cfg=self.conv_cfg,
|
| 71 |
+
norm_cfg=self.norm_cfg,
|
| 72 |
+
act_cfg=self.act_cfg),
|
| 73 |
+
nn.Conv2d(
|
| 74 |
+
self.channels, mask_h * mask_w, kernel_size=1, bias=False))
|
| 75 |
+
if psa_type == 'bi-direction':
|
| 76 |
+
self.reduce_p = ConvModule(
|
| 77 |
+
self.in_channels,
|
| 78 |
+
self.channels,
|
| 79 |
+
kernel_size=1,
|
| 80 |
+
conv_cfg=self.conv_cfg,
|
| 81 |
+
norm_cfg=self.norm_cfg,
|
| 82 |
+
act_cfg=self.act_cfg)
|
| 83 |
+
self.attention_p = nn.Sequential(
|
| 84 |
+
ConvModule(
|
| 85 |
+
self.channels,
|
| 86 |
+
self.channels,
|
| 87 |
+
kernel_size=1,
|
| 88 |
+
conv_cfg=self.conv_cfg,
|
| 89 |
+
norm_cfg=self.norm_cfg,
|
| 90 |
+
act_cfg=self.act_cfg),
|
| 91 |
+
nn.Conv2d(
|
| 92 |
+
self.channels, mask_h * mask_w, kernel_size=1, bias=False))
|
| 93 |
+
self.psamask_collect = PSAMask('collect', mask_size)
|
| 94 |
+
self.psamask_distribute = PSAMask('distribute', mask_size)
|
| 95 |
+
else:
|
| 96 |
+
self.psamask = PSAMask(psa_type, mask_size)
|
| 97 |
+
self.proj = ConvModule(
|
| 98 |
+
self.channels * (2 if psa_type == 'bi-direction' else 1),
|
| 99 |
+
self.in_channels,
|
| 100 |
+
kernel_size=1,
|
| 101 |
+
padding=1,
|
| 102 |
+
conv_cfg=self.conv_cfg,
|
| 103 |
+
norm_cfg=self.norm_cfg,
|
| 104 |
+
act_cfg=self.act_cfg)
|
| 105 |
+
self.bottleneck = ConvModule(
|
| 106 |
+
self.in_channels * 2,
|
| 107 |
+
self.channels,
|
| 108 |
+
kernel_size=3,
|
| 109 |
+
padding=1,
|
| 110 |
+
conv_cfg=self.conv_cfg,
|
| 111 |
+
norm_cfg=self.norm_cfg,
|
| 112 |
+
act_cfg=self.act_cfg)
|
| 113 |
+
|
| 114 |
+
def forward(self, inputs):
|
| 115 |
+
"""Forward function."""
|
| 116 |
+
x = self._transform_inputs(inputs)
|
| 117 |
+
identity = x
|
| 118 |
+
align_corners = self.align_corners
|
| 119 |
+
if self.psa_type in ['collect', 'distribute']:
|
| 120 |
+
out = self.reduce(x)
|
| 121 |
+
n, c, h, w = out.size()
|
| 122 |
+
if self.shrink_factor != 1:
|
| 123 |
+
if h % self.shrink_factor and w % self.shrink_factor:
|
| 124 |
+
h = (h - 1) // self.shrink_factor + 1
|
| 125 |
+
w = (w - 1) // self.shrink_factor + 1
|
| 126 |
+
align_corners = True
|
| 127 |
+
else:
|
| 128 |
+
h = h // self.shrink_factor
|
| 129 |
+
w = w // self.shrink_factor
|
| 130 |
+
align_corners = False
|
| 131 |
+
out = resize(
|
| 132 |
+
out,
|
| 133 |
+
size=(h, w),
|
| 134 |
+
mode='bilinear',
|
| 135 |
+
align_corners=align_corners)
|
| 136 |
+
y = self.attention(out)
|
| 137 |
+
if self.compact:
|
| 138 |
+
if self.psa_type == 'collect':
|
| 139 |
+
y = y.view(n, h * w,
|
| 140 |
+
h * w).transpose(1, 2).view(n, h * w, h, w)
|
| 141 |
+
else:
|
| 142 |
+
y = self.psamask(y)
|
| 143 |
+
if self.psa_softmax:
|
| 144 |
+
y = F.softmax(y, dim=1)
|
| 145 |
+
out = torch.bmm(
|
| 146 |
+
out.view(n, c, h * w), y.view(n, h * w, h * w)).view(
|
| 147 |
+
n, c, h, w) * (1.0 / self.normalization_factor)
|
| 148 |
+
else:
|
| 149 |
+
x_col = self.reduce(x)
|
| 150 |
+
x_dis = self.reduce_p(x)
|
| 151 |
+
n, c, h, w = x_col.size()
|
| 152 |
+
if self.shrink_factor != 1:
|
| 153 |
+
if h % self.shrink_factor and w % self.shrink_factor:
|
| 154 |
+
h = (h - 1) // self.shrink_factor + 1
|
| 155 |
+
w = (w - 1) // self.shrink_factor + 1
|
| 156 |
+
align_corners = True
|
| 157 |
+
else:
|
| 158 |
+
h = h // self.shrink_factor
|
| 159 |
+
w = w // self.shrink_factor
|
| 160 |
+
align_corners = False
|
| 161 |
+
x_col = resize(
|
| 162 |
+
x_col,
|
| 163 |
+
size=(h, w),
|
| 164 |
+
mode='bilinear',
|
| 165 |
+
align_corners=align_corners)
|
| 166 |
+
x_dis = resize(
|
| 167 |
+
x_dis,
|
| 168 |
+
size=(h, w),
|
| 169 |
+
mode='bilinear',
|
| 170 |
+
align_corners=align_corners)
|
| 171 |
+
y_col = self.attention(x_col)
|
| 172 |
+
y_dis = self.attention_p(x_dis)
|
| 173 |
+
if self.compact:
|
| 174 |
+
y_dis = y_dis.view(n, h * w,
|
| 175 |
+
h * w).transpose(1, 2).view(n, h * w, h, w)
|
| 176 |
+
else:
|
| 177 |
+
y_col = self.psamask_collect(y_col)
|
| 178 |
+
y_dis = self.psamask_distribute(y_dis)
|
| 179 |
+
if self.psa_softmax:
|
| 180 |
+
y_col = F.softmax(y_col, dim=1)
|
| 181 |
+
y_dis = F.softmax(y_dis, dim=1)
|
| 182 |
+
x_col = torch.bmm(
|
| 183 |
+
x_col.view(n, c, h * w), y_col.view(n, h * w, h * w)).view(
|
| 184 |
+
n, c, h, w) * (1.0 / self.normalization_factor)
|
| 185 |
+
x_dis = torch.bmm(
|
| 186 |
+
x_dis.view(n, c, h * w), y_dis.view(n, h * w, h * w)).view(
|
| 187 |
+
n, c, h, w) * (1.0 / self.normalization_factor)
|
| 188 |
+
out = torch.cat([x_col, x_dis], 1)
|
| 189 |
+
out = self.proj(out)
|
| 190 |
+
out = resize(
|
| 191 |
+
out,
|
| 192 |
+
size=identity.shape[2:],
|
| 193 |
+
mode='bilinear',
|
| 194 |
+
align_corners=align_corners)
|
| 195 |
+
out = self.bottleneck(torch.cat((identity, out), dim=1))
|
| 196 |
+
out = self.cls_seg(out)
|
| 197 |
+
return out
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/psp_head.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from ..utils import resize
|
| 8 |
+
from .decode_head import BaseDecodeHead
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class PPM(nn.ModuleList):
|
| 12 |
+
"""Pooling Pyramid Module used in PSPNet.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 16 |
+
Module.
|
| 17 |
+
in_channels (int): Input channels.
|
| 18 |
+
channels (int): Channels after modules, before conv_seg.
|
| 19 |
+
conv_cfg (dict|None): Config of conv layers.
|
| 20 |
+
norm_cfg (dict|None): Config of norm layers.
|
| 21 |
+
act_cfg (dict): Config of activation layers.
|
| 22 |
+
align_corners (bool): align_corners argument of F.interpolate.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, pool_scales, in_channels, channels, conv_cfg, norm_cfg,
|
| 26 |
+
act_cfg, align_corners, **kwargs):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.pool_scales = pool_scales
|
| 29 |
+
self.align_corners = align_corners
|
| 30 |
+
self.in_channels = in_channels
|
| 31 |
+
self.channels = channels
|
| 32 |
+
self.conv_cfg = conv_cfg
|
| 33 |
+
self.norm_cfg = norm_cfg
|
| 34 |
+
self.act_cfg = act_cfg
|
| 35 |
+
for pool_scale in pool_scales:
|
| 36 |
+
self.append(
|
| 37 |
+
nn.Sequential(
|
| 38 |
+
nn.AdaptiveAvgPool2d(pool_scale),
|
| 39 |
+
ConvModule(
|
| 40 |
+
self.in_channels,
|
| 41 |
+
self.channels,
|
| 42 |
+
1,
|
| 43 |
+
conv_cfg=self.conv_cfg,
|
| 44 |
+
norm_cfg=self.norm_cfg,
|
| 45 |
+
act_cfg=self.act_cfg,
|
| 46 |
+
**kwargs)))
|
| 47 |
+
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
"""Forward function."""
|
| 50 |
+
ppm_outs = []
|
| 51 |
+
for ppm in self:
|
| 52 |
+
ppm_out = ppm(x)
|
| 53 |
+
upsampled_ppm_out = resize(
|
| 54 |
+
ppm_out,
|
| 55 |
+
size=x.size()[2:],
|
| 56 |
+
mode='bilinear',
|
| 57 |
+
align_corners=self.align_corners)
|
| 58 |
+
ppm_outs.append(upsampled_ppm_out)
|
| 59 |
+
return ppm_outs
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@MODELS.register_module()
|
| 63 |
+
class PSPHead(BaseDecodeHead):
|
| 64 |
+
"""Pyramid Scene Parsing Network.
|
| 65 |
+
|
| 66 |
+
This head is the implementation of
|
| 67 |
+
`PSPNet <https://arxiv.org/abs/1612.01105>`_.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 71 |
+
Module. Default: (1, 2, 3, 6).
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs):
|
| 75 |
+
super().__init__(**kwargs)
|
| 76 |
+
assert isinstance(pool_scales, (list, tuple))
|
| 77 |
+
self.pool_scales = pool_scales
|
| 78 |
+
self.psp_modules = PPM(
|
| 79 |
+
self.pool_scales,
|
| 80 |
+
self.in_channels,
|
| 81 |
+
self.channels,
|
| 82 |
+
conv_cfg=self.conv_cfg,
|
| 83 |
+
norm_cfg=self.norm_cfg,
|
| 84 |
+
act_cfg=self.act_cfg,
|
| 85 |
+
align_corners=self.align_corners)
|
| 86 |
+
self.bottleneck = ConvModule(
|
| 87 |
+
self.in_channels + len(pool_scales) * self.channels,
|
| 88 |
+
self.channels,
|
| 89 |
+
3,
|
| 90 |
+
padding=1,
|
| 91 |
+
conv_cfg=self.conv_cfg,
|
| 92 |
+
norm_cfg=self.norm_cfg,
|
| 93 |
+
act_cfg=self.act_cfg)
|
| 94 |
+
|
| 95 |
+
def _forward_feature(self, inputs):
|
| 96 |
+
"""Forward function for feature maps before classifying each pixel with
|
| 97 |
+
``self.cls_seg`` fc.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
inputs (list[Tensor]): List of multi-level img features.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
feats (Tensor): A tensor of shape (batch_size, self.channels,
|
| 104 |
+
H, W) which is feature map for last layer of decoder head.
|
| 105 |
+
"""
|
| 106 |
+
x = self._transform_inputs(inputs)
|
| 107 |
+
psp_outs = [x]
|
| 108 |
+
psp_outs.extend(self.psp_modules(x))
|
| 109 |
+
psp_outs = torch.cat(psp_outs, dim=1)
|
| 110 |
+
feats = self.bottleneck(psp_outs)
|
| 111 |
+
return feats
|
| 112 |
+
|
| 113 |
+
def forward(self, inputs):
|
| 114 |
+
"""Forward function."""
|
| 115 |
+
output = self._forward_feature(inputs)
|
| 116 |
+
output = self.cls_seg(output)
|
| 117 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/san_head.py
ADDED
|
@@ -0,0 +1,736 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from functools import partial
|
| 3 |
+
from typing import Dict, List, Tuple
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from mmcv.cnn import ConvModule, build_norm_layer
|
| 8 |
+
from mmcv.cnn.bricks.transformer import BaseTransformerLayer
|
| 9 |
+
from mmcv.ops import point_sample
|
| 10 |
+
from mmengine.dist import all_reduce
|
| 11 |
+
from mmengine.model.weight_init import (caffe2_xavier_init, normal_init,
|
| 12 |
+
trunc_normal_)
|
| 13 |
+
from mmengine.runner.checkpoint import CheckpointLoader, load_state_dict
|
| 14 |
+
from mmengine.structures import InstanceData
|
| 15 |
+
from torch import Tensor
|
| 16 |
+
from torch.nn import functional as F
|
| 17 |
+
|
| 18 |
+
from mmseg.models.backbones.vit import TransformerEncoderLayer
|
| 19 |
+
from mmseg.registry import MODELS
|
| 20 |
+
from mmseg.utils import (ConfigType, MatchMasks, SampleList,
|
| 21 |
+
seg_data_to_instance_data)
|
| 22 |
+
from ..utils import (MLP, LayerNorm2d, PatchEmbed, cross_attn_layer,
|
| 23 |
+
get_uncertain_point_coords_with_randomness, resize)
|
| 24 |
+
from .decode_head import BaseDecodeHead
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class MLPMaskDecoder(nn.Module):
|
| 28 |
+
"""Module for decoding query and visual features with MLP layers to
|
| 29 |
+
generate the attention biases and the mask proposals."""
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
*,
|
| 34 |
+
in_channels: int,
|
| 35 |
+
total_heads: int = 1,
|
| 36 |
+
total_layers: int = 1,
|
| 37 |
+
embed_channels: int = 256,
|
| 38 |
+
mlp_channels: int = 256,
|
| 39 |
+
mlp_num_layers: int = 3,
|
| 40 |
+
rescale_attn_bias: bool = False,
|
| 41 |
+
):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.total_heads = total_heads
|
| 44 |
+
self.total_layers = total_layers
|
| 45 |
+
|
| 46 |
+
dense_affine_func = partial(nn.Conv2d, kernel_size=1)
|
| 47 |
+
# Query Branch
|
| 48 |
+
self.query_mlp = MLP(in_channels, mlp_channels, embed_channels,
|
| 49 |
+
mlp_num_layers)
|
| 50 |
+
# Pixel Branch
|
| 51 |
+
self.pix_mlp = MLP(
|
| 52 |
+
in_channels,
|
| 53 |
+
mlp_channels,
|
| 54 |
+
embed_channels,
|
| 55 |
+
mlp_num_layers,
|
| 56 |
+
affine_func=dense_affine_func,
|
| 57 |
+
)
|
| 58 |
+
# Attention Bias Branch
|
| 59 |
+
self.attn_mlp = MLP(
|
| 60 |
+
in_channels,
|
| 61 |
+
mlp_channels,
|
| 62 |
+
embed_channels * self.total_heads * self.total_layers,
|
| 63 |
+
mlp_num_layers,
|
| 64 |
+
affine_func=dense_affine_func,
|
| 65 |
+
)
|
| 66 |
+
if rescale_attn_bias:
|
| 67 |
+
self.bias_scaling = nn.Linear(1, 1)
|
| 68 |
+
else:
|
| 69 |
+
self.bias_scaling = nn.Identity()
|
| 70 |
+
|
| 71 |
+
def forward(self, query: torch.Tensor,
|
| 72 |
+
x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]:
|
| 73 |
+
"""Forward function.
|
| 74 |
+
Args:
|
| 75 |
+
query (Tensor): Query Tokens [B,N,C].
|
| 76 |
+
x (Tensor): Visual features [B,C,H,W]
|
| 77 |
+
|
| 78 |
+
Return:
|
| 79 |
+
mask_preds (Tensor): Mask proposals.
|
| 80 |
+
attn_bias (List[Tensor]): List of attention bias.
|
| 81 |
+
"""
|
| 82 |
+
query = self.query_mlp(query)
|
| 83 |
+
pix = self.pix_mlp(x)
|
| 84 |
+
b, c, h, w = pix.shape
|
| 85 |
+
# preidict mask
|
| 86 |
+
mask_preds = torch.einsum('bqc,bchw->bqhw', query, pix)
|
| 87 |
+
# generate attn bias
|
| 88 |
+
attn = self.attn_mlp(x)
|
| 89 |
+
attn = attn.reshape(b, self.total_layers, self.total_heads, c, h, w)
|
| 90 |
+
attn_bias = torch.einsum('bqc,blnchw->blnqhw', query, attn)
|
| 91 |
+
attn_bias = self.bias_scaling(attn_bias[..., None]).squeeze(-1)
|
| 92 |
+
attn_bias = attn_bias.chunk(self.total_layers, dim=1)
|
| 93 |
+
attn_bias = [attn.squeeze(1) for attn in attn_bias]
|
| 94 |
+
return mask_preds, attn_bias
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class SideAdapterNetwork(nn.Module):
|
| 98 |
+
"""Side Adapter Network for predicting mask proposals and attention bias.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
in_channels (int): Number of input channels. Default: 3.
|
| 102 |
+
clip_channels (int): Number of channels of visual features.
|
| 103 |
+
Default: 768.
|
| 104 |
+
embed_dims (int): embedding dimension. Default: 240.
|
| 105 |
+
patch_size (int): The patch size. Default: 16.
|
| 106 |
+
patch_bias (bool): Whether use bias in patch embedding.
|
| 107 |
+
Default: True.
|
| 108 |
+
num_queries (int): Number of queries for mask proposals.
|
| 109 |
+
Default: 100.
|
| 110 |
+
fusion_index (List[int]): The layer number of the encode
|
| 111 |
+
transformer to fuse with the CLIP feature.
|
| 112 |
+
Default: [0, 1, 2, 3].
|
| 113 |
+
cfg_encoder (ConfigType): Configs for the encode layers.
|
| 114 |
+
cfg_decoder (ConfigType): Configs for the decode layers.
|
| 115 |
+
norm_cfg (dict): Config dict for normalization layer.
|
| 116 |
+
Default: dict(type='LN').
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
in_channels: int = 3,
|
| 122 |
+
clip_channels: int = 768,
|
| 123 |
+
embed_dims: int = 240,
|
| 124 |
+
patch_size: int = 16,
|
| 125 |
+
patch_bias: bool = True,
|
| 126 |
+
num_queries: int = 100,
|
| 127 |
+
fusion_index: list = [0, 1, 2, 3],
|
| 128 |
+
cfg_encoder: ConfigType = ...,
|
| 129 |
+
cfg_decoder: ConfigType = ...,
|
| 130 |
+
norm_cfg: dict = dict(type='LN'),
|
| 131 |
+
):
|
| 132 |
+
super().__init__()
|
| 133 |
+
|
| 134 |
+
self.patch_embed = PatchEmbed(
|
| 135 |
+
in_channels=in_channels,
|
| 136 |
+
embed_dims=embed_dims,
|
| 137 |
+
conv_type='Conv2d',
|
| 138 |
+
kernel_size=patch_size,
|
| 139 |
+
stride=patch_size,
|
| 140 |
+
padding=0,
|
| 141 |
+
input_size=(640, 640),
|
| 142 |
+
bias=patch_bias,
|
| 143 |
+
norm_cfg=None,
|
| 144 |
+
init_cfg=None,
|
| 145 |
+
)
|
| 146 |
+
ori_h, ori_w = self.patch_embed.init_out_size
|
| 147 |
+
num_patches = ori_h * ori_w
|
| 148 |
+
self.pos_embed = nn.Parameter(
|
| 149 |
+
torch.randn(1, num_patches, embed_dims) * .02)
|
| 150 |
+
self.query_pos_embed = nn.Parameter(
|
| 151 |
+
torch.zeros(1, num_queries, embed_dims))
|
| 152 |
+
self.query_embed = nn.Parameter(
|
| 153 |
+
torch.zeros(1, num_queries, embed_dims))
|
| 154 |
+
encode_layers = []
|
| 155 |
+
for i in range(cfg_encoder.num_encode_layer):
|
| 156 |
+
encode_layers.append(
|
| 157 |
+
TransformerEncoderLayer(
|
| 158 |
+
embed_dims=embed_dims,
|
| 159 |
+
num_heads=cfg_encoder.num_heads,
|
| 160 |
+
feedforward_channels=cfg_encoder.mlp_ratio * embed_dims,
|
| 161 |
+
norm_cfg=norm_cfg))
|
| 162 |
+
self.encode_layers = nn.ModuleList(encode_layers)
|
| 163 |
+
conv_clips = []
|
| 164 |
+
for i in range(len(fusion_index)):
|
| 165 |
+
conv_clips.append(
|
| 166 |
+
nn.Sequential(
|
| 167 |
+
LayerNorm2d(clip_channels),
|
| 168 |
+
ConvModule(
|
| 169 |
+
clip_channels,
|
| 170 |
+
embed_dims,
|
| 171 |
+
kernel_size=1,
|
| 172 |
+
norm_cfg=None,
|
| 173 |
+
act_cfg=None)))
|
| 174 |
+
self.conv_clips = nn.ModuleList(conv_clips)
|
| 175 |
+
self.fusion_index = fusion_index
|
| 176 |
+
self.mask_decoder = MLPMaskDecoder(
|
| 177 |
+
in_channels=embed_dims,
|
| 178 |
+
total_heads=cfg_decoder.num_heads,
|
| 179 |
+
total_layers=cfg_decoder.num_layers,
|
| 180 |
+
embed_channels=cfg_decoder.embed_channels,
|
| 181 |
+
mlp_channels=cfg_decoder.mlp_channels,
|
| 182 |
+
mlp_num_layers=cfg_decoder.num_mlp,
|
| 183 |
+
rescale_attn_bias=cfg_decoder.rescale)
|
| 184 |
+
|
| 185 |
+
def init_weights(self):
|
| 186 |
+
trunc_normal_(self.pos_embed, std=0.02)
|
| 187 |
+
nn.init.normal_(self.query_embed, std=0.02)
|
| 188 |
+
nn.init.normal_(self.query_pos_embed, std=0.02)
|
| 189 |
+
for i in range(len(self.conv_clips)):
|
| 190 |
+
caffe2_xavier_init(self.conv_clips[i][1].conv)
|
| 191 |
+
|
| 192 |
+
def fuse_clip(self, fused_index: int, x: torch.Tensor,
|
| 193 |
+
clip_feature: torch.Tensor, hwshape: Tuple[int,
|
| 194 |
+
int], L: int):
|
| 195 |
+
"""Fuse CLIP feature and visual tokens."""
|
| 196 |
+
fused_clip = (resize(
|
| 197 |
+
self.conv_clips[fused_index](clip_feature.contiguous()),
|
| 198 |
+
size=hwshape,
|
| 199 |
+
mode='bilinear',
|
| 200 |
+
align_corners=False)).permute(0, 2, 3, 1).reshape(x[:, -L:,
|
| 201 |
+
...].shape)
|
| 202 |
+
x = torch.cat([x[:, :-L, ...], x[:, -L:, ...] + fused_clip], dim=1)
|
| 203 |
+
return x
|
| 204 |
+
|
| 205 |
+
def encode_feature(self, image: torch.Tensor,
|
| 206 |
+
clip_features: List[torch.Tensor],
|
| 207 |
+
deep_supervision_idxs: List[int]) -> List[List]:
|
| 208 |
+
"""Encode images by a lightweight vision transformer."""
|
| 209 |
+
assert len(self.fusion_index) == len(clip_features)
|
| 210 |
+
x, hwshape = self.patch_embed(image)
|
| 211 |
+
ori_h, ori_w = self.patch_embed.init_out_size
|
| 212 |
+
pos_embed = self.pos_embed
|
| 213 |
+
if self.pos_embed.shape[1] != x.shape[1]:
|
| 214 |
+
# resize the position embedding
|
| 215 |
+
pos_embed = (
|
| 216 |
+
resize(
|
| 217 |
+
self.pos_embed.reshape(1, ori_h, ori_w,
|
| 218 |
+
-1).permute(0, 3, 1, 2),
|
| 219 |
+
size=hwshape,
|
| 220 |
+
mode='bicubic',
|
| 221 |
+
align_corners=False,
|
| 222 |
+
).flatten(2).permute(0, 2, 1))
|
| 223 |
+
pos_embed = torch.cat([
|
| 224 |
+
self.query_pos_embed.expand(pos_embed.shape[0], -1, -1), pos_embed
|
| 225 |
+
],
|
| 226 |
+
dim=1)
|
| 227 |
+
x = torch.cat([self.query_embed.expand(x.shape[0], -1, -1), x], dim=1)
|
| 228 |
+
x = x + pos_embed
|
| 229 |
+
L = hwshape[0] * hwshape[1]
|
| 230 |
+
fused_index = 0
|
| 231 |
+
if self.fusion_index[fused_index] == 0:
|
| 232 |
+
x = self.fuse_clip(fused_index, x, clip_features[0][0], hwshape, L)
|
| 233 |
+
fused_index += 1
|
| 234 |
+
outs = []
|
| 235 |
+
for index, block in enumerate(self.encode_layers, start=1):
|
| 236 |
+
x = block(x)
|
| 237 |
+
if index < len(self.fusion_index
|
| 238 |
+
) and index == self.fusion_index[fused_index]:
|
| 239 |
+
x = self.fuse_clip(fused_index, x,
|
| 240 |
+
clip_features[fused_index][0], hwshape, L)
|
| 241 |
+
fused_index += 1
|
| 242 |
+
x_query = x[:, :-L, ...]
|
| 243 |
+
x_feat = x[:, -L:, ...].permute(0, 2, 1)\
|
| 244 |
+
.reshape(x.shape[0], x.shape[-1], hwshape[0], hwshape[1])
|
| 245 |
+
|
| 246 |
+
if index in deep_supervision_idxs or index == len(
|
| 247 |
+
self.encode_layers):
|
| 248 |
+
outs.append({'query': x_query, 'x': x_feat})
|
| 249 |
+
|
| 250 |
+
if index < len(self.encode_layers):
|
| 251 |
+
x = x + pos_embed
|
| 252 |
+
return outs
|
| 253 |
+
|
| 254 |
+
def decode_feature(self, features):
|
| 255 |
+
mask_embeds = []
|
| 256 |
+
attn_biases = []
|
| 257 |
+
for feature in features:
|
| 258 |
+
mask_embed, attn_bias = self.mask_decoder(**feature)
|
| 259 |
+
mask_embeds.append(mask_embed)
|
| 260 |
+
attn_biases.append(attn_bias)
|
| 261 |
+
return mask_embeds, attn_biases
|
| 262 |
+
|
| 263 |
+
def forward(
|
| 264 |
+
self, image: torch.Tensor, clip_features: List[torch.Tensor],
|
| 265 |
+
deep_supervision_idxs: List[int]
|
| 266 |
+
) -> Tuple[List[torch.Tensor], List[List[torch.Tensor]]]:
|
| 267 |
+
"""Forward function."""
|
| 268 |
+
features = self.encode_feature(image, clip_features,
|
| 269 |
+
deep_supervision_idxs)
|
| 270 |
+
mask_embeds, attn_biases = self.decode_feature(features)
|
| 271 |
+
return mask_embeds, attn_biases
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class RecWithAttnbias(nn.Module):
|
| 275 |
+
"""Mask recognition module by applying the attention biases to rest deeper
|
| 276 |
+
CLIP layers.
|
| 277 |
+
|
| 278 |
+
Args:
|
| 279 |
+
sos_token_format (str): The format of sos token. It should be
|
| 280 |
+
chosen from ["cls_token", "learnable_token", "pos_embedding"].
|
| 281 |
+
Default: 'cls_token'.
|
| 282 |
+
sos_token_num (int): Number of sos token. It should be equal to
|
| 283 |
+
the number of quries. Default: 100.
|
| 284 |
+
num_layers (int): Number of rest CLIP layers for mask recognition.
|
| 285 |
+
Default: 3.
|
| 286 |
+
cross_attn (bool): Whether use cross attention to update sos token.
|
| 287 |
+
Default: False.
|
| 288 |
+
embed_dims (int): The feature dimension of CLIP layers.
|
| 289 |
+
Default: 768.
|
| 290 |
+
num_heads (int): Parallel attention heads of CLIP layers.
|
| 291 |
+
Default: 768.
|
| 292 |
+
mlp_ratio (int): Ratio of mlp hidden dim to embedding dim.
|
| 293 |
+
Default: 4.
|
| 294 |
+
qkv_bias (bool): Whether to use bias in multihead-attention.
|
| 295 |
+
Default: True.
|
| 296 |
+
out_dims (int): Number of channels of the output mask proposals.
|
| 297 |
+
It should be equal to the out_dims of text_encoder.
|
| 298 |
+
Default: 512.
|
| 299 |
+
final_norm (True): Whether use norm layer for sos token.
|
| 300 |
+
act_cfg (dict): The activation config for FFNs.
|
| 301 |
+
Default: dict(type='GELU').
|
| 302 |
+
norm_cfg (dict): Config dict for normalization layer.
|
| 303 |
+
Default: dict(type='LN').
|
| 304 |
+
frozen_exclude (List): List of parameters that are not to be frozen.
|
| 305 |
+
"""
|
| 306 |
+
|
| 307 |
+
def __init__(self,
|
| 308 |
+
sos_token_format: str = 'cls_token',
|
| 309 |
+
sos_token_num: int = 100,
|
| 310 |
+
num_layers: int = 3,
|
| 311 |
+
cross_attn: bool = False,
|
| 312 |
+
embed_dims: int = 768,
|
| 313 |
+
num_heads: int = 12,
|
| 314 |
+
mlp_ratio: int = 4,
|
| 315 |
+
num_fcs: int = 2,
|
| 316 |
+
qkv_bias: bool = True,
|
| 317 |
+
out_dims: int = 512,
|
| 318 |
+
final_norm: bool = True,
|
| 319 |
+
act_cfg: dict = dict(type='GELU'),
|
| 320 |
+
norm_cfg: dict = dict(type='LN'),
|
| 321 |
+
frozen_exclude: List = []):
|
| 322 |
+
super().__init__()
|
| 323 |
+
|
| 324 |
+
assert sos_token_format in [
|
| 325 |
+
'cls_token', 'learnable_token', 'pos_embedding'
|
| 326 |
+
]
|
| 327 |
+
self.sos_token_format = sos_token_format
|
| 328 |
+
self.sos_token_num = sos_token_num
|
| 329 |
+
self.frozen_exclude = frozen_exclude
|
| 330 |
+
self.cross_attn = cross_attn
|
| 331 |
+
self.num_layers = num_layers
|
| 332 |
+
self.num_heads = num_heads
|
| 333 |
+
if sos_token_format in ['learnable_token', 'pos_embedding']:
|
| 334 |
+
self.sos_token = nn.Parameter(
|
| 335 |
+
torch.randn(sos_token_num, 1, self.proj.shape[0]))
|
| 336 |
+
self.frozen.append('sos_token')
|
| 337 |
+
|
| 338 |
+
layers = []
|
| 339 |
+
for i in range(num_layers):
|
| 340 |
+
layers.append(
|
| 341 |
+
BaseTransformerLayer(
|
| 342 |
+
attn_cfgs=dict(
|
| 343 |
+
type='MultiheadAttention',
|
| 344 |
+
embed_dims=embed_dims,
|
| 345 |
+
num_heads=num_heads,
|
| 346 |
+
batch_first=False,
|
| 347 |
+
bias=qkv_bias),
|
| 348 |
+
ffn_cfgs=dict(
|
| 349 |
+
type='FFN',
|
| 350 |
+
embed_dims=embed_dims,
|
| 351 |
+
feedforward_channels=mlp_ratio * embed_dims,
|
| 352 |
+
act_cfg=act_cfg),
|
| 353 |
+
operation_order=('norm', 'self_attn', 'norm', 'ffn')))
|
| 354 |
+
self.layers = nn.ModuleList(layers)
|
| 355 |
+
|
| 356 |
+
self.ln_post = build_norm_layer(norm_cfg, embed_dims)[1]
|
| 357 |
+
self.proj = nn.Linear(embed_dims, out_dims, bias=False)
|
| 358 |
+
|
| 359 |
+
self.final_norm = final_norm
|
| 360 |
+
self._freeze()
|
| 361 |
+
|
| 362 |
+
def init_weights(self, rec_state_dict):
|
| 363 |
+
if hasattr(self, 'sos_token'):
|
| 364 |
+
normal_init(self.sos_token, std=0.02)
|
| 365 |
+
if rec_state_dict is not None:
|
| 366 |
+
load_state_dict(self, rec_state_dict, strict=False, logger=None)
|
| 367 |
+
else:
|
| 368 |
+
super().init_weights()
|
| 369 |
+
|
| 370 |
+
def _freeze(self):
|
| 371 |
+
if 'all' in self.frozen_exclude:
|
| 372 |
+
return
|
| 373 |
+
for name, param in self.named_parameters():
|
| 374 |
+
if not any([exclude in name for exclude in self.frozen_exclude]):
|
| 375 |
+
param.requires_grad = False
|
| 376 |
+
|
| 377 |
+
def _build_attn_biases(self, attn_biases, target_shape):
|
| 378 |
+
formatted_attn_biases = []
|
| 379 |
+
for attn_bias in attn_biases:
|
| 380 |
+
# convert it to proper format: N*num_head,L,L
|
| 381 |
+
# attn_bias: [N, num_head/1, num_sos,H,W]
|
| 382 |
+
n, num_head, num_sos, h, w = attn_bias.shape
|
| 383 |
+
# reshape and downsample
|
| 384 |
+
attn_bias = F.adaptive_max_pool2d(
|
| 385 |
+
attn_bias.reshape(n, num_head * num_sos, h, w),
|
| 386 |
+
output_size=target_shape)
|
| 387 |
+
attn_bias = attn_bias.reshape(n, num_head, num_sos, *target_shape)
|
| 388 |
+
|
| 389 |
+
true_num_head = self.num_heads
|
| 390 |
+
assert (num_head == 1 or num_head
|
| 391 |
+
== true_num_head), f'num_head={num_head} is not supported.'
|
| 392 |
+
if num_head == 1:
|
| 393 |
+
attn_bias = attn_bias.repeat(1, true_num_head, 1, 1, 1)
|
| 394 |
+
attn_bias = attn_bias.reshape(n * true_num_head, num_sos, -1)
|
| 395 |
+
L = attn_bias.shape[-1]
|
| 396 |
+
if self.cross_attn:
|
| 397 |
+
# [n*num_head, num_sos, L]
|
| 398 |
+
formatted_attn_biases.append(attn_bias)
|
| 399 |
+
else:
|
| 400 |
+
# [n*num_head, num_sos+1+L, num_sos+1+L]
|
| 401 |
+
new_attn_bias = attn_bias.new_zeros(num_sos + 1 + L,
|
| 402 |
+
num_sos + 1 + L)
|
| 403 |
+
new_attn_bias[:, :num_sos] = -100
|
| 404 |
+
new_attn_bias[torch.arange(num_sos), torch.arange(num_sos)] = 0
|
| 405 |
+
new_attn_bias[:num_sos, num_sos] = -100
|
| 406 |
+
new_attn_bias = (
|
| 407 |
+
new_attn_bias[None, ...].expand(n * true_num_head, -1,
|
| 408 |
+
-1).clone())
|
| 409 |
+
new_attn_bias[..., :num_sos, -L:] = attn_bias
|
| 410 |
+
formatted_attn_biases.append(new_attn_bias)
|
| 411 |
+
|
| 412 |
+
if len(formatted_attn_biases) == 1:
|
| 413 |
+
formatted_attn_biases = [
|
| 414 |
+
formatted_attn_biases[0] for _ in range(self.num_layers)
|
| 415 |
+
]
|
| 416 |
+
return formatted_attn_biases
|
| 417 |
+
|
| 418 |
+
def forward(self, bias: List[Tensor], feature: List[Tensor]):
|
| 419 |
+
"""Forward function to recognize the category of masks
|
| 420 |
+
Args:
|
| 421 |
+
bias (List[Tensor]): Attention bias for transformer layers
|
| 422 |
+
feature (List[Tensor]): Output of the image encoder,
|
| 423 |
+
including cls_token and img_feature.
|
| 424 |
+
"""
|
| 425 |
+
cls_token = feature[1].unsqueeze(0)
|
| 426 |
+
img_feature = feature[0]
|
| 427 |
+
b, c, h, w = img_feature.shape
|
| 428 |
+
# construct clip shadow features
|
| 429 |
+
x = torch.cat(
|
| 430 |
+
[cls_token,
|
| 431 |
+
img_feature.reshape(b, c, -1).permute(2, 0, 1)])
|
| 432 |
+
|
| 433 |
+
# construct sos token
|
| 434 |
+
if self.sos_token_format == 'cls_token':
|
| 435 |
+
sos_token = cls_token.repeat(self.sos_token_num, 1, 1)
|
| 436 |
+
elif self.sos_token_format == 'learnable_token':
|
| 437 |
+
sos_token = self.sos_token.expand(-1, b, -1)
|
| 438 |
+
elif self.sos_token_format == 'pos_embedding':
|
| 439 |
+
sos_token = self.sos_token.expand(-1, b, -1) + cls_token
|
| 440 |
+
|
| 441 |
+
# construct attn bias
|
| 442 |
+
attn_biases = self._build_attn_biases(bias, target_shape=(h, w))
|
| 443 |
+
|
| 444 |
+
if self.cross_attn:
|
| 445 |
+
for i, block in enumerate(self.layers):
|
| 446 |
+
if self.cross_attn:
|
| 447 |
+
sos_token = cross_attn_layer(
|
| 448 |
+
block,
|
| 449 |
+
sos_token,
|
| 450 |
+
x[1:, ],
|
| 451 |
+
attn_biases[i],
|
| 452 |
+
)
|
| 453 |
+
if i < len(self.layers) - 1:
|
| 454 |
+
x = block(x)
|
| 455 |
+
else:
|
| 456 |
+
x = torch.cat([sos_token, x], dim=0)
|
| 457 |
+
for i, block in enumerate(self.layers):
|
| 458 |
+
x = block(x, attn_masks=[attn_biases[i]])
|
| 459 |
+
sos_token = x[:self.sos_token_num]
|
| 460 |
+
|
| 461 |
+
sos_token = sos_token.permute(1, 0, 2) # LND -> NLD
|
| 462 |
+
sos_token = self.ln_post(sos_token)
|
| 463 |
+
sos_token = self.proj(sos_token)
|
| 464 |
+
if self.final_norm:
|
| 465 |
+
sos_token = F.normalize(sos_token, dim=-1)
|
| 466 |
+
return sos_token
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
@MODELS.register_module()
|
| 470 |
+
class SideAdapterCLIPHead(BaseDecodeHead):
|
| 471 |
+
"""Side Adapter Network (SAN) for open-vocabulary semantic segmentation
|
| 472 |
+
with pre-trained vision-language model.
|
| 473 |
+
|
| 474 |
+
This decode head is the implementation of `Side Adapter Network
|
| 475 |
+
for Open-Vocabulary Semantic Segmentation`
|
| 476 |
+
<https://arxiv.org/abs/2302.12242>.
|
| 477 |
+
Modified from https://github.com/MendelXu/SAN/blob/main/san/model/side_adapter/side_adapter.py # noqa:E501
|
| 478 |
+
Copyright (c) 2023 MendelXu.
|
| 479 |
+
Licensed under the MIT License
|
| 480 |
+
|
| 481 |
+
Args:
|
| 482 |
+
num_classes (int): the number of classes.
|
| 483 |
+
san_cfg (ConfigType): Configs for SideAdapterNetwork module
|
| 484 |
+
maskgen_cfg (ConfigType): Configs for RecWithAttnbias module
|
| 485 |
+
"""
|
| 486 |
+
|
| 487 |
+
def __init__(self, num_classes: int, san_cfg: ConfigType,
|
| 488 |
+
maskgen_cfg: ConfigType, deep_supervision_idxs: List[int],
|
| 489 |
+
train_cfg: ConfigType, **kwargs):
|
| 490 |
+
super().__init__(
|
| 491 |
+
in_channels=san_cfg.in_channels,
|
| 492 |
+
channels=san_cfg.embed_dims,
|
| 493 |
+
num_classes=num_classes,
|
| 494 |
+
**kwargs)
|
| 495 |
+
assert san_cfg.num_queries == maskgen_cfg.sos_token_num, \
|
| 496 |
+
'num_queries in san_cfg should be equal to sos_token_num ' \
|
| 497 |
+
'in maskgen_cfg'
|
| 498 |
+
del self.conv_seg
|
| 499 |
+
self.side_adapter_network = SideAdapterNetwork(**san_cfg)
|
| 500 |
+
self.rec_with_attnbias = RecWithAttnbias(**maskgen_cfg)
|
| 501 |
+
self.deep_supervision_idxs = deep_supervision_idxs
|
| 502 |
+
self.train_cfg = train_cfg
|
| 503 |
+
if train_cfg:
|
| 504 |
+
self.match_masks = MatchMasks(
|
| 505 |
+
num_points=train_cfg.num_points,
|
| 506 |
+
num_queries=san_cfg.num_queries,
|
| 507 |
+
num_classes=num_classes,
|
| 508 |
+
assigner=train_cfg.assigner)
|
| 509 |
+
|
| 510 |
+
def init_weights(self):
|
| 511 |
+
|
| 512 |
+
rec_state_dict = None
|
| 513 |
+
if isinstance(self.init_cfg, dict) and \
|
| 514 |
+
self.init_cfg.get('type') == 'Pretrained_Part':
|
| 515 |
+
checkpoint = CheckpointLoader.load_checkpoint(
|
| 516 |
+
self.init_cfg['checkpoint'], logger=None, map_location='cpu')
|
| 517 |
+
|
| 518 |
+
rec_state_dict = checkpoint.copy()
|
| 519 |
+
para_prefix = 'decode_head.rec_with_attnbias'
|
| 520 |
+
prefix_len = len(para_prefix) + 1
|
| 521 |
+
for k, v in checkpoint.items():
|
| 522 |
+
rec_state_dict.pop(k)
|
| 523 |
+
if para_prefix in k:
|
| 524 |
+
rec_state_dict[k[prefix_len:]] = v
|
| 525 |
+
|
| 526 |
+
self.side_adapter_network.init_weights()
|
| 527 |
+
self.rec_with_attnbias.init_weights(rec_state_dict)
|
| 528 |
+
|
| 529 |
+
def forward(self, inputs: Tuple[Tensor],
|
| 530 |
+
deep_supervision_idxs) -> Tuple[List]:
|
| 531 |
+
"""Forward function.
|
| 532 |
+
|
| 533 |
+
Args:
|
| 534 |
+
inputs (Tuple[Tensor]): A triplet including images,
|
| 535 |
+
list of multi-level visual features from image encoder and
|
| 536 |
+
class embeddings from text_encoder.
|
| 537 |
+
|
| 538 |
+
Returns:
|
| 539 |
+
mask_props (List[Tensor]): Mask proposals predicted by SAN.
|
| 540 |
+
mask_logits (List[Tensor]): Class logits of mask proposals.
|
| 541 |
+
"""
|
| 542 |
+
imgs, clip_feature, class_embeds = inputs
|
| 543 |
+
# predict mask proposals and attention bias
|
| 544 |
+
mask_props, attn_biases = self.side_adapter_network(
|
| 545 |
+
imgs, clip_feature, deep_supervision_idxs)
|
| 546 |
+
|
| 547 |
+
# mask recognition with attention bias
|
| 548 |
+
mask_embeds = [
|
| 549 |
+
self.rec_with_attnbias(att_bias, clip_feature[-1])
|
| 550 |
+
for att_bias in attn_biases
|
| 551 |
+
]
|
| 552 |
+
# Obtain class prediction of masks by comparing the similarity
|
| 553 |
+
# between the image token and the text embedding of class names.
|
| 554 |
+
mask_logits = [
|
| 555 |
+
torch.einsum('bqc,nc->bqn', mask_embed, class_embeds)
|
| 556 |
+
for mask_embed in mask_embeds
|
| 557 |
+
]
|
| 558 |
+
return mask_props, mask_logits
|
| 559 |
+
|
| 560 |
+
def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict],
|
| 561 |
+
test_cfg: ConfigType) -> Tensor:
|
| 562 |
+
"""Forward function for prediction.
|
| 563 |
+
|
| 564 |
+
Args:
|
| 565 |
+
inputs (Tuple[Tensor]): Images, visual features from image encoder
|
| 566 |
+
and class embedding from text encoder.
|
| 567 |
+
batch_img_metas (dict): List Image info where each dict may also
|
| 568 |
+
contain: 'img_shape', 'scale_factor', 'flip', 'img_path',
|
| 569 |
+
'ori_shape', and 'pad_shape'.
|
| 570 |
+
For details on the values of these keys see
|
| 571 |
+
`mmseg/datasets/pipelines/formatting.py:PackSegInputs`.
|
| 572 |
+
test_cfg (dict): The testing config.
|
| 573 |
+
|
| 574 |
+
Returns:
|
| 575 |
+
Tensor: Outputs segmentation logits map.
|
| 576 |
+
"""
|
| 577 |
+
mask_props, mask_logits = self.forward(inputs, [])
|
| 578 |
+
|
| 579 |
+
return self.predict_by_feat([mask_props[-1], mask_logits[-1]],
|
| 580 |
+
batch_img_metas)
|
| 581 |
+
|
| 582 |
+
def predict_by_feat(self, seg_logits: List[Tensor],
|
| 583 |
+
batch_img_metas: List[dict]) -> Tensor:
|
| 584 |
+
"""1. Transform a batch of mask proposals to the input shape.
|
| 585 |
+
2. Generate segmentation map with mask proposals and class logits.
|
| 586 |
+
"""
|
| 587 |
+
mask_pred = seg_logits[0]
|
| 588 |
+
cls_score = seg_logits[1]
|
| 589 |
+
if isinstance(batch_img_metas[0]['img_shape'], torch.Size):
|
| 590 |
+
# slide inference
|
| 591 |
+
size = batch_img_metas[0]['img_shape']
|
| 592 |
+
elif 'pad_shape' in batch_img_metas[0]:
|
| 593 |
+
size = batch_img_metas[0]['pad_shape'][:2]
|
| 594 |
+
else:
|
| 595 |
+
size = batch_img_metas[0]['img_shape']
|
| 596 |
+
# upsample mask
|
| 597 |
+
mask_pred = F.interpolate(
|
| 598 |
+
mask_pred, size=size, mode='bilinear', align_corners=False)
|
| 599 |
+
|
| 600 |
+
mask_cls = F.softmax(cls_score, dim=-1)[..., :-1]
|
| 601 |
+
mask_pred = mask_pred.sigmoid()
|
| 602 |
+
seg_logits = torch.einsum('bqc,bqhw->bchw', mask_cls, mask_pred)
|
| 603 |
+
return seg_logits
|
| 604 |
+
|
| 605 |
+
def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList,
|
| 606 |
+
train_cfg: ConfigType) -> dict:
|
| 607 |
+
"""Perform forward propagation and loss calculation of the decoder head
|
| 608 |
+
on the features of the upstream network.
|
| 609 |
+
|
| 610 |
+
Args:
|
| 611 |
+
x (tuple[Tensor]): Multi-level features from the upstream
|
| 612 |
+
network, each is a 4D-tensor.
|
| 613 |
+
batch_data_samples (List[:obj:`SegDataSample`]): The Data
|
| 614 |
+
Samples. It usually includes information such as
|
| 615 |
+
`gt_sem_seg`.
|
| 616 |
+
train_cfg (ConfigType): Training config.
|
| 617 |
+
|
| 618 |
+
Returns:
|
| 619 |
+
dict[str, Tensor]: a dictionary of loss components.
|
| 620 |
+
"""
|
| 621 |
+
# batch SegDataSample to InstanceDataSample
|
| 622 |
+
batch_gt_instances = seg_data_to_instance_data(self.ignore_index,
|
| 623 |
+
batch_data_samples)
|
| 624 |
+
|
| 625 |
+
# forward
|
| 626 |
+
all_mask_props, all_mask_logits = self.forward(
|
| 627 |
+
x, self.deep_supervision_idxs)
|
| 628 |
+
|
| 629 |
+
# loss
|
| 630 |
+
losses = self.loss_by_feat(all_mask_logits, all_mask_props,
|
| 631 |
+
batch_gt_instances)
|
| 632 |
+
|
| 633 |
+
return losses
|
| 634 |
+
|
| 635 |
+
def loss_by_feat(
|
| 636 |
+
self, all_cls_scores: Tensor, all_mask_preds: Tensor,
|
| 637 |
+
batch_gt_instances: List[InstanceData]) -> Dict[str, Tensor]:
|
| 638 |
+
"""Loss function.
|
| 639 |
+
|
| 640 |
+
Args:
|
| 641 |
+
all_cls_scores (Tensor): Classification scores for all decoder
|
| 642 |
+
layers with shape (num_decoder, batch_size, num_queries,
|
| 643 |
+
cls_out_channels). Note `cls_out_channels` should includes
|
| 644 |
+
background.
|
| 645 |
+
all_mask_preds (Tensor): Mask scores for all decoder layers with
|
| 646 |
+
shape (num_decoder, batch_size, num_queries, h, w).
|
| 647 |
+
batch_gt_instances (list[obj:`InstanceData`]): each contains
|
| 648 |
+
``labels`` and ``masks``.
|
| 649 |
+
|
| 650 |
+
Returns:
|
| 651 |
+
dict[str, Tensor]: A dictionary of loss components.
|
| 652 |
+
"""
|
| 653 |
+
num_dec_layers = len(all_cls_scores)
|
| 654 |
+
batch_gt_instances_list = [
|
| 655 |
+
batch_gt_instances for _ in range(num_dec_layers)
|
| 656 |
+
]
|
| 657 |
+
|
| 658 |
+
losses = []
|
| 659 |
+
for i in range(num_dec_layers):
|
| 660 |
+
cls_scores = all_cls_scores[i]
|
| 661 |
+
mask_preds = all_mask_preds[i]
|
| 662 |
+
# matching N mask predictions to K category labels
|
| 663 |
+
(labels, mask_targets, mask_weights,
|
| 664 |
+
avg_factor) = self.match_masks.get_targets(
|
| 665 |
+
cls_scores, mask_preds, batch_gt_instances_list[i])
|
| 666 |
+
cls_scores = cls_scores.flatten(0, 1)
|
| 667 |
+
labels = labels.flatten(0, 1)
|
| 668 |
+
num_total_masks = cls_scores.new_tensor([avg_factor],
|
| 669 |
+
dtype=torch.float)
|
| 670 |
+
all_reduce(num_total_masks, op='mean')
|
| 671 |
+
num_total_masks = max(num_total_masks, 1)
|
| 672 |
+
|
| 673 |
+
# extract positive ones
|
| 674 |
+
# shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w)
|
| 675 |
+
mask_preds = mask_preds[mask_weights > 0]
|
| 676 |
+
|
| 677 |
+
if mask_targets.shape[0] != 0:
|
| 678 |
+
with torch.no_grad():
|
| 679 |
+
points_coords = get_uncertain_point_coords_with_randomness(
|
| 680 |
+
mask_preds.unsqueeze(1), None,
|
| 681 |
+
self.train_cfg.num_points,
|
| 682 |
+
self.train_cfg.oversample_ratio,
|
| 683 |
+
self.train_cfg.importance_sample_ratio)
|
| 684 |
+
# shape (num_total_gts, h, w)
|
| 685 |
+
# -> (num_total_gts, num_points)
|
| 686 |
+
mask_point_targets = point_sample(
|
| 687 |
+
mask_targets.unsqueeze(1).float(),
|
| 688 |
+
points_coords).squeeze(1)
|
| 689 |
+
# shape (num_queries, h, w) -> (num_queries, num_points)
|
| 690 |
+
mask_point_preds = point_sample(
|
| 691 |
+
mask_preds.unsqueeze(1), points_coords).squeeze(1)
|
| 692 |
+
|
| 693 |
+
if not isinstance(self.loss_decode, nn.ModuleList):
|
| 694 |
+
losses_decode = [self.loss_decode]
|
| 695 |
+
else:
|
| 696 |
+
losses_decode = self.loss_decode
|
| 697 |
+
loss = dict()
|
| 698 |
+
for loss_decode in losses_decode:
|
| 699 |
+
if 'loss_cls' in loss_decode.loss_name:
|
| 700 |
+
if loss_decode.loss_name == 'loss_cls_ce':
|
| 701 |
+
loss[loss_decode.loss_name] = loss_decode(
|
| 702 |
+
cls_scores, labels)
|
| 703 |
+
else:
|
| 704 |
+
assert False, "Only support 'CrossEntropyLoss' in" \
|
| 705 |
+
' classification loss'
|
| 706 |
+
|
| 707 |
+
elif 'loss_mask' in loss_decode.loss_name:
|
| 708 |
+
if mask_targets.shape[0] == 0:
|
| 709 |
+
loss[loss_decode.loss_name] = mask_preds.sum()
|
| 710 |
+
elif loss_decode.loss_name == 'loss_mask_ce':
|
| 711 |
+
loss[loss_decode.loss_name] = loss_decode(
|
| 712 |
+
mask_point_preds,
|
| 713 |
+
mask_point_targets,
|
| 714 |
+
avg_factor=num_total_masks *
|
| 715 |
+
self.train_cfg.num_points)
|
| 716 |
+
elif loss_decode.loss_name == 'loss_mask_dice':
|
| 717 |
+
loss[loss_decode.loss_name] = loss_decode(
|
| 718 |
+
mask_point_preds,
|
| 719 |
+
mask_point_targets,
|
| 720 |
+
avg_factor=num_total_masks)
|
| 721 |
+
else:
|
| 722 |
+
assert False, "Only support 'CrossEntropyLoss' and" \
|
| 723 |
+
" 'DiceLoss' in mask loss"
|
| 724 |
+
else:
|
| 725 |
+
assert False, "Only support for 'loss_cls' and 'loss_mask'"
|
| 726 |
+
|
| 727 |
+
losses.append(loss)
|
| 728 |
+
|
| 729 |
+
loss_dict = dict()
|
| 730 |
+
# loss from the last decoder layer
|
| 731 |
+
loss_dict.update(losses[-1])
|
| 732 |
+
# loss from other decoder layers
|
| 733 |
+
for i, loss in enumerate(losses[:-1]):
|
| 734 |
+
for k, v in loss.items():
|
| 735 |
+
loss_dict[f'd{self.deep_supervision_idxs[i]}.{k}'] = v
|
| 736 |
+
return loss_dict
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/segformer_head.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.models.decode_heads.decode_head import BaseDecodeHead
|
| 7 |
+
from mmseg.registry import MODELS
|
| 8 |
+
from ..utils import resize
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@MODELS.register_module()
|
| 12 |
+
class SegformerHead(BaseDecodeHead):
|
| 13 |
+
"""The all mlp Head of segformer.
|
| 14 |
+
|
| 15 |
+
This head is the implementation of
|
| 16 |
+
`Segformer <https://arxiv.org/abs/2105.15203>` _.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
interpolate_mode: The interpolate mode of MLP head upsample operation.
|
| 20 |
+
Default: 'bilinear'.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, interpolate_mode='bilinear', **kwargs):
|
| 24 |
+
super().__init__(input_transform='multiple_select', **kwargs)
|
| 25 |
+
|
| 26 |
+
self.interpolate_mode = interpolate_mode
|
| 27 |
+
num_inputs = len(self.in_channels)
|
| 28 |
+
|
| 29 |
+
assert num_inputs == len(self.in_index)
|
| 30 |
+
|
| 31 |
+
self.convs = nn.ModuleList()
|
| 32 |
+
for i in range(num_inputs):
|
| 33 |
+
self.convs.append(
|
| 34 |
+
ConvModule(
|
| 35 |
+
in_channels=self.in_channels[i],
|
| 36 |
+
out_channels=self.channels,
|
| 37 |
+
kernel_size=1,
|
| 38 |
+
stride=1,
|
| 39 |
+
norm_cfg=self.norm_cfg,
|
| 40 |
+
act_cfg=self.act_cfg))
|
| 41 |
+
|
| 42 |
+
self.fusion_conv = ConvModule(
|
| 43 |
+
in_channels=self.channels * num_inputs,
|
| 44 |
+
out_channels=self.channels,
|
| 45 |
+
kernel_size=1,
|
| 46 |
+
norm_cfg=self.norm_cfg)
|
| 47 |
+
|
| 48 |
+
def forward(self, inputs):
|
| 49 |
+
# Receive 4 stage backbone feature map: 1/4, 1/8, 1/16, 1/32
|
| 50 |
+
inputs = self._transform_inputs(inputs)
|
| 51 |
+
outs = []
|
| 52 |
+
for idx in range(len(inputs)):
|
| 53 |
+
x = inputs[idx]
|
| 54 |
+
conv = self.convs[idx]
|
| 55 |
+
outs.append(
|
| 56 |
+
resize(
|
| 57 |
+
input=conv(x),
|
| 58 |
+
size=inputs[0].shape[2:],
|
| 59 |
+
mode=self.interpolate_mode,
|
| 60 |
+
align_corners=self.align_corners))
|
| 61 |
+
|
| 62 |
+
out = self.fusion_conv(torch.cat(outs, dim=1))
|
| 63 |
+
|
| 64 |
+
out = self.cls_seg(out)
|
| 65 |
+
|
| 66 |
+
return out
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/segmenter_mask_head.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from mmcv.cnn import build_norm_layer
|
| 6 |
+
from mmengine.model import ModuleList
|
| 7 |
+
from mmengine.model.weight_init import (constant_init, trunc_normal_,
|
| 8 |
+
trunc_normal_init)
|
| 9 |
+
|
| 10 |
+
from mmseg.models.backbones.vit import TransformerEncoderLayer
|
| 11 |
+
from mmseg.registry import MODELS
|
| 12 |
+
from .decode_head import BaseDecodeHead
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@MODELS.register_module()
|
| 16 |
+
class SegmenterMaskTransformerHead(BaseDecodeHead):
|
| 17 |
+
"""Segmenter: Transformer for Semantic Segmentation.
|
| 18 |
+
|
| 19 |
+
This head is the implementation of
|
| 20 |
+
`Segmenter: <https://arxiv.org/abs/2105.05633>`_.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
backbone_cfg:(dict): Config of backbone of
|
| 24 |
+
Context Path.
|
| 25 |
+
in_channels (int): The number of channels of input image.
|
| 26 |
+
num_layers (int): The depth of transformer.
|
| 27 |
+
num_heads (int): The number of attention heads.
|
| 28 |
+
embed_dims (int): The number of embedding dimension.
|
| 29 |
+
mlp_ratio (int): ratio of mlp hidden dim to embedding dim.
|
| 30 |
+
Default: 4.
|
| 31 |
+
drop_path_rate (float): stochastic depth rate. Default 0.1.
|
| 32 |
+
drop_rate (float): Probability of an element to be zeroed.
|
| 33 |
+
Default 0.0
|
| 34 |
+
attn_drop_rate (float): The drop out rate for attention layer.
|
| 35 |
+
Default 0.0
|
| 36 |
+
num_fcs (int): The number of fully-connected layers for FFNs.
|
| 37 |
+
Default: 2.
|
| 38 |
+
qkv_bias (bool): Enable bias for qkv if True. Default: True.
|
| 39 |
+
act_cfg (dict): The activation config for FFNs.
|
| 40 |
+
Default: dict(type='GELU').
|
| 41 |
+
norm_cfg (dict): Config dict for normalization layer.
|
| 42 |
+
Default: dict(type='LN')
|
| 43 |
+
init_std (float): The value of std in weight initialization.
|
| 44 |
+
Default: 0.02.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
in_channels,
|
| 50 |
+
num_layers,
|
| 51 |
+
num_heads,
|
| 52 |
+
embed_dims,
|
| 53 |
+
mlp_ratio=4,
|
| 54 |
+
drop_path_rate=0.1,
|
| 55 |
+
drop_rate=0.0,
|
| 56 |
+
attn_drop_rate=0.0,
|
| 57 |
+
num_fcs=2,
|
| 58 |
+
qkv_bias=True,
|
| 59 |
+
act_cfg=dict(type='GELU'),
|
| 60 |
+
norm_cfg=dict(type='LN'),
|
| 61 |
+
init_std=0.02,
|
| 62 |
+
**kwargs,
|
| 63 |
+
):
|
| 64 |
+
super().__init__(in_channels=in_channels, **kwargs)
|
| 65 |
+
|
| 66 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_layers)]
|
| 67 |
+
self.layers = ModuleList()
|
| 68 |
+
for i in range(num_layers):
|
| 69 |
+
self.layers.append(
|
| 70 |
+
TransformerEncoderLayer(
|
| 71 |
+
embed_dims=embed_dims,
|
| 72 |
+
num_heads=num_heads,
|
| 73 |
+
feedforward_channels=mlp_ratio * embed_dims,
|
| 74 |
+
attn_drop_rate=attn_drop_rate,
|
| 75 |
+
drop_rate=drop_rate,
|
| 76 |
+
drop_path_rate=dpr[i],
|
| 77 |
+
num_fcs=num_fcs,
|
| 78 |
+
qkv_bias=qkv_bias,
|
| 79 |
+
act_cfg=act_cfg,
|
| 80 |
+
norm_cfg=norm_cfg,
|
| 81 |
+
batch_first=True,
|
| 82 |
+
))
|
| 83 |
+
|
| 84 |
+
self.dec_proj = nn.Linear(in_channels, embed_dims)
|
| 85 |
+
|
| 86 |
+
self.cls_emb = nn.Parameter(
|
| 87 |
+
torch.randn(1, self.num_classes, embed_dims))
|
| 88 |
+
self.patch_proj = nn.Linear(embed_dims, embed_dims, bias=False)
|
| 89 |
+
self.classes_proj = nn.Linear(embed_dims, embed_dims, bias=False)
|
| 90 |
+
|
| 91 |
+
self.decoder_norm = build_norm_layer(
|
| 92 |
+
norm_cfg, embed_dims, postfix=1)[1]
|
| 93 |
+
self.mask_norm = build_norm_layer(
|
| 94 |
+
norm_cfg, self.num_classes, postfix=2)[1]
|
| 95 |
+
|
| 96 |
+
self.init_std = init_std
|
| 97 |
+
|
| 98 |
+
delattr(self, 'conv_seg')
|
| 99 |
+
|
| 100 |
+
def init_weights(self):
|
| 101 |
+
trunc_normal_(self.cls_emb, std=self.init_std)
|
| 102 |
+
trunc_normal_init(self.patch_proj, std=self.init_std)
|
| 103 |
+
trunc_normal_init(self.classes_proj, std=self.init_std)
|
| 104 |
+
for n, m in self.named_modules():
|
| 105 |
+
if isinstance(m, nn.Linear):
|
| 106 |
+
trunc_normal_init(m, std=self.init_std, bias=0)
|
| 107 |
+
elif isinstance(m, nn.LayerNorm):
|
| 108 |
+
constant_init(m, val=1.0, bias=0.0)
|
| 109 |
+
|
| 110 |
+
def forward(self, inputs):
|
| 111 |
+
x = self._transform_inputs(inputs)
|
| 112 |
+
b, c, h, w = x.shape
|
| 113 |
+
x = x.permute(0, 2, 3, 1).contiguous().view(b, -1, c)
|
| 114 |
+
|
| 115 |
+
x = self.dec_proj(x)
|
| 116 |
+
cls_emb = self.cls_emb.expand(x.size(0), -1, -1)
|
| 117 |
+
x = torch.cat((x, cls_emb), 1)
|
| 118 |
+
for layer in self.layers:
|
| 119 |
+
x = layer(x)
|
| 120 |
+
x = self.decoder_norm(x)
|
| 121 |
+
|
| 122 |
+
patches = self.patch_proj(x[:, :-self.num_classes])
|
| 123 |
+
cls_seg_feat = self.classes_proj(x[:, -self.num_classes:])
|
| 124 |
+
|
| 125 |
+
patches = F.normalize(patches, dim=2, p=2)
|
| 126 |
+
cls_seg_feat = F.normalize(cls_seg_feat, dim=2, p=2)
|
| 127 |
+
|
| 128 |
+
masks = patches @ cls_seg_feat.transpose(1, 2)
|
| 129 |
+
masks = self.mask_norm(masks)
|
| 130 |
+
masks = masks.permute(0, 2, 1).contiguous().view(b, -1, h, w)
|
| 131 |
+
|
| 132 |
+
return masks
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_aspp_head.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from ..utils import resize
|
| 8 |
+
from .aspp_head import ASPPHead, ASPPModule
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DepthwiseSeparableASPPModule(ASPPModule):
|
| 12 |
+
"""Atrous Spatial Pyramid Pooling (ASPP) Module with depthwise separable
|
| 13 |
+
conv."""
|
| 14 |
+
|
| 15 |
+
def __init__(self, **kwargs):
|
| 16 |
+
super().__init__(**kwargs)
|
| 17 |
+
for i, dilation in enumerate(self.dilations):
|
| 18 |
+
if dilation > 1:
|
| 19 |
+
self[i] = DepthwiseSeparableConvModule(
|
| 20 |
+
self.in_channels,
|
| 21 |
+
self.channels,
|
| 22 |
+
3,
|
| 23 |
+
dilation=dilation,
|
| 24 |
+
padding=dilation,
|
| 25 |
+
norm_cfg=self.norm_cfg,
|
| 26 |
+
act_cfg=self.act_cfg)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@MODELS.register_module()
|
| 30 |
+
class DepthwiseSeparableASPPHead(ASPPHead):
|
| 31 |
+
"""Encoder-Decoder with Atrous Separable Convolution for Semantic Image
|
| 32 |
+
Segmentation.
|
| 33 |
+
|
| 34 |
+
This head is the implementation of `DeepLabV3+
|
| 35 |
+
<https://arxiv.org/abs/1802.02611>`_.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
c1_in_channels (int): The input channels of c1 decoder. If is 0,
|
| 39 |
+
the no decoder will be used.
|
| 40 |
+
c1_channels (int): The intermediate channels of c1 decoder.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, c1_in_channels, c1_channels, **kwargs):
|
| 44 |
+
super().__init__(**kwargs)
|
| 45 |
+
assert c1_in_channels >= 0
|
| 46 |
+
self.aspp_modules = DepthwiseSeparableASPPModule(
|
| 47 |
+
dilations=self.dilations,
|
| 48 |
+
in_channels=self.in_channels,
|
| 49 |
+
channels=self.channels,
|
| 50 |
+
conv_cfg=self.conv_cfg,
|
| 51 |
+
norm_cfg=self.norm_cfg,
|
| 52 |
+
act_cfg=self.act_cfg)
|
| 53 |
+
if c1_in_channels > 0:
|
| 54 |
+
self.c1_bottleneck = ConvModule(
|
| 55 |
+
c1_in_channels,
|
| 56 |
+
c1_channels,
|
| 57 |
+
1,
|
| 58 |
+
conv_cfg=self.conv_cfg,
|
| 59 |
+
norm_cfg=self.norm_cfg,
|
| 60 |
+
act_cfg=self.act_cfg)
|
| 61 |
+
else:
|
| 62 |
+
self.c1_bottleneck = None
|
| 63 |
+
self.sep_bottleneck = nn.Sequential(
|
| 64 |
+
DepthwiseSeparableConvModule(
|
| 65 |
+
self.channels + c1_channels,
|
| 66 |
+
self.channels,
|
| 67 |
+
3,
|
| 68 |
+
padding=1,
|
| 69 |
+
norm_cfg=self.norm_cfg,
|
| 70 |
+
act_cfg=self.act_cfg),
|
| 71 |
+
DepthwiseSeparableConvModule(
|
| 72 |
+
self.channels,
|
| 73 |
+
self.channels,
|
| 74 |
+
3,
|
| 75 |
+
padding=1,
|
| 76 |
+
norm_cfg=self.norm_cfg,
|
| 77 |
+
act_cfg=self.act_cfg))
|
| 78 |
+
|
| 79 |
+
def forward(self, inputs):
|
| 80 |
+
"""Forward function."""
|
| 81 |
+
x = self._transform_inputs(inputs)
|
| 82 |
+
aspp_outs = [
|
| 83 |
+
resize(
|
| 84 |
+
self.image_pool(x),
|
| 85 |
+
size=x.size()[2:],
|
| 86 |
+
mode='bilinear',
|
| 87 |
+
align_corners=self.align_corners)
|
| 88 |
+
]
|
| 89 |
+
aspp_outs.extend(self.aspp_modules(x))
|
| 90 |
+
aspp_outs = torch.cat(aspp_outs, dim=1)
|
| 91 |
+
output = self.bottleneck(aspp_outs)
|
| 92 |
+
if self.c1_bottleneck is not None:
|
| 93 |
+
c1_output = self.c1_bottleneck(inputs[0])
|
| 94 |
+
output = resize(
|
| 95 |
+
input=output,
|
| 96 |
+
size=c1_output.shape[2:],
|
| 97 |
+
mode='bilinear',
|
| 98 |
+
align_corners=self.align_corners)
|
| 99 |
+
output = torch.cat([output, c1_output], dim=1)
|
| 100 |
+
output = self.sep_bottleneck(output)
|
| 101 |
+
output = self.cls_seg(output)
|
| 102 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_fcn_head.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from mmcv.cnn import DepthwiseSeparableConvModule
|
| 3 |
+
|
| 4 |
+
from mmseg.registry import MODELS
|
| 5 |
+
from .fcn_head import FCNHead
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@MODELS.register_module()
|
| 9 |
+
class DepthwiseSeparableFCNHead(FCNHead):
|
| 10 |
+
"""Depthwise-Separable Fully Convolutional Network for Semantic
|
| 11 |
+
Segmentation.
|
| 12 |
+
|
| 13 |
+
This head is implemented according to `Fast-SCNN: Fast Semantic
|
| 14 |
+
Segmentation Network <https://arxiv.org/abs/1902.04502>`_.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
in_channels(int): Number of output channels of FFM.
|
| 18 |
+
channels(int): Number of middle-stage channels in the decode head.
|
| 19 |
+
concat_input(bool): Whether to concatenate original decode input into
|
| 20 |
+
the result of several consecutive convolution layers.
|
| 21 |
+
Default: True.
|
| 22 |
+
num_classes(int): Used to determine the dimension of
|
| 23 |
+
final prediction tensor.
|
| 24 |
+
in_index(int): Correspond with 'out_indices' in FastSCNN backbone.
|
| 25 |
+
norm_cfg (dict | None): Config of norm layers.
|
| 26 |
+
align_corners (bool): align_corners argument of F.interpolate.
|
| 27 |
+
Default: False.
|
| 28 |
+
loss_decode(dict): Config of loss type and some
|
| 29 |
+
relevant additional options.
|
| 30 |
+
dw_act_cfg (dict):Activation config of depthwise ConvModule. If it is
|
| 31 |
+
'default', it will be the same as `act_cfg`. Default: None.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(self, dw_act_cfg=None, **kwargs):
|
| 35 |
+
super().__init__(**kwargs)
|
| 36 |
+
self.convs[0] = DepthwiseSeparableConvModule(
|
| 37 |
+
self.in_channels,
|
| 38 |
+
self.channels,
|
| 39 |
+
kernel_size=self.kernel_size,
|
| 40 |
+
padding=self.kernel_size // 2,
|
| 41 |
+
norm_cfg=self.norm_cfg,
|
| 42 |
+
dw_act_cfg=dw_act_cfg)
|
| 43 |
+
|
| 44 |
+
for i in range(1, self.num_convs):
|
| 45 |
+
self.convs[i] = DepthwiseSeparableConvModule(
|
| 46 |
+
self.channels,
|
| 47 |
+
self.channels,
|
| 48 |
+
kernel_size=self.kernel_size,
|
| 49 |
+
padding=self.kernel_size // 2,
|
| 50 |
+
norm_cfg=self.norm_cfg,
|
| 51 |
+
dw_act_cfg=dw_act_cfg)
|
| 52 |
+
|
| 53 |
+
if self.concat_input:
|
| 54 |
+
self.conv_cat = DepthwiseSeparableConvModule(
|
| 55 |
+
self.in_channels + self.channels,
|
| 56 |
+
self.channels,
|
| 57 |
+
kernel_size=self.kernel_size,
|
| 58 |
+
padding=self.kernel_size // 2,
|
| 59 |
+
norm_cfg=self.norm_cfg,
|
| 60 |
+
dw_act_cfg=dw_act_cfg)
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_mla_head.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from ..utils import Upsample
|
| 8 |
+
from .decode_head import BaseDecodeHead
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@MODELS.register_module()
|
| 12 |
+
class SETRMLAHead(BaseDecodeHead):
|
| 13 |
+
"""Multi level feature aggretation head of SETR.
|
| 14 |
+
|
| 15 |
+
MLA head of `SETR <https://arxiv.org/pdf/2012.15840.pdf>`_.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
mlahead_channels (int): Channels of conv-conv-4x of multi-level feature
|
| 19 |
+
aggregation. Default: 128.
|
| 20 |
+
up_scale (int): The scale factor of interpolate. Default:4.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, mla_channels=128, up_scale=4, **kwargs):
|
| 24 |
+
super().__init__(input_transform='multiple_select', **kwargs)
|
| 25 |
+
self.mla_channels = mla_channels
|
| 26 |
+
|
| 27 |
+
num_inputs = len(self.in_channels)
|
| 28 |
+
|
| 29 |
+
# Refer to self.cls_seg settings of BaseDecodeHead
|
| 30 |
+
assert self.channels == num_inputs * mla_channels
|
| 31 |
+
|
| 32 |
+
self.up_convs = nn.ModuleList()
|
| 33 |
+
for i in range(num_inputs):
|
| 34 |
+
self.up_convs.append(
|
| 35 |
+
nn.Sequential(
|
| 36 |
+
ConvModule(
|
| 37 |
+
in_channels=self.in_channels[i],
|
| 38 |
+
out_channels=mla_channels,
|
| 39 |
+
kernel_size=3,
|
| 40 |
+
padding=1,
|
| 41 |
+
norm_cfg=self.norm_cfg,
|
| 42 |
+
act_cfg=self.act_cfg),
|
| 43 |
+
ConvModule(
|
| 44 |
+
in_channels=mla_channels,
|
| 45 |
+
out_channels=mla_channels,
|
| 46 |
+
kernel_size=3,
|
| 47 |
+
padding=1,
|
| 48 |
+
norm_cfg=self.norm_cfg,
|
| 49 |
+
act_cfg=self.act_cfg),
|
| 50 |
+
Upsample(
|
| 51 |
+
scale_factor=up_scale,
|
| 52 |
+
mode='bilinear',
|
| 53 |
+
align_corners=self.align_corners)))
|
| 54 |
+
|
| 55 |
+
def forward(self, inputs):
|
| 56 |
+
inputs = self._transform_inputs(inputs)
|
| 57 |
+
outs = []
|
| 58 |
+
for x, up_conv in zip(inputs, self.up_convs):
|
| 59 |
+
outs.append(up_conv(x))
|
| 60 |
+
out = torch.cat(outs, dim=1)
|
| 61 |
+
out = self.cls_seg(out)
|
| 62 |
+
return out
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_up_head.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from mmcv.cnn import ConvModule, build_norm_layer
|
| 4 |
+
|
| 5 |
+
from mmseg.registry import MODELS
|
| 6 |
+
from ..utils import Upsample
|
| 7 |
+
from .decode_head import BaseDecodeHead
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@MODELS.register_module()
|
| 11 |
+
class SETRUPHead(BaseDecodeHead):
|
| 12 |
+
"""Naive upsampling head and Progressive upsampling head of SETR.
|
| 13 |
+
|
| 14 |
+
Naive or PUP head of `SETR <https://arxiv.org/pdf/2012.15840.pdf>`_.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
norm_layer (dict): Config dict for input normalization.
|
| 18 |
+
Default: norm_layer=dict(type='LN', eps=1e-6, requires_grad=True).
|
| 19 |
+
num_convs (int): Number of decoder convolutions. Default: 1.
|
| 20 |
+
up_scale (int): The scale factor of interpolate. Default:4.
|
| 21 |
+
kernel_size (int): The kernel size of convolution when decoding
|
| 22 |
+
feature information from backbone. Default: 3.
|
| 23 |
+
init_cfg (dict | list[dict] | None): Initialization config dict.
|
| 24 |
+
Default: dict(
|
| 25 |
+
type='Constant', val=1.0, bias=0, layer='LayerNorm').
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(self,
|
| 29 |
+
norm_layer=dict(type='LN', eps=1e-6, requires_grad=True),
|
| 30 |
+
num_convs=1,
|
| 31 |
+
up_scale=4,
|
| 32 |
+
kernel_size=3,
|
| 33 |
+
init_cfg=[
|
| 34 |
+
dict(type='Constant', val=1.0, bias=0, layer='LayerNorm'),
|
| 35 |
+
dict(
|
| 36 |
+
type='Normal',
|
| 37 |
+
std=0.01,
|
| 38 |
+
override=dict(name='conv_seg'))
|
| 39 |
+
],
|
| 40 |
+
**kwargs):
|
| 41 |
+
|
| 42 |
+
assert kernel_size in [1, 3], 'kernel_size must be 1 or 3.'
|
| 43 |
+
|
| 44 |
+
super().__init__(init_cfg=init_cfg, **kwargs)
|
| 45 |
+
|
| 46 |
+
assert isinstance(self.in_channels, int)
|
| 47 |
+
|
| 48 |
+
_, self.norm = build_norm_layer(norm_layer, self.in_channels)
|
| 49 |
+
|
| 50 |
+
self.up_convs = nn.ModuleList()
|
| 51 |
+
in_channels = self.in_channels
|
| 52 |
+
out_channels = self.channels
|
| 53 |
+
for _ in range(num_convs):
|
| 54 |
+
self.up_convs.append(
|
| 55 |
+
nn.Sequential(
|
| 56 |
+
ConvModule(
|
| 57 |
+
in_channels=in_channels,
|
| 58 |
+
out_channels=out_channels,
|
| 59 |
+
kernel_size=kernel_size,
|
| 60 |
+
stride=1,
|
| 61 |
+
padding=int(kernel_size - 1) // 2,
|
| 62 |
+
norm_cfg=self.norm_cfg,
|
| 63 |
+
act_cfg=self.act_cfg),
|
| 64 |
+
Upsample(
|
| 65 |
+
scale_factor=up_scale,
|
| 66 |
+
mode='bilinear',
|
| 67 |
+
align_corners=self.align_corners)))
|
| 68 |
+
in_channels = out_channels
|
| 69 |
+
|
| 70 |
+
def forward(self, x):
|
| 71 |
+
x = self._transform_inputs(x)
|
| 72 |
+
|
| 73 |
+
n, c, h, w = x.shape
|
| 74 |
+
x = x.reshape(n, c, h * w).transpose(2, 1).contiguous()
|
| 75 |
+
x = self.norm(x)
|
| 76 |
+
x = x.transpose(1, 2).reshape(n, c, h, w).contiguous()
|
| 77 |
+
|
| 78 |
+
for up_conv in self.up_convs:
|
| 79 |
+
x = up_conv(x)
|
| 80 |
+
out = self.cls_seg(x)
|
| 81 |
+
return out
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/stdc_head.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from mmengine.structures import PixelData
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
|
| 7 |
+
from mmseg.registry import MODELS
|
| 8 |
+
from mmseg.structures import SegDataSample
|
| 9 |
+
from mmseg.utils import SampleList
|
| 10 |
+
from .fcn_head import FCNHead
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@MODELS.register_module()
|
| 14 |
+
class STDCHead(FCNHead):
|
| 15 |
+
"""This head is the implementation of `Rethinking BiSeNet For Real-time
|
| 16 |
+
Semantic Segmentation <https://arxiv.org/abs/2104.13188>`_.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
boundary_threshold (float): The threshold of calculating boundary.
|
| 20 |
+
Default: 0.1.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, boundary_threshold=0.1, **kwargs):
|
| 24 |
+
super().__init__(**kwargs)
|
| 25 |
+
self.boundary_threshold = boundary_threshold
|
| 26 |
+
# Using register buffer to make laplacian kernel on the same
|
| 27 |
+
# device of `seg_label`.
|
| 28 |
+
self.register_buffer(
|
| 29 |
+
'laplacian_kernel',
|
| 30 |
+
torch.tensor([-1, -1, -1, -1, 8, -1, -1, -1, -1],
|
| 31 |
+
dtype=torch.float32,
|
| 32 |
+
requires_grad=False).reshape((1, 1, 3, 3)))
|
| 33 |
+
self.fusion_kernel = torch.nn.Parameter(
|
| 34 |
+
torch.tensor([[6. / 10], [3. / 10], [1. / 10]],
|
| 35 |
+
dtype=torch.float32).reshape(1, 3, 1, 1),
|
| 36 |
+
requires_grad=False)
|
| 37 |
+
|
| 38 |
+
def loss_by_feat(self, seg_logits: Tensor,
|
| 39 |
+
batch_data_samples: SampleList) -> dict:
|
| 40 |
+
"""Compute Detail Aggregation Loss."""
|
| 41 |
+
# Note: The paper claims `fusion_kernel` is a trainable 1x1 conv
|
| 42 |
+
# parameters. However, it is a constant in original repo and other
|
| 43 |
+
# codebase because it would not be added into computation graph
|
| 44 |
+
# after threshold operation.
|
| 45 |
+
seg_label = self._stack_batch_gt(batch_data_samples).to(
|
| 46 |
+
self.laplacian_kernel)
|
| 47 |
+
boundary_targets = F.conv2d(
|
| 48 |
+
seg_label, self.laplacian_kernel, padding=1)
|
| 49 |
+
boundary_targets = boundary_targets.clamp(min=0)
|
| 50 |
+
boundary_targets[boundary_targets > self.boundary_threshold] = 1
|
| 51 |
+
boundary_targets[boundary_targets <= self.boundary_threshold] = 0
|
| 52 |
+
|
| 53 |
+
boundary_targets_x2 = F.conv2d(
|
| 54 |
+
seg_label, self.laplacian_kernel, stride=2, padding=1)
|
| 55 |
+
boundary_targets_x2 = boundary_targets_x2.clamp(min=0)
|
| 56 |
+
|
| 57 |
+
boundary_targets_x4 = F.conv2d(
|
| 58 |
+
seg_label, self.laplacian_kernel, stride=4, padding=1)
|
| 59 |
+
boundary_targets_x4 = boundary_targets_x4.clamp(min=0)
|
| 60 |
+
|
| 61 |
+
boundary_targets_x4_up = F.interpolate(
|
| 62 |
+
boundary_targets_x4, boundary_targets.shape[2:], mode='nearest')
|
| 63 |
+
boundary_targets_x2_up = F.interpolate(
|
| 64 |
+
boundary_targets_x2, boundary_targets.shape[2:], mode='nearest')
|
| 65 |
+
|
| 66 |
+
boundary_targets_x2_up[
|
| 67 |
+
boundary_targets_x2_up > self.boundary_threshold] = 1
|
| 68 |
+
boundary_targets_x2_up[
|
| 69 |
+
boundary_targets_x2_up <= self.boundary_threshold] = 0
|
| 70 |
+
|
| 71 |
+
boundary_targets_x4_up[
|
| 72 |
+
boundary_targets_x4_up > self.boundary_threshold] = 1
|
| 73 |
+
boundary_targets_x4_up[
|
| 74 |
+
boundary_targets_x4_up <= self.boundary_threshold] = 0
|
| 75 |
+
|
| 76 |
+
boundary_targets_pyramids = torch.stack(
|
| 77 |
+
(boundary_targets, boundary_targets_x2_up, boundary_targets_x4_up),
|
| 78 |
+
dim=1)
|
| 79 |
+
|
| 80 |
+
boundary_targets_pyramids = boundary_targets_pyramids.squeeze(2)
|
| 81 |
+
boudary_targets_pyramid = F.conv2d(boundary_targets_pyramids,
|
| 82 |
+
self.fusion_kernel)
|
| 83 |
+
|
| 84 |
+
boudary_targets_pyramid[
|
| 85 |
+
boudary_targets_pyramid > self.boundary_threshold] = 1
|
| 86 |
+
boudary_targets_pyramid[
|
| 87 |
+
boudary_targets_pyramid <= self.boundary_threshold] = 0
|
| 88 |
+
|
| 89 |
+
seg_labels = boudary_targets_pyramid.long()
|
| 90 |
+
batch_sample_list = []
|
| 91 |
+
for label in seg_labels:
|
| 92 |
+
seg_data_sample = SegDataSample()
|
| 93 |
+
seg_data_sample.gt_sem_seg = PixelData(data=label)
|
| 94 |
+
batch_sample_list.append(seg_data_sample)
|
| 95 |
+
|
| 96 |
+
loss = super().loss_by_feat(seg_logits, batch_sample_list)
|
| 97 |
+
return loss
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/uper_head.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from mmcv.cnn import ConvModule
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import MODELS
|
| 7 |
+
from ..utils import resize
|
| 8 |
+
from .decode_head import BaseDecodeHead
|
| 9 |
+
from .psp_head import PPM
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@MODELS.register_module()
|
| 13 |
+
class UPerHead(BaseDecodeHead):
|
| 14 |
+
"""Unified Perceptual Parsing for Scene Understanding.
|
| 15 |
+
|
| 16 |
+
This head is the implementation of `UPerNet
|
| 17 |
+
<https://arxiv.org/abs/1807.10221>`_.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 21 |
+
Module applied on the last feature. Default: (1, 2, 3, 6).
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs):
|
| 25 |
+
super().__init__(input_transform='multiple_select', **kwargs)
|
| 26 |
+
# PSP Module
|
| 27 |
+
self.psp_modules = PPM(
|
| 28 |
+
pool_scales,
|
| 29 |
+
self.in_channels[-1],
|
| 30 |
+
self.channels,
|
| 31 |
+
conv_cfg=self.conv_cfg,
|
| 32 |
+
norm_cfg=self.norm_cfg,
|
| 33 |
+
act_cfg=self.act_cfg,
|
| 34 |
+
align_corners=self.align_corners)
|
| 35 |
+
self.bottleneck = ConvModule(
|
| 36 |
+
self.in_channels[-1] + len(pool_scales) * self.channels,
|
| 37 |
+
self.channels,
|
| 38 |
+
3,
|
| 39 |
+
padding=1,
|
| 40 |
+
conv_cfg=self.conv_cfg,
|
| 41 |
+
norm_cfg=self.norm_cfg,
|
| 42 |
+
act_cfg=self.act_cfg)
|
| 43 |
+
# FPN Module
|
| 44 |
+
self.lateral_convs = nn.ModuleList()
|
| 45 |
+
self.fpn_convs = nn.ModuleList()
|
| 46 |
+
for in_channels in self.in_channels[:-1]: # skip the top layer
|
| 47 |
+
l_conv = ConvModule(
|
| 48 |
+
in_channels,
|
| 49 |
+
self.channels,
|
| 50 |
+
1,
|
| 51 |
+
conv_cfg=self.conv_cfg,
|
| 52 |
+
norm_cfg=self.norm_cfg,
|
| 53 |
+
act_cfg=self.act_cfg,
|
| 54 |
+
inplace=False)
|
| 55 |
+
fpn_conv = ConvModule(
|
| 56 |
+
self.channels,
|
| 57 |
+
self.channels,
|
| 58 |
+
3,
|
| 59 |
+
padding=1,
|
| 60 |
+
conv_cfg=self.conv_cfg,
|
| 61 |
+
norm_cfg=self.norm_cfg,
|
| 62 |
+
act_cfg=self.act_cfg,
|
| 63 |
+
inplace=False)
|
| 64 |
+
self.lateral_convs.append(l_conv)
|
| 65 |
+
self.fpn_convs.append(fpn_conv)
|
| 66 |
+
|
| 67 |
+
self.fpn_bottleneck = ConvModule(
|
| 68 |
+
len(self.in_channels) * self.channels,
|
| 69 |
+
self.channels,
|
| 70 |
+
3,
|
| 71 |
+
padding=1,
|
| 72 |
+
conv_cfg=self.conv_cfg,
|
| 73 |
+
norm_cfg=self.norm_cfg,
|
| 74 |
+
act_cfg=self.act_cfg)
|
| 75 |
+
|
| 76 |
+
def psp_forward(self, inputs):
|
| 77 |
+
"""Forward function of PSP module."""
|
| 78 |
+
x = inputs[-1]
|
| 79 |
+
psp_outs = [x]
|
| 80 |
+
psp_outs.extend(self.psp_modules(x))
|
| 81 |
+
psp_outs = torch.cat(psp_outs, dim=1)
|
| 82 |
+
output = self.bottleneck(psp_outs)
|
| 83 |
+
|
| 84 |
+
return output
|
| 85 |
+
|
| 86 |
+
def _forward_feature(self, inputs):
|
| 87 |
+
"""Forward function for feature maps before classifying each pixel with
|
| 88 |
+
``self.cls_seg`` fc.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
inputs (list[Tensor]): List of multi-level img features.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
feats (Tensor): A tensor of shape (batch_size, self.channels,
|
| 95 |
+
H, W) which is feature map for last layer of decoder head.
|
| 96 |
+
"""
|
| 97 |
+
inputs = self._transform_inputs(inputs)
|
| 98 |
+
|
| 99 |
+
# build laterals
|
| 100 |
+
laterals = [
|
| 101 |
+
lateral_conv(inputs[i])
|
| 102 |
+
for i, lateral_conv in enumerate(self.lateral_convs)
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
laterals.append(self.psp_forward(inputs))
|
| 106 |
+
|
| 107 |
+
# build top-down path
|
| 108 |
+
used_backbone_levels = len(laterals)
|
| 109 |
+
for i in range(used_backbone_levels - 1, 0, -1):
|
| 110 |
+
prev_shape = laterals[i - 1].shape[2:]
|
| 111 |
+
laterals[i - 1] = laterals[i - 1] + resize(
|
| 112 |
+
laterals[i],
|
| 113 |
+
size=prev_shape,
|
| 114 |
+
mode='bilinear',
|
| 115 |
+
align_corners=self.align_corners)
|
| 116 |
+
|
| 117 |
+
# build outputs
|
| 118 |
+
fpn_outs = [
|
| 119 |
+
self.fpn_convs[i](laterals[i])
|
| 120 |
+
for i in range(used_backbone_levels - 1)
|
| 121 |
+
]
|
| 122 |
+
# append psp feature
|
| 123 |
+
fpn_outs.append(laterals[-1])
|
| 124 |
+
|
| 125 |
+
for i in range(used_backbone_levels - 1, 0, -1):
|
| 126 |
+
fpn_outs[i] = resize(
|
| 127 |
+
fpn_outs[i],
|
| 128 |
+
size=fpn_outs[0].shape[2:],
|
| 129 |
+
mode='bilinear',
|
| 130 |
+
align_corners=self.align_corners)
|
| 131 |
+
fpn_outs = torch.cat(fpn_outs, dim=1)
|
| 132 |
+
feats = self.fpn_bottleneck(fpn_outs)
|
| 133 |
+
return feats
|
| 134 |
+
|
| 135 |
+
def forward(self, inputs):
|
| 136 |
+
"""Forward function."""
|
| 137 |
+
output = self._forward_feature(inputs)
|
| 138 |
+
output = self.cls_seg(output)
|
| 139 |
+
return output
|
reconstruction/modules/InterFormer/mmseg/models/decode_heads/vpd_depth_head.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import Dict, List, Optional, Sequence, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from mmcv.cnn import build_conv_layer, build_norm_layer, build_upsample_layer
|
| 8 |
+
from mmengine.model import BaseModule
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
|
| 11 |
+
from mmseg.registry import MODELS
|
| 12 |
+
from mmseg.utils import SampleList
|
| 13 |
+
from ..utils import resize
|
| 14 |
+
from .decode_head import BaseDecodeHead
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class VPDDepthDecoder(BaseModule):
|
| 18 |
+
"""VPD Depth Decoder class.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
in_channels (int): Number of input channels.
|
| 22 |
+
out_channels (int): Number of output channels.
|
| 23 |
+
num_deconv_layers (int): Number of deconvolution layers.
|
| 24 |
+
num_deconv_filters (List[int]): List of output channels for
|
| 25 |
+
deconvolution layers.
|
| 26 |
+
init_cfg (Optional[Union[Dict, List[Dict]]], optional): Configuration
|
| 27 |
+
for weight initialization. Defaults to Normal for Conv2d and
|
| 28 |
+
ConvTranspose2d layers.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self,
|
| 32 |
+
in_channels: int,
|
| 33 |
+
out_channels: int,
|
| 34 |
+
num_deconv_layers: int,
|
| 35 |
+
num_deconv_filters: List[int],
|
| 36 |
+
init_cfg: Optional[Union[Dict, List[Dict]]] = dict(
|
| 37 |
+
type='Normal',
|
| 38 |
+
std=0.001,
|
| 39 |
+
layer=['Conv2d', 'ConvTranspose2d'])):
|
| 40 |
+
super().__init__(init_cfg=init_cfg)
|
| 41 |
+
self.in_channels = in_channels
|
| 42 |
+
|
| 43 |
+
self.deconv_layers = self._make_deconv_layer(
|
| 44 |
+
num_deconv_layers,
|
| 45 |
+
num_deconv_filters,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
conv_layers = []
|
| 49 |
+
conv_layers.append(
|
| 50 |
+
build_conv_layer(
|
| 51 |
+
dict(type='Conv2d'),
|
| 52 |
+
in_channels=num_deconv_filters[-1],
|
| 53 |
+
out_channels=out_channels,
|
| 54 |
+
kernel_size=3,
|
| 55 |
+
stride=1,
|
| 56 |
+
padding=1))
|
| 57 |
+
conv_layers.append(build_norm_layer(dict(type='BN'), out_channels)[1])
|
| 58 |
+
conv_layers.append(nn.ReLU(inplace=True))
|
| 59 |
+
self.conv_layers = nn.Sequential(*conv_layers)
|
| 60 |
+
|
| 61 |
+
self.up_sample = nn.Upsample(
|
| 62 |
+
scale_factor=2, mode='bilinear', align_corners=False)
|
| 63 |
+
|
| 64 |
+
def forward(self, x):
|
| 65 |
+
"""Forward pass through the decoder network."""
|
| 66 |
+
out = self.deconv_layers(x)
|
| 67 |
+
out = self.conv_layers(out)
|
| 68 |
+
|
| 69 |
+
out = self.up_sample(out)
|
| 70 |
+
out = self.up_sample(out)
|
| 71 |
+
|
| 72 |
+
return out
|
| 73 |
+
|
| 74 |
+
def _make_deconv_layer(self, num_layers, num_deconv_filters):
|
| 75 |
+
"""Make deconv layers."""
|
| 76 |
+
|
| 77 |
+
layers = []
|
| 78 |
+
in_channels = self.in_channels
|
| 79 |
+
for i in range(num_layers):
|
| 80 |
+
|
| 81 |
+
num_channels = num_deconv_filters[i]
|
| 82 |
+
layers.append(
|
| 83 |
+
build_upsample_layer(
|
| 84 |
+
dict(type='deconv'),
|
| 85 |
+
in_channels=in_channels,
|
| 86 |
+
out_channels=num_channels,
|
| 87 |
+
kernel_size=2,
|
| 88 |
+
stride=2,
|
| 89 |
+
padding=0,
|
| 90 |
+
output_padding=0,
|
| 91 |
+
bias=False))
|
| 92 |
+
layers.append(nn.BatchNorm2d(num_channels))
|
| 93 |
+
layers.append(nn.ReLU(inplace=True))
|
| 94 |
+
in_channels = num_channels
|
| 95 |
+
|
| 96 |
+
return nn.Sequential(*layers)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@MODELS.register_module()
|
| 100 |
+
class VPDDepthHead(BaseDecodeHead):
|
| 101 |
+
"""Depth Prediction Head for VPD.
|
| 102 |
+
|
| 103 |
+
.. _`VPD`: https://arxiv.org/abs/2303.02153
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
max_depth (float): Maximum depth value. Defaults to 10.0.
|
| 107 |
+
in_channels (Sequence[int]): Number of input channels for each
|
| 108 |
+
convolutional layer.
|
| 109 |
+
embed_dim (int): Dimension of embedding. Defaults to 192.
|
| 110 |
+
feature_dim (int): Dimension of aggregated feature. Defaults to 1536.
|
| 111 |
+
num_deconv_layers (int): Number of deconvolution layers in the
|
| 112 |
+
decoder. Defaults to 3.
|
| 113 |
+
num_deconv_filters (Sequence[int]): Number of filters for each deconv
|
| 114 |
+
layer. Defaults to (32, 32, 32).
|
| 115 |
+
fmap_border (Union[int, Sequence[int]]): Feature map border for
|
| 116 |
+
cropping. Defaults to 0.
|
| 117 |
+
align_corners (bool): Flag for align_corners in interpolation.
|
| 118 |
+
Defaults to False.
|
| 119 |
+
loss_decode (dict): Configurations for the loss function. Defaults to
|
| 120 |
+
dict(type='SiLogLoss').
|
| 121 |
+
init_cfg (dict): Initialization configurations. Defaults to
|
| 122 |
+
dict(type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']).
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
num_classes = 1
|
| 126 |
+
out_channels = 1
|
| 127 |
+
input_transform = None
|
| 128 |
+
|
| 129 |
+
def __init__(
|
| 130 |
+
self,
|
| 131 |
+
max_depth: float = 10.0,
|
| 132 |
+
in_channels: Sequence[int] = [320, 640, 1280, 1280],
|
| 133 |
+
embed_dim: int = 192,
|
| 134 |
+
feature_dim: int = 1536,
|
| 135 |
+
num_deconv_layers: int = 3,
|
| 136 |
+
num_deconv_filters: Sequence[int] = (32, 32, 32),
|
| 137 |
+
fmap_border: Union[int, Sequence[int]] = 0,
|
| 138 |
+
align_corners: bool = False,
|
| 139 |
+
loss_decode: dict = dict(type='SiLogLoss'),
|
| 140 |
+
init_cfg=dict(
|
| 141 |
+
type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']),
|
| 142 |
+
):
|
| 143 |
+
|
| 144 |
+
super(BaseDecodeHead, self).__init__(init_cfg=init_cfg)
|
| 145 |
+
|
| 146 |
+
# initialize parameters
|
| 147 |
+
self.in_channels = in_channels
|
| 148 |
+
self.max_depth = max_depth
|
| 149 |
+
self.align_corners = align_corners
|
| 150 |
+
|
| 151 |
+
# feature map border
|
| 152 |
+
if isinstance(fmap_border, int):
|
| 153 |
+
fmap_border = (fmap_border, fmap_border)
|
| 154 |
+
self.fmap_border = fmap_border
|
| 155 |
+
|
| 156 |
+
# define network layers
|
| 157 |
+
self.conv1 = nn.Sequential(
|
| 158 |
+
nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1),
|
| 159 |
+
nn.GroupNorm(16, in_channels[0]),
|
| 160 |
+
nn.ReLU(),
|
| 161 |
+
nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1),
|
| 162 |
+
)
|
| 163 |
+
self.conv2 = nn.Conv2d(
|
| 164 |
+
in_channels[1], in_channels[1], 3, stride=2, padding=1)
|
| 165 |
+
|
| 166 |
+
self.conv_aggregation = nn.Sequential(
|
| 167 |
+
nn.Conv2d(sum(in_channels), feature_dim, 1),
|
| 168 |
+
nn.GroupNorm(16, feature_dim),
|
| 169 |
+
nn.ReLU(),
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
self.decoder = VPDDepthDecoder(
|
| 173 |
+
in_channels=embed_dim * 8,
|
| 174 |
+
out_channels=embed_dim,
|
| 175 |
+
num_deconv_layers=num_deconv_layers,
|
| 176 |
+
num_deconv_filters=num_deconv_filters)
|
| 177 |
+
|
| 178 |
+
self.depth_pred_layer = nn.Sequential(
|
| 179 |
+
nn.Conv2d(
|
| 180 |
+
embed_dim, embed_dim, kernel_size=3, stride=1, padding=1),
|
| 181 |
+
nn.ReLU(inplace=False),
|
| 182 |
+
nn.Conv2d(embed_dim, 1, kernel_size=3, stride=1, padding=1))
|
| 183 |
+
|
| 184 |
+
# build loss
|
| 185 |
+
if isinstance(loss_decode, dict):
|
| 186 |
+
self.loss_decode = MODELS.build(loss_decode)
|
| 187 |
+
elif isinstance(loss_decode, (list, tuple)):
|
| 188 |
+
self.loss_decode = nn.ModuleList()
|
| 189 |
+
for loss in loss_decode:
|
| 190 |
+
self.loss_decode.append(MODELS.build(loss))
|
| 191 |
+
else:
|
| 192 |
+
raise TypeError(f'loss_decode must be a dict or sequence of dict,\
|
| 193 |
+
but got {type(loss_decode)}')
|
| 194 |
+
|
| 195 |
+
def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tensor:
|
| 196 |
+
gt_depth_maps = [
|
| 197 |
+
data_sample.gt_depth_map.data for data_sample in batch_data_samples
|
| 198 |
+
]
|
| 199 |
+
return torch.stack(gt_depth_maps, dim=0)
|
| 200 |
+
|
| 201 |
+
def forward(self, x):
|
| 202 |
+
x = [
|
| 203 |
+
x[0], x[1],
|
| 204 |
+
torch.cat([x[2], F.interpolate(x[3], scale_factor=2)], dim=1)
|
| 205 |
+
]
|
| 206 |
+
x = torch.cat([self.conv1(x[0]), self.conv2(x[1]), x[2]], dim=1)
|
| 207 |
+
x = self.conv_aggregation(x)
|
| 208 |
+
|
| 209 |
+
x = x[:, :, :x.size(2) - self.fmap_border[0], :x.size(3) -
|
| 210 |
+
self.fmap_border[1]].contiguous()
|
| 211 |
+
x = self.decoder(x)
|
| 212 |
+
out = self.depth_pred_layer(x)
|
| 213 |
+
|
| 214 |
+
depth = torch.sigmoid(out) * self.max_depth
|
| 215 |
+
|
| 216 |
+
return depth
|
| 217 |
+
|
| 218 |
+
def loss_by_feat(self, pred_depth_map: Tensor,
|
| 219 |
+
batch_data_samples: SampleList) -> dict:
|
| 220 |
+
"""Compute depth estimation loss.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
pred_depth_map (Tensor): The output from decode head forward
|
| 224 |
+
function.
|
| 225 |
+
batch_data_samples (List[:obj:`SegDataSample`]): The seg
|
| 226 |
+
data samples. It usually includes information such
|
| 227 |
+
as `metainfo` and `gt_dpeth_map`.
|
| 228 |
+
|
| 229 |
+
Returns:
|
| 230 |
+
dict[str, Tensor]: a dictionary of loss components
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
gt_depth_map = self._stack_batch_gt(batch_data_samples)
|
| 234 |
+
loss = dict()
|
| 235 |
+
pred_depth_map = resize(
|
| 236 |
+
input=pred_depth_map,
|
| 237 |
+
size=gt_depth_map.shape[2:],
|
| 238 |
+
mode='bilinear',
|
| 239 |
+
align_corners=self.align_corners)
|
| 240 |
+
|
| 241 |
+
if not isinstance(self.loss_decode, nn.ModuleList):
|
| 242 |
+
losses_decode = [self.loss_decode]
|
| 243 |
+
else:
|
| 244 |
+
losses_decode = self.loss_decode
|
| 245 |
+
for loss_decode in losses_decode:
|
| 246 |
+
if loss_decode.loss_name not in loss:
|
| 247 |
+
loss[loss_decode.loss_name] = loss_decode(
|
| 248 |
+
pred_depth_map, gt_depth_map)
|
| 249 |
+
else:
|
| 250 |
+
loss[loss_decode.loss_name] += loss_decode(
|
| 251 |
+
pred_depth_map, gt_depth_map)
|
| 252 |
+
|
| 253 |
+
return loss
|
reconstruction/modules/InterFormer/mmseg/models/losses/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .accuracy import Accuracy, accuracy
|
| 3 |
+
from .boundary_loss import BoundaryLoss
|
| 4 |
+
from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy,
|
| 5 |
+
cross_entropy, mask_cross_entropy)
|
| 6 |
+
from .dice_loss import DiceLoss
|
| 7 |
+
from .focal_loss import FocalLoss
|
| 8 |
+
from .huasdorff_distance_loss import HuasdorffDisstanceLoss
|
| 9 |
+
from .lovasz_loss import LovaszLoss
|
| 10 |
+
from .ohem_cross_entropy_loss import OhemCrossEntropy
|
| 11 |
+
from .silog_loss import SiLogLoss
|
| 12 |
+
from .tversky_loss import TverskyLoss
|
| 13 |
+
from .utils import reduce_loss, weight_reduce_loss, weighted_loss
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
'accuracy', 'Accuracy', 'cross_entropy', 'binary_cross_entropy',
|
| 17 |
+
'mask_cross_entropy', 'CrossEntropyLoss', 'reduce_loss',
|
| 18 |
+
'weight_reduce_loss', 'weighted_loss', 'LovaszLoss', 'DiceLoss',
|
| 19 |
+
'FocalLoss', 'TverskyLoss', 'OhemCrossEntropy', 'BoundaryLoss',
|
| 20 |
+
'HuasdorffDisstanceLoss', 'SiLogLoss'
|
| 21 |
+
]
|
reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.01 kB). View file
|
|
|
reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (1.03 kB). View file
|
|
|
reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-310.pyc
ADDED
|
Binary file (3.59 kB). View file
|
|
|
reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-38.pyc
ADDED
|
Binary file (3.58 kB). View file
|
|
|
reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-310.pyc
ADDED
|
Binary file (2.32 kB). View file
|
|
|