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.

start.py 7.1 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. # Copyright 2019 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. """Start mindinsight service."""
  16. import os
  17. import sys
  18. import argparse
  19. from importlib import import_module
  20. import psutil
  21. from mindinsight.conf import settings
  22. from mindinsight.utils.command import BaseCommand
  23. from mindinsight.utils.hook import HookUtils
  24. from mindinsight.utils.hook import init
  25. from mindinsight.utils.exceptions import PortNotAvailableError
  26. class ConfigAction(argparse.Action):
  27. """Config action class definition."""
  28. def __call__(self, parser, namespace, values, option_string=None):
  29. """
  30. Inherited __call__ method from argparse.Action.
  31. Args:
  32. parser (ArgumentParser): Passed-in argument parser.
  33. namespace (Namespace): Namespace object to hold arguments.
  34. values (object): Argument values with type depending on argument definition.
  35. option_string (str): Optional string for specific argument name. Default: None.
  36. """
  37. config = values
  38. if not config:
  39. setattr(namespace, self.dest, config)
  40. # python:full.path.for.config.module
  41. if config.startswith('python:'):
  42. config = config[len('python:'):]
  43. try:
  44. import_module(config)
  45. except ModuleNotFoundError:
  46. parser.error(f'{option_string} {config} not exists')
  47. config = f'python:{config}'
  48. else:
  49. # file:/full/path/for/config/module.py
  50. if config.startswith('file:'):
  51. config = config[len('file:'):]
  52. if config.startswith('~'):
  53. config = os.path.realpath(os.path.expanduser(config))
  54. if not config.startswith('/'):
  55. config = os.path.realpath(os.path.join(os.getcwd(), config))
  56. if not os.path.exists(config):
  57. parser.error(f'{option_string} {config} not exists')
  58. if not os.access(config, os.R_OK):
  59. parser.error(f'{option_string} {config} not accessible')
  60. config = f'file:{config}'
  61. setattr(namespace, self.dest, config)
  62. class WorkspaceAction(argparse.Action):
  63. """Workspace action class definition."""
  64. def __call__(self, parser, namespace, values, option_string=None):
  65. """
  66. Inherited __call__ method from argparse.Action.
  67. Args:
  68. parser (ArgumentParser): Passed-in argument parser.
  69. namespace (Namespace): Namespace object to hold arguments.
  70. values (object): Argument values with type depending on argument definition.
  71. option_string (str): Optional string for specific argument name. Default: None.
  72. """
  73. workspace = os.path.realpath(values)
  74. setattr(namespace, self.dest, workspace)
  75. class PortAction(argparse.Action):
  76. """Port action class definition."""
  77. MIN_PORT = 1
  78. MAX_PORT = 65535
  79. OPEN_PORT_LIMIT = 1024
  80. def __call__(self, parser, namespace, values, option_string=None):
  81. """
  82. Inherited __call__ method from argparse.Action.
  83. Args:
  84. parser (ArgumentParser): Passed-in argument parser.
  85. namespace (Namespace): Namespace object to hold arguments.
  86. values (object): Argument values with type depending on argument definition.
  87. option_string (str): Optional string for specific argument name. Default: None.
  88. """
  89. port = values
  90. if not self.MIN_PORT <= port <= self.MAX_PORT:
  91. parser.error(f'{option_string} should be chosen from {self.MIN_PORT} to {self.MAX_PORT}')
  92. setattr(namespace, self.dest, port)
  93. class Command(BaseCommand):
  94. """
  95. Start mindinsight service.
  96. """
  97. name = 'start'
  98. description = 'startup mindinsight service'
  99. def add_arguments(self, parser):
  100. """
  101. Add arguments to parser.
  102. Args:
  103. parser (ArgumentParser): Specify parser to which arguments are added.
  104. """
  105. parser.add_argument(
  106. '--config',
  107. type=str,
  108. action=ConfigAction,
  109. help="""
  110. Specify path for user config module or file of the form python:path.to.config.module
  111. or file:/path/to/config.py
  112. """)
  113. parser.add_argument(
  114. '--workspace',
  115. type=str,
  116. action=WorkspaceAction,
  117. help="""
  118. Specify path for user workspace. Default is %s.
  119. """ % settings.WORKSPACE)
  120. parser.add_argument(
  121. '--port',
  122. type=int,
  123. action=PortAction,
  124. help="""
  125. Custom port ranging from %s to %s. Default value is %s.
  126. """ % (PortAction.MIN_PORT, PortAction.MAX_PORT, settings.PORT))
  127. for hook in HookUtils.instance().hooks():
  128. hook.register_startup_arguments(parser)
  129. def update_settings(self, args):
  130. """
  131. Update settings.
  132. Args:
  133. args (Namespace): parsed arguments to hold customized parameters.
  134. """
  135. kwargs = {}
  136. for key, value in args.__dict__.items():
  137. if value is not None:
  138. kwargs[key] = value
  139. init(**kwargs)
  140. def run(self, args):
  141. """
  142. Execute for start command.
  143. Args:
  144. args (Namespace): Parsed arguments to hold customized parameters.
  145. """
  146. for key, value in args.__dict__.items():
  147. if value is not None:
  148. self.logfile.info('%s = %s', key, value)
  149. try:
  150. self.check_port()
  151. except PortNotAvailableError as error:
  152. self.console.error(error.message)
  153. self.logfile.error(error.message)
  154. sys.exit(1)
  155. run_module = import_module('mindinsight.backend.run')
  156. run_module.start()
  157. self.logfile.info('Start mindinsight done.')
  158. def check_port(self):
  159. """Check port."""
  160. if os.getuid() != 0 and settings.PORT < PortAction.OPEN_PORT_LIMIT:
  161. raise PortNotAvailableError(
  162. f'Port {settings.PORT} below {PortAction.OPEN_PORT_LIMIT} is not allowed by current user.')
  163. connections = psutil.net_connections()
  164. for connection in connections:
  165. if connection.status != 'LISTEN':
  166. continue
  167. if connection.laddr.port == settings.PORT:
  168. raise PortNotAvailableError(f'Port {settings.PORT} is not available for MindInsight')

MindInsight为MindSpore提供了简单易用的调优调试能力。在训练过程中,可以将标量、张量、图像、计算图、模型超参、训练耗时等数据记录到文件中,通过MindInsight可视化页面进行查看及分析。