0% found this document useful (0 votes)
21 views5 pages

ViViT Fine-Tuning for HMDB51 Guide

The document outlines the ViViT fine-tuning pipeline for the HMDB51 dataset, detailing steps from dataset preparation to post-training evaluation. Key processes include verifying dataset structure, data preprocessing with frame sampling and augmentation, model setup with a pre-trained ViViT model, and training execution with loss tracking and validation checks. Finally, it covers post-training evaluation, result visualization, model export, and inference testing to ensure effective action recognition performance.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views5 pages

ViViT Fine-Tuning for HMDB51 Guide

The document outlines the ViViT fine-tuning pipeline for the HMDB51 dataset, detailing steps from dataset preparation to post-training evaluation. Key processes include verifying dataset structure, data preprocessing with frame sampling and augmentation, model setup with a pre-trained ViViT model, and training execution with loss tracking and validation checks. Finally, it covers post-training evaluation, result visualization, model export, and inference testing to ensure effective action recognition performance.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Great — here's a step-by-step explanation of the ViViT fine-tuning pipeline for HMDB51,

clearly broken down from start to finish, matching your notebook structure:

1. Dataset Preparation
✅ Verify Dataset Structure

Ensure the HMDB51 folder follows this format:

root_dir/
└── brush_hair/
└── [Link], [Link], ...
└── cartwheel/
└── ...

This includes checking if all 51 class folders are present and videos are readable.

Parse Official Splits

HMDB51 provides 3 train/test split files per class. You read those .txt files and extract which
videos belong to train/test per split. The goal is to convert them into a Python dictionary for easy
access.

Create Stratified Train/Val/Test Splits

Split the dataset such that each class is equally represented in train, val, and test. Typically:

• 70% train
• 15% val
• 15% test
This ensures balanced performance evaluation.

2. Data Preprocessing
Video Frame Sampling

Use VideoFrameSampler to extract a fixed number of frames (T, e.g., 16 or 32) from each video.

• Uniform: Evenly spaced frames


• Random: Randomly selected frames
Spatial Transformations

Transformations like resizing, cropping, normalization to standardize frame dimensions and


improve model performance.

Temporal Normalization

Ensure each video sample has the same number of frames (T). This includes:

• Looping short videos


• Truncating long ones

Data Augmentation

For training only:

• Random horizontal flip


• Color jitter
• Rotation
• Random crop
This helps generalize the model to real-world variations.

3. Model Setup
Load Pre-trained ViViT

Use a ViViT model pre-trained on a large dataset like Kinetics-400. This provides a good
initialization for action recognition.

Modify Classification Head

Replace the final fully connected layer to match HMDB51's 51 classes:

[Link] = [Link](in_features, 51)

Configure Mixed Precision

Use AMP ([Link]) to:

• Reduce memory usage


• Increase training speed
Recommended for large models like ViViT.
Set Device Placement

Move model and tensors to the appropriate device (cuda if available).

4. Training Configuration
Define Loss Function

Use CrossEntropyLoss, optionally with class weighting for imbalance.

Initialize Optimizer

AdamW is a common choice. Use different learning rates for backbone vs. classification head if
needed.

Configure Learning Rate Scheduler

Common choices:

• CosineAnnealingLR
• ReduceLROnPlateau
• StepLR
This adjusts the learning rate during training.

Set Up Metrics Tracking

Track:

• Loss
• Top-1 accuracy
• Per-class accuracy
Use wandb, TensorBoard, or simple logging.

5. Training Execution
Batch Processing

Load batches of (video_tensor, label) pairs. Move to GPU, apply transforms.


Backpropagation

For each batch:

• Forward pass
• Compute loss
• Backward pass
• Optimizer step
• Optional: gradient clipping

✅ Validation Checks

At the end of each epoch:

• Run model on validation set


• Log accuracy/loss
• Save best-performing checkpoint

Model Checkpointing

Save model weights, optimizer state, and epoch info:

[Link]({
'epoch': epoch,
'model_state_dict': model.state_dict(),
...
}, '[Link]')

6. Post-Training
Final Evaluation

Run model on test set using best checkpoint. Compute:

• Confusion matrix
• Precision, recall, F1 per class
• Mean accuracy

Result Visualization

Plot training/validation curves for:

• Loss
• Accuracy
Show confusion matrix heatmap for insight into misclassifications.

Model Export

Export for deployment:

• TorchScript via [Link] or script


• ONNX for use in inference engines

Inference Testing

Load exported model and test inference speed and accuracy on single video samples.

Interface Contracts (Recap)


Data Flow
Video (.avi) → Frames → Tensor (T, H, W, C) → Batch (B, C, T, H, W)

Model Interface
Input: (B, C, T, H, W)
Output: (B, 51) → logits for each class

Training Protocol

• Mixed precision
• Per-class accuracy tracking
• Gradient clipping

Serialization

• Save full training state


• Export model in hardware-agnostic formats

Let me know if you want a complete version of the notebook filled out or help with writing
specific parts like the optimizer config or transform functions!

Common questions

Powered by AI

Per-class accuracy tracking plays a critical role in evaluating the model's performance across different action categories. Instead of providing an overall accuracy score, it tracks how accurately the model predicts each class, highlighting any discrepancies in performance among them. This is crucial for identifying classes that the model struggles to recognize, guiding targeted improvements like data augmentation for underperforming classes. It ensures a comprehensive evaluation that goes beyond aggregate accuracy, fostering balanced learning across all action categories in HMDB51 .

A learning rate scheduler adjusts the learning rate during training, which can help avoid issues like weights oscillating or converging too quickly to suboptimal minima. In the ViViT fine-tuning pipeline, common schedulers such as CosineAnnealingLR, ReduceLROnPlateau, or StepLR are used to dynamically modify the learning rate, usually decreasing it over time to help fine-tune the model more precisely. This controlled adjustment improves model performance by ensuring stable convergence and maintaining a balance between exploration and exploitation during training .

The HMDB51 dataset is organized into 51 class folders, each containing multiple video files. This structure allows easy parsing of official train/test split files provided for each class, which are then converted into Python dictionaries. Stratified train/val/test splits, where the dataset is divided so each class is equally represented (typically 70% train, 15% val, 15% test), ensure balanced performance evaluation across all classes. This prevents class imbalance from skewing the results and provides a more reliable assessment of the model's generalization ability to unseen data .

During data preprocessing, transformations such as resizing, cropping, and normalization are applied to standardize frame dimensions, which helps improve the model's performance by making the input data consistent. Furthermore, temporal normalization ensures each video sample has the same number of frames, addressing discrepancies in video length by looping shorter videos and truncating longer ones. Additionally, data augmentation techniques like random horizontal flips, color jitter, rotation, and random crops are used during training to enhance model generalization by simulating real-world variations .

Post-training analyses on the ViViT model involve running it on the test set using the best checkpoint and computing metrics such as confusion matrix, precision, recall, F1 score per class, and mean accuracy. Additionally, training/validation curves for loss and accuracy are plotted, and a confusion matrix heatmap is shown to gain insights into misclassifications. These analyses provide a detailed understanding of model performance, revealing strengths and weaknesses in classifying different actions, informing decisions for further model iterations or tuning .

Inference testing involves loading the exported model and assessing its speed and accuracy on single video samples. This process benefits from adhering to interface contracts, which define the data flow from video files to tensors and batch processing (from video ".avi" to tensor shape (T, H, W, C) to batch shape (B, C, T, H, W)). These contracts ensure consistency and compatibility between the data input/output structures expected by the model and the actual inputs provided during inference testing. This alignment is critical for achieving reliable results and optimizing the model's performance during deployment .

Gradient clipping prevents the issue of exploding gradients during backpropagation by limiting the maximum gradient value ( norm). This ensures that the weight updates are not excessively large, maintaining stable learning and facilitating convergence. It's considered optional because not all models suffer from exploding gradients, and utilizations depend on the observed stability issues during training. In ViViT's context, its complex architecture might occasionally benefit from this technique to maintain training stability, particularly when dealing with large models or noisy data .

Mixed precision involves using 16-bit floating-point numbers along with 32-bit ones to reduce memory usage and increase training speed. For large models like ViViT, this optimization is crucial as it allows larger batch sizes or more parameters to fit into the same GPU memory, reducing the time and cost of training while maintaining similar performance to using full precision .

Replacing the classification head of the ViViT model is significant for adapting the pre-trained model to the specific task of HMDB51, which involves action recognition across 51 classes. The original classification layer is replaced with a new fully connected layer matching the number of classes in HMDB51 (from the pre-trained dataset's classes to 51 classes in HMDB51). This customization allows the model to output logits specifically tailored for HMDB51's action categories, adapting learned features from the larger pre-trained dataset to the specific domain of HMDB51 .

Using AMP in the PyTorch CUDA module during ViViT training reduces memory usage significantly because it allows computation in lower precision (16-bit) while maintaining model accuracy. This reduction in memory allows for training with larger batch sizes or more complex models on the same hardware. It also enhances training speed, which is beneficial for large-scale deep learning models, where computational efficiency and reduced training time contribute significantly to the feasibility and scalability of practical AI applications .

You might also like