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

#869 Add DagsHub Logger to Super Gradients

Merged
Ghost merged 1 commits into Deci-AI:master from timho102003:dagshub_logger
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
  1. from torch.nn.modules.loss import _Loss, KLDivLoss
  2. import torch
  3. from super_gradients.common.object_names import Losses
  4. from super_gradients.common.registry.registry import register_loss
  5. class KDklDivLoss(KLDivLoss):
  6. """KL divergence wrapper for knowledge distillation"""
  7. def __init__(self):
  8. super(KDklDivLoss, self).__init__(reduction="batchmean")
  9. def forward(self, student_output, teacher_output):
  10. return super(KDklDivLoss, self).forward(torch.log_softmax(student_output, dim=1), torch.softmax(teacher_output, dim=1))
  11. @register_loss(Losses.KD_LOSS)
  12. class KDLogitsLoss(_Loss):
  13. """Knowledge distillation loss, wraps the task loss and distillation loss"""
  14. def __init__(self, task_loss_fn: _Loss, distillation_loss_fn: _Loss = KDklDivLoss(), distillation_loss_coeff: float = 0.5):
  15. """
  16. :param task_loss_fn: task loss. E.g., LabelSmoothingCrossEntropyLoss
  17. :param distillation_loss_fn: distillation loss. E.g., KLDivLoss
  18. :param distillation_loss_coeff:
  19. """
  20. super(KDLogitsLoss, self).__init__()
  21. self.task_loss_fn = task_loss_fn
  22. self.distillation_loss_fn = distillation_loss_fn
  23. self.distillation_loss_coeff = distillation_loss_coeff
  24. @property
  25. def component_names(self):
  26. """
  27. Component names for logging during training.
  28. These correspond to 2nd item in the tuple returned in self.forward(...).
  29. See super_gradients.Trainer.train() docs for more info.
  30. """
  31. return ["Loss", "Task Loss", "Distillation Loss"]
  32. def forward(self, kd_module_output, target):
  33. task_loss = self.task_loss_fn(kd_module_output.student_output, target)
  34. if isinstance(task_loss, tuple): # SOME LOSS FUNCTIONS RETURNS LOSS AND LOG_ITEMS
  35. task_loss = task_loss[0]
  36. distillation_loss = self.distillation_loss_fn(kd_module_output.student_output, kd_module_output.teacher_output)
  37. loss = task_loss * (1 - self.distillation_loss_coeff) + distillation_loss * self.distillation_loss_coeff
  38. return loss, torch.cat((loss.unsqueeze(0), task_loss.unsqueeze(0), distillation_loss.unsqueeze(0))).detach()
Discard
Tip!

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