Merged
feat(pro): report tensor shape via aclprof range in the JIT launcher #6221
feat(pro): report tensor shape via aclprof range in the JIT launcher #6221
Merged
gravel1997Add on Sep 12
Total: 2 files changed+329-4
@@ -111,6 +111,8 @@ class ParamSpec:
111 dtype: DataType | None # element dtype; None for tiling struct params111 dtype: DataType | None # element dtype; None for tiling struct params
112 # Tensor dims: positive int = static, str = named dynamic var, -1 = unnamed dynamic; None for ptr/scalar.112 # Tensor dims: positive int = static, str = named dynamic var, -1 = unnamed dynamic; None for ptr/scalar.
113 shape: list[int | str] | None113 shape: list[int | str] | None
114+ # Data direction of tensor params: "in" (read-only) or "out" (kernel stores into it).
115+ direction: str | None = None
114 116 
115 117 
116@dataclasses.dataclass118@dataclasses.dataclass
@@ -455,15 +457,42 @@ def _get_kernel_ir_function(prog):
455 )457 )
456 458 
457 459 
458-def _extract_param_specs(prog) -> list[ParamSpec]:460+def _infer_store_targets_ast(program_source_ast) -> set:
461+ """Names of tensor params passed to ``pl.store`` in the kernel source AST.
462+ 
463+ Walks the parsed Python AST of the kernel body; the first positional argument
464+ of every ``<name>.store(...)`` call whose base name matches a ``pl``-style
465+ attribute (``pl.store(dst, src, offset)``) is a store target.
466+ """
467+ import ast as _ast
468+ 
469+ targets: set = set()
470+ for node in _ast.walk(program_source_ast):
471+ if (
472+ isinstance(node, _ast.Call)
473+ and isinstance(node.func, _ast.Attribute)
474+ and node.func.attr == "store"
gaoxiang618

store和store_tile都要考虑

likedislike
475+ and node.args
476+ and isinstance(node.args[0], _ast.Name)
gaoxiang618

对于make_tensor场景或者赋值场景会有别名,需要在parser的时候记录一下

likedislike
477+ ):
478+ targets.add(node.args[0].id)
479+ return targets
480+ 
481+ 
482+def _extract_param_specs(prog, store_targets: set | None = None) -> list[ParamSpec]:
459 """Extract parameter descriptions from the kernel function in an ir.Program."""483 """Extract parameter descriptions from the kernel function in an ir.Program."""
460 func = _get_kernel_ir_function(prog)484 func = _get_kernel_ir_function(prog)
485+ store_targets = store_targets or set()
461 specs: list[ParamSpec] = []486 specs: list[ParamSpec] = []
462 for var in func.params:487 for var in func.params:
463 t = var.type488 t = var.type
464 if isinstance(t, TensorType):489 if isinstance(t, TensorType):
465 shape = [s.value if isinstance(s, ConstInt) else (s.name if isinstance(s, Var) else -1) for s in t.shape]490 shape = [s.value if isinstance(s, ConstInt) else (s.name if isinstance(s, Var) else -1) for s in t.shape]
466- specs.append(ParamSpec(var.name, ParamKind.TENSOR, t.dtype, shape))491+ # IR names may carry a binding suffix (source ``out`` -> ``out_0``);
492+ # match store targets by the source-level basename.
493+ base_name = var.name.rsplit("_", 1)[0] if var.name.rsplit("_", 1)[-1].isdigit() else var.name
494+ direction = "out" if base_name in store_targets or var.name in store_targets else "in"
495+ specs.append(ParamSpec(var.name, ParamKind.TENSOR, t.dtype, shape, direction))
467 elif isinstance(t, PtrType):496 elif isinstance(t, PtrType):
468 specs.append(ParamSpec(var.name, ParamKind.PTR, t.dtype, None))497 specs.append(ParamSpec(var.name, ParamKind.PTR, t.dtype, None))
469 elif isinstance(t, TupleType):498 elif isinstance(t, TupleType):
@@ -825,6 +854,130 @@ def _get_mlir_code(result):
825 return result if isinstance(result, str) else "".join(result.values())854 return result if isinstance(result, str) else "".join(result.values())
826 855 
827 856 
857+# aclDataType ids (acl_base.h) for the aclprofTensor.dataType field; keyed by str(DataType).
858+_ACL_DTYPE_MAP = {
859+ "fp32": 0,
860+ "fp16": 1,
861+ "int8": 2,
862+ "int32": 3,
863+ "uint8": 4,
864+ "int16": 6,
865+ "uint16": 7,
866+ "uint32": 8,
867+ "int64": 9,
868+ "uint64": 10,
869+ "float64": 11,
870+ "double": 11,
871+ "bool": 12,
872+ "bf16": 27,
873+ "bfloat16": 27,
874+ "fp8": 28,
875+ "hf8": 34,
876+ "fp8e5m2": 35,
877+ "fp8e4m3": 36,
878+ "fp8e8m0": 37,
879+ "fp4e2m1": 40,
880+ "fp4e1m2": 41,
881+}
882+ 
883+_ACL_FORMAT_ND = 2 # aclFormat::ACL_FORMAT_ND
884+ 
885+ 
886+def _prof_shape_token(dim, dims_in_scope: set) -> str:
887+ """C++ expression for one tensor dim inside the generated launcher.
888+ 
889+ Static dims become literals; named dynamic dims reference the matching
890+ int32_t dim parameter the launcher already receives; unknown dynamics
891+ (``-1``) degrade to 0.
892+ """
893+ if isinstance(dim, int) and dim > 0:
894+ return str(dim)
895+ if isinstance(dim, str) and dim in dims_in_scope:
896+ return f"static_cast<uint32_t>({dim})"
897+ return "0"
898+ 
899+ 
900+def _generate_prof_range_snippet(
901+ kernel_name: str,
902+ param_specs: list[ParamSpec],
903+ dims_in_scope: set,
904+) -> tuple[str, str, str]:
905+ """Generate the aclprof tensor-info range (push/pop) wrapped around the launch.
906+ 
907+ Mirrors the asc-devkit torch_library_report_tensor sample: an
908+ ``aclprofEventAttributes`` carrying ``aclprofTensorInfo`` is pushed right
909+ before the ``<<<>>>`` launch and popped right after, so msprof associates
910+ op name/type and per-tensor in/out, dtype, format and shape with the kernel.
911+ Reporting uses the ``aclprof*`` interfaces declared in ``acl/acl_prof.h``
912+ and exported by libmsprofiler (added to the link line in
913+ :func:`_compile_shared_library`); the ``ProfStr2Id`` alias in libprofapi
914+ crashes with std::bad_alloc and must not be used. Failures are ignored:
915+ profiling metadata must never break the launch.
916+ """
917+ tensors = [s for s in param_specs if s.kind == ParamKind.TENSOR]
918+ if not tensors:
919+ return "", "", ""
920+ 
921+ tensor_inits = []
922+ for spec in tensors:
923+ dims = list(spec.shape or [])
924+ shape_tokens = [_prof_shape_token(d, dims_in_scope) for d in dims]
925+ padded = shape_tokens[:8] + ["0"] * (8 - min(len(shape_tokens), 8))
926+ tensor_type = 1 if spec.direction == "out" else 0
927+ acl_dtype = _ACL_DTYPE_MAP.get(str(spec.dtype), 0)
928+ shape_str = "{" + ", ".join(padded) + "}"
929+ tensor_inits.append(
930+ f" {{{tensor_type}, {_ACL_FORMAT_ND}, {acl_dtype}, "
931+ f"{min(len(dims), 8)}, {shape_str}}},"
932+ )
933+ 
934+ op_name = f"PYPTO_{kernel_name}"
935+ # The block opens before the tensor descriptions and closes AFTER the pop:
936+ # aclprofRangePushEx hands msprof a pointer to the stack tensors/info, and the
937+ # Tx plugin may read them until the matching pop -- the locals must stay in
938+ # scope across the kernel launch (official sample keeps push/launch/pop in
939+ # one scope for the same reason). ``MsprofGetPath`` (weak, libprofapi) gates
940+ # the ~1.5us push/pop pair on an active collection session: a non-empty
941+ # profiler result path means a profiler is running; a toolkit without the
942+ # symbol links it to null and we report unconditionally, as before.
943+ return (
944+ "#include \"acl/acl_prof.h\"\n"
945+ "// Weak: a toolkit without it links to null and we report unconditionally, as before.\n"
946+ "extern \"C\" __attribute__((weak)) char *MsprofGetPath();\n",
947+ " {\n"
948+ " // Skip the push/pop pair unless a profiler is collecting; empty path means off.\n"
949+ " const char *pyptoProfPath = (MsprofGetPath != nullptr) ? MsprofGetPath() : nullptr;\n"
950+ " const bool pyptoProfOn =\n"
951+ " (MsprofGetPath == nullptr) || (pyptoProfPath != nullptr && pyptoProfPath[0] != '\\0');\n"
952+ " // Outside the guard on purpose: libmsprofiler dereferences these pointers when the\n"
953+ " // launch below is reported, so the storage has to outlive the <<<>>> line.\n"
954+ " aclprofTensor pyptoProfTensors[] = {\n"
955+ + "\n".join(tensor_inits)
956+ + "\n };\n"
957+ " aclprofTensorInfo pyptoProfInfo;\n"
958+ " aclprofEventAttributes pyptoProfAttrs;\n"
959+ " if (pyptoProfOn) {\n"
960+ " pyptoProfInfo.opNameId = aclprofStr2Id(\"" + op_name + "\");\n"
961+ " pyptoProfInfo.opTypeId = aclprofStr2Id(\"PyPTO\");\n"
962+ " pyptoProfInfo.resv = 0;\n"
963+ f" pyptoProfInfo.tensorNum = {len(tensor_inits)};\n"
964+ " pyptoProfInfo.kernelType = 0;\n"
965+ " pyptoProfInfo.blockNums = blockDim;\n"
966+ " pyptoProfInfo.stream = stream;\n"
967+ " pyptoProfInfo.tensors = pyptoProfTensors;\n"
968+ " pyptoProfAttrs.version = 1;\n"
969+ " pyptoProfAttrs.size = sizeof(pyptoProfAttrs.message);\n"
970+ " pyptoProfAttrs.messageType = 0;\n"
971+ " pyptoProfAttrs.message.tensorInfo = &pyptoProfInfo;\n"
972+ " (void)aclprofRangePushEx(&pyptoProfAttrs);\n"
973+ " }\n",
974+ " if (pyptoProfOn) {\n"
975+ " (void)aclprofRangePop();\n"
976+ " }\n"
977+ " }\n",
978+ )
979+ 
980+ 
828def _generate_caller_cpp(981def _generate_caller_cpp(
829 kernel_params: list[tuple[str, str, bool]],982 kernel_params: list[tuple[str, str, bool]],
830 kernel_cpp_name: str,983 kernel_cpp_name: str,
@@ -834,6 +987,7 @@ def _generate_caller_cpp(
834 global_entry: str = "",987 global_entry: str = "",
835 *,988 *,
836 target: KernelTarget,989 target: KernelTarget,
990+ prof_param_specs: list[ParamSpec] | None = None,
837) -> str:991) -> str:
838 """Generate extern "C" wrapper that calls the __global__ kernel.992 """Generate extern "C" wrapper that calls the __global__ kernel.
839 993 
@@ -846,6 +1000,9 @@ def _generate_caller_cpp(
846 Reserved compatibility switch from compile(); currently this wrapper1000 Reserved compatibility switch from compile(); currently this wrapper
847 does not need extra caller-side code changes for print debug.1001 does not need extra caller-side code changes for print debug.
848 target: The same resolved compiler target used to build the shared library.1002 target: The same resolved compiler target used to build the shared library.
1003+ prof_param_specs:
1004+ IR param specs (with tensor direction/shape) used to emit the
1005+ aclprof tensor-info range around the launch; None disables it.
849 1006 
850 Returns:1007 Returns:
851 Generated caller.cpp content as string1008 Generated caller.cpp content as string
@@ -874,8 +1031,16 @@ def _generate_caller_cpp(
874 " rtGetC2cCtrlAddr(&ffts, &fftsLen);\n"1031 " rtGetC2cCtrlAddr(&ffts, &fftsLen);\n"
875 )1032 )
876 1033 
1034+ prof_include, prof_push, prof_pop = ("", "", "")
1035+ if prof_param_specs:
1036+ dims_in_scope = {name for _, name, _is_ptr in kernel_params}
1037+ prof_include, prof_push, prof_pop = _generate_prof_range_snippet(
1038+ kernel_name, prof_param_specs, dims_in_scope
1039+ )
1040+ 
877 return (1041 return (
878 '#include "pypto_launch.h"\n'1042 '#include "pypto_launch.h"\n'
1043+ f'{prof_include}'
879 f'{sync_include}'1044 f'{sync_include}'
880 f'#include "{kernel_cpp_name}"\n'1045 f'#include "{kernel_cpp_name}"\n'
881 f'{global_entry}'1046 f'{global_entry}'
@@ -888,7 +1053,9 @@ def _generate_caller_cpp(
888 " }\n"1053 " }\n"
889 " blockDim = static_cast<uint32_t>(launchDim);\n"1054 " blockDim = static_cast<uint32_t>(launchDim);\n"
890 f"{sync_setup}"1055 f"{sync_setup}"
1056+ f"{prof_push}"
891 f" {kernel_name}<<<blockDim, nullptr, stream>>>({call_args});\n"1057 f" {kernel_name}<<<blockDim, nullptr, stream>>>({call_args});\n"
1058+ f"{prof_pop}"
892 " return launchDim;\n"1059 " return launchDim;\n"
893 "}\n"1060 "}\n"
894 )1061 )
@@ -1037,6 +1204,7 @@ def _codegen_target_cce(
1037 arch: str,1204 arch: str,
1038 build_dir: str,1205 build_dir: str,
1039 target: ir.SectionKind,1206 target: ir.SectionKind,
1207+ store_targets: set | None = None,
1040) -> CodegenResult:1208) -> CodegenResult:
1041 """CCE codegen for one target-specific Program.1209 """CCE codegen for one target-specific Program.
1042 1210 
@@ -1058,7 +1226,7 @@ def _codegen_target_cce(
1058 # change without breaking JIT launch parameter discovery.1226 # change without breaking JIT launch parameter discovery.
1059 kernel_func = _get_kernel_ir_function(prog)1227 kernel_func = _get_kernel_ir_function(prog)
1060 kernel_name = kernel_func.name1228 kernel_name = kernel_func.name
1061- param_specs = _extract_param_specs(prog)1229+ param_specs = _extract_param_specs(prog, store_targets)
1062 entry_params = _entry_params_from_param_specs(param_specs)1230 entry_params = _entry_params_from_param_specs(param_specs)
1063 has_ffts = "set_ffts_base_addr" in cpp_code1231 has_ffts = "set_ffts_base_addr" in cpp_code
1064 has_cross_sync = has_ffts or "set_intra_block" in cpp_code1232 has_cross_sync = has_ffts or "set_intra_block" in cpp_code
@@ -1198,9 +1366,12 @@ def _parse_and_codegen_targets(
1198 for target in target_list:1366 for target in target_list:
1199 programs[target] = sanitizer_pass(programs[target])1367 programs[target] = sanitizer_pass(programs[target])
1200 1368 
1369+ store_targets = _infer_store_targets_ast(kernel_def.func_def)
1201 results = {1370 results = {
1202 target: (1371 target: (
1203- _codegen_target_cce(programs.get(target), arch, build_dir, target=target)1372+ _codegen_target_cce(
1373+ programs.get(target), arch, build_dir, target=target, store_targets=store_targets
1374+ )
1204 if matched.get(target)1375 if matched.get(target)
1205 else None1376 else None
1206 )1377 )
@@ -1307,6 +1478,12 @@ def _compile_shared_library(
1307 if not ascend_home_path:1478 if not ascend_home_path:
1308 raise RuntimeError("ASCEND_HOME_PATH is not set")1479 raise RuntimeError("ASCEND_HOME_PATH is not set")
1309 link_args = _runtime_link_args(ascend_home_path)1480 link_args = _runtime_link_args(ascend_home_path)
1481+ # The generated caller references the aclprof* tensor-info range interfaces
1482+ # (aclprofStr2Id / aclprofRangePushEx / aclprofRangePop, declared in
1483+ # acl/acl_prof.h); they are exported by libmsprofiler.so in the runtime lib
1484+ # dir, so make sure it is on the link line.
1485+ if "-lmsprofiler" not in link_args:
1486+ link_args = link_args + ["-lmsprofiler"]
1310 1487 
1311 resolved_enable_print_debug = generated.needs_print_debug1488 resolved_enable_print_debug = generated.needs_print_debug
1312 flags = _build_bisheng_flags(1489 flags = _build_bisheng_flags(
@@ -1414,6 +1591,7 @@ def _build_jit_so(
1414 enable_print_debug=resolved_print_debug,1591 enable_print_debug=resolved_print_debug,
1415 global_entry=global_entry,1592 global_entry=global_entry,
1416 target=target,1593 target=target,
1594+ prof_param_specs=cg.param_specs,
1417 )1595 )
1418 _atomic_write_text(Path(paths.final_kernel), caller_content)1596 _atomic_write_text(Path(paths.final_kernel), caller_content)
1419 1597 
@@ -0,0 +1,147 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+"""The aclprof tensor-info range embedded in the generated launcher.
13+ 
14+``_generate_prof_range_snippet`` turns IR param specs into an ``aclprofTensor[]``
15+initializer pushed around the ``<<<>>>`` launch, so msprof can attach shape/dtype/
16+format per tensor to the kernel row (Tx channel -- independent of the mspf node
17+chain). These tests check the generated snippet text directly: tensor direction
18+comes from the store-target AST inference, static dims become literals, named
19+dynamic dims reference the launcher's dim parameters, and unknown dynamics
20+degrade to 0.
21+ 
22+One pipeline test drives ``_parse_and_codegen_targets`` into
23+``_generate_caller_cpp`` end-to-end, checking the include, the registered op
24+name, the push/pop placement around the launch line and both tensor directions
25+on the generated caller source.
26+"""
27+ 
28+import ast
29+ 
30+import pypto_pro.language as pl
31+from pypto_pro.runtime.jit import (
32+ ParamKind,
33+ ParamSpec,
34+ _generate_caller_cpp,
35+ _generate_prof_range_snippet,
36+ _infer_store_targets_ast,
37+ _parse_and_codegen_targets,
38+)
39+ 
40+ 
41+def _snippet(kernel_name, specs, dims):
42+ return _generate_prof_range_snippet(kernel_name, specs, dims)
43+ 
44+ 
45+def _spec(name, shape, dtype_str, direction):
46+ return ParamSpec(name, ParamKind.TENSOR, dtype_str, shape, direction)
47+ 
48+ 
49+def test_store_targets_from_ast():
50+ node = ast.parse(
51+ "def k(a, b, out):\n"
52+ " pl.store(out, t, [0, 0])\n"
53+ " y = other.store2(out)\n"
54+ " pl.store(out2, t, [0, 0])\n"
55+ ).body[0]
56+ targets = _infer_store_targets_ast(node)
57+ assert targets == {"out", "out2"}
58+ 
59+ 
60+def test_no_store_yields_no_targets():
61+ node = ast.parse("def k(a, out):\n x = pl.load(t, a, [0, 0])\n").body[0]
62+ assert _infer_store_targets_ast(node) == set()
63+ 
64+ 
65+def test_static_shapes_are_literals():
66+ specs = [
67+ _spec("a", [64, 64], "fp32", "in"),
68+ _spec("b", [64, 64], "fp32", "in"),
69+ _spec("out", [64, 64], "fp32", "out"),
70+ ]
71+ _inc, push, pop = _snippet("k", specs, set())
72+ assert '#include "acl/acl_prof.h"' in _inc
73+ assert "{0, 2, 0, 2, {64, 64, 0, 0, 0, 0, 0, 0}}," in push # a: in
74+ assert "{1, 2, 0, 2, {64, 64, 0, 0, 0, 0, 0, 0}}," in push # out: out
75+ assert 'aclprofRangePushEx(&pyptoProfAttrs);' in push
76+ assert '(void)aclprofRangePop();' in pop
77+ assert "aclprofStr2Id(\"PYPTO_k\")" in push
78+ assert "pyptoProfInfo.tensorNum = 3;" in push
79+ 
80+ 
81+def test_dynamic_dims_reference_launcher_params():
82+ dims = {"a", "b", "out", "__pypto_dyn_a_0", "__pypto_dyn_a_1"}
83+ specs = [_spec("a", ["__pypto_dyn_a_0", "__pypto_dyn_a_1"], "fp32", "in")]
84+ _inc, push, _pop = _snippet("k", specs, dims)
85+ assert "{static_cast<uint32_t>(__pypto_dyn_a_0), static_cast<uint32_t>(__pypto_dyn_a_1)," in push
86+ 
87+ 
88+def test_unknown_dynamic_degrades_to_zero():
89+ specs = [_spec("a", [-1, 8], "fp16", "in")]
90+ _inc, push, _pop = _snippet("k", specs, set())
91+ assert "{0, 2, 1, 2, {0, 8, 0, 0, 0, 0, 0, 0}}," in push
92+ 
93+ 
94+def test_dtype_mapping():
95+ specs = [
96+ _spec("a", [4], "fp16", "in"),
97+ _spec("b", [4], "bf16", "in"),
98+ _spec("c", [4], "int32", "in"),
99+ _spec("d", [4], "nonexistent", "in"),
100+ ]
101+ _inc, push, _pop = _snippet("k", specs, set())
102+ assert "{0, 2, 1, 1," in push # fp16 -> 1
103+ assert "{0, 2, 27, 1," in push # bf16 -> 27
104+ assert "{0, 2, 3, 1," in push # int32 -> 3
105+ assert "{0, 2, 0, 1," in push # unknown dtype -> 0 fallback
106+ 
107+ 
108+def test_no_tensor_params_disables_snippet():
109+ assert _snippet("k", [], set()) == ("", "", "")
110+ 
111+ 
112+def test_caller_embeds_range_around_launch_static():
113+ """End-to-end caller generation: direction flows from the kernel AST into the snippet."""
114+ @pl.jit()
115+ def static_kernel(
116+ a: pl.Tensor[[64, 64], pl.DT_FP32],
117+ out: pl.Tensor[[64, 64], pl.DT_FP32],
118+ ):
119+ tt = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
120+ ta = pl.make_tile(tt, addr=0x0000, size=16384)
121+ tc = pl.make_tile(tt, addr=0x8000, size=16384)
122+ with pl.section_vector():
123+ pl.load(ta, a, [0, 0])
124+ pl.add(tc, ta, ta)
125+ pl.store(out, tc, [0, 0])
126+ 
127+ cube, vector = _parse_and_codegen_targets(static_kernel.to_kernel_def(), "a5", "")
128+ from pypto_pro.runtime.compile_config import get_jit_compile_config
129+ 
130+ target = get_jit_compile_config().resolve_kernel_target("a5", has_cube=cube is not None,
131+ has_vector=vector is not None)
132+ cg = cube or vector
133+ content = _generate_caller_cpp(
134+ kernel_params=cg.kernel_params,
135+ kernel_cpp_name="kernel.cpp",
136+ kernel_name=cg.kernel_name,
137+ target=target,
138+ prof_param_specs=cg.param_specs,
139+ )
140+ assert '#include "acl/acl_prof.h"' in content
141+ assert 'aclprofStr2Id("PYPTO_static_kernel")' in content
142+ push_idx = content.index("aclprofRangePushEx")
143+ launch_idx = content.index("<<<blockDim")
144+ pop_idx = content.index("aclprofRangePop")
145+ assert push_idx < launch_idx < pop_idx
146+ assert "{0, 2, 0, 2, {64, 64" in content # a: in
147+ assert "{1, 2, 0, 2, {64, 64" in content # out: out