yolo Documentation

repository·main·Indexed 23 days ago

https://github.com/multimediatechlab/yolo

Official implementation of YOLO, a high-performance object detection framework for training and deploying computer vision models. It features support for YOLOv7 and YOLOv9, modular customization via Hydra YAML configurations, and optimized deployment options including ONNX and TensorRT. The framework provides specialized tools such as ModelTrainer for training, ModelValidator for performance evaluation, and FastModelLoader for accelerated inference.

Tokens
10.6K
Snippets
23
Records
56
Agent score
82%

What's inside yolo

  1. Understand StreamDataLoader return types for inference

    main

    When iterating through a StreamDataLoader (used for inference tasks), each iteration returns:

    • images: The input image tensor.
    • rev_tensor: A reverse tensor used to revert bounding boxes and images back to their original input shape.
    • origin_frame: The original input image tensor.
  2. Understand the YOLOv9 Forward Process

    main

    The YOLOv9 forward process is a multi-stage pipeline designed to extract features and generate object detections in a single pass. The architecture consists of the following components:

    • BackBone: Responsible for extracting features from the input image.
    • FPN (Feature Pyramid Network): Aggregates features across different scales.
    • PAN (Region Proposal Network): Proposes regions of interest.
    • Main Prediction: The primary output containing the detected objects.
    • Auxiliary Prediction: An additional prediction path used to assist and improve the accuracy of the Main Prediction.
  3. Understand the YOLOv9 Loss Function components

    main

    YOLOv9 optimizes its performance using a composite loss function that evaluates the accuracy of both class predictions and bounding box regressions. The total loss is composed of:

    • IoU Loss: Measures the overlap (Intersection over Union) between the predicted bounding boxes and the Ground Truth boxes.
    • BCE (Binary Cross-Entropy) Loss: Used to optimize class prediction accuracy.
    • DFL (Distribution Focal Loss): Used to improve the precision and refinement of bounding box regression.
  4. Understand the YOLO configuration hierarchy

    main

    The YOLO configuration system is organized into a hierarchical structure of specialized configuration objects. The root object is yolo.config.config.Config, which composes several sub-configurations depending on the operation (Training, Inference, or Validation).

    Core Configuration Components

    • Config (Root): The top-level container that aggregates DatasetConfig, ModelConfig, GeneralConfig, and a task-specific configuration (TrainConfig, InferenceConfig, or ValidationConfig).
    • ModelConfig: Defines the architecture, including AnchorConfig (strides, reg_max, anchor dimensions) and a model dictionary containing BlockConfig (sequences of LayerConfig).
    • DatasetConfig: Specifies the data source via path, class_num, class_list, and optional auto_download settings.
    • GeneralConfig: Handles global execution settings such as device, cpu_num, image_size, out_path, and logging preferences (use_wandb, use_TensorBoard).

    Task-Specific Configurations

    Depending on the task selected, the Config object will include one of the following:

    1. TrainConfig: Used for model training. Includes DataConfig (batch size, shuffle, augmentation), OptimizerConfig (learning rate, weight decay), LossConfig (objective, matcher), SchedulerConfig, and EMAConfig (Exponential Moving Average).
    2. InferenceConfig: Used for running predictions. Includes DataConfig and NMSConfig (Non-Maximum Suppression settings like min_confidence and min_iou).
    3. ValidationConfig: Used for evaluating model performance. Includes DataConfig and NMSConfig.
  5. Understand YoloDataLoader return types for training and validation

    main

    When iterating through a YoloDataLoader (used for train or validation tasks), each iteration returns a batch containing:

    • batch_size: The size of the current batch (useful for calculating batch average loss).
    • images: The input image tensors.
    • targets: The ground truth data corresponding to the images based on the current task.
  6. How YOLO prediction and conversion works

    main

    The model's output format depends on the YOLO version:

    • YOLOv7: Predicts Anchor (Anc).
    • YOLOv9: Predicts Vector (Vec).

    A converter is required to transform these predictions into bounding boxes. The data flow follows this pattern:

    Input $\rightarrow$ Model $\rightarrow$ (Class $\rightarrow$ NMS) AND (Anc/Vec $\rightarrow$ Converter $\rightarrow$ Box $\rightarrow$ NMS) $\rightarrow$ Output.

  7. Install YOLO

    main

    You can install YOLO using two methods depending on whether you want to modify the source code or just use the package.

    Method 1: Clone for Development

    Use this method if you intend to make customizations. You must work inside the cloned folder.

    Method 2: Pip Install for Simple Changes

    Use this method for simple changes or standard usage.

    Note: When running commands via the script, replace python yolo/lazy.py with the yolo command if you installed via pip. Most tasks are accessible via the yolo/lazy.py prefix.

    # Method 1: Clone and install dependencies
    git clone https://github.com/WongKinYiu/YOLO.git
    cd YOLO
    pip install -r requirements-dev.txt
    
    # Method 2: Install via pip
    pip install git+https://github.com/WongKinYiu/YOLO.git
  8. Enable auto-download for datasets

    main

    If you provide the auto_download configuration in your dataset settings, the system will automatically download and unzip the dataset from a specified {prefix}/{postfix}.

    After downloading, the system:

    1. Verifies the dataset contains the expected {file_num} files.
    2. Generates {train, validation}.cache files in Tensor format to accelerate subsequent dataset preparation.
  9. Configure YOLO using Hydra

    main

    YOLO uses hydra to manage its configuration. You must generate a configuration class based on yolo.config.config.Config. The resulting configuration object contains settings for your task, including general settings, dataset information, and task-specific parameters for train, inference, and validation.

    import hydra
    from yolo import ProgressLogger
    from yolo.config.config import Config
    
    @hydra.main(config_path="config", config_name="config", version_base=None)
    def main(cfg: Config):
        progress = ProgressLogger(cfg, exp_name=cfg.name)
        pass
  10. Run YOLO tasks via CLI

    main

    The YOLO project uses yolo/lazy.py as the primary entry point for executing different tasks. You can specify the task type (train, validation, inference) and override various parameters using command-line arguments.

    Common Tasks

    Training Run training with a specific dataset and enable Weights & Biases (wandb) logging:

    python yolo/lazy.py task=train dataset=dev use_wandb=True

    Validation Run validation on a specific model and dataset:

    python yolo/lazy.py task=validation model=v9-s dataset=toy name=validation

    Inference Run inference with various configurations such as device selection, image size, or NMS thresholds:

    python yolo/lazy.py task=inference device=cpu image_size=[480,640] task.nms.min_confidence=0.1

    Inference Configuration Options

    • device: Specify hardware (e.g., cpu).
    • +quiet=True: Enable quiet mode.
    • name: Set a custom name for the inference run.
    • image_size: Set input dimensions as a list, e.g., [480,640].
    • task.nms.min_confidence: Set the minimum confidence threshold for Non-Maximum Suppression.
    • task.fast_inference: Set to deploy or onnx (e.g., task.fast_inference=onnx device=cpu).
    • task.data.source: Specify the image source path (e.g., task.data.source=data/toy/images/train).
    # Train
    python yolo/lazy.py task=train dataset=dev use_wandb=True
    
    # Validate
    python yolo/lazy.py task=validation
    python yolo/lazy.py task=validation model=v9-s
    python yolo/lazy.py task=validation dataset=toy
    python yolo/lazy.py task=validation dataset=toy name=validation
    
    # Inference
    python yolo/lazy.py task=inference
    python yolo/lazy.py task=inference device=cpu
    python yolo/lazy.py task=inference +quiet=True
    python yolo/lazy.py task=inference name=AnyNameYouWant
    python yolo/lazy.py task=inference image_size=\[480,640]
    python yolo/lazy.py task=inference task.nms.min_confidence=0.1
    python yolo/lazy.py task=inference task.fast_inference=deploy
    python yolo/lazy.py task=inference task.fast_inference=onnx device=cpu
    python yolo/lazy.py task=inference task.data.source=data/toy/images/train
  11. Train a model using ModelTrainer

    main

    To manage the training process, use the ModelTrainer class. Before calling the solver, you must start the progress logger to enable status logging and integration with Weights & Biases (wandb) or TensorBoard.

    1. Initialize ModelTrainer with your configuration, model, converter, progress logger, device, and DDP settings.
    2. Call progress.start().
    3. Call solver.solve(dataloader) to begin training.
    from yolo import ModelTrainer
    solver = ModelTrainer(cfg, model, converter, progress, device, use_ddp)
    progress.start()
    solver.solve(dataloader)