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.

vid.py 3.6 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. import numpy as np
  15. import time
  16. import torch.nn as nn
  17. import torch._ops
  18. import torch.nn.functional as F
  19. from .kd import KDDistiller
  20. from kamal.utils import set_mode
  21. from kamal.core.tasks.loss import KDLoss
  22. class VIDDistiller(KDDistiller):
  23. def __init__(self, logger=None, tb_writer=None ):
  24. super(VIDDistiller, self).__init__( logger, tb_writer )
  25. def setup(self, student, teacher, dataloader, optimizer, regressor_l, T=1.0, alpha=1.0, beta=1.0, gamma=1.0, stu_hooks=[], tea_hooks=[], out_flags=[], device=None):
  26. super( VIDDistiller, self ).setup(
  27. student, teacher, dataloader, optimizer, T=T, alpha=alpha, beta=beta, gamma=gamma, device=device )
  28. self.regressor_l = regressor_l
  29. self.stu_hooks = stu_hooks
  30. self.tea_hooks = tea_hooks
  31. self.out_flags = out_flags
  32. self.regressor_l = [regressor.to(self.device).train() for regressor in self.regressor_l]
  33. def additional_kd_loss(self, engine, batch):
  34. feat_s = [f.feat_out if flag else f.feat_in for (f, flag) in zip(self.stu_hooks, self.out_flags)]
  35. feat_t = [f.feat_out.detach() if flag else f.feat_in for (f, flag) in zip(self.tea_hooks, self.out_flags)]
  36. g_s = feat_s[1:-1]
  37. g_t = feat_t[1:-1]
  38. return sum([c(f_s, f_t) for f_s, f_t, c in zip(g_s, g_t, self.regressor_l)])
  39. class VIDRegressor(nn.Module):
  40. def __init__(self,
  41. num_input_channels,
  42. num_mid_channel,
  43. num_target_channels,
  44. init_pred_var=5.0,
  45. eps=1e-5):
  46. super(VIDRegressor, self).__init__()
  47. def conv1x1(in_channels, out_channels, stride=1):
  48. return nn.Conv2d(
  49. in_channels, out_channels,
  50. kernel_size=1, padding=0,
  51. bias=False, stride=stride)
  52. self.regressor = nn.Sequential(
  53. conv1x1(num_input_channels, num_mid_channel),
  54. nn.ReLU(),
  55. conv1x1(num_mid_channel, num_mid_channel),
  56. nn.ReLU(),
  57. conv1x1(num_mid_channel, num_target_channels),
  58. )
  59. self.log_scale = torch.nn.Parameter(
  60. np.log(np.exp(init_pred_var-eps)-1.0) * torch.ones(num_target_channels)
  61. )
  62. self.eps = eps
  63. def forward(self, input, target):
  64. # pool for dimentsion match
  65. s_H, t_H = input.shape[2], target.shape[2]
  66. if s_H > t_H:
  67. input = F.adaptive_avg_pool2d(input, (t_H, t_H))
  68. elif s_H < t_H:
  69. target = F.adaptive_avg_pool2d(target, (s_H, s_H))
  70. else:
  71. pass
  72. pred_mean = self.regressor(input)
  73. pred_var = torch.log(1.0+torch.exp(self.log_scale))+self.eps
  74. pred_var = pred_var.view(1, -1, 1, 1)
  75. neg_log_prob = 0.5*(
  76. (pred_mean-target)**2/pred_var+torch.log(pred_var)
  77. )
  78. loss = torch.mean(neg_log_prob)
  79. return loss

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

Contributors (1)