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

Class WindowAttention

semantic_sam/backbone/swin.py:79–177  ·  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

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

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected