code: # https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.ht
  from torch.nn.modules.loss import _Loss
  from typing import Optional
  from torch import Tensor
  import torch.nn.functional as F
  
  class BCEWithLogitsLoss(_Loss):
      r"""This loss combines a `Sigmoid` layer and the `BCELoss` in one single
      class. This version is more numerically stable than using a plain `Sigmoid`
      followed by a `BCELoss` as, by combining the operations into one layer,
      we take advantage of the log-sum-exp trick for numerical stability.
  
      The unreduced (i.e. with :attr:`reduction` set to ``'none'``) loss can be described as:
  
      .. math::
          \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
          l_n = - w_n \left[ y_n \cdot \log \sigma(x_n)
          + (1 - y_n) \cdot \log (1 - \sigma(x_n)) \right],
  
      where :math:`N` is the batch size. If :attr:`reduction` is not ``'none'``
      (default ``'mean'``), then
  
      .. math::
          \ell(x, y) = \begin{cases}
              \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
              \operatorname{sum}(L),  & \text{if reduction} = \text{`sum'.}
          \end{cases}
  
      This is used for measuring the error of a reconstruction in for example
      an auto-encoder. Note that the targets `t[i]` should be numbers
      between 0 and 1.
  
      It's possible to trade off recall and precision by adding weights to positive examples.
      In the case of multi-label classification the loss can be described as:
  
      .. math::
          \ell_c(x, y) = L_c = \{l_{1,c},\dots,l_{N,c}\}^\top, \quad
          l_{n,c} = - w_{n,c} \left[ p_c y_{n,c} \cdot \log \sigma(x_{n,c})
          + (1 - y_{n,c}) \cdot \log (1 - \sigma(x_{n,c})) \right],
  
      where :math:`c` is the class number (:math:`c > 1` for multi-label binary classification,
      :math:`c = 1` for single-label binary classification),
      :math:`n` is the number of the sample in the batch and
      :math:`p_c` is the weight of the positive answer for the class :math:`c`.
  
      :math:`p_c > 1` increases the recall, :math:`p_c < 1` increases the precision.
  
      For example, if a dataset contains 100 positive and 300 negative examples of a single class,
      then `pos_weight` for the class should be equal to :math:`\frac{300}{100}=3`.
      The loss would act as if the dataset contains :math:`3\times 100=300` positive examples.
  
      Examples::
  
          >>> target = torch.ones([10, 64], dtype=torch.float32)  # 64 classes, batch size = 10
          >>> output = torch.full([10, 64], 1.5)  # A prediction (logit)
          >>> pos_weight = torch.ones([64])  # All weights are equal to 1
          >>> criterion = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight)
          >>> criterion(output, target)  # -log(sigmoid(1.5))
          tensor(0.2014)
  
      Args:
          weight (Tensor, optional): a manual rescaling weight given to the loss
              of each batch element. If given, has to be a Tensor of size `nbatch`.
          size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
              the losses are averaged over each loss element in the batch. Note that for
              some losses, there are multiple elements per sample. If the field :attr:`size_average`
              is set to ``False``, the losses are instead summed for each minibatch. Ignored
              when :attr:`reduce` is ``False``. Default: ``True``
          reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
              losses are averaged or summed over observations for each minibatch depending
              on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
              batch element instead and ignores :attr:`size_average`. Default: ``True``
          reduction (string, optional): Specifies the reduction to apply to the output:
              ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
              ``'mean'``: the sum of the output will be divided by the number of
              elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
              and :attr:`reduce` are in the process of being deprecated, and in the meantime,
              specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
          pos_weight (Tensor, optional): a weight of positive examples.
                  Must be a vector with length equal to the number of classes.
  
      Shape:
          - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
          - Target: :math:`(*)`, same shape as the input.
          - Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(*)`, same
            shape as input.
  
       Examples::
  
          >>> loss = nn.BCEWithLogitsLoss()
          >>> input = torch.randn(3, requires_grad=True)
          >>> target = torch.empty(3).random_(2)
          >>> output = loss(input, target)
          >>> output.backward()
      """
      def __init__(self, weight: Optional[Tensor] = None, size_average=None, reduce=None, reduction: str = 'mean',
                   pos_weight: Optional[Tensor] = None) -> None:
          super(BCEWithLogitsLoss, self).__init__(size_average, reduce, reduction)
          self.register_buffer('weight', weight)
          self.register_buffer('pos_weight', pos_weight)
          self.weight: Optional[Tensor]
          self.pos_weight: Optional[Tensor]
  
      def forward(self, inputs, target):
          return F.binary_cross_entropy_with_logits(inputs, target,
                                                    self.weight)
apis: torch.nn.functional.binary_cross_entropy_with_logits