We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Focal loss for single label classification?
### Checklist
- I have searched related issues but cannot get the expected help.
- I have read related documents and don't know what to do.

### Describe the question you meet

I'm trying to train a resnet18 with a LinearClsHead using the focal loss for a single label binary classification problem, but the current focal loss implementation raises an assertion error as the predictions have shape [batch_size, 2] and target has shape [batch_size]. According to the documentation the implemented focal loss only works for multilabel tasks. Is there any way of using it also for single label tasks? 

### Post related information
1. The output of `pip list | grep "mmcv\|mmcls\|^torch"`
mmcls                     0.17.0
mmcv-full                 1.3.9
torch                     1.9.0
torch-model-archiver      0.4.1
torchvision               0.10.0

2. This is the model config I'm using:
```python
# type: ignore
model = dict(
    type="ImageClassifier",
    backbone=dict(
        type="ResNet", depth=18, num_stages=4, out_indices=(3,), style="pytorch"
    ),
    neck=dict(type="GlobalAveragePooling"),
    head=dict(
        type="LinearClsHead",
        num_classes=2,
        in_channels=512,
        loss=dict(type="FocalLoss", loss_weight=1.0),
        topk=(1),
    ),
)

load_from = "/media/VA/pretrained_weights/mmcls/resnet18_batch256_20200708-34ab8f90.pth"
```
3. I am getting the following error during training:
```
File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/apis/train.py", line 164, in train_model
    runner.run(data_loaders, cfg.workflow)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/runner/epoch_based_runner.py", line 127, in run
    epoch_runner(data_loaders[i], **kwargs)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/runner/epoch_based_runner.py", line 50, in train
    self.run_iter(data_batch, train_mode=True, **kwargs)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/runner/epoch_based_runner.py", line 29, in run_iter
    outputs = self.model.train_step(data_batch, self.optimizer,
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/parallel/data_parallel.py", line 67, in train_step
    return self.module.train_step(*inputs[0], **kwargs[0])
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/classifiers/base.py", line 146, in train_step
    losses = self(**data)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/runner/fp16_utils.py", line 98, in new_func
    return old_func(*args, **kwargs)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/classifiers/base.py", line 90, in forward
    return self.forward_train(img, **kwargs)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/classifiers/image.py", line 110, in forward_train
    loss = self.head.forward_train(x, gt_label)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/heads/linear_head.py", line 53, in forward_train
    losses = self.loss(cls_score, gt_label)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/heads/cls_head.py", line 46, in loss
    loss = self.compute_loss(cls_score, gt_label, avg_factor=num_samples)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/losses/focal_loss.py", line 106, in forward
    loss_cls = self.loss_weight * sigmoid_focal_loss(
  File "/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/losses/focal_loss.py", line 36, in sigmoid_focal_loss
    assert pred.shape == \
AssertionError: pred and target should be in the same shape.
```
Thank you!

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mmcls/models/losses/focal_loss.py`
Content:
```
1 # Copyright (c) OpenMMLab. All rights reserved.
2 import torch.nn as nn
3 import torch.nn.functional as F
4 
5 from ..builder import LOSSES
6 from .utils import weight_reduce_loss
7 
8 
9 def sigmoid_focal_loss(pred,
10                        target,
11                        weight=None,
12                        gamma=2.0,
13                        alpha=0.25,
14                        reduction='mean',
15                        avg_factor=None):
16     r"""Sigmoid focal loss.
17 
18     Args:
19         pred (torch.Tensor): The prediction with shape (N, \*).
20         target (torch.Tensor): The ground truth label of the prediction with
21             shape (N, \*).
22         weight (torch.Tensor, optional): Sample-wise loss weight with shape
23             (N, ). Defaults to None.
24         gamma (float): The gamma for calculating the modulating factor.
25             Defaults to 2.0.
26         alpha (float): A balanced form for Focal Loss. Defaults to 0.25.
27         reduction (str): The method used to reduce the loss.
28             Options are "none", "mean" and "sum". If reduction is 'none' ,
29             loss is same shape as pred and label. Defaults to 'mean'.
30         avg_factor (int, optional): Average factor that is used to average
31             the loss. Defaults to None.
32 
33     Returns:
34         torch.Tensor: Loss.
35     """
36     assert pred.shape == \
37         target.shape, 'pred and target should be in the same shape.'
38     pred_sigmoid = pred.sigmoid()
39     target = target.type_as(pred)
40     pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target)
41     focal_weight = (alpha * target + (1 - alpha) *
42                     (1 - target)) * pt.pow(gamma)
43     loss = F.binary_cross_entropy_with_logits(
44         pred, target, reduction='none') * focal_weight
45     if weight is not None:
46         assert weight.dim() == 1
47         weight = weight.float()
48         if pred.dim() > 1:
49             weight = weight.reshape(-1, 1)
50     loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
51     return loss
52 
53 
54 @LOSSES.register_module()
55 class FocalLoss(nn.Module):
56     """Focal loss.
57 
58     Args:
59         gamma (float): Focusing parameter in focal loss.
60             Defaults to 2.0.
61         alpha (float): The parameter in balanced form of focal
62             loss. Defaults to 0.25.
63         reduction (str): The method used to reduce the loss into
64             a scalar. Options are "none" and "mean". Defaults to 'mean'.
65         loss_weight (float): Weight of loss. Defaults to 1.0.
66     """
67 
68     def __init__(self,
69                  gamma=2.0,
70                  alpha=0.25,
71                  reduction='mean',
72                  loss_weight=1.0):
73 
74         super(FocalLoss, self).__init__()
75         self.gamma = gamma
76         self.alpha = alpha
77         self.reduction = reduction
78         self.loss_weight = loss_weight
79 
80     def forward(self,
81                 pred,
82                 target,
83                 weight=None,
84                 avg_factor=None,
85                 reduction_override=None):
86         r"""Sigmoid focal loss.
87 
88         Args:
89             pred (torch.Tensor): The prediction with shape (N, \*).
90             target (torch.Tensor): The ground truth label of the prediction
91                 with shape (N, \*).
92             weight (torch.Tensor, optional): Sample-wise loss weight with shape
93                 (N, \*). Defaults to None.
94             avg_factor (int, optional): Average factor that is used to average
95                 the loss. Defaults to None.
96             reduction_override (str, optional): The method used to reduce the
97                 loss into a scalar. Options are "none", "mean" and "sum".
98                 Defaults to None.
99 
100         Returns:
101             torch.Tensor: Loss.
102         """
103         assert reduction_override in (None, 'none', 'mean', 'sum')
104         reduction = (
105             reduction_override if reduction_override else self.reduction)
106         loss_cls = self.loss_weight * sigmoid_focal_loss(
107             pred,
108             target,
109             weight,
110             gamma=self.gamma,
111             alpha=self.alpha,
112             reduction=reduction,
113             avg_factor=avg_factor)
114         return loss_cls
115
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mmcls/models/losses/focal_loss.py b/mmcls/models/losses/focal_loss.py
--- a/mmcls/models/losses/focal_loss.py
+++ b/mmcls/models/losses/focal_loss.py
@@ -3,7 +3,7 @@
 import torch.nn.functional as F
 
 from ..builder import LOSSES
-from .utils import weight_reduce_loss
+from .utils import convert_to_one_hot, weight_reduce_loss
 
 
 def sigmoid_focal_loss(pred,
@@ -88,7 +88,7 @@
         Args:
             pred (torch.Tensor): The prediction with shape (N, \*).
             target (torch.Tensor): The ground truth label of the prediction
-                with shape (N, \*).
+                with shape (N, \*), N or (N,1).
             weight (torch.Tensor, optional): Sample-wise loss weight with shape
                 (N, \*). Defaults to None.
             avg_factor (int, optional): Average factor that is used to average
@@ -103,6 +103,8 @@
         assert reduction_override in (None, 'none', 'mean', 'sum')
         reduction = (
             reduction_override if reduction_override else self.reduction)
+        if target.dim() == 1 or (target.dim() == 2 and target.shape[1] == 1):
+            target = convert_to_one_hot(target.view(-1, 1), pred.shape[-1])
         loss_cls = self.loss_weight * sigmoid_focal_loss(
             pred,
             target,

{"golden_diff": "diff --git a/mmcls/models/losses/focal_loss.py b/mmcls/models/losses/focal_loss.py\n--- a/mmcls/models/losses/focal_loss.py\n+++ b/mmcls/models/losses/focal_loss.py\n@@ -3,7 +3,7 @@\n import torch.nn.functional as F\n \n from ..builder import LOSSES\n-from .utils import weight_reduce_loss\n+from .utils import convert_to_one_hot, weight_reduce_loss\n \n \n def sigmoid_focal_loss(pred,\n@@ -88,7 +88,7 @@\n         Args:\n             pred (torch.Tensor): The prediction with shape (N, \\*).\n             target (torch.Tensor): The ground truth label of the prediction\n-                with shape (N, \\*).\n+                with shape (N, \\*), N or (N,1).\n             weight (torch.Tensor, optional): Sample-wise loss weight with shape\n                 (N, \\*). Defaults to None.\n             avg_factor (int, optional): Average factor that is used to average\n@@ -103,6 +103,8 @@\n         assert reduction_override in (None, 'none', 'mean', 'sum')\n         reduction = (\n             reduction_override if reduction_override else self.reduction)\n+        if target.dim() == 1 or (target.dim() == 2 and target.shape[1] == 1):\n+            target = convert_to_one_hot(target.view(-1, 1), pred.shape[-1])\n         loss_cls = self.loss_weight * sigmoid_focal_loss(\n             pred,\n             target,\n", "issue": "Focal loss for single label classification?\n### Checklist\r\n- I have searched related issues but cannot get the expected help.\r\n- I have read related documents and don't know what to do.\r\n\r\n### Describe the question you meet\r\n\r\nI'm trying to train a resnet18 with a LinearClsHead using the focal loss for a single label binary classification problem, but the current focal loss implementation raises an assertion error as the predictions have shape [batch_size, 2] and target has shape [batch_size]. According to the documentation the implemented focal loss only works for multilabel tasks. Is there any way of using it also for single label tasks? \r\n\r\n### Post related information\r\n1. The output of `pip list | grep \"mmcv\\|mmcls\\|^torch\"`\r\nmmcls                     0.17.0\r\nmmcv-full                 1.3.9\r\ntorch                     1.9.0\r\ntorch-model-archiver      0.4.1\r\ntorchvision               0.10.0\r\n\r\n2. This is the model config I'm using:\r\n```python\r\n# type: ignore\r\nmodel = dict(\r\n    type=\"ImageClassifier\",\r\n    backbone=dict(\r\n        type=\"ResNet\", depth=18, num_stages=4, out_indices=(3,), style=\"pytorch\"\r\n    ),\r\n    neck=dict(type=\"GlobalAveragePooling\"),\r\n    head=dict(\r\n        type=\"LinearClsHead\",\r\n        num_classes=2,\r\n        in_channels=512,\r\n        loss=dict(type=\"FocalLoss\", loss_weight=1.0),\r\n        topk=(1),\r\n    ),\r\n)\r\n\r\nload_from = \"/media/VA/pretrained_weights/mmcls/resnet18_batch256_20200708-34ab8f90.pth\"\r\n```\r\n3. I am getting the following error during training:\r\n```\r\nFile \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/apis/train.py\", line 164, in train_model\r\n    runner.run(data_loaders, cfg.workflow)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/runner/epoch_based_runner.py\", line 127, in run\r\n    epoch_runner(data_loaders[i], **kwargs)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/runner/epoch_based_runner.py\", line 50, in train\r\n    self.run_iter(data_batch, train_mode=True, **kwargs)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/runner/epoch_based_runner.py\", line 29, in run_iter\r\n    outputs = self.model.train_step(data_batch, self.optimizer,\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/parallel/data_parallel.py\", line 67, in train_step\r\n    return self.module.train_step(*inputs[0], **kwargs[0])\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/classifiers/base.py\", line 146, in train_step\r\n    losses = self(**data)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/torch/nn/modules/module.py\", line 1051, in _call_impl\r\n    return forward_call(*input, **kwargs)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcv/runner/fp16_utils.py\", line 98, in new_func\r\n    return old_func(*args, **kwargs)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/classifiers/base.py\", line 90, in forward\r\n    return self.forward_train(img, **kwargs)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/classifiers/image.py\", line 110, in forward_train\r\n    loss = self.head.forward_train(x, gt_label)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/heads/linear_head.py\", line 53, in forward_train\r\n    losses = self.loss(cls_score, gt_label)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/heads/cls_head.py\", line 46, in loss\r\n    loss = self.compute_loss(cls_score, gt_label, avg_factor=num_samples)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/torch/nn/modules/module.py\", line 1051, in _call_impl\r\n    return forward_call(*input, **kwargs)\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/losses/focal_loss.py\", line 106, in forward\r\n    loss_cls = self.loss_weight * sigmoid_focal_loss(\r\n  File \"/media/data/miniconda3/envs/ai-project-screen_classification/lib/python3.8/site-packages/mmcls/models/losses/focal_loss.py\", line 36, in sigmoid_focal_loss\r\n    assert pred.shape == \\\r\nAssertionError: pred and target should be in the same shape.\r\n```\r\nThank you!\n", "before_files": [{"content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ..builder import LOSSES\nfrom .utils import weight_reduce_loss\n\n\ndef sigmoid_focal_loss(pred,\n                       target,\n                       weight=None,\n                       gamma=2.0,\n                       alpha=0.25,\n                       reduction='mean',\n                       avg_factor=None):\n    r\"\"\"Sigmoid focal loss.\n\n    Args:\n        pred (torch.Tensor): The prediction with shape (N, \\*).\n        target (torch.Tensor): The ground truth label of the prediction with\n            shape (N, \\*).\n        weight (torch.Tensor, optional): Sample-wise loss weight with shape\n            (N, ). Defaults to None.\n        gamma (float): The gamma for calculating the modulating factor.\n            Defaults to 2.0.\n        alpha (float): A balanced form for Focal Loss. Defaults to 0.25.\n        reduction (str): The method used to reduce the loss.\n            Options are \"none\", \"mean\" and \"sum\". If reduction is 'none' ,\n            loss is same shape as pred and label. Defaults to 'mean'.\n        avg_factor (int, optional): Average factor that is used to average\n            the loss. Defaults to None.\n\n    Returns:\n        torch.Tensor: Loss.\n    \"\"\"\n    assert pred.shape == \\\n        target.shape, 'pred and target should be in the same shape.'\n    pred_sigmoid = pred.sigmoid()\n    target = target.type_as(pred)\n    pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target)\n    focal_weight = (alpha * target + (1 - alpha) *\n                    (1 - target)) * pt.pow(gamma)\n    loss = F.binary_cross_entropy_with_logits(\n        pred, target, reduction='none') * focal_weight\n    if weight is not None:\n        assert weight.dim() == 1\n        weight = weight.float()\n        if pred.dim() > 1:\n            weight = weight.reshape(-1, 1)\n    loss = weight_reduce_loss(loss, weight, reduction, avg_factor)\n    return loss\n\n\n@LOSSES.register_module()\nclass FocalLoss(nn.Module):\n    \"\"\"Focal loss.\n\n    Args:\n        gamma (float): Focusing parameter in focal loss.\n            Defaults to 2.0.\n        alpha (float): The parameter in balanced form of focal\n            loss. Defaults to 0.25.\n        reduction (str): The method used to reduce the loss into\n            a scalar. Options are \"none\" and \"mean\". Defaults to 'mean'.\n        loss_weight (float): Weight of loss. Defaults to 1.0.\n    \"\"\"\n\n    def __init__(self,\n                 gamma=2.0,\n                 alpha=0.25,\n                 reduction='mean',\n                 loss_weight=1.0):\n\n        super(FocalLoss, self).__init__()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = reduction\n        self.loss_weight = loss_weight\n\n    def forward(self,\n                pred,\n                target,\n                weight=None,\n                avg_factor=None,\n                reduction_override=None):\n        r\"\"\"Sigmoid focal loss.\n\n        Args:\n            pred (torch.Tensor): The prediction with shape (N, \\*).\n            target (torch.Tensor): The ground truth label of the prediction\n                with shape (N, \\*).\n            weight (torch.Tensor, optional): Sample-wise loss weight with shape\n                (N, \\*). Defaults to None.\n            avg_factor (int, optional): Average factor that is used to average\n                the loss. Defaults to None.\n            reduction_override (str, optional): The method used to reduce the\n                loss into a scalar. Options are \"none\", \"mean\" and \"sum\".\n                Defaults to None.\n\n        Returns:\n            torch.Tensor: Loss.\n        \"\"\"\n        assert reduction_override in (None, 'none', 'mean', 'sum')\n        reduction = (\n            reduction_override if reduction_override else self.reduction)\n        loss_cls = self.loss_weight * sigmoid_focal_loss(\n            pred,\n            target,\n            weight,\n            gamma=self.gamma,\n            alpha=self.alpha,\n            reduction=reduction,\n            avg_factor=avg_factor)\n        return loss_cls\n", "path": "mmcls/models/losses/focal_loss.py"}], "after_files": [{"content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ..builder import LOSSES\nfrom .utils import convert_to_one_hot, weight_reduce_loss\n\n\ndef sigmoid_focal_loss(pred,\n                       target,\n                       weight=None,\n                       gamma=2.0,\n                       alpha=0.25,\n                       reduction='mean',\n                       avg_factor=None):\n    r\"\"\"Sigmoid focal loss.\n\n    Args:\n        pred (torch.Tensor): The prediction with shape (N, \\*).\n        target (torch.Tensor): The ground truth label of the prediction with\n            shape (N, \\*).\n        weight (torch.Tensor, optional): Sample-wise loss weight with shape\n            (N, ). Defaults to None.\n        gamma (float): The gamma for calculating the modulating factor.\n            Defaults to 2.0.\n        alpha (float): A balanced form for Focal Loss. Defaults to 0.25.\n        reduction (str): The method used to reduce the loss.\n            Options are \"none\", \"mean\" and \"sum\". If reduction is 'none' ,\n            loss is same shape as pred and label. Defaults to 'mean'.\n        avg_factor (int, optional): Average factor that is used to average\n            the loss. Defaults to None.\n\n    Returns:\n        torch.Tensor: Loss.\n    \"\"\"\n    assert pred.shape == \\\n        target.shape, 'pred and target should be in the same shape.'\n    pred_sigmoid = pred.sigmoid()\n    target = target.type_as(pred)\n    pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target)\n    focal_weight = (alpha * target + (1 - alpha) *\n                    (1 - target)) * pt.pow(gamma)\n    loss = F.binary_cross_entropy_with_logits(\n        pred, target, reduction='none') * focal_weight\n    if weight is not None:\n        assert weight.dim() == 1\n        weight = weight.float()\n        if pred.dim() > 1:\n            weight = weight.reshape(-1, 1)\n    loss = weight_reduce_loss(loss, weight, reduction, avg_factor)\n    return loss\n\n\n@LOSSES.register_module()\nclass FocalLoss(nn.Module):\n    \"\"\"Focal loss.\n\n    Args:\n        gamma (float): Focusing parameter in focal loss.\n            Defaults to 2.0.\n        alpha (float): The parameter in balanced form of focal\n            loss. Defaults to 0.25.\n        reduction (str): The method used to reduce the loss into\n            a scalar. Options are \"none\" and \"mean\". Defaults to 'mean'.\n        loss_weight (float): Weight of loss. Defaults to 1.0.\n    \"\"\"\n\n    def __init__(self,\n                 gamma=2.0,\n                 alpha=0.25,\n                 reduction='mean',\n                 loss_weight=1.0):\n\n        super(FocalLoss, self).__init__()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = reduction\n        self.loss_weight = loss_weight\n\n    def forward(self,\n                pred,\n                target,\n                weight=None,\n                avg_factor=None,\n                reduction_override=None):\n        r\"\"\"Sigmoid focal loss.\n\n        Args:\n            pred (torch.Tensor): The prediction with shape (N, \\*).\n            target (torch.Tensor): The ground truth label of the prediction\n                with shape (N, \\*), N or (N,1).\n            weight (torch.Tensor, optional): Sample-wise loss weight with shape\n                (N, \\*). Defaults to None.\n            avg_factor (int, optional): Average factor that is used to average\n                the loss. Defaults to None.\n            reduction_override (str, optional): The method used to reduce the\n                loss into a scalar. Options are \"none\", \"mean\" and \"sum\".\n                Defaults to None.\n\n        Returns:\n            torch.Tensor: Loss.\n        \"\"\"\n        assert reduction_override in (None, 'none', 'mean', 'sum')\n        reduction = (\n            reduction_override if reduction_override else self.reduction)\n        if target.dim() == 1 or (target.dim() == 2 and target.shape[1] == 1):\n            target = convert_to_one_hot(target.view(-1, 1), pred.shape[-1])\n        loss_cls = self.loss_weight * sigmoid_focal_loss(\n            pred,\n            target,\n            weight,\n            gamma=self.gamma,\n            alpha=self.alpha,\n            reduction=reduction,\n            avg_factor=avg_factor)\n        return loss_cls\n", "path": "mmcls/models/losses/focal_loss.py"}]}