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

Method __init__

semantic_sam/backbone/swin.py:92–134  ·  view source on GitHub ↗
(
        self,
        dim,
        window_size,
        num_heads,
        qkv_bias=True,
        qk_scale=None,
        attn_drop=0.0,
        proj_drop=0.0,
    )

Source from the content-addressed store, hash-verified

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):
137 """Forward function.

Callers

nothing calls this directly

Calls 1

__init__Method · 0.45

Tested by

no test coverage detected