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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 = {'loss': settings['loss'],
  51. 'optimizer': settings['optimizer'],
  52. 'dataset': settings['dataset']}
  53. self.settings.update(config)
  54. return config
  55. loss = self.ask_loss_function()
  56. optimizer = self.ask_optimizer()
  57. dataset = self.ask_dataset()
  58. self._dataset_maker = load_dataset_maker(dataset)
  59. self._dataset_maker.set_network(self)
  60. dataset_config = self._dataset_maker.configure()
  61. config = {'loss': loss,
  62. 'optimizer': optimizer,
  63. 'dataset': dataset}
  64. config.update(dataset_config)
  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. return choice_contents[choice - 1]
  85. def ask_loss_function(self):
  86. """Select loss function by user."""
  87. return self.ask_choice('%sPlease select a loss function' % QUESTION_START, self.supported_loss_functions)
  88. def ask_optimizer(self):
  89. """Select optimizer by user."""
  90. return self.ask_choice('%sPlease select an optimizer' % QUESTION_START, self.supported_optimizers)
  91. def ask_dataset(self):
  92. """Select dataset by user."""
  93. return self.ask_choice('%sPlease select a dataset' % QUESTION_START, self.supported_datasets)
  94. def generate(self, **options):
  95. """Generate network definition scripts."""
  96. context = self.get_generate_context(**options)
  97. network_source_files = self.network_template_manager.render(**context)
  98. for source_file in network_source_files:
  99. source_file.file_relative_path = os.path.join('src', source_file.file_relative_path)
  100. dataset_source_files = self._dataset_maker.generate(**options)
  101. for source_file in dataset_source_files:
  102. source_file.file_relative_path = os.path.join('src', source_file.file_relative_path)
  103. assemble_files = self._assemble(**options)
  104. source_files = network_source_files + dataset_source_files + assemble_files
  105. return source_files
  106. def get_generate_context(self, **options):
  107. """Get detailed info based on settings to network files."""
  108. context = dict(options)
  109. context.update(self.settings)
  110. return context
  111. def get_assemble_context(self, **options):
  112. """Get detailed info based on settings to assemble files."""
  113. context = dict(options)
  114. context.update(self.settings)
  115. return context
  116. def _assemble(self, **options):
  117. # generate train.py & eval.py & assemble scripts.
  118. assemble_files = []
  119. context = self.get_assemble_context(**options)
  120. common_source_files = self.common_template_manager.render(**context)
  121. assemble_files.extend(common_source_files)
  122. return assemble_files