Certainly! Below is a generalized, modular Python pipeline for training, evaluating, performing inference, generating plots, and saving model weights related to image classification using the Vision Transformer (ViT) model. This pipeline adheres strictly to PEP-8 standards, incorporates type hints using the typing module, ensures efficiency and scalability, and includes comprehensive error handling for robustness.
Overview
The pipeline is structured into the following components:
- Configuration Management: Centralizes all configurable parameters.
- Data Handling: Loads and preprocesses the dataset.
- Model Preparation: Sets up teacher and student models.
- Training and Evaluation: Handles training with and without knowledge distillation, and evaluates the models.
- Visualization: Generates and saves plots of model predictions.
- Utilities: Includes helper functions for logging and error handling.
Directory Structure
All outputs such as plots and model weights are saved in a specified output directory with organized subfolders:
output/
├── plots/
├── weights/
│ ├── base_model/
│ └── student_model/
Complete Code
import logging
import os
from pathlib import Path
from typing import Dict, Any, Optional
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from datasets import DatasetDict, load_dataset
from torch.utils.data import DataLoader
from transformers import (
AutoImageProcessor,
AutoModelForImageClassification,
TrainingArguments,
Trainer,
ViTForImageClassification,
ViTImageProcessor,
)
import evaluate
def setup_logging(output_dir: Path) -> None:
"""
Configures the logging settings.
Args:
output_dir (Path): Directory where logs will be saved.
"""
log_file = output_dir / "pipeline.log"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler()
]
)
logging.info("Logging is set up.")
def create_output_dirs(base_output: Path) -> Dict[str, Path]:
"""
Creates necessary output directories.
Args:
base_output (Path): Base directory for outputs.
Returns:
Dict[str, Path]: Dictionary of created directories.
"""
try:
plots_dir = base_output / "plots"
weights_dir = base_output / "weights"
base_model_weights_dir = weights_dir / "base_model"
student_model_weights_dir = weights_dir / "student_model"
for directory in [plots_dir, base_model_weights_dir, student_model_weights_dir]:
directory.mkdir(parents=True, exist_ok=True)
logging.info(f"Created directory: {directory}")
return {
"plots": plots_dir,
"base_model_weights": base_model_weights_dir,
"student_model_weights": student_model_weights_dir
}
except Exception as e:
logging.error(f"Failed to create output directories: {e}")
raise
def load_and_prepare_dataset(dataset_name: str, cache_dir: Path) -> DatasetDict:
"""
Loads and prepares the dataset.
Args:
dataset_name (str): Name of the dataset to load.
cache_dir (Path): Directory to cache the dataset.
Returns:
DatasetDict: Loaded dataset dictionary.
"""
try:
logging.info(f"Loading dataset: {dataset_name}")
dataset = load_dataset(dataset_name, cache_dir=str(cache_dir))
logging.info("Dataset loaded successfully.")
return dataset
except Exception as e:
logging.error(f"Failed to load dataset {dataset_name}: {e}")
raise
def prepare_label_mappings(dataset: DatasetDict) -> (Dict[int, str], Dict[str, int]):
"""
Prepares label-to-ID and ID-to-label mappings.
Args:
dataset (DatasetDict): The dataset containing labels.
Returns:
Tuple[Dict[int, str], Dict[str, int]]: ID-to-label and label-to-ID mappings.
"""
try:
labels = sorted(list(set(dataset['train']['label'])))
id2label = {i: label for i, label in enumerate(labels)}
label2id = {label: i for i, label in enumerate(labels)}
logging.info("Label mappings created.")
return id2label, label2id
except Exception as e:
logging.error(f"Failed to create label mappings: {e}")
raise
def initialize_device() -> torch.device:
"""
Initializes the computation device.
Returns:
torch.device: The device to be used for computations.
"""
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
logging.info(f"Using device: {device}")
return device
def load_teacher_model(model_name: str, device: torch.device) -> AutoModelForImageClassification:
"""
Loads the pre-trained teacher model.
Args:
model_name (str): Name or path of the pre-trained model.
device (torch.device): Device to load the model onto.
Returns:
AutoModelForImageClassification: The loaded teacher model.
"""
try:
logging.info(f"Loading teacher model: {model_name}")
teacher_model = AutoModelForImageClassification.from_pretrained(model_name).to(device)
teacher_model.eval()
logging.info("Teacher model loaded and set to evaluation mode.")
return teacher_model
except Exception as e:
logging.error(f"Failed to load teacher model {model_name}: {e}")
raise
def load_image_processor(processor_name: str) -> ViTImageProcessor:
"""
Loads the image processor.
Args:
processor_name (str): Name or path of the image processor.
Returns:
ViTImageProcessor: The loaded image processor.
"""
try:
logging.info(f"Loading image processor: {processor_name}")
processor = ViTImageProcessor.from_pretrained(processor_name)
logging.info("Image processor loaded.")
return processor
except Exception as e:
logging.error(f"Failed to load image processor {processor_name}: {e}")
raise
def plot_teacher_distributions(
id2label: Dict[int, str],
distributions: Dict[str, np.ndarray],
plots_dir: Path
) -> None:
"""
Plots teacher model's probability distributions.
Args:
id2label (Dict[int, str]): Mapping from class IDs to labels.
distributions (Dict[str, np.ndarray]): Dictionary of distributions to plot.
plots_dir (Path): Directory to save the plots.
"""
try:
plt.figure(figsize=(12, 6))
# Plot default temperature
plt.subplot(1, 2, 1)
plt.bar(id2label.keys(), distributions["temperature_no_change"], width=0.4)
plt.title("Teacher Probability Over All Classes")
plt.xlabel("Class ID")
plt.ylabel("Probability")
# Plot different temperatures
x = np.array(list(id2label.keys()))
plt.subplot(1, 2, 2)
plt.bar(x - 0.2, distributions["low_temperature"], width=0.4, label='Temperature=2')
plt.bar(x + 0.2, distributions["high_temperature"], width=0.4, label='Temperature=8')
plt.title("Teacher Probability with Varying Temperatures")
plt.xlabel("Class ID")
plt.ylabel("Probability")
plt.legend()
plt.tight_layout()
plot_path = plots_dir / "teacher_distributions.png"
plt.savefig(plot_path)
plt.close()
logging.info(f"Teacher distribution plots saved at {plot_path}")
except Exception as e:
logging.error(f"Failed to plot teacher distributions: {e}")
raise
def preprocess_example(example: Dict[str, Any], processor: ViTImageProcessor, label2id: Dict[str, int]) -> Dict[str, Any]:
"""
Preprocesses a single example from the dataset.
Args:
example (Dict[str, Any]): A single data example.
processor (ViTImageProcessor): Image processor.
label2id (Dict[str, int]): Label-to-ID mapping.
Returns:
Dict[str, Any]: The preprocessed example.
"""
try:
# Convert image to RGB
example['image'] = example['image'].convert('RGB')
# Process image
inputs = processor(example['image'], return_tensors='pt')
example['pixel_values'] = inputs['pixel_values'].squeeze()
# Map label to ID
example['label'] = label2id[example['label']]
return example
except Exception as e:
logging.error(f"Failed to preprocess example: {e}")
raise
def prepare_datasets(
dataset: DatasetDict,
processor: ViTImageProcessor,
label2id: Dict[str, int]
) -> DatasetDict:
"""
Applies transformations and splits the dataset into train, validation, and test sets.
Args:
dataset (DatasetDict): The original dataset.
processor (ViTImageProcessor): Image processor.
label2id (Dict[str, int]): Label-to-ID mapping.
Returns:
DatasetDict: Transformed and split dataset.
"""
try:
logging.info("Applying transformations to the dataset.")
transformed_dataset = dataset.map(
lambda x: preprocess_example(x, processor, label2id),
remove_columns=dataset["train"].column_names,
num_proc=4 # Adjust based on your system
)
transformed_dataset.set_format("torch", columns=["pixel_values", "label"])
logging.info("Dataset transformation complete.")
# Split the dataset
logging.info("Splitting dataset into train, validation, and test sets.")
train_test = transformed_dataset['train'].train_test_split(test_size=0.2, seed=42)
train_val = train_test['train'].train_test_split(test_size=0.125, seed=42) # 0.125 x 0.8 = 0.1
final_dataset = DatasetDict({
'train': train_val['train'],
'valid': train_val['test'],
'test': train_test['test']
})
logging.info("Dataset split complete.")
return final_dataset
except Exception as e:
logging.error(f"Failed to prepare datasets: {e}")
raise
def collate_fn(batch: list) -> Dict[str, torch.Tensor]:
"""
Collate function to merge a list of samples into a batch.
Args:
batch (list): List of samples.
Returns:
Dict[str, torch.Tensor]: Batch of pixel values and labels.
"""
try:
pixel_values = torch.stack([item['pixel_values'] for item in batch])
labels = torch.tensor([item['label'] for item in batch])
return {'pixel_values': pixel_values, 'labels': labels}
except Exception as e:
logging.error(f"Failed in collate_fn: {e}")
raise
def compute_metrics_fn(eval_pred: tuple) -> Dict[str, float]:
"""
Computes evaluation metrics.
Args:
eval_pred (tuple): Tuple of predictions and labels.
Returns:
Dict[str, float]: Computed metrics.
"""
try:
predictions, labels = eval_pred
preds = np.argmax(predictions, axis=1)
acc = accuracy_metric.compute(references=labels, predictions=preds)
return {"accuracy": acc["accuracy"]}
except Exception as e:
logging.error(f"Failed to compute metrics: {e}")
raise
class ImageDistilTrainer(Trainer):
"""
Custom Trainer for Knowledge Distillation.
"""
def __init__(
self,
teacher_model: nn.Module,
student_model: nn.Module,
temperature: float,
lambda_param: float,
*args,
**kwargs
):
super().__init__(model=student_model, *args, **kwargs)
self.teacher = teacher_model
self.student = student_model
self.temperature = temperature
self.lambda_param = lambda_param
self.loss_function = nn.KLDivLoss(reduction="batchmean")
self.teacher.to(self.args.device)
self.teacher.eval()
logging.info("ImageDistilTrainer initialized with knowledge distillation parameters.")
def compute_loss(self, model, inputs, return_outputs=False):
"""
Computes the loss incorporating knowledge distillation.
Args:
model (nn.Module): The student model.
inputs (Dict[str, torch.Tensor]): Batch inputs.
return_outputs (bool): Whether to return the outputs.
Returns:
Union[torch.Tensor, Tuple[torch.Tensor, Any]]: Loss value and optionally outputs.
"""
try:
student_outputs = model(**inputs)
with torch.no_grad():
teacher_outputs = self.teacher(**inputs)
# Soft targets
soft_teacher = F.softmax(teacher_outputs.logits / self.temperature, dim=-1)
soft_student = F.log_softmax(student_outputs.logits / self.temperature, dim=-1)
# Distillation loss
distillation_loss = self.loss_function(soft_student, soft_teacher) * (self.temperature ** 2)
# Classification loss
classification_loss = F.cross_entropy(student_outputs.logits, inputs['labels'])
# Total loss
loss = (1.0 - self.lambda_param) * classification_loss + self.lambda_param * distillation_loss
return (loss, student_outputs) if return_outputs else loss
except Exception as e:
logging.error(f"Failed to compute loss in ImageDistilTrainer: {e}")
raise
def plot_predictions(
processor: ViTImageProcessor,
model: nn.Module,
dataset: DatasetDict,
id2label: Dict[int, str],
device: torch.device,
plots_dir: Path
) -> None:
"""
Performs inference on a sample and plots the predictions.
Args:
processor (ViTImageProcessor): Image processor.
model (nn.Module): The model for inference.
dataset (DatasetDict): The dataset for sampling.
id2label (Dict[int, str]): ID-to-label mapping.
device (torch.device): Computation device.
plots_dir (Path): Directory to save the plot.
"""
try:
sample = dataset['test'][0]
inputs = processor(sample["image"], return_tensors="pt")
inputs = {k: v.to(device) for k, v in inputs.items()}
model.eval()
with torch.no_grad():
logits = model(**inputs).logits
prediction = torch.argmax(logits, dim=1).item()
probabilities = F.softmax(logits, dim=1).cpu().numpy().flatten()
# Plotting
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(sample["image"])
plt.title(f"True Label: {id2label[sample['label']]}\nPredicted: {id2label[prediction]}")
plt.axis('off')
plt.subplot(1, 2, 2)
plt.bar(id2label.keys(), probabilities)
plt.title("Predicted Class Probabilities")
plt.xlabel("Class ID")
plt.ylabel("Probability")
plt.tight_layout()
plot_path = plots_dir / "inference_sample.png"
plt.savefig(plot_path)
plt.close()
logging.info(f"Inference plot saved at {plot_path}")
except Exception as e:
logging.error(f"Failed to plot predictions: {e}")
raise
def main() -> None:
"""
Main function to execute the pipeline.
"""
try:
# Configuration
dataset_name = "pcuenq/oxford-pets"
cache_dir = Path("./data")
teacher_model_name = "asusevski/vit-base-patch16-224-oxford-pets"
image_processor_name = "google/vit-base-patch16-224"
base_model_pretrained = "google/vit-base-patch16-224"
student_model_pretrained = "WinKawaks/vit-tiny-patch16-224"
output_dir = Path("./output")
output_dirs = create_output_dirs(output_dir)
setup_logging(output_dir)
# Load dataset
dataset = load_and_prepare_dataset(dataset_name, cache_dir)
# Prepare label mappings
id2label, label2id = prepare_label_mappings(dataset)
# Initialize device
device = initialize_device()
# Load teacher model and processor
teacher_model = load_teacher_model(teacher_model_name, device)
processor = load_image_processor(image_processor_name)
# Plot teacher distributions for the first sample
sample_input = processor(dataset["train"][0]["image"], return_tensors="pt")
sample_input = {k: v.to(device) for k, v in sample_input.items()}
with torch.no_grad():
teacher_logits = teacher_model(**sample_input).logits
teacher_distribution = F.softmax(teacher_logits / 1, dim=-1).cpu().numpy().flatten()
teacher_distribution_low = F.softmax(teacher_logits / 2, dim=-1).cpu().numpy().flatten()
teacher_distribution_high = F.softmax(teacher_logits / 8, dim=-1).cpu().numpy().flatten()
distributions = {
"temperature_no_change": teacher_distribution,
"low_temperature": teacher_distribution_low,
"high_temperature": teacher_distribution_high
}
plot_teacher_distributions(id2label, distributions, output_dirs["plots"])
# Prepare datasets
final_dataset = prepare_datasets(dataset, processor, label2id)
# Initialize metrics
global accuracy_metric
accuracy_metric = evaluate.load("accuracy")
# Define compute metrics
compute_metrics = compute_metrics_fn
# Training arguments for base model
base_training_args = TrainingArguments(
output_dir=str(output_dirs["base_model_weights"]),
per_device_train_batch_size=48,
per_device_eval_batch_size=48,
evaluation_strategy="epoch",
save_strategy="epoch",
logging_dir=str(output_dir / "logs"),
logging_steps=100,
num_train_epochs=10,
learning_rate=3e-4,
load_best_model_at_end=True,
metric_for_best_model="accuracy",
push_to_hub=False, # Set to True if you want to push to Hugging Face Hub
)
# Load and configure base model
logging.info("Initializing base model for training.")
base_config = ViTForImageClassification.from_pretrained(base_model_pretrained).config
base_config.id2label = id2label
base_config.label2id = label2id
base_config.num_labels = len(id2label)
base_model = ViTForImageClassification.from_pretrained(base_model_pretrained, config=base_config).to(device)
# Initialize Trainer for base model
trainer = Trainer(
model=base_model,
args=base_training_args,
data_collator=collate_fn,
compute_metrics=compute_metrics,
train_dataset=final_dataset["train"],
eval_dataset=final_dataset["valid"],
tokenizer=processor
)
# Train base model
logging.info("Starting training of the base model.")
trainer.train()
trainer.save_model(output_dirs["base_model_weights"])
logging.info("Base model training complete.")
# Evaluate base model
logging.info("Evaluating base model on the test set.")
base_evaluation = trainer.evaluate(final_dataset["test"])
logging.info(f"Base Model Evaluation: {base_evaluation}")
# Plot inference for base model
plot_predictions(processor, base_model, final_dataset, id2label, device, output_dirs["plots"])
# Prepare student model
logging.info("Initializing student model for knowledge distillation.")
student_config = ViTForImageClassification.from_pretrained(student_model_pretrained).config
student_config.id2label = id2label
student_config.label2id = label2id
student_config.num_labels = len(id2label)
student_model = ViTForImageClassification.from_pretrained(student_model_pretrained, config=student_config).to(device)
# Training arguments for student model with knowledge distillation
student_training_args = TrainingArguments(
output_dir=str(output_dirs["student_model_weights"]),
per_device_train_batch_size=48,
per_device_eval_batch_size=48,
evaluation_strategy="epoch",
save_strategy="epoch",
logging_dir=str(output_dir / "logs"),
logging_steps=100,
num_train_epochs=10,
learning_rate=3e-4,
load_best_model_at_end=True,
metric_for_best_model="accuracy",
push_to_hub=False,
)
# Initialize ImageDistilTrainer
logging.info("Starting training of the student model with knowledge distillation.")
distil_trainer = ImageDistilTrainer(
teacher_model=teacher_model,
student_model=student_model,
temperature=5.0,
lambda_param=0.9,
args=student_training_args,
data_collator=collate_fn,
compute_metrics=compute_metrics,
train_dataset=final_dataset["train"],
eval_dataset=final_dataset["valid"],
tokenizer=processor
)
# Train student model
distil_trainer.train()
distil_trainer.save_model(output_dirs["student_model_weights"])
logging.info("Student model training complete.")
# Evaluate student model
logging.info("Evaluating student model on the test set.")
student_evaluation = distil_trainer.evaluate(final_dataset["test"])
logging.info(f"Student Model Evaluation: {student_evaluation}")
# Plot inference for student model
plot_predictions(processor, student_model, final_dataset, id2label, device, output_dirs["plots"])
except Exception as e:
logging.critical(f"An error occurred in the pipeline: {e}")
raise
if __name__ == "__main__":
main()
Detailed Breakdown
-
Logging Setup:
- A logging mechanism is established to record the pipeline's progress and errors both to a log file and the console.
-
Output Directories:
- The
create_output_dirs function ensures that all necessary directories for plots and model weights are created.
-
Dataset Handling:
- The dataset is loaded using Hugging Face's
load_dataset.
- Label mappings (
id2label and label2id) are created for converting between label names and numerical IDs.
- Data preprocessing includes converting images to RGB, processing them with the ViT image processor, and mapping labels to IDs.
- The dataset is split into training, validation, and testing subsets.
-
Model Preparation:
- A pre-trained teacher model is loaded and set to evaluation mode.
- A base model is initialized from a pre-trained ViT model, configured with the appropriate label mappings.
- A student model is also initialized for knowledge distillation purposes.
-
Training Arguments:
- Two separate
TrainingArguments instances are defined: one for training the base model and another for training the student model with knowledge distillation.
-
Training and Evaluation:
- The
Trainer class from Hugging Face is used to train and evaluate the base model.
- A custom
ImageDistilTrainer class extends Trainer to incorporate knowledge distillation during the training of the student model.
- Both models are evaluated on the test dataset, and their performances are logged.
-
Visualization:
- The teacher model's prediction distributions at different temperatures are plotted and saved.
- Inference samples from both the base and student models are visualized alongside their predicted probabilities.
-
Error Handling:
- Comprehensive try-except blocks are used throughout the pipeline to catch and log errors, ensuring robustness.
-
Type Hints and PEP-8 Compliance:
- The code extensively uses type hints from the module for clarity.
Dependencies
Ensure that the following packages are installed in your environment:
pip install torch torchvision transformers datasets evaluate matplotlib
Running the Pipeline
Simply execute the script:
python your_pipeline_script.py
Ensure that you have the necessary computational resources, especially if training on large datasets or using large models.
Notes
- Scalability: The pipeline uses multiprocessing (
num_proc=4) during dataset preprocessing, which can be adjusted based on your hardware capabilities.
- Performance: Batch sizes and learning rates are set to common defaults but can be tuned for better performance.
- Extensibility: The modular structure allows for easy extensions, such as incorporating additional metrics or supporting different models and datasets.
This pipeline serves as a robust foundation for image classification tasks using ViT models, ensuring best practices in code quality, performance, and maintainability.