code: def sigmoid_focal_loss(
      input: torch.Tensor,
      target: torch.Tensor,
      gamma: float = 2.0,
      alpha: Optional[float] = None,
  ) -> torch.Tensor:
      """
      FL(pt) = -alpha * (1 - pt)**gamma * log(pt)
  
      where p = sigmoid(x), pt = p if label is 1 or 1 - p if label is 0
      """
      # computing binary cross entropy with logits
      # equivalent to F.binary_cross_entropy_with_logits(input, target, reduction='none')
      # see also https://github.com/pytorch/pytorch/blob/v1.9.0/aten/src/ATen/native/Loss.cpp#L231
      max_val = (-input).clamp(min=0)
      loss: torch.Tensor = (
          input
          - input * target
          + max_val
          + ((-max_val).exp() + (-input - max_val).exp()).log()
      )
  
      # sigmoid(-i) if t==1; sigmoid(i) if t==0 <=>
      # 1-sigmoid(i) if t==1; sigmoid(i) if t==0 <=>
      # 1-p if t==1; p if t==0 <=>
      # pfac, that is, the term (1 - pt)
      invprobs = F.logsigmoid(
          -input * (target * 2 - 1)
      )  # reduced chance of overflow
      # (pfac.log() * gamma).exp() <=>
      # pfac.log().exp() ^ gamma <=>
      # pfac ^ gamma
      loss = (invprobs * gamma).exp() * loss
  
      if alpha is not None:
          # alpha if t==1; (1-alpha) if t==0
          alpha_factor = target * alpha + (1 - target) * (1 - alpha)
          loss = alpha_factor * loss
  
      return loss
  
file_path: MONAI/monai/losses/focal_loss.py
imports: from __future__ import annotations
  import warnings
  from collections.abc import Sequence
  from typing import Optional
  import torch
  import torch.nn.functional
  from torch.nn.modules.loss import _Loss
  from monai.networks import one_hot
  from monai.utils import LossReduction
label_desc: Use image node_id 2 for calling a global function with example usage: sigmoid_focal_loss(input, target, gamma, alpha) and returns: loss