Final Eye Blink Tracker Implementation

Eye Tracking for Everyone: Final Implementation Phase

In this final blog post of our iTracker series, I'll walk you through the complete implementation of our eye-tracking model using PyTorch. This post covers the full architecture, training process, and results of our gaze estimation system.

Project Overview

The implementation provides a complete pipeline for eye gaze tracking, built on PyTorch and utilizing the GazeCapture dataset. The system can predict where a person is looking on a screen using just their face and eye images. You can find the complete implementation in my GitHub repository.

Key Components

1. Data Pipeline

The data pipeline consists of two main components:

Data Preparation (prepareDataset.py)

  • Processes the raw GazeCapture dataset
  • Extracts and crops face and eye images
  • Generates face grid representations
  • Creates a metadata.mat file containing frame indices, recording numbers, and gaze targets

Custom Dataset Implementation (DataLoader.py)

  • Implements a PyTorch Dataset class for efficient data loading
  • Handles image preprocessing and normalization
  • Manages train/validation/test splits
  • Implements face grid generation on the fly

2. Model Architecture

The iTracker model (iTrackerModel.py) implements a multi-stream CNN architecture:

class iTracker(nn.Module):
    def __init__(self, dropout_rate=0.5):
        # Three parallel CNN branches:
        self.left_eye_branch = nn.Sequential(...)
        self.right_eye_branch = nn.Sequential(...)
        self.face_branch = nn.Sequential(...)
        self.face_grid_branch = nn.Sequential(...)
        self.fully_con_layers = nn.Sequential(...)

Key features:

  • Separate CNN branches for left eye, right eye, and face processing
  • Face grid processing branch for spatial awareness
  • Feature fusion layer combining all streams
  • Final regression layers for gaze prediction

3. Training Pipeline

The training system (main.py) includes:

  • Apple Silicon GPU support via MPS backend
  • Automatic checkpointing of best models
  • Comprehensive evaluation metrics
  • Hyperparameters:
  • Batch size: 50
  • Learning rate: 0.001
  • Weight decay: 1e-4
  • Number of epochs: 100

Implementation Highlights

GPU Acceleration

One of the key features of our implementation is the support for Apple Silicon GPUs through PyTorch's MPS (Metal Performance Shaders) backend. This optimization allows for significantly faster training times on modern Mac hardware:

if torch.backends.mps.is_available():
    device = torch.device('mps')
    print('Using MPS backend for Apple Silicon GPU.')
else:
    device = torch.device('cpu')

This implementation choice provides several benefits:

  • Native support for Apple M1/M2 chips
  • Reduced training time compared to CPU-only processing
  • Efficient memory utilization through Metal's optimization

Data Augmentation and Preprocessing

Our data pipeline includes careful preprocessing steps to ensure optimal model performance. Each image stream (face, left eye, right eye) undergoes the following transformations:

self.transformFace = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    scalarmean(
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225]
    )
])

Key preprocessing features include:

  • Consistent image resizing to 224x224 pixels
  • Normalization using ImageNet statistics for transfer learning benefits
  • Custom face grid generation for spatial awareness
  • Efficient data loading through PyTorch's DataLoader

Model Training

The training pipeline is designed for robustness and reproducibility, incorporating several best practices:

  1. Loss Function: We use Mean Square Error (MSE) loss, which is particularly suitable for regression tasks like gaze estimation:
  2. Provides smooth gradients for optimization
  3. Natural choice for coordinate prediction
  4. Easy to interpret in terms of pixel-level accuracy

  5. Optimization Strategy:

  6. Adam optimizer with carefully tuned parameters
  7. Learning rate of 0.001 for stable convergence
  8. Weight decay (1e-4) for regularization
  9. Batch size of 50 for good gradient estimates

  10. Training Loop Features:

  11. Regular validation to monitor overfitting
  12. Automatic model checkpointing
  13. Early stopping based on validation loss
  14. Comprehensive logging of metrics

Results and Performance

πŸ“ˆ Training Evolution

Milestone Training Loss Validation Loss Gaze Error
Initial (Epoch 1) 33.37 31.15 55.89Β°
Mid-Training (Epoch 50) ~4.5 ~2.5 ~10Β°
Best (Epoch 95) 3.04 1.66 8.18Β°
Final (Epoch 100) 3.09 2.12 8.79Β°

πŸƒβ€β™‚οΈ Training Progress Timeline


Loss     β”‚                                  Best Model (Epoch 95)
33.37    β”‚β–ˆ                                      ↓
         β”‚β–ˆ
         β”‚β–ˆ
~15.0    β”‚ β–ˆ
         β”‚  β–ˆ
         β”‚   β–ˆ
~7.86    β”‚    β–ˆ
         β”‚     β–ˆ        Steady Optimization
         β”‚      β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
3.04     β”‚                                      β–ˆ
         β”‚
         └───────────────────────────────────────────────-───────────────
           1    10    20    30    40    50    60    70    80    90   100
                                  Epochs

Hardware & Dataset Statistics

Training Environment

  • Platform: Apple Silicon GPU (MPS backend)
  • Dataset Split: β”œβ”€β”€ Training: 9,089 records (β‰ˆ2% of full dataset) β”œβ”€β”€ Validation: 9,089 records └── Test: 2,682 records

Key Performance Metrics

Best Model Performance (Epoch 95)

πŸ“Š Training Loss: 3.04
πŸ“Š Validation Loss: 1.66
πŸ“Š Average Gaze Error: 8.18Β°

Test Set Performance

⚠️ Test Loss: 51.82
⚠️ Average Gaze Error: 53.63°

πŸ“Š Training Analysis

Major Milestones

  1. Rapid Initial Improvement πŸ“ˆ
  2. First 10 epochs showed dramatic improvement
  3. Training loss dropped from 33.37 β†’ 7.86

  4. Optimization Phase ⚑

  5. Steady improvement between epochs 10-50
  6. Gradual refinement of model parameters

  7. Fine-tuning Phase 🎯

  8. Best performance at epoch 95
  9. Validation loss reached minimum of 1.66

Performance Insights

βœ… Successes:

  • Reduced gaze error by 85% (55.89Β° β†’ 8.18Β°)
  • Achieved stable training progression
  • Maintained consistent validation performance

⚠️ Challenges:

  • Significant gap between validation and test performance
  • Signs of potential overfitting
  • Limited dataset utilization (~2% of full dataset)

Areas for Improvement

  1. Data Enhancement
  2. Expand training to full dataset
  3. Implement additional augmentation techniques
  4. Enhance data preprocessing pipeline

  5. Model Optimization

  6. Add regularization layers
  7. Tune learning rate schedule
  8. Explore architectural modifications

  9. Performance Tuning

  10. Address validation-test gap
  11. Improve generalization
  12. Optimize inference speed

Future Work

The current implementation, while functional, represents only the beginning of what's possible with this eye-tracking system. Here are the key areas for future development:

  1. Expanded Dataset Utilization
  2. Current implementation uses only ~2% of the full GazeCapture dataset
  3. Plan to extend training to the complete dataset (>2.4M frames)
  4. Expect significant improvement in model robustness and accuracy

  5. Real-time Implementation

  6. Develop webcam integration for live gaze tracking
  7. Optimize inference pipeline for real-time performance
  8. Implement efficient frame processing and prediction

  9. Technical Improvements

  10. Integration of attention mechanisms
  11. Performance optimization strategies
  12. Mobile deployment solutions
  13. Cross-platform GPU support

  14. Model Architecture Enhancements

  15. Explore architectural modifications to reduce overfitting
  16. Implement additional data augmentation techniques
  17. Fine-tune hyperparameters with larger dataset

The immediate focus will be on expanding the training data utilization, as this forms the foundation for more robust real-time applications. Once we achieve better generalization through comprehensive training, we'll move on to implementing real-time webcam tracking capabilities.

Resources

Acknowledgments

This implementation builds upon the work presented in:

K.Krafka, A. Khosla, P. Kellnhofer, H. Kannan, S. Bhandarkar, W. Matusik and A. Torralba, "Eye Tracking for Everyone", IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016

Special thanks to the CSAIL Vision group for making their dataset and original implementation publicly available.


This completes our journey of implementing the iTracker model. The full source code, along with detailed documentation, is available in the GitHub repository. Feel free to explore, experiment, and contribute to the project!

← all field notes