AI Workshop For Senior Government Officials

Workshop Resources

Activity 7: Fine-tuning Vision AI for Beaker Volume Recognition

Duration: 60 minutes
The Art of Patience in AI Training

“AI training is a patient person’s work.” This activity represents the culmination of our workshop – training a sophisticated vision-language model that can accurately estimate fluid volumes in laboratory beakers. Unlike our previous activities that completed in minutes, this training process can take several hours to achieve optimal results. This teaches us an important lesson about AI development: the best models require time, patience, and careful iteration.

Why This Problem Matters

The Laboratory Challenge: Imagine you’re working in a chemistry laboratory, pharmaceutical research facility, or quality control environment. Throughout the day, researchers and technicians need to:

  • Measure precise fluid volumes in various containers
  • Document experimental procedures with volume measurements
  • Ensure consistency across multiple experiments
  • Validate measurements for regulatory compliance

Current Manual Process Problems:

  • Human Error: Visual estimation varies between individuals
  • Time Consuming: Manual measurements slow down experiments
  • Inconsistency: Different people measure differently
  • Documentation: Manual recording prone to errors
  • Scalability: Cannot handle high-volume scenarios

The AI Solution: A computer vision model that can accurately estimate fluid volumes from photographs, providing:

  • Consistent, objective measurements
  • Instant analysis of multiple samples
  • Automatic documentation and logging
  • Integration with laboratory management systems
  • 24/7 availability without fatigue
Understanding Vision-Language Model Fine-tuning

What We’re Actually Training: Unlike our previous text classification model, we’re now training a vision-language model that can:

  • “See” and understand images
  • “Read” and understand text instructions
  • “Think” about the relationship between visual and textual information
  • “Respond” with accurate, contextual answers

Qwen2.5-VL-3B Architecture:

  • Vision Encoder: Processes and understands images
  • Language Model: Generates text responses
  • Cross-modal Attention: Connects visual and textual understanding
  • 3 Billion Parameters: Sophisticated enough for complex visual reasoning

Why Fine-tuning Instead of Training from Scratch:

  • Foundation Knowledge: Model already understands basic visual concepts and language
  • Transfer Learning: Leverages existing understanding of objects, shapes, and measurements
  • Efficiency: Requires less data and computational resources
  • Specialization: Adapts general vision capabilities to our specific domain
The Technical Innovation: LoRA (Low-Rank Adaptation)

The Memory Challenge: Fine-tuning a 3-billion parameter model traditionally requires enormous computational resources. LoRA solves this through mathematical elegance:

How LoRA Works:

  • Instead of updating all 3 billion parameters, LoRA adds small “adapter” layers
  • These adapters capture the specialized knowledge for our task
  • Original model weights remain mostly unchanged
  • Dramatically reduces memory requirements and training time

LoRA Parameters in Our Training:

  • Rank (r=16): Controls the capacity of adaptation
  • Alpha (16): Scaling factor for the adaptation
  • Target Modules: Attention and MLP layers for maximum impact
  • Dropout (0): No regularization needed for our dataset size
Real-World Applications Beyond Beakers

Laboratory Automation:

  • Clinical Labs: Blood sample volume verification
  • Research Labs: Precise reagent measurement
  • Quality Control: Batch consistency verification
  • Pharmaceutical: Drug formulation accuracy

Medical Applications:

  • IV Fluid Monitoring: Patient hydration tracking
  • Medication Dosing: Liquid medication verification
  • Blood Banking: Donation volume validation
  • Dialysis: Fluid removal monitoring

Industrial Applications:

  • Chemical Processing: Raw material measurement
  • Food & Beverage: Recipe consistency verification
  • Paint & Coatings: Mixture proportion validation
  • Petroleum: Fuel quality sampling

Manufacturing Quality Control:

  • Automotive: Fluid level verification
  • Electronics: Coating thickness estimation
  • Packaging: Fill level validation
  • Cosmetics: Product consistency checking
Step-by-Step Implementation
Step 1: Download the Vision Training Application

In your Jupyter notebook, create a new cell and run:

%cd /home
!git clone https://github.com/ictBioRtc/finetune_qwen2.5_vision_language_model.git

What this does: Downloads a complete vision model fine-tuning application with training data, model architecture, and evaluation tools.

Step 2: Navigate to the Project

Create another cell and run:

%cd finetune_qwen2.5_vision_language_model

What this does: Changes your working directory to the vision fine-tuning project folder.

Step 3: Install Vision Model Dependencies

Create a new cell and run:

!pip install -r requirements.txt

What this installs:

  • Unsloth: Optimized training framework for vision-language models
  • Pillow: Advanced image processing capabilities
  • Gradio: Interactive web interface for model training and testing
  • Matplotlib: Visualization tools for training progress

This installation takes 4-5 minutes as it downloads optimized CUDA kernels and vision model components.

Step 4: Launch the Vision Training Platform

Create a new cell and run:

!python app.py

What happens:

  • The application initializes the Qwen2.5-VL-3B vision-language model
  • Creates a comprehensive training, testing, and evaluation interface
  • Provides a public URL (like: https://xyz789.gradio.live)
  • Click the URL to access your vision AI training platform
Step 5: Understanding the Training Interface

Your application opens with three sophisticated tabs:

“Inference (Before Training)” Tab:

  • Test the base model’s initial capabilities
  • Understand baseline performance before specialization
  • Upload beaker images and see untrained responses

“Training” Tab:

  • Configure and execute the fine-tuning process
  • Monitor training progress in real-time
  • Save and deploy your trained model

“Evaluation (After Training)” Tab:

  • Test your specialized model’s performance
  • Compare before and after training results
  • Validate model accuracy on new images
The Complete Training Process
Phase 1: Understanding the Baseline (5 minutes)

Step 1a: Initialize the Base Model

  1. Go to the “Inference (Before Training)” tab
  2. Click “Initialize Base Model”
  3. Wait for confirmation: “Model initialized successfully!”

What happens behind the scenes:

  • Qwen2.5-VL-3B model loads into GPU memory
  • Vision encoder and language decoder initialize
  • Model enters evaluation mode for inference

Step 1b: Test Baseline Performance

  1. Upload a beaker image (use provided samples or your own)
  2. Keep the default instruction: “Estimate the volume of the fluid in the beaker.”
  3. Click “Run Inference”
  4. Observe the base model’s response

Expected Baseline Results: The untrained model might give vague responses like:

  • “The beaker appears to contain some liquid”
  • “There is fluid visible in the container”
  • Generic descriptions without specific volume estimates

Why This Matters: This demonstrates why domain-specific training is crucial. The general model understands it’s looking at a beaker with liquid, but cannot provide the precise volume estimation required for laboratory use.

Phase 2: Preparing for Specialized Training (2 minutes)

Step 2a: Model Preparation

  1. Switch to the “Training” tab
  2. Click “Prepare Model for Training”
  3. Wait for confirmation: “Model prepared for training! LoRA adapters added successfully.”

What happens during preparation:

  • LoRA adapter layers are added to the model
  • Vision and language components are prepared for fine-tuning
  • Training-specific configurations are applied
  • Memory optimization strategies are activated

Step 2b: Understanding Training Parameters

Batch Size (Default: 2):

  • Number of images processed simultaneously
  • Smaller batches = less memory usage but slower training
  • Larger batches = faster training but more memory required

Gradient Accumulation Steps (Default: 4):

  • Simulates larger batch sizes without memory overhead
  • Effective batch size = Batch Size × Gradient Accumulation
  • Helps stabilize training on limited hardware

Epochs (Default: 5):

  • Complete passes through the entire training dataset
  • More epochs = better learning but risk of overfitting
  • 5 epochs is conservative for workshop; production might use 10-15

Learning Rate (Default: 2e-4):

  • Controls how aggressively the model updates weights
  • Too high = unstable training, too low = slow convergence
  • 2e-4 is optimized for vision-language model fine-tuning
Phase 3: The Patient Art of Training (2-4 hours)

Important Expectation Setting: This is where patience becomes crucial. Quality AI training cannot be rushed. The following process will take considerable time, but each minute contributes to creating a specialized, highly accurate model.

Step 3a: Start the Training Process

  1. Leave all parameters at their defaults for optimal results
  2. Click “Start Training”
  3. Observe the initial setup messages

Step 3b: Understanding Training Progress

What You’ll See During Training:

Initial Phase (First 30 minutes):

Preparing model: Model prepared for training! LoRA adapters added successfully.
Setting up trainer...
Loading dataset from HuggingFace...
Loading main train split...
Loaded 12800 samples from main train split
Converting training samples to conversation format...
Training samples: 12800
Validation samples: 2400
Starting training process...

Training Loop (Main Duration):

Epoch 1/5: Step 100/3200 - Loss: 2.45 - Learning Rate: 1.8e-4
Epoch 1/5: Step 200/3200 - Loss: 1.89 - Learning Rate: 1.6e-4
Epoch 1/5: Step 300/3200 - Loss: 1.34 - Learning Rate: 1.4e-4
...
Epoch 5/5: Step 3200/3200 - Loss: 0.12 - Learning Rate: 0.0e-4

Training Progression Indicators:

Loss Values (What to Expect):

  • Epoch 1: Loss starts around 2.5, decreases to ~1.5
  • Epoch 2: Loss decreases from 1.5 to ~0.8
  • Epoch 3: Loss decreases from 0.8 to ~0.4
  • Epoch 4: Loss decreases from 0.4 to ~0.2
  • Epoch 5: Loss stabilizes around 0.1-0.15

Time Estimates:

  • Per Epoch: 45-60 minutes on GPU
  • Total Training: 4-5 hours for all 5 epochs
  • Varies by: GPU type, batch size, dataset size

Step 3c: Monitoring Training Health

Good Training Signs:

  • Loss consistently decreasing
  • No sudden spikes or crashes
  • Memory usage stable
  • Regular checkpoint saves

Warning Signs:

  • Loss not decreasing after first epoch
  • Out of memory errors
  • Training process hanging
  • Sudden loss spikes
Phase 4: Model Preservation (5 minutes)

Step 4a: Save Your Trained Model

  1. After training completes successfully
  2. Click “Save Model Locally”
  3. Note the save path: “trained_beaker_model”
  4. Wait for confirmation: “Model saved successfully!”

What gets saved:

  • Fine-tuned model weights with LoRA adapters
  • Tokenizer configuration for image and text processing
  • Model configuration files for deployment
  • Training metadata and performance metrics

Step 4b: Optional Hugging Face Upload

  1. Enter your model name: “your-username/beaker-volume-model”
  2. Enter your Hugging Face token
  3. Click “Upload to Hub”
  4. Follow the post-upload instructions for configuration files

Why Upload to Hugging Face:

  • Preserves your work beyond the workshop
  • Enables sharing with colleagues
  • Provides model versioning and documentation
  • Facilitates deployment in production environments
Phase 5: Evaluation and Validation (10 minutes)

Step 5a: Load Your Trained Model

  1. Switch to the “Evaluation (After Training)” tab
  2. Enter model path: “trained_beaker_model”
  3. Click “Load Trained Model”
  4. Wait for confirmation: “Model loaded successfully!”

Step 5b: Test Specialized Performance

  1. Upload the same beaker image you tested earlier
  2. Use the same instruction: “Estimate the volume of the fluid in the beaker.”
  3. Click “Run Inference”
  4. Compare the results with your baseline test

Expected Improved Results: Your trained model should now provide specific, accurate responses like:

  • “The fluid volume in the beaker is approximately 250 mL”
  • “Based on the fluid level, I estimate 180 mL of liquid”
  • “The beaker contains roughly 320 mL of fluid”

Step 5c: Comprehensive Testing Test your model with various scenarios:

  • Different fluid levels (low, medium, high)
  • Different beaker sizes and shapes
  • Various lighting conditions
  • Different fluid colors and transparency
Understanding What Happened During Training

The Complete Fine-tuning Pipeline:

1. Data Processing (First 30 minutes):

  • 12,800 training images with volume labels loaded
  • Each image paired with instruction-response conversation
  • Data converted to vision-language model format
  • Training and validation splits created

2. Model Architecture Adaptation:

  • LoRA adapters added to attention mechanisms
  • Vision encoder prepared for specialized feature extraction
  • Language decoder prepared for volume-specific responses
  • Cross-modal connections optimized for measurement tasks

3. Iterative Learning Process:

  • Model processes image-instruction pairs
  • Generates volume estimates
  • Compares predictions to ground truth labels
  • Updates LoRA adapter weights to minimize errors
  • Gradually specializes in volume estimation

4. Knowledge Transfer:

  • General vision understanding preserved
  • Domain-specific volume recognition learned
  • Measurement accuracy progressively improved
  • Consistency across different scenarios developed
Advanced Training Concepts for Vision Models

Transfer Learning in Computer Vision: Your model leveraged pre-trained knowledge about:

  • Object recognition (identifying beakers, fluids, containers)
  • Spatial reasoning (understanding 3D volume from 2D images)
  • Text generation (producing coherent measurement responses)
  • Cross-modal understanding (connecting visual and textual information)

Why Training Takes So Long:

  • Dataset Size: 12,800 high-quality labeled images
  • Model Complexity: 3 billion parameters with vision and language components
  • Precision Requirements: Volume estimation requires high accuracy
  • Cross-modal Learning: Vision and language must be synchronized
  • Quality Optimization: Multiple epochs ensure robust learning

Memory and Computational Efficiency:

  • LoRA Adapters: Only 1% of parameters actually updated
  • Gradient Checkpointing: Memory usage optimized for limited GPU
  • Mixed Precision Training: FP16/BF16 for speed without quality loss
  • Batch Optimization: Balanced throughput and memory constraints
Customization for Different Applications

Medical Imaging Applications:

IV Bag Monitoring:

  • Replace beaker images with IV bag photos
  • Modify labels for medical volume standards
  • Add patient safety considerations

Blood Sample Analysis:

  • Train on test tube and vial images
  • Include different blood components
  • Integrate with laboratory information systems

Industrial Quality Control:

Manufacturing Line Integration:

  • Real-time volume verification
  • Automated quality rejection
  • Statistical process control integration

Chemical Processing:

  • Hazardous material handling
  • Batch consistency monitoring
  • Regulatory compliance documentation
Production Deployment Considerations

Model Serving Infrastructure:

  • Local Deployment: On-premises laboratory servers
  • Cloud Deployment: Scalable cloud-based inference
  • Edge Deployment: Embedded systems in laboratory equipment
  • Mobile Deployment: Tablet or smartphone applications

Integration Strategies:

  • API Services: RESTful endpoints for laboratory systems
  • Database Integration: Automatic result logging and tracking
  • Workflow Automation: Seamless laboratory management integration
  • Quality Assurance: Confidence scoring and human verification triggers

Performance Monitoring:

  • Accuracy Tracking: Continuous validation against manual measurements
  • Drift Detection: Model performance degradation alerts
  • Retraining Triggers: Automated model updates with new data
  • Audit Trails: Complete measurement history and compliance reporting
Troubleshooting Extended Training Sessions

Common Long Training Issues:

“Training appears stuck”

  • Check GPU utilization (should be high during training)
  • Verify no memory leaks or system resource constraints
  • Monitor training logs for progress indicators
  • Be patient – complex models require time

“Out of memory during training”

  • Reduce batch size from 2 to 1
  • Increase gradient accumulation steps to maintain effective batch size
  • Clear CUDA cache and restart application
  • Consider using smaller model variant if available

“Loss not decreasing after several hours”

  • Check learning rate (may be too high or too low)
  • Verify data quality and labeling consistency
  • Consider data augmentation if overfitting
  • Ensure sufficient training data diversity

“Training process interrupted”

  • Check if model checkpoints were saved automatically
  • Resume from last checkpoint if available
  • Verify stable power and network connectivity
  • Consider breaking training into smaller segments
The Business Value of Patient AI Development

Why the Investment in Time Pays Off:

Accuracy Benefits:

  • Precision: Trained models achieve 95%+ accuracy vs. 60% untrained
  • Consistency: Eliminates human variability in measurements
  • Reliability: 24/7 operation without fatigue or distraction
  • Scalability: Handles thousands of measurements per day

Cost-Benefit Analysis:

  • Training Cost: One-time investment in computational resources
  • Deployment Savings: Eliminates ongoing manual measurement costs
  • Error Reduction: Prevents costly mistakes and rework
  • Compliance Value: Automated documentation and audit trails

Competitive Advantages:

  • Innovation Leadership: Advanced AI capabilities differentiate services
  • Operational Efficiency: Faster, more reliable laboratory processes
  • Quality Improvement: Consistent, documented measurement standards
  • Future-Proofing: Foundation for additional AI applications
Key Insights and Takeaways

Technical Mastery:

  1. Vision-Language Integration: Successfully trained a model that understands both images and text
  2. Transfer Learning Expertise: Leveraged pre-trained knowledge for domain specialization
  3. Efficient Fine-tuning: Used LoRA adapters for resource-efficient training
  4. Production Pipeline: Experienced complete ML workflow from data to deployment
  5. Patience and Persistence: Learned that quality AI requires time and careful iteration

Business Acumen:

  1. ROI Understanding: Calculated long-term value of AI training investments
  2. Problem-Solution Mapping: Identified real-world applications for AI capabilities
  3. Quality Standards: Balanced training time with accuracy requirements
  4. Deployment Strategy: Considered infrastructure and integration requirements
  5. Continuous Improvement: Planned for model monitoring and updates

Personal Development:

  1. Technical Patience: Experienced the reality of AI development timelines
  2. Problem-Solving Skills: Troubleshot complex training scenarios
  3. Systems Thinking: Understood end-to-end AI application development
  4. Quality Focus: Appreciated the importance of thorough testing and validation
  5. Innovation Mindset: Recognized opportunities for AI applications in various domains
Workshop Conclusion: From Consumer to Creator

Your AI Journey:

  • Day 1: Used existing AI models through APIs and applications
  • Day 2: Trained your own specialized AI models for specific problems
  • Outcome: Transformed from AI consumer to AI creator

Skills Acquired:

  • Text Classification: BERT fine-tuning for document categorization
  • Computer Vision: Vision-language model training for measurement tasks
  • Production Deployment: Model serving and integration strategies
  • Business Applications: ROI analysis and problem-solution mapping

What You Can Do Next:

  • Apply these techniques to your own domain-specific problems
  • Build AI solutions for your organization’s unique challenges
  • Continue learning advanced AI techniques and architectures
  • Join the community of AI practitioners and innovators

The Future of AI: You’ve experienced both the power and the patience required for AI development. Remember that the most valuable AI solutions often take time to develop properly, but the results can transform entire industries. The techniques you’ve learned today are the foundation for tomorrow’s AI innovations.

Final Wisdom: “AI training is indeed a patient person’s work, but patience in AI development is always rewarded with solutions that seemed impossible just a few years ago.”

Congratulations on completing this comprehensive AI workshop! You’ve not only learned to use AI tools but have become capable of creating them. This is your first step into a larger world of AI innovation and problem-solving.