# Training Guide

## Overview

This guide covers the complete training process for YOLOv8 French ID Card Detection models.

## 🎯 Training Process

### 1. Data Preparation

Before training, ensure your dataset is properly structured:

```
data/
├── data.yaml          # Dataset configuration
├── train/
│   ├── images/        # Training images
│   └── labels/        # Training labels (YOLO format)
├── valid/
│   ├── images/        # Validation images
│   └── labels/        # Validation labels
└── test/
    ├── images/        # Test images
    └── labels/        # Test labels
```

### 2. Data Configuration

The `data.yaml` file should contain:

```yaml
train: ../train/images
val: ../valid/images
test: ../test/images

nc: 1  # Number of classes
names: ['french']  # Class names

# Roboflow metadata (optional)
roboflow:
  workspace: your-workspace
  project: your-project
  version: 5
```

### 3. Basic Training

```bash
# Start training with default settings
python train.py
```

**Default Configuration:**
- Model: YOLOv8n (nano)
- Epochs: 100
- Batch size: 16
- Image size: 640x640
- Patience: 50

### 4. Advanced Training

#### Custom Model Size
```bash
# Small model (balanced)
python train.py --model-size s

# Medium model (better accuracy)
python train.py --model-size m

# Large model (high accuracy)
python train.py --model-size l

# XLarge model (best accuracy)
python train.py --model-size x
```

#### Custom Training Parameters
```bash
python train.py \
    --model-size m \
    --epochs 200 \
    --batch-size 32 \
    --img-size 640 \
    --patience 100 \
    --save-period 20
```

#### Training with Validation
```bash
# Validate after training
python train.py --validate

# Validate only (no training)
python train.py --validate-only
```

## 📊 Training Configuration

### Model Sizes Comparison

| Size | Parameters | Speed | Accuracy | Use Case |
|------|------------|-------|----------|----------|
| n    | 3.2M       | Fast  | Low      | Quick testing |
| s    | 11.2M      | Medium| Medium   | Production |
| m    | 25.9M      | Medium| High     | High accuracy |
| l    | 43.7M      | Slow  | Very High| Best accuracy |
| x    | 68.2M      | Slowest| Highest | Research |

### Augmentation Settings

The training uses Roboflow-compatible augmentations:

```python
DEFAULT_TRAINING_CONFIG = {
    'augment': True,
    'hsv_s': 0.61,    # Saturation: -61% to +61%
    'hsv_h': 0.015,   # Hue adjustment
    'hsv_v': 0.4,     # Value adjustment
    'fliplr': 0.5,    # Horizontal flip 50%
    'mosaic': 1.0,    # Mosaic augmentation
    'erasing': 0.08,  # Random erasing
    'translate': 0.1, # Translation
    'scale': 0.5,     # Scaling
}
```

## 🔍 Monitoring Training

### Real-time Monitoring

Training progress is displayed in real-time:

```
Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
  1/100     0G       1.031      2.223      1.216         32        640: 100%|██████████| 8/8 [00:02<00:00,  3.52it/s]
```

### Log Files

Training logs are saved to:
- `logs/training.log`: Detailed training logs
- `runs/train/yolov8_*_french_id_card/`: Training results

### TensorBoard (Optional)

```bash
# Start TensorBoard
tensorboard --logdir runs/train

# Access at http://localhost:6006
```

## 📈 Training Metrics

### Key Metrics to Monitor

1. **Loss Values**
   - `box_loss`: Bounding box regression loss
   - `cls_loss`: Classification loss
   - `dfl_loss`: Distribution Focal Loss

2. **Validation Metrics**
   - `mAP50`: Mean Average Precision at IoU=0.5
   - `mAP50-95`: Mean Average Precision across IoU thresholds
   - `precision`: Precision score
   - `recall`: Recall score

### Expected Performance

For French ID Card detection:

| Metric | Target | Good | Excellent |
|--------|--------|------|-----------|
| mAP50  | >0.8   | >0.9 | >0.95     |
| mAP50-95| >0.6   | >0.8 | >0.9      |
| Precision| >0.8   | >0.9 | >0.95     |
| Recall | >0.8   | >0.9 | >0.95     |

## ⚡ Performance Optimization

### GPU Memory Management

```bash
# Reduce batch size if OOM
python train.py --batch-size 8

# Use smaller image size
python train.py --img-size 416

# Use smaller model
python train.py --model-size n
```

### Training Speed Optimization

```bash
# Increase batch size (if memory allows)
python train.py --batch-size 32

# Use larger model with more epochs
python train.py --model-size m --epochs 300

# Enable mixed precision (default)
# Already enabled in config
```

## 🔧 Troubleshooting

### Common Training Issues

**1. CUDA Out of Memory**
```bash
# Solution: Reduce batch size
python train.py --batch-size 8
```

**2. Training Too Slow**
```bash
# Solution: Use smaller model
python train.py --model-size n
```

**3. Poor Accuracy**
```bash
# Solution: Use larger model
python train.py --model-size m --epochs 200
```

**4. Overfitting**
```bash
# Solution: Reduce epochs, increase patience
python train.py --epochs 50 --patience 20
```

### Debug Commands

```bash
# Validate data structure
python train.py --validate-only

# Check GPU availability
python -c "import torch; print(torch.cuda.is_available())"

# Test with small dataset
python train.py --epochs 5 --batch-size 4
```

## 📋 Training Checklist

- [ ] Data properly structured
- [ ] `data.yaml` configured correctly
- [ ] GPU available (recommended)
- [ ] Dependencies installed
- [ ] Sufficient disk space
- [ ] Training parameters set
- [ ] Monitoring setup

## 🎯 Next Steps

After training:

1. **Evaluate the model**: `python eval.py`
2. **Test inference**: `python inference.py --input test.jpg`
3. **Export model**: Use the export functionality
4. **Deploy**: Integrate into your application

---

**Note**: Training times vary based on hardware. A typical training run takes 1-4 hours on a modern GPU. 