diff --git a/luxonis_train/assigners/__init__.py b/luxonis_train/assigners/__init__.py index 4d9bec9f..0b8b074a 100644 --- a/luxonis_train/assigners/__init__.py +++ b/luxonis_train/assigners/__init__.py @@ -1,4 +1,4 @@ -from .atts_assigner import ATSSAssigner +from .atss_assigner import ATSSAssigner from .tal_assigner import TaskAlignedAssigner __all__ = ["ATSSAssigner", "TaskAlignedAssigner"] diff --git a/luxonis_train/assigners/atts_assigner.py b/luxonis_train/assigners/atss_assigner.py similarity index 100% rename from luxonis_train/assigners/atts_assigner.py rename to luxonis_train/assigners/atss_assigner.py diff --git a/luxonis_train/assigners/tal_assigner.py b/luxonis_train/assigners/tal_assigner.py index ea228eba..c9435afa 100644 --- a/luxonis_train/assigners/tal_assigner.py +++ b/luxonis_train/assigners/tal_assigner.py @@ -17,7 +17,7 @@ def __init__( """Task Aligned Assigner. Adapted from: U{TOOD: Task-aligned One-stage Object Detection}. - Cose is adapted from: U{https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py}. + Code is adapted from: U{https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py}. @license: U{Apache License, Version 2.0} @@ -25,7 +25,7 @@ def __init__( @type n_classes: int @param n_classes: Number of classes in the dataset. @type topk: int - @param topk: Number of anchors considere in selection. Defaults to 13. + @param topk: Number of anchors considered in selection. Defaults to 13. @type alpha: float @param alpha: Defaults to 1.0. @type beta: float diff --git a/luxonis_train/assigners/utils.py b/luxonis_train/assigners/utils.py index fe9fba4b..4c4a44b4 100644 --- a/luxonis_train/assigners/utils.py +++ b/luxonis_train/assigners/utils.py @@ -64,8 +64,8 @@ def fix_collisions( def batch_iou(batch1: Tensor, batch2: Tensor) -> Tensor: - """Calculates IoU for each pair of bboxes in the batch. Bboxes must - be in xyxy format. + """Calculates IoU for each pair of bounding boxes in the batch. + Bounding boxes must be in the "xyxy" format. @type batch1: Tensor @param batch1: Tensor of shape C{[bs, N, 4]} diff --git a/luxonis_train/attached_modules/base_attached_module.py b/luxonis_train/attached_modules/base_attached_module.py index c65a4b7d..e52f5790 100644 --- a/luxonis_train/attached_modules/base_attached_module.py +++ b/luxonis_train/attached_modules/base_attached_module.py @@ -27,9 +27,9 @@ class BaseAttachedModule( Attached modules include losses, metrics and visualizers. - This class contains a default implementation of `prepare` method, which + This class contains a default implementation of C{prepare} method, which should be sufficient for most simple cases. More complex modules should - override the `prepare` method. + override the C{prepare} method. When subclassing, the following methods can be overridden: - L{prepare}: Prepares node outputs for the forward pass of the module. @@ -163,7 +163,8 @@ def node_tasks(self) -> dict[TaskType, str]: """Getter for the tasks of the attached node. @type: dict[TaskType, str] - @raises RuntimeError: If the node does not have the `tasks` attribute set. + @raises RuntimeError: If the node does not have the C{tasks} + attribute set. """ if self.node._tasks is None: raise RuntimeError( @@ -250,7 +251,7 @@ def get_input_tensors( @raises IncompatibleException: If the task is not present in the inputs. @raises ValueError: If the module requires multiple labels. - For such cases, the `prepare` method should be overridden. + For such cases, the C{prepare} method should be overridden. """ if task_type is not None: if isinstance(task_type, TaskType): diff --git a/luxonis_train/attached_modules/losses/adaptive_detection_loss.py b/luxonis_train/attached_modules/losses/adaptive_detection_loss.py index c11aa878..32e25257 100644 --- a/luxonis_train/attached_modules/losses/adaptive_detection_loss.py +++ b/luxonis_train/attached_modules/losses/adaptive_detection_loss.py @@ -70,7 +70,7 @@ def __init__( self.original_img_size = self.original_in_shape[1:] self.n_warmup_epochs = n_warmup_epochs - self.atts_assigner = ATSSAssigner(topk=9, n_classes=self.n_classes) + self.atss_assigner = ATSSAssigner(topk=9, n_classes=self.n_classes) self.tal_assigner = TaskAlignedAssigner( topk=13, n_classes=self.n_classes, alpha=1.0, beta=6.0 ) @@ -197,7 +197,7 @@ def _run_assigner( pred_scores: Tensor, ) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: if self._epoch < self.n_warmup_epochs: - return self.atts_assigner( + return self.atss_assigner( self.anchors, self.n_anchors_list, gt_labels, diff --git a/luxonis_train/attached_modules/losses/base_loss.py b/luxonis_train/attached_modules/losses/base_loss.py index 7a69d0d8..440a79b0 100644 --- a/luxonis_train/attached_modules/losses/base_loss.py +++ b/luxonis_train/attached_modules/losses/base_loss.py @@ -31,7 +31,7 @@ def forward( @type args: Unpack[Ts] @param args: Prepared inputs from the L{prepare} method. @rtype: Tensor | tuple[Tensor, dict[str, Tensor]] - @return: The main loss and optional a dictionary of sublosses + @return: The main loss and optional a dictionary of sub-losses (for logging). Only the main loss is used for backpropagation. """ @@ -49,7 +49,7 @@ def run( @type labels: L{Labels} @param labels: Labels from the dataset. @rtype: Tensor | tuple[Tensor, dict[str, Tensor]] - @return: The main loss and optional a dictionary of sublosses + @return: The main loss and optional a dictionary of sub-losses (for logging). Only the main loss is used for backpropagation. @raises IncompatibleException: If the inputs are not compatible diff --git a/luxonis_train/attached_modules/losses/efficient_keypoint_bbox_loss.py b/luxonis_train/attached_modules/losses/efficient_keypoint_bbox_loss.py index 7d25a8d2..701a3c72 100644 --- a/luxonis_train/attached_modules/losses/efficient_keypoint_bbox_loss.py +++ b/luxonis_train/attached_modules/losses/efficient_keypoint_bbox_loss.py @@ -62,9 +62,10 @@ def __init__( @type iou_loss_weight: float @param iou_loss_weight: Weight of IoU loss. @type sigmas: list[float] | None - @param sigmas: Sigmas used in KeypointLoss for OKS metric. If None then use COCO ones if possible or default ones. Defaults to C{None}. + @param sigmas: Sigmas used in keypoint loss for OKS metric. If None then use COCO ones if possible or default ones. Defaults to C{None}. @type area_factor: float | None - @param area_factor: Factor by which we multiply bbox area which is used in KeypointLoss. If None then use default one. Defaults to C{None}. + @param area_factor: Factor by which we multiply bounding box area which is used in the keypoint loss. + If not set, the default factor of `0.53` is used. """ super().__init__( n_warmup_epochs=n_warmup_epochs, diff --git a/luxonis_train/attached_modules/metrics/base_metric.py b/luxonis_train/attached_modules/metrics/base_metric.py index a4109d2d..ad94c312 100644 --- a/luxonis_train/attached_modules/metrics/base_metric.py +++ b/luxonis_train/attached_modules/metrics/base_metric.py @@ -42,8 +42,8 @@ def compute( @rtype: Tensor | tuple[Tensor, dict[str, Tensor]] | dict[str, Tensor] @return: The computed metric. Can be one of: - A single Tensor. - - A tuple of a Tensor and a dictionary of submetrics. - - A dictionary of submetrics. If this is the case, then the metric + - A tuple of a Tensor and a dictionary of sub-metrics. + - A dictionary of sub-metrics. If this is the case, then the metric cannot be used as the main metric of the model. """ ... diff --git a/luxonis_train/attached_modules/metrics/mean_average_precision_keypoints.py b/luxonis_train/attached_modules/metrics/mean_average_precision_keypoints.py index f536956c..e086d6b5 100644 --- a/luxonis_train/attached_modules/metrics/mean_average_precision_keypoints.py +++ b/luxonis_train/attached_modules/metrics/mean_average_precision_keypoints.py @@ -66,11 +66,12 @@ def __init__( @param sigmas: Sigma for each keypoint to weigh its importance, if C{None}, then use COCO if possible otherwise defaults. Defaults to C{None}. @type area_factor: float | None - @param area_factor: Factor by which we multiply bbox area. If None then use default one. Defaults to C{None}. + @param area_factor: Factor by which we multiply the bounding box area. + If not set, the default factor of C{0.53} is used. @type max_dets: int, @param max_dets: Maximum number of detections to be considered per image. Defaults to C{20}. @type box_format: Literal["xyxy", "xywh", "cxcywh"] - @param box_format: Input bbox format. + @param box_format: Input bounding box format. Defaults to C{"xyxy"}. """ super().__init__(**kwargs) @@ -170,7 +171,7 @@ def update( - labels (tIntTensor): Tensor of shape C{(N)} containing 0-indexed detection classes for the boxes. - keypoints (FloatTensor): Tensor of shape C{(N, 3*K)} and in - format C{[x, y, vis, x, y, vis, ...]} where C{x} an C{y} are unnormalized + format C{[x, y, vis, x, y, vis, ...]} where C{x} an C{y} are absolute keypoint coordinates and C{vis} is keypoint visibility. @type target: list[dict[str, Tensor]] @@ -191,7 +192,7 @@ def update( based on the bounding box/masks provided. Only affects which samples contribute to the C{map_small}, C{map_medium}, C{map_large} values. - keypoints (FloatTensor): Tensor of shape C{(N, 3*K)} in format - C{[x, y, vis, x, y, vis, ...]} where C{x} an C{y} are unnormalized keypoint + C{[x, y, vis, x, y, vis, ...]} where C{x} an C{y} are absolute keypoint coordinates and `vis` is keypoint visibility. """ for item in preds: diff --git a/luxonis_train/attached_modules/metrics/object_keypoint_similarity.py b/luxonis_train/attached_modules/metrics/object_keypoint_similarity.py index d291e7e0..9485c90c 100644 --- a/luxonis_train/attached_modules/metrics/object_keypoint_similarity.py +++ b/luxonis_train/attached_modules/metrics/object_keypoint_similarity.py @@ -49,8 +49,8 @@ def __init__( if C{None}, then use COCO if possible otherwise defaults. Defaults to C{None}. @type area_factor: float | None - @param area_factor: Factor by which we multiply bbox area. If - None then use default one. Defaults to C{None}. + @param area_factor: Factor by which we multiply the bounding box + area. If not set, the default factor of C{0.53} is used. @type use_cocoeval_oks: bool @param use_cocoeval_oks: Whether to use same OKS formula as in COCOeval or use the one from definition. Defaults to @@ -124,7 +124,7 @@ def update( - keypoints (FloatTensor): Tensor of shape (N, 3*K) and in format [x, y, vis, x, y, vis, ...] where `x` an `y` - are unnormalized keypoint coordinates and `vis` is keypoint visibility. + are absolute keypoint coordinates and `vis` is keypoint visibility. @type target: list[dict[str, Tensor]] @param target: A list consisting of dictionaries each containing key-values for a single image. @@ -132,11 +132,11 @@ def update( - keypoints (FloatTensor): Tensor of shape (N, 3*K) and in format [x, y, vis, x, y, vis, ...] where `x` an `y` - are unnormalized keypoint coordinates and `vis` is keypoint visibility. + are absolute keypoint coordinates and `vis` is keypoint visibility. - scales (FloatTensor): Tensor of shape (N) where each value corresponds to scale of the bounding box. Scale of one bounding box is defined as sqrt(width*height) where - width and height are unnormalized. + width and height are not normalized. """ for item in preds: keypoints = self._fix_empty_tensors(item["keypoints"]) @@ -204,7 +204,7 @@ def compute_oks( @type pred: Tensor[N, K, 3] @param pred: Predicted keypoints. @type gt: Tensor[M, K, 3] - @param gt: Groundtruth keypoints. + @param gt: Ground truth keypoints. @type scales: Tensor[M] @param scales: Scales of the bounding boxes. @type sigmas: Tensor diff --git a/luxonis_train/attached_modules/visualizers/__init__.py b/luxonis_train/attached_modules/visualizers/__init__.py index a5652cb4..50b90471 100644 --- a/luxonis_train/attached_modules/visualizers/__init__.py +++ b/luxonis_train/attached_modules/visualizers/__init__.py @@ -6,14 +6,14 @@ from .segmentation_visualizer import SegmentationVisualizer from .utils import ( combine_visualizations, + denormalize, draw_bounding_box_labels, draw_keypoint_labels, draw_segmentation_labels, get_color, - get_unnormalized_images, + get_denormalized_images, preprocess_images, seg_output_to_bool, - unnormalize, ) __all__ = [ @@ -28,8 +28,8 @@ "draw_keypoint_labels", "draw_segmentation_labels", "get_color", - "get_unnormalized_images", + "get_denormalized_images", "preprocess_images", "seg_output_to_bool", - "unnormalize", + "denormalize", ] diff --git a/luxonis_train/attached_modules/visualizers/utils.py b/luxonis_train/attached_modules/visualizers/utils.py index a8965020..45ec454b 100644 --- a/luxonis_train/attached_modules/visualizers/utils.py +++ b/luxonis_train/attached_modules/visualizers/utils.py @@ -77,14 +77,14 @@ def preprocess_images( ) -> Tensor: """Performs preprocessing on a batch of images. - Preprocessing includes unnormalizing and converting to uint8. + Preprocessing includes denormalizing and converting to uint8. @type imgs: Tensor @param imgs: Batch of images. @type mean: list[float] | float | None - @param mean: Mean used for unnormalization. Defaults to C{None}. + @param mean: Mean used for denormalization. Defaults to C{None}. @type std: list[float] | float | None - @param std: Std used for unnormalization. Defaults to C{None}. + @param std: Std used for denormalization. Defaults to C{None}. @rtype: Tensor @return: Batch of preprocessed images. """ @@ -92,7 +92,7 @@ def preprocess_images( for i in range(imgs.shape[0]): curr_img = imgs[i] if mean is not None or std is not None: - curr_img = unnormalize(curr_img, to_uint8=True, mean=mean, std=std) + curr_img = denormalize(curr_img, to_uint8=True, mean=mean, std=std) else: curr_img = curr_img.to(torch.uint8) @@ -187,25 +187,25 @@ def seg_output_to_bool(data: Tensor, binary_threshold: float = 0.5) -> Tensor: return masks -def unnormalize( +def denormalize( img: Tensor, mean: list[float] | float | None = None, std: list[float] | float | None = None, to_uint8: bool = False, ) -> Tensor: - """Unnormalizes an image back to original values, optionally + """Denormalizes an image back to original values, optionally converts it to uint8. @type img: Tensor - @param img: Image to unnormalize. + @param img: Image to denormalize. @type mean: list[float] | float | None - @param mean: Mean used for unnormalization. Defaults to C{None}. + @param mean: Mean used for denormalization. Defaults to C{None}. @type std: list[float] | float | None - @param std: Std used for unnormalization. Defaults to C{None}. + @param std: Std used for denormalization. Defaults to C{None}. @type to_uint8: bool @param to_uint8: Whether to convert to uint8. Defaults to C{False}. @rtype: Tensor - @return: Unnormalized image. + @return: denormalized image. """ mean = mean or 0 std = std or 1 @@ -223,7 +223,7 @@ def unnormalize( return out_img -def get_unnormalized_images(cfg: Config, inputs: dict[str, Tensor]) -> Tensor: +def get_denormalized_images(cfg: Config, inputs: dict[str, Tensor]) -> Tensor: # Get images from inputs according to config images = inputs[cfg.loader.image_source] diff --git a/luxonis_train/config/config.py b/luxonis_train/config/config.py index 218abee3..604b9c31 100644 --- a/luxonis_train/config/config.py +++ b/luxonis_train/config/config.py @@ -384,7 +384,7 @@ class TrainerConfig(BaseModelExtraForbid): def validate_deterministic(self) -> Self: if self.seed is not None and self.deterministic is None: logger.warning( - "Setting `trainer.deterministic` to True because `trainer.seed` is set." + "Setting `trainer.deterministic` to True because `trainer.seed` is set. " "This can cause certain layers to fail. " "In such cases, set `trainer.deterministic` to `'warn'`." ) @@ -489,7 +489,7 @@ def check_environment(cls, data: Any) -> Any: if "ENVIRON" in data: logger.warning( "Specifying `ENVIRON` section in config file is not recommended. " - "Please use environment variables or .env file instead." + "Please use environment variables or `.env` file instead." ) return data diff --git a/luxonis_train/core/core.py b/luxonis_train/core/core.py index 04f006d5..7f21e5e4 100644 --- a/luxonis_train/core/core.py +++ b/luxonis_train/core/core.py @@ -1,9 +1,10 @@ import os.path as osp import signal import threading +from collections.abc import Mapping from logging import getLogger from pathlib import Path -from typing import Any, Literal, Mapping, overload +from typing import Any, Literal, overload import lightning.pytorch as pl import lightning_utilities.core.rank_zero as rank_zero_module @@ -492,7 +493,7 @@ def infer( infer_from_dataset(self, view, save_dir) def tune(self) -> None: - """Runs Optuna tunning of hyperparameters.""" + """Runs Optuna tuning of hyperparameters.""" import optuna from optuna.integration import PyTorchLightningPruningCallback @@ -778,8 +779,8 @@ def get_status(self) -> tuple[int, int]: """Get current status of training. @rtype: tuple[int, int] - @return: First element is current epoch, second element is total - number of epochs. + @return: First element is the current epoch, second element is + the total number of epochs. """ return self.lightning_module.get_status() @@ -809,7 +810,7 @@ def get_min_loss_checkpoint_path(self) -> str | None: validation loss. @rtype: str - @return: Path to best checkpoint with respect to minimal + @return: Path to the best checkpoint with respect to minimal validation loss """ if not self.pl_trainer.checkpoint_callbacks: @@ -822,8 +823,8 @@ def get_best_metric_checkpoint_path(self) -> str | None: metric. @rtype: str - @return: Path to best checkpoint with respect to best validation - metric + @return: Path to the best checkpoint with respect to best + validation metric """ if len(self.pl_trainer.checkpoint_callbacks) < 2: return None diff --git a/luxonis_train/core/utils/export_utils.py b/luxonis_train/core/utils/export_utils.py index fe94556f..25e1a3ff 100644 --- a/luxonis_train/core/utils/export_utils.py +++ b/luxonis_train/core/utils/export_utils.py @@ -25,7 +25,7 @@ def replace_weights( module.load_state_dict(old_weights) except RuntimeError: logger.error( - "Failed to strictly load old weights. The model likey underwent reparametrization, " + "Failed to strictly load old weights. The model likely underwent re-parametrization, " "which is a destructive operation. Loading old weights with strict=False." ) module.load_state_dict(old_weights, strict=False) diff --git a/luxonis_train/core/utils/infer_utils.py b/luxonis_train/core/utils/infer_utils.py index ffeaa1cb..e7c3a074 100644 --- a/luxonis_train/core/utils/infer_utils.py +++ b/luxonis_train/core/utils/infer_utils.py @@ -9,7 +9,7 @@ from torch import Tensor import luxonis_train -from luxonis_train.attached_modules.visualizers import get_unnormalized_images +from luxonis_train.attached_modules.visualizers import get_denormalized_images IMAGE_FORMATS = { ".bmp", @@ -54,7 +54,7 @@ def prepare_and_infer_image( inputs = { "image": torch.tensor(img).unsqueeze(0).permute(0, 3, 1, 2).float() } - images = get_unnormalized_images(model.cfg, inputs) + images = get_denormalized_images(model.cfg, inputs) outputs = model.lightning_module.forward( inputs, images=images, compute_visualizations=True @@ -178,7 +178,7 @@ def infer_from_dataset( if broken: # pragma: no cover break - images = get_unnormalized_images(model.cfg, inputs) + images = get_denormalized_images(model.cfg, inputs) batch_size = images.shape[0] outputs = model.lightning_module.forward( inputs, labels, images=images, compute_visualizations=True diff --git a/luxonis_train/core/utils/tune_utils.py b/luxonis_train/core/utils/tune_utils.py index ead8a3dd..b602fb44 100644 --- a/luxonis_train/core/utils/tune_utils.py +++ b/luxonis_train/core/utils/tune_utils.py @@ -30,7 +30,7 @@ def _augs_to_indices(all_augs: list[str], aug_names: list[str]) -> list[int]: def get_trial_params( all_augs: list[str], params: dict[str, Any], trial: optuna.trial.Trial ) -> dict[str, Any]: - """Get trial params based on specified config.""" + """Get trial parameters based on specified config.""" new_params = {} for key, value in params.items(): key_info = key.split("_") diff --git a/luxonis_train/models/luxonis_lightning.py b/luxonis_train/models/luxonis_lightning.py index 2ca59117..e10df8c0 100644 --- a/luxonis_train/models/luxonis_lightning.py +++ b/luxonis_train/models/luxonis_lightning.py @@ -23,7 +23,7 @@ ) from luxonis_train.attached_modules.visualizers import ( combine_visualizations, - get_unnormalized_images, + get_denormalized_images, ) from luxonis_train.callbacks import BaseLuxonisProgressBar, ModuleFreezer from luxonis_train.config import AttachedModuleConfig, Config @@ -594,11 +594,11 @@ def process_losses( @param losses_dict: Dictionary of computed losses. Each node can have multiple losses attached. The first key identifies the node, the second key identifies the specific loss. Values - are either single tensors or tuples of tensors and - sublosses. + are either single tensors or tuples of tensors and sub- + losses. @rtype: tuple[Tensor, dict[str, Tensor]] - @return: Tuple of final loss and dictionary of processed - sublosses. The dictionary is in a format of {loss_name: + @return: Tuple of final loss and dictionary of processed sub- + losses. The dictionary is in a format of {loss_name: loss_value}. """ final_loss = torch.zeros(1, device=self.device) @@ -693,7 +693,7 @@ def _evaluation_step( inputs, labels = batch images = None if self._logged_images < self.cfg.trainer.n_log_images: - images = get_unnormalized_images(self.cfg, inputs) + images = get_denormalized_images(self.cfg, inputs) outputs = self.forward( inputs, labels, diff --git a/luxonis_train/nodes/backbones/ddrnet/blocks.py b/luxonis_train/nodes/backbones/ddrnet/blocks.py index 64804b0e..ce78503c 100644 --- a/luxonis_train/nodes/backbones/ddrnet/blocks.py +++ b/luxonis_train/nodes/backbones/ddrnet/blocks.py @@ -28,10 +28,11 @@ def __init__( parameter is omitted, and AdaptiveAvgPool2d over all the input is performed. @type stride: int - @param stride: Stride for the first convolution. When stride=0, - AdaptiveAvgPool2d over all the input is performed (output is - 1x1). When stride=1, nothing is performed. When stride>1, a - convolution with stride=stride is performed. + @param stride: Stride for the first convolution. When stride is + set to 0, C{AdaptiveAvgPool2d} over all the input is + performed (output is 1x1). When set to 1, no operation is + performed. When stride>1, a convolution with + C{stride=stride} is performed. @type in_channels: int @param in_channels: Number of input channels. @type branch_channels: int diff --git a/luxonis_train/nodes/backbones/mobileone/blocks.py b/luxonis_train/nodes/backbones/mobileone/blocks.py index 63e19eae..a9006c7e 100644 --- a/luxonis_train/nodes/backbones/mobileone/blocks.py +++ b/luxonis_train/nodes/backbones/mobileone/blocks.py @@ -50,8 +50,8 @@ def __init__( @param use_se: Whether to use SE-ReLU activations. Defaults to False. @type n_conv_branches: int - @param n_conv_branches: Number of linear conv branches. Defaults - to 1. + @param n_conv_branches: Number of convolutional branches. + Defaults to 1. """ super().__init__() @@ -168,8 +168,8 @@ def reparameterize(self): def _get_kernel_bias(self) -> tuple[Tensor, Tensor]: """Method to obtain re-parameterized kernel and bias. - Reference: U{https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py#L83} + @see: U{https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py#L83} @rtype: tuple[Tensor, Tensor] @return: Tuple of (kernel, bias) after re-parameterization. """ @@ -205,8 +205,10 @@ def _get_kernel_bias(self) -> tuple[Tensor, Tensor]: return kernel_final, bias_final def _fuse_bn_tensor(self, branch: nn.Module) -> tuple[Tensor, Tensor]: - """Method to fuse batchnorm layer with preceeding conv layer. - Reference: U{https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py#L95} + """Method to fuse batch normalization layer with preceding + convolutional layer. + + @see: U{https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py#L95} @rtype: tuple[Tensor, Tensor] @return: Tuple of (kernel, bias) after fusing batchnorm. diff --git a/luxonis_train/nodes/backbones/mobileone/mobileone.py b/luxonis_train/nodes/backbones/mobileone/mobileone.py index 2047e474..1ed476cf 100644 --- a/luxonis_train/nodes/backbones/mobileone/mobileone.py +++ b/luxonis_train/nodes/backbones/mobileone/mobileone.py @@ -130,7 +130,7 @@ def set_export_mode(self, mode: bool = True) -> None: Reparameterizes the model to obtain a plain CNN-like structure for inference. TODO: add more details - @warning: The reparametrization is destructive and cannot be reversed! + @warning: The re-parametrization is destructive and cannot be reversed! @type export: bool @param export: Whether to set the export mode to True or False. Defaults to True. diff --git a/luxonis_train/nodes/base_node.py b/luxonis_train/nodes/base_node.py index 966c89ae..44f2a69c 100644 --- a/luxonis_train/nodes/base_node.py +++ b/luxonis_train/nodes/base_node.py @@ -44,7 +44,7 @@ class BaseNode( When the node is called, the inputs are sent to the L{unwrap} method. The C{unwrap} method should return a valid input to the L{forward} method. - Outputs of the C{forward} method are then send to L{wrap} method, + Outputs of the C{forward} method are then sent to L{wrap} method, which wraps the output into a C{Packet}. The wrapped C{Packet} is the final output of the node. The L{run} method combines the C{unwrap}, C{forward} and C{wrap} methods @@ -53,9 +53,9 @@ class BaseNode( When subclassing, the following methods should be implemented: - L{forward}: Forward pass of the module. - L{unwrap}: Optional. Unwraps the inputs from the input packet. - The default implementation expects a single input with `features` key. + The default implementation expects a single input with C{features} key. - L{wrap}: Optional. Wraps the output of the forward pass - into a `Packet[Tensor]`. The default implementation expects wraps the output + into a C{Packet[Tensor]}. The default implementation expects wraps the output of the forward pass into a packet with either "features" or the task name as the key. Additionally, the following class attributes can be defined: @@ -64,7 +64,7 @@ class BaseNode( Example:: class MyNode(BaseNode): - # equivalent to `tasks = {TaskType.CLASSIFICATION: "classification"}` + # equivalent to C{tasks = {TaskType.CLASSIFICATION: "classification"}} tasks = [TaskType.CLASSIFICATION] def __init__(self, **kwargs): @@ -95,7 +95,7 @@ def wrap(output: Tensor) -> Packet[Tensor]: @type attach_index: AttachIndexType @ivar attach_index: Index of previous output that this node attaches to. Can be a single integer to specify a single output, a tuple of - two or three integers to specify a range of outputs or `"all"` to + two or three integers to specify a range of outputs or C{"all"} to specify all outputs. Defaults to "all". Python indexing conventions apply. @type tasks: list[TaskType] | dict[TaskType, str] | None @@ -122,37 +122,34 @@ def __init__( attach_index: AttachIndexType | None = None, _tasks: dict[TaskType, str] | None = None, ): - """Constructor for the BaseNode. + """Constructor for the C{BaseNode}. @type input_shapes: list[Packet[Size]] | None @param input_shapes: List of input shapes for the module. - @type original_in_shape: Size | None - @param original_in_shape: Original input shape of the model. Some - nodes won't function if not provided. - - @type dataset_metadata: L{DatasetMetadata} | None - @param dataset_metadata: Metadata of the dataset. + @param original_in_shape: Original input shape of the model. Some nodes won't function if not provided. - + @type dataset_metadata: L{DatasetMetadata} | None + @param dataset_metadata: Metadata of the dataset. Some nodes + won't function if not provided. @type n_classes: int | None @param n_classes: Number of classes in the dataset. Provide only - in case `dataset_metadata` is not provided. Defaults to None. - + in case C{dataset_metadata} is not provided. Defaults to + None. @type in_sizes: Size | list[Size] | None - @param in_sizes: List of input sizes for the node. - Provide only in case the `input_shapes` were not provided. - + @param in_sizes: List of input sizes for the node. Provide only + in case the C{input_shapes} were not provided. @type attach_index: AttachIndexType - @param attach_index: Index of previous output that this node attaches to. - Can be a single integer to specify a single output, a tuple of - two or three integers to specify a range of outputs or `"all"` to - specify all outputs. Defaults to "all". Python indexing conventions apply. If provided as a constructor argument, overrides the class attribute. - - + @param attach_index: Index of previous output that this node + attaches to. Can be a single integer to specify a single + output, a tuple of two or three integers to specify a range + of outputs or C{"all"} to specify all outputs. Defaults to + "all". Python indexing conventions apply. If provided as a + constructor argument, overrides the class attribute. @type _tasks: dict[TaskType, str] | None - @param _tasks: Dictionary of tasks that the node supports. Overrides the - class L{tasks} attribute. Shouldn't be provided by the user in most cases. + @param _tasks: Dictionary of tasks that the node supports. + Overrides the class L{tasks} attribute. Shouldn't be + provided by the user in most cases. """ super().__init__() @@ -423,10 +420,10 @@ def dataset_metadata(self) -> DatasetMetadata: def in_sizes(self) -> Size | list[Size]: """Simplified getter for the input shapes. - Should work out of the box for most cases where the `input_shapes` are - sufficiently simple. Otherwise the `input_shapes` should be used directly. + Should work out of the box for most cases where the C{input_shapes} are + sufficiently simple. Otherwise, the C{input_shapes} should be used directly. - In case `in_sizes` were provided during initialization, they are returned + In case C{in_sizes} were provided during initialization, they are returned directly. Example:: @@ -459,7 +456,7 @@ def in_channels(self) -> int | list[int]: """Simplified getter for the number of input channels. Should work out of the box for most cases where the - C{input_shapes} are sufficiently simple. Otherwise the + C{input_shapes} are sufficiently simple. Otherwise, the C{input_shapes} should be used directly. If C{attach_index} is set to "all" or is a slice, returns a list of input channels, otherwise returns a single value. @@ -474,12 +471,13 @@ def in_channels(self) -> int | list[int]: def in_height(self) -> int | list[int]: """Simplified getter for the input height. - Should work out of the box for most cases where the `input_shapes` are - sufficiently simple. Otherwise the `input_shapes` should be used directly. + Should work out of the box for most cases where the + C{input_shapes} are sufficiently simple. Otherwise, the + C{input_shapes} should be used directly. @type: int | list[int] - @raises RuntimeError: If the C{input_shapes} are too complicated for - the default implementation of C{in_sizes}. + @raises RuntimeError: If the C{input_shapes} are too complicated + for the default implementation of C{in_sizes}. """ return self._get_nth_size(-2) @@ -487,12 +485,13 @@ def in_height(self) -> int | list[int]: def in_width(self) -> int | list[int]: """Simplified getter for the input width. - Should work out of the box for most cases where the `input_shapes` are - sufficiently simple. Otherwise the `input_shapes` should be used directly. + Should work out of the box for most cases where the + C{input_shapes} are sufficiently simple. Otherwise, the + C{input_shapes} should be used directly. @type: int | list[int] - @raises RuntimeError: If the C{input_shapes} are too complicated for - the default implementation of C{in_sizes}. + @raises RuntimeError: If the C{input_shapes} are too complicated + for the default implementation of C{in_sizes}. """ return self._get_nth_size(-1) @@ -553,7 +552,8 @@ def forward(self, inputs: ForwardInputT) -> ForwardOutputT: ... def wrap(self, output: ForwardOutputT) -> Packet[Tensor]: - """Wraps the output of the forward pass into a `Packet[Tensor]`. + """Wraps the output of the forward pass into a + C{Packet[Tensor]}. The default implementation expects a single tensor or a list of tensors and wraps them into a Packet with either the node task as a key @@ -609,7 +609,7 @@ def run(self, inputs: list[Packet[Tensor]]) -> Packet[Tensor]: @rtype: L{Packet}[Tensor] @return: Outputs of the module as a dictionary of list of tensors: - `{"features": [Tensor, ...], "segmentation": [Tensor]}` + C{{"features": [Tensor, ...], "segmentation": [Tensor]}} @raises RuntimeError: If default L{wrap} or L{unwrap} methods are not sufficient. """ diff --git a/luxonis_train/utils/boundingbox.py b/luxonis_train/utils/boundingbox.py index c8f69802..e72360c3 100644 --- a/luxonis_train/utils/boundingbox.py +++ b/luxonis_train/utils/boundingbox.py @@ -75,7 +75,7 @@ def bbox_iou( @type bbox2: Tensor @param bbox2: Second set of bboxes [M, 4]. @type bbox_format: BBoxFormatType - @param bbox_format: Input bbox format. Defaults to "xyxy". + @param bbox_format: Input bounding box format. Defaults to C{"xyxy"}. @type iou_type: Literal["none", "giou", "diou", "ciou", "siou"] @param iou_type: IoU type. Defaults to "none". Possible values are: diff --git a/tests/unittests/test_assigners/test_atts_assigner.py b/tests/unittests/test_assigners/test_atss_assigner.py similarity index 100% rename from tests/unittests/test_assigners/test_atts_assigner.py rename to tests/unittests/test_assigners/test_atss_assigner.py