SuperGradients

repository·master·Indexed 26 days ago

https://github.com/deci-ai/super-gradients

A deep learning library for building, training, and fine-tuning state-of-the-art (SOTA) computer vision models. It supports tasks including classification, semantic segmentation, object detection, and pose estimation. Key features include a SOTA model zoo (e.g., YOLO-NAS), plug-and-play training recipes via CLI, Distributed Data Parallel (DDP) for multi-GPU training, and tools for ONNX, TensorRT, and OpenVINO conversion.

Tokens
88.3K
Snippets
224
Records
344
Agent score
84%

What's inside SuperGradients

  1. Overview of Pose Estimation in SuperGradients

    master

    SuperGradients supports both top-down and bottom-up approaches for pose estimation:

    • Top-down approach: Uses an object detection model to identify an object (e.g., a person) first, then applies a pose estimation model to that specific object.
    • Bottom-up approach: Identifies individual body parts or joints across the entire image first, then connects them to form complete poses.

    Supported models include DEKR, which utilizes specific target generators, loss functions, and callbacks for decoding and visualization.

  2. Overview of the super_gradients.training package

    master

    The super_gradients.training package is the core module for training computer vision models. It provides a comprehensive suite of tools including datasets, dataloaders, loss functions, metrics, model architectures, and trainers.

    Key submodules include:

    • super_gradients.training.datasets: Tools for managing and loading datasets.
    • super_gradients.training.dataloaders: Data loading utilities.
    • super_gradients.training.losses: Implementation of various loss functions.
    • super_gradients.training.metrics: Evaluation metrics for model performance.
    • super_gradients.training.models: Pre-defined model architectures.
    • super_gradients.training.sg_trainer: The primary trainer class for executing training loops.
    • super_gradients.training.transforms: Image and data augmentation transformations.
  3. Introduction to SuperGradients

    master

    SuperGradients is an open-source PyTorch-based deep learning training library designed for computer vision tasks. It provides tools to train or fine-tune State-of-the-Art (SOTA) pre-trained models.

    Supported tasks include:

    • Object detection
    • Image classification
    • Semantic segmentation (for both images and videos)
    • Pose estimation
  4. Explore the super_gradients.common package modules

    master

    The super_gradients.common package provides core utilities, abstractions, and infrastructure used throughout the SuperGradients library. Key submodules include:

    • auto_logging: Utilities for automated logging configuration.
    • abstraction: Base classes and architectural abstractions.
    • data_connection, data_interface, and data_types: Core components for handling data pipelines, interfaces, and type definitions.
    • decorators: Utility decorators for common functional patterns.
    • environment: Tools for managing environment variables and system configurations.
    • factories: Factory patterns for object instantiation.
    • plugins: Infrastructure for extending library functionality via plugins.
    • registry: Centralized registry for managing and retrieving components (e.g., models, datasets, or optimizers).
    • sg_loggers: Specialized logging implementations for SuperGradients.
  5. Understand Hydra integration in SuperGradients

    master

    SuperGradients uses the Hydra framework to manage YAML files. Hydra loads YAML files, converts them into dictionaries, and instantiates objects referenced within the configuration.

    Key behaviors:

    • The @hydra.main decorator looks for YAML files in super_gradients.recipes based on the configuration name provided via the command line.
    • When a run is executed, a .hydra subdirectory is created in the experiment directory containing the configuration files used for that specific run.
    • Users can leverage Hydra's Command-Line Overrides and YAML Composition to dynamically modify configurations during execution.
  6. Supported Datasets

    master

    SuperGradients provides implementations for several standard datasets. Detailed instructions for downloading datasets can be found in the Dataset Setup Instructions.

    Image Classification

    • Cifar10, ImageNet.

    Semantic Segmentation

    • Cityscapes, Coco, PascalVOC 2012 / PascalAUG 2012, SuperviselyPersons, Mapillary Vistas Dataset.

    Object Detection

    • Coco, PascalVOC 2007 & 2012.

    Pose Estimation

    • COCO.
  7. Supported Model Architectures

    master

    SuperGradients implements a wide variety of state-of-the-art architectures across different computer vision tasks. Pre-trained checkpoints for these models can be found in the Model Zoo.

    Image Classification

    • DensNet, DPN, EfficientNet, LeNet, MobileNet (v1, v2, v3), PNASNet, Pre-activation ResNet, RegNet, RepVGG, ResNet, ResNeXt, SENet, ShuffleNet (v1, v2), VGG.

    Semantic Segmentation

    • PP-LiteSeg, DDRNet, LadderNet, RegSeg, ShelfNet, STDC.

    Object Detection

    • CSP DarkNet, DarkNet-53, SSD, YOLOX.

    Pose Estimation

    • DEKR-W32-NO-DC.
  8. Understand Experiment Management Core Concepts

    master

    SuperGradients organizes training outputs using a hierarchical structure to prevent data overwrites and ensure traceability:

    • Checkpoint Root Directory (ckpt_root_dir): The top-level directory containing all experiment outputs.
    • Experiments (experiment_name): Represents a specific training recipe or configuration. Changing the experiment_name is recommended when updating your training recipe to maintain transparency.
    • Runs (run_id): Represents an individual training session. A unique run_id is automatically generated for every training session, even if the parameters are identical to a previous run. This ensures that logs and checkpoints for different sessions under the same experiment name are kept separate.
  9. Implement a custom Pose Estimation dataset

    master

    To add a new dataset for pose estimation, subclass BaseKeypointsDataset. You must implement the __len__ method and the load_sample method. The load_sample method must return a tuple of (image, mask, joints, extras) with the following specifications:

    • image: Numpy array of [H, W, 3] (RGB).
    • mask: Numpy array of [H, W] (binary mask where zero values indicate ignored regions).
    • joints: Numpy array of [Num Instances, Num Joints, 3] representing skeletons.
    • extras: A dictionary for additional sample information.
    from super_gradients.training.datasets.pose_estimation_datasets import BaseKeypointsDataset
    from super_gradients.training.datasets.pose_estimation_datasets import KeypointsTargetsGenerator
    from super_gradients.training.transforms.keypoint_transforms import KeypointTransform
    from typing import Tuple, Dict, Any, List
    import numpy as np
    import cv2
    
    class MyNewPoseEstimationDataset(BaseKeypointsDataset):
        def __init__(
                self,
                image_paths,
                joint_paths,
                target_generator: KeypointsTargetsGenerator,
                transforms: List[KeypointTransform],
                min_instance_area: float = 0.0,
        ):
            super().__init__(target_generator, transforms, min_instance_area)
            self.image_paths = image_paths
            self.joint_paths = joint_paths
    
        def __len__(self) -> int:
            return len(self.image_paths)
    
        def load_sample(self, index) -> Tuple[np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]:
            # Read image from the disk
            image = cv2.imread(self.image_paths[index])
            mask = np.ones(image.shape[:2])
            joints = np.loadtxt(self.joint_paths[index])
            return image, mask, joints, {}
  10. Define a custom loss function for SuperGradients

    master

    To use a custom loss function in the SuperGradients training pipeline, create a class that inherits from torch.nn.Module. The forward() method must accept two parameters in this specific order: preds (the predictions tensor) and target (the target tensor). This allows you to implement specialized loss logic, such as combining Binary Cross-Entropy (BCE) with a custom Intersection-over-Union (IoU) loss.

    import torch
    import torch.nn as nn
    
    class CustomIoU(torch.nn.Module):
        def __init__(self):
            super(CustomIoU, self).__init__()
    
        def forward(self, preds, target):
            intersection = torch.sum(target * preds)
            union = torch.sum(target) + torch.sum(preds) - intersection + 1e-5
            iou = intersection / union
            return iou
    
    class CustomSegLoss(torch.nn.Module):
        def __init__(self, bce_weight=1, iou_weight=1):
            super(CustomSegLoss, self).__init__()
            self.bce_weight = bce_weight
            self.iou_weight = iou_weight
            self.bce_loss = nn.BCELoss()
            self.iou_func = CustomIoU()
    
        def forward(self, preds, target):
            bce_loss = self.bce_loss(preds, target)
            # Binarize predictions and targets for IoU calculation
            iou_loss = 1.0 - self.iou_func(torch.gt(preds, 0.5).long(), torch.gt(target, 0.5).long())
            return self.bce_weight * bce_loss + self.iou_weight * iou_loss
  11. Export YoloNAS-Pose models to ONNX

    master

    You can export YoloNAS-Pose models (N, S, M, L) to the .onnx format using the export() method. This method automatically attaches preprocessing (e.g., normalization/standardization) and postprocessing (e.g., NMS decoding) to the ONNX graph, providing ready-to-consume bounding box and pose outputs.

    Key features include:

    • Support for FP16 / INT8 quantization with calibration.
    • Customization of input image shape and batch size.
    • Customization of NMS parameters and number of detections.
    • Choice of output format: flat or batch.
    from super_gradients.common.object_names import Models
    from super_gradients.training import models
    
    model = models.get(Models.YOLO_NAS_POSE_S, pretrained_weights="coco_pose")
    export_result = model.export("yolo_nas_pose_s.onnx")