instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Generate missing documentation strings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import ast import shutil import subprocess import sys from pathlib import Path from types import SimpleNamespace from typing import Any from ultralytics import __version__ from ultralytics.utils import ( ASSETS...
--- +++ @@ -244,6 +244,32 @@ def cfg2dict(cfg: str | Path | dict | SimpleNamespace) -> dict: + """Convert a configuration object to a dictionary. + + Args: + cfg (str | Path | dict | SimpleNamespace): Configuration object to be converted. Can be a file path, a string, a + dictionary, or a Si...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/cfg/__init__.py
Write reusable docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. from __future__ import annotations import torch import torch.nn.functional as F from torch import nn from torch.nn.init import trunc_normal_ from ultralytics.nn.modules imp...
--- +++ @@ -23,6 +23,32 @@ class SAMModel(nn.Module): + """Segment Anything Model (SAM) for object segmentation tasks. + + This class combines image encoders, prompt encoders, and mask decoders to predict object masks from images and input + prompts. + + Attributes: + mask_threshold (float): Thre...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/modules/sam.py
Write reusable docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import json from collections import defaultdict from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from typing import Any import cv2 import numpy as np import torch fr...
--- +++ @@ -47,8 +47,39 @@ class YOLODataset(BaseDataset): + """Dataset class for loading object detection and/or segmentation labels in YOLO format. + + This class supports loading data for object detection, segmentation, pose estimation, and oriented bounding box + (OBB) tasks using the YOLO format. + + ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/dataset.py
Add inline docstrings for readability
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import copy import torch from torch import nn from .blocks import RoPEAttention class MemoryAttentionLayer(nn.Module): def __init__( self, d_model: int = 256, dim_feedforward: int = ...
--- +++ @@ -11,6 +11,45 @@ class MemoryAttentionLayer(nn.Module): + """Implements a memory attention layer with self-attention and cross-attention mechanisms for neural networks. + + This class combines self-attention, cross-attention, and feedforward components to process input tensors and + generate memo...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/modules/memory_attention.py
Document all endpoints with docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import json import time from pathlib import Path import numpy as np import torch import torch.distributed as dist from ultralytics.cfg import get_cfg, get_save_dir from ultralytics.data.utils import check_cls_data...
--- +++ @@ -1,4 +1,27 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Check a model's accuracy on a test or val split of a dataset. + +Usage: + $ yolo mode=val model=yolo26n.pt data=coco8.yaml imgsz=640 + +Usage - formats: + $ yolo mode=val model=yolo26n.pt # PyTorch +...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/engine/validator.py
Provide docstrings following PEP 257
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any import numpy as np import torch from ultralytics.models.yolo.detect import DetectionValidator from ultralytics.utils import LOGGER, ops from ultralytics.utils.metric...
--- +++ @@ -16,31 +16,114 @@ class OBBValidator(DetectionValidator): + """A class extending the DetectionValidator class for validation based on an Oriented Bounding Box (OBB) model. + + This validator specializes in evaluating models that predict rotated bounding boxes, commonly used for aerial and + sate...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/obb/val.py
Write docstrings describing functionality
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from ultralytics.models.yolo.segment import SegmentationValidator class FastSAMValidator(SegmentationValidator): def __init__(self, dataloader=None, save_dir=None, args=None, _callbacks: dict | None = None): ...
--- +++ @@ -6,8 +6,35 @@ class FastSAMValidator(SegmentationValidator): + """Custom validation class for FastSAM (Segment Anything Model) segmentation in the Ultralytics YOLO framework. + + Extends the SegmentationValidator class, customizing the validation process specifically for FastSAM. This class + se...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/fastsam/val.py
Create docstrings for each class method
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved # Based on https://github.com/IDEA-Research/GroundingDINO from __future__ import annotations import torch from torch import nn from ultralytics.nn.modules.utils import _get_clo...
--- +++ @@ -13,6 +13,15 @@ class TransformerEncoderLayer(nn.Module): + """Transformer encoder layer that performs self-attention followed by cross-attention. + + This layer was previously called TransformerDecoderLayer but was renamed to better reflect its role in the + architecture. It processes input seq...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/encoder.py
Replace inline comments with docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved from __future__ import annotations from copy import deepcopy import torch from ultralytics.nn.modules.utils import inverse_sigmoid from ultralytics.utils.ops import xywh2xyxy...
--- +++ @@ -17,6 +17,7 @@ def _update_out(out, out_name, out_value, auxiliary=True, update_aux=True): + """Helper function to update output dictionary with main and auxiliary outputs.""" out[out_name] = out_value[-1] if auxiliary else out_value if auxiliary and update_aux: if "aux_outputs" not...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/sam3_image.py
Generate docstrings with parameter types
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved from __future__ import annotations import math import numpy as np import torch from torch import Tensor, nn class DotProductScoring(torch.nn.Module): def __init__( ...
--- +++ @@ -2,6 +2,7 @@ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved +"""Various utility models.""" from __future__ import annotations @@ -13,6 +14,7 @@ class DotProductScoring(torch.nn.Module): + """A module that computes dot-product scores between query features and pooled ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/model_misc.py
Add inline docstrings for readability
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import itertools from pathlib import Path from typing import Any import torch from ultralytics.data import build_yolo_dataset from ultralytics.models.yolo.detect import DetectionTrainer from ultralytics.nn.tasks i...
--- +++ @@ -16,6 +16,7 @@ def on_pretrain_routine_end(trainer) -> None: + """Set up model classes and text encoder at the end of the pretrain routine.""" if RANK in {-1, 0}: # Set class names for evaluation names = [name.split("/", 1)[0] for name in list(trainer.test_loader.dataset.data["n...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/world/train.py
Document all endpoints with docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import torch import torch.nn as nn import torch.nn.functional as F from ultralytics.nn.modules import LayerNorm2d from .blocks import ( Block, CXBlock, Fuser, MaskDownSampler, MultiScaleBlock, ...
--- +++ @@ -21,6 +21,28 @@ class ImageEncoderViT(nn.Module): + """An image encoder using Vision Transformer (ViT) architecture for encoding images into a compact latent space. + + This class processes images by splitting them into patches, applying transformer blocks, and generating a final + encoded repre...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/modules/encoders.py
Generate docstrings for script automation
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import math from collections.abc import Generator from itertools import product from typing import Any import numpy as np import torch def is_box_near_crop_edge( boxes: torch.Tensor, crop_box: list[int], orig...
--- +++ @@ -14,6 +14,23 @@ def is_box_near_crop_edge( boxes: torch.Tensor, crop_box: list[int], orig_box: list[int], atol: float = 20.0 ) -> torch.Tensor: + """Determine if bounding boxes are near the edge of a cropped image region using a specified tolerance. + + Args: + boxes (torch.Tensor): Boundi...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/amg.py
Add docstrings to my Python code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any import numpy as np import torch import torch.nn.functional as F from ultralytics.models.yolo.detect import DetectionValidator from ultralytics.utils import LOGGER, o...
--- +++ @@ -16,19 +16,58 @@ class SegmentationValidator(DetectionValidator): + """A class extending the DetectionValidator class for validation based on a segmentation model. + + This validator handles the evaluation of segmentation models, processing both bounding box and mask predictions to + compute met...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/segment/val.py
Improve documentation using docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved from __future__ import annotations from copy import deepcopy import torch import torch.nn as nn class Sam3DualViTDetNeck(nn.Module): def __init__( self, ...
--- +++ @@ -2,6 +2,7 @@ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved +"""Necks are the interface between a vision backbone and the rest of the detection model.""" from __future__ import annotations @@ -12,6 +13,7 @@ class Sam3DualViTDetNeck(nn.Module): + """A neck that implem...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/necks.py
Add docstrings including usage examples
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import math import random from copy import deepcopy from typing import Any import cv2 import numpy as np import torch from PIL import Image from torch.nn import functional as F from ultralytics.data.utils import p...
--- +++ @@ -26,46 +26,230 @@ class BaseTransform: + """Base class for image transformations in the Ultralytics library. + + This class serves as a foundation for implementing various image processing operations, designed to be compatible + with both classification and semantic segmentation tasks. + + Me...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/augment.py
Write docstrings describing each step
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from ultralytics.hub.utils import HUB_API_ROOT, HUB_WEB_ROOT, PREFIX, request_with_credentials from ultralytics.utils import IS_COLAB, LOGGER, SETTINGS, emojis API_KEY_URL = f"{HUB_WEB_ROOT}/settings?tab=api+keys" ...
--- +++ @@ -9,10 +9,44 @@ class Auth: + """Manages authentication processes including API key handling, cookie-based authentication, and header generation. + + The class supports different methods of authentication: + 1. Directly using an API key. + 2. Authenticating using browser cookies (specifically ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/hub/auth.py
Write clean docstrings for readability
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import asyncio import hashlib import json import random import shutil from collections import defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path import cv2 import n...
--- +++ @@ -22,6 +22,12 @@ def coco91_to_coco80_class() -> list[int]: + """Convert 91-index COCO class IDs to 80-index COCO class IDs. + + Returns: + (list[int | None]): A list of 91 elements where the index represents the 91-index class ID and the value is the + corresponding 80-index class...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/converter.py
Generate docstrings with parameter types
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import math import torch from torch import Tensor, nn from ultralytics.nn.modules import MLPBlock class TwoWayTransformer(nn.Module): def __init__( self, depth: int, embedding_dim: i...
--- +++ @@ -11,6 +11,31 @@ class TwoWayTransformer(nn.Module): + """A Two-Way Transformer module for simultaneous attention to image and query points. + + This class implements a specialized transformer decoder that attends to an input image using queries with supplied + positional embeddings. It's useful ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/modules/transformer.py
Auto-generate documentation strings for this file
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import copy from pathlib import Path from ultralytics.models import yolo from ultralytics.nn.tasks import OBBModel from ultralytics.utils import DEFAULT_CFG, RANK class OBBTrainer(yolo.detect.DetectionT...
--- +++ @@ -11,8 +11,36 @@ class OBBTrainer(yolo.detect.DetectionTrainer): + """A class extending the DetectionTrainer class for training based on an Oriented Bounding Box (OBB) model. + + This trainer specializes in training YOLO models that detect oriented bounding boxes, which are useful for detecting + ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/obb/train.py
Add docstrings for production code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import torch from torch import nn from ultralytics.nn.modules import MLP, LayerNorm2d class MaskDecoder(nn.Module): def __init__( self, transformer_dim: int, transformer: nn.Module, ...
--- +++ @@ -9,6 +9,33 @@ class MaskDecoder(nn.Module): + """Decoder module for generating masks and their associated quality scores using a transformer architecture. + + This class predicts masks given image and prompt embeddings, utilizing a transformer to process the inputs and + generate mask prediction...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/modules/decoders.py
Write docstrings for algorithm functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import os import threading import time from typing import Any from ultralytics.utils import ( IS_COLAB, LOGGER, TQDM, TryExcept, colorstr, ) HUB_API_ROOT = os.environ.get("ULTRALYTICS_HUB_API", "https://api.ultralytics.com") HUB_...
--- +++ @@ -21,6 +21,17 @@ def request_with_credentials(url: str) -> Any: + """Make an AJAX request with cookies attached in a Google Colab environment. + + Args: + url (str): The URL to make the request to. + + Returns: + (Any): The response data from the AJAX request. + + Raises: + ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/hub/utils.py
Add docstrings for better understanding
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any import numpy as np import torch from ultralytics.models.yolo.detect import DetectionValidator from ultralytics.utils import ops from ultralytics.utils.metrics import...
--- +++ @@ -14,8 +14,56 @@ class PoseValidator(DetectionValidator): + """A class extending the DetectionValidator class for validation based on a pose model. + + This validator is specifically designed for pose estimation tasks, handling keypoints and implementing specialized + metrics for pose evaluation....
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/pose/val.py
Write documentation strings for class attributes
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any from ultralytics.engine.model import Model from .predict import FastSAMPredictor from .val import FastSAMValidator class FastSAM(Model): def __init__(self, mo...
--- +++ @@ -12,8 +12,31 @@ class FastSAM(Model): + """FastSAM model interface for Segment Anything tasks. + + This class extends the base Model class to provide specific functionality for the FastSAM (Fast Segment Anything + Model) implementation, allowing for efficient and accurate image segmentation with...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/fastsam/model.py
Add docstrings explaining edge cases
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import torch from ultralytics.models.yolo.detect import DetectionValidator from ultralytics.utils import ops __all__ = ["NASValidator"] class NASValidator(DetectionValidator): def postprocess(self, preds_in): boxes = ops.xyxy2xywh(pre...
--- +++ @@ -9,8 +9,30 @@ class NASValidator(DetectionValidator): + """Ultralytics YOLO NAS Validator for object detection. + + Extends DetectionValidator from the Ultralytics models package and is designed to post-process the raw predictions + generated by YOLO NAS models. It performs non-maximum suppressi...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/nas/val.py
Add docstrings that explain inputs and outputs
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import torch from ultralytics.models.yolo.detect.predict import DetectionPredictor from ultralytics.utils import ops class NASPredictor(DetectionPredictor): def postprocess(self, preds_in, img, orig_imgs): boxes = ops.xyxy2xywh(preds_i...
--- +++ @@ -7,8 +7,50 @@ class NASPredictor(DetectionPredictor): + """Ultralytics YOLO NAS Predictor for object detection. + + This class extends the DetectionPredictor from Ultralytics engine and is responsible for post-processing the raw + predictions generated by the YOLO NAS models. It applies operatio...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/nas/predict.py
Include argument descriptions in docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import json import os import re import shutil import subprocess import time from copy import deepcopy from datetime import datetime from pathlib import Path import numpy as np import torch from ultralytics import ...
--- +++ @@ -1,4 +1,64 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Export a YOLO PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit. + +Format | `format=argument` | Model +--- | --- ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/engine/exporter.py
Generate consistent documentation across files
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import inspect from pathlib import Path from typing import Any import numpy as np import torch from PIL import Image from ultralytics.cfg import TASK2DATA, get_cfg, get_save_dir from ultralytics.engine.results imp...
--- +++ @@ -27,6 +27,56 @@ class Model(torch.nn.Module): + """A base class for implementing YOLO models, unifying APIs across different model types. + + This class provides a common interface for various operations related to YOLO models, such as training, validation, + prediction, exporting, and benchmark...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/engine/model.py
Add docstrings for better understanding
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import glob import math import os import random from copy import deepcopy from multiprocessing.pool import ThreadPool from pathlib import Path from typing import Any import cv2 import numpy as np from torch.utils.d...
--- +++ @@ -21,6 +21,53 @@ class BaseDataset(Dataset): + """Base dataset class for loading and processing image data. + + This class provides core functionality for loading images, caching, and preparing data for training and inference in + object detection tasks. + + Attributes: + img_path (str ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/base.py
Expand my code with proper documentation strings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import torch from ultralytics.engine.results import Results from ultralytics.models.yolo.detect.predict import DetectionPredictor from ultralytics.utils import DEFAULT_CFG, ops class OBBPredictor(DetectionPredict...
--- +++ @@ -10,13 +10,49 @@ class OBBPredictor(DetectionPredictor): + """A class extending the DetectionPredictor class for prediction based on an Oriented Bounding Box (OBB) model. + + This predictor handles oriented bounding box detection tasks, processing images and returning results with rotated + boun...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/obb/predict.py
Generate consistent documentation across files
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import torch from ultralytics.data.augment import LetterBox from ultralytics.engine.predictor import BasePredictor from ultralytics.engine.results import Results from ultralytics.utils import ops class RTDETRPredictor(BasePredictor): def postp...
--- +++ @@ -9,8 +9,45 @@ class RTDETRPredictor(BasePredictor): + """RT-DETR (Real-Time Detection Transformer) Predictor extending the BasePredictor class for making predictions. + + This class leverages Vision Transformers to provide real-time object detection while maintaining high accuracy. It + supports...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/rtdetr/predict.py
Generate documentation strings for clarity
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved from __future__ import annotations from copy import copy import torch import torch.nn as nn from torch.nn.attention import SDPBackend, sdpa_kernel from .necks import Sam3Dua...
--- +++ @@ -2,6 +2,7 @@ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved +"""Provides utility to combine a vision backbone with a language backbone.""" from __future__ import annotations @@ -15,6 +16,11 @@ class SAM3VLBackbone(nn.Module): + """This backbone combines a vision back...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/vl_combiner.py
Add docstrings following best practices
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import os from pathlib import Path from typing import Any import numpy as np import torch import torch.distributed as dist from ultralytics.data import build_dataloader, build_yolo_dataset, converter from ultralyt...
--- +++ @@ -19,8 +19,38 @@ class DetectionValidator(BaseValidator): + """A class extending the BaseValidator class for validation based on a detection model. + + This class implements validation functionality specific to object detection tasks, including metrics calculation, + prediction processing, and vi...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/detect/val.py
Add docstrings to incomplete code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import glob import math import os import time import urllib from dataclasses import dataclass from pathlib import Path from threading import Thread from typing import Any import cv2 import numpy as np import torch ...
--- +++ @@ -25,6 +25,24 @@ @dataclass class SourceTypes: + """Class to represent various types of input sources for predictions. + + This class uses dataclass to define boolean flags for different types of input sources that can be used for making + predictions with YOLO models. + + Attributes: + ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/loaders.py
Create documentation for each function signature
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import concurrent.futures import statistics import time class GCPRegions: def __init__(self): self.regions = { "asia-east1": (1, "Taiwan", "China"), "asia-east2": (2, "Hong Kon...
--- +++ @@ -8,8 +8,28 @@ class GCPRegions: + """A class for managing and analyzing Google Cloud Platform (GCP) regions. + + This class provides functionality to initialize, categorize, and analyze GCP regions based on their geographical + location, tier classification, and network latency. + + Attribute...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/hub/google/__init__.py
Create docstrings for API functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved from __future__ import annotations import numpy as np import torch from torch import nn from torchvision.ops.roi_align import RoIAlign from ultralytics.nn.modules.transformer ...
--- +++ @@ -1,6 +1,10 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved +""" +Transformer decoder. +Inspired from Pytorch's version, adds the pre-norm variant. +""" from __future__ import annotations @@ -17,6 +21,7 @@ ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/decoder.py
Generate docstrings with examples
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license __version__ = "8.4.23" import importlib import os from typing import TYPE_CHECKING # Set ENV variables (place before imports) if not os.environ.get("OMP_NUM_THREADS"): os.environ["OMP_NUM_THREADS"] = "1" # default for reduced CPU utilization du...
--- +++ @@ -33,14 +33,16 @@ def __getattr__(name: str): + """Lazy-import model classes on first access.""" if name in MODELS: return getattr(importlib.import_module("ultralytics.models"), name) raise AttributeError(f"module {__name__} has no attribute {name}") def __dir__(): + """Exten...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/__init__.py
Add structured docstrings to improve clarity
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import math from typing import Any import torch import torch.nn.functional as F def select_closest_cond_frames(frame_idx: int, cond_frame_outputs: dict[int, Any], max_cond_frame_num: int): if max_cond_frame_n...
--- +++ @@ -10,6 +10,27 @@ def select_closest_cond_frames(frame_idx: int, cond_frame_outputs: dict[int, Any], max_cond_frame_num: int): + """Select the closest conditioning frames to a given frame index. + + Args: + frame_idx (int): Current frame index. + cond_frame_outputs (dict[int, Any]): Dic...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/modules/utils.py
Write reusable docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from functools import partial import torch from ult...
--- +++ @@ -22,6 +22,7 @@ def _load_checkpoint(model, checkpoint): + """Load checkpoint into model from file path.""" if checkpoint is None: return model @@ -36,6 +37,7 @@ def build_sam_vit_h(checkpoint=None): + """Build and return a Segment Anything Model (SAM) h-size model with specified...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/build.py
Create docstrings for each class method
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import copy import math from functools import partial import numpy as np import torch import torch.nn.functional as F from torch import Tensor, nn from ultralytics.nn.modules import MLP, LayerNorm2d, MLPBlock from...
--- +++ @@ -17,13 +17,29 @@ class DropPath(nn.Module): + """Implements stochastic depth regularization for neural networks during training. + + Attributes: + drop_prob (float): Probability of dropping a path during training. + scale_by_keep (bool): Whether to scale the output by the keep probabi...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/modules/blocks.py
Add minimal docstrings for each function
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from ultralytics.engine.model import Model from ultralytics.nn.tasks import RTDETRDetectionModel from ultralytics.utils.torch_utils import TORCH_1_11 from .predict import RTDETRPredictor from .train import RTDETRTrainer from .val import RTDETRValidat...
--- +++ @@ -1,4 +1,13 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Interface for Baidu's RT-DETR, a Vision Transformer-based real-time object detector. + +RT-DETR offers real-time performance and high accuracy, excelling in accelerated backends like CUDA with TensorRT. +It features an ef...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/rtdetr/model.py
Create docstrings for each class method
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import deepcopy from functools import lru_cache from pathlib import Path from typing import Any import numpy as np import torch from ultralytics.data.augment import LetterBox from ultralytics.utils impor...
--- +++ @@ -1,4 +1,9 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Ultralytics Results, Boxes, Masks, Keypoints, Probs, and OBB classes for handling inference results. + +Usage: See https://docs.ultralytics.com/modes/predict/ +""" from __future__ import annotations @@ -16,36 +21,204 ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/engine/results.py
Add detailed docstrings explaining each function
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import json import os import random import subprocess import time import zipfile from multiprocessing.pool import ThreadPool from pathlib import Path from tarfile import is_tarfile from typing import Any import cv2...
--- +++ @@ -58,6 +58,7 @@ def img2label_paths(img_paths: list[str]) -> list[str]: + """Convert image paths to label paths by replacing 'images' with 'labels' and extension with '.txt'.""" sa, sb = f"{os.sep}images{os.sep}", f"{os.sep}labels{os.sep}" # /images/, /labels/ substrings return [sb.join(x.rs...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/utils.py
Document this code for team use
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import ast import html import re import subprocess import textwrap from collections import defaultdict from collections.abc import Iterable from dataclasses import dataclass, field from pathlib import Path from typi...
--- +++ @@ -1,4 +1,12 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Helper file to build Ultralytics Docs reference section. + +This script recursively walks through the ultralytics directory and builds a MkDocs reference section of *.md files +composed of classes and functions, and also ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/docs/build_reference.py
Write docstrings for this repository
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import gc import math import os import subprocess import time import warnings from copy import copy, deepcopy from datetime import datetime, timedelta from functools import partial from pathlib import Path import n...
--- +++ @@ -1,4 +1,10 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Train a model on a dataset. + +Usage: + $ yolo mode=train model=yolo26n.pt data=coco8.yaml imgsz=640 epochs=100 batch=16 +""" from __future__ import annotations @@ -59,8 +65,63 @@ class BaseTrainer: + """A ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/engine/trainer.py
Write docstrings for utility functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # -------------------------------------------------------- # TinyViT Model Architecture # Copyright (c) 2022 Microsoft # Adapted from LeViT and Swin Transformer # LeViT: (https://github.com/facebookresearch/levit) # Swin: (https://github.com/micro...
--- +++ @@ -22,6 +22,23 @@ class Conv2d_BN(torch.nn.Sequential): + """A sequential container that performs 2D convolution followed by batch normalization. + + This module combines a 2D convolution layer with batch normalization, providing a common building block for + convolutional neural networks. The bat...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/modules/tiny_encoder.py
Add missing documentation to my Python functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved import torch.nn as nn from ultralytics.nn.modules.transformer import MLP from ultralytics.utils.patches import torch_load from .modules.blocks import PositionEmbeddingSine, Ro...
--- +++ @@ -24,6 +24,7 @@ def _create_vision_backbone(compile_mode=None, enable_inst_interactivity=True) -> Sam3DualViTDetNeck: + """Create SAM3 visual backbone with ViT and neck.""" # Position encoding position_encoding = PositionEmbeddingSine( num_pos_feats=256, @@ -69,6 +70,7 @@ def _cr...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/build_sam3.py
Add inline docstrings for readability
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import torch from PIL import Image from ultralytics.models.yolo.segment import SegmentationPredictor from ultralytics.utils import DEFAULT_CFG from ultralytics.utils.metrics import box_iou from ultralytics.utils.op...
--- +++ @@ -15,12 +15,49 @@ class FastSAMPredictor(SegmentationPredictor): + """FastSAMPredictor is specialized for fast SAM (Segment Anything Model) segmentation prediction tasks. + + This class extends the SegmentationPredictor, customizing the prediction pipeline specifically for fast SAM. It + adjusts ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/fastsam/predict.py
Create docstrings for reusable components
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from ultralytics.data import YOLOConcatDataset, build_grounding, build_yolo_dataset from ultralytics.data.utils import check_det_dataset from ultralytics.models.yolo.world import WorldTrain...
--- +++ @@ -13,13 +13,76 @@ class WorldTrainerFromScratch(WorldTrainer): + """A class extending the WorldTrainer for training a world model from scratch on open-set datasets. + + This trainer specializes in handling mixed datasets including both object detection and grounding datasets, + supporting trainin...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/world/train_world.py
Fully document this Python code with docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import copy from typing import Any import torch from ultralytics.data import ClassificationDataset, build_dataloader from ultralytics.engine.trainer import BaseTrainer from ultralytics.models import yolo...
--- +++ @@ -17,8 +17,46 @@ class ClassificationTrainer(BaseTrainer): + """A trainer class extending BaseTrainer for training image classification models. + + This trainer handles the training process for image classification tasks, supporting both YOLO classification models + and torchvision models with co...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/classify/train.py
Add structured docstrings to improve clarity
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved from __future__ import annotations import math import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from ultralytics...
--- +++ @@ -15,22 +15,28 @@ class LinearPresenceHead(nn.Sequential): + """Linear presence head for predicting the presence of classes in an image.""" def __init__(self, d_model): + """Initializes the LinearPresenceHead.""" # a hack to make `LinearPresenceHead` compatible with old checkpoin...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/maskformer_segmentation.py
Create docstrings for reusable components
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import random import shutil from pathlib import Path from ultralytics.data.utils import IMG_FORMATS, img2label_paths from ultralytics.utils import DATASETS_DIR, LOGGER, TQDM def split_classify_dataset(source_dir:...
--- +++ @@ -11,6 +11,55 @@ def split_classify_dataset(source_dir: str | Path, train_ratio: float = 0.8) -> Path: + """Split classification dataset into train and val directories in a new directory. + + Creates a new directory '{source_dir}_split' with train/val subdirectories, preserving the original class st...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/split.py
Write reusable docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved from __future__ import annotations import math from functools import partial from typing import Callable import torch import torch.nn as nn import torch.nn.functional as F im...
--- +++ @@ -2,6 +2,15 @@ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved +""" +ViTDet backbone adapted from Detectron2. +This module implements Vision Transformer (ViT) backbone for object detection. + +Rope embedding code adopted from: +1. https://github.com/meta-llama/codellama/blob/main/...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/vitdet.py
Generate documentation strings for clarity
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import math import random from copy import copy from typing import Any import numpy as np import torch import torch.nn as nn from ultralytics.data import build_dataloader, build_yolo_dataset from ultralytics.engin...
--- +++ @@ -22,15 +22,72 @@ class DetectionTrainer(BaseTrainer): + """A class extending the BaseTrainer class for training based on a detection model. + + This trainer specializes in object detection tasks, handling the specific requirements for training YOLO models for + object detection including dataset...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/detect/train.py
Add documentation for all methods
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import copy from ultralytics.models.yolo.detect import DetectionTrainer from ultralytics.nn.tasks import RTDETRDetectionModel from ultralytics.utils import RANK, colorstr from .val import RTDETRDataset, ...
--- +++ @@ -12,14 +12,62 @@ class RTDETRTrainer(DetectionTrainer): + """Trainer class for the RT-DETR model developed by Baidu for real-time object detection. + + This class extends the DetectionTrainer class for YOLO to adapt to the specific features and architecture of + RT-DETR. The model leverages Visi...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/rtdetr/train.py
Write beginner-friendly docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from ultralytics.engine.results import Results from ultralytics.models.yolo.detect.predict import DetectionPredictor from ultralytics.utils import DEFAULT_CFG, ops class SegmentationPredictor(DetectionPredictor): ...
--- +++ @@ -8,23 +8,94 @@ class SegmentationPredictor(DetectionPredictor): + """A class extending the DetectionPredictor class for prediction based on a segmentation model. + + This class specializes in processing segmentation model outputs, handling both bounding boxes and masks in the + prediction result...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/segment/predict.py
Document all public functions with docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from ultralytics.engine.predictor import BasePredictor from ultralytics.engine.results import Results from ultralytics.utils import nms, ops class DetectionPredictor(BasePredictor): def postprocess(self, preds, img, orig_imgs, **kwargs): ...
--- +++ @@ -6,8 +6,50 @@ class DetectionPredictor(BasePredictor): + """A class extending the BasePredictor class for prediction based on a detection model. + + This predictor specializes in object detection tasks, processing model outputs into meaningful detection results + with bounding boxes and class pr...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/detect/predict.py
Add well-formatted docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import copy from pathlib import Path from ultralytics.models import yolo from ultralytics.nn.tasks import SegmentationModel from ultralytics.utils import DEFAULT_CFG, RANK class SegmentationTrainer(yolo...
--- +++ @@ -11,14 +11,50 @@ class SegmentationTrainer(yolo.detect.DetectionTrainer): + """A class extending the DetectionTrainer class for training based on a segmentation model. + + This trainer specializes in handling segmentation tasks, extending the detection trainer with segmentation-specific + functi...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/segment/train.py
Document helper functions with docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from ultralytics.data.utils import HUBDatasetStats from ultralytics.hub.auth import Auth from ultralytics.hub.session import HUBTrainingSession from ultralytics.hub.utils import HUB_API_ROOT, HUB_WEB_ROOT, PREFIX fr...
--- +++ @@ -23,6 +23,19 @@ def login(api_key: str | None = None, save: bool = True) -> bool: + """Log in to the Ultralytics HUB API using the provided API key. + + The session is not stored; a new session is created when needed using the saved SETTINGS or the HUB_API_KEY + environment variable if successfu...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/hub/__init__.py
Add inline docstrings for readability
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved import torch import torch.nn as nn import torchvision from ultralytics.nn.modules.utils import _get_clones from ultralytics.utils.ops import xywh2xyxy def is_right_padded(mas...
--- +++ @@ -11,10 +11,29 @@ def is_right_padded(mask: torch.Tensor): + """Given a padding mask (following pytorch convention, 1s for padded values), returns whether the padding is on the + right or not. + """ return (mask.long() == torch.sort(mask.long(), dim=-1)[0]).all() def concat_padded_seque...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/geometry_encoders.py
Improve my code by adding docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import copy from pathlib import Path from typing import Any from ultralytics.models import yolo from ultralytics.nn.tasks import PoseModel from ultralytics.utils import DEFAULT_CFG from ultralytics.utils....
--- +++ @@ -13,8 +13,43 @@ class PoseTrainer(yolo.detect.DetectionTrainer): + """A class extending the DetectionTrainer class for training YOLO pose estimation models. + + This trainer specializes in handling pose estimation tasks, managing model training, validation, and visualization + of pose keypoints ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/pose/train.py
Generate consistent docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from typing import Any import torch import torch.nn as nn import torch.nn.functional as F from scipy.optimize import linear_sum_assignment from ultralytics.utils.metrics import bbox_iou from ultralytics.utils.ops ...
--- +++ @@ -14,6 +14,37 @@ class HungarianMatcher(nn.Module): + """A module implementing the HungarianMatcher for optimal assignment between predictions and ground truth. + + HungarianMatcher performs optimal bipartite assignment over predicted and ground truth bounding boxes using a cost + function that c...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/utils/ops.py
Help me document legacy Python code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any import torch from ultralytics.data.build import load_inference_source from ultralytics.engine.model import Model from ultralytics.models import yolo from ultralytics...
--- +++ @@ -24,8 +24,44 @@ class YOLO(Model): + """YOLO (You Only Look Once) object detection model. + + This class provides a unified interface for YOLO models, automatically switching to specialized model types + (YOLOWorld or YOLOE) based on the model filename. It supports various computer vision tasks ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/model.py
Document this module using docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import cv2 import torch from PIL import Image from ultralytics.data.augment import classify_transforms from ultralytics.engine.predictor import BasePredictor from ultralytics.engine.results import Results from ultr...
--- +++ @@ -13,12 +13,45 @@ class ClassificationPredictor(BasePredictor): + """A class extending the BasePredictor class for prediction based on a classification model. + + This predictor handles the specific requirements of classification models, including preprocessing images and + postprocessing predict...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/classify/predict.py
Fill in missing docstrings in my code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import itertools from glob import glob from math import ceil from pathlib import Path from typing import Any import cv2 import numpy as np from PIL import Image from ultralytics.data.utils import exif_size, img2la...
--- +++ @@ -18,6 +18,20 @@ def bbox_iof(polygon1: np.ndarray, bbox2: np.ndarray, eps: float = 1e-6) -> np.ndarray: + """Calculate Intersection over Foreground (IoF) between polygons and bounding boxes. + + Args: + polygon1 (np.ndarray): Polygon coordinates with shape (N, 8). + bbox2 (np.ndarray)...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/split_dota.py
Generate helpful docstrings for debugging
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from ultralytics.models.yolo.detect.predict import DetectionPredictor from ultralytics.utils import DEFAULT_CFG, ops class PosePredictor(DetectionPredictor): def __init__(self, cfg=DEFAULT_CFG, overrides=None...
--- +++ @@ -7,16 +7,61 @@ class PosePredictor(DetectionPredictor): + """A class extending the DetectionPredictor class for prediction based on a pose model. + + This class specializes in pose estimation, handling keypoints detection alongside standard object detection + capabilities inherited from Detectio...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/pose/predict.py
Add docstrings to improve collaboration
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any import torch from ultralytics.data import YOLODataset from ultralytics.data.augment import Compose, Format, v8_transforms from ultralytics.models.yolo.detect import ...
--- +++ @@ -16,14 +16,69 @@ class RTDETRDataset(YOLODataset): + """Real-Time DEtection and TRacking (RT-DETR) dataset class extending the base YOLODataset class. + + This specialized dataset class is designed for use with the RT-DETR object detection model and is optimized for + real-time detection and tra...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/rtdetr/val.py
Add concise docstrings to each method
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import gc import random import shutil import subprocess import time from datetime import datetime import numpy as np import torch from ultralytics.cfg import CFG_INT_KEYS, get_cfg, get_save_dir from ultralytics.ut...
--- +++ @@ -1,4 +1,18 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Module provides functionalities for hyperparameter tuning of the Ultralytics YOLO models for object detection, instance +segmentation, image classification, pose estimation, and multi-object tracking. + +Hyperparameter tu...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/engine/tuner.py
Write clean docstrings for readability
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved from __future__ import annotations from collections import OrderedDict from typing import Callable import torch import torch.nn as nn from torch.utils.checkpoint import checkp...
--- +++ @@ -15,6 +15,7 @@ class ResidualAttentionBlock(nn.Module): + """Transformer block with multi-head attention, layer normalization, and MLP feed-forward network.""" def __init__( self, @@ -25,6 +26,7 @@ act_layer: Callable[[], nn.Module] = nn.GELU, norm_layer: Callable[[int...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/sam3/text_encoder_ve.py
Generate docstrings for exported functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from typing import Any import torch import torch.nn as nn import torch.nn.functional as F from ultralytics.utils.loss import FocalLoss, VarifocalLoss from ultralytics.utils.metrics import bbox_iou from .ops impor...
--- +++ @@ -15,6 +15,24 @@ class DETRLoss(nn.Module): + """DETR (DEtection TRansformer) Loss class for calculating various loss components. + + This class computes classification loss, bounding box loss, GIoU loss, and optionally auxiliary losses for the DETR + object detection model. + + Attributes: + ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/utils/loss.py
Add minimal docstrings for each function
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any import torch import torch.distributed as dist from ultralytics.data import ClassificationDataset, build_dataloader from ultralytics.engine.validator import BaseValid...
--- +++ @@ -16,8 +16,52 @@ class ClassificationValidator(BaseValidator): + """A class extending the BaseValidator class for validation based on a classification model. + + This validator handles the validation process for classification models, including metrics calculation, confusion + matrix generation, ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/classify/val.py
Add docstrings for production code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any import torch from ultralytics.engine.model import Model from ultralytics.utils import DEFAULT_CFG_DICT from ultralytics.utils.downloads import attempt_download_asset...
--- +++ @@ -18,12 +18,41 @@ class NAS(Model): + """YOLO-NAS model for object detection. + + This class provides an interface for the YOLO-NAS models and extends the `Model` class from Ultralytics engine. It + is designed to facilitate the task of object detection using pre-trained or custom-trained YOLO-NA...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/nas/model.py
Turn comments into proper docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import numpy as np import torch from ultralytics.data.augment import LoadVisualPrompt from ultralytics.models.yolo.detect import DetectionPredictor from ultralytics.models.yolo.segment import SegmentationPredictor class YOLOEVPDetectPredictor(Detec...
--- +++ @@ -9,15 +9,58 @@ class YOLOEVPDetectPredictor(DetectionPredictor): + """A class extending DetectionPredictor for YOLO-EVP (Enhanced Visual Prompting) predictions. + + This class provides common functionality for YOLO models that use visual prompting, including model setup, prompt + handling, and p...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/yoloe/predict.py
Add detailed docstrings explaining each function
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import torch import torch.nn as nn class AGLU(nn.Module): def __init__(self, device=None, dtype=None) -> None: super().__init__() self.act = nn.Softplus(beta=-1.0) self.lambd = nn.Parameter(nn.init.uniform_(torch.empty(1...
--- +++ @@ -1,17 +1,54 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Activation modules.""" import torch import torch.nn as nn class AGLU(nn.Module): + """Unified activation function module from AGLU. + + This class implements a parameterized activation function with learnabl...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/modules/activation.py
Create documentation for each function signature
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import copy, deepcopy from pathlib import Path import torch from ultralytics.data import YOLOConcatDataset, build_yolo_dataset from ultralytics.data.augment import LoadVisualPrompt from ultralytics.model...
--- +++ @@ -19,8 +19,28 @@ class YOLOETrainer(DetectionTrainer): + """A trainer class for YOLOE object detection models. + + This class extends DetectionTrainer to provide specialized training functionality for YOLOE models, including custom + model initialization, validation, and dataset building with mul...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/yoloe/train.py
Add docstrings for utility scripts
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from copy import copy, deepcopy from ultralytics.models.yolo.segment import SegmentationTrainer from ultralytics.nn.tasks import YOLOESegModel from ultralytics.utils import RANK from .train import YOLOETrainer, YOLOETrainerFromScratch, YOLOEVPTraine...
--- +++ @@ -11,8 +11,28 @@ class YOLOESegTrainer(YOLOETrainer, SegmentationTrainer): + """Trainer class for YOLOE segmentation models. + + This class combines YOLOETrainer and SegmentationTrainer to provide training functionality specifically for YOLOE + segmentation models, enabling both object detection ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/yoloe/train_seg.py
Improve my code by adding docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from copy import deepcopy from pathlib import Path from typing import Any import torch from torch.nn import functional as F from ultralytics.data import YOLOConcatDataset, build_dataloader, build_yolo_dataset from...
--- +++ @@ -21,9 +21,47 @@ class YOLOEDetectValidator(DetectionValidator): + """A validator class for YOLOE detection models that handles both text and visual prompt embeddings. + + This class extends DetectionValidator to provide specialized validation functionality for YOLOE models. It supports + validat...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/yolo/yoloe/val.py
Generate docstrings for this script
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import copy import math import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import constant_, xavier_uniform_ from ultralytics.utils import NOT_MACOS14 from ultralytics.utils.tal ...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Model head modules.""" from __future__ import annotations @@ -23,6 +24,45 @@ class Detect(nn.Module): + """YOLO Detect head for object detection models. + + This class implements the detection head used in YOL...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/modules/head.py
Add docstrings for internal functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import math import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import constant_, xavier_uniform_ from ultralytics.utils.torch_utils import TORCH_1_11 from .conv import Conv from...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Transformer modules.""" from __future__ import annotations @@ -29,6 +30,23 @@ class TransformerEncoderLayer(nn.Module): + """A single layer of the transformer encoder. + + This class implements a standard tran...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/modules/transformer.py
Auto-generate documentation strings for this file
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from typing import Any import numpy as np import torch import torch.nn as nn from ultralytics.utils.checks import check_suffix from ultralytics.utils.downloads import is_url from .backend...
--- +++ @@ -32,6 +32,17 @@ def check_class_names(names: list | dict) -> dict[int, str]: + """Check class names and convert to dict format if needed. + + Args: + names (list | dict): Class names as list or dict format. + + Returns: + (dict): Class names in dict format with integer keys and str...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/autobackend.py
Write docstrings for utility functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from itertools import cycle from typing import Any import cv2 import numpy as np from ultralytics.solutions.solutions import BaseSolution, SolutionResults # Import a parent class from ultralytics.utils import plt...
--- +++ @@ -13,9 +13,43 @@ class Analytics(BaseSolution): + """A class for creating and updating various types of charts for visual analytics. + + This class extends BaseSolution to provide functionality for generating line, bar, pie, and area charts based on + object detection and tracking data. + + At...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/analytics.py
Create docstrings for each class method
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import math from typing import Any import cv2 from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults from ultralytics.utils.plotting import colors class DistanceCalculation(BaseSolution): def __init__(sel...
--- +++ @@ -10,8 +10,30 @@ class DistanceCalculation(BaseSolution): + """A class to calculate distance between two objects in a real-time video stream based on their tracks. + + This class extends BaseSolution to provide functionality for selecting objects and calculating the distance between + them in a v...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/distance_calculation.py
Create docstrings for all classes and functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from typing import Any import cv2 import numpy as np from ultralytics.solutions.object_counter import ObjectCounter from ultralytics.solutions.solutions import SolutionAnnotator, SolutionResults class Heatmap(Ob...
--- +++ @@ -12,8 +12,34 @@ class Heatmap(ObjectCounter): + """A class to draw heatmaps in real-time video streams based on object tracks. + + This class extends the ObjectCounter class to generate and visualize heatmaps of object movements in video + streams. It uses tracked object positions to create a cu...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/heatmap.py
Provide clean and structured docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import contextlib import pickle import re import types from copy import deepcopy from pathlib import Path import torch import torch.nn as nn from ultralytics.nn.autobackend import check_class_names from ultralytics.nn.modules import ( AIFI, ...
--- +++ @@ -100,18 +100,76 @@ class BaseModel(torch.nn.Module): + """Base class for all YOLO models in the Ultralytics family. + + This class provides common functionality for YOLO models including forward pass handling, model fusion, information + display, and weight loading capabilities. + + Attribute...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/tasks.py
Improve documentation using docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from abc import abstractmethod from pathlib import Path import torch import torch.nn as nn from PIL import Image from ultralytics.utils import checks from ultralytics.utils.torch_utils import smart_inference_mode ...
--- +++ @@ -20,22 +20,65 @@ class TextModel(nn.Module): + """Abstract base class for text encoding models. + + This class defines the interface for text encoding models used in vision-language tasks. Subclasses must implement + the tokenize and encode_text methods to provide text tokenization and encoding ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/text_model.py
Generate docstrings for exported functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import torch from torch import optim def zeropower_via_newtonschulz5(G: torch.Tensor, eps: float = 1e-7) -> torch.Tensor: assert len(G.shape) == 2 X = G.bfloat16() X /= X.norm() + eps # ensure top sin...
--- +++ @@ -7,6 +7,33 @@ def zeropower_via_newtonschulz5(G: torch.Tensor, eps: float = 1e-7) -> torch.Tensor: + """Compute the zeroth power / orthogonalization of matrix G using Newton-Schulz iteration. + + This function implements a quintic Newton-Schulz iteration to compute an approximate orthogonalization ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/optim/muon.py
Generate docstrings for this script
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path import numpy as np import torch from PIL import Image from ultralytics.utils import LOGGER from ultralytics.utils.checks import check_requirements from .base import BaseBackend class Co...
--- +++ @@ -15,8 +15,18 @@ class CoreMLBackend(BaseBackend): + """CoreML inference backend for Apple hardware. + + Loads and runs inference with CoreML models (.mlpackage files) using the coremltools library. Supports both static + and dynamic input shapes and handles NMS-included model outputs. + """ ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/coreml.py
Write documentation strings for class attributes
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from typing import Any from ultralytics.engine.results import Results from ultralytics.solutions.solutions import BaseSolution, SolutionResults class InstanceSegmentation(BaseSolution): def __init__(self, **kwargs: Any) -> None: kwargs...
--- +++ @@ -7,8 +7,40 @@ class InstanceSegmentation(BaseSolution): + """A class to manage instance segmentation in images or video streams. + + This class extends the BaseSolution class and provides functionality for performing instance segmentation, including + drawing segmented masks with bounding boxes ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/instance_segmentation.py
Document this code for team use
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import copy import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import uniform_ __all__ = "inverse_sigmoid", "multi_scale_deformable_attn_pytorch" def _get_clones(module, n): ret...
--- +++ @@ -13,14 +13,61 @@ def _get_clones(module, n): + """Create a list of cloned modules from the given module. + + Args: + module (nn.Module): The module to be cloned. + n (int): Number of clones to create. + + Returns: + (nn.ModuleList): A ModuleList containing n clones of the in...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/modules/utils.py
Write Python docstrings for this snippet
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path import numpy as np import torch from ultralytics.utils import LOGGER from ultralytics.utils.checks import check_requirements from .base import BaseBackend class OpenVINOBackend(BaseBack...
--- +++ @@ -14,8 +14,18 @@ class OpenVINOBackend(BaseBackend): + """Intel OpenVINO inference backend for Intel hardware acceleration. + + Loads and runs inference with Intel OpenVINO IR models (*_openvino_model/ directories). Supports automatic device + selection, Intel-specific device targeting, and async...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/openvino.py
Help me document legacy Python code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path import numpy as np import torch from ultralytics.utils import ARM64, LOGGER from ultralytics.utils.checks import check_requirements from .base import BaseBackend class PaddleBackend(Bas...
--- +++ @@ -14,8 +14,18 @@ class PaddleBackend(BaseBackend): + """Baidu PaddlePaddle inference backend. + + Loads and runs inference with Baidu PaddlePaddle models (*_paddle_model/ directories). Supports both CPU and GPU + execution with automatic device configuration and memory pool initialization. + "...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/paddle.py
Generate docstrings for each module
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from collections import defaultdict from typing import Any from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults class AIGym(BaseSolution): def __init__(self, **kwargs: Any) -> None: kwargs["model...
--- +++ @@ -7,8 +7,36 @@ class AIGym(BaseSolution): + """A class to manage gym steps of people in a real-time video stream based on their poses. + + This class extends BaseSolution to monitor workouts using YOLO pose estimation models. It tracks and counts + repetitions of exercises based on predefined ang...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/ai_gym.py
Generate helpful docstrings for debugging
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path import numpy as np import torch from ultralytics.utils import LOGGER from ultralytics.utils.checks import check_requirements from .base import BaseBackend class NCNNBackend(BaseBackend)...
--- +++ @@ -14,8 +14,18 @@ class NCNNBackend(BaseBackend): + """Tencent NCNN inference backend for mobile and embedded deployment. + + Loads and runs inference with Tencent NCNN models (*_ncnn_model/ directories). Optimized for mobile platforms with + optional Vulkan GPU acceleration when available. + "...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/ncnn.py
Write proper docstrings for these functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path import torch from ultralytics.utils import LOGGER from ultralytics.utils.checks import check_executorch_requirements from .base import BaseBackend class ExecuTorchBackend(BaseBackend): ...
--- +++ @@ -13,8 +13,18 @@ class ExecuTorchBackend(BaseBackend): + """Meta ExecuTorch inference backend for on-device deployment. + + Loads and runs inference with Meta ExecuTorch models (.pte files) using the ExecuTorch runtime. Supports both + standalone .pte files and directory-based model packages with...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/executorch.py
Write proper docstrings for these functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from dataclasses import dataclass, field from typing import Any import cv2 @dataclass class SolutionConfig: source: str | None = None model: str | None = None classes: list[int] | None = None sho...
--- +++ @@ -10,6 +10,57 @@ @dataclass class SolutionConfig: + """Manages configuration parameters for Ultralytics Vision AI solutions. + + The SolutionConfig class serves as a centralized configuration container for all the Ultralytics solution modules: + https://docs.ultralytics.com/solutions/#solutions. I...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/config.py
Add minimal docstrings for each function
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import os from pathlib import Path import torch from ultralytics.utils import LOGGER from ultralytics.utils.checks import check_requirements from .base import BaseBackend class AxeleraBackend(BaseBackend): ...
--- +++ @@ -14,8 +14,18 @@ class AxeleraBackend(BaseBackend): + """Axelera AI inference backend for Axelera Metis AI accelerators. + + Loads compiled Axelera models (.axm files) and runs inference using the Axelera AI runtime SDK. Requires the Axelera + runtime environment to be activated before use. + ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/axelera.py
Create docstrings for each class method
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path import numpy as np import torch from ultralytics.utils import LOGGER from ultralytics.utils.checks import check_requirements from .base import BaseBackend class ONNXBackend(BaseBackend)...
--- +++ @@ -14,13 +14,32 @@ class ONNXBackend(BaseBackend): + """Microsoft ONNX Runtime inference backend with optional OpenCV DNN support. + + Loads and runs inference with ONNX models (.onnx files) using either Microsoft ONNX Runtime with CUDA/CoreML + execution providers, or OpenCV DNN for lightweight C...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/onnx.py
Write docstrings that follow conventions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import json import os from pathlib import Path import torch from ultralytics.utils import LOGGER from ultralytics.utils.checks import check_requirements from .base import BaseBackend class MNNBackend(BaseBacken...
--- +++ @@ -15,8 +15,18 @@ class MNNBackend(BaseBackend): + """MNN (Mobile Neural Network) inference backend. + + Loads and runs inference with MNN models (.mnn files) using the Alibaba MNN framework. Optimized for mobile and edge + deployment with configurable thread count and precision. + """ d...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/mnn.py
Add docstrings for production code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import ast from abc import ABC, abstractmethod import torch class BaseBackend(ABC): def __init__(self, weight: str | torch.nn.Module, device: torch.device | str, fp16: bool = False): self.device = de...
--- +++ @@ -9,8 +9,35 @@ class BaseBackend(ABC): + """Base class for all inference backends. + + This abstract class defines the interface that all inference backends must implement. It provides common + functionality for model loading, metadata processing, and device management. + + Attributes: + ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/base.py
Create docstrings for all classes and functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import json from collections import OrderedDict, namedtuple from pathlib import Path import numpy as np import torch from ultralytics.utils import IS_JETSON, LINUX, LOGGER, PYTHON_VERSION from ultralytics.utils.ch...
--- +++ @@ -16,8 +16,18 @@ class TensorRTBackend(BaseBackend): + """NVIDIA TensorRT inference backend for GPU-accelerated deployment. + + Loads and runs inference with NVIDIA TensorRT serialized engines (.engine files). Supports both TensorRT 7-9 and + TensorRT 10+ APIs, dynamic input shapes, FP16 precisio...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/tensorrt.py