Co-authored-by: msjz11<liuchengju5@huawei.com> # message auto-generated for no-merge-commit merge: !37663 merge mfu2 into master feat(profiler): add fused op flops formulas Created-by: mjsz11 Commit-by: msjz11 Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [x] 需求 - [ ] 问题单 - [ ] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 1. 在 profiler FLOPs 公式注册中补充融合算子默认 FLOPs 计算规则,新增支持 `npu_all_gather_base_mm`、`npu_transpose_batchmatmul`、`npu_grouped_matmul`、`npu_quant_matmul_gelu`、`npu_grouped_matmul_swiglu_quant_v2`、`npu_alltoallv_gmm`、`npu_gmm_alltoallv`、`npu_block_sparse_attention`。 2. 修正 `npu_fusion_attention` / `npu_fused_infer_attention_score` 的 Attention FLOPs 口径,按 `QK^T + P @ V` 统计,使用 `q_dim + value_dim`,不再误用 `key_dim`。 3. 统一只统计主 GEMM 或 Attention 矩阵乘 FLOPs,不统计通信、transpose/permute、bias、scale、量化/反量化、GELU/SwiGLU、softmax、dropout 等融合后处理。 4. 补充对应 UT 覆盖融合算子基础 shape、grouped matmul `group_list`、block sparse attention 有效块统计、BNSD actual lengths,以及 `value_dim != key_dim` 回归场景。 # 【资料变更】 不涉及。 # 【接口变更】 不涉及。未新增或变更客户可见 API,仅补充 profiler 内部 FLOPs 默认计算公式。 # 【功能验证】 1. 执行 `python -m py_compile torch_npu/profiler/_flops_formulas.py test/profiler/test_flops_hook.py`,通过。 2. 执行 `git diff --check`,通过。 3. 通过纯 Python 公式断言验证新增融合算子 FLOPs 计算结果,验证通过。 4. 尝试执行 `python -m pytest test/profiler/test_flops_hook.py -q`,当前本地环境缺少编译扩展 `torch_npu._C`,收集阶段报 `ModuleNotFoundError`,未进入 UT 执行。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [ ] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!37663
204 lines
8.4 KiB
Python
204 lines
8.4 KiB
Python
# Owner(s): ["oncall: profiler"]
|
|
import os
|
|
import shutil
|
|
from unittest import mock
|
|
|
|
from torch_npu._C._profiler import ProfilerActivity
|
|
from torch_npu.npu import Event
|
|
from torch_npu.profiler import supported_activities
|
|
from torch_npu.profiler._profiler_path_creator import ProfPathCreator
|
|
from torch_npu.profiler.analysis.prof_common_func._cann_package_manager import (
|
|
CannPackageManager,
|
|
)
|
|
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
|
from torch_npu.profiler.profiler_interface import (
|
|
_disable_event_record,
|
|
_enable_event_record,
|
|
_ProfInterface,
|
|
)
|
|
from torch_npu.testing.testcase import run_tests, TestCase
|
|
|
|
import torch
|
|
|
|
|
|
class TestActionController(TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
super().setUpClass()
|
|
cls.prof_dir = "./result_dir"
|
|
cls.namespace = "torch_npu.profiler.profiler_interface"
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
if os.path.exists(cls.prof_dir):
|
|
shutil.rmtree(cls.prof_dir)
|
|
|
|
def setUp(self):
|
|
self.prof_if = _ProfInterface()
|
|
ProfPathCreator().init(dir_name=self.prof_dir)
|
|
|
|
def test_init_trace(self):
|
|
self.prof_if.custom_trace_id_callback = lambda: "trace_0"
|
|
with mock.patch(self.namespace + "._init_profiler") as mock_func:
|
|
self.prof_if.init_trace()
|
|
self.assertEqual(1, mock_func.call_count)
|
|
self.assertTrue(os.path.exists(self.prof_dir))
|
|
self.assertEqual("trace_0", self.prof_if.trace_id)
|
|
|
|
def test_start_trace(self):
|
|
with (
|
|
mock.patch(
|
|
self.namespace + ".NpuProfilerConfig", return_value="config_obj"
|
|
),
|
|
mock.patch(self.namespace + "._get_syscnt_enable", return_value=True),
|
|
mock.patch(self.namespace + "._get_freq", return_value=100),
|
|
mock.patch(self.namespace + "._get_syscnt", return_value=10000),
|
|
mock.patch(self.namespace + "._get_monotonic", return_value=20000),
|
|
mock.patch(self.namespace + "._start_profiler") as mock_start,
|
|
):
|
|
self.prof_if.start_trace()
|
|
self.assertEqual(True, self.prof_if.syscnt_enable)
|
|
self.assertEqual(100, self.prof_if.freq)
|
|
self.assertEqual(10000, self.prof_if.start_cnt)
|
|
self.assertEqual(20000, self.prof_if.start_monotonic)
|
|
mock_start.assert_called_once_with("config_obj", supported_activities())
|
|
|
|
def test_stop_trace(self):
|
|
with mock.patch(self.namespace + "._stop_profiler") as mock_stop:
|
|
self.prof_if.stop_trace()
|
|
mock_stop.assert_called_once()
|
|
|
|
def test_start_and_stop_trace_with_flops_and_msprof_tx(self):
|
|
self.prof_if.with_flops = True
|
|
self.prof_if.experimental_config._msprof_tx = True
|
|
with (
|
|
mock.patch(self.namespace + "._start_profiler"),
|
|
mock.patch(self.namespace + "._stop_profiler"),
|
|
mock.patch(self.namespace + ".FlopsHookManager.install") as mock_install,
|
|
mock.patch(self.namespace + ".FlopsHookManager.uninstall") as mock_uninstall,
|
|
):
|
|
self.prof_if.start_trace()
|
|
self.prof_if.stop_trace()
|
|
mock_install.assert_called_once()
|
|
mock_uninstall.assert_called_once()
|
|
|
|
def test_start_and_stop_trace_with_flops_without_msprof_tx_skips_flops_hook(self):
|
|
self.prof_if.with_flops = True
|
|
with (
|
|
mock.patch(self.namespace + "._start_profiler"),
|
|
mock.patch(self.namespace + "._stop_profiler"),
|
|
mock.patch(self.namespace + ".FlopsHookManager.install") as mock_install,
|
|
mock.patch(self.namespace + ".FlopsHookManager.uninstall") as mock_uninstall,
|
|
):
|
|
self.prof_if.start_trace()
|
|
self.prof_if.stop_trace()
|
|
mock_install.assert_not_called()
|
|
mock_uninstall.assert_not_called()
|
|
|
|
def test_finalize_trace(self):
|
|
with (
|
|
mock.patch(self.namespace + "._init_profiler"),
|
|
mock.patch(self.namespace + "._finalize_profiler") as mock_finalize,
|
|
):
|
|
self.prof_if.metadata = {"key": "val"}
|
|
self.prof_if.init_trace()
|
|
self.prof_if.finalize_trace()
|
|
mock_finalize.assert_called_once()
|
|
self.assertTrue(self._check_profiler_info_json(self.prof_if.prof_path))
|
|
self.assertTrue(self._check_metadata_json(self.prof_if.prof_path))
|
|
|
|
def test_analyse(self):
|
|
with mock.patch(
|
|
"torch_npu.profiler.analysis._npu_profiler.NpuProfiler.analyse"
|
|
) as mock_analyse:
|
|
self.prof_if.analyse()
|
|
mock_analyse.assert_called_once()
|
|
|
|
def test_supported_activities(self):
|
|
activities = set(supported_activities())
|
|
self.assertEqual(2, len(activities))
|
|
self.assertTrue(ProfilerActivity.CPU in activities)
|
|
self.assertTrue(ProfilerActivity.NPU in activities)
|
|
|
|
def test_create_trace_id_should_return_default_when_callback_is_none(self):
|
|
self.prof_if.custom_trace_id_callback = None
|
|
trace_id = self.prof_if.create_trace_id()
|
|
self.assertIsInstance(trace_id, str)
|
|
self.assertEqual(32, len(trace_id))
|
|
|
|
def test_create_trace_id_should_return_callback_result_when_callback_is_valid(self):
|
|
self.prof_if.custom_trace_id_callback = lambda: "custom_trace_id"
|
|
trace_id = self.prof_if.create_trace_id()
|
|
self.assertEqual("custom_trace_id", trace_id)
|
|
|
|
def test_create_trace_id_should_return_default_when_callback_is_not_callable(self):
|
|
self.prof_if.custom_trace_id_callback = "not_callable"
|
|
trace_id = self.prof_if.create_trace_id()
|
|
self.assertIsInstance(trace_id, str)
|
|
self.assertEqual(32, len(trace_id))
|
|
|
|
def test_create_trace_id_should_return_default_when_callback_returns_non_string(
|
|
self,
|
|
):
|
|
self.prof_if.custom_trace_id_callback = lambda: 12345
|
|
trace_id = self.prof_if.create_trace_id()
|
|
self.assertIsInstance(trace_id, str)
|
|
self.assertEqual(32, len(trace_id))
|
|
|
|
def test_create_trace_id_should_return_default_when_callback_raises_exception(self):
|
|
def bad_callback():
|
|
raise RuntimeError("callback error")
|
|
|
|
self.prof_if.custom_trace_id_callback = bad_callback
|
|
trace_id = self.prof_if.create_trace_id()
|
|
self.assertIsInstance(trace_id, str)
|
|
self.assertEqual(32, len(trace_id))
|
|
|
|
def test_create_trace_id_should_return_default_when_callback_returns_too_long_string(
|
|
self,
|
|
):
|
|
long_str = "a" * (self.prof_if.MAX_TRACE_ID_LEN + 1)
|
|
self.prof_if.custom_trace_id_callback = lambda: long_str
|
|
trace_id = self.prof_if.create_trace_id()
|
|
self.assertIsInstance(trace_id, str)
|
|
self.assertEqual(32, len(trace_id))
|
|
|
|
def test_event_record_should_have_return_true_attr_when_enable_record(self):
|
|
_enable_event_record()
|
|
self.assertTrue(hasattr(Event.record, "origin_func"))
|
|
self.assertTrue(hasattr(Event.wait, "origin_func"))
|
|
self.assertTrue(hasattr(Event.query, "origin_func"))
|
|
self.assertTrue(hasattr(Event.elapsed_time, "origin_func"))
|
|
self.assertTrue(hasattr(Event.synchronize, "origin_func"))
|
|
_disable_event_record()
|
|
self.assertFalse(hasattr(Event.record, "origin_func"))
|
|
self.assertFalse(hasattr(Event.wait, "origin_func"))
|
|
self.assertFalse(hasattr(Event.query, "origin_func"))
|
|
self.assertFalse(hasattr(Event.elapsed_time, "origin_func"))
|
|
self.assertFalse(hasattr(Event.synchronize, "origin_func"))
|
|
|
|
def _check_profiler_info_json(self, prof_path: str) -> bool:
|
|
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
|
rank_id = torch.distributed.get_rank()
|
|
path = os.path.join(
|
|
os.path.realpath(prof_path), f"profiler_info_{rank_id}.json"
|
|
)
|
|
else:
|
|
path = os.path.join(os.path.realpath(prof_path), "profiler_info.json")
|
|
return os.path.exists(path)
|
|
|
|
def _check_metadata_json(self, prof_path: str) -> bool:
|
|
path = os.path.join(os.path.realpath(prof_path), "profiler_metadata.json")
|
|
return os.path.exists(path)
|
|
|
|
def _check_params(self):
|
|
CannPackageManager.SUPPORT_EXPORT_DB = False
|
|
self.prof_if.activities = set(supported_activities())
|
|
self.prof_if.experimental_config.export_type = Constant.Db
|
|
with self.assertExpectedRaises(RuntimeError):
|
|
self.prof_if._check_params()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_tests()
|