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.

validate.py 14 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. # Copyright 2020-2021 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. """Validate the profiler parameters."""
  16. import os
  17. import sys
  18. from mindinsight.datavisual.utils.tools import to_int
  19. from mindinsight.profiler.common.exceptions.exceptions import ProfilerParamTypeErrorException, \
  20. ProfilerDeviceIdException, ProfilerOpTypeException, \
  21. ProfilerSortConditionException, ProfilerFilterConditionException, \
  22. ProfilerGroupConditionException, ProfilerParamValueErrorException
  23. from mindinsight.profiler.common.log import logger as log
  24. AICORE_TYPE_COL = ["op_type", "execution_time", "execution_frequency", "percent"]
  25. AICORE_DETAIL_COL = ["op_name", "op_type", "avg_execution_time", "subgraph", "full_op_name"]
  26. AICPU_TYPE_COL = ["op_type", "execution_time", "execution_frequency", "percent"]
  27. AICPU_DETAIL_COL = ["serial_number", "op_type", "total_time", "dispatch_time", "run_start", "run_end"]
  28. GPU_TYPE_COL = ["op_type", "type_occurrences", "total_time", "proportion", "avg_time"]
  29. GPU_ACTIVITY_COL = ["name", "type", "op_full_name", "stream_id",
  30. "block_dim", "grid_dim", "occurrences", "total_duration",
  31. "avg_duration", "max_duration", "min_duration"]
  32. GPU_DETAIL_COL = ["op_side", "op_type", "op_name", "op_full_name",
  33. "op_occurrences", "op_total_time", "op_avg_time",
  34. "proportion", "cuda_activity_cost_time", "cuda_activity_call_count"]
  35. CPU_TYPE_COL = ["op_type", "type_occurrences", "execution_frequency", "total_compute_time",
  36. "avg_time", "percent"]
  37. CPU_DETAIL_COL = ["op_side", "op_type", "op_name", "full_op_name", "op_occurrences",
  38. "op_total_time", "op_avg_time", "total_time_proportion", "subgraph"]
  39. MINDDATA_PIPELINE_COL = [
  40. 'op_id', 'op_type', 'num_workers', 'output_queue_average_size',
  41. 'output_queue_length', 'output_queue_usage_rate', 'sample_interval',
  42. 'parent_id'
  43. ]
  44. def validate_condition(search_condition):
  45. """
  46. Verify the param in search_condition is valid or not.
  47. Args:
  48. search_condition (dict): The search condition.
  49. Raises:
  50. ProfilerParamTypeErrorException: If the type of the param in search_condition is invalid.
  51. ProfilerDeviceIdException: If the device_id param in search_condition is invalid.
  52. ProfilerOpTypeException: If the op_type param in search_condition is invalid.
  53. ProfilerGroupConditionException: If the group_condition param in search_condition is invalid.
  54. ProfilerSortConditionException: If the sort_condition param in search_condition is invalid.
  55. ProfilerFilterConditionException: If the filter_condition param in search_condition is invalid.
  56. """
  57. if not isinstance(search_condition, dict):
  58. log.error("Invalid search_condition type, it should be dict.")
  59. raise ProfilerParamTypeErrorException(
  60. "Invalid search_condition type, it should be dict.")
  61. if "device_id" in search_condition:
  62. device_id = search_condition.get("device_id")
  63. if not isinstance(device_id, str):
  64. raise ProfilerDeviceIdException("Invalid device_id type, it should be str.")
  65. if "op_type" in search_condition:
  66. op_type = search_condition.get("op_type")
  67. if op_type == "aicpu_type":
  68. search_scope = AICPU_TYPE_COL
  69. elif op_type == "aicpu_detail":
  70. search_scope = AICPU_DETAIL_COL
  71. elif op_type == "aicore_type":
  72. search_scope = AICORE_TYPE_COL
  73. elif op_type == "aicore_detail":
  74. search_scope = AICORE_DETAIL_COL
  75. elif op_type == "gpu_op_type":
  76. search_scope = GPU_TYPE_COL
  77. elif op_type == "gpu_op_info":
  78. search_scope = GPU_DETAIL_COL
  79. elif op_type == "gpu_cuda_activity":
  80. search_scope = GPU_ACTIVITY_COL
  81. elif op_type == "cpu_op_type":
  82. search_scope = CPU_TYPE_COL
  83. elif op_type == "cpu_op_info":
  84. search_scope = CPU_DETAIL_COL
  85. else:
  86. raise ProfilerOpTypeException(
  87. "The op_type must in ['aicpu_type','aicpu_detail', 'aicore_type', 'aicore_detail', "
  88. "'gpu_op_type', 'gpu_op_info', 'gpu_cuda_activity', 'cpu_op_type', 'cpu_op_info']")
  89. else:
  90. raise ProfilerOpTypeException(
  91. "The op_type must in ['aicpu_type','aicpu_detail', 'aicore_type', 'aicore_detail', "
  92. "'gpu_op_type', 'gpu_op_info', 'gpu_cuda_activity', 'cpu_op_type', 'cpu_op_info']")
  93. if "group_condition" in search_condition:
  94. validate_group_condition(search_condition)
  95. if "sort_condition" in search_condition:
  96. validate_sort_condition(search_condition, search_scope)
  97. if "filter_condition" in search_condition:
  98. validate_filter_condition(search_condition)
  99. def validate_group_condition(search_condition):
  100. """
  101. Verify the group_condition in search_condition is valid or not.
  102. Args:
  103. search_condition (dict): The search condition.
  104. Raises:
  105. ProfilerGroupConditionException: If the group_condition param in search_condition is invalid.
  106. """
  107. group_condition = search_condition.get("group_condition")
  108. if not isinstance(group_condition, dict):
  109. raise ProfilerGroupConditionException("The group condition must be dict.")
  110. if "limit" in group_condition:
  111. limit = group_condition.get("limit", 10)
  112. if isinstance(limit, bool) \
  113. or not isinstance(group_condition.get("limit"), int):
  114. log.error("The limit must be int.")
  115. raise ProfilerGroupConditionException("The limit must be int.")
  116. if limit < 1 or limit > 100:
  117. raise ProfilerGroupConditionException("The limit must in [1, 100].")
  118. if "offset" in group_condition:
  119. offset = group_condition.get("offset", 0)
  120. if isinstance(offset, bool) \
  121. or not isinstance(group_condition.get("offset"), int):
  122. log.error("The offset must be int.")
  123. raise ProfilerGroupConditionException("The offset must be int.")
  124. if offset < 0:
  125. raise ProfilerGroupConditionException("The offset must ge 0.")
  126. if offset > 1000000:
  127. raise ProfilerGroupConditionException("The offset must le 1000000.")
  128. def validate_sort_condition(search_condition, search_scope):
  129. """
  130. Verify the sort_condition in search_condition is valid or not.
  131. Args:
  132. search_condition (dict): The search condition.
  133. search_scope (list): The search scope.
  134. Raises:
  135. ProfilerSortConditionException: If the sort_condition param in search_condition is invalid.
  136. """
  137. sort_condition = search_condition.get("sort_condition")
  138. if not isinstance(sort_condition, dict):
  139. raise ProfilerSortConditionException("The sort condition must be dict.")
  140. if "name" in sort_condition:
  141. sorted_name = sort_condition.get("name", "")
  142. err_msg = "The sorted_name must be in {}".format(search_scope)
  143. if not isinstance(sorted_name, str):
  144. log.error("Wrong sorted name type.")
  145. raise ProfilerSortConditionException("Wrong sorted name type.")
  146. if sorted_name not in search_scope:
  147. log.error(err_msg)
  148. raise ProfilerSortConditionException(err_msg)
  149. if "type" in sort_condition:
  150. sorted_type_param = ['ascending', 'descending']
  151. sorted_type = sort_condition.get("type")
  152. if sorted_type and sorted_type not in sorted_type_param:
  153. err_msg = "The sorted type must be ascending or descending."
  154. log.error(err_msg)
  155. raise ProfilerSortConditionException(err_msg)
  156. def validate_op_filter_condition(op_condition, value_type=str, value_type_msg='str'):
  157. """
  158. Verify the op_condition in filter_condition is valid or not.
  159. Args:
  160. op_condition (dict): The op_condition in search_condition.
  161. value_type (type): The value type. Default: str.
  162. value_type_msg (str): The value type message. Default: 'str'.
  163. Raises:
  164. ProfilerFilterConditionException: If the filter_condition param in search_condition is invalid.
  165. """
  166. filter_key = ["in", "not_in", "partial_match_str_in"]
  167. if not isinstance(op_condition, dict):
  168. raise ProfilerFilterConditionException("The filter condition value must be dict.")
  169. for key, value in op_condition.items():
  170. if not isinstance(key, str):
  171. raise ProfilerFilterConditionException("The filter key must be str")
  172. if not isinstance(value, list):
  173. raise ProfilerFilterConditionException("The filter value must be list")
  174. if key not in filter_key:
  175. raise ProfilerFilterConditionException("The filter key must in {}.".format(filter_key))
  176. for item in value:
  177. if not isinstance(item, value_type):
  178. raise ProfilerFilterConditionException(
  179. "The item in filter value must be {}.".format(value_type_msg)
  180. )
  181. def validate_filter_condition(search_condition):
  182. """
  183. Verify the filter_condition in search_condition is valid or not.
  184. Args:
  185. search_condition (dict): The search condition.
  186. Raises:
  187. ProfilerFilterConditionException: If the filter_condition param in search_condition is invalid.
  188. """
  189. filter_condition = search_condition.get("filter_condition")
  190. if not isinstance(filter_condition, dict):
  191. raise ProfilerFilterConditionException("The filter condition must be dict.")
  192. if filter_condition:
  193. if "op_type" in filter_condition:
  194. op_type_condition = filter_condition.get("op_type")
  195. validate_op_filter_condition(op_type_condition)
  196. if "op_name" in filter_condition:
  197. op_name_condition = filter_condition.get("op_name")
  198. validate_op_filter_condition(op_name_condition)
  199. def validate_and_set_job_id_env(job_id_env):
  200. """
  201. Validate the job id and set it in environment.
  202. Args:
  203. job_id_env (str): The id that to be set in environment parameter `JOB_ID`.
  204. Returns:
  205. int, the valid job id env.
  206. """
  207. if job_id_env is None:
  208. return job_id_env
  209. # get job_id_env in int type
  210. valid_id = to_int(job_id_env, 'job_id_env')
  211. # check the range of valid_id
  212. if valid_id and 255 < valid_id < sys.maxsize:
  213. os.environ['JOB_ID'] = job_id_env
  214. else:
  215. log.warning("Invalid job_id_env %s. The value should be int and between 255 and %s. Use"
  216. "default job id env instead.",
  217. job_id_env, sys.maxsize)
  218. return valid_id
  219. def validate_ui_proc(proc_name):
  220. """
  221. Validate proc name in restful request.
  222. Args:
  223. proc_name (str): The proc name to query. Acceptable value is in
  224. [`iteration_interval`, `fp_and_bp`, `fp`, `tail`].
  225. Raises:
  226. ProfilerParamValueErrorException: If the proc_name is invalid.
  227. """
  228. accept_names = ['iteration_interval', 'fp_and_bp', 'fp', 'tail']
  229. if proc_name not in accept_names:
  230. log.error("Invalid proc_name. The proc_name for restful api is in %s", accept_names)
  231. raise ProfilerParamValueErrorException(f'proc_name should be in {accept_names}.')
  232. def validate_minddata_pipeline_condition(condition):
  233. """
  234. Verify the minddata pipeline search condition is valid or not.
  235. Args:
  236. condition (dict): The minddata pipeline search condition.
  237. Raises:
  238. ProfilerParamTypeErrorException: If the type of the search condition is
  239. invalid.
  240. ProfilerDeviceIdException: If the device_id param in the search
  241. condition is invalid.
  242. ProfilerGroupConditionException: If the group_condition param in the
  243. search condition is invalid.
  244. ProfilerSortConditionException: If the sort_condition param in the
  245. search condition is invalid.
  246. ProfilerFilterConditionException: If the filter_condition param in the
  247. search condition is invalid.
  248. """
  249. if not isinstance(condition, dict):
  250. log.error("Invalid condition type, it should be dict.")
  251. raise ProfilerParamTypeErrorException(
  252. "Invalid condition type, it should be dict."
  253. )
  254. if "device_id" in condition:
  255. device_id = condition.get("device_id")
  256. if not isinstance(device_id, str):
  257. raise ProfilerDeviceIdException(
  258. "Invalid device_id type, it should be str."
  259. )
  260. if "group_condition" in condition:
  261. validate_group_condition(condition)
  262. if "sort_condition" in condition:
  263. validate_sort_condition(condition, MINDDATA_PIPELINE_COL)
  264. if "filter_condition" in condition:
  265. filter_condition = condition.get('filter_condition')
  266. if not isinstance(filter_condition, dict):
  267. raise ProfilerFilterConditionException(
  268. "The filter condition must be dict."
  269. )
  270. for key, value in filter_condition.items():
  271. if key == 'op_id':
  272. validate_op_filter_condition(
  273. value, value_type=int, value_type_msg='int'
  274. )
  275. elif key == 'op_type':
  276. validate_op_filter_condition(value)
  277. elif key == 'is_display_op_detail':
  278. if not isinstance(value, bool):
  279. raise ProfilerFilterConditionException(
  280. "The condition must be bool."
  281. )
  282. else:
  283. raise ProfilerFilterConditionException(
  284. "The key {} of filter_condition is not support.".format(key)
  285. )