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

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