mindstudio-probe 1.1.1__py3-none-any.whl → 1.2.2__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.
- {mindstudio_probe-1.1.1.dist-info → mindstudio_probe-1.2.2.dist-info}/METADATA +3 -2
- mindstudio_probe-1.2.2.dist-info/RECORD +415 -0
- msprobe/CMakeLists.txt +5 -0
- msprobe/README.md +16 -21
- msprobe/config.json +1 -0
- msprobe/core/common/const.py +185 -11
- msprobe/core/common/exceptions.py +3 -1
- msprobe/core/common/file_utils.py +33 -7
- msprobe/core/common/inplace_ops.yaml +4 -0
- msprobe/core/common/utils.py +42 -14
- msprobe/core/common_config.py +6 -0
- msprobe/core/compare/acc_compare.py +139 -128
- msprobe/core/compare/check.py +31 -29
- msprobe/core/compare/compare_cli.py +17 -16
- msprobe/core/compare/highlight.py +186 -99
- msprobe/core/compare/layer_mapping/data_scope_parser.py +19 -8
- msprobe/core/compare/layer_mapping/layer_mapping.py +21 -14
- msprobe/core/compare/layer_mapping/postprocess_pass.py +4 -3
- msprobe/core/compare/merge_result/merge_result.py +381 -0
- msprobe/core/compare/merge_result/merge_result_cli.py +31 -0
- msprobe/core/compare/merge_result/utils.py +81 -0
- msprobe/core/compare/multiprocessing_compute.py +2 -2
- msprobe/core/compare/npy_compare.py +109 -147
- msprobe/core/compare/utils.py +199 -69
- msprobe/core/data_dump/data_collector.py +100 -25
- msprobe/core/data_dump/data_processor/base.py +130 -28
- msprobe/core/data_dump/data_processor/factory.py +8 -3
- msprobe/core/data_dump/data_processor/mindspore_processor.py +170 -23
- msprobe/core/data_dump/data_processor/pytorch_processor.py +175 -64
- msprobe/core/data_dump/json_writer.py +54 -8
- msprobe/core/data_dump/scope.py +19 -18
- msprobe/core/overflow_check/abnormal_scene.py +9 -5
- msprobe/core/overflow_check/checker.py +1 -1
- msprobe/core/overflow_check/utils.py +1 -1
- msprobe/docs/01.installation.md +121 -17
- msprobe/docs/02.config_introduction.md +18 -16
- msprobe/docs/03.config_examples.md +24 -0
- msprobe/docs/05.data_dump_PyTorch.md +107 -58
- msprobe/docs/06.data_dump_MindSpore.md +95 -34
- msprobe/docs/07.accuracy_checker_PyTorch.md +18 -18
- msprobe/docs/09.accuracy_checker_MindSpore.md +8 -6
- msprobe/docs/10.accuracy_compare_PyTorch.md +99 -41
- msprobe/docs/11.accuracy_compare_MindSpore.md +249 -48
- msprobe/docs/12.overflow_check_PyTorch.md +1 -1
- msprobe/docs/19.monitor.md +310 -220
- msprobe/docs/21.visualization_PyTorch.md +125 -35
- msprobe/docs/22.visualization_MindSpore.md +149 -41
- msprobe/docs/23.generate_operator_PyTorch.md +107 -0
- msprobe/docs/24.code_mapping_Mindspore.md +28 -0
- msprobe/docs/{23.tool_function_introduction.md → 25.tool_function_introduction.md} +1 -0
- msprobe/docs/26.data_dump_PyTorch_baseline.md +37 -0
- msprobe/docs/27.dump_json_instruction.md +525 -0
- msprobe/docs/28.debugger_save_instruction.md +94 -0
- msprobe/docs/28.kernel_dump_MindSpore.md +69 -0
- msprobe/docs/FAQ.md +26 -2
- msprobe/docs/accuracy_checker_MindSpore/accuracy_checker_MindSpore_baseline.md +14 -0
- msprobe/docs/data_dump_MindSpore/data_dump_MindSpore_baseline.md +22 -0
- msprobe/docs/img/merge_result.png +0 -0
- msprobe/docs/img/monitor/step_count_per_record.png +0 -0
- msprobe/docs/img/visualization/fuzzy_match_ms.png +0 -0
- msprobe/docs/img/visualization/fuzzy_match_pt.png +0 -0
- msprobe/docs/img/visualization/tensorboard_1.png +0 -0
- msprobe/docs/img/visualization/tensorboard_2.png +0 -0
- msprobe/docs/img/visualization/vis_browser_1.png +0 -0
- msprobe/docs/img/visualization/vis_browser_2.png +0 -0
- msprobe/docs/img/visualization/vis_precision_info.png +0 -0
- msprobe/docs/img/visualization/vis_search_info.png +0 -0
- msprobe/docs/img/visualization/vis_show_info.png +0 -0
- msprobe/docs/img/visualization/vis_showcase.png +0 -0
- msprobe/docs/img/visualization/vis_unmatch_info.png +0 -0
- msprobe/docs/visualization/GPTModel.png +0 -0
- msprobe/docs/visualization/ParallelMLP.png +0 -0
- msprobe/docs/visualization/layer_mapping_example.md +132 -0
- msprobe/docs/visualization/mapping.png +0 -0
- msprobe/docs/visualization/mapping1.png +0 -0
- msprobe/docs/visualization/module_name.png +0 -0
- msprobe/docs/visualization/module_name1.png +0 -0
- msprobe/docs/visualization/no_mapping.png +0 -0
- msprobe/docs/visualization/no_mapping1.png +0 -0
- msprobe/docs/visualization/no_mapping_analyze.png +0 -0
- msprobe/docs/visualization/top_layer.png +0 -0
- msprobe/mindspore/__init__.py +11 -0
- msprobe/mindspore/api_accuracy_checker/api_accuracy_checker.py +80 -28
- msprobe/mindspore/api_accuracy_checker/api_runner.py +54 -16
- msprobe/mindspore/api_accuracy_checker/cmd_parser.py +2 -1
- msprobe/mindspore/api_accuracy_checker/compute_element.py +52 -8
- msprobe/mindspore/api_accuracy_checker/data_manager.py +37 -0
- msprobe/mindspore/api_accuracy_checker/main.py +1 -0
- msprobe/mindspore/api_accuracy_checker/multi_api_accuracy_checker.py +12 -6
- msprobe/mindspore/api_accuracy_checker/multi_data_manager.py +3 -1
- msprobe/mindspore/api_accuracy_checker/torch_mindtorch_importer.py +129 -0
- msprobe/mindspore/api_accuracy_checker/type_mapping.py +24 -1
- msprobe/mindspore/api_accuracy_checker/utils.py +6 -1
- msprobe/mindspore/code_mapping/bind.py +264 -0
- msprobe/mindspore/code_mapping/cmd_parser.py +40 -0
- msprobe/mindspore/code_mapping/graph.py +49 -0
- msprobe/mindspore/code_mapping/graph_parser.py +226 -0
- msprobe/mindspore/code_mapping/main.py +24 -0
- msprobe/mindspore/code_mapping/processor.py +34 -0
- msprobe/mindspore/common/const.py +3 -1
- msprobe/mindspore/common/utils.py +68 -5
- msprobe/mindspore/compare/distributed_compare.py +0 -2
- msprobe/mindspore/compare/ms_compare.py +105 -63
- msprobe/mindspore/compare/ms_graph_compare.py +14 -5
- msprobe/mindspore/debugger/debugger_config.py +28 -2
- msprobe/mindspore/debugger/precision_debugger.py +100 -12
- msprobe/mindspore/dump/hook_cell/api_registry.py +85 -16
- msprobe/mindspore/dump/hook_cell/hook_cell.py +60 -38
- msprobe/mindspore/dump/hook_cell/primitive_hooks.py +33 -15
- msprobe/mindspore/dump/hook_cell/support_wrap_ops.yaml +11 -1
- msprobe/mindspore/dump/hook_cell/wrap_api.py +92 -1
- msprobe/mindspore/dump/jit_dump.py +7 -6
- msprobe/mindspore/dump/kernel_dump/kernel_config.py +33 -0
- msprobe/mindspore/dump/kernel_graph_dump.py +7 -0
- msprobe/mindspore/free_benchmark/api_pynative_self_check.py +13 -4
- msprobe/mindspore/free_benchmark/perturbation/bit_noise.py +2 -2
- msprobe/mindspore/grad_probe/grad_analyzer.py +24 -12
- msprobe/mindspore/grad_probe/hook.py +13 -4
- msprobe/mindspore/mindtorch/__init__.py +18 -0
- msprobe/mindspore/mindtorch/mindtorch_adaptor.py +255 -0
- msprobe/mindspore/monitor/anomaly_detect.py +404 -0
- msprobe/mindspore/monitor/distributed/__init__.py +0 -0
- msprobe/mindspore/monitor/distributed/distributed_ops.yaml +15 -0
- msprobe/mindspore/monitor/distributed/stack_blacklist.yaml +5 -0
- msprobe/mindspore/monitor/distributed/wrap_distributed.py +300 -0
- msprobe/mindspore/monitor/features.py +63 -0
- msprobe/mindspore/monitor/module_hook.py +821 -0
- msprobe/mindspore/monitor/module_spec_verifier.py +94 -0
- msprobe/mindspore/monitor/utils.py +267 -0
- msprobe/mindspore/ms_config.py +13 -3
- msprobe/mindspore/overflow_check/kernel_graph_overflow_check.py +7 -0
- msprobe/mindspore/service.py +347 -107
- msprobe/msprobe.py +24 -3
- msprobe/pytorch/__init__.py +7 -7
- msprobe/pytorch/api_accuracy_checker/common/utils.py +31 -16
- msprobe/pytorch/api_accuracy_checker/compare/algorithm.py +41 -8
- msprobe/pytorch/api_accuracy_checker/compare/api_precision_compare.py +100 -267
- msprobe/pytorch/api_accuracy_checker/compare/api_precision_standard.yaml +4 -1
- msprobe/pytorch/api_accuracy_checker/compare/compare.py +69 -68
- msprobe/pytorch/api_accuracy_checker/compare/compare_column.py +54 -0
- msprobe/pytorch/api_accuracy_checker/compare/compare_input.py +51 -0
- msprobe/pytorch/api_accuracy_checker/compare/compare_utils.py +2 -4
- msprobe/pytorch/api_accuracy_checker/generate_op_script/op_generator.py +55 -31
- msprobe/pytorch/api_accuracy_checker/precision_standard/absolute_threshold.py +106 -0
- msprobe/pytorch/api_accuracy_checker/precision_standard/accumulative_error_compare.py +107 -0
- msprobe/pytorch/api_accuracy_checker/precision_standard/base_standard.py +151 -0
- msprobe/pytorch/api_accuracy_checker/precision_standard/benchmark_compare.py +226 -0
- msprobe/pytorch/api_accuracy_checker/precision_standard/binary_consistency.py +68 -0
- msprobe/pytorch/api_accuracy_checker/precision_standard/standard_config.py +218 -0
- msprobe/pytorch/api_accuracy_checker/precision_standard/standard_register.py +104 -0
- msprobe/pytorch/api_accuracy_checker/precision_standard/thousandth_standard.py +63 -0
- msprobe/pytorch/api_accuracy_checker/precision_standard/ulp_compare.py +200 -0
- msprobe/pytorch/api_accuracy_checker/run_ut/data_generate.py +57 -1
- msprobe/pytorch/api_accuracy_checker/run_ut/multi_run_ut.py +2 -1
- msprobe/pytorch/api_accuracy_checker/run_ut/run_overflow_check.py +42 -14
- msprobe/pytorch/api_accuracy_checker/run_ut/run_ut.py +64 -19
- msprobe/pytorch/api_accuracy_checker/run_ut/run_ut_utils.py +34 -4
- msprobe/pytorch/api_accuracy_checker/tensor_transport_layer/device_dispatch.py +5 -3
- msprobe/pytorch/bench_functions/apply_adam.py +215 -0
- msprobe/pytorch/bench_functions/group_norm_silu.py +27 -0
- msprobe/pytorch/bench_functions/mish.py +21 -0
- msprobe/pytorch/bench_functions/moe_gating_top_k_softmax.py +44 -0
- msprobe/pytorch/bench_functions/npu_fusion_attention.py +42 -10
- msprobe/pytorch/bench_functions/sort_v2.py +21 -0
- msprobe/pytorch/common/parse_json.py +2 -1
- msprobe/pytorch/common/utils.py +116 -2
- msprobe/pytorch/compare/distributed_compare.py +17 -29
- msprobe/pytorch/compare/pt_compare.py +40 -20
- msprobe/pytorch/debugger/debugger_config.py +42 -17
- msprobe/pytorch/debugger/precision_debugger.py +56 -12
- msprobe/pytorch/dump/module_dump/__init__.py +0 -0
- msprobe/pytorch/dump/module_dump/module_dump.py +86 -0
- msprobe/pytorch/dump/module_dump/module_processer.py +204 -0
- msprobe/pytorch/free_benchmark/common/params.py +2 -1
- msprobe/pytorch/free_benchmark/common/utils.py +3 -0
- msprobe/pytorch/free_benchmark/compare/grad_saver.py +0 -2
- msprobe/pytorch/free_benchmark/result_handlers/base_handler.py +31 -47
- msprobe/pytorch/free_benchmark/result_handlers/preheat_handler.py +0 -4
- msprobe/pytorch/function_factory.py +7 -1
- msprobe/pytorch/hook_module/__init__.py +1 -1
- msprobe/pytorch/hook_module/hook_module.py +14 -11
- msprobe/pytorch/hook_module/register_optimizer_hook.py +59 -0
- msprobe/pytorch/hook_module/support_wrap_ops.yaml +36 -1
- msprobe/pytorch/hook_module/wrap_distributed.py +10 -8
- msprobe/pytorch/hook_module/wrap_functional.py +0 -40
- msprobe/pytorch/monitor/anomaly_analyse.py +1 -1
- msprobe/pytorch/monitor/anomaly_detect.py +98 -28
- msprobe/pytorch/monitor/csv2tb.py +164 -0
- msprobe/pytorch/monitor/distributed/wrap_distributed.py +25 -14
- msprobe/pytorch/monitor/features.py +3 -3
- msprobe/pytorch/monitor/module_hook.py +543 -318
- msprobe/pytorch/monitor/module_metric.py +27 -48
- msprobe/pytorch/monitor/module_spec_verifier.py +3 -1
- msprobe/pytorch/monitor/optimizer_collect.py +76 -56
- msprobe/pytorch/monitor/unittest/test_monitor.py +24 -9
- msprobe/pytorch/monitor/utils.py +84 -48
- msprobe/pytorch/online_dispatch/dispatch.py +8 -2
- msprobe/pytorch/parse_tool/lib/compare.py +10 -10
- msprobe/pytorch/parse_tool/lib/config.py +5 -7
- msprobe/pytorch/parse_tool/lib/file_desc.py +15 -1
- msprobe/pytorch/parse_tool/lib/interactive_cli.py +10 -10
- msprobe/pytorch/parse_tool/lib/parse_exception.py +7 -7
- msprobe/pytorch/parse_tool/lib/parse_tool.py +11 -10
- msprobe/pytorch/parse_tool/lib/utils.py +18 -19
- msprobe/pytorch/parse_tool/lib/visualization.py +9 -10
- msprobe/pytorch/pt_config.py +19 -22
- msprobe/pytorch/service.py +264 -115
- msprobe/visualization/builder/graph_builder.py +93 -10
- msprobe/visualization/builder/msprobe_adapter.py +30 -6
- msprobe/visualization/compare/graph_comparator.py +64 -14
- msprobe/visualization/compare/mode_adapter.py +1 -15
- msprobe/visualization/graph/base_node.py +15 -19
- msprobe/visualization/graph/distributed_analyzer.py +395 -0
- msprobe/visualization/graph/graph.py +9 -0
- msprobe/visualization/graph/node_op.py +4 -2
- msprobe/visualization/graph_service.py +100 -27
- msprobe/visualization/utils.py +24 -31
- mindstudio_probe-1.1.1.dist-info/RECORD +0 -341
- msprobe/pytorch/functional/module_dump.py +0 -84
- msprobe/pytorch/module_processer.py +0 -150
- {mindstudio_probe-1.1.1.dist-info → mindstudio_probe-1.2.2.dist-info}/LICENSE +0 -0
- {mindstudio_probe-1.1.1.dist-info → mindstudio_probe-1.2.2.dist-info}/WHEEL +0 -0
- {mindstudio_probe-1.1.1.dist-info → mindstudio_probe-1.2.2.dist-info}/entry_points.txt +0 -0
- {mindstudio_probe-1.1.1.dist-info → mindstudio_probe-1.2.2.dist-info}/top_level.txt +0 -0
- /msprobe/docs/{data_dump_Mindspore → data_dump_MindSpore}/dynamic_graph_quick_start_example.md +0 -0
- /msprobe/{pytorch/functional → mindspore/code_mapping}/__init__.py +0 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
# From PyTorch:
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2025 Huawei Technologies Co., Ltd
|
|
4
|
+
# Copyright (c) 2016- Facebook, Inc (Adam Paszke)
|
|
5
|
+
# Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
|
|
6
|
+
# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
|
|
7
|
+
# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
|
|
8
|
+
# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
|
|
9
|
+
# Copyright (c) 2011-2013 NYU (Clement Farabet)
|
|
10
|
+
# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
|
|
11
|
+
# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
|
|
12
|
+
# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
|
|
13
|
+
|
|
14
|
+
# From Caffe2:
|
|
15
|
+
|
|
16
|
+
# Copyright (c) 2016-present, Facebook Inc. All rights reserved.
|
|
17
|
+
|
|
18
|
+
# All contributions by Facebook:
|
|
19
|
+
# Copyright (c) 2016 Facebook Inc.
|
|
20
|
+
|
|
21
|
+
# All contributions by Google:
|
|
22
|
+
# Copyright (c) 2015 Google Inc.
|
|
23
|
+
# All rights reserved.
|
|
24
|
+
|
|
25
|
+
# All contributions by Yangqing Jia:
|
|
26
|
+
# Copyright (c) 2015 Yangqing Jia
|
|
27
|
+
# All rights reserved.
|
|
28
|
+
|
|
29
|
+
# All contributions by Kakao Brain:
|
|
30
|
+
# Copyright 2019-2020 Kakao Brain
|
|
31
|
+
|
|
32
|
+
# All contributions by Cruise LLC:
|
|
33
|
+
# Copyright (c) 2022 Cruise LLC.
|
|
34
|
+
# All rights reserved.
|
|
35
|
+
|
|
36
|
+
# All contributions by Tri Dao:
|
|
37
|
+
# Copyright (c) 2024 Tri Dao.
|
|
38
|
+
# All rights reserved.
|
|
39
|
+
|
|
40
|
+
# All contributions by Arm:
|
|
41
|
+
# Copyright (c) 2021, 2023-2024 Arm Limited and/or its affiliates
|
|
42
|
+
|
|
43
|
+
# All contributions from Caffe:
|
|
44
|
+
# Copyright(c) 2013, 2014, 2015, the respective contributors
|
|
45
|
+
# All rights reserved.
|
|
46
|
+
|
|
47
|
+
# All other contributions:
|
|
48
|
+
# Copyright(c) 2015, 2016 the respective contributors
|
|
49
|
+
# All rights reserved.
|
|
50
|
+
|
|
51
|
+
# Caffe2 uses a copyright model similar to Caffe: each contributor holds
|
|
52
|
+
# copyright over their contributions to Caffe2. The project versioning records
|
|
53
|
+
# all such contribution and copyright details. If a contributor wants to further
|
|
54
|
+
# mark their specific copyright on a particular contribution, they should
|
|
55
|
+
# indicate their copyright solely in the commit message of the change when it is
|
|
56
|
+
# committed.
|
|
57
|
+
|
|
58
|
+
# All rights reserved.
|
|
59
|
+
|
|
60
|
+
# Redistribution and use in source and binary forms, with or without
|
|
61
|
+
# modification, are permitted provided that the following conditions are met:
|
|
62
|
+
|
|
63
|
+
# 1. Redistributions of source code must retain the above copyright
|
|
64
|
+
# notice, this list of conditions and the following disclaimer.
|
|
65
|
+
|
|
66
|
+
# 2. Redistributions in binary form must reproduce the above copyright
|
|
67
|
+
# notice, this list of conditions and the following disclaimer in the
|
|
68
|
+
# documentation and/or other materials provided with the distribution.
|
|
69
|
+
|
|
70
|
+
# 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories
|
|
71
|
+
# America, IDIAP Research Institute and Huawei nor the names of its contributors
|
|
72
|
+
# may be used to endorse or promote products derived from this software without
|
|
73
|
+
# specific prior written permission.
|
|
74
|
+
|
|
75
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
76
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
77
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
78
|
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
|
79
|
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
80
|
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
81
|
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
82
|
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
83
|
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
84
|
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
85
|
+
# POSSIBILITY OF SUCH DAMAGE.
|
|
86
|
+
|
|
87
|
+
import warnings
|
|
88
|
+
|
|
89
|
+
import mindspore as ms
|
|
90
|
+
from mindspore.ops.operations import _inner_ops as inner
|
|
91
|
+
from torch.nn.modules.module import (_global_backward_pre_hooks, _global_backward_hooks,
|
|
92
|
+
_global_is_full_backward_hook, _global_forward_pre_hooks,
|
|
93
|
+
_global_forward_hooks, _global_forward_hooks_always_called)
|
|
94
|
+
from torch.utils.hooks import RemovableHandle
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _call_impl(self, *args, **kwargs):
|
|
98
|
+
forward_call = self.forward
|
|
99
|
+
if self.__ms_class__:
|
|
100
|
+
return forward_call(*args, **kwargs)
|
|
101
|
+
|
|
102
|
+
# If we don't have any hooks, we want to skip the rest of the logic in
|
|
103
|
+
# this function, and just call forward.
|
|
104
|
+
if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
|
|
105
|
+
or _global_backward_pre_hooks or _global_backward_hooks
|
|
106
|
+
or _global_forward_hooks or _global_forward_pre_hooks):
|
|
107
|
+
return forward_call(*args, **kwargs)
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
result = None
|
|
111
|
+
called_always_called_hooks = set()
|
|
112
|
+
|
|
113
|
+
if self._backward_pre_hooks or _global_backward_pre_hooks:
|
|
114
|
+
_get_backward_pre_hooks(self)
|
|
115
|
+
|
|
116
|
+
if self._backward_hooks or _global_backward_hooks:
|
|
117
|
+
_get_backward_hooks(self)
|
|
118
|
+
|
|
119
|
+
if _global_forward_pre_hooks or self._forward_pre_hooks:
|
|
120
|
+
for hook_id, hook in (
|
|
121
|
+
*_global_forward_pre_hooks.items(),
|
|
122
|
+
*self._forward_pre_hooks.items(),
|
|
123
|
+
):
|
|
124
|
+
if hook_id in self._forward_pre_hooks_with_kwargs:
|
|
125
|
+
args_kwargs_result = hook(self, args, kwargs) # type: ignore[misc]
|
|
126
|
+
if args_kwargs_result is not None:
|
|
127
|
+
if isinstance(args_kwargs_result, tuple) and len(args_kwargs_result) == 2:
|
|
128
|
+
args, kwargs = args_kwargs_result
|
|
129
|
+
else:
|
|
130
|
+
raise RuntimeError(
|
|
131
|
+
"forward pre-hook must return None or a tuple "
|
|
132
|
+
f"of (new_args, new_kwargs), but got {args_kwargs_result}."
|
|
133
|
+
)
|
|
134
|
+
else:
|
|
135
|
+
args_result = hook(self, args)
|
|
136
|
+
if args_result is not None:
|
|
137
|
+
if not isinstance(args_result, tuple):
|
|
138
|
+
args_result = (args_result,)
|
|
139
|
+
args = args_result
|
|
140
|
+
|
|
141
|
+
bw_hook = None
|
|
142
|
+
if self._backward_hooks:
|
|
143
|
+
bw_hook = inner.CellBackwardHook(self.__class__.__name__ + "(" + str(id(self)) + ")",
|
|
144
|
+
self, self._backward_hooks)
|
|
145
|
+
bw_hook.register_backward_hook()
|
|
146
|
+
args = apply_backward_hook_on_tensors(bw_hook, args)
|
|
147
|
+
|
|
148
|
+
result = forward_call(*args, **kwargs)
|
|
149
|
+
if _global_forward_hooks or self._forward_hooks:
|
|
150
|
+
for hook_id, hook in (
|
|
151
|
+
*_global_forward_hooks.items(),
|
|
152
|
+
*self._forward_hooks.items(),
|
|
153
|
+
):
|
|
154
|
+
# mark that always called hook is run
|
|
155
|
+
if hook_id in self._forward_hooks_always_called or hook_id in _global_forward_hooks_always_called:
|
|
156
|
+
called_always_called_hooks.add(hook_id)
|
|
157
|
+
|
|
158
|
+
if hook_id in self._forward_hooks_with_kwargs:
|
|
159
|
+
hook_result = hook(self, args, kwargs, result)
|
|
160
|
+
else:
|
|
161
|
+
hook_result = hook(self, args, result)
|
|
162
|
+
|
|
163
|
+
if hook_result is not None:
|
|
164
|
+
result = hook_result
|
|
165
|
+
|
|
166
|
+
if bw_hook:
|
|
167
|
+
if not isinstance(result, (ms.Tensor, tuple)):
|
|
168
|
+
warnings.warn("For backward hooks to be called,"
|
|
169
|
+
" module output should be a Tensor or a tuple of Tensors"
|
|
170
|
+
f" but received {type(result)}")
|
|
171
|
+
result = apply_backward_hook_on_tensors(bw_hook, result)
|
|
172
|
+
|
|
173
|
+
if self._backward_pre_hooks:
|
|
174
|
+
bw_pre_hook = inner.CellBackwardHook(self.__class__.__name__ + "(" + str(id(self)) + ")",
|
|
175
|
+
self, self._backward_pre_hooks)
|
|
176
|
+
bw_pre_hook.register_backward_pre_hook()
|
|
177
|
+
result = apply_backward_hook_on_tensors(bw_pre_hook, result)
|
|
178
|
+
|
|
179
|
+
return result
|
|
180
|
+
except Exception:
|
|
181
|
+
# run always called hooks if they have not already been run
|
|
182
|
+
# For now only forward hooks have the always_call option but perhaps
|
|
183
|
+
# this functionality should be added to full backward hooks as well.
|
|
184
|
+
for hook_id, hook in _global_forward_hooks.items():
|
|
185
|
+
# type: ignore[possibly-undefined]
|
|
186
|
+
if hook_id in _global_forward_hooks_always_called and hook_id not in called_always_called_hooks:
|
|
187
|
+
try:
|
|
188
|
+
hook_result = hook(self, args, result) # type: ignore[possibly-undefined]
|
|
189
|
+
if hook_result is not None:
|
|
190
|
+
result = hook_result
|
|
191
|
+
except Exception as e:
|
|
192
|
+
warnings.warn("global module forward hook with ``always_call=True`` raised an exception "
|
|
193
|
+
f"that was silenced as another error was raised in forward: {str(e)}")
|
|
194
|
+
continue
|
|
195
|
+
|
|
196
|
+
for hook_id, hook in self._forward_hooks.items():
|
|
197
|
+
# type: ignore[possibly-undefined]
|
|
198
|
+
if hook_id in self._forward_hooks_always_called and hook_id not in called_always_called_hooks:
|
|
199
|
+
try:
|
|
200
|
+
if hook_id in self._forward_hooks_with_kwargs:
|
|
201
|
+
hook_result = hook(self, args, kwargs, result) # type: ignore[possibly-undefined]
|
|
202
|
+
else:
|
|
203
|
+
hook_result = hook(self, args, result) # type: ignore[possibly-undefined]
|
|
204
|
+
if hook_result is not None:
|
|
205
|
+
result = hook_result
|
|
206
|
+
except Exception as e:
|
|
207
|
+
warnings.warn("module forward hook with ``always_call=True`` raised an exception "
|
|
208
|
+
f"that was silenced as another error was raised in forward: {str(e)}")
|
|
209
|
+
continue
|
|
210
|
+
# raise exception raised in try block
|
|
211
|
+
raise
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def register_full_backward_pre_hook(self, hook, prepend: bool = False) -> RemovableHandle:
|
|
215
|
+
handle = RemovableHandle(self._backward_pre_hooks)
|
|
216
|
+
self._backward_pre_hooks[handle.id] = hook
|
|
217
|
+
if prepend:
|
|
218
|
+
self._backward_pre_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
|
|
219
|
+
return handle
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def register_full_backward_hook(self, hook, prepend: bool = False) -> RemovableHandle:
|
|
223
|
+
if self._is_full_backward_hook is False:
|
|
224
|
+
raise RuntimeError(
|
|
225
|
+
"Cannot use both regular backward hooks and full backward hooks on a "
|
|
226
|
+
"single Module. Please use only one of them."
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
self._is_full_backward_hook = True
|
|
230
|
+
|
|
231
|
+
handle = RemovableHandle(self._backward_hooks)
|
|
232
|
+
self._backward_hooks[handle.id] = hook
|
|
233
|
+
if prepend:
|
|
234
|
+
self._backward_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined]
|
|
235
|
+
return handle
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _get_backward_pre_hooks(self):
|
|
239
|
+
self._backward_pre_hooks.update(_global_backward_pre_hooks)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _get_backward_hooks(self):
|
|
243
|
+
if (_global_is_full_backward_hook is True):
|
|
244
|
+
self._backward_hooks.update(_global_backward_hooks)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def apply_backward_hook_on_tensors(cell_backward_hook, args):
|
|
248
|
+
is_tuple = True
|
|
249
|
+
if not isinstance(args, tuple):
|
|
250
|
+
args = (args,)
|
|
251
|
+
is_tuple = False
|
|
252
|
+
hooked_args = cell_backward_hook(*args)
|
|
253
|
+
if is_tuple and len(args) == 1:
|
|
254
|
+
hooked_args = (hooked_args, )
|
|
255
|
+
return hooked_args
|
|
@@ -0,0 +1,404 @@
|
|
|
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
|
|
File without changes
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
communication.comm_func:
|
|
2
|
+
- all_reduce
|
|
3
|
+
- all_gather_into_tensor
|
|
4
|
+
- reduce
|
|
5
|
+
- reduce_scatter_tensor
|
|
6
|
+
- all_to_all_single_with_output_shape
|
|
7
|
+
- all_to_all_with_output_shape
|
|
8
|
+
- batch_isend_irecv
|
|
9
|
+
- broadcast
|
|
10
|
+
- gather_into_tensor
|
|
11
|
+
- scatter_tensor
|
|
12
|
+
- send
|
|
13
|
+
- recv
|
|
14
|
+
- isend
|
|
15
|
+
- irecv
|