Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#604 fix master installation

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-000_fix_master_inastallation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  1. import torch
  2. from torch.nn.modules.loss import _Loss
  3. from super_gradients.training.losses.loss_utils import apply_reduce, LossReduction
  4. from typing import Union
  5. class MaskAttentionLoss(_Loss):
  6. """
  7. Pixel mask attention loss. For semantic segmentation usages with 4D tensors.
  8. """
  9. def __init__(self,
  10. criterion: _Loss,
  11. loss_weights: Union[list, tuple] = (1., 1.),
  12. reduction: Union[LossReduction, str] = "mean"):
  13. """
  14. :param criterion: _Loss object, loss function that apply per pixel cost penalty are supported, i.e
  15. CrossEntropyLoss, BCEWithLogitsLoss, MSELoss, SL1Loss.
  16. criterion reduction must be `none`.
  17. :param loss_weights: Weight to apply for each part of the loss contributions,
  18. [regular loss, masked loss] respectively.
  19. :param reduction: Specifies the reduction to apply to the output: `none` | `mean` | `sum`.
  20. `none`: no reduction will be applied.
  21. `mean`: the sum of the output will be divided by the number of elements in the output.
  22. `sum`: the output will be summed.
  23. Default: `mean`
  24. """
  25. super().__init__(reduction=reduction.value if isinstance(reduction, LossReduction) else reduction)
  26. # Check that the arguments are valid.
  27. if criterion.reduction != "none":
  28. raise ValueError(f"criterion reduction must be `none`, for computing the mask contribution loss values,"
  29. f" found reduction: {criterion.reduction}")
  30. if len(loss_weights) != 2:
  31. raise ValueError(f"loss_weights must have 2 values, found: {len(loss_weights)}")
  32. if loss_weights[1] <= 0:
  33. raise ValueError("If no loss weight is applied on mask samples, consider using simply criterion")
  34. self.criterion = criterion
  35. self.loss_weights = loss_weights
  36. def forward(self, predict: torch.Tensor, target: torch.Tensor, mask: torch.Tensor):
  37. criterion_loss = self.criterion(predict, target)
  38. mask = self._broadcast_mask(mask, criterion_loss.size())
  39. mask_loss = criterion_loss * mask
  40. if self.reduction == LossReduction.NONE.value:
  41. return criterion_loss * self.loss_weights[0] + mask_loss * self.loss_weights[1]
  42. mask_loss = mask_loss[mask == 1] # consider only mask samples for mask loss computing
  43. mask_loss = apply_reduce(mask_loss, self.reduction)
  44. criterion_loss = apply_reduce(criterion_loss, self.reduction)
  45. loss = criterion_loss * self.loss_weights[0] + mask_loss * self.loss_weights[1]
  46. return loss
  47. def _broadcast_mask(self, mask: torch.Tensor, size: torch.Size):
  48. """
  49. Broadcast the mask tensor before elementwise multiplication.
  50. """
  51. # Assert that batch size and spatial size are the same.
  52. if mask.size()[-2:] != size[-2:] or mask.size(0) != size[0]:
  53. raise AssertionError("Mask broadcast is allowed only in channels dimension, found shape mismatch between"
  54. f"mask shape: {mask.size()}, and target shape: {size}")
  55. # when mask is [B, 1, H, W] | [B, H, W] and size is [B, H, W]
  56. # or when mask is [B, 1, H, W] | [B, H, W] and size is [B, 1, H, W]
  57. if len(size) == 3 or (len(size) == 4 and size[1] == 1):
  58. mask = mask.view(*size)
  59. # when mask is [B, C, H, W] | [B, 1, H, W] | [B, H, W] and size is [B, C, H, W]
  60. else:
  61. mask = mask if len(mask.size()) == 4 else mask.unsqueeze(1)
  62. if mask.size(1) not in [1, size[1]]:
  63. raise AssertionError(f"Broadcast is not allowed, num mask channels must be 1 or same as target channels"
  64. f"mask shape: {mask.size()}, and target shape: {size}")
  65. mask = mask if mask.size() == size else mask.expand(*size)
  66. return mask
Discard
Tip!

Press p or to see the previous file or, n or to see the next file