A custom Vision Transformer (ViT) implemented in PyTorch and trained on the CIFAR-10 dataset for image classification.
This project explores Transformer-based architectures for computer vision, implementing the Vision Transformer approach and training it using mixed-precision training for improved computational efficiency.
The model was trained for 20 epochs on CIFAR-10 using PyTorch.
This model is a custom implementation of a Vision Transformer (ViT) designed for image classification.
Unlike traditional Convolutional Neural Networks (CNNs), which process images using convolutional operations, Vision Transformers divide an image into smaller patches, project them into embeddings, and process these embeddings using Transformer encoder blocks.
The model uses self-attention mechanisms to learn relationships between different image patches and generate representations useful for image classification.
The model was trained on CIFAR-10, a widely used benchmark dataset containing 60,000 color images across 10 different object categories.
Key Highlights:
The model can be used directly for classifying images into one of the ten CIFAR-10 categories.
The supported classes are:
Users can load the trained model weights and perform inference on compatible input images.
The model can serve as a starting point for:
This model is not intended for:
Although CIFAR-10 is a commonly used benchmark dataset, the model has several limitations.
Users should:
Install the required dependencies:
pip install torch torchvision numpy matplotlib tqdm
The model architecture must be defined before loading the trained weights.
import torch
# Import your custom Vision Transformer architecture
from model import VisionTransformer
device = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
)
# Initialize the model with the same configuration
model = VisionTransformer(
# Add your architecture parameters here
)
# Load trained weights
checkpoint = torch.load(
"model.pth",
map_location=device,
weights_only=True
)
model.load_state_dict(checkpoint)
model.to(device)
model.eval()
print("Model loaded successfully!")
import torch
from PIL import Image
from torchvision import transforms
classes = [
"airplane", "automobile", "bird", "cat", "deer",
"dog", "frog", "horse", "ship", "truck"
]
transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(
(0.4914, 0.4822, 0.4465),
(0.2470, 0.2435, 0.2616)
)
])
image = Image.open("image.jpg").convert("RGB")
image = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
outputs = model(image)
prediction = outputs.argmax(dim=1).item()
print("Predicted class:", classes[prediction])
Note: The example assumes a standard CIFAR-10 normalization scheme and a model that accepts 32 × 32 images and returns ten class logits. Adjust the architecture initialization, checkpoint loading, and preprocessing to match your actual implementation.
The model was trained using the CIFAR-10 dataset.
CIFAR-10 consists of:
Dataset Source: https://www.cs.toronto.edu/~kriz/cifar.html
The Vision Transformer was implemented and trained using PyTorch.
Training was performed for 20 epochs with a batch size of 64.
Mixed-precision training was enabled to improve computational efficiency and reduce memory consumption during training.
The CIFAR-10 dataset was loaded using Torchvision.
Preprocessing included:
| Parameter | Value |
|---|---|
| Framework | PyTorch |
| Dataset | CIFAR-10 |
| Epochs | 20 |
| Batch Size | 64 |
| Precision | Mixed Precision (AMP) |
| Task | Image Classification |
| Optimizer | Adam] |
| Loss Function | Cross Entropy Loss |
| Learning Rate | 1e-4 |
| Scheduler | [None] |
| Hardware | [Tesla T4] |
The model follows the Vision Transformer architecture.
Its main components include:
Model Architecture Summary (Torchinfo):
Complete torchinfo.summary() output here.
[=====================================================================================
Layer (type:depth-idx) Param #
=====================================================================================
vit --
├─Patch_Embedding: 1-1 16,896
│ └─Conv2d: 2-1 12,544
├─Sequential: 1-2 --
│ └─TransformerEncoderLayer: 2-2 --
│ │ └─LayerNorm: 3-1 512
│ │ └─MultiheadAttention: 3-2 263,168
│ │ └─LayerNorm: 3-3 512
│ │ └─MLP: 3-4 262,912
│ └─TransformerEncoderLayer: 2-3 --
│ │ └─LayerNorm: 3-5 512
│ │ └─MultiheadAttention: 3-6 263,168
│ │ └─LayerNorm: 3-7 512
│ │ └─MLP: 3-8 262,912
│ └─TransformerEncoderLayer: 2-4 --
│ │ └─LayerNorm: 3-9 512
│ │ └─MultiheadAttention: 3-10 263,168
│ │ └─LayerNorm: 3-11 512
│ │ └─MLP: 3-12 262,912
│ └─TransformerEncoderLayer: 2-5 --
│ │ └─LayerNorm: 3-13 512
│ │ └─MultiheadAttention: 3-14 263,168
│ │ └─LayerNorm: 3-15 512
│ │ └─MLP: 3-16 262,912
│ └─TransformerEncoderLayer: 2-6 --
│ │ └─LayerNorm: 3-17 512
│ │ └─MultiheadAttention: 3-18 263,168
│ │ └─LayerNorm: 3-19 512
│ │ └─MLP: 3-20 262,912
│ └─TransformerEncoderLayer: 2-7 --
│ │ └─LayerNorm: 3-21 512
│ │ └─MultiheadAttention: 3-22 263,168
│ │ └─LayerNorm: 3-23 512
│ │ └─MLP: 3-24 262,912
├─LayerNorm: 1-3 512
├─Linear: 1-4 2,570
=====================================================================================
Total params: 3,195,146
Trainable params: 3,195,146
Non-trainable params: 0
=====================================================================================]
| Metric | Result |
|---|---|
| Test Accuracy | 69% |
| Test Loss | 0.98 |
| Training Epochs | 20 |
Evaluation metrics should be updated with the actual results from your training and testing process.
This model is released under the MIT License.
You are free to use, modify, and distribute this project in accordance with the terms of the license.
Built with PyTorch | Computer Vision | Vision Transformers