Ultralytics YOLO (v8.4.38) is the official Python package for the YOLO family of real-time computer vision models. It provides a single, unified toolkit to train, validate, predict, track, benchmark, and export models across five computer vision tasks — object detection, instance segmentation, image classification, pose estimation, and oriented bounding box (OBB) detection — from one CLI command or a few lines of Python.
The package ships pre-trained weights for YOLO versions 3 through 26, plus specialized architectures like SAM, SAM3, FastSAM, RTDETR, YOLO-World, YOLOE, and YOLOv-NAS. Models export to 18+ deployment formats, from ONNX and TensorRT to CoreML, TFLite, Edge TPU, and more.
This guide covers the CLI (yolo), the Python API (from ultralytics import YOLO), the 15 ready-to-run Solutions, and every configuration key you will touch in day-to-day work.
1. Quick Start
What is Ultralytics YOLO?
Ultralytics YOLO is a Python library and CLI that wraps every YOLO model generation into one consistent interface. Whether you want to detect objects, segment instances, classify images, estimate poses, or detect rotated bounding boxes, the workflow is the same: load a model, run a mode, get results.
Key features
- 5 tasks: detect, segment, classify, pose, obb
- 6 modes: train, val, predict, export, track, benchmark
- 18+ export formats: PyTorch, ONNX, TensorRT, CoreML, TFLite, OpenVINO, and more
- 15 prebuilt Solutions: object counting, heatmaps, speed estimation, security alarms, parking management, and more
- Multi-tracker support: ByteTrack and BoTSORT
- Full CLI and Python API parity: everything available on the command line is available in Python, and vice versa
Prerequisites
| Requirement | Minimum | Recommended |
|---|---|---|
| Python | 3.8 | 3.10+ |
| PyTorch | 1.8 | 2.0+ |
| OS | Linux, macOS, Windows | Ubuntu 20.04+ / macOS 12+ / Windows 10+ |
| RAM | 4 GB | 16 GB+ |
| GPU | Not required (CPU works) | NVIDIA with CUDA 11.8+ |
Install in one line
pip install ultralytics
Run your first prediction
yolo predict model=yolo26n.pt source="https://ultralytics.com/images/bus.jpg"
Expected output:
image 1/1 ...bus.jpg: 640x480 4 persons, 1 bus, 23.5ms
Speed: 2.1ms preprocess, 23.5ms inference, 1.8ms postprocess per image at shape (1, 3, 640, 480)
Results saved to runs/detect/predict
Or in Python:
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model.predict("https://ultralytics.com/images/bus.jpg")
for r in results:
print(r.boxes.xyxy) # bounding boxes
print(r.boxes.conf) # confidence scores
print(r.boxes.cls) # class IDs
Tip
New to YOLO? Start with
yolo26n.pt(the nano model) for fast experimentation. Move toyolo26s.pt,yolo26m.pt,yolo26l.pt, oryolo26x.ptas you need more accuracy. The letter suffix indicates model size: nano < small < medium < large < extra-large.
What to try next
- Train a custom model — see Section 5: Common Tasks
- Export for deployment — see Model Export in Section 4
- Run Solutions — see Solutions in Section 4
- Configure all settings — see Section 3: Configuration
2. Installation
pip (recommended)
pip install ultralytics
This installs the ultralytics package plus all core dependencies (PyTorch, OpenCV, NumPy, Pillow, etc.). Missing optional dependencies are auto-installed at runtime when needed (controlled by the YOLO_AUTOINSTALL environment variable).
pip from source (editable / development)
git clone https://github.com/ultralytics/ultralytics.git
cd ultralytics
pip install -e .
This installs in editable mode so changes to the source are immediately reflected.
Important
When installing from source, make sure you are on the
mainbranch for stable releases. Thedevelopbranch may contain breaking changes.
conda
conda install -c conda-forge ultralytics
Docker
Ultralytics provides multiple Docker images for different use cases:
| Dockerfile | Use Case | GPU |
|---|---|---|
Dockerfile |
Full GPU environment | Yes (CUDA) |
Dockerfile-cpu |
CPU-only, lightweight | No |
Dockerfile-arm64 |
ARM64 platforms | No |
Dockerfile-nvidia-arm64 |
NVIDIA ARM64 (Jetson L4T) | Yes |
Dockerfile-jetson-jetpack4 |
Jetson JetPack 4.x | Yes |
Dockerfile-jetson-jetpack5 |
Jetson JetPack 5.x | Yes |
Dockerfile-jetson-jetpack6 |
Jetson JetPack 6.x | Yes |
Dockerfile-conda |
Conda-based environment | Yes |
Dockerfile-jupyter |
Jupyter notebook server | Yes |
Dockerfile-export |
Export-only (ONNX, TRT, etc.) | Yes |
Dockerfile-python |
Minimal Python runtime | No |
Dockerfile-python-export |
Python + export deps | No |
Dockerfile-runner |
CI runner (GPU) | Yes |
Dockerfile-runner-cpu |
CI runner (CPU) | No |
Pull and run the GPU image:
docker pull ultralytics/ultralytics:latest
docker run -it --gpus all ultralytics/ultralytics:latest
Pull and run the CPU-only image:
docker pull ultralytics/ultralytics:latest-cpu
docker run -it ultralytics/ultralytics:latest-cpu
Run with a local directory mounted:
docker run -it --gpus all -v /path/to/data:/data ultralytics/ultralytics:latest
System requirements
| Component | CPU-only | GPU (recommended) |
|---|---|---|
| Python | 3.8–3.12 | 3.8–3.12 |
| PyTorch | 1.8+ | 2.0+ with CUDA |
| CUDA | N/A | 11.8 or 12.x |
| cuDNN | N/A | 8.x+ |
| RAM | 4 GB minimum | 16 GB+ |
| Disk | 2 GB for package + models | 10 GB+ for training |
| GPU VRAM | N/A | 4 GB+ (8 GB+ recommended) |
Post-install verification
Run the built-in system check:
yolo checks
Expected output:
Ultralytics 8.4.38 🚀 Python-3.10.12 torch-2.1.0+cu121 CUDA:0 (NVIDIA GeForce RTX 4090, 24564MiB)
Setup complete ✅ (32 CPUs, 62.7 GB RAM, 456.2/931.5 GB disk)
Verify the Python API:
import ultralytics
ultralytics.checks()
print(ultralytics.__version__) # 8.4.38
Warning
If
yolo checksreports a PyTorch version without CUDA support (e.g.,torch-2.1.0+cpu), you need to reinstall PyTorch with CUDA. See PyTorch Get Started and install the CUDA variant before installing ultralytics.
Platform-specific notes
Windows:
- Use
pip install ultralyticsin a virtual environment or Anaconda prompt. - Visual C++ Build Tools may be required for some optional dependencies.
- Long path support should be enabled (Settings > Developer Settings > Enable long paths).
macOS (Apple Silicon):
- PyTorch supports MPS (Metal Performance Shaders) acceleration on M1/M2/M3/M4 chips.
- Install with
pip install ultralytics— PyTorch will use MPS automatically. - CoreML export is natively supported.
Linux:
- For GPU support, install NVIDIA drivers and CUDA toolkit first.
- On headless servers, set
DISPLAYor useshow=Falseto avoid display errors.
Raspberry Pi / ARM:
- Use
Dockerfile-arm64or install directly with pip. - Expect significantly slower inference; use nano models (
yolo26n.pt). - NCNN export is recommended for best ARM performance.
NVIDIA Jetson:
- Use the appropriate JetPack Dockerfile (4, 5, or 6).
- TensorRT export is recommended for best Jetson performance.
Install troubleshooting
Error: No module named 'ultralytics'
Cause: Package not installed in the active Python environment.
Solution:
pip install ultralytics
# Or verify you're using the right Python:
which python
python -m pip install ultralytics
Error: ModuleNotFoundError: No module named 'torch'
Cause: PyTorch not installed or not compatible with your system.
Solution:
# CPU only:
pip install torch torchvision
# CUDA 11.8:
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118
# CUDA 12.1:
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
Error: CUDA not available
Cause: PyTorch was installed without CUDA support, or NVIDIA drivers are missing.
Solution:
# Check CUDA availability:
python -c "import torch; print(torch.cuda.is_available())"
# If False, reinstall PyTorch with CUDA:
pip uninstall torch torchvision
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
Error: pip install fails with compilation errors
Cause: Missing build tools for C extensions in dependencies.
Solution (Ubuntu/Debian):
sudo apt-get update
sudo apt-get install -y build-essential python3-dev
Solution (Windows): Install Visual C++ Build Tools.
Error: ImportError: libGL.so.1: cannot open shared object file
Cause: OpenCV requires GUI libraries, even in headless mode.
Solution:
# Install headless OpenCV instead:
pip uninstall opencv-python
pip install opencv-python-headless
# Or install the system library:
sudo apt-get install -y libgl1-mesa-glx
Error: OSError: [Errno 28] No space left on device
Cause: Insufficient disk space for model downloads or training output.
Solution: Free disk space or change the output directory:
yolo train data=coco8.yaml project=/path/with/space
Error: RuntimeError: CUDA out of memory
Cause: Model or batch size exceeds available GPU memory.
Solution:
# Reduce batch size:
yolo train data=coco8.yaml batch=4
# Use a smaller model:
yolo train model=yolo26n.pt data=coco8.yaml
# Enable automatic batch sizing:
yolo train data=coco8.yaml batch=-1
Error: Permission denied when installing
Cause: Trying to install to a system Python without root access.
Solution:
# Use a virtual environment:
python -m venv yolo_env
source yolo_env/bin/activate # Linux/macOS
# yolo_env\Scripts\activate # Windows
pip install ultralytics
Error: Package version conflicts
Cause: Conflicting dependency versions.
Solution:
# Create a clean environment:
python -m venv clean_env
source clean_env/bin/activate
pip install ultralytics
Error: SSL: CERTIFICATE_VERIFY_FAILED during model download
Cause: Corporate firewall or proxy blocking HTTPS.
Solution:
# Download model manually and use local path:
wget https://github.com/ultralytics/assets/releases/download/v8.4.0/yolo26n.pt
yolo predict model=./yolo26n.pt source=image.jpg
# Or set proxy:
export HTTPS_PROXY=http://proxy.company.com:8080
3. Configuration
The yolo cfg command
View all default configuration values:
yolo cfg
This prints every available configuration key with its default value and description.
Settings management
View current persistent settings:
yolo settings
Update a setting:
yolo settings runs_dir=/my/custom/runs
yolo settings datasets_dir=/my/datasets
Reset all settings to defaults:
yolo settings reset
In Python:
from ultralytics import settings
# View current settings
print(settings)
# Update settings
settings.update({"runs_dir": "/my/custom/runs"})
Configuration argument categories
Arguments are passed as key=value pairs on the CLI or as keyword arguments in Python. The following tables organize all configuration keys by category.
Training arguments
| Key | Type | Default | Description |
|---|---|---|---|
model |
str | None |
Path to model file (.pt, .yaml) |
data |
str | None |
Path to dataset config (.yaml) |
epochs |
int | 100 | Number of training epochs |
patience |
int | 50 | Early stopping patience (epochs without improvement) |
batch |
int | 16 | Batch size (-1 for auto) |
imgsz |
int | 640 | Input image size |
save |
bool | True | Save checkpoints and results |
save_period |
int | -1 | Save checkpoint every N epochs (-1 = disabled) |
workers |
int | 8 | Dataloader worker threads |
project |
str | None |
Project directory name |
name |
str | None |
Run name |
exist_ok |
bool | False | Allow overwriting existing run directory |
verbose |
bool | True | Verbose output |
seed |
int | 0 | Random seed for reproducibility |
deterministic |
bool | True | Enable deterministic mode |
single_cls |
bool | False | Treat all classes as one class |
rect |
bool | False | Rectangular training (batch composition) |
cos_lr |
bool | False | Use cosine learning rate scheduler |
close_mosaic |
int | 10 | Disable mosaic augmentation for last N epochs |
resume |
bool/str | False | Resume training from checkpoint |
fraction |
float | 1.0 | Fraction of dataset to use |
profile |
bool | False | Profile ONNX/TensorRT speeds during training |
multi_scale |
float | 0.0 | Multi-scale training factor (0.0 = disabled) |
Learning rate and optimizer arguments
| Key | Type | Default | Description |
|---|---|---|---|
lr0 |
float | 0.01 | Initial learning rate |
lrf |
float | 0.01 | Final learning rate (as fraction of lr0) |
momentum |
float | 0.937 | SGD momentum / Adam beta1 |
weight_decay |
float | 0.0005 | Optimizer weight decay |
warmup_epochs |
float | 3.0 | Warmup epochs |
warmup_momentum |
float | 0.8 | Warmup initial momentum |
warmup_bias_lr |
float | 0.1 | Warmup initial bias learning rate |
nbs |
int | 64 | Nominal batch size |
Augmentation arguments
| Key | Type | Default | Description |
|---|---|---|---|
hsv_h |
float | 0.015 | HSV-Hue augmentation (fraction) |
hsv_s |
float | 0.7 | HSV-Saturation augmentation (fraction) |
hsv_v |
float | 0.4 | HSV-Value augmentation (fraction) |
degrees |
float | 0.0 | Rotation augmentation (degrees) |
translate |
float | 0.1 | Translation augmentation (fraction) |
scale |
float | 0.5 | Scale augmentation (gain) |
shear |
float | 0.0 | Shear augmentation (degrees) |
perspective |
float | 0.0 | Perspective augmentation (fraction) |
flipud |
float | 0.0 | Vertical flip probability |
fliplr |
float | 0.5 | Horizontal flip probability |
bgr |
float | 0.0 | BGR channel swap probability |
mosaic |
float | 1.0 | Mosaic augmentation probability |
mixup |
float | 0.0 | Mixup augmentation probability |
cutmix |
float | 0.0 | CutMix augmentation probability |
copy_paste |
float | 0.0 | Copy-paste augmentation probability |
Loss function arguments
| Key | Type | Default | Description |
|---|---|---|---|
box |
float | 7.5 | Box loss gain |
cls |
float | 0.5 | Class loss gain |
cls_pw |
float | 1.0 | Class BCELoss positive weight |
dfl |
float | 1.5 | Distribution focal loss gain |
Prediction arguments
| Key | Type | Default | Description |
|---|---|---|---|
source |
str | None |
Image/video/dir/glob/URL/webcam |
conf |
float | 0.25 | Confidence threshold |
iou |
float | 0.7 | NMS IoU threshold |
max_det |
int | 300 | Maximum detections per image |
half |
bool | False | Use FP16 inference |
show |
bool | False | Display results in window |
save |
bool | True | Save results |
save_txt |
bool | False | Save results as .txt files |
save_conf |
bool | False | Save confidence scores in .txt |
save_crop |
bool | False | Save cropped detections |
save_frames |
bool | False | Save video frames |
show_labels |
bool | True | Show class labels |
show_conf |
bool | True | Show confidence scores |
show_boxes |
bool | True | Show bounding boxes |
line_width |
int | None |
Bounding box line width (auto if None) |
visualize |
bool | False | Visualize model features |
augment |
bool | False | Test-time augmentation |
agnostic_nms |
bool | False | Class-agnostic NMS |
retina_masks |
bool | False | High-resolution segmentation masks |
vid_stride |
int | 1 | Video frame-rate stride |
Export arguments
| Key | Type | Default | Description |
|---|---|---|---|
format |
str | torchscript |
Export format |
keras |
bool | False | Use Keras for TF SavedModel |
optimize |
bool | False | Optimize for mobile (TorchScript) |
int8 |
bool | False | INT8 quantization |
dynamic |
bool | False | Dynamic axes for ONNX |
simplify |
bool | True | Simplify ONNX graph |
nms |
bool | False | Add NMS to exported model |
half |
bool | False | FP16 quantization |
batch |
int | 1 | Export batch size |
workspace |
float | None | TensorRT max workspace (GB) |
end2end |
bool | False | End-to-end export (include NMS) |
Validation arguments
| Key | Type | Default | Description |
|---|---|---|---|
val |
bool | True | Validate during training |
split |
str | val |
Dataset split to use (train/val/test) |
save_json |
bool | False | Save results to JSON |
plots |
bool | True | Save validation plots |
dnn |
bool | False | Use OpenCV DNN for ONNX inference |
Tracking arguments
| Key | Type | Default | Description |
|---|---|---|---|
tracker |
str | botsort.yaml |
Tracker config file |
Environment variables
| Variable | Default | Description |
|---|---|---|
YOLO_CONFIG_DIR |
Platform-specific | Override the configuration directory path |
YOLO_AUTOINSTALL |
True |
Automatically install missing dependencies at runtime |
YOLO_VERBOSE |
True |
Enable verbose logging output |
YOLO_OFFLINE |
Not set | Force offline mode (no network requests) |
OMP_NUM_THREADS |
1 (set by ultralytics) |
Number of OpenMP threads |
ULTRALYTICS_HUB_API |
https://api.ultralytics.com |
Ultralytics HUB API endpoint |
ULTRALYTICS_HUB_WEB |
https://hub.ultralytics.com |
Ultralytics HUB web URL |
ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS |
0 |
Skip dependency version checks on import |
CUDA_VISIBLE_DEVICES |
System default | Select which GPUs are visible (e.g., 0, 0,1) |
Set environment variables before running:
# Linux/macOS
export YOLO_VERBOSE=False
export CUDA_VISIBLE_DEVICES=0
# Windows (cmd)
set YOLO_VERBOSE=False
set CUDA_VISIBLE_DEVICES=0
Or in Python:
import os
os.environ["YOLO_VERBOSE"] = "False"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
Note
See the Admin Guide for the full configuration reference, including internal engine settings, dataset YAML schema details, and custom model architecture YAML formats.
4. Core Usage
Ultralytics organizes operations by task (what you're detecting) and mode (what operation you're performing). Every combination uses the same interface.
Default task-to-model mappings
| Task | Default Model | Description |
|---|---|---|
detect |
yolo26n.pt |
Object detection |
segment |
yolo26n-seg.pt |
Instance segmentation |
classify |
yolo26n-cls.pt |
Image classification |
pose |
yolo26n-pose.pt |
Pose estimation |
obb |
yolo26n-obb.pt |
Oriented bounding boxes |
Detection (predict, train, val)
Predict
CLI:
yolo detect predict model=yolo26n.pt source="image.jpg"
yolo detect predict model=yolo26n.pt source="video.mp4"
yolo detect predict model=yolo26n.pt source="path/to/images/"
yolo detect predict model=yolo26n.pt source=0 # webcam
Python:
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
# Single image
results = model("image.jpg")
# Process results
for r in results:
boxes = r.boxes
for box in boxes:
xyxy = box.xyxy[0] # [x1, y1, x2, y2]
conf = box.conf[0] # confidence
cls = box.cls[0] # class id
name = r.names[int(cls)]
print(f"{name}: {conf:.2f} at {xyxy}")
# Save annotated image
results[0].save("result.jpg")
Train
CLI:
yolo detect train data=coco8.yaml model=yolo26n.pt epochs=100 imgsz=640
Python:
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)
Validate
CLI:
yolo detect val model=yolo26n.pt data=coco8.yaml
Python:
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
metrics = model.val(data="coco8.yaml")
print(metrics.box.map) # mAP50-95
print(metrics.box.map50) # mAP50
print(metrics.box.map75) # mAP75
Segmentation
Predict
CLI:
yolo segment predict model=yolo26n-seg.pt source="image.jpg"
Python:
from ultralytics import YOLO
model = YOLO("yolo26n-seg.pt")
results = model("image.jpg")
for r in results:
masks = r.masks # segmentation masks
boxes = r.boxes # bounding boxes
if masks is not None:
for mask in masks.data:
print(mask.shape) # binary mask per instance
Train
CLI:
yolo segment train data=coco8-seg.yaml model=yolo26n-seg.pt epochs=100
Python:
from ultralytics import YOLO
model = YOLO("yolo26n-seg.pt")
results = model.train(data="coco8-seg.yaml", epochs=100)
Validate
CLI:
yolo segment val model=yolo26n-seg.pt data=coco8-seg.yaml
Python:
from ultralytics import YOLO
model = YOLO("yolo26n-seg.pt")
metrics = model.val(data="coco8-seg.yaml")
print(metrics.seg.map) # mask mAP50-95
Classification
Predict
CLI:
yolo classify predict model=yolo26n-cls.pt source="image.jpg"
Python:
from ultralytics import YOLO
model = YOLO("yolo26n-cls.pt")
results = model("image.jpg")
for r in results:
top5 = r.probs.top5 # top-5 class indices
top5conf = r.probs.top5conf # top-5 confidences
for idx, conf in zip(top5, top5conf):
print(f"{r.names[idx]}: {conf:.4f}")
Train
CLI:
yolo classify train data=imagenet10 model=yolo26n-cls.pt epochs=100
Python:
from ultralytics import YOLO
model = YOLO("yolo26n-cls.pt")
results = model.train(data="imagenet10", epochs=100)
Note
Classification datasets must be organized as directories with one subfolder per class. They do not use YAML config files like detection and segmentation.
Validate
CLI:
yolo classify val model=yolo26n-cls.pt data=imagenet10
Pose Estimation
Predict
CLI:
yolo pose predict model=yolo26n-pose.pt source="image.jpg"
Python:
from ultralytics import YOLO
model = YOLO("yolo26n-pose.pt")
results = model("image.jpg")
for r in results:
keypoints = r.keypoints
if keypoints is not None:
xy = keypoints.xy # keypoint x,y positions
conf = keypoints.conf # keypoint confidences
print(f"Detected {len(xy)} people")
for person_kpts in xy:
print(person_kpts.shape) # (17, 2) for COCO keypoints
Train
CLI:
yolo pose train data=coco8-pose.yaml model=yolo26n-pose.pt epochs=100
Python:
from ultralytics import YOLO
model = YOLO("yolo26n-pose.pt")
results = model.train(data="coco8-pose.yaml", epochs=100)
Validate
CLI:
yolo pose val model=yolo26n-pose.pt data=coco8-pose.yaml
Oriented Bounding Boxes (OBB)
OBB detection handles rotated objects, useful for aerial imagery, document layout analysis, and any scenario where objects are not axis-aligned.
Predict
CLI:
yolo obb predict model=yolo26n-obb.pt source="aerial_image.jpg"
Python:
from ultralytics import YOLO
model = YOLO("yolo26n-obb.pt")
results = model("aerial_image.jpg")
for r in results:
obb = r.obb
if obb is not None:
xywhr = obb.xywhr # center x, center y, width, height, rotation
conf = obb.conf
cls = obb.cls
Train
CLI:
yolo obb train data=dota8.yaml model=yolo26n-obb.pt epochs=100
Validate
CLI:
yolo obb val model=yolo26n-obb.pt data=dota8.yaml
Object Tracking
Tracking extends detection (or segmentation/pose) with temporal object identity across video frames. Ultralytics supports ByteTrack and BoTSORT trackers.
CLI
# Default tracker (BoTSORT)
yolo track model=yolo26n.pt source="video.mp4"
# ByteTrack
yolo track model=yolo26n.pt source="video.mp4" tracker=bytetrack.yaml
# BoTSORT (explicit)
yolo track model=yolo26n.pt source="video.mp4" tracker=botsort.yaml
# Tracking with segmentation
yolo track model=yolo26n-seg.pt source="video.mp4"
# Tracking with pose
yolo track model=yolo26n-pose.pt source="video.mp4"
Python
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model.track(source="video.mp4", tracker="bytetrack.yaml", show=True)
# Process tracking results
for r in results:
boxes = r.boxes
if boxes.id is not None:
track_ids = boxes.id.int().tolist()
for box, tid in zip(boxes, track_ids):
print(f"Track {tid}: {box.xyxy[0]}")
Tip
Tracking does not work with classification (
classify). If you need to re-identify classified objects across frames, use detection + tracking and then classify detected crops separately.
Custom tracker configuration
Copy and edit a tracker YAML:
# Find the default tracker configs:
# ultralytics/cfg/trackers/bytetrack.yaml
# ultralytics/cfg/trackers/botsort.yaml
Example custom_tracker.yaml:
tracker_type: bytetrack
track_high_thresh: 0.5
track_low_thresh: 0.1
new_track_thresh: 0.6
track_buffer: 30
match_thresh: 0.8
yolo track model=yolo26n.pt source="video.mp4" tracker=custom_tracker.yaml
Model Export
Export converts a PyTorch model to optimized formats for deployment. Ultralytics supports 18+ export formats.
Export format reference
| Format | format= |
File Extension | GPU | Notes |
|---|---|---|---|---|
| PyTorch | — | .pt |
Yes | Default training format |
| TorchScript | torchscript |
.torchscript |
Yes | Mobile-optimized |
| ONNX | onnx |
.onnx |
Yes | Universal interchange |
| OpenVINO | openvino |
_openvino_model/ |
No | Intel hardware |
| TensorRT | engine |
.engine |
Yes | NVIDIA optimized |
| CoreML | coreml |
.mlpackage |
Yes | Apple devices |
| TF SavedModel | saved_model |
_saved_model/ |
Yes | TensorFlow serving |
| TF GraphDef | pb |
.pb |
Yes | TensorFlow frozen |
| TFLite | tflite |
.tflite |
No | Mobile/edge |
| TF Edge TPU | edgetpu |
_edgetpu.tflite |
No | Google Edge TPU |
| TF.js | tfjs |
_web_model/ |
No | Browser |
| PaddlePaddle | paddle |
_paddle_model/ |
Yes | Baidu ecosystem |
| MNN | mnn |
.mnn |
No | Alibaba edge |
| NCNN | ncnn |
_ncnn_model/ |
No | Mobile (ARM) |
| IMX | imx |
_imx_model/ |
No | NXP i.MX chips |
| RKNN | rknn |
.rknn |
No | Rockchip NPU |
| ExecuTorch | executorch |
.pte |
No | Meta on-device |
| Axelera AI | axelera |
_axelera_model/ |
No | Axelera Metis |
CLI export examples
# ONNX (most common interchange format)
yolo export model=yolo26n.pt format=onnx
# ONNX with dynamic batch size
yolo export model=yolo26n.pt format=onnx dynamic=True
# TensorRT (NVIDIA GPU deployment)
yolo export model=yolo26n.pt format=engine
# TensorRT with FP16
yolo export model=yolo26n.pt format=engine half=True
# TensorRT with INT8 quantization
yolo export model=yolo26n.pt format=engine int8=True data=coco8.yaml
# CoreML (Apple)
yolo export model=yolo26n.pt format=coreml
# TFLite (mobile/edge)
yolo export model=yolo26n.pt format=tflite
# TFLite with INT8
yolo export model=yolo26n.pt format=tflite int8=True data=coco8.yaml
# OpenVINO (Intel)
yolo export model=yolo26n.pt format=openvino
# NCNN (ARM mobile)
yolo export model=yolo26n.pt format=ncnn
# Edge TPU
yolo export model=yolo26n.pt format=edgetpu
# Multiple: export then run inference on exported model
yolo export model=yolo26n.pt format=onnx
yolo predict model=yolo26n.onnx source="image.jpg"
Python export
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
# ONNX
model.export(format="onnx")
# TensorRT FP16
model.export(format="engine", half=True)
# TFLite INT8
model.export(format="tflite", int8=True, data="coco8.yaml")
# ONNX with dynamic axes and simplified graph
model.export(format="onnx", dynamic=True, simplify=True)
# Export and immediately load exported model
model.export(format="onnx")
onnx_model = YOLO("yolo26n.onnx")
results = onnx_model("image.jpg")
Important
INT8 quantization (
int8=True) requires a calibration dataset. Pass thedataargument pointing to a dataset YAML. Without it, the export will fail or produce poor accuracy.
Benchmarking
Benchmark measures inference speed and accuracy across all export formats.
CLI:
yolo benchmark model=yolo26n.pt data=coco8.yaml imgsz=640
Python:
from ultralytics.utils.benchmarks import benchmark
benchmark(model="yolo26n.pt", data="coco8.yaml", imgsz=640, half=False, device=0)
Output includes a table of format, file size, mAP50-95, and inference time for each successfully exported format.
Solutions
Ultralytics Solutions are pre-built applications that combine YOLO models with business logic for common computer vision use cases. Each solution is available via CLI and Python.
Solutions reference
| Solution | CLI Key | Python Class | Description |
|---|---|---|---|
| Object Counter | count |
ObjectCounter |
Count objects crossing a line or in a region |
| Object Cropper | crop |
ObjectCropper |
Crop and save detected objects |
| Object Blurrer | blur |
ObjectBlurrer |
Blur detected objects (faces, plates) |
| AI Gym / Workout | workout |
AIGym |
Count workout repetitions using pose |
| Heatmap | heatmap |
Heatmap |
Generate heatmaps of object activity |
| Instance Segmentation | isegment |
InstanceSegmentation |
Interactive instance segmentation |
| VisionEye | visioneye |
VisionEye |
Map object positions to a viewpoint |
| Speed Estimator | speed |
SpeedEstimator |
Estimate object speed in video |
| Queue Manager | queue |
QueueManager |
Monitor queue lengths in regions |
| Analytics | analytics |
Analytics |
Generate analytical visualizations |
| Inference | inference |
Inference |
Streamlined real-time inference |
| TrackZone | trackzone |
TrackZone |
Track objects within defined zones |
| Region Counter | region |
RegionCounter |
Count objects in polygonal regions |
| Security Alarm | security |
SecurityAlarm |
Trigger alerts on detections |
| Parking Management | parking |
ParkingManagement |
Monitor parking lot occupancy |
Solution CLI syntax
yolo solutions SOLUTION_NAME [ARGS]
Object Counter
Count objects crossing a defined line or within a region.
CLI:
yolo solutions count source="video.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
counter = solutions.ObjectCounter(
model="yolo26n.pt",
region=[(100, 500), (1080, 500)], # counting line
show=True,
)
counter.start(source="video.mp4")
Object Cropper
Save cropped images of detected objects.
CLI:
yolo solutions crop source="image.jpg" model=yolo26n.pt
Python:
from ultralytics import solutions
cropper = solutions.ObjectCropper(model="yolo26n.pt")
cropper.start(source="image.jpg")
Object Blurrer
Blur detected objects (useful for privacy — faces, license plates).
CLI:
yolo solutions blur source="video.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
blurrer = solutions.ObjectBlurrer(model="yolo26n.pt", show=True)
blurrer.start(source="video.mp4")
AI Gym (Workout Counter)
Count workout repetitions using pose estimation.
CLI:
yolo solutions workout source="workout.mp4" model=yolo26n-pose.pt show=True
Python:
from ultralytics import solutions
gym = solutions.AIGym(model="yolo26n-pose.pt", show=True)
gym.start(source="workout.mp4")
Heatmap
Generate activity heatmaps from object trajectories.
CLI:
yolo solutions heatmap source="video.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
heatmap = solutions.Heatmap(model="yolo26n.pt", show=True)
heatmap.start(source="video.mp4")
Speed Estimator
Estimate speed of tracked objects using reference region.
CLI:
yolo solutions speed source="traffic.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
speed = solutions.SpeedEstimator(model="yolo26n.pt", show=True)
speed.start(source="traffic.mp4")
Queue Manager
Monitor queue lengths in specified regions.
CLI:
yolo solutions queue source="store.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
queue = solutions.QueueManager(
model="yolo26n.pt",
region=[(50, 200), (400, 200), (400, 600), (50, 600)],
show=True,
)
queue.start(source="store.mp4")
Analytics
Generate analytical charts and visualizations.
CLI:
yolo solutions analytics source="video.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
analytics = solutions.Analytics(model="yolo26n.pt", show=True)
analytics.start(source="video.mp4")
TrackZone
Track objects within user-defined zones.
CLI:
yolo solutions trackzone source="video.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
trackzone = solutions.TrackZone(
model="yolo26n.pt",
region=[(100, 100), (500, 100), (500, 500), (100, 500)],
show=True,
)
trackzone.start(source="video.mp4")
Region Counter
Count objects in polygonal regions.
CLI:
yolo solutions region source="video.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
region = solutions.RegionCounter(
model="yolo26n.pt",
region=[(100, 100), (500, 100), (500, 500), (100, 500)],
show=True,
)
region.start(source="video.mp4")
Security Alarm
Trigger alerts when objects are detected in a monitored area.
CLI:
yolo solutions security source="camera.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
alarm = solutions.SecurityAlarm(model="yolo26n.pt", show=True)
alarm.start(source="camera.mp4")
Parking Management
Monitor parking lot occupancy.
CLI:
yolo solutions parking source="parking_lot.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
parking = solutions.ParkingManagement(model="yolo26n.pt", show=True)
parking.start(source="parking_lot.mp4")
Instance Segmentation (Interactive)
CLI:
yolo solutions isegment source="image.jpg" model=yolo26n-seg.pt show=True
VisionEye
Map object positions to a fixed viewpoint.
CLI:
yolo solutions visioneye source="video.mp4" model=yolo26n.pt show=True
Python:
from ultralytics import solutions
visioneye = solutions.VisionEye(model="yolo26n.pt", show=True)
visioneye.start(source="video.mp4")
Inference (Streamlined)
Simple real-time inference with display.
CLI:
yolo solutions inference source=0 model=yolo26n.pt show=True
Python:
from ultralytics import solutions
inference = solutions.Inference(model="yolo26n.pt", show=True)
inference.start(source=0)
5. Common Tasks
Train a custom detection model
Prepare your dataset in YOLO format:
dataset/
├── images/
│ ├── train/
│ │ ├── img001.jpg
│ │ └── ...
│ └── val/
│ ├── img100.jpg
│ └── ...
└── labels/
├── train/
│ ├── img001.txt
│ └── ...
└── val/
├── img100.txt
└── ...
Each label file has one line per object: class_id center_x center_y width height (all values normalized 0-1).
Create a dataset YAML (my_dataset.yaml):
path: /path/to/dataset
train: images/train
val: images/val
names:
0: cat
1: dog
2: bird
Train:
yolo detect train data=my_dataset.yaml model=yolo26n.pt epochs=100 imgsz=640
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model.train(data="my_dataset.yaml", epochs=100, imgsz=640)
Fine-tune a pre-trained model on custom data
Fine-tuning starts from pre-trained weights and adapts to your specific dataset:
yolo detect train model=yolo26s.pt data=my_dataset.yaml epochs=50 lr0=0.001
from ultralytics import YOLO
model = YOLO("yolo26s.pt") # start from pre-trained
results = model.train(
data="my_dataset.yaml",
epochs=50,
lr0=0.001, # lower learning rate for fine-tuning
freeze=10, # optionally freeze first N layers
)
Export to ONNX
yolo export model=best.pt format=onnx
from ultralytics import YOLO
model = YOLO("best.pt")
model.export(format="onnx", dynamic=True, simplify=True)
Export to TensorRT
yolo export model=best.pt format=engine half=True
from ultralytics import YOLO
model = YOLO("best.pt")
model.export(format="engine", half=True)
# Run inference on TensorRT engine
trt_model = YOLO("best.engine")
results = trt_model("image.jpg")
Run inference on video
yolo predict model=yolo26n.pt source="video.mp4" save=True
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model("video.mp4", save=True, save_txt=True)
Run inference on webcam
yolo predict model=yolo26n.pt source=0 show=True
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model(source=0, show=True, stream=True)
for r in results:
# Process each frame
pass
Run inference on RTSP stream
yolo predict model=yolo26n.pt source="rtsp://username:password@192.168.1.100:554/stream"
Run inference on multiple sources
Create a text file listing sources (one per line):
image1.jpg
image2.jpg
video.mp4
rtsp://stream1
yolo predict model=yolo26n.pt source="sources.txt"
Run inference on a directory of images
yolo predict model=yolo26n.pt source="path/to/images/" save=True
Multi-GPU training
yolo detect train data=coco.yaml model=yolo26n.pt epochs=100 device=0,1
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model.train(data="coco.yaml", epochs=100, device=[0, 1])
Warning
Multi-GPU training uses PyTorch DistributedDataParallel (DDP). The batch size is per-GPU, so
batch=16with 2 GPUs processes 32 images per step. Ensure each GPU has sufficient VRAM.
Resume interrupted training
yolo detect train resume model=runs/detect/train/weights/last.pt
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/last.pt")
results = model.train(resume=True)
Hyperparameter tuning
yolo detect tune data=coco8.yaml model=yolo26n.pt epochs=30 iterations=300
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.tune(data="coco8.yaml", epochs=30, iterations=300)
Use SAHI for tiled inference on large images
SAHI (Slicing Aided Hyper Inference) splits large images into overlapping tiles for better small-object detection:
from ultralytics import YOLO
from sahi import AutoDetectionModel
from sahi.predict import get_sliced_prediction
# Using sahi library
detection_model = AutoDetectionModel.from_pretrained(
model_type="ultralytics",
model_path="yolo26n.pt",
confidence_threshold=0.3,
)
result = get_sliced_prediction(
"large_image.jpg",
detection_model,
slice_height=640,
slice_width=640,
overlap_height_ratio=0.2,
overlap_width_ratio=0.2,
)
result.export_visuals(export_dir="sahi_results/")
Track objects in video
yolo track model=yolo26n.pt source="video.mp4" tracker=bytetrack.yaml show=True
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
# Stream mode for video
for result in model.track(source="video.mp4", stream=True, tracker="bytetrack.yaml"):
if result.boxes.id is not None:
ids = result.boxes.id.int().tolist()
for box, tid in zip(result.boxes, ids):
print(f"Frame: Track {tid} at {box.xyxy[0]}")
Count objects in a region
from ultralytics import solutions
counter = solutions.ObjectCounter(
model="yolo26n.pt",
region=[(100, 500), (1080, 500)],
show=True,
)
counter.start(source="video.mp4")
Generate heatmaps
from ultralytics import solutions
heatmap = solutions.Heatmap(
model="yolo26n.pt",
show=True,
)
heatmap.start(source="video.mp4")
Monitor workouts with pose estimation
from ultralytics import solutions
gym = solutions.AIGym(
model="yolo26n-pose.pt",
show=True,
)
gym.start(source="workout_video.mp4")
Deploy to NVIDIA Jetson
# On Jetson, use the JetPack Dockerfile or install natively
pip install ultralytics
# Export to TensorRT for best performance
yolo export model=yolo26n.pt format=engine half=True
# Run inference with TensorRT engine
yolo predict model=yolo26n.engine source=0 show=True
Deploy to Raspberry Pi
# Install on Raspberry Pi
pip install ultralytics
# Export to NCNN for best ARM performance
yolo export model=yolo26n.pt format=ncnn
# Run inference
yolo predict model=yolo26n_ncnn_model source=0 show=True
Deploy to Edge TPU
# Export to Edge TPU format
yolo export model=yolo26n.pt format=edgetpu
# Run on Coral device
yolo predict model=yolo26n_edgetpu.tflite source="image.jpg"
Use with Ultralytics HUB
from ultralytics import hub
# Login to HUB
hub.login("YOUR_API_KEY")
# Train with HUB integration
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.train(data="my_dataset.yaml", epochs=100)
# Models and results sync to HUB automatically
Validate model performance
yolo detect val model=best.pt data=my_dataset.yaml split=test
from ultralytics import YOLO
model = YOLO("best.pt")
metrics = model.val(data="my_dataset.yaml", split="test")
print(f"mAP50-95: {metrics.box.map:.4f}")
print(f"mAP50: {metrics.box.map50:.4f}")
print(f"mAP75: {metrics.box.map75:.4f}")
print(f"Precision: {metrics.box.mp:.4f}")
print(f"Recall: {metrics.box.mr:.4f}")
Run on a specific GPU
# Use GPU 0
yolo predict model=yolo26n.pt source="image.jpg" device=0
# Use GPU 1
yolo predict model=yolo26n.pt source="image.jpg" device=1
# Use CPU
yolo predict model=yolo26n.pt source="image.jpg" device=cpu
Or via environment variable:
CUDA_VISIBLE_DEVICES=1 yolo predict model=yolo26n.pt source="image.jpg"
Batch inference on a folder
yolo predict model=yolo26n.pt source="images/" save=True save_txt=True
from ultralytics import YOLO
from pathlib import Path
model = YOLO("yolo26n.pt")
results = model("images/", save=True)
for r in results:
print(f"{Path(r.path).name}: {len(r.boxes)} detections")
Save detection crops
yolo predict model=yolo26n.pt source="image.jpg" save_crop=True
Crops are saved to runs/detect/predict/crops/{class_name}/.
Export with INT8 quantization
# TensorRT INT8
yolo export model=yolo26n.pt format=engine int8=True data=coco8.yaml
# TFLite INT8
yolo export model=yolo26n.pt format=tflite int8=True data=coco8.yaml
Caution
INT8 quantization reduces model size and increases speed but may decrease accuracy. Always validate the quantized model against your dataset before deploying to production.
Use custom model YAML architectures
Create a custom architecture YAML:
# custom_model.yaml
nc: 80 # number of classes
scales:
n: [0.33, 0.25, 1024]
backbone:
- [-1, 1, Conv, [64, 3, 2]]
- [-1, 1, Conv, [128, 3, 2]]
# ... define your architecture
head:
- # ... define detection head
yolo detect train model=custom_model.yaml data=coco8.yaml epochs=100
from ultralytics import YOLO
# Build model from YAML (random weights)
model = YOLO("custom_model.yaml")
model.train(data="coco8.yaml", epochs=100)
# Or load YAML and transfer pre-trained weights
model = YOLO("custom_model.yaml").load("yolo26n.pt")
model.train(data="coco8.yaml", epochs=100)
Convert COCO format to YOLO format
from ultralytics.data.converter import convert_coco
convert_coco(
labels_dir="coco/annotations/",
save_dir="yolo_labels/",
use_segments=False,
use_keypoints=False,
)
Use data augmentation
Augmentation is controlled through training arguments:
yolo detect train data=coco8.yaml model=yolo26n.pt epochs=100 \
mosaic=1.0 \
mixup=0.1 \
copy_paste=0.1 \
hsv_h=0.015 \
hsv_s=0.7 \
hsv_v=0.4 \
degrees=10.0 \
translate=0.1 \
scale=0.5 \
flipud=0.5 \
fliplr=0.5
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.train(
data="coco8.yaml",
epochs=100,
mosaic=1.0,
mixup=0.1,
copy_paste=0.1,
degrees=10.0,
flipud=0.5,
fliplr=0.5,
)
Deploy with Docker
# Build and run GPU container
docker run -it --gpus all -v $(pwd)/data:/data ultralytics/ultralytics:latest \
yolo predict model=yolo26n.pt source=/data/images/ save=True
# Train inside container
docker run -it --gpus all \
-v $(pwd)/datasets:/datasets \
-v $(pwd)/runs:/runs \
ultralytics/ultralytics:latest \
yolo detect train data=/datasets/my_dataset.yaml model=yolo26n.pt epochs=100 project=/runs
Predict and extract results programmatically
from ultralytics import YOLO
import json
model = YOLO("yolo26n.pt")
results = model("image.jpg")
# Convert to list of dicts
detections = []
for r in results:
for box in r.boxes:
detections.append({
"class": r.names[int(box.cls[0])],
"confidence": float(box.conf[0]),
"bbox": box.xyxy[0].tolist(),
})
print(json.dumps(detections, indent=2))
Run inference with FP16 (half precision)
yolo predict model=yolo26n.pt source="image.jpg" half=True
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model("image.jpg", half=True)
Tip
FP16 inference roughly doubles throughput on GPUs with Tensor Cores (NVIDIA Volta and newer) with negligible accuracy loss. It is strongly recommended for production GPU deployments.
Set automatic batch size
Let Ultralytics determine the optimal batch size for your GPU:
yolo train data=coco8.yaml model=yolo26n.pt batch=-1
The system profiles available VRAM and selects the largest safe batch size.
Save results as YOLO format labels
yolo predict model=yolo26n.pt source="images/" save_txt=True save_conf=True
Label files are saved to runs/detect/predict/labels/ in YOLO format.
6. Troubleshooting
Error: Invalid 'mode={mode}'. Valid modes are {MODES}
Cause: You used an unrecognized mode in the CLI or Python.
Solution: Use one of the valid modes: train, val, predict, export, track, benchmark.
# Wrong
yolo detect inference model=yolo26n.pt source="image.jpg"
# Correct
yolo detect predict model=yolo26n.pt source="image.jpg"
Error: Invalid 'task={task}'. Valid tasks are {TASKS}
Cause: You specified an invalid task.
Solution: Use one of: detect, segment, classify, pose, obb.
# Wrong
yolo recognition predict model=yolo26n.pt source="image.jpg"
# Correct
yolo classify predict model=yolo26n-cls.pt source="image.jpg"
Error: model='{model}' is not a supported model format
Cause: The model file path or format is not recognized.
Solution: Use a supported model format: .pt, .onnx, .engine, .xml (OpenVINO), .mlpackage, .tflite, .pb, .paddle, .ncnn, .mnn, .pte, .rknn, or a YAML model config.
# Verify the file exists
ls -la model_file.pt
Error: Dataset '{data}' for task={task} not found
Cause: The dataset YAML or directory path is incorrect, or the dataset has not been downloaded.
Solution:
# Verify the path exists
ls -la /path/to/dataset.yaml
# Use a built-in dataset to test
yolo detect train data=coco8.yaml model=yolo26n.pt epochs=1
Built-in datasets (like coco8.yaml) are downloaded automatically on first use.
Error: Resume checkpoint not found
Cause: Trying to resume training but the last.pt checkpoint does not exist at the expected path.
Solution:
# Find the checkpoint
find runs/ -name "last.pt"
# Resume with explicit path
yolo train resume model=runs/detect/train2/weights/last.pt
Error: '{k}={v}' is of invalid type
Cause: A configuration value has the wrong type (e.g., passing a string where an integer is expected).
Solution: Check the expected type for that key in the Configuration section. Common issues:
# Wrong: string instead of int
yolo train epochs="one hundred"
# Correct
yolo train epochs=100
# Wrong: passing boolean as string
yolo train half="true"
# Correct
yolo train half=True
Error: imgsz={imgsz} is not a valid image size
Cause: Image size must be a positive integer divisible by the model's stride (typically 32).
Solution:
# Wrong
yolo predict imgsz=641
# Correct (divisible by 32)
yolo predict imgsz=640
yolo predict imgsz=1280
Error: Classification datasets must be a directory
Cause: You passed a YAML file for a classification task, but classification expects a directory structure.
Solution: Organize classification data as:
dataset/
├── train/
│ ├── class1/
│ │ ├── img1.jpg
│ │ └── ...
│ ├── class2/
│ │ └── ...
├── val/
│ ├── class1/
│ └── class2/
yolo classify train data=/path/to/dataset model=yolo26n-cls.pt
Error: Classification doesn't support 'mode=track'
Cause: Tracking requires spatial bounding boxes, which classification models do not produce.
Solution: Use a detection model for tracking:
yolo track model=yolo26n.pt source="video.mp4"
Error: RuntimeError: CUDA out of memory
Cause: The batch size, model size, or image size exceeds GPU VRAM.
Solution:
# Reduce batch size
yolo train data=coco8.yaml batch=4
# Use a smaller model
yolo train model=yolo26n.pt data=coco8.yaml
# Reduce image size
yolo train data=coco8.yaml imgsz=416
# Use automatic batch sizing
yolo train data=coco8.yaml batch=-1
# Use FP16 to reduce memory
yolo train data=coco8.yaml half=True
Error: RuntimeError: DataLoader worker ... is killed
Cause: System ran out of memory or too many dataloader workers.
Solution:
# Reduce workers
yolo train data=coco8.yaml workers=2
# Or disable workers entirely
yolo train data=coco8.yaml workers=0
Error: FileNotFoundError: Image not found
Cause: The path in your dataset labels or source argument is invalid.
Solution:
- Verify all image paths exist.
- Check for special characters in paths (see issue #24257 — square brackets in paths like
./[examples]cause failures). - Use absolute paths when possible.
Error: ConnectionError during model download
Cause: Network issue or firewall blocking the download.
Solution:
# Download manually
wget https://github.com/ultralytics/assets/releases/download/v8.4.0/yolo26n.pt
# Use offline mode after downloading
export YOLO_OFFLINE=True
yolo predict model=./yolo26n.pt source="image.jpg"
Error: AssertionError: Image Not Found
Cause: The source file does not exist or the path is wrong.
Solution:
# Verify the file
ls -la image.jpg
# Use absolute path
yolo predict model=yolo26n.pt source="/absolute/path/to/image.jpg"
Error: ValueError: operands could not be broadcast together
Cause: Image dimensions or tensor shapes are incompatible, often due to corrupted images in the dataset.
Solution:
- Check for corrupted images in your dataset.
- Run dataset verification:
yolo detect val data=my_dataset.yamlto identify problematic files. - Remove or re-download corrupted images.
Issue: Training loss is NaN
Cause: Learning rate too high, data issue, or numerical instability.
Solution:
# Lower learning rate
yolo train data=coco8.yaml lr0=0.001
# Check dataset for issues (empty labels, corrupt images)
# Use smaller model to test
yolo train model=yolo26n.pt data=coco8.yaml epochs=5
Issue: Model predicts nothing (zero detections)
Cause: Confidence threshold too high, or the model has not learned the classes.
Solution:
# Lower confidence threshold
yolo predict model=best.pt source="image.jpg" conf=0.1
# Check if the model was trained on the right classes
python -c "from ultralytics import YOLO; print(YOLO('best.pt').names)"
Issue: Very slow training
Cause: No GPU detected, excessive data augmentation, or I/O bottleneck.
Solution:
# Verify GPU is detected
python -c "import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0))"
# Reduce augmentation
yolo train data=coco8.yaml mosaic=0.0 mixup=0.0
# Increase workers for I/O
yolo train data=coco8.yaml workers=8
# Use smaller image size
yolo train data=coco8.yaml imgsz=416
Issue: Poor segmentation mask quality for small objects
Cause: The default mask resolution may be insufficient for small objects. Related to GitHub issue #24084.
Solution:
# Use retina masks for higher resolution
yolo segment predict model=yolo26n-seg.pt source="image.jpg" retina_masks=True
# Use a larger model
yolo segment predict model=yolo26l-seg.pt source="image.jpg" retina_masks=True
Issue: Segmentation mask shrinks when object moves closer (issue #24168)
Cause: Known issue where segmentation masks become disproportionately small as objects approach the camera.
Solution:
- Use
retina_masks=Truefor improved mask quality. - Use a larger model variant (e.g.,
yolo26l-seg.pt). - Check for updates as this is being actively addressed.
Issue: IoU metric intermittently not working (issue #24253)
Cause: Known edge case in IoU computation.
Solution:
- Ensure your bounding box annotations are valid (no zero-area boxes).
- Use the latest ultralytics version.
Issue: YOLO26-OBB lower accuracy than YOLO11 (issue #24205)
Cause: The YOLO26 OBB architecture may underperform YOLOv11 on certain OBB datasets, particularly in version 8.4.x compared to 8.3.x.
Solution:
- For OBB tasks, benchmark both YOLO26 and YOLO11 variants on your specific dataset.
- Consider using
yolov8n-obb.ptoryolo11n-obb.ptif accuracy is more critical than using the latest architecture.
Issue: SAM3VideoSemanticPredictor gives different results from SAM3SemanticPredictor (issue #23941)
Cause: The video and image semantic predictors use different internal processing pipelines.
Solution:
- If consistent results are required, use the same predictor type for both video and image inference.
- Apply consistent pre-processing (resolution, normalization) to inputs for both predictors.
Error: TensorRT export fails
Cause: TensorRT version mismatch, unsupported operations, or insufficient memory during engine building.
Solution:
# Check TensorRT version
python -c "import tensorrt; print(tensorrt.__version__)"
# Try with simpler options first
yolo export model=yolo26n.pt format=engine
# Reduce workspace
yolo export model=yolo26n.pt format=engine workspace=4
# Use FP16 instead of INT8
yolo export model=yolo26n.pt format=engine half=True
Caution
TensorRT engines are built for a specific GPU architecture and TensorRT version. An engine built on an RTX 4090 will not run on a Jetson Nano. Always build the engine on the target hardware.
Error: ONNX export produces inconsistent output tensor names (issue #24265)
Cause: ONNX output tensor names vary across different tasks (detect, segment, pose).
Solution:
- Use the
--simplifyflag during export. - If consuming ONNX models downstream, rely on tensor shapes rather than names for task disambiguation.
Issue: Model files not loading from HuggingFace (issue #24243)
Cause: HuggingFace model loading/saving is not fully standardized yet.
Solution:
- Download the model file manually from HuggingFace and use the local path.
- Check for updates, as native HuggingFace load/save support is being developed.
Issue: batch parameter does not support numpy or PIL arrays (issue #24218)
Cause: The batch parameter currently expects integer batch size, not pre-formed arrays.
Solution:
- Pass images as a list of file paths or a directory.
- For programmatic batching, iterate over images:
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
images = ["img1.jpg", "img2.jpg", "img3.jpg"]
results = model(images) # pass list of paths
Issue: cache=disk does not allow custom cache directory (issue #24256)
Cause: The disk cache directory is determined internally and cannot be overridden.
Solution:
- Use symlinks to redirect the cache directory if needed.
- Monitor the issue for when a
cache_dirparameter is added.
Warning
If paths contain special characters such as square brackets (e.g.,
./[examples]/image.jpg), Ultralytics may fail to load the media (issue #24257). Rename directories to avoid special characters, or use glob patterns carefully.
7. FAQ
Installation
Q: What Python versions are supported? Python 3.8 through 3.12 are supported. Python 3.10+ is recommended for best compatibility with current PyTorch versions.
Q: Is a GPU required? No. Ultralytics works on CPU, but training and inference are significantly faster with an NVIDIA GPU (CUDA). Apple MPS acceleration is also supported on Apple Silicon Macs.
Q: Can I install just the inference dependencies without training dependencies?
Yes. Install with pip install ultralytics and set YOLO_AUTOINSTALL=False. Missing optional packages will not be auto-installed, but core inference works with minimal dependencies (torch, opencv, numpy, pillow).
Q: How do I install a specific version?
pip install ultralytics==8.4.38
Q: Can I use Ultralytics with Anaconda?
Yes. Use conda install -c conda-forge ultralytics or create a conda environment and use pip inside it.
Training
Q: How long does training take? Training time depends on dataset size, model size, image size, and hardware. As a rough guide on an RTX 4090: COCO (118K images) with YOLO26n at 640px takes about 12 hours for 100 epochs.
Q: What dataset format does YOLO use?
YOLO format: one .txt file per image, each line containing class_id center_x center_y width height (normalized 0-1). Classification uses a directory structure with one folder per class.
Q: Can I train with mixed precision automatically? Yes. PyTorch AMP (Automatic Mixed Precision) is used by default when a CUDA GPU is available. No extra flags needed.
Q: What is the close_mosaic parameter?
It disables the mosaic augmentation for the last N epochs of training (default: 10). This helps the model fine-tune on non-augmented images at the end, often improving final accuracy.
Q: How do I train on a custom number of classes?
Set the nc (number of classes) in your dataset YAML or model YAML. When using a pre-trained model, the classification head is automatically adapted to match the new number of classes.
Q: Can I freeze layers during training?
Yes. Use the freeze parameter:
yolo train model=yolo26n.pt data=my_dataset.yaml freeze=10
This freezes the first 10 layers, which is useful for fine-tuning with small datasets.
Q: What happens if training is interrupted? Checkpoints are saved periodically. Resume with:
yolo train resume model=runs/detect/train/weights/last.pt
Q: How do I use early stopping?
Early stopping is enabled by default with patience=50. Training stops if no improvement in the monitored metric for 50 epochs. Adjust with patience=100 for longer training.
Q: Can I train from a YAML file without pre-trained weights? Yes. Build a model from scratch:
yolo train model=yolo26n.yaml data=coco8.yaml epochs=300
Note: training from scratch requires significantly more epochs than fine-tuning.
Inference
Q: What input sources are supported? Images (jpg, png, bmp, tiff, webp), videos (mp4, avi, mov, mkv), directories of images, glob patterns, URLs, RTSP/RTMP/HTTP streams, YouTube URLs, webcam (source=0), PIL images, numpy arrays, torch tensors, CSV files, and screenshots.
Q: How do I adjust detection sensitivity? Lower the confidence threshold:
yolo predict conf=0.1 # more detections, more false positives
yolo predict conf=0.5 # fewer detections, higher precision
Q: Can I run inference on multiple GPUs?
Inference does not support multi-GPU. Use a single GPU with device=0. For parallel inference, run multiple processes each on a different GPU using CUDA_VISIBLE_DEVICES.
Q: How do I get results in JSON format?
from ultralytics import YOLO
import json
model = YOLO("yolo26n.pt")
results = model("image.jpg")
# Convert to JSON-serializable format
for r in results:
data = r.tojson()
print(data)
Q: What is the stream=True option?
When processing videos or multiple images, stream=True returns a generator instead of loading all results into memory. This is essential for long videos:
for r in model("long_video.mp4", stream=True):
process(r)
Q: Can I run inference on a screenshot? Yes:
yolo predict model=yolo26n.pt source="screen"
Q: How do I visualize model features?
yolo predict model=yolo26n.pt source="image.jpg" visualize=True
Feature maps are saved to the output directory.
Export
Q: Which export format is best for deployment? It depends on your target:
| Target | Recommended Format |
|---|---|
| NVIDIA GPU server | TensorRT (engine) |
| Intel CPU/iGPU | OpenVINO (openvino) |
| Apple (iOS/macOS) | CoreML (coreml) |
| Android / mobile | TFLite (tflite) or NCNN (ncnn) |
| Browser | TF.js (tfjs) |
| Edge TPU (Coral) | Edge TPU (edgetpu) |
| Cross-platform | ONNX (onnx) |
| NVIDIA Jetson | TensorRT (engine) |
| Rockchip NPU | RKNN (rknn) |
| NXP i.MX | IMX (imx) |
Q: Does export change model accuracy? Minimal change for FP32 and FP16 exports. INT8 quantization may reduce accuracy by 0.5-2% mAP depending on the model and calibration dataset. Always validate after exporting.
Q: Can I export with dynamic input shapes? Yes, for ONNX:
yolo export model=yolo26n.pt format=onnx dynamic=True
Q: Can I include NMS in the exported model? Yes:
yolo export model=yolo26n.pt format=onnx nms=True
# or
yolo export model=yolo26n.pt format=engine end2end=True
Q: How large are exported models? Approximate sizes for YOLO26n:
| Format | Size |
|---|---|
| PyTorch (.pt) | ~6 MB |
| ONNX | ~12 MB |
| TensorRT FP16 | ~8 MB |
| TensorRT INT8 | ~5 MB |
| TFLite | ~12 MB |
| TFLite INT8 | ~4 MB |
Data
Q: How do I convert COCO annotations to YOLO format?
from ultralytics.data.converter import convert_coco
convert_coco(labels_dir="coco/annotations/", save_dir="yolo_labels/")
Q: What image formats are supported? bmp, dng, jpeg, jpg, mpo, png, tif, tiff, webp, pfm, heic.
Q: What video formats are supported? asf, avi, gif, m4v, mkv, mov, mp4, mpeg, mpg, ts, wmv, webm.
Q: How do I split my dataset into train/val/test? Ultralytics does not include a dataset splitting tool. Use scikit-learn or a manual approach:
import random
from pathlib import Path
import shutil
images = list(Path("all_images").glob("*.jpg"))
random.shuffle(images)
split = int(0.8 * len(images))
for img in images[:split]:
shutil.copy(img, "images/train/")
shutil.copy(str(img).replace("all_images", "all_labels").replace(".jpg", ".txt"), "labels/train/")
for img in images[split:]:
shutil.copy(img, "images/val/")
shutil.copy(str(img).replace("all_images", "all_labels").replace(".jpg", ".txt"), "labels/val/")
Q: Can I use data from multiple directories? Yes. In your dataset YAML, use lists:
path: /data
train:
- images/train_set1
- images/train_set2
val: images/val
Q: How do I handle class imbalance?
- Use oversampling or data augmentation for underrepresented classes.
- Adjust the
clsloss weight. - Use
copy_pasteaugmentation to paste minority-class instances. - Consider
single_cls=Trueif you only care about foreground vs. background.
General
Q: How do I check my Ultralytics version?
yolo version
# or
python -c "import ultralytics; print(ultralytics.__version__)"
Q: How do I update Ultralytics?
pip install --upgrade ultralytics
Q: Where are models downloaded to? Models are downloaded to the Ultralytics config directory. Check the location:
from ultralytics import settings
print(settings["weights_dir"])
Q: Where are training results saved?
By default, to runs/{task}/{mode}/ (e.g., runs/detect/train/). Override with project and name:
yolo train data=coco8.yaml project=my_project name=experiment1
Q: Can I use Ultralytics commercially? Ultralytics is licensed under AGPL-3.0. For commercial use without AGPL obligations, you need an Ultralytics Enterprise License.
Q: How do I suppress verbose output?
export YOLO_VERBOSE=False
Or in Python:
import os
os.environ["YOLO_VERBOSE"] = "False"
Q: Can I use multiple models in sequence (ensemble)? Ultralytics does not have a built-in ensemble mode, but you can combine predictions manually:
from ultralytics import YOLO
model1 = YOLO("yolo26n.pt")
model2 = YOLO("yolo26s.pt")
results1 = model1("image.jpg")
results2 = model2("image.jpg")
# Merge results programmatically
Q: How do I disable auto-install of missing packages?
export YOLO_AUTOINSTALL=False
Q: What is yolo settings and how does it differ from training arguments?
yolo settings manages persistent global settings (like default directories). Training arguments are per-run and override defaults. Settings persist across sessions; training arguments do not.
Q: How do I skip dependency checks for faster imports?
export ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS=1
Q: Can I use Ultralytics offline? Yes. Download models and datasets beforehand, then:
export YOLO_OFFLINE=True
yolo predict model=./yolo26n.pt source="image.jpg"
Q: What YOLO model versions are supported? YOLOv3, YOLOv5, YOLOv6, YOLOv8, YOLOv9, YOLOv10, YOLOv11, YOLOv12, YOLO26, plus specialized models: YOLO-World, YOLOE, YOLO-NAS, SAM, SAM3, FastSAM, and RTDETR.
Q: How do I load an older YOLO version model?
from ultralytics import YOLO
model = YOLO("yolov8n.pt") # YOLOv8
model = YOLO("yolov5nu.pt") # YOLOv5
model = YOLO("yolo11n.pt") # YOLOv11
All models use the same YOLO() interface regardless of version.