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.

generic_network.py 6.0 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  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. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """GenericNetwork module."""
  16. import os
  17. import click
  18. from mindinsight.wizard.base.network import BaseNetwork
  19. from mindinsight.wizard.base.templates import TemplateManager
  20. from mindinsight.wizard.base.utility import process_prompt_choice, load_dataset_maker
  21. from mindinsight.wizard.conf.constants import TEMPLATES_BASE_DIR
  22. from mindinsight.wizard.conf.constants import QUESTION_START
  23. class GenericNetwork(BaseNetwork):
  24. """BaseNetwork code generator."""
  25. name = 'GenericNetwork'
  26. supported_datasets = []
  27. supported_loss_functions = []
  28. supported_optimizers = []
  29. def __init__(self):
  30. self._dataset_maker = None
  31. template_dir = os.path.join(TEMPLATES_BASE_DIR, 'network', self.name.lower())
  32. self.network_template_manager = TemplateManager(os.path.join(template_dir, 'src'))
  33. self.common_template_manager = TemplateManager(template_dir, ['src', 'dataset'])
  34. def configure(self, settings=None):
  35. """
  36. Configure the network options.
  37. If settings is not None, then use the input settings to configure the network.
  38. Args:
  39. settings (dict): Settings to configure, format is {'options': value}.
  40. Example:
  41. {
  42. "loss": "SoftmaxCrossEntropyWithLogits",
  43. "optimizer": "Momentum",
  44. "dataset": "Cifar10"
  45. }
  46. Returns:
  47. dict, configuration value to network.
  48. """
  49. if settings:
  50. config = dict(settings)
  51. dataset_name = settings['dataset']
  52. self._dataset_maker = load_dataset_maker(dataset_name)
  53. else:
  54. loss = self.ask_loss_function()
  55. optimizer = self.ask_optimizer()
  56. dataset_name = self.ask_dataset()
  57. self._dataset_maker = load_dataset_maker(dataset_name)
  58. dataset_config = self._dataset_maker.configure()
  59. config = {'loss': loss,
  60. 'optimizer': optimizer,
  61. 'dataset': dataset_name}
  62. config.update(dataset_config)
  63. self._dataset_maker.set_network(self)
  64. self.settings.update(config)
  65. return config
  66. @staticmethod
  67. def ask_choice(prompt_head, content_list, default_value=None):
  68. """Ask user to get selected result."""
  69. if default_value is None:
  70. default_choice = 1 # start from 1 in prompt message.
  71. default_value = content_list[default_choice - 1]
  72. choice_contents = content_list[:]
  73. choice_contents.sort(reverse=False)
  74. default_choice = choice_contents.index(default_value) + 1 # start from 1 in prompt message.
  75. prompt_msg = '{}:\n{}\n'.format(
  76. prompt_head,
  77. '\n'.join(f'{idx: >4}: {choice}' for idx, choice in enumerate(choice_contents, start=1))
  78. )
  79. prompt_type = click.IntRange(min=1, max=len(choice_contents))
  80. choice = click.prompt(prompt_msg, type=prompt_type, hide_input=False, show_choices=False,
  81. confirmation_prompt=False, default=default_choice,
  82. value_proc=lambda x: process_prompt_choice(x, prompt_type))
  83. return choice_contents[choice - 1]
  84. def ask_loss_function(self):
  85. """Select loss function by user."""
  86. return self.ask_choice('%sPlease select a loss function' % QUESTION_START, self.supported_loss_functions)
  87. def ask_optimizer(self):
  88. """Select optimizer by user."""
  89. return self.ask_choice('%sPlease select an optimizer' % QUESTION_START, self.supported_optimizers)
  90. def ask_dataset(self):
  91. """Select dataset by user."""
  92. return self.ask_choice('%sPlease select a dataset' % QUESTION_START, self.supported_datasets)
  93. def generate(self, **options):
  94. """Generate network definition scripts."""
  95. context = self.get_generate_context(**options)
  96. network_source_files = self.network_template_manager.render(**context)
  97. for source_file in network_source_files:
  98. source_file.file_relative_path = os.path.join('src', source_file.file_relative_path)
  99. dataset_source_files = self._dataset_maker.generate(**options)
  100. for source_file in dataset_source_files:
  101. source_file.file_relative_path = os.path.join('src', source_file.file_relative_path)
  102. assemble_files = self._assemble(**options)
  103. source_files = network_source_files + dataset_source_files + assemble_files
  104. return source_files
  105. def get_generate_context(self, **options):
  106. """Get detailed info based on settings to network files."""
  107. context = dict(options)
  108. context.update(self.settings)
  109. return context
  110. def get_assemble_context(self, **options):
  111. """Get detailed info based on settings to assemble files."""
  112. context = dict(options)
  113. context.update(self.settings)
  114. return context
  115. def _assemble(self, **options):
  116. # generate train.py & eval.py & assemble scripts.
  117. assemble_files = []
  118. context = self.get_assemble_context(**options)
  119. common_source_files = self.common_template_manager.render(**context)
  120. assemble_files.extend(common_source_files)
  121. return assemble_files