MCPcopy Create free account
hub / github.com/geekcomputers/Python / VisionTransformerBlock

Class VisionTransformerBlock

ML/src/python/neuralforge/nn/attention.py:130–161  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

128 return self.norm(x)
129
130class VisionTransformerBlock(nn.Module):
131 def __init__(self, img_size=224, patch_size=16, in_channels=3, embed_dim=768,
132 num_heads=12, num_layers=12, num_classes=1000, dropout=0.1):
133 super().__init__()
134 self.patch_size = patch_size
135 self.num_patches = (img_size // patch_size) ** 2
136
137 self.patch_embed = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
138 self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
139 self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + 1, embed_dim))
140 self.dropout = nn.Dropout(dropout)
141
142 self.encoder = TransformerEncoder(embed_dim, num_heads, num_layers, dropout=dropout)
143 self.head = nn.Linear(embed_dim, num_classes)
144
145 nn.init.trunc_normal_(self.pos_embed, std=0.02)
146 nn.init.trunc_normal_(self.cls_token, std=0.02)
147
148 def forward(self, x):
149 B = x.shape[0]
150 x = self.patch_embed(x).flatten(2).transpose(1, 2)
151
152 cls_tokens = self.cls_token.expand(B, -1, -1)
153 x = torch.cat([cls_tokens, x], dim=1)
154 x = x + self.pos_embed
155 x = self.dropout(x)
156
157 x = self.encoder(x)
158 x = x[:, 0]
159 x = self.head(x)
160
161 return x
162
163class SelfAttention2D(nn.Module):
164 def __init__(self, in_channels):

Callers 1

VisionTransformerFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected