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

#378 Feature/sg 281 add kd notebook

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-281-add_kd_notebook
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
  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. def forward(self, kd_module_output, target):
  23. task_loss = self.task_loss_fn(kd_module_output.student_output, target)
  24. if isinstance(task_loss, tuple): # SOME LOSS FUNCTIONS RETURNS LOSS AND LOG_ITEMS
  25. task_loss = task_loss[0]
  26. distillation_loss = self.distillation_loss_fn(kd_module_output.student_output, kd_module_output.teacher_output)
  27. loss = task_loss * (1 - self.distillation_loss_coeff) + distillation_loss * self.distillation_loss_coeff
  28. 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