第11章注意機構とTransformer
11.8.2. Patch Embedding11.8.2 パッチ埋め込み
To implement a vision Transformer, let’s start with patch embedding in Fig. 11.8.1. Splitting an image into patches and linearly projecting these flattened patches can be simplified as a single convolution operation, where both the kernel size and the stride size are set to the patch size.
英語のヒント
視覚のTransformerを実装するため、図11.8.1のパッチ埋め込みから始めよう。画像をパッチに分け、平らにしたパッチを線形に射影することは、カーネルの大きさとストライドの大きさをどちらもパッチの大きさに設定した、一つの畳み込みの演算として単純化できる。
class PatchEmbedding(nn.Module):
def __init__(self, img_size=96, patch_size=16, num_hiddens=512):
super().__init__()
def _make_tuple(x):
if not isinstance(x, (list, tuple)):
return (x, x)
return x
img_size, patch_size = _make_tuple(img_size), _make_tuple(patch_size)
self.num_patches = (img_size[0] // patch_size[0]) * (
img_size[1] // patch_size[1])
self.conv = nn.LazyConv2d(num_hiddens, kernel_size=patch_size,
stride=patch_size)
def forward(self, X):
# Output shape: (batch size, no. of patches, no. of channels)
return self.conv(X).flatten(2).transpose(1, 2)In the following example, taking images with height and width of
img_size as inputs, the patch embedding outputs (img_size//patch_size)**2 patches that are linearly projected to vectors of length num_hiddens.英語のヒント
次の例では、高さと幅が
img_sizeの画像を入力にとると、パッチ埋め込みは(img_size//patch_size)**2個のパッチを出力し、それらは長さnum_hiddensのベクトルに線形に射影される。img_size, patch_size, num_hiddens, batch_size = 96, 16, 512, 4
patch_emb = PatchEmbedding(img_size, patch_size, num_hiddens)
X = torch.zeros(batch_size, 3, img_size, img_size)
d2l.check_shape(patch_emb(X),
(batch_size, (img_size//patch_size)**2, num_hiddens))