Improved CLI error reporting for users (#458)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
single_channel
Glenn Jocher 2 years ago committed by GitHub
parent db26ccba94
commit cc3c774bde
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -56,11 +56,17 @@ To request an Enterprise License please complete the form at [Ultralytics Licens
<div align="center"> <div align="center">
[Ultralytics Live Session 3](https://youtu.be/IPcpYO5ITa8) ✨ is here! Join us on January 24th at 18 CET as we dive into the latest advancements in YOLOv8, and demonstrate how to use this cutting-edge, SOTA model to improve your object detection, instance segmentation, and image classification projects. See firsthand how YOLOv8's speed, accuracy, and ease of use make it a top choice for professionals and researchers alike. [Ultralytics Live Session 3](https://youtu.be/IPcpYO5ITa8) ✨ is here! Join us on January 24th at 18 CET as we dive into
the latest advancements in YOLOv8, and demonstrate how to use this cutting-edge, SOTA model to improve your object
detection, instance segmentation, and image classification projects. See firsthand how YOLOv8's speed, accuracy, and
ease of use make it a top choice for professionals and researchers alike.
In addition to learning about the exciting new features and improvements of Ultralytics YOLOv8, you will also have the opportunity to ask questions and interact with our team during the live Q&A session. We encourage you to come prepared with any questions you may have. In addition to learning about the exciting new features and improvements of Ultralytics YOLOv8, you will also have the
opportunity to ask questions and interact with our team during the live Q&A session. We encourage you to come prepared
with any questions you may have.
To join the webinar, visit our YouTube [Channel](https://www.youtube.com/@Ultralytics/streams) and turn on your notifications! To join the webinar, visit our YouTube [Channel](https://www.youtube.com/@Ultralytics/streams) and turn on your
notifications!
<a align="center" href="https://youtu.be/IPcpYO5ITa8" target="_blank"> <a align="center" href="https://youtu.be/IPcpYO5ITa8" target="_blank">
<img width="80%" src="https://user-images.githubusercontent.com/107626595/212887899-e94b006c-5192-40fa-8b24-7b5428e065e8.png"></a> <img width="80%" src="https://user-images.githubusercontent.com/107626595/212887899-e94b006c-5192-40fa-8b24-7b5428e065e8.png"></a>
@ -68,8 +74,8 @@ To join the webinar, visit our YouTube [Channel](https://www.youtube.com/@Ultral
## <div align="center">Documentation</div> ## <div align="center">Documentation</div>
See below for a quickstart installation and usage example, and see the [YOLOv8 Docs](https://docs.ultralytics.com) for full See below for a quickstart installation and usage example, and see the [YOLOv8 Docs](https://docs.ultralytics.com) for
documentation on training, validation, prediction and deployment. full documentation on training, validation, prediction and deployment.
<details open> <details open>
<summary>Install</summary> <summary>Install</summary>
@ -88,22 +94,18 @@ pip install ultralytics
<details open> <details open>
<summary>Usage</summary> <summary>Usage</summary>
#### CLI
YOLOv8 may be used directly in the Command Line Interface (CLI) with a `yolo` command: YOLOv8 may be used directly in the Command Line Interface (CLI) with a `yolo` command:
```bash ```bash
yolo predict model=yolov8n.pt source="https://ultralytics.com/images/bus.jpg" yolo predict model=yolov8n.pt source="https://ultralytics.com/images/bus.jpg"
``` ```
`yolo` can be used for a variety of tasks and modes and accepts additional arguments, i.e. `imgsz=640`. See a full list `yolo` can be used for a variety of tasks and modes and accepts additional arguments, i.e. `imgsz=640`. See the YOLOv8
of available `yolo` [arguments](https://docs.ultralytics.com/config/) in the [CLI Docs](https://docs.ultralytics.com/cli) for examples.
YOLOv8 [Docs](https://docs.ultralytics.com).
```bash #### Python
yolo task=detect mode=train model=yolov8n.pt args...
classify predict yolov8n-cls.yaml args...
segment val yolov8n-seg.yaml args...
export yolov8n.pt format=onnx args...
```
YOLOv8 may also be used directly in a Python environment, and accepts the YOLOv8 may also be used directly in a Python environment, and accepts the
same [arguments](https://docs.ultralytics.com/config/) as in the CLI example above: same [arguments](https://docs.ultralytics.com/config/) as in the CLI example above:
@ -123,9 +125,10 @@ success = model.export(format="onnx") # export the model to ONNX format
``` ```
[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest [Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest
Ultralytics [release](https://github.com/ultralytics/assets/releases). Ultralytics [release](https://github.com/ultralytics/assets/releases). See
YOLOv8 [Python Docs](https://docs.ultralytics.com/python) for more examples.
### Known Issues / TODOs #### Known Issues / TODOs
We are still working on several parts of YOLOv8! We aim to have these completed soon to bring the YOLOv8 feature set up We are still working on several parts of YOLOv8! We aim to have these completed soon to bring the YOLOv8 feature set up
to par with YOLOv5, including export and inference to all the same formats. We are also writing a YOLOv8 paper which we to par with YOLOv5, including export and inference to all the same formats. We are also writing a YOLOv8 paper which we

@ -1,85 +1,196 @@
If you want to train, validate or run inference on models and don't need to make any modifications to the code, using The YOLO Command Line Interface (CLI) is the easiest way to get started training, validating, predicting and exporting
YOLO command line interface is the easiest way to get started. YOLOv8 models.
!!! tip "Syntax" The `yolo` command is used for all actions:
!!! example ""
=== "CLI"
```bash ```bash
yolo task=detect mode=train model=yolov8n.yaml args... yolo TASK MODE ARGS
classify predict yolov8n-cls.yaml args...
segment val yolov8n-seg.yaml args...
export yolov8n.pt format=onnx args...
``` ```
The default arguments can be overridden directly by passing custom `arg=val` covered in the next section. You can run Where:
any supported task by setting `task` and `mode` in CLI.
=== "Training"
| | `task` | snippet | - `TASK` (optional) is one of `[detect, segment, classify]`. If it is not passed explicitly YOLOv8 will try to guess
|------------------|------------|------------------------------------------------------------| the `TASK` from the model type.
| Detection | `detect` | <pre><code>yolo detect train </code></pre> | - `MODE` (required) is one of `[train, val, predict, export]`
| Instance Segment | `segment` | <pre><code>yolo segment train </code></pre> | - `ARGS` (optional) are any number of custom `arg=value` pairs like `imgsz=320` that override defaults.
| Classification | `classify` | <pre><code>yolo classify train </code></pre> | For a full list of available `ARGS` see the [Configuration](config.md) page.
=== "Prediction" !!! note ""
| | `task` | snippet | <b>Note:</b> Arguments MUST be passed as `arg=val` with an equals sign and a space between `arg=val` pairs
|------------------|------------|--------------------------------------------------------------|
| Detection | `detect` | <pre><code>yolo detect predict </code></pre> |
| Instance Segment | `segment` | <pre><code>yolo segment predict </code></pre> |
| Classification | `classify` | <pre><code>yolo classify predict </code></pre> |
=== "Validation" - `yolo predict model=yolov8n.pt imgsz=640 conf=0.25` &nbsp;
- `yolo predict model yolov8n.pt imgsz 640 conf 0.25` &nbsp;
- `yolo predict --model yolov8n.pt --imgsz 640 --conf 0.25` &nbsp;
| | `task` | snippet | ## Train
|------------------|------------|-----------------------------------------------------------|
| Detection | `detect` | <pre><code>yolo detect val </code></pre> |
| Instance Segment | `segment` | <pre><code>yolo segment val </code></pre> |
| Classification | `classify` | <pre><code>yolo classify val </code></pre> |
!!! note "" Train YOLOv8n on the COCO128 dataset for 100 epochs at image size 640. For a full list of available arguments see
the [Configuration](config.md) page.
<b>Note:</b> The arguments don't require `'--'` prefix. These are reserved for special commands covered later !!! example ""
--- === "CLI"
```bash
yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640
```
## Overriding default config arguments === "Python"
Default arguments can be overriden by simply passing them as arguments in the CLI. ```python
from ultralytics import YOLO
!!! tip "" # Load a model
model = YOLO("yolov8n.yaml") # build a new model from scratch
model = YOLO("yolov8n.pt") # load a pretrained model (recommended for training)
# Train the model
results = model.train(data="coco128.yaml", epochs=100, imgsz=640)
```
## Val
Validate trained YOLOv8n model accuracy on the COCO128 dataset. No argument need to passed as the `model` retains it's
training `data` and arguments as model attributes.
!!! example ""
=== "CLI"
=== "Syntax"
```bash ```bash
yolo task mode arg=val... yolo detect val model=yolov8n.pt # val official model
yolo detect val model=path/to/best.pt # val custom model
``` ```
=== "Example" === "Python"
Perform detection training for `10 epochs` with `learning_rate` of `0.01`
```python
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.pt") # load an official model
model = YOLO("path/to/best.pt") # load a custom model
# Validate the model
results = model.val() # no arguments needed, dataset and settings remembered
```
## Predict
Use a trained YOLOv8n model to run predictions on images.
!!! example ""
=== "CLI"
```bash ```bash
yolo detect train epochs=10 lr0=0.01 yolo detect predict model=yolov8n.pt source="https://ultralytics.com/images/bus.jpg" # predict with official model
yolo detect predict model=path/to/best.pt source="https://ultralytics.com/images/bus.jpg" # predict with custom model
``` ```
=== "Python"
```python
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.pt") # load an official model
model = YOLO("path/to/best.pt") # load a custom model
# Predict with the model
results = model("https://ultralytics.com/images/bus.jpg") # predict on an image
```
## Export
Export a YOLOv8n model to a different format like ONNX, CoreML, etc.
!!! example ""
=== "CLI"
```bash
yolo export model=yolov8n.pt format=onnx # export official model
yolo export model=path/to/best.pt format=onnx # export custom trained model
```
=== "Python"
```python
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.pt") # load an official model
model = YOLO("path/to/best.pt") # load a custom trained
# Export the model
model.export(format="onnx")
```
Available YOLOv8 export formats include:
| Format | `format=` | Model |
|----------------------------------------------------------------------------|--------------------|---------------------------|
| [PyTorch](https://pytorch.org/) | - | `yolov8n.pt` |
| [TorchScript](https://pytorch.org/docs/stable/jit.html) | `torchscript` | `yolov8n.torchscript` |
| [ONNX](https://onnx.ai/) | `onnx` | `yolov8n.onnx` |
| [OpenVINO](https://docs.openvino.ai/latest/index.html) | `openvino` | `yolov8n_openvino_model/` |
| [TensorRT](https://developer.nvidia.com/tensorrt) | `engine` | `yolov8n.engine` |
| [CoreML](https://github.com/apple/coremltools) | `coreml` | `yolov8n.mlmodel` |
| [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) | `saved_model` | `yolov8n_saved_model/` |
| [TensorFlow GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb` | `yolov8n.pb` |
| [TensorFlow Lite](https://www.tensorflow.org/lite) | `tflite` | `yolov8n.tflite` |
| [TensorFlow Edge TPU](https://coral.ai/docs/edgetpu/models-intro/) | `edgetpu` | `yolov8n_edgetpu.tflite` |
| [TensorFlow.js](https://www.tensorflow.org/js) | `tfjs` | `yolov8n_web_model/` |
| [PaddlePaddle](https://github.com/PaddlePaddle) | `paddle` | `yolov8n_paddle_model/` |
--- ---
## Overriding default config file ## Overriding default arguments
Default arguments can be overriden by simply passing them as arguments in the CLI in `arg=value` pairs.
You can override config file entirely by passing a new file. You can create a copy of default config file in your !!! tip ""
current working dir as follows:
=== "Example 1"
Train a detection model for `10 epochs` with `learning_rate` of `0.01`
```bash ```bash
yolo copy-config yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01
``` ```
You can then use `cfg=default_copy.yaml` command to pass the new config file along with any addition args: === "Example 2"
Predict a YouTube video using a pretrained segmentation model at image size 320:
```bash
yolo segment predict model=yolov8n-seg.pt source=https://youtu.be/Zgi9g1ksQHc imgsz=320
```
=== "Example 3"
Validate a pretrained detection model at batch-size 1 and image size 640:
```bash ```bash
yolo cfg=default_copy.yaml args... yolo detect val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640
``` ```
??? example ---
## Overriding default config file
You can override the `default.yaml` config file entirely by passing a new file with the `cfg` arguments,
i.e. `cfg=custom.yaml`.
To do this first create a copy of `default.yaml` in your current working dir with the `yolo copy-config` command.
This will create `default_copy.yaml`, which you can then pass as `cfg=default_copy.yaml` along with any additional args,
like `imgsz=320` in this example:
!!! example ""
=== "Command" === "CLI"
```bash ```bash
yolo copy-config yolo copy-config
yolo cfg=default_copy.yaml args... yolo cfg=default_copy.yaml imgsz=320
``` ```

@ -1,9 +1,9 @@
# Ultralytics YOLO 🚀, GPL-3.0 license # Ultralytics YOLO 🚀, GPL-3.0 license
__version__ = "8.0.7" __version__ = "8.0.8"
from ultralytics.hub import checks
from ultralytics.yolo.engine.model import YOLO from ultralytics.yolo.engine.model import YOLO
from ultralytics.yolo.utils import ops from ultralytics.yolo.utils import ops
from ultralytics.yolo.utils.checks import check_yolo as checks
__all__ = ["__version__", "YOLO", "hub", "checks"] # allow simpler import __all__ = ["__version__", "YOLO", "hub", "checks"] # allow simpler import

@ -1,38 +1,14 @@
# Ultralytics YOLO 🚀, GPL-3.0 license # Ultralytics YOLO 🚀, GPL-3.0 license
import os
import shutil
import psutil
import requests import requests
from IPython import display # to display images and clear console output
from ultralytics.hub.auth import Auth from ultralytics.hub.auth import Auth
from ultralytics.hub.session import HubTrainingSession from ultralytics.hub.session import HubTrainingSession
from ultralytics.hub.utils import PREFIX, split_key from ultralytics.hub.utils import PREFIX, split_key
from ultralytics.yolo.utils import LOGGER, emojis, is_colab from ultralytics.yolo.utils import LOGGER, emojis
from ultralytics.yolo.utils.torch_utils import select_device
from ultralytics.yolo.v8.detect import DetectionTrainer from ultralytics.yolo.v8.detect import DetectionTrainer
def checks(verbose=True):
if is_colab():
shutil.rmtree('sample_data', ignore_errors=True) # remove colab /sample_data directory
if verbose:
# System info
gib = 1 << 30 # bytes per GiB
ram = psutil.virtual_memory().total
total, used, free = shutil.disk_usage("/")
display.clear_output()
s = f'({os.cpu_count()} CPUs, {ram / gib:.1f} GB RAM, {(total - free) / gib:.1f}/{total / gib:.1f} GB disk)'
else:
s = ''
select_device(newline=False)
LOGGER.info(f'Setup complete ✅ {s}')
def start(key=''): def start(key=''):
# Start training models with Ultralytics HUB. Usage: from src.ultralytics import start; start('API_KEY') # Start training models with Ultralytics HUB. Usage: from src.ultralytics import start; start('API_KEY')
def request_api_key(attempts=0): def request_api_key(attempts=0):

@ -4,13 +4,53 @@ import argparse
import shutil import shutil
from pathlib import Path from pathlib import Path
from hydra import compose, initialize from ultralytics import __version__, yolo
from ultralytics.yolo.utils import DEFAULT_CONFIG, LOGGER, PREFIX, checks, print_settings, yaml_load
from ultralytics import hub, yolo
from ultralytics.yolo.utils import DEFAULT_CONFIG, HELP_MSG, LOGGER, PREFIX, print_settings, yaml_load
DIR = Path(__file__).parent DIR = Path(__file__).parent
CLI_HELP_MSG = \
"""
YOLOv8 CLI Usage examples:
1. Install the ultralytics package:
pip install ultralytics
2. Train, Val, Predict and Export using 'yolo' commands of the form:
yolo TASK MODE ARGS
Where TASK (optional) is one of [detect, segment, classify]
MODE (required) is one of [train, val, predict, export]
ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.
For a full list of available ARGS see https://docs.ultralytics.com/config.
Train a detection model for 10 epochs with an initial learning_rate of 0.01
yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01
Predict a YouTube video using a pretrained segmentation model at image size 320:
yolo segment predict model=yolov8n-seg.pt source=https://youtu.be/Zgi9g1ksQHc imgsz=320
Validate a pretrained detection model at batch-size 1 and image size 640:
yolo detect val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640
Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)
yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128
3. Run special commands:
yolo help
yolo checks
yolo version
yolo settings
yolo copy-config
Docs: https://docs.ultralytics.com/cli
Community: https://community.ultralytics.com
GitHub: https://github.com/ultralytics/ultralytics
"""
def cli(cfg): def cli(cfg):
""" """
@ -28,20 +68,16 @@ def cli(cfg):
task, mode = cfg.task.lower(), cfg.mode.lower() task, mode = cfg.task.lower(), cfg.mode.lower()
# Mapping from task to module # Mapping from task to module
task_module_map = {"detect": yolo.v8.detect, "segment": yolo.v8.segment, "classify": yolo.v8.classify} tasks = {"detect": yolo.v8.detect, "segment": yolo.v8.segment, "classify": yolo.v8.classify}
module = task_module_map.get(task) module = tasks.get(task)
if not module: if not module:
raise SyntaxError(f"task not recognized. Choices are {', '.join(task_module_map.keys())}") raise SyntaxError(f"yolo task={task} is invalid. Valid tasks are: {', '.join(tasks.keys())}\n{CLI_HELP_MSG}")
# Mapping from mode to function # Mapping from mode to function
mode_func_map = { modes = {"train": module.train, "val": module.val, "predict": module.predict, "export": yolo.engine.exporter.export}
"train": module.train, func = modes.get(mode)
"val": module.val,
"predict": module.predict,
"export": yolo.engine.exporter.export}
func = mode_func_map.get(mode)
if not func: if not func:
raise SyntaxError(f"mode not recognized. Choices are {', '.join(mode_func_map.keys())}") raise SyntaxError(f"yolo mode={mode} is invalid. Valid modes are: {', '.join(modes.keys())}\n{CLI_HELP_MSG}")
func(cfg) func(cfg)
@ -68,8 +104,9 @@ def entrypoint():
tasks = 'detect', 'segment', 'classify' tasks = 'detect', 'segment', 'classify'
modes = 'train', 'val', 'predict', 'export' modes = 'train', 'val', 'predict', 'export'
special_modes = { special_modes = {
'checks': hub.checks, 'help': lambda: LOGGER.info(CLI_HELP_MSG),
'help': lambda: LOGGER.info(HELP_MSG), 'checks': checks.check_yolo,
'version': lambda: LOGGER.info(__version__),
'settings': print_settings, 'settings': print_settings,
'copy-config': copy_default_config} 'copy-config': copy_default_config}
@ -87,8 +124,17 @@ def entrypoint():
return return
elif a in defaults and defaults[a] is False: elif a in defaults and defaults[a] is False:
overrides.append(f'{a}=True') # auto-True for default False args, i.e. yolo show overrides.append(f'{a}=True') # auto-True for default False args, i.e. yolo show
elif a in defaults:
raise SyntaxError(f"'{a}' is a valid YOLO argument but is missing an '=' sign to set its value, "
f"i.e. try '{a}={defaults[a]}'"
f"\n{CLI_HELP_MSG}")
else: else:
raise (SyntaxError(f"'{a}' is not a valid yolo argument\n{HELP_MSG}")) raise SyntaxError(
f"'{a}' is not a valid YOLO argument. For a full list of valid arguments see "
f"https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/configs/default.yaml"
f"\n{CLI_HELP_MSG}")
from hydra import compose, initialize
with initialize(version_base=None, config_path=str(DEFAULT_CONFIG.parent.relative_to(DIR)), job_name="YOLO"): with initialize(version_base=None, config_path=str(DEFAULT_CONFIG.parent.relative_to(DIR)), job_name="YOLO"):
cfg = compose(config_name=DEFAULT_CONFIG.name, overrides=overrides) cfg = compose(config_name=DEFAULT_CONFIG.name, overrides=overrides)

@ -3,7 +3,9 @@
import glob import glob
import inspect import inspect
import math import math
import os
import platform import platform
import shutil
import urllib import urllib
from pathlib import Path from pathlib import Path
from subprocess import check_output from subprocess import check_output
@ -12,10 +14,12 @@ from typing import Optional
import cv2 import cv2
import numpy as np import numpy as np
import pkg_resources as pkg import pkg_resources as pkg
import psutil
import torch import torch
from IPython import display
from ultralytics.yolo.utils import (AUTOINSTALL, FONT, LOGGER, ROOT, USER_CONFIG_DIR, TryExcept, colorstr, emojis, from ultralytics.yolo.utils import (AUTOINSTALL, FONT, LOGGER, ROOT, USER_CONFIG_DIR, TryExcept, colorstr, emojis,
is_docker, is_jupyter_notebook) is_colab, is_docker, is_jupyter_notebook)
def is_ascii(s) -> bool: def is_ascii(s) -> bool:
@ -245,6 +249,26 @@ def check_imshow(warn=False):
return False return False
def check_yolo(verbose=True):
from ultralytics.yolo.utils.torch_utils import select_device
if is_colab():
shutil.rmtree('sample_data', ignore_errors=True) # remove colab /sample_data directory
if verbose:
# System info
gib = 1 << 30 # bytes per GiB
ram = psutil.virtual_memory().total
total, used, free = shutil.disk_usage("/")
display.clear_output()
s = f'({os.cpu_count()} CPUs, {ram / gib:.1f} GB RAM, {(total - free) / gib:.1f}/{total / gib:.1f} GB disk)'
else:
s = ''
select_device(newline=False)
LOGGER.info(f'Setup complete ✅ {s}')
def git_describe(path=ROOT): # path must be a directory def git_describe(path=ROOT): # path must be a directory
# Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
try: try:

Loading…
Cancel
Save