r""" Patch Merging Layer. Args: input_resolution (tuple[int]): Resolution of input feature. dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
| 186 | |
| 187 | |
| 188 | class PatchMerging2D(nn.Module): |
| 189 | r""" Patch Merging Layer. |
| 190 | Args: |
| 191 | input_resolution (tuple[int]): Resolution of input feature. |
| 192 | dim (int): Number of input channels. |
| 193 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm |
| 194 | """ |
| 195 | |
| 196 | def __init__(self, dim, norm_layer=nn.LayerNorm): |
| 197 | super().__init__() |
| 198 | self.dim = dim |
| 199 | self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) |
| 200 | self.norm = norm_layer(4 * dim) |
| 201 | |
| 202 | def forward(self, x): |
| 203 | B, H, W, C = x.shape |
| 204 | |
| 205 | SHAPE_FIX = [-1, -1] |
| 206 | if (W % 2 != 0) or (H % 2 != 0): |
| 207 | print(f"Warning, x.shape {x.shape} is not match even ===========", flush=True) |
| 208 | SHAPE_FIX[0] = H // 2 |
| 209 | SHAPE_FIX[1] = W // 2 |
| 210 | |
| 211 | x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C |
| 212 | x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C |
| 213 | x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C |
| 214 | x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C |
| 215 | |
| 216 | if SHAPE_FIX[0] > 0: |
| 217 | x0 = x0[:, :SHAPE_FIX[0], :SHAPE_FIX[1], :] |
| 218 | x1 = x1[:, :SHAPE_FIX[0], :SHAPE_FIX[1], :] |
| 219 | x2 = x2[:, :SHAPE_FIX[0], :SHAPE_FIX[1], :] |
| 220 | x3 = x3[:, :SHAPE_FIX[0], :SHAPE_FIX[1], :] |
| 221 | |
| 222 | x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C |
| 223 | x = x.view(B, H // 2, W // 2, 4 * C) # B H/2*W/2 4*C |
| 224 | |
| 225 | x = self.norm(x) |
| 226 | x = self.reduction(x) |
| 227 | |
| 228 | return x |
| 229 | |
| 230 | class SS2D(nn.Module): |
| 231 | def __init__( |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…