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

Class WindowAttention

semantic_sam/backbone/swin_new.py:74–171  ·  view source on GitHub ↗

Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window. Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of a

Source from the content-addressed store, hash-verified

72
73
74class WindowAttention(nn.Module):
75 """Window based multi-head self attention (W-MSA) module with relative position bias.
76 It supports both of shifted and non-shifted window.
77 Args:
78 dim (int): Number of input channels.
79 window_size (tuple[int]): The height and width of the window.
80 num_heads (int): Number of attention heads.
81 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
82 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
83 attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
84 proj_drop (float, optional): Dropout ratio of output. Default: 0.0
85 """
86
87 def __init__(
88 self,
89 dim,
90 window_size,
91 num_heads,
92 qkv_bias=True,
93 qk_scale=None,
94 attn_drop=0.0,
95 proj_drop=0.0,
96 ):
97
98 super().__init__()
99 self.dim = dim
100 self.window_size = window_size # Wh, Ww
101 self.num_heads = num_heads
102 head_dim = dim // num_heads
103 self.scale = qk_scale or head_dim ** -0.5
104
105 # define a parameter table of relative position bias
106 self.relative_position_bias_table = nn.Parameter(
107 torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)
108 ) # 2*Wh-1 * 2*Ww-1, nH
109
110 # get pair-wise relative position index for each token inside the window
111 coords_h = torch.arange(self.window_size[0])
112 coords_w = torch.arange(self.window_size[1])
113 coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
114 coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
115 relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
116 relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
117 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
118 relative_coords[:, :, 1] += self.window_size[1] - 1
119 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
120 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
121 self.register_buffer("relative_position_index", relative_position_index)
122
123 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
124 self.attn_drop = nn.Dropout(attn_drop)
125 self.proj = nn.Linear(dim, dim)
126 self.proj_drop = nn.Dropout(proj_drop)
127
128 trunc_normal_(self.relative_position_bias_table, std=0.02)
129 self.softmax = nn.Softmax(dim=-1)
130
131 def forward(self, x, mask=None):

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected