You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

kd.py 3.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. Copyright 2020 Tianshu AI Platform. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. =============================================================
  13. """
  14. from kamal.core.engine.trainer import Engine
  15. from kamal.core.tasks.loss import kldiv
  16. import torch.nn.functional as F
  17. from kamal.utils.logger import get_logger
  18. from kamal.utils import set_mode, move_to_device
  19. import weakref
  20. import torch
  21. import torch.nn as nn
  22. import time
  23. import numpy as np
  24. class KDDistiller(Engine):
  25. def __init__( self,
  26. logger=None,
  27. tb_writer=None):
  28. super(KDDistiller, self).__init__(logger=logger, tb_writer=tb_writer)
  29. def setup(self, student, teacher, dataloader, optimizer, T=1.0, alpha=1.0, beta=1.0, gamma=1.0, device=None):
  30. self.model = self.student = student
  31. self.teacher = teacher
  32. self.dataloader = dataloader
  33. self.optimizer = optimizer
  34. if device is None:
  35. device = torch.device( 'cuda' if torch.cuda.is_available() else 'cpu' )
  36. self.device = device
  37. self.T = T
  38. self.gamma = gamma
  39. self.alpha = alpha
  40. self.beta = beta
  41. self.student.to(self.device)
  42. self.teacher.to(self.device)
  43. def run( self, max_iter, start_iter=0, epoch_length=None):
  44. with set_mode(self.student, training=True), \
  45. set_mode(self.teacher, training=False):
  46. super( KDDistiller, self ).run( self.step_fn, self.dataloader, start_iter=start_iter, max_iter=max_iter, epoch_length=epoch_length)
  47. def additional_kd_loss(self, engine, batch):
  48. return batch[0].new_zeros(1)
  49. def step_fn(self, engine, batch):
  50. student = self.student
  51. teacher = self.teacher
  52. start_time = time.perf_counter()
  53. batch = move_to_device(batch, self.device)
  54. inputs, targets = batch
  55. outputs = student(inputs)
  56. with torch.no_grad():
  57. soft_targets = teacher(inputs)
  58. loss_dict = { "loss_kld": self.alpha * kldiv(outputs, soft_targets, T=self.T),
  59. "loss_ce": self.beta * F.cross_entropy( outputs, targets ),
  60. "loss_additional": self.gamma * self.additional_kd_loss(engine, batch) }
  61. loss = sum( loss_dict.values() )
  62. self.optimizer.zero_grad()
  63. loss.backward()
  64. self.optimizer.step()
  65. step_time = time.perf_counter() - start_time
  66. metrics = { loss_name: loss_value.item() for (loss_name, loss_value) in loss_dict.items() }
  67. metrics.update({
  68. 'total_loss': loss.item(),
  69. 'step_time': step_time,
  70. 'lr': float( self.optimizer.param_groups[0]['lr'] )
  71. })
  72. return metrics

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能

Contributors (1)