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.

mutator.py 1.4 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536
  1. import torch
  2. import torch.nn.functional as F
  3. from pytorch.mutator import Mutator
  4. from pytorch.mutables import LayerChoice, InputChoice
  5. # TODO: This class is duplicate with SPOS.
  6. class RandomMutator(Mutator):
  7. """
  8. Random mutator that samples a random candidate in the search space each time ``reset()``.
  9. It uses random function in PyTorch, so users can set seed in PyTorch to ensure deterministic behavior.
  10. """
  11. def sample_search(self):
  12. """
  13. Sample a random candidate.
  14. """
  15. result = dict()
  16. for mutable in self.mutables:
  17. if isinstance(mutable, LayerChoice):
  18. gen_index = torch.randint(high=len(mutable), size=(1, ))
  19. result[mutable.key] = F.one_hot(gen_index, num_classes=len(mutable)).view(-1).bool()
  20. elif isinstance(mutable, InputChoice):
  21. if mutable.n_chosen is None:
  22. result[mutable.key] = torch.randint(high=2, size=(mutable.n_candidates,)).view(-1).bool()
  23. else:
  24. perm = torch.randperm(mutable.n_candidates)
  25. mask = [i in perm[:mutable.n_chosen] for i in range(mutable.n_candidates)]
  26. result[mutable.key] = torch.tensor(mask, dtype=torch.bool) # pylint: disable=not-callable
  27. return result
  28. def sample_final(self):
  29. """
  30. Same as :meth:`sample_search`.
  31. """
  32. return self.sample_search()

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