mindstudio-probe 1.3.0__py3-none-any.whl → 8.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. {mindstudio_probe-1.3.0.dist-info → mindstudio_probe-8.1.1.dist-info}/METADATA +4 -2
  2. {mindstudio_probe-1.3.0.dist-info → mindstudio_probe-8.1.1.dist-info}/RECORD +204 -152
  3. msprobe/README.md +32 -1
  4. msprobe/core/__init__.py +17 -0
  5. msprobe/core/common/const.py +120 -21
  6. msprobe/core/common/exceptions.py +2 -2
  7. msprobe/core/common/file_utils.py +279 -50
  8. msprobe/core/common/framework_adapter.py +169 -0
  9. msprobe/core/common/global_lock.py +86 -0
  10. msprobe/core/common/runtime.py +25 -0
  11. msprobe/core/common/utils.py +136 -45
  12. msprobe/core/common_config.py +7 -0
  13. msprobe/core/compare/acc_compare.py +646 -428
  14. msprobe/core/compare/check.py +36 -103
  15. msprobe/core/compare/compare_cli.py +4 -0
  16. msprobe/core/compare/config.py +72 -0
  17. msprobe/core/compare/highlight.py +215 -215
  18. msprobe/core/compare/layer_mapping/layer_mapping.py +2 -0
  19. msprobe/core/compare/merge_result/merge_result.py +4 -4
  20. msprobe/core/compare/multiprocessing_compute.py +223 -110
  21. msprobe/core/compare/npy_compare.py +2 -4
  22. msprobe/core/compare/utils.py +214 -244
  23. msprobe/core/config_check/__init__.py +17 -0
  24. msprobe/{pytorch/dump/kernel_dump/kernel_config.py → core/config_check/checkers/__init__.py} +8 -16
  25. msprobe/core/config_check/checkers/base_checker.py +60 -0
  26. msprobe/core/config_check/checkers/dataset_checker.py +138 -0
  27. msprobe/core/config_check/checkers/env_args_checker.py +96 -0
  28. msprobe/core/config_check/checkers/hyperparameter_checker.py +170 -0
  29. msprobe/core/config_check/checkers/pip_checker.py +90 -0
  30. msprobe/core/config_check/checkers/random_checker.py +367 -0
  31. msprobe/core/config_check/checkers/weights_checker.py +147 -0
  32. msprobe/core/config_check/ckpt_compare/ckpt_comparator.py +74 -0
  33. msprobe/core/config_check/ckpt_compare/megatron_loader.py +302 -0
  34. msprobe/core/config_check/ckpt_compare/metrics.py +83 -0
  35. msprobe/core/config_check/ckpt_compare/name_mapping.yaml +12 -0
  36. msprobe/core/config_check/config_check_cli.py +51 -0
  37. msprobe/core/config_check/config_checker.py +100 -0
  38. msprobe/{mindspore/runtime.py → core/config_check/resource/dependency.yaml} +7 -4
  39. msprobe/core/config_check/resource/env.yaml +57 -0
  40. msprobe/core/config_check/resource/hyperparameter.yaml +21 -0
  41. msprobe/core/config_check/utils/hyperparameter_parser.py +115 -0
  42. msprobe/core/config_check/utils/utils.py +107 -0
  43. msprobe/core/data_dump/api_registry.py +67 -4
  44. msprobe/core/data_dump/data_collector.py +170 -89
  45. msprobe/core/data_dump/data_processor/base.py +72 -51
  46. msprobe/core/data_dump/data_processor/mindspore_processor.py +109 -55
  47. msprobe/core/data_dump/data_processor/pytorch_processor.py +90 -82
  48. msprobe/core/data_dump/json_writer.py +143 -27
  49. msprobe/core/debugger/precision_debugger.py +144 -0
  50. msprobe/core/grad_probe/constant.py +1 -1
  51. msprobe/core/grad_probe/grad_compare.py +1 -1
  52. msprobe/core/grad_probe/utils.py +1 -1
  53. msprobe/core/hook_manager.py +242 -0
  54. msprobe/core/monitor/anomaly_processor.py +384 -0
  55. msprobe/core/service.py +357 -0
  56. msprobe/core/single_save/__init__.py +0 -0
  57. msprobe/core/single_save/single_comparator.py +243 -0
  58. msprobe/core/single_save/single_saver.py +146 -0
  59. msprobe/docs/01.installation.md +6 -5
  60. msprobe/docs/02.config_introduction.md +79 -22
  61. msprobe/docs/03.config_examples.md +1 -0
  62. msprobe/docs/04.kernel_dump_PyTorch.md +1 -1
  63. msprobe/docs/05.data_dump_PyTorch.md +118 -49
  64. msprobe/docs/06.data_dump_MindSpore.md +167 -20
  65. msprobe/docs/07.accuracy_checker_PyTorch.md +2 -2
  66. msprobe/docs/08.accuracy_checker_online_PyTorch.md +69 -9
  67. msprobe/docs/09.accuracy_checker_MindSpore.md +18 -6
  68. msprobe/docs/10.accuracy_compare_PyTorch.md +212 -74
  69. msprobe/docs/11.accuracy_compare_MindSpore.md +87 -37
  70. msprobe/docs/12.overflow_check_PyTorch.md +2 -2
  71. msprobe/docs/13.overflow_check_MindSpore.md +2 -2
  72. msprobe/docs/14.data_parse_PyTorch.md +3 -3
  73. msprobe/docs/17.grad_probe.md +2 -1
  74. msprobe/docs/18.online_dispatch.md +2 -2
  75. msprobe/docs/19.monitor.md +90 -44
  76. msprobe/docs/21.visualization_PyTorch.md +68 -15
  77. msprobe/docs/22.visualization_MindSpore.md +71 -18
  78. msprobe/docs/25.tool_function_introduction.md +23 -22
  79. msprobe/docs/26.data_dump_PyTorch_baseline.md +14 -3
  80. msprobe/docs/27.dump_json_instruction.md +1 -1
  81. msprobe/docs/28.debugger_save_instruction.md +111 -20
  82. msprobe/docs/29.data_dump_MSAdapter.md +2 -2
  83. msprobe/docs/30.overflow_check_MSAdapter.md +2 -2
  84. msprobe/docs/31.config_check.md +95 -0
  85. msprobe/docs/32.ckpt_compare.md +69 -0
  86. msprobe/docs/33.generate_operator_MindSpore.md +181 -0
  87. msprobe/docs/34.RL_collect.md +92 -0
  88. msprobe/docs/35.nan_analyze.md +72 -0
  89. msprobe/docs/data_dump_MindSpore/data_dump_MindSpore_baseline.md +12 -1
  90. msprobe/docs/data_dump_MindSpore/dynamic_graph_quick_start_example.md +3 -1
  91. msprobe/docs/img/compare_result.png +0 -0
  92. msprobe/docs/img/save_compare_result_sample.png +0 -0
  93. msprobe/docs/img/visualization/proxy.png +0 -0
  94. msprobe/mindspore/__init__.py +1 -2
  95. msprobe/mindspore/api_accuracy_checker/api_accuracy_checker.py +150 -58
  96. msprobe/mindspore/api_accuracy_checker/api_runner.py +7 -3
  97. msprobe/mindspore/api_accuracy_checker/bench_functions/flash_attention_score.py +47 -69
  98. msprobe/mindspore/api_accuracy_checker/cmd_parser.py +4 -0
  99. msprobe/mindspore/api_accuracy_checker/compute_element.py +0 -1
  100. msprobe/mindspore/api_accuracy_checker/data_manager.py +2 -2
  101. msprobe/mindspore/api_accuracy_checker/generate_op_script/op_generator.py +460 -0
  102. msprobe/mindspore/api_accuracy_checker/generate_op_script/operator_replication.template +2081 -0
  103. msprobe/mindspore/api_accuracy_checker/multi_api_accuracy_checker.py +9 -0
  104. msprobe/mindspore/api_accuracy_checker/torch_mindtorch_importer.py +2 -1
  105. msprobe/mindspore/cell_processor.py +204 -33
  106. msprobe/mindspore/code_mapping/graph_parser.py +4 -21
  107. msprobe/mindspore/common/const.py +17 -7
  108. msprobe/mindspore/common/utils.py +128 -11
  109. msprobe/mindspore/compare/common_dir_compare.py +382 -0
  110. msprobe/mindspore/compare/distributed_compare.py +2 -26
  111. msprobe/mindspore/compare/ms_compare.py +17 -405
  112. msprobe/mindspore/compare/ms_graph_compare.py +14 -5
  113. msprobe/mindspore/compare/utils.py +37 -0
  114. msprobe/mindspore/debugger/debugger_config.py +53 -3
  115. msprobe/mindspore/debugger/precision_debugger.py +72 -91
  116. msprobe/mindspore/dump/cell_dump_process.py +877 -0
  117. msprobe/mindspore/dump/cell_dump_with_insert_gradient.py +864 -0
  118. msprobe/mindspore/dump/dump_tool_factory.py +13 -5
  119. msprobe/mindspore/dump/graph_mode_cell_dump.py +139 -0
  120. msprobe/mindspore/dump/graph_tensor_dump.py +123 -0
  121. msprobe/mindspore/dump/hook_cell/api_register.py +40 -6
  122. msprobe/mindspore/dump/hook_cell/hook_cell.py +18 -7
  123. msprobe/mindspore/dump/hook_cell/ms_hook_manager.py +88 -0
  124. msprobe/mindspore/dump/hook_cell/primitive_hooks.py +8 -2
  125. msprobe/mindspore/dump/hook_cell/support_wrap_ops.yaml +18 -0
  126. msprobe/mindspore/dump/jit_dump.py +21 -18
  127. msprobe/mindspore/dump/kernel_kbyk_dump.py +6 -3
  128. msprobe/mindspore/dym_loader/hook_dynamic_loader.cpp +110 -0
  129. msprobe/mindspore/dym_loader/hook_dynamic_loader.h +15 -15
  130. msprobe/mindspore/free_benchmark/api_pynative_self_check.py +12 -6
  131. msprobe/mindspore/free_benchmark/common/utils.py +1 -1
  132. msprobe/mindspore/grad_probe/global_context.py +7 -2
  133. msprobe/mindspore/grad_probe/grad_stat_csv.py +3 -2
  134. msprobe/mindspore/mindspore_service.py +114 -0
  135. msprobe/mindspore/monitor/common_func.py +52 -0
  136. msprobe/mindspore/monitor/data_writers.py +237 -0
  137. msprobe/mindspore/monitor/features.py +20 -7
  138. msprobe/mindspore/monitor/module_hook.py +281 -209
  139. msprobe/mindspore/monitor/optimizer_collect.py +334 -0
  140. msprobe/mindspore/monitor/utils.py +25 -5
  141. msprobe/mindspore/ms_config.py +16 -15
  142. msprobe/mindspore/task_handler_factory.py +5 -2
  143. msprobe/msprobe.py +19 -0
  144. msprobe/nan_analyze/__init__.py +14 -0
  145. msprobe/nan_analyze/analyzer.py +255 -0
  146. msprobe/nan_analyze/graph.py +189 -0
  147. msprobe/nan_analyze/utils.py +211 -0
  148. msprobe/pytorch/api_accuracy_checker/common/config.py +2 -2
  149. msprobe/pytorch/api_accuracy_checker/compare/compare.py +36 -34
  150. msprobe/pytorch/api_accuracy_checker/compare/compare_utils.py +20 -20
  151. msprobe/pytorch/api_accuracy_checker/generate_op_script/op_generator.py +4 -7
  152. msprobe/pytorch/api_accuracy_checker/generate_op_script/operator_replication.template +204 -2
  153. msprobe/pytorch/api_accuracy_checker/run_ut/multi_run_ut.py +12 -11
  154. msprobe/pytorch/api_accuracy_checker/run_ut/run_overflow_check.py +1 -0
  155. msprobe/pytorch/api_accuracy_checker/run_ut/run_ut.py +8 -5
  156. msprobe/pytorch/api_accuracy_checker/run_ut/run_ut_utils.py +2 -3
  157. msprobe/pytorch/api_accuracy_checker/tensor_transport_layer/client.py +29 -13
  158. msprobe/pytorch/api_accuracy_checker/tensor_transport_layer/device_dispatch.py +12 -2
  159. msprobe/pytorch/api_accuracy_checker/tensor_transport_layer/server.py +45 -31
  160. msprobe/pytorch/api_accuracy_checker/tensor_transport_layer/utils.py +156 -0
  161. msprobe/pytorch/attl_manager.py +65 -0
  162. msprobe/pytorch/bench_functions/npu_fusion_attention.py +27 -0
  163. msprobe/pytorch/common/utils.py +26 -14
  164. msprobe/pytorch/compare/distributed_compare.py +4 -36
  165. msprobe/pytorch/compare/pt_compare.py +13 -84
  166. msprobe/pytorch/compare/utils.py +47 -0
  167. msprobe/pytorch/debugger/debugger_config.py +34 -17
  168. msprobe/pytorch/debugger/precision_debugger.py +66 -118
  169. msprobe/pytorch/dump/module_dump/hook_wrapper.py +93 -0
  170. msprobe/pytorch/dump/module_dump/module_dump.py +11 -58
  171. msprobe/pytorch/dump/module_dump/module_processer.py +143 -113
  172. msprobe/pytorch/grad_probe/grad_stat_csv.py +3 -2
  173. msprobe/pytorch/hook_module/api_register.py +29 -5
  174. msprobe/pytorch/hook_module/hook_module.py +9 -18
  175. msprobe/pytorch/hook_module/jit_script_wrapper.py +33 -0
  176. msprobe/pytorch/hook_module/pt_hook_manager.py +68 -0
  177. msprobe/pytorch/hook_module/support_wrap_ops.yaml +22 -1
  178. msprobe/pytorch/hook_module/utils.py +28 -2
  179. msprobe/pytorch/monitor/csv2tb.py +6 -2
  180. msprobe/pytorch/monitor/data_writers.py +259 -0
  181. msprobe/pytorch/monitor/module_hook.py +227 -158
  182. msprobe/pytorch/monitor/module_metric.py +14 -0
  183. msprobe/pytorch/monitor/optimizer_collect.py +242 -270
  184. msprobe/pytorch/monitor/utils.py +16 -3
  185. msprobe/pytorch/online_dispatch/dispatch.py +4 -2
  186. msprobe/pytorch/online_dispatch/dump_compare.py +5 -2
  187. msprobe/pytorch/parse_tool/lib/utils.py +3 -3
  188. msprobe/pytorch/pt_config.py +8 -7
  189. msprobe/pytorch/pytorch_service.py +73 -0
  190. msprobe/visualization/builder/graph_builder.py +33 -13
  191. msprobe/visualization/builder/msprobe_adapter.py +24 -11
  192. msprobe/visualization/compare/graph_comparator.py +53 -45
  193. msprobe/visualization/compare/mode_adapter.py +31 -1
  194. msprobe/visualization/graph/base_node.py +3 -3
  195. msprobe/visualization/graph/graph.py +2 -2
  196. msprobe/visualization/graph_service.py +250 -103
  197. msprobe/visualization/utils.py +27 -11
  198. msprobe/mindspore/dym_loader/hook_dynamic_loader.cc +0 -106
  199. msprobe/mindspore/monitor/anomaly_detect.py +0 -404
  200. msprobe/mindspore/monitor/module_spec_verifier.py +0 -94
  201. msprobe/mindspore/service.py +0 -549
  202. msprobe/pytorch/monitor/anomaly_analyse.py +0 -201
  203. msprobe/pytorch/monitor/anomaly_detect.py +0 -410
  204. msprobe/pytorch/monitor/module_spec_verifier.py +0 -95
  205. msprobe/pytorch/monitor/unittest/test_monitor.py +0 -160
  206. msprobe/pytorch/service.py +0 -473
  207. {mindstudio_probe-1.3.0.dist-info → mindstudio_probe-8.1.1.dist-info}/LICENSE +0 -0
  208. {mindstudio_probe-1.3.0.dist-info → mindstudio_probe-8.1.1.dist-info}/WHEEL +0 -0
  209. {mindstudio_probe-1.3.0.dist-info → mindstudio_probe-8.1.1.dist-info}/entry_points.txt +0 -0
  210. {mindstudio_probe-1.3.0.dist-info → mindstudio_probe-8.1.1.dist-info}/top_level.txt +0 -0
  211. /msprobe/{mindspore → core}/compare/ms_to_pt_api.yaml +0 -0
  212. /msprobe/{mindspore/dump → core}/kernel_dump/kernel_config.py +0 -0
  213. /msprobe/{pytorch/monitor/unittest → core/monitor}/__init__.py +0 -0
@@ -1,404 +0,0 @@
1
- # Copyright (c) 2024-2025, Huawei Technologies Co., Ltd.
2
- # All rights reserved.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- import itertools
17
- import os
18
- import sys
19
- import statistics as st
20
- from abc import ABC
21
- from dataclasses import dataclass, field
22
- from typing import List
23
- from collections import defaultdict
24
-
25
- import pandas as pd
26
-
27
- from mindspore import ops
28
- from mindspore import _no_grad
29
- from msprobe.core.common.log import logger
30
- from msprobe.core.common.file_utils import change_mode, create_directory, write_df_to_csv
31
- from msprobe.core.common.const import FileCheckConst, MonitorConst
32
-
33
-
34
- class ScanRule(ABC):
35
- name = "ScanRule"
36
-
37
- def apply(self, history, cur):
38
- raise NotImplementedError("abstract method apply is not implemented")
39
-
40
-
41
- class AnomalyTurbulence(ScanRule):
42
- name = "AnomalyTurbulence"
43
-
44
- def __init__(self, threshold) -> None:
45
- self.threshold = threshold
46
-
47
- def apply(self, history, cur):
48
- baseline = st.mean(history) if isinstance(history, list) else history
49
-
50
- up_bound = baseline + baseline * self.threshold
51
- if baseline > 0:
52
- return cur > up_bound
53
- else:
54
- return cur < up_bound
55
-
56
-
57
- class AnomalyScanner:
58
-
59
- @staticmethod
60
- def load_rules(specs: List[dict]):
61
- """
62
- specs: [{"rule_name": "AnomalyTurbulence", "args": {"threshold": 0.5}}]
63
- """
64
- if specs is None:
65
- return []
66
- alert_rules = []
67
- for spec in specs:
68
- # 使用get方法获取键值,如果键不存在则返回None
69
- rule_cls_name = spec.get("rule_name")
70
- rule_args = spec.get("args")
71
-
72
- # 检查必要的键是否存在
73
- if rule_cls_name is None or rule_args is None:
74
- logger.warning(f"Spec is missing required keys: {spec}")
75
- continue
76
-
77
- cur_module = sys.modules.get(__name__)
78
- try:
79
- rule_cls = getattr(cur_module, rule_cls_name)
80
- except AttributeError:
81
- logger.error(f"Rule class '{rule_cls_name}' not found in the current module.")
82
- continue
83
-
84
- try:
85
- rule_instance = rule_cls(**rule_args)
86
- alert_rules.append(rule_instance)
87
- except Exception as e:
88
- logger.error(f"Error creating instance of rule '{rule_cls_name}': {e}")
89
- continue
90
-
91
- return alert_rules
92
-
93
- @staticmethod
94
- def scan(scan_rules: List[ScanRule], history, cur):
95
- anomaly = False
96
- for rule in scan_rules:
97
- anomaly = rule.apply(history, cur)
98
- if anomaly:
99
- return anomaly, rule.name
100
- return anomaly, None
101
-
102
-
103
- class BCOLORS:
104
- HEADER = '\033[95m'
105
- OKBLUE = '\033[94m'
106
- OKCYAN = '\033[96m'
107
- OKGREEN = '\033[92m'
108
- WARNING = '\033[93m'
109
- FAIL = '\033[91m'
110
- ENDC = '\033[0m'
111
- BOLD = '\033[1m'
112
- UNDERLINE = '\033[4m'
113
-
114
-
115
- class AnomalyDataFactory(ABC):
116
- def __init__(self, rank, pp_stage, group_mates):
117
- super().__init__()
118
- self.rank = rank
119
- self.pp_stage = pp_stage
120
- self.group_mates = group_mates
121
- self.micro_step = 0
122
- self.name2callid = {}
123
-
124
- def set_call_id(self, name2callid):
125
- """根据当前GradContext信息更新call_id vpp_stage等信息
126
- """
127
- self.name2callid = name2callid
128
-
129
- def create(self, tag, message, step):
130
- """如果检查出异常, 调用当前接口生成GradAnomalyData实例
131
- tag (tuple): metric tag ('0:1.post_attention_norm.weight/rank0/pre_grad', 'min')
132
- message (str): anomaly detect message
133
- step (int): training step
134
- """
135
- if not isinstance(tag, tuple) or len(tag) != 2:
136
- raise ValueError("tag must be a tuple with length 2")
137
- tag_name = tag[0]
138
- param_name = tag_name.split('/')[0]
139
- call_id = self.name2callid.get(tag_name, -1)
140
- if MonitorConst.NAME_SEP in param_name:
141
- vpp_stage = int(param_name.split(MonitorConst.NAME_SEP)[0])
142
- else:
143
- vpp_stage = 0
144
-
145
- return GradAnomalyData(
146
- self.rank,
147
- step,
148
- self.micro_step,
149
- self.pp_stage,
150
- vpp_stage,
151
- call_id,
152
- tag_name,
153
- message,
154
- self.group_mates
155
- )
156
-
157
-
158
- class TrainStage:
159
- DEFAULT_STAGE = -1
160
- FORWARD_STAGE = 0
161
- BACKWARD_STAGE = 1
162
- OPTIMIZER_STAGE = 2
163
-
164
-
165
- FORWARD_KEY = [MonitorConst.ACTV_IN, MonitorConst.ACTV_OUT]
166
- BACKWARD_KEY = [MonitorConst.ACTVGRAD_IN, MonitorConst.ACTVGRAD_OUT,
167
- MonitorConst.PRE_GRAD, MonitorConst.POST_GRAD, MonitorConst.ACC_GRAD]
168
- OPTIMIZER_KEY = [MonitorConst.EXP_AVG, MonitorConst.EXP_AVG_SQ]
169
- TRAIN_STAGE = {
170
- **{key_: TrainStage.FORWARD_STAGE for key_ in FORWARD_KEY},
171
- **{key_: TrainStage.BACKWARD_STAGE for key_ in BACKWARD_KEY},
172
- **{key_: TrainStage.OPTIMIZER_STAGE for key_ in OPTIMIZER_KEY}
173
- }
174
-
175
-
176
- @dataclass(eq=True)
177
- class GradAnomalyData:
178
- rank: int = 0
179
- step: int = 0
180
- micro_step: int = 0
181
- pp_stage: int = 0
182
- vpp_stage: int = 0
183
- call_id: int = 0
184
- tag_name: str = field(default=None, compare=False)
185
- message: str = field(default="", compare=False)
186
- group_mates: list = field(default=None, compare=False)
187
-
188
- def __lt__(self, other):
189
- """
190
- 自定义比较函数,用于确定 GradAnomalyData 实例之间的顺序。
191
- 比较规则为:
192
- step 和 micro_step 值越小优先级越高;
193
- vpp 和 pp 在前向阶段值越小优先级越高,在非前向阶段值越大优先级越高;
194
- call_id 值越小优先级越高。
195
- """
196
- if not isinstance(other, GradAnomalyData):
197
- return NotImplemented
198
-
199
- self_train_stage = self.get_train_stage(self.tag_name)
200
- other_train_stage = self.get_train_stage(other.tag_name)
201
-
202
- def vpp_pp_comparator(anomaly):
203
- """
204
- Determine the priority rule for vpp and pp based on train stage
205
- Forward stage prefers smaller vpp and pp
206
- Other stages prefer larger vpp and pp
207
- """
208
- if self_train_stage == TrainStage.FORWARD_STAGE:
209
- return anomaly.vpp_stage, anomaly.pp_stage
210
- else:
211
- return -anomaly.vpp_stage, -anomaly.pp_stage
212
-
213
- self_cmp = [self.step, self.micro_step, self_train_stage, *vpp_pp_comparator(self), self.call_id]
214
- other_cmp = [other.step, other.micro_step, other_train_stage, *vpp_pp_comparator(other), other.call_id]
215
- return self_cmp < other_cmp
216
-
217
- def __le__(self, other):
218
- if not isinstance(other, GradAnomalyData):
219
- return NotImplemented
220
- return self == other or self < other
221
-
222
- @staticmethod
223
- def get_train_stage(tag_name):
224
- """
225
- :param tag_name: "0:fc2_0/rank0/input", "0:fc1.weight/rank0/post_grad", "0:fc2.weight/rank0/exp_avg_sq"
226
- :return: int, if forward return 0; if backward return 1; if optimizer return 2
227
- """
228
- key_ = tag_name.split("/")[-1]
229
- return TRAIN_STAGE.get(key_, TrainStage.DEFAULT_STAGE)
230
-
231
- def to_dict(self):
232
- return self.__dict__
233
-
234
- def get_key(self):
235
- # 0:1.self_attention.core_attention_flash_0/rank0/input_grad
236
- return ''.join([str(self.tag_name), "_step_", str(self.step), "_call_", str(self.call_id)])
237
-
238
-
239
- @dataclass
240
- class WriterInput:
241
- path: str
242
- ad_rules: list
243
- job_id: str
244
- anomaly_factory: AnomalyDataFactory = None
245
- ndigits: int = 6
246
- step_count_per_record: int = 1
247
-
248
-
249
- class BaseWriterWithAD:
250
- def __init__(self, writer_input: WriterInput):
251
- self.tag2scalars = {}
252
- self.ad_rules = writer_input.ad_rules
253
- self.job_id = writer_input.job_id
254
- self.anomaly_factory = writer_input.anomaly_factory
255
- self.anomalies = []
256
- self.ndigits = writer_input.ndigits
257
-
258
- def get_anomalies(self):
259
- """返回已检测到的异常列表
260
- """
261
- return self.anomalies
262
-
263
- def clear_anomalies(self):
264
- self.anomalies.clear()
265
-
266
- def add_scalar(self, tag, scalar_value, global_step=None, need_explain=False):
267
- """If an anomaly is detected, the anomaly information is recorded and added to self.anomalies.
268
- Args:
269
- tag (tuple): tuple of tag_name and tag like ('0:1.post_attention_norm.weight/rank0/pre_grad', 'min').
270
- scalar_value (float): scalar_value.
271
- global_step (int): global_step.
272
- Returns:
273
- None
274
- """
275
- detected = False
276
- if self.ad_rules:
277
- avg = self._update_tag2scalars(tag, scalar_value)
278
- detected, rule_name = self._ad(scalar_value, history=avg)
279
- if detected:
280
- exception_message = f"Rule {rule_name} reports anomaly signal in {tag} at step {global_step}."
281
- logger.info(f"{BCOLORS.WARNING}> {exception_message}{BCOLORS.ENDC}")
282
- # append to self.anomalies for dump
283
- if self.anomaly_factory:
284
- self.anomalies.append(self.anomaly_factory.create(tag, exception_message, global_step))
285
-
286
- def write_metrics(self, op_list, metric_value, step, prefix='', need_explain=False):
287
- if not metric_value:
288
- return
289
- tensors = []
290
- tags = list(itertools.product(metric_value.keys(), op_list))
291
- for op2tensor in metric_value.values():
292
- tensors.extend(op2tensor.values())
293
- with _no_grad():
294
- metric_list = ops.stack(tensors).tolist() if tensors else []
295
- for tag, metric in zip(tags, metric_list):
296
- self.add_scalar(tag, metric, step, need_explain)
297
-
298
- def _ad(self, scalar_value, history):
299
- return AnomalyScanner.scan(self.ad_rules, history, cur=scalar_value)
300
-
301
- def _update_tag2scalars(self, tag, scalar_value):
302
- """Update the average and count of a scalar value associated with a tag.
303
-
304
- This method is used to maintain a running average of scalar values for each tag.
305
-
306
-
307
- Args:
308
- tag (str): The tag identifier.
309
- scalar_value (float): The scalar value to be added.
310
-
311
- Returns:
312
- float: The average value before update.
313
- """
314
- if tag not in self.tag2scalars:
315
- self.tag2scalars[tag] = {'avg': scalar_value, 'count': 0}
316
- avg = self.tag2scalars[tag]['avg']
317
- new_avg = (avg * self.tag2scalars[tag]['count'] + scalar_value) / (self.tag2scalars[tag]['count'] + 1)
318
- self.tag2scalars[tag]['avg'] = new_avg
319
- self.tag2scalars[tag]['count'] += 1
320
- return avg
321
-
322
-
323
- class CSVWriterWithAD(BaseWriterWithAD):
324
- def __init__(self, writer_input: WriterInput):
325
- super().__init__(writer_input)
326
-
327
- path = writer_input.path
328
- self.log_dir = path
329
- create_directory(path)
330
- change_mode(path, FileCheckConst.DATA_DIR_AUTHORITY)
331
- self.context_dict = defaultdict(list)
332
- self.header = []
333
- self.step_count_per_record = writer_input.step_count_per_record
334
-
335
- def get_step_interval(self, step):
336
- count = step // self.step_count_per_record
337
- return count * self.step_count_per_record, (count + 1) * self.step_count_per_record - 1
338
-
339
- def write_csv(self, prefix, step):
340
- """
341
- Args:
342
- prefix[str]: prefix of output csv file e.g. grad_unreduced
343
- step[int]
344
- """
345
- if len(self.context_dict) == 0:
346
- return
347
-
348
- ster_start, step_end = self.get_step_interval(step)
349
- filepath = os.path.join(self.log_dir, f'{prefix}_{ster_start}-{step_end}.csv')
350
- if not os.path.exists(filepath):
351
- data_frame = pd.DataFrame(columns=self.header)
352
- write_df_to_csv(data_frame, filepath)
353
-
354
- new_data = []
355
- for name, metric_value in self.context_dict.items():
356
- if MonitorConst.NAME_SEP not in name:
357
- new_data.append([name] + [step] + metric_value)
358
- else:
359
- new_data.append(name.split(MonitorConst.NAME_SEP) + [step] + metric_value)
360
- new_data = pd.DataFrame(new_data).round(self.ndigits)
361
- write_df_to_csv(new_data, filepath, mode='a+', header=False)
362
- self.context_dict = defaultdict(list)
363
-
364
- def add_scalar(self, tag, scalar_value, global_step, need_explain=False):
365
- """
366
- ('0:1.post_attention_norm.weight/rank0/pre_grad', 'min')
367
- """
368
- super().add_scalar(tag, scalar_value, global_step, need_explain=False)
369
- split_name = tag[0].split('/')
370
- name = split_name[0]
371
- if need_explain:
372
- if 'pre' in split_name[-1]:
373
- name += '.input'
374
- if 'post' in split_name[-1]:
375
- name += '.output'
376
- self.context_dict[name].append(scalar_value)
377
-
378
- def write_metrics(self, op_list, metric_value, step, prefix='', need_explain=False):
379
- need_explain = prefix == 'other'
380
- super().write_metrics(op_list, metric_value, step, prefix='', need_explain=need_explain)
381
-
382
- # generate csv headers
383
- # set hashmap to reduce the number of headers generated.
384
- # 前向的norm用input.ops_和output.ops_,反向的用input_grad.ops_和output_grad.ops_
385
- if prefix in {"actv", "actv_grad"}:
386
- if prefix == "actv":
387
- input_and_output = [MonitorConst.ACTV_IN, MonitorConst.ACTV_OUT]
388
- else:
389
- input_and_output = [MonitorConst.ACTVGRAD_IN, MonitorConst.ACTVGRAD_OUT]
390
- ops_ = [MonitorConst.DOT.join(i) for i in itertools.product(input_and_output, op_list)]
391
- csv_header = ["module_name", "step", *ops_]
392
- else:
393
- csv_header = ["param_name", "step", *op_list]
394
-
395
- keys = list(metric_value.keys())
396
- if keys and MonitorConst.NAME_SEP in keys[0]:
397
- csv_header.insert(0, "vpp_stage")
398
-
399
- self.header = csv_header
400
- self.write_csv(prefix, step)
401
- self.header = []
402
-
403
- def close(self):
404
- pass
@@ -1,94 +0,0 @@
1
- # Copyright (c) 2024-2025, Huawei Technologies Co., Ltd.
2
- # All rights reserved.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- import re
17
- import abc
18
- from mindspore import Tensor
19
-
20
- from msprobe.core.common.log import logger
21
-
22
-
23
- # 用于存储所有validator实现类的注册表
24
- config_validator_registry = {}
25
-
26
-
27
- def register_config_validator(cls):
28
- """装饰器 用于注册ConfigValidator的实现类"""
29
- config_validator_registry[cls.__name__] = cls
30
- return cls
31
-
32
-
33
- class ConfigValidator(metaclass=abc.ABCMeta):
34
- @abc.abstractmethod
35
- def check_pattern_match(self, config_spec: str):
36
- pass
37
-
38
- @abc.abstractmethod
39
- def validate(self, actual_data, module_name: str, data_type: str, pattern_match):
40
- pass
41
-
42
-
43
- @register_config_validator
44
- class TensorValidator(ConfigValidator):
45
- def check_pattern_match(self, config_spec: str):
46
- pattern = re.compile(r"tensor")
47
- return pattern.match(config_spec)
48
-
49
- def validate(self, actual_data, module_name: str, data_type: str, pattern_match):
50
- if not isinstance(actual_data, Tensor):
51
- raise ValueError(
52
- f"Format of {module_name} {data_type} does not match the required format 'tensor' in config.")
53
-
54
-
55
- @register_config_validator
56
- class TupleValidator(ConfigValidator):
57
- def check_pattern_match(self, config_spec: str):
58
- pattern = re.compile(r"tuple\[(\d+)\]:?(\d+)?")
59
- return pattern.match(config_spec)
60
-
61
- def validate(self, actual_data, module_name: str, data_type: str, pattern_match):
62
- length, index = pattern_match.groups()
63
- if index is None:
64
- index = 0
65
- length, index = int(length), int(index)
66
-
67
- if not (0 <= index < length):
68
- raise ValueError(
69
- f"Format of {module_name} {data_type} in config.json does not match the required format 'tuple[x]:y'."
70
- f"y must be greater than or equal to 0 and less than x.")
71
- if not isinstance(actual_data, tuple):
72
- raise ValueError(
73
- f"Type of {module_name} {data_type} does not match spec of config.json, should be tuple, please check.")
74
- if len(actual_data) != length:
75
- raise ValueError(
76
- f"Length of {module_name} {data_type} does not match spec of config.json, should be {length}, "
77
- f"actual is {len(actual_data)} please check.")
78
- return index
79
-
80
-
81
- def validate_config_spec(config_spec: str, actual_data, module_name: str, data_type: str):
82
- focused_col = None
83
- for _, validator_cls in config_validator_registry.items():
84
- config_validator = validator_cls()
85
- pattern_match = config_validator.check_pattern_match(config_spec)
86
- if pattern_match:
87
- try:
88
- focused_col = config_validator.validate(actual_data, module_name, data_type, pattern_match)
89
- except ValueError as e:
90
- logger.warning(f"config spec validate failed: {str(e)}")
91
- return focused_col
92
- logger.warning(f"config spec in {module_name} {data_type} not supported, "
93
- f"expected spec:'tuple\[(\d+)\]:(\d+)' or 'tensor', actual spec: {config_spec}.")
94
- return focused_col