class_docstr: Implements SSD architecture from `"SSD: Single Shot MultiBox Detector" <https://arxiv.org/abs/1512.02325>`_.
  
  The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
  image, and should be in 0-1 range. Different images can have different sizes, but they will be resized
  to a fixed size before passing it to the backbone.
  
  The behavior of the model changes depending on if it is in training or evaluation mode.
  
  During training, the model expects both the input tensors and targets (list of dictionary),
  containing:
      - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
        ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
      - labels (Int64Tensor[N]): the class label for each ground-truth box
  
  The model returns a Dict[Tensor] during training, containing the classification and regression
  losses.
  
  During inference, the model requires only the input tensors, and returns the post-processed
  predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
  follows, where ``N`` is the number of detections:
  
      - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
        ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
      - labels (Int64Tensor[N]): the predicted labels for each detection
      - scores (Tensor[N]): the scores for each detection
  
  Args:
      backbone (nn.Module): the network used to compute the features for the model.
          It should contain an out_channels attribute with the list of the output channels of
          each feature map. The backbone should return a single Tensor or an OrderedDict[Tensor].
      anchor_generator (DefaultBoxGenerator): module that generates the default boxes for a
          set of feature maps.
      size (Tuple[int, int]): the width and height to which images will be rescaled before feeding them
          to the backbone.
      num_classes (int): number of output classes of the model (including the background).
      image_mean (Tuple[float, float, float]): mean values used for input normalization.
          They are generally the mean values of the dataset on which the backbone has been trained
          on
      image_std (Tuple[float, float, float]): std values used for input normalization.
          They are generally the std values of the dataset on which the backbone has been trained on
      head (nn.Module, optional): Module run on top of the backbone features. Defaults to a module containing
          a classification and regression module.
      score_thresh (float): Score threshold used for postprocessing the detections.
      nms_thresh (float): NMS threshold used for postprocessing the detections.
      detections_per_img (int): Number of best detections to keep after NMS.
      iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
          considered as positive during training.
      topk_candidates (int): Number of best detections to keep before NMS.
      positive_fraction (float): a number between 0 and 1 which indicates the proportion of positive
          proposals used during the training of the classification head. It is used to estimate the negative to
          positive ratio.
class_docstr_tok: ["Implements","SSD","architecture","from","`","``","SSD",":","Single","Shot","MultiBox","Detector","''","<","https",":","\/\/arxiv.org\/abs\/1512.02325",">","`","_",".","The","input","to","the","model","is","expected","to","be","a","list","of","tensors",",","each","of","shape","[","C",",","H",",","W","]",",","one","for","each","image",",","and","should","be","in","0-1","range",".","Different","images","can","have","different","sizes",",","but","they","will","be","resized","to","a","fixed","size","before","passing","it","to","the","backbone",".","The","behavior","of","the","model","changes","depending","on","if","it","is","in","training","or","evaluation","mode",".","During","training",",","the","model","expects","both","the","input","tensors","and","targets","(","list","of","dictionary",")",",","containing",":","-","boxes","(","``","FloatTensor","[","N",",","4","]","``",")",":","the","ground-truth","boxes","in","``","[","x1",",","y1",",","x2",",","y2","]","``","format",",","with","``","0","<","=","x1","<","x2","<","=","W","``","and","``","0","<","=","y1","<","y2","<","=","H","``",".","-","labels","(","Int64Tensor","[","N","]",")",":","the","class","label","for","each","ground-truth","box","The","model","returns","a","Dict","[","Tensor","]","during","training",",","containing","the","classification","and","regression","losses",".","During","inference",",","the","model","requires","only","the","input","tensors",",","and","returns","the","post-processed","predictions","as","a","List","[","Dict","[","Tensor","]","]",",","one","for","each","input","image",".","The","fields","of","the","Dict","are","as","follows",",","where","``","N","``","is","the","number","of","detections",":","-","boxes","(","``","FloatTensor","[","N",",","4","]","``",")",":","the","predicted","boxes","in","``","[","x1",",","y1",",","x2",",","y2","]","``","format",",","with","``","0","<","=","x1","<","x2","<","=","W","``","and","``","0","<","=","y1","<","y2","<","=","H","``",".","-","labels","(","Int64Tensor","[","N","]",")",":","the","predicted","labels","for","each","detection","-","scores","(","Tensor","[","N","]",")",":","the","scores","for","each","detection","Args",":","backbone","(","nn.Module",")",":","the","network","used","to","compute","the","features","for","the","model",".","It","should","contain","an","out_channels","attribute","with","the","list","of","the","output","channels","of","each","feature","map",".","The","backbone","should","return","a","single","Tensor","or","an","OrderedDict","[","Tensor","]",".","anchor_generator","(","DefaultBoxGenerator",")",":","module","that","generates","the","default","boxes","for","a","set","of","feature","maps",".","size","(","Tuple","[","int",",","int","]",")",":","the","width","and","height","to","which","images","will","be","rescaled","before","feeding","them","to","the","backbone",".","num_classes","(","int",")",":","number","of","output","classes","of","the","model","(","including","the","background",")",".","image_mean","(","Tuple","[","float",",","float",",","float","]",")",":","mean","values","used","for","input","normalization",".","They","are","generally","the","mean","values","of","the","dataset","on","which","the","backbone","has","been","trained","on","image_std","(","Tuple","[","float",",","float",",","float","]",")",":","std","values","used","for","input","normalization",".","They","are","generally","the","std","values","of","the","dataset","on","which","the","backbone","has","been","trained","on","head","(","nn.Module",",","optional",")",":","Module","run","on","top","of","the","backbone","features",".","Defaults","to","a","module","containing","a","classification","and","regression","module",".","score_thresh","(","float",")",":","Score","threshold","used","for","postprocessing","the","detections",".","nms_thresh","(","float",")",":","NMS","threshold","used","for","postprocessing","the","detections",".","detections_per_img","(","int",")",":","Number","of","best","detections","to","keep","after","NMS",".","iou_thresh","(","float",")",":","minimum","IoU","between","the","anchor","and","the","GT","box","so","that","they","can","be","considered","as","positive","during","training",".","topk_candidates","(","int",")",":","Number","of","best","detections","to","keep","before","NMS",".","positive_fraction","(","float",")",":","a","number","between","0","and","1","which","indicates","the","proportion","of","positive","proposals","used","during","the","training","of","the","classification","head",".","It","is","used","to","estimate","the","negative","to","positive","ratio","."]
code: def compute_loss(
      self,
      targets: List[Dict[str, Tensor]],
      head_outputs: Dict[str, Tensor],
      anchors: List[Tensor],
      matched_idxs: List[Tensor],
  ) -> Dict[str, Tensor]:
      bbox_regression = head_outputs["bbox_regression"]
      cls_logits = head_outputs["cls_logits"]
  
      # Match original targets with default boxes
      num_foreground = 0
      bbox_loss = []
      cls_targets = []
      for (
          targets_per_image,
          bbox_regression_per_image,
          cls_logits_per_image,
          anchors_per_image,
          matched_idxs_per_image,
      ) in zip(
          targets, bbox_regression, cls_logits, anchors, matched_idxs
      ):
          # produce the matching between boxes and targets
          foreground_idxs_per_image = torch.where(
              matched_idxs_per_image >= 0
          )[0]
          foreground_matched_idxs_per_image = matched_idxs_per_image[
              foreground_idxs_per_image
          ]
          num_foreground += foreground_matched_idxs_per_image.numel()
  
          # Calculate regression loss
          matched_gt_boxes_per_image = targets_per_image["boxes"][
              foreground_matched_idxs_per_image
          ]
          bbox_regression_per_image = bbox_regression_per_image[
              foreground_idxs_per_image, :
          ]
          anchors_per_image = anchors_per_image[
              foreground_idxs_per_image, :
          ]
          target_regression = self.box_coder.encode_single(
              matched_gt_boxes_per_image, anchors_per_image
          )
          bbox_loss.append(
              torch.nn.functional.smooth_l1_loss(
                  bbox_regression_per_image,
                  target_regression,
                  reduction="sum",
              )
          )
  
          # Estimate ground truth for class targets
          gt_classes_target = torch.zeros(
              (cls_logits_per_image.size(0),),
              dtype=targets_per_image["labels"].dtype,
              device=targets_per_image["labels"].device,
          )
          gt_classes_target[
              foreground_idxs_per_image
          ] = targets_per_image["labels"][
              foreground_matched_idxs_per_image
          ]
          cls_targets.append(gt_classes_target)
  
      bbox_loss = torch.stack(bbox_loss)
      cls_targets = torch.stack(cls_targets)
  
      # Calculate classification loss
      num_classes = cls_logits.size(-1)
      cls_loss = F.cross_entropy(
          cls_logits.view(-1, num_classes),
          cls_targets.view(-1),
          reduction="none",
      ).view(cls_targets.size())
  
      # Hard Negative Sampling
      foreground_idxs = cls_targets > 0
      num_negative = self.neg_to_pos_ratio * foreground_idxs.sum(
          1, keepdim=True
      )
      # num_negative[num_negative < self.neg_to_pos_ratio] = self.neg_to_pos_ratio
      negative_loss = cls_loss.clone()
      negative_loss[foreground_idxs] = -float(
          "inf"
      )  # use -inf to detect positive values that creeped in the sample
      values, idx = negative_loss.sort(1, descending=True)
      # background_idxs = torch.logical_and(idx.sort(1)[1] < num_negative, torch.isfinite(values))
      background_idxs = idx.sort(1)[1] < num_negative
  
      N = max(1, num_foreground)
      return {
          "bbox_regression": bbox_loss.sum() / N,
          "classification": (
              cls_loss[foreground_idxs].sum()
              + cls_loss[background_idxs].sum()
          )
          / N,
      }
  
imports: import warnings
  from collections import OrderedDict
  from typing import Any, Dict, List, Optional, Tuple
  import torch
  import torch.nn.functional
  from torch import nn, Tensor
  from ...ops import boxes
  from ...transforms._presets import ObjectDetection
  from ...utils import _log_api_usage_once
  from .._api import register_model, Weights, WeightsEnum
  from .._meta import _COCO_CATEGORIES
  from .._utils import _ovewrite_value_param, handle_legacy_interface
  from ..vgg import VGG, vgg16, VGG16_Weights
  from .None import _utils
  from .anchor_utils import DefaultBoxGenerator
  from .backbone_utils import _validate_trainable_layers
  from .transform import GeneralizedRCNNTransform
label_desc: Use image node_id 3 for calling the SSD obj's underlying member method code with example usage: obj.compute_loss(targets, head_outputs, anchors, matched_idxs) and returns: dict