MCPcopy Create free account
hub / github.com/alinlab/SelfPatch / WindowMSA

Class WindowMSA

segmentation/backbones/swin.py:20–122  ·  view source on GitHub ↗

Window based multi-head self-attention (W-MSA) module with relative position bias. Args: embed_dims (int): Number of input channels. num_heads (int): Number of attention heads. window_size (tuple[int]): The height and width of the window. qkv_bias (bool, opti

Source from the content-addressed store, hash-verified

18
19
20class WindowMSA(BaseModule):
21 """Window based multi-head self-attention (W-MSA) module with relative
22 position bias.
23
24 Args:
25 embed_dims (int): Number of input channels.
26 num_heads (int): Number of attention heads.
27 window_size (tuple[int]): The height and width of the window.
28 qkv_bias (bool, optional): If True, add a learnable bias to q, k, v.
29 Default: True.
30 qk_scale (float | None, optional): Override default qk scale of
31 head_dim ** -0.5 if set. Default: None.
32 attn_drop_rate (float, optional): Dropout ratio of attention weight.
33 Default: 0.0
34 proj_drop_rate (float, optional): Dropout ratio of output. Default: 0.
35 init_cfg (dict | None, optional): The Config for initialization.
36 Default: None.
37 """
38
39 def __init__(self,
40 embed_dims,
41 num_heads,
42 window_size,
43 qkv_bias=True,
44 qk_scale=None,
45 attn_drop_rate=0.,
46 proj_drop_rate=0.,
47 init_cfg=None):
48
49 super().__init__(init_cfg=init_cfg)
50 self.embed_dims = embed_dims
51 self.window_size = window_size # Wh, Ww
52 self.num_heads = num_heads
53 head_embed_dims = embed_dims // num_heads
54 self.scale = qk_scale or head_embed_dims**-0.5
55
56 # define a parameter table of relative position bias
57 self.relative_position_bias_table = nn.Parameter(
58 torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1),
59 num_heads)) # 2*Wh-1 * 2*Ww-1, nH
60
61 # About 2x faster than original impl
62 Wh, Ww = self.window_size
63 rel_index_coords = self.double_step_seq(2 * Ww - 1, Wh, 1, Ww)
64 rel_position_index = rel_index_coords + rel_index_coords.T
65 rel_position_index = rel_position_index.flip(1).contiguous()
66 self.register_buffer('relative_position_index', rel_position_index)
67
68 self.qkv = nn.Linear(embed_dims, embed_dims * 3, bias=qkv_bias)
69 self.attn_drop = nn.Dropout(attn_drop_rate)
70 self.proj = nn.Linear(embed_dims, embed_dims)
71 self.proj_drop = nn.Dropout(proj_drop_rate)
72
73 self.softmax = nn.Softmax(dim=-1)
74
75 def init_weights(self):
76 trunc_normal_init(self.relative_position_bias_table, std=0.02)
77

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected