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

#970 Update YoloNASQuickstart.md

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

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