test_distillation_empty_supervision.py 993 B

123456789101112131415161718192021
  1. import unittest
  2. import torch
  3. from trainer.train_distillation import distillation_loss
  4. class EmptyDistillationTests(unittest.TestCase):
  5. def test_all_ignored_labels_produce_differentiable_zero(self):
  6. student = torch.randn(2, 4, 8, requires_grad=True)
  7. teacher = torch.randn_like(student)
  8. valid = torch.zeros(2, 4, dtype=torch.bool)
  9. loss = distillation_loss(student[valid], teacher[valid], temperature=1.5)
  10. self.assertTrue(bool(loss.isfinite()))
  11. self.assertEqual(loss.item(), 0.0)
  12. loss.backward()
  13. self.assertTrue(torch.equal(student.grad, torch.zeros_like(student)))
  14. def test_nonempty_identical_logits_keep_zero_loss(self):
  15. student = torch.tensor([[0.1, 0.2, 0.3]], requires_grad=True)
  16. loss = distillation_loss(student, student.detach().clone(), temperature=1.5)
  17. self.assertAlmostEqual(loss.item(), 0.0, places=6)
  18. loss.backward()
  19. self.assertTrue(bool(student.grad.isfinite().all()))