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

#609 Ci fix

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