Skip to content

Commit

Permalink
Missing types and pyleft (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
kozlov721 authored Feb 4, 2025
1 parent c82c86d commit 9948244
Show file tree
Hide file tree
Showing 61 changed files with 286 additions and 319 deletions.
5 changes: 4 additions & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ jobs:
- name: Install dependencies
run: pip install -e .[dev]

- name: Type check
- name: Pyright check
uses: jakebailey/pyright-action@v2
with:
version: '1.1.380'
Expand All @@ -73,6 +73,9 @@ jobs:
python-version: '3.10'
project: pyproject.toml

- name: Pyleft Check
run: pyleft luxonis_train

tests:
needs:
- type-check
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal, cast
from typing import Literal, cast

import torch
import torch.nn.functional as F
Expand Down Expand Up @@ -37,7 +37,7 @@ def __init__(
reduction: Literal["sum", "mean"] = "mean",
class_loss_weight: float = 1.0,
iou_loss_weight: float = 2.5,
**kwargs: Any,
**kwargs,
):
"""BBox loss adapted from U{YOLOv6: A Single-Stage Object Detection Framework for Industrial Applications
<https://arxiv.org/pdf/2209.02976.pdf>}. It combines IoU based bbox regression loss and varifocal loss
Expand Down
4 changes: 2 additions & 2 deletions luxonis_train/attached_modules/losses/bce_with_logits.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal
from typing import Literal

import torch
from torch import Tensor, nn
Expand All @@ -16,7 +16,7 @@ def __init__(
weight: list[float] | None = None,
reduction: Literal["none", "mean", "sum"] = "mean",
pos_weight: Tensor | None = None,
**kwargs: Any,
**kwargs,
):
"""This loss combines a L{nn.Sigmoid} layer and the
L{nn.BCELoss} in one single class. This version is more
Expand Down
4 changes: 2 additions & 2 deletions luxonis_train/attached_modules/losses/cross_entropy.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal
from typing import Literal

import torch
import torch.nn as nn
Expand All @@ -22,7 +22,7 @@ def __init__(
ignore_index: int = -100,
reduction: Literal["none", "mean", "sum"] = "mean",
label_smoothing: float = 0.0,
**kwargs: Any,
**kwargs,
):
super().__init__(**kwargs)

Expand Down
4 changes: 1 addition & 3 deletions luxonis_train/attached_modules/losses/ctc_loss.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Any

import torch
import torch.nn as nn
from torch import Tensor
Expand All @@ -14,7 +12,7 @@ class CTCLoss(BaseLoss):

node: OCRCTCHead

def __init__(self, use_focal_loss: bool = True, **kwargs: Any):
def __init__(self, use_focal_loss: bool = True, **kwargs):
"""Initializes the CTC loss with optional focal loss support.
@type use_focal_loss: bool
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal
from typing import Literal

import torch
import torch.nn.functional as F
Expand Down Expand Up @@ -37,7 +37,7 @@ def __init__(
vis_kpts_loss_weight: float = 1.0,
sigmas: list[float] | None = None,
area_factor: float | None = None,
**kwargs: Any,
**kwargs,
):
"""BBox loss adapted from U{YOLOv6: A Single-Stage Object Detection Framework for Industrial Applications
<https://arxiv.org/pdf/2209.02976.pdf>}. It combines IoU based bbox regression loss and varifocal loss
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Any

import torch
import torch.nn.functional as F
from torch import Tensor
Expand All @@ -15,13 +13,11 @@ class FOMOLocalizationLoss(BaseLoss):
node: FOMOHead
supported_tasks = [Tasks.FOMO]

def __init__(self, object_weight: float = 500, **kwargs: Any):
def __init__(self, object_weight: float = 500, **kwargs):
"""FOMO Localization Loss for object detection using heatmaps.
@type object_weight: float
@param object_weight: Weight for object in loss calculation.
@type kwargs: Any
@param kwargs: Additional arguments.
"""
super().__init__(**kwargs)
self.original_img_size = self.original_in_shape[1:]
Expand Down
4 changes: 1 addition & 3 deletions luxonis_train/attached_modules/losses/ohem_loss.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Any

import torch
from torch import Tensor

Expand All @@ -18,7 +16,7 @@ def __init__(
criterion: BaseLoss,
ohem_ratio: float = 0.1,
ohem_threshold: float = 0.7,
**kwargs: Any,
**kwargs,
):
"""Initializes the criterion.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, cast
from typing import cast

import torch
import torch.nn.functional as F
Expand Down Expand Up @@ -28,7 +28,7 @@ def __init__(
class_loss_weight: float = 0.5,
bbox_loss_weight: float = 7.5,
dfl_loss_weight: float = 1.5,
**kwargs: Any,
**kwargs,
):
"""BBox loss adapted from U{Real-Time Flying Object Detection with YOLOv8
<https://arxiv.org/pdf/2305.09972>} and from U{YOLOv6: A Single-Stage Object Detection Framework for Industrial Applications
Expand Down Expand Up @@ -162,7 +162,7 @@ def decode_bbox(self, anchor_points: Tensor, pred_dist: Tensor) -> Tensor:
)
return dist2bbox(dist_transformed, anchor_points, out_format="xyxy")

def _init_parameters(self, features: list[Tensor]):
def _init_parameters(self, features: list[Tensor]) -> None:
if not hasattr(self, "gt_bboxes_scale"):
_, self.anchor_points, _, self.stride_tensor = (
anchors_for_fpn_features(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Any

import torch
import torch.nn.functional as F
from torch import Tensor
Expand All @@ -22,7 +20,7 @@ def __init__(
class_loss_weight: float = 0.5,
bbox_loss_weight: float = 7.5,
dfl_loss_weight: float = 1.5,
**kwargs: Any,
**kwargs,
):
"""Instance Segmentation and BBox loss adapted from U{Real-Time Flying Object Detection with YOLOv8
<https://arxiv.org/pdf/2305.09972>} and from U{YOLOv6: A Single-Stage Object Detection Framework for Industrial Applications
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def create_window(window_size: int, channel: int = 1) -> Tensor:


def gaussian(window_size: int, sigma: float) -> Tensor:
gauss = torch.Tensor(
gauss = torch.tensor(
[
exp(-((x - window_size // 2) ** 2) / float(2 * sigma**2))
for x in range(window_size)
Expand Down
4 changes: 2 additions & 2 deletions luxonis_train/attached_modules/losses/sigmoid_focal_loss.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal
from typing import Literal

from torch import Tensor
from torchvision.ops import sigmoid_focal_loss
Expand All @@ -15,7 +15,7 @@ def __init__(
alpha: float = 0.25,
gamma: float = 2.0,
reduction: Literal["none", "mean", "sum"] = "mean",
**kwargs: Any,
**kwargs,
):
"""Focal loss from U{Focal Loss for Dense Object Detection
<https://arxiv.org/abs/1708.02002>}.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal
from typing import Literal

import torch
from torch import Tensor
Expand All @@ -18,7 +18,7 @@ def __init__(
bce_pow: float = 1.0,
weight: list[float] | None = None,
reduction: Literal["mean", "sum", "none"] = "mean",
**kwargs: Any,
**kwargs,
):
"""BCE with logits loss and label smoothing.
Expand Down
4 changes: 2 additions & 2 deletions luxonis_train/attached_modules/losses/softmax_focal_loss.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal
from typing import Literal

import torch
from torch import Tensor
Expand All @@ -18,7 +18,7 @@ def __init__(
gamma: float = 2.0,
smooth: float = 0.0,
reduction: Literal["none", "mean", "sum"] = "mean",
**kwargs: Any,
**kwargs,
):
"""Focal loss implementation for classification and segmentation
tasks using Softmax.
Expand Down
14 changes: 7 additions & 7 deletions luxonis_train/attached_modules/metrics/embedding_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def update(self, predictions: Tensor, target: Tensor) -> None:
self.correct_predictions += correct_predictions
self.total_predictions += len(filtered_labels)

def compute(self):
def compute(self) -> Tensor:
return self.correct_predictions / self.total_predictions


Expand All @@ -90,7 +90,7 @@ def __init__(self, **kwargs):
"closest_vs_positive_distances", default=[], dist_reduce_fx="cat"
)

def update(self, embeddings: Tensor, target: Tensor):
def update(self, embeddings: Tensor, target: Tensor) -> None:
if self.cross_batch_memory_size is not None:
self.cross_batch_memory.extend(list(zip(embeddings, target)))

Expand Down Expand Up @@ -137,7 +137,7 @@ def update(self, embeddings: Tensor, target: Tensor):
closest_positive_distances[non_inf_mask]
)

def compute(self):
def compute(self) -> dict[str, Tensor]:
if len(self.all_distances) == 0:
return {
"MedianDistance": torch.tensor(float("nan")),
Expand Down Expand Up @@ -165,18 +165,18 @@ def compute(self):
}


def _pairwise_distances(embeddings, squared=False):
def _pairwise_distances(embeddings: Tensor, squared: bool = False) -> Tensor:
"""Compute the 2D matrix of distances between all the embeddings.
@param embeddings: tensor of shape (batch_size, embed_dim)
@type embeddings: torch.Tensor
@type embeddings: Tensor
@param squared: If true, output is the pairwise squared euclidean
distance matrix. If false, output is the pairwise euclidean
distance matrix.
@type squared: bool
@return: pairwise_distances: tensor of shape (batch_size,
batch_size)
@rtype: torch.Tensor
@rtype: Tensor
"""
dot_product = torch.matmul(embeddings, embeddings.t())

Expand All @@ -198,7 +198,7 @@ def _pairwise_distances(embeddings, squared=False):
return distances


def _get_anchor_positive_triplet_mask(labels):
def _get_anchor_positive_triplet_mask(labels: Tensor) -> Tensor:
indices_equal = torch.eye(
labels.shape[0], dtype=torch.uint8, device=labels.device
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Any

import torch
import torchmetrics.detection as detection
from torch import Tensor
Expand All @@ -20,7 +18,7 @@ class MeanAveragePrecisionBBox(BaseMetric, register=False):

supported_tasks = [Tasks.BOUNDINGBOX]

def __init__(self, **kwargs: Any):
def __init__(self, **kwargs):
super().__init__(**kwargs)

self.metric = detection.MeanAveragePrecision(iou_type="bbox")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from functools import cached_property
from typing import Any

import torch
from scipy.optimize import linear_sum_assignment
Expand Down Expand Up @@ -35,7 +34,7 @@ def __init__(
sigmas: list[float] | None = None,
area_factor: float | None = None,
use_cocoeval_oks: bool = True,
**kwargs: Any,
**kwargs,
) -> None:
"""Object Keypoint Similarity metric for evaluating keypoint
predictions.
Expand Down
2 changes: 1 addition & 1 deletion luxonis_train/attached_modules/metrics/ocr_accuracy.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(self, blank_cls: int = 0, **kwargs):
self.blank_cls = blank_cls
self._init_metric()

def _init_metric(self):
def _init_metric(self) -> None:
"""Initializes the running metric."""
self.running_metric = {
"acc_0": 0.0,
Expand Down
3 changes: 1 addition & 2 deletions luxonis_train/attached_modules/metrics/torchmetrics.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from contextlib import suppress
from functools import cached_property
from typing import Any

import torchmetrics
from torch import Tensor
Expand All @@ -14,7 +13,7 @@
class TorchMetricWrapper(BaseMetric):
Metric: type[torchmetrics.Metric]

def __init__(self, **kwargs: Any):
def __init__(self, **kwargs):
super().__init__(node=kwargs.pop("node", None))
task = kwargs.get("task")
if task is None:
Expand Down
Loading

0 comments on commit 9948244

Please sign in to comment.