Jesse A. Green / notebook

YOLOv5 User Guide

Generated May 2026 from ultralytics/yolov5 at 66554d2

AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it.

1. Quick Start

YOLOv5 is a family of compound-scaled object detection models built on PyTorch, supporting object detection, instance segmentation, and image classification. It provides pre-trained weights, a flexible training pipeline, and export to 11+ deployment formats including ONNX, TensorRT, CoreML, and TensorFlow.

Key features:

  • Real-time object detection with five model sizes (nano through extra-large)
  • Instance segmentation with pixel-level masks
  • Image classification with transfer learning support
  • Multi-backend inference (PyTorch, ONNX, TensorRT, OpenVINO, CoreML, TFLite, and more)
  • PyTorch Hub integration for two-line inference
  • Multi-GPU distributed training (DDP)
  • Hyperparameter evolution for automated tuning
  • Experiment tracking via ClearML, Comet, W&B, and TensorBoard

Prerequisites: Python 3.8+, PyTorch 1.8+

Quickest path to a detection:

git clone https://github.com/ultralytics/yolov5
cd yolov5
pip install -r requirements.txt
python detect.py --weights yolov5s.pt --source data/images/bus.jpg
image 1/1 data/images/bus.jpg: 640x480 4 persons, 1 bus, 12.3ms
Speed: 1.2ms pre-process, 12.3ms inference, 1.5ms NMS per image at shape (1, 3, 640, 640)
Results saved to runs/detect/exp

Tip

For the fastest setup, use PyTorch Hub — no cloning required. See the PyTorch Hub section below.

What to try next:

  • Train a custom model: see Core Usage — Training
  • Run segmentation: see Instance Segmentation
  • Export for deployment: see Model Export
  • See the Admin Guide for full configuration reference and deployment options

2. Installation

System Requirements

Requirement Minimum Recommended
Python 3.8 3.10+
PyTorch 1.8.0 2.0+
CUDA (GPU) 10.2 11.8+
RAM 8 GB 16 GB+
Disk 2 GB (code + weights) 10 GB+ (with datasets)

Install Methods

pip (recommended)

git clone https://github.com/ultralytics/yolov5
cd yolov5
pip install -r requirements.txt

Docker (GPU)

docker pull ultralytics/yolov5:latest
docker run --ipc=host --gpus all ultralytics/yolov5:latest

Docker (CPU)

docker build -t yolov5-cpu -f utils/docker/Dockerfile-cpu .
docker run --ipc=host yolov5-cpu

Docker (ARM64)

docker build -t yolov5-arm64 -f utils/docker/Dockerfile-arm64 .
docker run --ipc=host yolov5-arm64

Important

Install PyTorch separately first if you need a specific CUDA version. Visit https://pytorch.org/get-started/locally/ for platform-specific install commands. The requirements.txt lists torch>=1.8.0 but does not pin a CUDA variant.

Core Dependencies

Package Version Purpose
torch >=1.8.0 Deep learning framework
torchvision >=0.9.0 Image transforms, pretrained models
opencv-python >=4.1.1 Image/video I/O
numpy >=1.23.5 Array operations
pillow >=10.3.0 Image loading
matplotlib >=3.3 Plotting
PyYAML >=5.3.1 Config file parsing
tqdm >=4.66.3 Progress bars
pandas >=1.1.4 Data tables
seaborn >=0.11.0 Statistical plots
scipy >=1.4.1 Scientific computing
ultralytics >=8.2.64 Utility functions
gitpython >=3.1.30 Git status checks
psutil any System resource monitoring
thop >=0.1.1 FLOPs computation
requests >=2.32.2 HTTP downloads

Optional Dependencies (by use case)

Use Case Packages
Export to ONNX onnx>=1.10.0, onnx-simplifier>=0.4.1, onnxruntime or onnxruntime-gpu
Export to TensorRT nvidia-tensorrt
Export to CoreML coremltools>=6.0
Export to TensorFlow tensorflow>=2.4.0
Export to TF.js tensorflowjs>=3.9.0
Export to OpenVINO openvino-dev>=2023.0
Logging (TensorBoard) tensorboard>=2.4.1
Logging (ClearML) clearml>=1.2.0
Logging (Comet) comet_ml
Augmentations albumentations>=1.0.3
COCO evaluation pycocotools>=2.0.6

Post-Install Verification

python detect.py --weights yolov5s.pt --source data/images/bus.jpg
image 1/1 data/images/bus.jpg: 640x480 4 persons, 1 bus, 12.3ms
Results saved to runs/detect/exp

If the command downloads yolov5s.pt automatically, loads the model, runs inference, and saves annotated images to runs/detect/exp, your installation is working.

Warning

On Windows, opencv-python may conflict with opencv-python-headless. If you get import errors, uninstall both and reinstall only one: pip install opencv-python-headless.

Install Troubleshooting

Q: ModuleNotFoundError: No module named 'ultralytics'

The ultralytics package is a required dependency. Install it:

pip install ultralytics>=8.2.64

Q: CUDA out of memory during inference

Reduce image size or use a smaller model:

python detect.py --weights yolov5n.pt --imgsz 320

Q: Model download fails or hangs

Ensure network access and that GitHub releases are reachable. Pre-download weights manually:

python -c "from utils.downloads import attempt_download; attempt_download('yolov5s.pt')"

Q: Slow inference on CPU

Use --half for FP16 (GPU only) or export to ONNX/OpenVINO for optimized CPU inference:

python export.py --weights yolov5s.pt --include onnx openvino

Q: ImportError related to torch

Verify your PyTorch installation:

python -c "import torch; print(torch.__version__); print(torch.cuda.is_available())"

3. Configuration

Model Selection

YOLOv5 provides five model sizes trading speed for accuracy:

Model Parameters Size (MB) Speed (ms) Use Case
yolov5n.pt 1.9M 3.9 ~6 Edge / mobile / real-time
yolov5s.pt 7.2M 14.1 ~8 General purpose, balanced
yolov5m.pt 21.2M 40.8 ~12 Higher accuracy
yolov5l.pt 46.5M 89.3 ~17 Accuracy-focused
yolov5x.pt 86.7M 166.0 ~25 Maximum accuracy

Extended P6 models (1280px input, extra detection layer for large objects): yolov5n6, yolov5s6, yolov5m6, yolov5l6, yolov5x6.

Segmentation models use the -seg suffix: yolov5s-seg.pt, yolov5m-seg.pt, etc.

Classification models use the -cls suffix: yolov5s-cls.pt, yolov5m-cls.pt, etc.

Dataset Configuration (YAML)

YOLOv5 uses YAML files to define datasets. Example from data/coco128.yaml:

path: ../datasets/coco128  # dataset root dir
train: images/train2017     # train images (relative to 'path')
val: images/train2017       # val images
test:                       # test images (optional)

# Classes
names:
  0: person
  1: bicycle
  2: car
  # ... 80 classes total

Note

Datasets are expected in ../datasets/ relative to the YOLOv5 root directory. Set the YOLOv5_DATASETS_DIR environment variable to override this default location.

Bundled Dataset Configs

Config File Dataset Classes Notes
data/coco.yaml COCO 80 Full COCO 2017 (118K train images)
data/coco128.yaml COCO128 80 Tiny 128-image subset for testing
data/coco128-seg.yaml COCO128-seg 80 Segmentation variant of COCO128
data/VOC.yaml Pascal VOC 20 VOC 2007+2012
data/Argoverse.yaml Argoverse-HD 8 Autonomous driving
data/VisDrone.yaml VisDrone 10 Drone imagery
data/GlobalWheat2020.yaml Global Wheat 1 Wheat head detection
data/Objects365.yaml Objects365 365 Large-scale detection
data/SKU-110K.yaml SKU-110K 1 Densely packed retail
data/xView.yaml xView 60 Satellite imagery
data/ImageNet.yaml ImageNet 1000 Classification
data/ImageNet10.yaml ImageNet-10 10 Tiny ImageNet subset
data/ImageNet100.yaml ImageNet-100 100 ImageNet subset
data/ImageNet1000.yaml ImageNet-1000 1000 Full ImageNet

Environment Variables

Variable Default Description
YOLOv5_DATASETS_DIR ../datasets Root directory for datasets
YOLOv5_AUTOINSTALL True Auto-install missing packages
YOLOv5_VERBOSE True Enable verbose logging
PIN_MEMORY True Pin dataloader memory for faster GPU transfer

For the full configuration reference (hyperparameters, model architecture YAML, all environment variables), see the Admin Guide.


4. Core Usage

Object Detection — detect.py

Run inference on images, videos, directories, webcams, streams, or URLs:

# Image
python detect.py --weights yolov5s.pt --source image.jpg

# Video
python detect.py --weights yolov5s.pt --source video.mp4

# Webcam
python detect.py --weights yolov5s.pt --source 0

# Directory
python detect.py --weights yolov5s.pt --source path/to/images/

# Screenshot
python detect.py --weights yolov5s.pt --source screen

# URL / stream
python detect.py --weights yolov5s.pt --source 'https://youtu.be/LNwODJXcvt4'
python detect.py --weights yolov5s.pt --source 'rtsp://example.com/media.mp4'

# Glob pattern
python detect.py --weights yolov5s.pt --source 'path/*.jpg'

Tip

Use --nosave to skip saving output images (useful for benchmarking). Use --view-img to display results live in a window.

Detection CLI Reference

Flag Type Default Description
--weights str yolov5s.pt Model path or Triton URL
--source str data/images Input source (file/dir/URL/glob/screen/webcam)
--data str data/coco128.yaml Dataset YAML (for class names)
--imgsz int 640 Inference image size (pixels)
--conf-thres float 0.25 Confidence threshold
--iou-thres float 0.45 NMS IoU threshold
--max-det int 1000 Maximum detections per image
--device str (auto) CUDA device (0, 0,1,2,3, or cpu)
--view-img flag off Display results live
--save-txt flag off Save results to *.txt
--save-format int 0 Save format: 0 = YOLO, 1 = Pascal-VOC
--save-csv flag off Save results as CSV
--save-conf flag off Include confidence in saved labels
--save-crop flag off Save cropped detection boxes
--nosave flag off Do not save output images/videos
--classes int[] all Filter by class index(es)
--agnostic-nms flag off Class-agnostic NMS
--augment flag off Test-time augmentation
--visualize flag off Visualize feature maps
--update flag off Strip optimizer from weights
--project str runs/detect Output directory
--name str exp Experiment name (subdirectory)
--exist-ok flag off Reuse existing directory
--line-thickness int 3 Bounding box line width (pixels)
--hide-labels flag off Hide class labels
--hide-conf flag off Hide confidence scores
--half flag off FP16 half-precision (GPU only)
--dnn flag off Use OpenCV DNN for ONNX
--vid-stride int 1 Video frame-rate stride

Multi-Format Inference

YOLOv5's DetectMultiBackend transparently loads models in any exported format — pass the exported file to --weights:

python detect.py --weights yolov5s.pt                 # PyTorch
python detect.py --weights yolov5s.torchscript         # TorchScript
python detect.py --weights yolov5s.onnx               # ONNX
python detect.py --weights yolov5s_openvino_model      # OpenVINO
python detect.py --weights yolov5s.engine              # TensorRT
python detect.py --weights yolov5s.mlpackage           # CoreML (macOS)
python detect.py --weights yolov5s_saved_model         # TF SavedModel
python detect.py --weights yolov5s.pb                  # TF GraphDef
python detect.py --weights yolov5s.tflite              # TF Lite
python detect.py --weights yolov5s_paddle_model        # PaddlePaddle

Training — train.py

Train a detection model from pretrained weights or from scratch:

# Fine-tune YOLOv5s on COCO128 dataset
python train.py --weights yolov5s.pt --data coco128.yaml --epochs 100 --batch-size 16 --imgsz 640
train: weights=yolov5s.pt, cfg=, data=coco128.yaml, hyp=data/hyps/hyp.scratch-low.yaml, epochs=100, batch_size=16
                 Class     Images  Instances          P          R      mAP50   mAP50-95
                   all        128        929      0.732      0.681      0.724      0.468

Important

Set --batch-size -1 to enable autobatch, which automatically determines the largest batch size that fits in GPU memory.

Training CLI Reference

Flag Type Default Description
--weights str (required) Pretrained weights path
--cfg str (none) Model architecture YAML
--data str (required) Dataset YAML path
--hyp str hyp.scratch-low.yaml Hyperparameters YAML path
--epochs int 100 Total training epochs
--batch-size int 16 Batch size (-1 for autobatch)
--imgsz int 640 Training image size
--rect flag off Rectangular training
--resume str False Resume from checkpoint path or True for latest
--nosave flag off Only save final checkpoint
--noval flag off Only validate final epoch
--noautoanchor flag off Disable AutoAnchor
--noplots flag off Disable plot generation
--evolve int (none) Evolve hyperparameters for N generations
--evolve_population str (none) Location for loading population
--resume_evolve str (none) Resume evolve from last generation
--bucket str (none) gsutil bucket
--cache str (none) Cache images: ram or disk
--image-weights flag off Weighted image selection
--device str (auto) CUDA device
--multi-scale flag off Vary image size +/- 50%
--single-cls flag off Treat all classes as one
--optimizer str SGD Optimizer (SGD, Adam, AdamW)
--sync-bn flag off SyncBatchNorm (DDP only)
--workers int 8 Dataloader workers per rank
--cos-lr flag off Cosine LR scheduler
--label-smoothing float 0.0 Label smoothing epsilon
--patience int 100 EarlyStopping epochs
--freeze int[] (none) Freeze layers (e.g., 10 for backbone)
--save-period int (none) Save checkpoint every N epochs
--seed int 0 Global training seed
--local_rank int (auto) DDP multi-GPU rank
--quad flag off Quad dataloader
--ndjson-console flag off NDJSON console logging
--ndjson-file flag off NDJSON file logging
--entity str (none) Logger entity (W&B/Comet)
--upload_dataset str False Upload dataset to logger
--bbox_interval int (none) Bounding box logging interval
--artifact_alias str latest Dataset artifact version

Multi-GPU Training (DDP)

python -m torch.distributed.run --nproc_per_node 4 train.py \
  --weights yolov5s.pt --data coco.yaml --epochs 100 --batch-size 64 --device 0,1,2,3

Warning

When using DDP, the --batch-size is the total across all GPUs (divided evenly). With 4 GPUs and --batch-size 64, each GPU processes 16 images per batch. The --workers value is per rank.

Validation — val.py

Evaluate model performance on a validation or test split:

python val.py --weights yolov5s.pt --data coco128.yaml --imgsz 640
                 Class     Images  Instances          P          R      mAP50   mAP50-95
                   all        128        929      0.732      0.681      0.724      0.468
Speed: 0.5ms pre-process, 4.8ms inference, 1.2ms NMS per image at shape (32, 3, 640, 640)

Validation CLI Reference

Flag Type Default Description
--data str (required) Dataset YAML path
--weights str (required) Model path(s)
--batch-size int 32 Batch size
--imgsz int 640 Image size
--conf-thres float 0.001 Confidence threshold
--iou-thres float 0.6 NMS IoU threshold
--max-det int 300 Max detections per image
--task str val Task: train, val, test, speed, or study
--device str (auto) CUDA device
--single-cls flag off Single-class mode
--augment flag off Augmented inference
--verbose flag off Report mAP by class
--save-txt flag off Save results to text
--save-hybrid flag off Save label + prediction hybrid
--save-conf flag off Save confidences
--save-json flag off Save COCO-JSON results
--half flag off FP16 inference
--dnn flag off OpenCV DNN backend

Model Export — export.py

Export trained models to deployment formats:

python export.py --weights yolov5s.pt --include torchscript onnx openvino engine
export: weights=yolov5s.pt, include=['torchscript', 'onnx', 'openvino', 'engine']
YOLOv5s summary: 213 layers, 7225885 parameters
PyTorch: starting export...
TorchScript: starting export with torch X.X.X...
ONNX: starting export with onnx X.X.X...

Supported Export Formats

Format --include value Output Notes
PyTorch (default) *.pt Native format
TorchScript torchscript *.torchscript Mobile-optimizable
ONNX onnx *.onnx Cross-platform
OpenVINO openvino *_openvino_model/ Intel hardware
TensorRT engine *.engine NVIDIA GPU
CoreML coreml *.mlpackage Apple devices (macOS only)
TF SavedModel saved_model *_saved_model/ TensorFlow Serving
TF GraphDef pb *.pb Frozen graph
TF Lite tflite *.tflite Mobile/edge
TF Edge TPU edgetpu *_edgetpu.tflite Google Coral
TF.js tfjs *_web_model/ Browser
PaddlePaddle paddle *_paddle_model/ Baidu ecosystem

Note

Edge TPU and TF.js exports are supported for export but not for YOLOv5's built-in inference pipeline. These formats are intended for use in their respective runtime environments.

Export CLI Reference

Flag Type Default Description
--weights str yolov5s.pt Model weights
--imgsz int 640 Image size
--batch-size int 1 Batch size
--device str cpu Export device
--half flag off FP16 export
--inplace flag off Detect() inplace mode
--keras flag off Use Keras for TF
--optimize flag off TorchScript mobile optimization
--int8 flag off INT8 quantization (CoreML/TF/OpenVINO)
--per-tensor flag off TF per-tensor quantization
--dynamic flag off Dynamic axes (ONNX/TF/TensorRT)
--cache str (none) TensorRT timing cache file
--simplify flag off ONNX simplifier
--mlmodel flag off CoreML export in *.mlmodel format
--opset int 17 ONNX opset version
--verbose flag off TensorRT verbose logging
--workspace int 4 TensorRT workspace (GB)
--nms flag off Add NMS to TF model
--agnostic-nms flag off Add agnostic NMS to TF model
--topk-per-class int 100 TF.js NMS: topk per class
--topk-all int 100 TF.js NMS: topk for all classes
--iou-thres float 0.45 TF.js NMS: IoU threshold
--conf-thres float 0.25 TF.js NMS: confidence threshold
--include str[] (required) Export format(s)

Instance Segmentation

YOLOv5 supports instance segmentation via dedicated scripts in the segment/ directory:

# Predict with segmentation model
python segment/predict.py --weights yolov5s-seg.pt --source data/images/bus.jpg

# Train segmentation model
python segment/train.py --weights yolov5s-seg.pt --data coco128-seg.yaml --epochs 100

# Validate segmentation model
python segment/val.py --weights yolov5s-seg.pt --data coco128-seg.yaml

Segmentation-specific flags (in addition to the standard detection flags):

Flag Type Default Description
--retina-masks flag off Plot masks in native resolution
--mask-ratio int 4 Downsample masks to save memory (train only)
--no-overlap flag off Non-overlapping masks (faster, slightly lower mAP)

Tip

Use --retina-masks for higher-quality mask visualization at the cost of slightly slower post-processing.

Image Classification

Train and predict with classification models:

# Train classifier
python classify/train.py --model yolov5s-cls.pt --data imagenette160 --epochs 10 --imgsz 224

# Predict
python classify/predict.py --weights yolov5s-cls.pt --source image.jpg

# Validate
python classify/val.py --weights yolov5s-cls.pt --data imagenette160

Classification supports torchvision pretrained models as starting points:

python classify/train.py --model resnet50 --data cifar100 --epochs 10

Note

Classification uses 224x224 image size by default (vs 640x640 for detection/segmentation). The --optimizer default is Adam with lr0=0.001 (vs SGD with lr0=0.01 for detection).

Classification-Specific Flags

Flag Type Default Description
--model str yolov5s-cls.pt Model name or path
--pretrained str True Use pretrained weights
--lr0 float 0.001 Initial learning rate
--decay float 5e-5 Weight decay
--cutoff int (none) Layer cutoff for Classify head
--dropout float (none) Dropout fraction
--label-smoothing float 0.1 Label smoothing epsilon
--verbose flag off Verbose mode

PyTorch Hub

Load YOLOv5 models directly without cloning the repository:

import torch

# Load a pretrained model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)

# Inference on an image
results = model('https://ultralytics.com/images/zidane.jpg')

# Show results
results.show()
results.print()

# Access detections as pandas DataFrame
df = results.pandas().xyxy[0]
print(df)
   xmin    ymin    xmax    ymax  confidence  class  name
0  749.5   43.5  1148.0   704.0       0.874      0  person
1  114.2  198.7   1148.0  708.9       0.624      0  person

Available Hub models: yolov5n, yolov5s, yolov5m, yolov5l, yolov5x, yolov5n6, yolov5s6, yolov5m6, yolov5l6, yolov5x6.

Load a custom-trained model:

model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt')

Benchmarks

Compare model performance across all export formats:

python benchmarks.py --weights yolov5s.pt --imgsz 640
Benchmarks complete (120.5s)
     Format  Size (MB)  mAP50-95  Inference time (ms)
   PyTorch       14.1    0.3720                  8.2
TorchScript       28.1    0.3720                  7.5
       ONNX       28.0    0.3720                  9.1
   OpenVINO       28.2    0.3720                  6.3
   TensorRT       18.5    0.3720                  3.1
Flag Type Default Description
--weights str yolov5s.pt Weights path
--imgsz int 640 Inference size
--batch-size int 1 Batch size
--data str data/coco128.yaml Dataset YAML
--device str (auto) CUDA device
--half flag off FP16 inference
--test flag off Test exports only (no inference)
--pt-only flag off Test PyTorch only
--hard-fail str/bool False Fail on error or below metric floor

5. Common Tasks

Train a Custom Object Detection Model

Goal: Train YOLOv5 on your own labeled dataset.

Prerequisites: Images with YOLO-format labels (class x_center y_center width height, normalized 0-1).

  1. Organize your dataset:

    datasets/
    └── my_dataset/
        ├── images/
        │   ├── train/
        │   └── val/
        └── labels/
            ├── train/
            └── val/
    
  2. Create a dataset YAML:

    path: ../datasets/my_dataset
    train: images/train
    val: images/val
    
    names:
      0: cat
      1: dog
    
  3. Train:

    python train.py --weights yolov5s.pt --data my_dataset.yaml --epochs 100 --imgsz 640
    
  4. Verify: Check runs/train/exp/ for training curves, confusion matrix, and best.pt.

If it fails: Ensure label files exist alongside images with matching filenames (.txt extension). Verify label format with no empty lines.

Resume Interrupted Training

# Resume most recent run
python train.py --resume

# Resume a specific run
python train.py --resume runs/train/exp5/weights/last.pt

Train From Scratch (No Pretrained Weights)

python train.py --weights '' --cfg yolov5s.yaml --data coco128.yaml --epochs 300 \
  --hyp data/hyps/hyp.scratch-low.yaml

Freeze Backbone for Transfer Learning

# Freeze the first 10 layers (backbone)
python train.py --weights yolov5s.pt --data my_dataset.yaml --freeze 10

Hyperparameter Evolution

Automatically search for optimal hyperparameters:

python train.py --weights yolov5s.pt --data coco128.yaml --evolve 300

Results are saved to runs/train/evolve/ with hyp_evolve.yaml containing the best configuration.

Run Detection on Video with Custom Thresholds

python detect.py --weights best.pt --source video.mp4 \
  --conf-thres 0.5 --iou-thres 0.3 --max-det 50 \
  --save-txt --save-conf

Filter Detections by Class

# Only detect persons (class 0) and cars (class 2)
python detect.py --weights yolov5s.pt --source image.jpg --classes 0 2

Export and Run with TensorRT

# Export
python export.py --weights yolov5s.pt --include engine --half --device 0

# Run inference with exported engine
python detect.py --weights yolov5s.engine --source image.jpg --device 0

Export with Dynamic Batch Size

python export.py --weights yolov5s.pt --include onnx --dynamic

Serve Model via REST API

python utils/flask_rest_api/restapi.py --port 5000 --model yolov5s

Send an inference request:

curl -X POST -F "image=@image.jpg" http://localhost:5000/v1/object-detection/yolov5s
[{"xmin": 749.5, "ymin": 43.5, "xmax": 1148.0, "ymax": 704.0, "confidence": 0.874, "class": 0, "name": "person"}]

Cache Images for Faster Training

# Cache to RAM (fastest, requires sufficient memory)
python train.py --weights yolov5s.pt --data coco128.yaml --cache ram

# Cache to disk
python train.py --weights yolov5s.pt --data coco128.yaml --cache disk

Use Cosine Learning Rate Scheduler

python train.py --weights yolov5s.pt --data coco128.yaml --cos-lr

Save COCO-JSON Results for Official Evaluation

python val.py --weights yolov5s.pt --data coco.yaml --save-json

Save Detection Results as CSV

python detect.py --weights yolov5s.pt --source images/ --save-csv

6. Troubleshooting

Diagnostic Decision Tree

Problem?
├── Training fails → Check GPU memory, dataset format, YAML path
├── Poor accuracy → Check dataset quality, try larger model, more epochs
├── Slow inference → Try smaller model, --half, export to TensorRT/OpenVINO
├── Export fails → Check optional dependency installed, compatible versions
└── Import error → Check Python/PyTorch versions, reinstall requirements

Error: FileNotFoundError: Source path '...' does not exist

Cause: The --source path does not exist on the filesystem.

Solution:

  1. Verify the file or directory path exists
  2. Check for typos in the path
  3. For URL sources, ensure the URL is accessible

Prevention: Use absolute paths or verify paths before running.

Error: RuntimeError: failed to load ONNX file: ...

Cause: The ONNX file is corrupted or was generated with an incompatible opset version.

Solution:

  1. Re-export the model: python export.py --weights yolov5s.pt --include onnx --opset 17
  2. Ensure onnx and onnxruntime versions are compatible

Prevention: Always verify exports with python benchmarks.py --weights yolov5s.onnx.

Error: NotImplementedError: ERROR: YOLOv5 TF.js inference is not supported

Cause: TF.js models cannot be used for inference within YOLOv5's Python pipeline.

Solution: Use the exported TF.js model directly in a JavaScript/browser environment. For Python inference, use TF SavedModel or TFLite instead.

Error: CUDA out of memory

Cause: Batch size or image size is too large for GPU memory.

Solution:

  1. Reduce --batch-size (or use -1 for autobatch)
  2. Reduce --imgsz
  3. Use a smaller model variant
  4. Use --cache ram to reduce dataloader overhead

Prevention: Monitor GPU memory with nvidia-smi. Use autobatch (--batch-size -1).

Error: aten::nonzero not supported on MPS backend

Cause: Apple Silicon MPS backend does not support all PyTorch operations used by YOLOv5. (GitHub issue #8508)

Solution: Fall back to CPU:

python detect.py --weights yolov5s.pt --device cpu

Prevention: Use CUDA GPUs for full feature support. MPS support is partial.

Warning

Apple MPS backend has known compatibility issues with YOLOv5. Use --device cpu if you encounter MPS-related errors.

Error: Cannot run parallel inference with DDP

Cause: DDP is designed for training, not inference. (GitHub issue #9687)

Solution: Use single-GPU inference or batch inference instead of DDP for prediction.

Error: Dataset not found

Cause: The dataset path in the YAML file does not exist. Auto-download may have failed.

Solution:

  1. Check the path field in your dataset YAML
  2. Ensure ../datasets/ directory exists relative to your YOLOv5 root
  3. Set YOLOv5_DATASETS_DIR to a custom location
  4. Manually download the dataset

Error: Optimizer ... not implemented

Cause: Invalid optimizer name passed via --optimizer.

Solution: Use one of the supported optimizers: SGD, Adam, or AdamW.

Error: ValueError with ClearML authentication

Cause: ClearML is installed but not configured with valid credentials. (GitHub issue #9877)

Solution: Run clearml-init to configure credentials, or uninstall ClearML if not needed:

pip uninstall clearml

Caution

Training and validation commands auto-detect installed loggers (ClearML, Comet, W&B). If a logger package is installed but not configured, it may cause authentication errors. Either configure the logger or uninstall the package.

Error: NotImplementedError: --task ... not in ("train", "val", "test", "speed", "study")

Cause: Invalid --task value passed to val.py or segment/val.py.

Solution: Use one of the supported task values: train, val, test, speed, or study.

Error: FileNotFoundError: ... does not exist during data loading

Cause: An image or label file referenced in the dataset is missing.

Solution:

  1. Verify all images exist at the paths listed in your dataset
  2. Run label verification: check for corresponding .txt files in labels directory
  3. Re-download the dataset if using a built-in config

Prevention: Use --cache to validate all images before training starts.


7. FAQ

Q: What image formats does YOLOv5 support for inference?

Images: bmp, dng, jpeg, jpg, mpo, png, tif, tiff, webp, pfm. Videos: asf, avi, gif, m4v, mkv, mov, mp4, mpeg, mpg, ts, wmv, webm.

Q: How do I use multiple GPUs for training?

Use DDP with torch.distributed.run:

python -m torch.distributed.run --nproc_per_node 4 train.py --device 0,1,2,3 --batch-size 64

For inference, specify a single device: --device 0.

Q: Can I train on a CPU?

Yes, pass --device cpu. Training will be significantly slower than GPU. This is mainly useful for testing or very small datasets.

Q: How do I use custom pretrained weights?

Pass the path to your .pt file via --weights:

python train.py --weights path/to/my_model.pt --data my_data.yaml

Q: What is the difference between --conf-thres in detect.py vs val.py?

detect.py uses 0.25 default (higher, for clean visual output). val.py uses 0.001 default (very low, to compute full precision-recall curves for mAP evaluation).

Q: How do I convert my model to ONNX for deployment?

python export.py --weights best.pt --include onnx --simplify

Q: What is rectangular training (--rect)?

Rectangular training pads images to the minimum size rather than square, reducing wasted computation on non-square images. It can improve training speed but may slightly affect accuracy.

Q: How does EarlyStopping work?

Training stops if fitness (mAP@0.5 + mAP@0.5:0.95) does not improve for --patience consecutive epochs (default: 100). The best weights are always saved to best.pt regardless.

Q: Can I use YOLOv5 for real-time video detection?

Yes. Use a webcam source and a fast model:

python detect.py --weights yolov5n.pt --source 0 --view-img

Q: What are the P6 models (e.g., yolov5s6)?

P6 models add an extra detection layer (P6) for large objects. They use 1280px input by default and are better suited for high-resolution images with objects at various scales.

Q: How do I access detection results programmatically?

Use --save-txt for label files, --save-csv for CSV, or --save-json (val.py) for COCO-JSON format. For Python programmatic access, use PyTorch Hub:

results = model(img)
df = results.pandas().xyxy[0]  # DataFrame: xmin, ymin, xmax, ymax, confidence, class, name

Q: What hyperparameter files are included?

File Use Case
data/hyps/hyp.scratch-low.yaml Low augmentation (default)
data/hyps/hyp.scratch-med.yaml Medium augmentation
data/hyps/hyp.scratch-high.yaml High augmentation
data/hyps/hyp.no-augmentation.yaml No built-in augmentation (for Albumentations)
data/hyps/hyp.Objects365.yaml Evolved for Objects365
data/hyps/hyp.VOC.yaml Evolved for Pascal VOC

Q: How do I check model FLOPs and parameters?

python models/yolo.py --cfg yolov5s.yaml

Or use thop during training — FLOPs are logged automatically.

Q: Can I ensemble multiple models?

Yes, pass multiple weights to val.py:

python val.py --weights yolov5s.pt yolov5m.pt --data coco.yaml

The attempt_load() function in models/experimental.py creates an Ensemble that averages predictions.

Q: What is --vid-stride?

It controls how many video frames to skip between processed frames. --vid-stride 2 processes every other frame, doubling effective throughput at the cost of temporal resolution.