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.

strategy.py 3.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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_pruning as tp
  15. import abc
  16. import torch
  17. import torch.nn as nn
  18. import random
  19. import numpy as np
  20. _PRUNABLE_MODULES= tp.DependencyGraph.PRUNABLE_MODULES
  21. class BaseStrategy(abc.ABC):
  22. @abc.abstractmethod
  23. def select(self, layer_to_prune):
  24. pass
  25. def __call__(self, model, rate=0.1, example_inputs=None):
  26. if example_inputs is None:
  27. example_inputs = torch.randn( 1,3,256,256 )
  28. DG = tp.DependencyGraph()
  29. DG.build_dependency(model, example_inputs=example_inputs)
  30. prunable_layers = []
  31. total_params = 0
  32. num_accumulative_conv_params = [ 0, ]
  33. for m in model.modules():
  34. if isinstance(m, _PRUNABLE_MODULES ) :
  35. nparam = tp.utils.count_prunable_params( m )
  36. total_params += nparam
  37. if isinstance(m, (nn.modules.conv._ConvNd, nn.Linear)):
  38. prunable_layers.append( m )
  39. num_accumulative_conv_params.append( num_accumulative_conv_params[-1]+nparam )
  40. prunable_layers.pop(-1) # remove the last layer
  41. num_accumulative_conv_params.pop(-1) # remove the last layer
  42. num_conv_params = num_accumulative_conv_params[-1]
  43. num_accumulative_conv_params = [ ( num_accumulative_conv_params[i], num_accumulative_conv_params[i+1] ) for i in range(len(num_accumulative_conv_params)-1) ]
  44. def map_param_idx_to_conv_layer(i):
  45. for l, accu in zip( prunable_layers, num_accumulative_conv_params ):
  46. if accu[0]<=i and i<accu[1]:
  47. return l
  48. num_pruned = 0
  49. while num_pruned<total_params*rate:
  50. layer_to_prune = map_param_idx_to_conv_layer( random.randint( 0, num_conv_params-1 ) )
  51. if layer_to_prune.weight.shape[0]<1:
  52. continue
  53. idx = self.select( layer_to_prune )
  54. fn = tp.prune_conv if isinstance(layer_to_prune, nn.modules.conv._ConvNd) else tp.prune_linear
  55. plan = DG.get_pruning_plan( layer_to_prune, fn, idxs=idx )
  56. num_pruned += plan.exec()
  57. return model
  58. class RandomStrategy(BaseStrategy):
  59. def select(self, layer_to_prune):
  60. return [ random.randint( 0, layer_to_prune.weight.shape[0]-1 ) ]
  61. class LNStrategy(BaseStrategy):
  62. def __init__(self, n=2):
  63. self.n = n
  64. def select(self, layer_to_prune):
  65. w = torch.flatten( layer_to_prune.weight, 1 )
  66. norm = torch.norm(w, p=self.n, dim=1)
  67. idx = [ int(norm.min(dim=0)[1].item()) ]
  68. return idx

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

Contributors (1)