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.1 kB

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