mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
1.5 MiB
1.5 MiB
In [2]:
# For this notebook to run with updated APIs, we need torch 1.12+ and torchvision 0.13+
try:
import torch
import torchvision
assert int(torch.__version__.split(".")[1]) >= 12, "torch version should be 1.12+"
assert int(torchvision.__version__.split(".")[1]) >= 13, "torchvision version should be 0.13+"
print(f"torch version: {torch.__version__}")
print(f"torchvision version: {torchvision.__version__}")
except:
print(f"[INFO] torch/torchvision versions not as required, installing nightly versions.")
!pip3 install -U --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu113
import torch
import torchvision
print(f"torch version: {torch.__version__}")
print(f"torchvision version: {torchvision.__version__}")torch version: 1.12.0+cu102 torchvision version: 0.13.0+cu102
In [3]:
# Continue with regular imports
import matplotlib.pyplot as plt
import torch
import torchvision
from torch import nn
from torchvision import transforms
# Try to get torchinfo, install it if it doesn't work
try:
from torchinfo import summary
except:
print("[INFO] Couldn't find torchinfo... installing it.")
!pip install -q torchinfo
from torchinfo import summary
# Try to import the going_modular directory, download it from GitHub if it doesn't work
try:
from going_modular.going_modular import data_setup, engine
from helper_functions import download_data, set_seeds, plot_loss_curves
except:
# Get the going_modular scripts
print("[INFO] Couldn't find going_modular or helper_functions scripts... downloading them from GitHub.")
!git clone https://github.com/mrdbourke/pytorch-deep-learning
!mv pytorch-deep-learning/going_modular .
!mv pytorch-deep-learning/helper_functions.py . # get the helper_functions.py script
!rm -rf pytorch-deep-learning
from going_modular.going_modular import data_setup, engine
from helper_functions import download_data, set_seeds, plot_loss_curvesIn [4]:
device = "cuda" if torch.cuda.is_available() else "cpu"
deviceOut [4]:
'cuda'
In [5]:
# Download pizza, steak, sushi images from GitHub
image_path = download_data(source="https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip",
destination="pizza_steak_sushi")
image_pathOut [5]:
[INFO] data/pizza_steak_sushi directory exists, skipping download.
PosixPath('data/pizza_steak_sushi')In [6]:
# Setup directory paths to train and test images
train_dir = image_path / "train"
test_dir = image_path / "test"In [7]:
# Create image size (from Table 3 in the ViT paper)
IMG_SIZE = 224
# Create transform pipeline manually
manual_transforms = transforms.Compose([
transforms.Resize((IMG_SIZE, IMG_SIZE)),
transforms.ToTensor(),
])
print(f"Manually created transforms: {manual_transforms}")Manually created transforms: Compose(
Resize(size=(224, 224), interpolation=bilinear, max_size=None, antialias=None)
ToTensor()
)
In [8]:
# Set the batch size
BATCH_SIZE = 32 # this is lower than the ViT paper but it's because we're starting small
# Create data loaders
train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(
train_dir=train_dir,
test_dir=test_dir,
transform=manual_transforms, # use manually created transforms
batch_size=BATCH_SIZE
)
train_dataloader, test_dataloader, class_namesOut [8]:
(<torch.utils.data.dataloader.DataLoader at 0x7fa8cc731550>, <torch.utils.data.dataloader.DataLoader at 0x7fa8cc731520>, ['pizza', 'steak', 'sushi'])
In [9]:
# Get a batch of images
image_batch, label_batch = next(iter(train_dataloader))
# Get a single image from the batch
image, label = image_batch[0], label_batch[0]
# View the batch shapes
image.shape, labelOut [9]:
(torch.Size([3, 224, 224]), tensor(0))
In [10]:
# Plot image with matplotlib
plt.imshow(image.permute(1, 2, 0)) # rearrange image dimensions to suit matplotlib [color_channels, height, width] -> [height, width, color_channels]
plt.title(class_names[label])
plt.axis(False);In [11]:
# Create example values
height = 224 # H ("The training resolution is 224.")
width = 224 # W
color_channels = 3 # C
patch_size = 16 # P
# Calculate N (number of patches)
number_of_patches = int((height * width) / patch_size**2)
print(f"Number of patches (N) with image height (H={height}), width (W={width}) and patch size (P={patch_size}): {number_of_patches}")Number of patches (N) with image height (H=224), width (W=224) and patch size (P=16): 196
In [12]:
# Input shape
input_shape = (height, width, color_channels)
# Output shape
output_shape = (number_of_patches, patch_size**2 * color_channels)
print(f"Input shape (2D image): {input_shape}")
print(f"Output shape (flattened 2D patches): {output_shape}")Input shape (2D image): (224, 224, 3) Output shape (flattened 2D patches): (196, 768)
In [13]:
# View single image
plt.imshow(image.permute(1, 2, 0)) # adjust for matplotlib
plt.title(class_names[label])
plt.axis(False);In [14]:
# Change image shape to be compatible with matplotlib (color_channels, height, width) -> (height, width, color_channels)
image_permuted = image.permute(1, 2, 0)
# Index to plot the top row of patched pixels
patch_size = 16
plt.figure(figsize=(patch_size, patch_size))
plt.imshow(image_permuted[:patch_size, :, :]);In [15]:
# Setup hyperparameters and make sure img_size and patch_size are compatible
img_size = 224
patch_size = 16
num_patches = img_size/patch_size
assert img_size % patch_size == 0, "Image size must be divisible by patch size"
print(f"Number of patches per row: {num_patches}")
# Create a series of subplots
fig, axs = plt.subplots(nrows=1,
ncols=img_size // patch_size, # one column for each patch
figsize=(num_patches, num_patches),
sharex=True,
sharey=True)
# Iterate through number of patches in the top row
for i, patch in enumerate(range(0, img_size, patch_size)):
axs[i].imshow(image_permuted[:patch_size, patch:patch+patch_size, :]); # keep height index constant, alter the width index
axs[i].set_xlabel(i+1) # set the label
axs[i].set_xticks([])
axs[i].set_yticks([])Number of patches per row: 14.0
In [16]:
# Setup hyperparameters and make sure img_size and patch_size are compatible
img_size = 224
patch_size = 16
num_patches = img_size/patch_size
assert img_size % patch_size == 0, "Image size must be divisible by patch size"
print(f"Number of patches per row: {num_patches}\nNumber of patches per column: {num_patches}\nTotal patches: {num_patches*num_patches}")
# Create a series of subplots
fig, axs = plt.subplots(nrows=img_size // patch_size, # need int not float
ncols=img_size // patch_size,
figsize=(num_patches, num_patches),
sharex=True,
sharey=True)
# Loop through height and width of image
for i, patch_height in enumerate(range(0, img_size, patch_size)): # iterate through height
for j, patch_width in enumerate(range(0, img_size, patch_size)): # iterate through width
# Plot the permuted image patch (image_permuted -> (Height, Width, Color Channels))
axs[i, j].imshow(image_permuted[patch_height:patch_height+patch_size, # iterate through height
patch_width:patch_width+patch_size, # iterate through width
:]) # get all color channels
# Set up label information, remove the ticks for clarity and set labels to outside
axs[i, j].set_ylabel(i+1,
rotation="horizontal",
horizontalalignment="right",
verticalalignment="center")
axs[i, j].set_xlabel(j+1)
axs[i, j].set_xticks([])
axs[i, j].set_yticks([])
axs[i, j].label_outer()
# Set a super title
fig.suptitle(f"{class_names[label]} -> Patchified", fontsize=16)
plt.show()Number of patches per row: 14.0 Number of patches per column: 14.0 Total patches: 196.0
In [17]:
from torch import nn
# Set the patch size
patch_size=16
# Create the Conv2d layer with hyperparameters from the ViT paper
conv2d = nn.Conv2d(in_channels=3, # number of color channels
out_channels=768, # from Table 1: Hidden size D, this is the embedding size
kernel_size=patch_size, # could also use (patch_size, patch_size)
stride=patch_size,
padding=0)In [18]:
# View single image
plt.imshow(image.permute(1, 2, 0)) # adjust for matplotlib
plt.title(class_names[label])
plt.axis(False);In [19]:
# Pass the image through the convolutional layer
image_out_of_conv = conv2d(image.unsqueeze(0)) # add a single batch dimension (height, width, color_channels) -> (batch, height, width, color_channels)
print(image_out_of_conv.shape)torch.Size([1, 768, 14, 14])
In [20]:
# Plot random 5 convolutional feature maps
import random
random_indexes = random.sample(range(0, 758), k=5) # pick 5 numbers between 0 and the embedding size
print(f"Showing random convolutional feature maps from indexes: {random_indexes}")
# Create plot
fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(12, 12))
# Plot random image feature maps
for i, idx in enumerate(random_indexes):
image_conv_feature_map = image_out_of_conv[:, idx, :, :] # index on the output tensor of the convolutional layer
axs[i].imshow(image_conv_feature_map.squeeze().detach().numpy())
axs[i].set(xticklabels=[], yticklabels=[], xticks=[], yticks=[]);Showing random convolutional feature maps from indexes: [180, 39, 286, 72, 105]
In [21]:
# Get a single feature map in tensor form
single_feature_map = image_out_of_conv[:, 0, :, :]
single_feature_map, single_feature_map.requires_gradOut [21]:
(tensor([[[0.2642, 1.1367, 1.0221, 0.9712, 1.0950, 1.2478, 1.2884, 1.1481,
0.9640, 0.6204, 0.5996, 0.5855, 0.5560, 0.4992],
[1.1578, 1.0633, 0.9593, 1.1931, 1.3194, 1.1306, 0.7317, 0.4322,
0.6025, 0.7246, 0.7891, 0.5383, 0.4786, 0.7098],
[1.0163, 0.9368, 1.1675, 1.3373, 1.0429, 0.7497, 0.7445, 0.4270,
0.7430, 0.8750, 0.6105, 0.5147, 1.0207, 0.7852],
[1.0669, 1.0157, 1.3291, 1.0117, 0.4848, 0.6802, 0.8365, 0.7736,
0.8618, 0.9144, 0.8926, 0.9795, 0.7475, 0.7585],
[0.9371, 1.1937, 1.0068, 0.6377, 0.7283, 0.9625, 1.0372, 0.8920,
0.9372, 0.9034, 0.9683, 0.9405, 0.5958, 0.8740],
[0.9419, 0.8599, 0.5429, 0.6954, 1.0202, 0.9093, 1.0003, 0.7619,
0.8472, 0.8062, 0.6418, 0.7741, 0.5791, 0.9816],
[0.7965, 0.7202, 0.6424, 0.9137, 0.8264, 1.0243, 1.0920, 0.9548,
0.9166, 0.7937, 0.4675, 0.5346, 0.7774, 1.1001],
[0.3298, 0.4832, 0.5324, 0.7486, 0.8303, 0.8101, 0.9969, 0.9931,
1.0058, 0.6002, 0.6643, 0.7254, 0.8453, 1.1323],
[0.5384, 0.4798, 0.6725, 0.8014, 0.7044, 0.7988, 0.8185, 0.8911,
0.9720, 0.8939, 0.6234, 0.5674, 0.5775, 1.0011],
[0.6199, 0.6465, 0.6503, 0.6215, 0.8154, 0.7950, 0.8647, 0.9872,
0.8513, 0.8833, 0.5799, 0.5914, 0.6936, 1.0554],
[0.5140, 0.6462, 0.6982, 0.7445, 0.7394, 0.8124, 0.7462, 0.9183,
0.7471, 0.9436, 0.7147, 0.6396, 0.5795, 1.0201],
[0.5467, 0.7408, 0.6854, 0.6624, 0.7465, 0.5077, 0.7633, 0.8709,
1.0026, 0.7276, 0.7847, 0.5811, 0.5521, 1.0318],
[0.8041, 0.8868, 0.5559, 0.5889, 0.7236, 0.6976, 0.7940, 0.9365,
0.9110, 0.8182, 0.7013, 0.4890, 0.8364, 1.0031],
[0.1976, 1.0262, 1.1979, 0.9982, 0.9644, 0.8868, 0.9556, 1.0204,
1.0060, 0.9586, 0.9351, 0.8819, 0.9290, 0.9289]]],
grad_fn=<SliceBackward0>),
True)In [22]:
# Current tensor shape
print(f"Current tensor shape: {image_out_of_conv.shape} -> [batch, embedding_dim, feature_map_height, feature_map_width]")Current tensor shape: torch.Size([1, 768, 14, 14]) -> [batch, embedding_dim, feature_map_height, feature_map_width]
In [23]:
# Create flatten layer
flatten = nn.Flatten(start_dim=2, # flatten feature_map_height (dimension 2)
end_dim=3) # flatten feature_map_width (dimension 3)In [24]:
# 1. View single image
plt.imshow(image.permute(1, 2, 0)) # adjust for matplotlib
plt.title(class_names[label])
plt.axis(False);
print(f"Original image shape: {image.shape}")
# 2. Turn image into feature maps
image_out_of_conv = conv2d(image.unsqueeze(0)) # add batch dimension to avoid shape errors
print(f"Image feature map shape: {image_out_of_conv.shape}")
# 3. Flatten the feature maps
image_out_of_conv_flattened = flatten(image_out_of_conv)
print(f"Flattened image feature map shape: {image_out_of_conv_flattened.shape}")Original image shape: torch.Size([3, 224, 224]) Image feature map shape: torch.Size([1, 768, 14, 14]) Flattened image feature map shape: torch.Size([1, 768, 196])
In [25]:
# Get flattened image patch embeddings in right shape
image_out_of_conv_flattened_reshaped = image_out_of_conv_flattened.permute(0, 2, 1) # [batch_size, P^2•C, N] -> [batch_size, N, P^2•C]
print(f"Patch embedding sequence shape: {image_out_of_conv_flattened_reshaped.shape} -> [batch_size, num_patches, embedding_size]")Patch embedding sequence shape: torch.Size([1, 196, 768]) -> [batch_size, num_patches, embedding_size]
In [26]:
# Get a single flattened feature map
single_flattened_feature_map = image_out_of_conv_flattened_reshaped[:, :, 0]
# Plot the flattened feature map visually
plt.figure(figsize=(22, 22))
plt.imshow(single_flattened_feature_map.detach().numpy())
plt.title(f"Flattened feature map shape: {single_flattened_feature_map.shape}")
plt.axis(False);In [27]:
# See the flattened feature map as a tensor
single_flattened_feature_map, single_flattened_feature_map.requires_grad, single_flattened_feature_map.shapeOut [27]:
(tensor([[0.2642, 1.1367, 1.0221, 0.9712, 1.0950, 1.2478, 1.2884, 1.1481, 0.9640,
0.6204, 0.5996, 0.5855, 0.5560, 0.4992, 1.1578, 1.0633, 0.9593, 1.1931,
1.3194, 1.1306, 0.7317, 0.4322, 0.6025, 0.7246, 0.7891, 0.5383, 0.4786,
0.7098, 1.0163, 0.9368, 1.1675, 1.3373, 1.0429, 0.7497, 0.7445, 0.4270,
0.7430, 0.8750, 0.6105, 0.5147, 1.0207, 0.7852, 1.0669, 1.0157, 1.3291,
1.0117, 0.4848, 0.6802, 0.8365, 0.7736, 0.8618, 0.9144, 0.8926, 0.9795,
0.7475, 0.7585, 0.9371, 1.1937, 1.0068, 0.6377, 0.7283, 0.9625, 1.0372,
0.8920, 0.9372, 0.9034, 0.9683, 0.9405, 0.5958, 0.8740, 0.9419, 0.8599,
0.5429, 0.6954, 1.0202, 0.9093, 1.0003, 0.7619, 0.8472, 0.8062, 0.6418,
0.7741, 0.5791, 0.9816, 0.7965, 0.7202, 0.6424, 0.9137, 0.8264, 1.0243,
1.0920, 0.9548, 0.9166, 0.7937, 0.4675, 0.5346, 0.7774, 1.1001, 0.3298,
0.4832, 0.5324, 0.7486, 0.8303, 0.8101, 0.9969, 0.9931, 1.0058, 0.6002,
0.6643, 0.7254, 0.8453, 1.1323, 0.5384, 0.4798, 0.6725, 0.8014, 0.7044,
0.7988, 0.8185, 0.8911, 0.9720, 0.8939, 0.6234, 0.5674, 0.5775, 1.0011,
0.6199, 0.6465, 0.6503, 0.6215, 0.8154, 0.7950, 0.8647, 0.9872, 0.8513,
0.8833, 0.5799, 0.5914, 0.6936, 1.0554, 0.5140, 0.6462, 0.6982, 0.7445,
0.7394, 0.8124, 0.7462, 0.9183, 0.7471, 0.9436, 0.7147, 0.6396, 0.5795,
1.0201, 0.5467, 0.7408, 0.6854, 0.6624, 0.7465, 0.5077, 0.7633, 0.8709,
1.0026, 0.7276, 0.7847, 0.5811, 0.5521, 1.0318, 0.8041, 0.8868, 0.5559,
0.5889, 0.7236, 0.6976, 0.7940, 0.9365, 0.9110, 0.8182, 0.7013, 0.4890,
0.8364, 1.0031, 0.1976, 1.0262, 1.1979, 0.9982, 0.9644, 0.8868, 0.9556,
1.0204, 1.0060, 0.9586, 0.9351, 0.8819, 0.9290, 0.9289]],
grad_fn=<SelectBackward0>),
True,
torch.Size([1, 196]))In [28]:
# 1. Create a class which subclasses nn.Module
class PatchEmbedding(nn.Module):
"""Turns a 2D input image into a 1D sequence learnable embedding vector.
Args:
in_channels (int): Number of color channels for the input images. Defaults to 3.
patch_size (int): Size of patches to convert input image into. Defaults to 16.
embedding_dim (int): Size of embedding to turn image into. Defaults to 768.
"""
# 2. Initialize the class with appropriate variables
def __init__(self,
in_channels:int=3,
patch_size:int=16,
embedding_dim:int=768):
super().__init__()
# 3. Create a layer to turn an image into patches
self.patcher = nn.Conv2d(in_channels=in_channels,
out_channels=embedding_dim,
kernel_size=patch_size,
stride=patch_size,
padding=0)
# 4. Create a layer to flatten the patch feature maps into a single dimension
self.flatten = nn.Flatten(start_dim=2, # only flatten the feature map dimensions into a single vector
end_dim=3)
# 5. Define the forward method
def forward(self, x):
# Create assertion to check that inputs are the correct shape
image_resolution = x.shape[-1]
assert image_resolution % patch_size == 0, f"Input image size must be divisble by patch size, image shape: {image_resolution}, patch size: {patch_size}"
# Perform the forward pass
x_patched = self.patcher(x)
x_flattened = self.flatten(x_patched)
# 6. Make sure the output shape has the right order
return x_flattened.permute(0, 2, 1) # adjust so the embedding is on the final dimension [batch_size, P^2•C, N] -> [batch_size, N, P^2•C]In [29]:
set_seeds()
# Create an instance of patch embedding layer
patchify = PatchEmbedding(in_channels=3,
patch_size=16,
embedding_dim=768)
# Pass a single image through
print(f"Input image shape: {image.unsqueeze(0).shape}")
patch_embedded_image = patchify(image.unsqueeze(0)) # add an extra batch dimension on the 0th index, otherwise will error
print(f"Output patch embedding shape: {patch_embedded_image.shape}")Input image shape: torch.Size([1, 3, 224, 224]) Output patch embedding shape: torch.Size([1, 196, 768])
In [30]:
# Create random input sizes
random_input_image = (1, 3, 224, 224)
random_input_image_error = (1, 3, 250, 250) # will error because image size is incompatible with patch_size
# Get a summary of the input and outputs of PatchEmbedding
summary(PatchEmbedding(),
input_size=random_input_image, # try swapping this for "random_input_image_error"
col_names=["input_size", "output_size", "num_params", "trainable"],
col_width=20,
row_settings=["var_names"])Out [30]:
======================================================================================================================== Layer (type (var_name)) Input Shape Output Shape Param # Trainable ======================================================================================================================== PatchEmbedding (PatchEmbedding) [1, 3, 224, 224] [1, 196, 768] -- True ├─Conv2d (patcher) [1, 3, 224, 224] [1, 768, 14, 14] 590,592 True ├─Flatten (flatten) [1, 768, 14, 14] [1, 768, 196] -- -- ======================================================================================================================== Total params: 590,592 Trainable params: 590,592 Non-trainable params: 0 Total mult-adds (M): 115.76 ======================================================================================================================== Input size (MB): 0.60 Forward/backward pass size (MB): 1.20 Params size (MB): 2.36 Estimated Total Size (MB): 4.17 ========================================================================================================================
In [31]:
# View the patch embedding and patch embedding shape
print(patch_embedded_image)
print(f"Patch embedding shape: {patch_embedded_image.shape} -> [batch_size, number_of_patches, embedding_dimension]")tensor([[[-0.4923, 0.0265, -0.0909, ..., 0.1478, -0.0986, 0.2243],
[-0.9849, 0.3805, -0.3638, ..., 0.6115, -0.0805, 0.2097],
[-0.6015, 0.1235, -0.2506, ..., 0.6307, -0.4673, 0.2756],
...,
[-0.6668, 0.1713, -0.1711, ..., 0.4699, -0.2881, 0.2599],
[-0.6983, 0.1949, -0.1884, ..., 0.5152, -0.3126, 0.2151],
[-0.6889, 0.1862, -0.1444, ..., 0.5019, -0.3564, 0.2378]]],
grad_fn=<PermuteBackward0>)
Patch embedding shape: torch.Size([1, 196, 768]) -> [batch_size, number_of_patches, embedding_dimension]
In [32]:
# Get the batch size and embedding dimension
batch_size = patch_embedded_image.shape[0]
embedding_dimension = patch_embedded_image.shape[-1]
# Create the class token embedding as a learnable parameter that shares the same size as the embedding dimension (D)
class_token = nn.Parameter(torch.ones(batch_size, 1, embedding_dimension), # [batch_size, number_of_patches, embedding_dimension]
requires_grad=True) # make sure the embedding is learnable
# Show the first 10 examples of the class_token
print(class_token[:, :, :10])
# Print the class_token shape
print(f"Class token shape: {class_token.shape} -> [batch_size, number_of_tokens, embedding_dimension]")tensor([[[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]], grad_fn=<SliceBackward0>) Class token shape: torch.Size([1, 1, 768]) -> [batch_size, number_of_tokens, embedding_dimension]
In [33]:
# Add the class token embedding to the front of the patch embedding
patch_embedded_image_with_class_embedding = torch.cat((class_token, patch_embedded_image),
dim=1) # concat on first dimension
# Print the sequence of patch embeddings with the prepended class token embedding
print(patch_embedded_image_with_class_embedding)
print(f"Sequence of patch embeddings with class token prepended shape: {patch_embedded_image_with_class_embedding.shape} -> [batch_size, number_of_patches, embedding_dimension]")tensor([[[ 1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],
[-0.4923, 0.0265, -0.0909, ..., 0.1478, -0.0986, 0.2243],
[-0.9849, 0.3805, -0.3638, ..., 0.6115, -0.0805, 0.2097],
...,
[-0.6668, 0.1713, -0.1711, ..., 0.4699, -0.2881, 0.2599],
[-0.6983, 0.1949, -0.1884, ..., 0.5152, -0.3126, 0.2151],
[-0.6889, 0.1862, -0.1444, ..., 0.5019, -0.3564, 0.2378]]],
grad_fn=<CatBackward0>)
Sequence of patch embeddings with class token prepended shape: torch.Size([1, 197, 768]) -> [batch_size, number_of_patches, embedding_dimension]
In [34]:
# View the sequence of patch embeddings with the prepended class embedding
patch_embedded_image_with_class_embedding, patch_embedded_image_with_class_embedding.shapeOut [34]:
(tensor([[[ 1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],
[-0.4923, 0.0265, -0.0909, ..., 0.1478, -0.0986, 0.2243],
[-0.9849, 0.3805, -0.3638, ..., 0.6115, -0.0805, 0.2097],
...,
[-0.6668, 0.1713, -0.1711, ..., 0.4699, -0.2881, 0.2599],
[-0.6983, 0.1949, -0.1884, ..., 0.5152, -0.3126, 0.2151],
[-0.6889, 0.1862, -0.1444, ..., 0.5019, -0.3564, 0.2378]]],
grad_fn=<CatBackward0>),
torch.Size([1, 197, 768]))In [35]:
# Calculate N (number of patches)
number_of_patches = int((height * width) / patch_size**2)
# Get embedding dimension
embedding_dimension = patch_embedded_image_with_class_embedding.shape[2]
# Create the learnable 1D position embedding
position_embedding = nn.Parameter(torch.ones(1,
number_of_patches+1,
embedding_dimension),
requires_grad=True) # make sure it's learnable
# Show the first 10 sequences and 10 position embedding values and check the shape of the position embedding
print(position_embedding[:, :10, :10])
print(f"Position embeddding shape: {position_embedding.shape} -> [batch_size, number_of_patches, embedding_dimension]")tensor([[[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]], grad_fn=<SliceBackward0>)
Position embeddding shape: torch.Size([1, 197, 768]) -> [batch_size, number_of_patches, embedding_dimension]
In [36]:
# Add the position embedding to the patch and class token embedding
patch_and_position_embedding = patch_embedded_image_with_class_embedding + position_embedding
print(patch_and_position_embedding)
print(f"Patch embeddings, class token prepended and positional embeddings added shape: {patch_and_position_embedding.shape} -> [batch_size, number_of_patches, embedding_dimension]")tensor([[[2.0000, 2.0000, 2.0000, ..., 2.0000, 2.0000, 2.0000],
[0.5077, 1.0265, 0.9091, ..., 1.1478, 0.9014, 1.2243],
[0.0151, 1.3805, 0.6362, ..., 1.6115, 0.9195, 1.2097],
...,
[0.3332, 1.1713, 0.8289, ..., 1.4699, 0.7119, 1.2599],
[0.3017, 1.1949, 0.8116, ..., 1.5152, 0.6874, 1.2151],
[0.3111, 1.1862, 0.8556, ..., 1.5019, 0.6436, 1.2378]]],
grad_fn=<AddBackward0>)
Patch embeddings, class token prepended and positional embeddings added shape: torch.Size([1, 197, 768]) -> [batch_size, number_of_patches, embedding_dimension]
In [37]:
set_seeds()
# 1. Set patch size
patch_size = 16
# 2. Print shape of original image tensor and get the image dimensions
print(f"Image tensor shape: {image.shape}")
height, width = image.shape[1], image.shape[2]
# 3. Get image tensor and add batch dimension
x = image.unsqueeze(0)
print(f"Input image with batch dimension shape: {x.shape}")
# 4. Create patch embedding layer
patch_embedding_layer = PatchEmbedding(in_channels=3,
patch_size=patch_size,
embedding_dim=768)
# 5. Pass image through patch embedding layer
patch_embedding = patch_embedding_layer(x)
print(f"Patching embedding shape: {patch_embedding.shape}")
# 6. Create class token embedding
batch_size = patch_embedding.shape[0]
embedding_dimension = patch_embedding.shape[-1]
class_token = nn.Parameter(torch.ones(batch_size, 1, embedding_dimension),
requires_grad=True) # make sure it's learnable
print(f"Class token embedding shape: {class_token.shape}")
# 7. Prepend class token embedding to patch embedding
patch_embedding_class_token = torch.cat((class_token, patch_embedding), dim=1)
print(f"Patch embedding with class token shape: {patch_embedding_class_token.shape}")
# 8. Create position embedding
number_of_patches = int((height * width) / patch_size**2)
position_embedding = nn.Parameter(torch.ones(1, number_of_patches+1, embedding_dimension),
requires_grad=True) # make sure it's learnable
# 9. Add position embedding to patch embedding with class token
patch_and_position_embedding = patch_embedding_class_token + position_embedding
print(f"Patch and position embedding shape: {patch_and_position_embedding.shape}")Image tensor shape: torch.Size([3, 224, 224]) Input image with batch dimension shape: torch.Size([1, 3, 224, 224]) Patching embedding shape: torch.Size([1, 196, 768]) Class token embedding shape: torch.Size([1, 1, 768]) Patch embedding with class token shape: torch.Size([1, 197, 768]) Patch and position embedding shape: torch.Size([1, 197, 768])
In [38]:
# 1. Create a class that inherits from nn.Module
class MultiheadSelfAttentionBlock(nn.Module):
"""Creates a multi-head self-attention block ("MSA block" for short).
"""
# 2. Initialize the class with hyperparameters from Table 1
def __init__(self,
embedding_dim:int=768, # from Table 1 for ViT-Base
num_heads:int=12, # from Table 1 for ViT-Base
attn_dropout:int=0): # doesn't look like the paper uses any dropout in MSABlocks
super().__init__()
# 3. Create the Norm layer (LN)
self.layer_norm = nn.LayerNorm(normalized_shape=embedding_dim)
# 4. Create the Multi-Head Attention (MSA) layer
self.multihead_attn = nn.MultiheadAttention(embed_dim=embedding_dim,
num_heads=num_heads,
dropout=attn_dropout,
batch_first=True) # does our batch dimension come first?
# 5. Create a forward() method to pass the data throguh the layers
def forward(self, x):
x = self.layer_norm(x)
attn_output, _ = self.multihead_attn(query=x, # query embeddings
key=x, # key embeddings
value=x, # value embeddings
need_weights=False) # do we need the weights or just the layer outputs?
return attn_outputWarning:
Output truncated. This notebook contains too many cells to display efficiently.
















