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.

zskt.py 3.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. import torch
  15. import time
  16. import torch.nn.functional as F
  17. from kamal.slim.distillation.kd import KDDistiller
  18. from kamal.utils import set_mode
  19. from kamal.core.tasks.loss import kldiv
  20. class ZSKTDistiller(KDDistiller):
  21. def __init__( self,
  22. student,
  23. teacher,
  24. generator,
  25. z_dim,
  26. logger=None,
  27. viz=None):
  28. super(ZSKTDistiller, self).__init__(logger, viz)
  29. self.teacher = teacher
  30. self.model = self.student = student
  31. self.generator = generator
  32. self.z_dim = z_dim
  33. def train(self, start_iter, max_iter, optim_s, optim_g, device=None):
  34. if device is None:
  35. device = torch.device( 'cuda' if torch.cuda.is_available() else 'cpu' )
  36. self.device = device
  37. self.optim_s, self.optim_g = optim_s, optim_g
  38. self.model.to(self.device)
  39. self.teacher.to(self.device)
  40. self.generator.to(self.device)
  41. self.train_loader = [0, ]
  42. with set_mode(self.student, training=True), \
  43. set_mode(self.teacher, training=False), \
  44. set_mode(self.generator, training=True):
  45. super( ZSKTDistiller, self ).train( start_iter, max_iter )
  46. def search_optimizer(self, evaluator, train_loader, hpo_space=None, mode='min', max_evals=20, max_iters=400):
  47. optimizer = hpo.search_optimizer(self, train_loader, evaluator=evaluator, hpo_space=hpo_space, mode=mode, max_evals=max_evals, max_iters=max_iters)
  48. return optimizer
  49. def step(self):
  50. start_time = time.perf_counter()
  51. # Adv
  52. z = torch.randn( self.z_dim ).to(self.device)
  53. fake = self.generator( z )
  54. self.optim_g.zero_grad()
  55. t_out = self.teacher( fake )
  56. s_out = self.student( fake )
  57. loss_g = -kldiv( s_out, t_out )
  58. loss_g.backward()
  59. self.optim_g.step()
  60. with torch.no_grad():
  61. fake = self.generator( z )
  62. t_out = self.teacher( fake.detach() )
  63. for _ in range(10):
  64. self.optim_s.zero_grad()
  65. s_out = self.student( fake.detach() )
  66. loss_s = kldiv( s_out, t_out )
  67. loss_s.backward()
  68. self.optim_s.step()
  69. loss_dict = {
  70. 'loss_g': loss_g,
  71. 'loss_s': loss_s,
  72. }
  73. step_time = time.perf_counter() - start_time
  74. # record training info
  75. info = loss_dict
  76. info['step_time'] = step_time
  77. info['lr_s'] = float( self.optim_s.param_groups[0]['lr'] )
  78. info['lr_g'] = float( self.optim_g.param_groups[0]['lr'] )
  79. self.history.put_scalars( **info )
  80. def reset(self):
  81. self.history = None
  82. self._train_loader_iter = iter(train_loader)
  83. self.iter = self.start_iter

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

Contributors (1)