Skip to content
Snippets Groups Projects
Commit 2c8483f3 authored by Sucio's avatar Sucio
Browse files

Create TD3_Vision_Transformer_rendu.ipynb

parent 98bb0c4f
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# TD3: Vision Transformer (ViT)
In this TD, you must modify this notebook to complete the code (**# TO DO comments**) and complete the **proposed experiments**. To do this,
1. Fork this repository
2. Clone your forked repository on your local computer
3. Add your code and answer the questions
4. Commit and push regularly
**The last commit is due on Sunday, 14th January 2024**. Later commits will not be taken into account.
As the computation is heavy, particularly during training, we encourage you to use a GPU. If your laptob is not equiped, you may use one of these remote jupyter servers, where you can select the execution on GPU :
1) [jupyter.mi90.ec-lyon.fr](https://jupyter.mi90.ec-lyon.fr/)
This server is accessible within the campus network. If outside, you need to use a VPN. Before executing the notebook, select the kernel "Python PyTorch" to run it on GPU and have access to PyTorch module.
2) [Google Colaboratory](https://colab.research.google.com/)
Before executing the notebook, select the execution on GPU : "Exécution" Menu -> "Modifier le type d'exécution" and select "T4 GPU".
%% Cell type:markdown id: tags:
### Goal of the TD
Transformers have been introduced by [Vaswani et al. in 2017](https://arxiv.org/abs/1706.03762) in the context of NLP (Natural Language Processing), and particulary for Machine Translation.
Its great success has led to its adaptation to various applications, including image classification. In this trend, [Dosovitskiy et al. in 2020](https://arxiv.org/abs/2010.11929) have proposed Vision Transformers (ViT) that we will study and implement from scratch in this TD.
The principle is illustrated in the following picture from this paper.
![Vision Tranformers](./figures/vit.png "Vision Transformers")
First, an input image is “cut” into sub-images equally sized.
Each such sub-image goes through a linear embedding. From then, each sub-image becomes a one-dimensional vector.
A positional embedding is then added to these vectors (tokens). The positional embedding allows the network to know where each sub-image is positioned originally in the image. Without this information, the network would not be able to know where each such image would be placed, leading to potentially wrong predictions.
These tokens are then passed, together with a special classification token, to the transformer encoders blocks, were each is composed of : A Layer Normalization (LN), followed by a Multi-head Self Attention (MSA) and a residual connection. Then a second LN, a Multi-Layer Perceptron (MLP), and again a residual connection. These blocks are connected back-to-back.
Finally, a classification MLP head is used for the final classification only on the special classification token, which by the end of this process has global information about the picture.
%% Cell type:markdown id: tags:
### Implementation of the ViT model
%% Cell type:markdown id: tags:
First, we import the required modules.
%% Cell type:code id: tags:
``` python
# Import modules
import numpy as np
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
from torch.optim import Adam
from torch.utils.data import DataLoader
from torchvision.datasets.mnist import MNIST
from torchvision.transforms import ToTensor
```
%% Cell type:markdown id: tags:
For this first experiment, we will use the MNIST dataset that contains 28x28 binary pixels images of hand-written digits ([0–9]).
%% Cell type:code id: tags:
``` python
# Load data
transform = ToTensor()
train_set = MNIST(
root="datasets", train=True, download=True, transform=transform
)
test_set = MNIST(
root="datasets", train=False, download=True, transform=transform
)
train_loader = DataLoader(train_set, shuffle=True, batch_size=128)
test_loader = DataLoader(test_set, shuffle=False, batch_size=128)
```
%% Cell type:code id: tags:
``` python
import matplotlib.pyplot as plt
import random
from torchvision.transforms import ToPILImage
to_pil = ToPILImage()
random_index = random.randint(0, len(train_set) - 1)
image, label = train_set[random_index]
image_pil = to_pil(image)
plt.imshow(image_pil, cmap='gray')
plt.title(f"Classe : {label}")
plt.axis('off')
plt.show()
```
%% Output
%% Cell type:markdown id: tags:
### "Patchification"
The transformer encoder was originally developed with sequence data in mind, such as English sentences. However, as an image is not a sequence, we need to “sequencify” an image. To do this, we break it into multiple sub-images and map each sub-image to a vector.
We do so by simply reshaping our input, which has size (N, C, H, W), where N is the batch size, C the number of channels and (H,W) the image dimension. In the case of MNIST, dimensions are (N, 1, 28, 28). The target dimension is (N, #Patches, Patch dimensionality), where the dimensionality of a patch is adjusted accordingly.
In this example, we break each (1, 28, 28) into 7x7 patches (hence, each of size 4x4). That is, we are going to obtain 7x7=49 sub-images out of a single image.
Thus, we reshape input (N, 1, 28, 28) to (N, PxP, C x H/P x W/P) = (N, 49, 16)
Notice that, while each patch is a picture of size 1x4x4, we flatten it to a 16-dimensional vector. Also, in this case, we only had a single color channel. If we had multiple color channels, those would also have been flattened into the vector.
%% Cell type:code id: tags:
``` python
def patchify(images, n_patches):
n, c, h, w = images.shape
assert h == w, "Patchify method is implemented for square images only"
patches = torch.zeros(n, n_patches**2, h * w * c // n_patches**2)
patch_size = h // n_patches
for idx, image in enumerate(images):
for i in range(n_patches):
for j in range(n_patches):
patch = image[
:,
i * patch_size : (i + 1) * patch_size,
j * patch_size : (j + 1) * patch_size,
]
patches[idx, i * n_patches + j] = patch.flatten()
return patches
```
%% Cell type:code id: tags:
``` python
def display_patches(patches, n_patches, image_size):
fig, axes = plt.subplots(n_patches, n_patches, figsize=(8, 8))
for i in range(n_patches):
for j in range(n_patches):
ax = axes[i, j]
patch = patches[i * n_patches + j].reshape(image_size)
ax.imshow(patch[0], cmap="gray") # Utiliser la composante 0 pour niveaux de gris
ax.axis("off")
plt.show()
n_patches = 4
image_plat = image.unsqueeze(0)
patches = patchify(image_plat, n_patches)
# Affichez les patches
display_patches(patches[0], n_patches, (1, 7, 7))
```
%% Output
%% Cell type:markdown id: tags:
### Linear embedding
Now that we have our flattened patches, we can map each of them through a Linear mapping. While each patch was a 4x4=16 dimensional vector, the linear mapping can map to any arbitrary vector size. Thus, we will use for this a parameter `hidden_d` for "hidden dimension".
In this example, we will use a hidden dimension of 8, but in principle, any number can be put here. We will thus be mapping each 16-dimensional patch to an 8-dimensional patch.
%% Cell type:code id: tags:
``` python
def features_embedding(patch,applatisseur,class_embaded):
embedded_patches = applatisseur(flattened_patches)
return(torch.cat((class_embaded, embedded_patches), dim=0))
```
%% Cell type:code id: tags:
``` python
hidden_d=8
batch_size=patches.shape[1]
flattened_patches = patches.view(batch_size, -1)
linear_layer = nn.Linear(flattened_patches.size(1), hidden_d)
classe_embedded = torch.rand((1,hidden_d))
features_emb=features_embedding(patches,linear_layer,classe_embedded)
print(features_emb)
```
%% Output
tensor([[ 0.0886, 0.1783, 0.7162, 0.6681, 0.3244, 0.4643, 0.1293, 0.5872],
[ 0.0779, -0.0984, -0.0306, 0.0446, -0.0793, 0.0205, -0.1166, 0.0932],
[ 0.0683, -0.0921, 0.0700, -0.1282, -0.1309, 0.1637, -0.0534, 0.2885],
[ 0.0614, -0.1821, 0.1938, 0.2289, -0.5469, -0.1450, 0.2406, -0.0501],
[ 0.0779, -0.0984, -0.0306, 0.0446, -0.0793, 0.0205, -0.1166, 0.0932],
[ 0.0779, -0.0984, -0.0306, 0.0446, -0.0793, 0.0205, -0.1166, 0.0932],
[-0.2211, 0.7500, 0.1590, -0.0509, -0.2274, -0.3068, -0.3688, 0.3081],
[-0.1137, 0.3398, 0.2008, -0.2193, -0.2279, -0.2736, 0.0489, 0.1655],
[ 0.1418, 0.0633, 0.2066, 0.1069, -0.1668, -0.1283, 0.0725, 0.1086],
[ 0.0876, -0.1036, -0.0232, 0.0168, -0.0834, 0.0253, -0.1026, 0.1292],
[-0.1190, 0.6631, 0.4508, 0.1273, -0.8950, -0.2657, -0.1744, 0.1429],
[-0.0139, 1.1310, 0.6801, -0.0420, -0.8295, -0.3431, -0.3398, 0.1292],
[ 0.2009, -0.1070, 0.3390, -0.1786, -0.2455, 0.1952, -0.2296, 0.0448],
[ 0.0779, -0.0984, -0.0306, 0.0446, -0.0793, 0.0205, -0.1166, 0.0932],
[ 0.0114, 0.2627, 0.1608, 0.1347, -0.0517, -0.1514, -0.2966, 0.0293],
[ 0.0699, 0.1150, 0.0422, 0.0093, -0.1582, 0.0118, -0.2497, 0.1767],
[ 0.0779, -0.0984, -0.0306, 0.0446, -0.0793, 0.0205, -0.1166, 0.0932]],
grad_fn=<CatBackward0>)
%% Cell type:markdown id: tags:
### Positional encoding
Positional encoding allows the model to understand where each patch would be placed in the original image. While it is theoretically possible to learn such positional embeddings, previous work by [Vaswani et al. in 2017](https://arxiv.org/abs/1706.03762) suggests that we can just add sines and cosines waves.
In particular, positional encoding adds high-frequency values to the first dimensions and lower-frequency values to the latter dimensions.
In each sequence, for token i we add to its j-th coordinate the following value:
$$p_{i,j}=\left\{\begin{matrix}
sin(\frac{i}{10000^{\frac{j-1}{d_{emb-dim}}}}) \:if \:j \: is \: even\\
cos(\frac{i}{10000^{\frac{j-1}{d_{emb-dim}}}})\:if\: j \: is \: odd
\end{matrix}\right.$$
![Positional encoding](./figures/positional_encoding.png "Positional encoding").
This positional embedding is a function of the number of elements in the sequence and the dimensionality of each element. Thus, it is always a 2-dimensional tensor or “rectangle”.
Here is a simple function that, given the number of tokens and the dimensionality of each of them, outputs a matrix where each coordinate (i,j) is the value to be added to token i in dimension j.
This positional encoding is added to our model after the linear mapping and the addition of the class token.
%% Cell type:code id: tags:
``` python
def get_positional_embeddings(sequence_length, d):
result = torch.ones(sequence_length, d)
for i in range(sequence_length):
for j in range(d):
result[i][j] = (
np.sin(i / (10000 ** (j / d)))
if j % 2 == 0
else np.cos(i / (10000 ** ((j - 1) / d)))
)
return result
```
%% Cell type:code id: tags:
``` python
positional_emb=get_positional_embeddings(17,8)
print(positional_emb)
```
%% Output
tensor([[ 0.0000e+00, 1.0000e+00, 0.0000e+00, 1.0000e+00, 0.0000e+00,
1.0000e+00, 0.0000e+00, 1.0000e+00],
[ 8.4147e-01, 5.4030e-01, 9.9833e-02, 9.9500e-01, 9.9998e-03,
9.9995e-01, 1.0000e-03, 1.0000e+00],
[ 9.0930e-01, -4.1615e-01, 1.9867e-01, 9.8007e-01, 1.9999e-02,
9.9980e-01, 2.0000e-03, 1.0000e+00],
[ 1.4112e-01, -9.8999e-01, 2.9552e-01, 9.5534e-01, 2.9996e-02,
9.9955e-01, 3.0000e-03, 1.0000e+00],
[-7.5680e-01, -6.5364e-01, 3.8942e-01, 9.2106e-01, 3.9989e-02,
9.9920e-01, 4.0000e-03, 9.9999e-01],
[-9.5892e-01, 2.8366e-01, 4.7943e-01, 8.7758e-01, 4.9979e-02,
9.9875e-01, 5.0000e-03, 9.9999e-01],
[-2.7942e-01, 9.6017e-01, 5.6464e-01, 8.2534e-01, 5.9964e-02,
9.9820e-01, 6.0000e-03, 9.9998e-01],
[ 6.5699e-01, 7.5390e-01, 6.4422e-01, 7.6484e-01, 6.9943e-02,
9.9755e-01, 6.9999e-03, 9.9998e-01],
[ 9.8936e-01, -1.4550e-01, 7.1736e-01, 6.9671e-01, 7.9915e-02,
9.9680e-01, 7.9999e-03, 9.9997e-01],
[ 4.1212e-01, -9.1113e-01, 7.8333e-01, 6.2161e-01, 8.9879e-02,
9.9595e-01, 8.9999e-03, 9.9996e-01],
[-5.4402e-01, -8.3907e-01, 8.4147e-01, 5.4030e-01, 9.9833e-02,
9.9500e-01, 9.9998e-03, 9.9995e-01],
[-9.9999e-01, 4.4257e-03, 8.9121e-01, 4.5360e-01, 1.0978e-01,
9.9396e-01, 1.1000e-02, 9.9994e-01],
[-5.3657e-01, 8.4385e-01, 9.3204e-01, 3.6236e-01, 1.1971e-01,
9.9281e-01, 1.2000e-02, 9.9993e-01],
[ 4.2017e-01, 9.0745e-01, 9.6356e-01, 2.6750e-01, 1.2963e-01,
9.9156e-01, 1.3000e-02, 9.9992e-01],
[ 9.9061e-01, 1.3674e-01, 9.8545e-01, 1.6997e-01, 1.3954e-01,
9.9022e-01, 1.4000e-02, 9.9990e-01],
[ 6.5029e-01, -7.5969e-01, 9.9749e-01, 7.0737e-02, 1.4944e-01,
9.8877e-01, 1.4999e-02, 9.9989e-01],
[-2.8790e-01, -9.5766e-01, 9.9957e-01, -2.9200e-02, 1.5932e-01,
9.8723e-01, 1.5999e-02, 9.9987e-01]])
%% Cell type:code id: tags:
``` python
input_vect=features_emb+positional_emb
print(input_vect.shape)
print(input_vect)
```
%% Output
torch.Size([17, 8])
tensor([[ 0.0886, 1.1783, 0.7162, 1.6681, 0.3244, 1.4643, 0.1293, 1.5872],
[ 0.9194, 0.4419, 0.0692, 1.0396, -0.0693, 1.0204, -0.1156, 1.0932],
[ 0.9775, -0.5082, 0.2687, 0.8518, -0.1109, 1.1635, -0.0514, 1.2885],
[ 0.2025, -1.1721, 0.4894, 1.1843, -0.5169, 0.8545, 0.2436, 0.9499],
[-0.6789, -0.7520, 0.3588, 0.9656, -0.0393, 1.0197, -0.1126, 1.0932],
[-0.8810, 0.1853, 0.4488, 0.9222, -0.0293, 1.0192, -0.1116, 1.0932],
[-0.5005, 1.7102, 0.7236, 0.7744, -0.1674, 0.6914, -0.3628, 1.3081],
[ 0.5433, 1.0937, 0.8450, 0.5456, -0.1580, 0.7240, 0.0559, 1.1655],
[ 1.1312, -0.0822, 0.9239, 0.8036, -0.0868, 0.8685, 0.0805, 1.1085],
[ 0.4997, -1.0147, 0.7601, 0.6384, 0.0065, 1.0213, -0.0936, 1.1292],
[-0.6631, -0.1760, 1.2923, 0.6676, -0.7952, 0.7293, -0.1644, 1.1428],
[-1.0139, 1.1354, 1.5714, 0.4116, -0.7198, 0.6509, -0.3288, 1.1291],
[-0.3357, 0.7369, 1.2710, 0.1837, -0.1258, 1.1880, -0.2176, 1.0448],
[ 0.4981, 0.8091, 0.9329, 0.3121, 0.0504, 1.0121, -0.1036, 1.0931],
[ 1.0020, 0.3994, 1.1463, 0.3046, 0.0878, 0.8389, -0.2827, 1.0292],
[ 0.7202, -0.6447, 1.0397, 0.0801, -0.0088, 1.0006, -0.2347, 1.1766],
[-0.2100, -1.0560, 0.9689, 0.0154, 0.0800, 1.0077, -0.1006, 1.0931]],
grad_fn=<AddBackward0>)
%% Cell type:markdown id: tags:
### Multi-Head Self-Attention
The objective is now that, for a single image, each patch has to be updated based on some similarity measure with the other patches. We do so by linearly mapping each patch (that is now an 8-dimensional vector in our example) to 3 distinct vectors: q, k, and v (query, key, value).
Then, for a single patch, we are going to compute the dot product between its q vector with all of the k vectors, divide by the square root of the dimensionality of these vectors (sqrt(8)), softmax these so-called attention cues, and finally multiply each attention cue with the v vectors associated with the different k vectors and sum all up.
In this way, each patch assumes a new value that is based on its similarity (after the linear mapping to q, k, and v) with other patches. This whole procedure, however, is carried out H times on H sub-vectors of our current 8-dimensional patches, where H is the number of Heads.
Once all results are obtained, they are concatenated together. Finally, the result is passed through a linear layer (for good measure).
The intuitive idea behind attention is that it allows modeling the relationship between the inputs. What makes a ‘0’ a zero are not the individual pixel values, but how they relate to each other.
This is implemented in the MSA class:
%% Cell type:code id: tags:
``` python
class MSA(nn.Module):
def __init__(self, d, n_heads=2):
super().__init__()
self.d = d
self.n_heads = n_heads
assert d % n_heads == 0, f"Can't divide dimension {d} into {n_heads} heads"
d_head = int(d / n_heads)
self.q_mappings = nn.ModuleList(
[nn.Linear(d_head, d_head) for _ in range(self.n_heads)]
)
self.k_mappings = nn.ModuleList(
[nn.Linear(d_head, d_head) for _ in range(self.n_heads)]
)
self.v_mappings = nn.ModuleList(
[nn.Linear(d_head, d_head) for _ in range(self.n_heads)]
)
self.d_head = d_head
self.softmax = nn.Softmax(dim=-1)
def forward(self, sequences):
# Sequences has shape (N, seq_length, token_dim)
# We go into shape (N, seq_length, n_heads, token_dim / n_heads)
# And come back to (N, seq_length, item_dim) (through concatenation)
result = []
for sequence in sequences:
seq_result = []
for head in range(self.n_heads):
q_mapping = self.q_mappings[head]
k_mapping = self.k_mappings[head]
v_mapping = self.v_mappings[head]
seq = sequence[:, head * self.d_head : (head + 1) * self.d_head]
q, k, v = q_mapping(seq), k_mapping(seq), v_mapping(seq)
attention = torch.matmul(self.softmax(torch.matmul(q, k.t())/np.sqrt(int(self.d / self.n_heads))),v)
seq_result.append(attention)
result.append(torch.hstack(seq_result))
return torch.cat([torch.unsqueeze(r, dim=0) for r in result])
```
%% Cell type:markdown id: tags:
Notice that, for each head, we create distinct Q, K, and V mapping functions (square matrices of size 4x4 in our example).
$$\left\{\begin{matrix}
Q=W^Q.I
\\
K=W^K.I
\\
V=W^V.I
\\
A=K^T.Q
\\
\hat{A}=softmax(A)
\\
O=V.\hat{A}
\end{matrix}\right.$$
Since our inputs will be sequences of size (N, 50, 8), and we only use 2 heads, we will at some point have an (N, 50, 2, 4) tensor, use a nn.Linear(4, 4) module on it, and then come back, after concatenation, to an (N, 50, 8) tensor.
Also notice that using loops is not the most efficient way to compute the multi-head self-attention, but it makes the code much clearer for learning.
%% Cell type:markdown id: tags:
### Transformer Encoder Blocks
The next step is to create the transformer encoder block class.
Layer normalization (LN) is a popular block that, given an input, subtracts its mean and divides by the standard deviation. It is applied to the last dimension only. We can thus make each of our 50x8 matrices (representing a single sequence) have mean 0 and std 1. After we run our (N, 50, 8) tensor through LN, we still get the same dimensionality.
Also, We will be using residual connection that consists in adding the original input to the result of some computation. This, intuitively, allows a network to become more powerful while also preserving the set of possible functions that the model can approximate.
We will add a residual connection that will add our original (N, 50, 8) tensor to the (N, 50, 8) obtained after LN and MSA.
Next is to add a simple residual connection between what we already have and what we get after passing the current tensor through another LN and an MLP. The MLP is composed of two layers, where the hidden layer typically is four times as big (this is a parameter).
The transformer encoder block class (which will be a component of the future ViT class) is thus as follows:
%% Cell type:code id: tags:
``` python
class ViTBlock(nn.Module):
def __init__(self, hidden_d, n_heads, mlp_ratio=4):
super().__init__()
self.hidden_d = hidden_d
self.n_heads = n_heads
self.norm1 = nn.LayerNorm(hidden_d)
self.mhsa = MSA(hidden_d, n_heads)
self.norm2 = nn.LayerNorm(hidden_d)
self.mlp = nn.Sequential(
nn.Linear(hidden_d, mlp_ratio * hidden_d),
nn.GELU(),
nn.Linear(mlp_ratio * hidden_d, hidden_d),
)
def forward(self, x):
m1=x
x = self.norm1(x)
x = m1+self.mhsa(x)
m2=x
x = self.norm2(x)
x = m2+self.mlp(x)
return x
```
%% Cell type:markdown id: tags:
### ViT model
Now that the encoder block is ready, we just need to insert it in our bigger ViT model which is responsible for patchifying before the transformer blocks, and carrying out the classification after.
To help classification, we will use an additional **classification token** to the input sequence. This is a special token that we add to our model that has the role of capturing information about the other tokens. This will happen with the MSA block. When information about all other tokens will be present here, we will be able to classify the image using only this special token. The initial value of the special token (the one fed to the transformer encoder) is a parameter of the model that needs to be learned.
Thus, we will add a parameter to our model and convert our (N, 49, 8) tokens tensor to an (N, 50, 8) tensor (we add the special token to each sequence).
We could have an arbitrary number of transformer blocks. In this example, to keep it simple, I will use only 2. We also add a parameter to know how many heads does each encoder block will use.
Finally, we can extract just the classification token (first token) out of our N sequences, and use each token to get N classifications.
Since we decided that each token is an 8-dimensional vector, and since we have 10 possible digits, we can implement the classification MLP as a simple 8x10 matrix, activated with the SoftMax function.
The output of our model shoud be an (N, 10) tensor.
%% Cell type:code id: tags:
``` python
class ViT(nn.Module):
def __init__(self, chw, n_patches=7, n_blocks=2, hidden_d=8, n_heads=2, out_d=10):
# Super constructor
super().__init__()
# Attributes
self.chw = chw # ( C , H , W )
self.n_patches = n_patches
self.n_blocks = n_blocks
self.n_heads = n_heads
self.hidden_d = hidden_d
# Input and patches sizes
assert (
chw[1] % n_patches == 0
), "Input shape not entirely divisible by number of patches"
assert (
chw[2] % n_patches == 0
), "Input shape not entirely divisible by number of patches"
self.patch_size = (chw[1] / n_patches, chw[2] / n_patches)
# 1) Linear mapper
self.input_d = int(chw[0] * self.patch_size[0] * self.patch_size[1])
self.linear_mapper = nn.Linear(self.input_d, self.hidden_d)
# 2) Learnable classification token
self.class_token = nn.Parameter(torch.rand(1, self.hidden_d))
# 3) Positional embedding
self.register_buffer(
"positional_embeddings",
get_positional_embeddings(n_patches**2 + 1, hidden_d),
persistent=False,
)
# 4) Transformer encoder blocks
self.blocks = nn.ModuleList(
[ViTBlock(hidden_d, n_heads) for _ in range(n_blocks)]
)
# 5) Classification MLPk
self.mlp = nn.Sequential(nn.Linear(self.hidden_d, out_d), nn.Softmax(dim=-1))
def forward(self, images):
# Dividing images into patches
n, c, h, w = images.shape
patches = patchify(images,self.n_patches)
patches=patches.to(device)
# Running linear layer tokenization
tokens = self.linear_mapper(patches)
# Map the vector corresponding to each patch to the hidden size dimension
tokens = torch.cat((self.class_token.expand(n, 1, -1), tokens), dim=1)
# Adding classification token to the tokens
tokens = tokens + self.positional_embeddings.repeat(n, 1, 1)
# Adding positional embedding
out = tokens + self.positional_embeddings.repeat(n, 1, 1)
# Transformer Blocks
for block in self.blocks:
out = block(out)
# Getting the classification token only
out = out[:, 0, :]
# Map to output dimension, output category distribution
out = self.mlp(out)
return out
```
%% Cell type:markdown id: tags:
### ViT training
The ViT model being built, the next step is to train it on the MNIST dataset.
%% Cell type:markdown id: tags:
First, we initialize the model and the hyperparameters.
%% Cell type:code id: tags:
``` python
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(
"Using device: ",
device,
f"({torch.cuda.get_device_name(device)})" if torch.cuda.is_available() else "",
)
model = ViT(
(1, 28, 28), n_patches=7, n_blocks=2, hidden_d=8, n_heads=2, out_d=10
).to(device)
N_EPOCHS = 5
LR = 0.005
```
%% Output
Using device: cuda (Tesla T4)
%% Cell type:markdown id: tags:
Training of the ViT model:
%% Cell type:code id: tags:
``` python
from tqdm import tqdm # Importez la fonction tqdm pour la barre de progression
optimizer = Adam(model.parameters(), lr=LR)
criterion = CrossEntropyLoss()
for epoch in range(N_EPOCHS):
train_loss = 0.0
model.train()
# Utilisez tqdm pour afficher la barre de progression
for batch in tqdm(train_loader, desc=f"Epoch {epoch + 1}/{N_EPOCHS}", leave=False):
x, y = batch
x, y = x.to(device), y.to(device)
optimizer.zero_grad()
y_hat = model(x)
loss = criterion(y_hat, y)
loss.backward()
optimizer.step()
train_loss += loss.detach().cpu().item() / len(train_loader)
print(f"Epoch {epoch + 1}/{N_EPOCHS} loss: {train_loss:.2f}")
```
%% Output
Epoch 1/5 loss: 1.83
Epoch 2/5 loss: 1.78
Epoch 3/5 loss: 1.74
Epoch 4/5 loss: 1.70
Epoch 5/5 loss: 1.68
%% Cell type:markdown id: tags:
### ViT test
Finally, let's test the trained model.
%% Cell type:code id: tags:
``` python
with torch.no_grad():
correct, total = 0, 0
test_loss = 0.0
model.eval()
for batch in tqdm(test_loader, desc=f"Batch avancement ", leave=False):
x, y = batch
x, y = x.to(device), y.to(device)
y_hat = model(x)
loss = criterion(y_hat, y)
_, pred = torch.max(y_hat, 1)
correct_tensor = pred.eq(y.data.view_as(pred))
test_loss += loss.detach().cpu().item() / len(test_loader)
for i in range(len(batch)):
correct += correct_tensor[i].item()
total += 1
print(f"Test loss: {test_loss:.2f}")
print(f"Test accuracy: {correct / total * 100:.2f}%")
```
%% Output
Test loss: 1.71
Test accuracy: 77.85%
%% Cell type:code id: tags:
``` python
# track test loss
test_loss = 0.0
class_correct_NET = list(0.0 for i in range(10))
class_total_NET = list(0.0 for i in range(10))
import torch.optim as optim
criterion = nn.CrossEntropyLoss() # specify loss function
optimizer = optim.SGD(model.parameters(), lr=0.01) # specify optimizer
model.eval()
# iterate over test data
for data, target in test_loader:
# move tensors to GPU if CUDA is available
if train_on_gpu:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the batch loss
loss = criterion(output, target)
# update test loss
test_loss += loss.item() * data.size(0)
# convert output probabilities to predicted class
_, pred = torch.max(output, 1)
# compare predictions to true label
correct_tensor = pred.eq(target.data.view_as(pred))
correct = (
np.squeeze(correct_tensor.numpy())
if not train_on_gpu
else np.squeeze(correct_tensor.cpu().numpy())
)
# calculate test accuracy for each object class
for i in range(batch_size):
label = target.data[i]
class_correct_NET[label] += correct[i].item()
class_total_NET[label] += 1
# average test loss
test_loss = test_loss / len(test_loader)
print("Test Loss: {:.6f}\n".format(test_loss))
for i in range(10):
if class_total_NET[i] > 0:
print(
"Test Accuracy of %5s: %2d%% (%2d/%2d)"
% (
classes[i],
100 * class_correct_NET[i] / class_total_NET[i],
np.sum(class_correct_NET[i]),
np.sum(class_total_NET[i]),
)
)
else:
print("Test Accuracy of %5s: N/A (no training examples)" % (classes[i]))
print(
"\nTest Accuracy (Overall): %2d%% (%2d/%2d)"
% (
100.0 * np.sum(class_correct_NET) / np.sum(class_total_NET),
np.sum(class_correct_NET),
np.sum(class_total_NET),
)
)
```
%% Cell type:markdown id: tags:
## Further experiments
1. Adapt the code to apply the ViT model on CIFAR dataset.
2. Make use of a validation set to evaluate overfitting.
3. Evaluate the model with a dimension of 16 for the tokens and 4 encoder blocks.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment