MCPcopy Create free account
hub / github.com/UX-Decoder/Semantic-SAM / forward

Method forward

semantic_sam/backbone/swin.py:417–464  ·  view source on GitHub ↗

Forward function. Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature.

(self, x, H, W)

Source from the content-addressed store, hash-verified

415 self.downsample = None
416
417 def forward(self, x, H, W):
418 """Forward function.
419 Args:
420 x: Input feature, tensor size (B, H*W, C).
421 H, W: Spatial resolution of the input feature.
422 """
423
424 # calculate attention mask for SW-MSA
425 Hp = int(np.ceil(H / self.window_size)) * self.window_size
426 Wp = int(np.ceil(W / self.window_size)) * self.window_size
427 img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
428 h_slices = (
429 slice(0, -self.window_size),
430 slice(-self.window_size, -self.shift_size),
431 slice(-self.shift_size, None),
432 )
433 w_slices = (
434 slice(0, -self.window_size),
435 slice(-self.window_size, -self.shift_size),
436 slice(-self.shift_size, None),
437 )
438 cnt = 0
439 for h in h_slices:
440 for w in w_slices:
441 img_mask[:, h, w, :] = cnt
442 cnt += 1
443
444 mask_windows = window_partition(
445 img_mask, self.window_size
446 ) # nW, window_size, window_size, 1
447 mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
448 attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
449 attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
450 attn_mask == 0, float(0.0)
451 ).type(x.dtype)
452
453 for blk in self.blocks:
454 blk.H, blk.W = H, W
455 if self.use_checkpoint:
456 x = checkpoint.checkpoint(blk, x, attn_mask)
457 else:
458 x = blk(x, attn_mask)
459 if self.downsample is not None:
460 x_down = self.downsample(x, H, W)
461 Wh, Ww = (H + 1) // 2, (W + 1) // 2
462 return x, H, W, x_down, Wh, Ww
463 else:
464 return x, H, W, x, H, W
465
466
467class PatchEmbed(nn.Module):

Callers

nothing calls this directly

Calls 1

window_partitionFunction · 0.70

Tested by

no test coverage detected