class PatchEmbedding(nn.Module):
"""Image-to-sequence stem of the vision transformer."""
def __init__(self, img_size=96, patch_size=16, num_hiddens=512,
num_channels=3):
super().__init__()
# A partial trailing patch would silently shrink the token grid
assert img_size % patch_size == 0, 'patches must tile the image'
self.num_patches = (img_size // patch_size) ** 2
self.conv = nn.Conv2d(num_channels, num_hiddens,
kernel_size=patch_size, stride=patch_size)
def forward(self, X): # (batch, c, h, w) -> (batch, patches, d)
return self.conv(X).flatten(2).transpose(1, 2)