Merged
fix(pro): fix profiling for cann 9.3.0 #6677
gravel1997Add on Sep 23
fix(pro): fix profiling for cann 9.3.0 #6677
Merged
Merged fromgravel1997/pypto9.2.0intocann/pypto9.2.0
Total: 20 files changed+1497-339
| @@ -72,6 +72,14 @@ target_link_libraries(tile_fwk_interface | |||
| 72 | Threads::Threads | 72 | Threads::Threads |
| 73 | tile_fwk_platform | 73 | tile_fwk_platform |
| 74 | ) | 74 | ) |
| 75 | + | ||
| 76 | +# Profiling uses the public CANN API, without a dependency on adapter-private | ||
| 77 | +# headers. CPU-only and C++ unit-test builds keep the status provider inactive. | ||
| 78 | +if (BUILD_WITH_CANN AND NOT ENABLE_UTEST) | ||
| 79 | + find_cann_package(msprof REQUIRED) | ||
| 80 | + target_compile_definitions(tile_fwk_interface PRIVATE BUILD_WITH_CANN) | ||
| 81 | + target_link_libraries(tile_fwk_interface PRIVATE profapi) | ||
| 82 | +endif () | ||
| 75 | PTO_Fwk_AnalysisTargetHeaderFiles(TARGET tile_fwk_interface) | 83 | PTO_Fwk_AnalysisTargetHeaderFiles(TARGET tile_fwk_interface) |
| 76 | PTO_Fwk_AnalysisTargetSymbols(TARGET tile_fwk_interface) | 84 | PTO_Fwk_AnalysisTargetSymbols(TARGET tile_fwk_interface) |
| 77 | 85 | ||
| @@ -0,0 +1,51 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#include <atomic> | ||
| 12 | + | ||
| 13 | +#ifdef BUILD_WITH_CANN | ||
| 14 | +#include <cstdint> | ||
| 15 | +#include <cstring> | ||
| 16 | + | ||
| 17 | +#include "profiling/aprof_pub.h" | ||
| 18 | +#endif | ||
| 19 | + | ||
| 20 | +namespace { | ||
| 21 | + | ||
| 22 | +// Keep the state in the process-wide backend, which Python loads before JIT | ||
| 23 | +// libraries. CANN replays an active session asynchronously to late registrants, | ||
| 24 | +// so registering in a JIT library can race its first launch. | ||
| 25 | +std::atomic<bool> gProfLive{false}; | ||
| 26 | + | ||
| 27 | +#ifdef BUILD_WITH_CANN | ||
| 28 | +int32_t ProfCommand(uint32_t type, void* data, uint32_t length) | ||
| 29 | +{ | ||
| 30 | + // ProfCtrlType::PROF_CTRL_SWITCH carries MsprofCommandHandle; a zero | ||
| 31 | + // profSwitch stops collection. Ignore reporter/step-info notifications. | ||
| 32 | + if (type != PROF_CTRL_SWITCH || data == nullptr || length < sizeof(uint64_t)) { | ||
| 33 | + return 0; | ||
| 34 | + } | ||
| 35 | + uint64_t profSwitch = 0; | ||
| 36 | + std::memcpy(&profSwitch, data, sizeof(profSwitch)); | ||
| 37 | + gProfLive.store(profSwitch != 0, std::memory_order_relaxed); | ||
| 38 | + return 0; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +// Use CANN's public API: the interface library must not include adapter-private | ||
| 42 | +// headers. Register at backend load time, before profiling or JIT compilation. | ||
| 43 | +constexpr uint32_t pyptoModuleId = 0x46; | ||
| 44 | +const int32_t gProfRegistration = MsprofRegisterCallback(pyptoModuleId, &ProfCommand); | ||
| 45 | +#endif | ||
| 46 | + | ||
| 47 | +} // namespace | ||
| 48 | + | ||
| 49 | +// Native ABI used by generated launchers. libtile_fwk_interface is loaded with | ||
| 50 | +// RTLD_GLOBAL by pypto._loader, so every JIT library queries this same state. | ||
| 51 | +extern "C" bool GetPyptoProfStatus() { return gProfLive.load(std::memory_order_relaxed); } | ||
| @@ -13,38 +13,137 @@ | |||
| 13 | #include <acl/acl_prof.h> | 13 | #include <acl/acl_prof.h> |
| 14 | #include <acl/acl_rt.h> | 14 | #include <acl/acl_rt.h> |
| 15 | #include <profiling/aprof_pub.h> | 15 | #include <profiling/aprof_pub.h> |
| 16 | +#include <cstdlib> | ||
| 17 | +#include <cstring> | ||
| 16 | #include <sys/syscall.h> | 18 | #include <sys/syscall.h> |
| 17 | #include <unistd.h> | 19 | #include <unistd.h> |
| 18 | 20 | ||
| 21 | +// Process-wide collection state, registered when the PyPTO backend loads. | ||
| 22 | +// Unlike the compiler-linked ASC flag, this also covers profiling sessions | ||
| 23 | +// that start before this JIT library is compiled or loaded. | ||
| 24 | +extern "C" bool GetPyptoProfStatus() __attribute__((weak)); | ||
| 25 | + | ||
| 19 | namespace pypto { | 26 | namespace pypto { |
| 20 | 27 | ||
| 21 | -inline uint64_t BeginCaptureTensorReport(bool profiling, aclrtStream stream) | 28 | +inline bool GetProfStatus() |
| 29 | +{ | ||
| 30 | + // Offline error reproduction loads the dumped launcher without importing | ||
| 31 | + // PyPTO. Without the backend's collection state, leave profiling disabled. | ||
| 32 | + return GetPyptoProfStatus != nullptr && GetPyptoProfStatus(); | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +inline uint64_t BeginCaptureTensorReport(bool profiling) | ||
| 22 | { | 36 | { |
| 23 | if (!profiling) { | 37 | if (!profiling) { |
| 24 | return 0; | 38 | return 0; |
| 25 | } | 39 | } |
| 26 | - aclrtStreamAttrValue attr{}; | 40 | + // Report for every launch, captured or eager: the toolchain launch stub no |
| 27 | - if (aclrtGetStreamAttribute(stream, ACL_STREAM_ATTR_CACHE_OP_INFO, &attr) != ACL_SUCCESS || | 41 | + // longer reports node basics and the range (Tx) pipeline no longer persists |
| 28 | - !attr.cacheOpInfoSwitch) { | 42 | + // eager tensor data, so the exporter needs the full record set from us. |
| 29 | - return 0; | ||
| 30 | - } | ||
| 31 | return MsprofSysCycleTime(); | 43 | return MsprofSysCycleTime(); |
| 32 | } | 44 | } |
| 33 | 45 | ||
| 34 | -inline void ReportCaptureTensorInfo(const aclprofTensorInfo& info, uint64_t begin) | 46 | +// Runtime's cached op-info wire header, followed by tensorNum MsrofTensorData |
| 47 | +// records. Keep in sync with CacheTaskInfo in machine/runtime/runner/host_prof.h | ||
| 48 | +// and CANN's CacheOpInfoBasic. Use public CANN types here: JIT headers cannot | ||
| 49 | +// depend on the framework's private adapter or machine headers. | ||
| 50 | +struct ProfCacheTaskInfo { | ||
| 51 | + uint32_t taskType; | ||
| 52 | + uint32_t numBlocks; | ||
| 53 | + uint64_t nodeId; | ||
| 54 | + uint64_t opType; | ||
| 55 | + uint64_t attrId; | ||
| 56 | + uint64_t reserve; | ||
| 57 | + uint32_t opFlag; | ||
| 58 | + uint32_t tensorNum; | ||
| 59 | +}; | ||
| 60 | +static_assert(sizeof(ProfCacheTaskInfo) == 48, "Unexpected cached op-info layout"); | ||
| 61 | +static_assert(sizeof(MsrofTensorData) == 44, "Unexpected cached tensor layout"); | ||
| 62 | + | ||
| 63 | +inline MsrofTensorData MakeProfTensorData(const aclprofTensor& source) | ||
| 35 | { | 64 | { |
| 65 | + MsrofTensorData dest{}; | ||
| 66 | + dest.tensorType = source.type; | ||
| 67 | + dest.format = source.format; | ||
| 68 | + dest.dataType = source.dataType; | ||
| 69 | + for (uint32_t dim = 0; dim < source.shapeDim && dim < MSPROF_GE_TENSOR_DATA_SHAPE_LEN; ++dim) { | ||
| 70 | + dest.shape[dim] = source.shape[dim]; | ||
| 71 | + } | ||
| 72 | + return dest; | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +inline void CacheCaptureTensorInfo(const aclprofTensorInfo& info) | ||
| 76 | +{ | ||
| 77 | + // aclrtCacheLastTaskOpInfo accepts at most 64 KiB, copies the bytes, and | ||
| 78 | + // attaches them to this thread's last task. Call immediately after launch. | ||
| 79 | + constexpr size_t maxInfoSize = 64 * 1024; | ||
| 80 | + if (info.tensorNum > (maxInfoSize - sizeof(ProfCacheTaskInfo)) / sizeof(MsrofTensorData)) { | ||
| 81 | + return; | ||
| 82 | + } | ||
| 83 | + const size_t size = sizeof(ProfCacheTaskInfo) + info.tensorNum * sizeof(MsrofTensorData); | ||
| 84 | + auto* buffer = static_cast<unsigned char*>(std::malloc(size)); | ||
| 85 | + if (buffer == nullptr) { | ||
| 86 | + return; | ||
| 87 | + } | ||
| 88 | + const ProfCacheTaskInfo task{info.kernelType, info.blockNums, info.opNameId, info.opTypeId, 0, 0, 0, | ||
| 89 | + info.tensorNum}; | ||
| 90 | + std::memcpy(buffer, &task, sizeof(task)); | ||
| 91 | + for (uint32_t index = 0; index < info.tensorNum; ++index) { | ||
| 92 | + const auto tensor = MakeProfTensorData(info.tensors[index]); | ||
| 93 | + std::memcpy(buffer + sizeof(task) + index * sizeof(tensor), &tensor, sizeof(tensor)); | ||
| 94 | + } | ||
| 95 | + (void)aclrtCacheLastTaskOpInfo(buffer, size); | ||
| 96 | + std::free(buffer); | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +inline void ReportCaptureTensorInfo(const aclprofTensorInfo& info, uint64_t begin, bool capture) | ||
| 100 | +{ | ||
| 101 | + // Capture may precede collection (for example a profiler schedule's skipped | ||
| 102 | + // steps). Replay does not re-enter this launcher: Runtime must retain shapes | ||
| 103 | + // on the captured task and report them when that graph is profiled later. | ||
| 104 | + if (capture) { | ||
| 105 | + CacheCaptureTensorInfo(info); | ||
| 106 | + } | ||
| 36 | if (begin == 0) { | 107 | if (begin == 0) { |
| 37 | return; | 108 | return; |
| 38 | } | 109 | } |
| 39 | const uint64_t end = MsprofSysCycleTime(); | 110 | const uint64_t end = MsprofSysCycleTime(); |
| 40 | - const uint64_t timestamp = begin + (end - begin) / 2; | 111 | + const uint64_t timestamp = end; |
| 41 | const auto threadId = static_cast<uint32_t>(syscall(SYS_gettid)); | 112 | const auto threadId = static_cast<uint32_t>(syscall(SYS_gettid)); |
| 42 | 113 | ||
| 43 | - // During graph capture aclprofRangePop caches tensors in RuntimeOpInfo. CANN | 114 | + // The exporter anchors eager kernel rows on an aging node-basic record and |
| 44 | - // can instead select the compiler's existing kernel node, whose tensor fields | 115 | + // only then attaches the additional tensor information, as the aclnn op |
| 45 | - // are empty. Also emit node tensor information, as the eager range does. | 116 | + // framework reports both with one shared timestamp. Emit the anchor first: |
| 46 | - // A timestamp inside the launch range associates it with that kernel node; | 117 | + // newer toolkits no longer report it from the launch stub. |
| 47 | - // keep the range push/pop as well so the graph's cached metadata survives. | 118 | + MsprofCompactInfo anchor{}; |
| 119 | + anchor.level = MSPROF_REPORT_NODE_LEVEL; | ||
| 120 | + anchor.type = MSPROF_REPORT_NODE_BASIC_INFO_TYPE; | ||
| 121 | + anchor.threadId = threadId; | ||
| 122 | + anchor.timeStamp = timestamp; | ||
| 123 | + anchor.dataLen = sizeof(MsprofNodeBasicInfo); | ||
| 124 | + auto& node = anchor.data.nodeBasicInfo; | ||
| 125 | + node.opName = info.opNameId; | ||
| 126 | + node.taskType = info.kernelType; | ||
| 127 | + node.opType = info.opTypeId; | ||
| 128 | + node.blockDim = info.blockNums & 0xffffU; | ||
| 129 | + node.opFlag = 0; | ||
| 130 | + // Metadata collection must never prevent or fail a kernel launch. | ||
| 131 | + (void)MsprofReportCompactInfo(true, &anchor, sizeof(anchor)); | ||
| 132 | + | ||
| 133 | + // The launch api event (node level, launch type, itemId = opName) spans the | ||
| 134 | + // op window and is what the exporter joins the anchor and tensor records | ||
| 135 | + // against; the aclnn op framework reports it for every eager op. | ||
| 136 | + MsprofApi launchEvent{}; | ||
| 137 | + launchEvent.level = MSPROF_REPORT_NODE_LEVEL; | ||
| 138 | + launchEvent.type = MSPROF_REPORT_NODE_LAUNCH_TYPE; | ||
| 139 | + launchEvent.threadId = threadId; | ||
| 140 | + launchEvent.beginTime = begin; | ||
| 141 | + launchEvent.endTime = end; | ||
| 142 | + launchEvent.itemId = info.opNameId; | ||
| 143 | + (void)MsprofReportApi(true, &launchEvent); | ||
| 144 | + | ||
| 145 | + // Live node tensors cover eager execution and collection during capture. | ||
| 146 | + // They supplement, rather than replace, Runtime's cached replay metadata. | ||
| 48 | for (uint32_t offset = 0; offset < info.tensorNum; offset += MSPROF_GE_TENSOR_DATA_NUM) { | 147 | for (uint32_t offset = 0; offset < info.tensorNum; offset += MSPROF_GE_TENSOR_DATA_NUM) { |
| 49 | MsprofAdditionalInfo additional{}; | 148 | MsprofAdditionalInfo additional{}; |
| 50 | additional.level = MSPROF_REPORT_NODE_LEVEL; | 149 | additional.level = MSPROF_REPORT_NODE_LEVEL; |
| @@ -57,14 +156,7 @@ inline void ReportCaptureTensorInfo(const aclprofTensorInfo& info, uint64_t begi | |||
| 57 | const uint32_t remaining = info.tensorNum - offset; | 156 | const uint32_t remaining = info.tensorNum - offset; |
| 58 | tensors.tensorNum = remaining < MSPROF_GE_TENSOR_DATA_NUM ? remaining : MSPROF_GE_TENSOR_DATA_NUM; | 157 | tensors.tensorNum = remaining < MSPROF_GE_TENSOR_DATA_NUM ? remaining : MSPROF_GE_TENSOR_DATA_NUM; |
| 59 | for (uint32_t index = 0; index < tensors.tensorNum; ++index) { | 158 | for (uint32_t index = 0; index < tensors.tensorNum; ++index) { |
| 60 | - const aclprofTensor& source = info.tensors[offset + index]; | 159 | + tensors.tensorData[index] = MakeProfTensorData(info.tensors[offset + index]); |
| 61 | - MsrofTensorData& dest = tensors.tensorData[index]; | ||
| 62 | - dest.tensorType = source.type; | ||
| 63 | - dest.format = source.format; | ||
| 64 | - dest.dataType = source.dataType; | ||
| 65 | - for (uint32_t dim = 0; dim < MSPROF_GE_TENSOR_DATA_SHAPE_LEN; ++dim) { | ||
| 66 | - dest.shape[dim] = source.shape[dim]; | ||
| 67 | - } | ||
| 68 | } | 160 | } |
| 69 | // Metadata collection must never prevent or fail a kernel launch. | 161 | // Metadata collection must never prevent or fail a kernel launch. |
| 70 | (void)MsprofReportAdditionalInfo(true, &additional, sizeof(additional)); | 162 | (void)MsprofReportAdditionalInfo(true, &additional, sizeof(additional)); |
| @@ -384,7 +384,7 @@ from ._api import ( | |||
| 384 | from ._simt_api import Simt as simt # noqa: N813 | 384 | from ._simt_api import Simt as simt # noqa: N813 |
| 385 | from ._vf_api import Vf | 385 | from ._vf_api import Vf |
| 386 | from .parser.decorator import inline, vector_function | 386 | from .parser.decorator import inline, vector_function |
| 387 | -from .typing import DYNAMIC, STATIC, Ptr, Scalar, Tensor | 387 | +from .typing import DYNAMIC, STATIC, Input, Output, Ptr, Scalar, Tensor |
| 388 | 388 | ||
| 389 | mutex = SimpleNamespace(mutex_lock=_mutex_lock, mutex_unlock=_mutex_unlock) | 389 | mutex = SimpleNamespace(mutex_lock=_mutex_lock, mutex_unlock=_mutex_unlock) |
| 390 | 390 | ||
| @@ -462,34 +462,3 @@ NZ = TensorLayout.NZ | |||
| 462 | ZN = TensorLayout.ZN | 462 | ZN = TensorLayout.ZN |
| 463 | NN = TensorLayout.NN | 463 | NN = TensorLayout.NN |
| 464 | ZZ = TensorLayout.ZZ | 464 | ZZ = TensorLayout.ZZ |
| 465 | - | ||
| 466 | - | ||
| 467 | -class _DirectionMarker: | ||
| 468 | - """Marker for tensor direction in ``pl.Tensor[...]`` annotations. | ||
| 469 | - | ||
| 470 | - ``pl.Input`` (default when omitted) marks a read-only parameter; | ||
| 471 | - ``pl.Output`` marks a parameter the kernel stores into. Used purely for | ||
| 472 | - profiling metadata (aclprof tensor type) — computation semantics unchanged. | ||
| 473 | - """ | ||
| 474 | - | ||
| 475 | - __slots__ = ("name",) | ||
| 476 | - | ||
| 477 | - def __init__(self, name: str): | ||
| 478 | - self.name = name | ||
| 479 | - | ||
| 480 | - def __repr__(self) -> str: | ||
| 481 | - return f"pl.{self.name}" | ||
| 482 | - | ||
| 483 | - def __reduce__(self): | ||
| 484 | - # Pickle by module attribute so the round-tripped object stays the same | ||
| 485 | - # singleton (identity matters: markers are compared with ``is``). | ||
| 486 | - return _DirectionMarker._from_module_attr, (self.name,) | ||
| 487 | - | ||
| 488 | - @staticmethod | ||
| 489 | - def _from_module_attr(name: str) -> "_DirectionMarker": | ||
| 490 | - import pypto_pro.language as _pl | ||
| 491 | - return getattr(_pl, name) | ||
| 492 | - | ||
| 493 | - | ||
| 494 | -Input = _DirectionMarker("Input") | ||
| 495 | -Output = _DirectionMarker("Output") | ||
| @@ -137,8 +137,6 @@ class ASTParser( | |||
| 137 | # Keep the Expr itself as the key. A bare id(expr) does not retain the | 137 | # Keep the Expr itself as the key. A bare id(expr) does not retain the |
| 138 | # Python IR wrapper and can be reused by an unrelated expression. | 138 | # Python IR wrapper and can be reused by an unrelated expression. |
| 139 | self._tile_mutex_meta: dict[ir.Expr, tuple] = {} | 139 | self._tile_mutex_meta: dict[ir.Expr, tuple] = {} |
| 140 | - # Param name -> "in"/"out" from pl.Input/pl.Output annotation markers. | ||
| 141 | - self.param_directions: dict[str, str] = {} | ||
| 142 | self.scope_manager = ScopeManager(strict_ssa=strict_ssa) | 140 | self.scope_manager = ScopeManager(strict_ssa=strict_ssa) |
| 143 | self._tilingkey_consts = tilingkey_consts | 141 | self._tilingkey_consts = tilingkey_consts |
| 144 | self._datatype_consts = datatype_consts | 142 | self._datatype_consts = datatype_consts |
| @@ -392,9 +390,9 @@ class ASTParser( | |||
| 392 | self._anchored_make_tuples.clear() | 390 | self._anchored_make_tuples.clear() |
| 393 | 391 | ||
| 394 | with self.builder.function(func_name, func_span, func_type=func_type) as f: | 392 | with self.builder.function(func_name, func_span, func_type=func_type) as f: |
| 395 | - for arg in args_to_process: | 393 | + for parameter_index, arg in enumerate(args_to_process): |
| 396 | callsite_type = callsite_param_types.get(arg.arg) if callsite_param_types is not None else None | 394 | callsite_type = callsite_param_types.get(arg.arg) if callsite_param_types is not None else None |
| 397 | - self._parse_function_param(arg, f, callsite_type) | 395 | + self._parse_function_param(arg, f, parameter_index, callsite_type) |
| 398 | 396 | ||
| 399 | # Give closure tuples a function-entry array-materialization anchor. | 397 | # Give closure tuples a function-entry array-materialization anchor. |
| 400 | self._hoist_closure_tuples() | 398 | self._hoist_closure_tuples() |
| @@ -593,7 +591,13 @@ class ASTParser( | |||
| 593 | hint="Move the tiling parameter to the last position", | 591 | hint="Move the tiling parameter to the last position", |
| 594 | ) | 592 | ) |
| 595 | 593 | ||
| 596 | - def _parse_function_param(self, arg: ast.arg, f: Any, callsite_type: ir.Type | None = None) -> None: | 594 | + def _parse_function_param( |
| 595 | + self, | ||
| 596 | + arg: ast.arg, | ||
| 597 | + f: Any, | ||
| 598 | + parameter_index: int, | ||
| 599 | + callsite_type: ir.Type | None = None, | ||
| 600 | + ) -> None: | ||
| 597 | """Parse a single function parameter and register it in scope or tiling registry.""" | 601 | """Parse a single function parameter and register it in scope or tiling registry.""" |
| 598 | param_name = arg.arg | 602 | param_name = arg.arg |
| 599 | param_span = self.span_tracker.get_span(arg) | 603 | param_span = self.span_tracker.get_span(arg) |
| @@ -617,7 +621,7 @@ class ASTParser( | |||
| 617 | if callsite_type is not None: | 621 | if callsite_type is not None: |
| 618 | if arg.annotation is not None: | 622 | if arg.annotation is not None: |
| 619 | annotated_type = self.type_resolver.resolve_param_type( | 623 | annotated_type = self.type_resolver.resolve_param_type( |
| 620 | - arg.annotation, parameter_name=param_name | 624 | + arg.annotation, parameter_name=param_name, parameter_index=parameter_index |
| 621 | ) | 625 | ) |
| 622 | _check_type_compatible( | 626 | _check_type_compatible( |
| 623 | annotated_type, callsite_type, what="SIMT parameter", name=param_name, span=param_span | 627 | annotated_type, callsite_type, what="SIMT parameter", name=param_name, span=param_span |
| @@ -635,33 +639,13 @@ class ASTParser( | |||
| 635 | hint="Add a type annotation like: x: pl.Tensor[[64], pl.DT_FP32]", | 639 | hint="Add a type annotation like: x: pl.Tensor[[64], pl.DT_FP32]", |
| 636 | parser_retry=True, | 640 | parser_retry=True, |
| 637 | ) | 641 | ) |
| 638 | - param_type = self.type_resolver.resolve_param_type(arg.annotation, parameter_name=param_name) | 642 | + param_type = self.type_resolver.resolve_param_type( |
| 643 | + arg.annotation, parameter_name=param_name, parameter_index=parameter_index | ||
| 644 | + ) | ||
| 639 | param_type = self._attach_ptr_to_tensor_type(param_name, param_type, param_span) | 645 | param_type = self._attach_ptr_to_tensor_type(param_name, param_type, param_span) |
| 640 | param_var = f.param(param_name, param_type, param_span) | 646 | param_var = f.param(param_name, param_type, param_span) |
| 641 | self.scope_manager.define_var(param_name, param_var, allow_redef=True) | 647 | self.scope_manager.define_var(param_name, param_var, allow_redef=True) |
| 642 | 648 | ||
| 643 | - # pl.Input / pl.Output annotation marker: record the declared direction so | ||
| 644 | - # the JIT caller can use it for profiling tensor type. | ||
| 645 | - direction = self._extract_declared_direction(arg.annotation) | ||
| 646 | - if direction is not None: | ||
| 647 | - self.param_directions[param_name] = direction | ||
| 648 | - | ||
| 649 | - def _extract_declared_direction(self, annotation: ast.expr | None) -> str | None: | ||
| 650 | - """Direction declared via ``pl.Tensor[..., pl.Output]`` in a param annotation. | ||
| 651 | - | ||
| 652 | - Evaluates the annotation expression and reads ``Tensor.direction`` — | ||
| 653 | - only annotation-only Tensor objects carry the attribute. | ||
| 654 | - """ | ||
| 655 | - if annotation is None or not isinstance(annotation, ast.Subscript): | ||
| 656 | - return None | ||
| 657 | - try: | ||
| 658 | - success, value = self.expr_evaluator.try_eval_expr(annotation) | ||
| 659 | - except Exception: | ||
| 660 | - return None | ||
| 661 | - if success and hasattr(value, "direction") and value.direction is not None: | ||
| 662 | - return value.direction | ||
| 663 | - return None | ||
| 664 | - | ||
| 665 | def _hoist_closure_tuples(self) -> None: | 649 | def _hoist_closure_tuples(self) -> None: |
| 666 | """Anchor convertible closure tuple/list values at function entry. | 650 | """Anchor convertible closure tuple/list values at function entry. |
| 667 | 651 | ||
| @@ -22,6 +22,7 @@ from typing import TYPE_CHECKING, Any | |||
| 22 | 22 | ||
| 23 | from pypto.pypto_impl import ir | 23 | from pypto.pypto_impl import ir |
| 24 | from pypto.pypto_impl.ir import DataType | 24 | from pypto.pypto_impl.ir import DataType |
| 25 | +from pypto_pro.language.typing.direction import TensorDirection | ||
| 25 | 26 | ||
| 26 | from ..._errors import ( | 27 | from ..._errors import ( |
| 27 | InvalidArgument, | 28 | InvalidArgument, |
| @@ -127,6 +128,8 @@ class TypeResolver: | |||
| 127 | self.span_tracker = span_tracker | 128 | self.span_tracker = span_tracker |
| 128 | self.bound_signature = bound_signature | 129 | self.bound_signature = bound_signature |
| 129 | self._parameter_name: str | None = None | 130 | self._parameter_name: str | None = None |
| 131 | + self._parameter_index: int | None = None | ||
| 132 | + self.param_directions: dict[int, TensorDirection] = {} | ||
| 130 | 133 | ||
| 131 | @staticmethod | 134 | @staticmethod |
| 132 | def _resolve_shape_spec_and_rank( | 135 | def _resolve_shape_spec_and_rank( |
| @@ -261,11 +264,18 @@ class TypeResolver: | |||
| 261 | isinstance(func, ast.Name) and func.id == "MemRef" | 264 | isinstance(func, ast.Name) and func.id == "MemRef" |
| 262 | ) | 265 | ) |
| 263 | 266 | ||
| 264 | - def resolve_param_type(self, type_node: ast.expr, parameter_name: str | None = None) -> "ir.Type": | 267 | + def resolve_param_type( |
| 268 | + self, | ||
| 269 | + type_node: ast.expr, | ||
| 270 | + parameter_name: str | None = None, | ||
| 271 | + parameter_index: int | None = None, | ||
| 272 | + ) -> "ir.Type": | ||
| 265 | """Resolve AST type annotation to ir.Type for function parameters. | 273 | """Resolve AST type annotation to ir.Type for function parameters. |
| 266 | 274 | ||
| 267 | Args: | 275 | Args: |
| 268 | type_node: AST expression representing the type annotation | 276 | type_node: AST expression representing the type annotation |
| 277 | + parameter_name: Source parameter name used by shape policies | ||
| 278 | + parameter_index: Stable parameter position used by direction metadata | ||
| 269 | 279 | ||
| 270 | Returns: | 280 | Returns: |
| 271 | Resolved IR type | 281 | Resolved IR type |
| @@ -273,12 +283,18 @@ class TypeResolver: | |||
| 273 | Raises: | 283 | Raises: |
| 274 | NotSupported: If the annotation is a tuple, which a parameter cannot be | 284 | NotSupported: If the annotation is a tuple, which a parameter cannot be |
| 275 | """ | 285 | """ |
| 286 | + if parameter_index is not None: | ||
| 287 | + self.param_directions.pop(parameter_index, None) | ||
| 288 | + | ||
| 276 | previous_parameter = self._parameter_name | 289 | previous_parameter = self._parameter_name |
| 290 | + previous_index = self._parameter_index | ||
| 277 | self._parameter_name = parameter_name | 291 | self._parameter_name = parameter_name |
| 292 | + self._parameter_index = parameter_index | ||
| 278 | try: | 293 | try: |
| 279 | resolved = self.resolve_type(type_node) | 294 | resolved = self.resolve_type(type_node) |
| 280 | finally: | 295 | finally: |
| 281 | self._parameter_name = previous_parameter | 296 | self._parameter_name = previous_parameter |
| 297 | + self._parameter_index = previous_index | ||
| 282 | if isinstance(resolved, ir.TupleType): | 298 | if isinstance(resolved, ir.TupleType): |
| 283 | raise NotSupported( | 299 | raise NotSupported( |
| 284 | "Parameter type cannot be a tuple", | 300 | "Parameter type cannot be a tuple", |
| @@ -449,7 +465,7 @@ class TypeResolver: | |||
| 449 | return self._resolve_tuple_type(type_node) | 465 | return self._resolve_tuple_type(type_node) |
| 450 | return self._resolve_subscript_type(type_node) | 466 | return self._resolve_subscript_type(type_node) |
| 451 | 467 | ||
| 452 | - # Handle pl.Tensor((64, 128), pl.DT_FP16) call notation (legacy) | 468 | + # Handle pl.Tensor((64, 128), pl.DT_FP16) call notation |
| 453 | if isinstance(type_node, ast.Call): | 469 | if isinstance(type_node, ast.Call): |
| 454 | return self._resolve_call_type(type_node) | 470 | return self._resolve_call_type(type_node) |
| 455 | 471 | ||
| @@ -759,6 +775,17 @@ class TypeResolver: | |||
| 759 | parser_retry=True, | 775 | parser_retry=True, |
| 760 | ) | 776 | ) |
| 761 | 777 | ||
| 778 | + def _resolve_tensor_direction(self, node: ast.expr) -> TensorDirection | None: | ||
| 779 | + """Resolve a public direction enum used in a Tensor annotation.""" | ||
| 780 | + if isinstance(node, ast.Attribute): | ||
| 781 | + if node.attr not in {"Input", "Output"}: | ||
| 782 | + return None | ||
| 783 | + elif not isinstance(node, ast.Name): | ||
| 784 | + return None | ||
| 785 | + | ||
| 786 | + success, value = self.expr_evaluator.try_eval_expr(node) | ||
| 787 | + return value if success and isinstance(value, TensorDirection) else None | ||
| 788 | + | ||
| 762 | def _resolve_subscript_type(self, subscript_node: ast.Subscript) -> ir.Type: | 789 | def _resolve_subscript_type(self, subscript_node: ast.Subscript) -> ir.Type: |
| 763 | """Resolve subscript type annotation. | 790 | """Resolve subscript type annotation. |
| 764 | 791 | ||
| @@ -795,7 +822,7 @@ class TypeResolver: | |||
| 795 | return ir.PtrType(dtype) | 822 | return ir.PtrType(dtype) |
| 796 | 823 | ||
| 797 | # Tensor: [shape, dtype], [shape, dtype, layout_or_memref], [shape, dtype, layout, memref] | 824 | # Tensor: [shape, dtype], [shape, dtype, layout_or_memref], [shape, dtype, layout, memref] |
| 798 | - valid_counts = (2, 3, 4) if type_name == "Tensor" else (2, 3) | 825 | + valid_counts = (2, 3, 4, 5) if type_name == "Tensor" else (2, 3) |
| 799 | if not isinstance(slice_value, ast.Tuple) or len(slice_value.elts) not in valid_counts: | 826 | if not isinstance(slice_value, ast.Tuple) or len(slice_value.elts) not in valid_counts: |
| 800 | if type_name == "Tensor": | 827 | if type_name == "Tensor": |
| 801 | message = ( | 828 | message = ( |
| @@ -824,35 +851,28 @@ class TypeResolver: | |||
| 824 | shape = self._resolve_annotation_shape(shape_node, type_name) | 851 | shape = self._resolve_annotation_shape(shape_node, type_name) |
| 825 | dtype = self.resolve_dtype(dtype_node) | 852 | dtype = self.resolve_dtype(dtype_node) |
| 826 | 853 | ||
| 827 | - n_elts = len(slice_value.elts) | 854 | + # Direction is parser metadata only; remove it before resolving the IR TensorType. |
| 828 | - | 855 | + direction: TensorDirection | None = None |
| 829 | - # 2 args: [shape, dtype] | 856 | + elts: list[ast.expr] = [] |
| 830 | - # Filter out pl.Input / pl.Output direction markers from the subscript | 857 | + for element in slice_value.elts: |
| 831 | - # elements; they were already captured by the annotation-level evaluation | 858 | + element_direction = self._resolve_tensor_direction(element) |
| 832 | - # (see _extract_declared_direction) and carry no IR type meaning here. | 859 | + if element_direction is None: |
| 833 | - from pypto_pro.language import _DirectionMarker | 860 | + elts.append(element) |
| 834 | - | 861 | + elif direction is not None: |
| 835 | - def _is_direction_marker(node: ast.expr) -> bool: | 862 | + raise InvalidArgument( |
| 836 | - # Match ``pl.Input`` / ``pl.Output`` (Attribute on ``pl``) or a bare | 863 | + "Tensor direction can be specified only once", |
| 837 | - # Name bound to a _DirectionMarker; the expr_evaluator fallback covers | 864 | + span=self._get_span(element), |
| 838 | - # aliased imports (``from pypto_pro.language import Output``). | 865 | + hint="Use one pl.Input or pl.Output value", |
| 839 | - if isinstance(node, ast.Attribute): | 866 | + parser_retry=True, |
| 840 | - if node.attr not in ("Input", "Output"): | 867 | + ) |
| 841 | - return False | ||
| 842 | - base = node.value | ||
| 843 | - return isinstance(base, ast.Name) and base.id == "pl" | ||
| 844 | - if isinstance(node, ast.Name): | ||
| 845 | - if node.id not in ("Input", "Output"): | ||
| 846 | - return False | ||
| 847 | else: | 868 | else: |
| 848 | - return False | 869 | + direction = element_direction |
| 849 | - try: | 870 | + if len(elts) not in (2, 3, 4): |
| 850 | - ok, v = self.expr_evaluator.try_eval_expr(node) | 871 | + raise InvalidArgument( |
| 851 | - return ok and isinstance(v, _DirectionMarker) | 872 | + f"Tensor subscript has invalid arguments: {ast.unparse(slice_value)}", |
| 852 | - except Exception: | 873 | + hint="Use pl.Tensor[[shape], dtype, optional layout/memref, optional pl.Input/pl.Output]", |
| 853 | - return False | 874 | + parser_retry=True, |
| 854 | - | 875 | + ) |
| 855 | - elts = [e for e in slice_value.elts if not _is_direction_marker(e)] | ||
| 856 | slice_value = ast.Tuple( | 876 | slice_value = ast.Tuple( |
| 857 | elts=elts, | 877 | elts=elts, |
| 858 | ctx=slice_value.ctx, | 878 | ctx=slice_value.ctx, |
| @@ -863,8 +883,13 @@ class TypeResolver: | |||
| 863 | ) | 883 | ) |
| 864 | n_elts = len(elts) | 884 | n_elts = len(elts) |
| 865 | 885 | ||
| 886 | + def with_direction(tensor_type: ir.TensorType) -> ir.TensorType: | ||
| 887 | + if direction is not None and self._parameter_index is not None: | ||
| 888 | + self.param_directions[self._parameter_index] = direction | ||
| 889 | + return tensor_type | ||
| 890 | + | ||
| 866 | if n_elts == 2: | 891 | if n_elts == 2: |
| 867 | - return ir.TensorType(shape, dtype) | 892 | + return with_direction(ir.TensorType(shape, dtype)) |
| 868 | 893 | ||
| 869 | # 3 args: [shape, dtype, layout_or_memref_or_view] | 894 | # 3 args: [shape, dtype, layout_or_memref_or_view] |
| 870 | if n_elts == 3: | 895 | if n_elts == 3: |
| @@ -872,11 +897,11 @@ class TypeResolver: | |||
| 872 | # Disambiguate 3rd arg (backward compat) | 897 | # Disambiguate 3rd arg (backward compat) |
| 873 | if self._is_memref_node(third): | 898 | if self._is_memref_node(third): |
| 874 | memref = self.resolve_memref(third) | 899 | memref = self.resolve_memref(third) |
| 875 | - return ir.TensorType(shape, dtype, memref) | 900 | + return with_direction(ir.TensorType(shape, dtype, memref)) |
| 876 | layout = self.resolve_layout(third) | 901 | layout = self.resolve_layout(third) |
| 877 | self._validate_tensor_layout(shape, layout, third) | 902 | self._validate_tensor_layout(shape, layout, third) |
| 878 | tensor_view = ir.TensorView([], layout) | 903 | tensor_view = ir.TensorView([], layout) |
| 879 | - return ir.TensorType(shape, dtype, None, tensor_view) | 904 | + return with_direction(ir.TensorType(shape, dtype, None, tensor_view)) |
| 880 | 905 | ||
| 881 | # 4 args: [shape, dtype, layout, memref] -> Tensor only | 906 | # 4 args: [shape, dtype, layout, memref] -> Tensor only |
| 882 | layout = self.resolve_layout(slice_value.elts[2]) | 907 | layout = self.resolve_layout(slice_value.elts[2]) |
| @@ -890,7 +915,7 @@ class TypeResolver: | |||
| 890 | parser_retry=True, | 915 | parser_retry=True, |
| 891 | ) | 916 | ) |
| 892 | memref = self.resolve_memref(memref_node) | 917 | memref = self.resolve_memref(memref_node) |
| 893 | - return ir.TensorType(shape, dtype, memref, tensor_view) | 918 | + return with_direction(ir.TensorType(shape, dtype, memref, tensor_view)) |
| 894 | 919 | ||
| 895 | def _resolve_tuple_type(self, subscript_node: ast.Subscript) -> "ir.TupleType": | 920 | def _resolve_tuple_type(self, subscript_node: ast.Subscript) -> "ir.TupleType": |
| 896 | """Resolve tuple[T1, T2, ...] return type annotation to a single TupleType. | 921 | """Resolve tuple[T1, T2, ...] return type annotation to a single TupleType. |
| @@ -947,7 +972,7 @@ class TypeResolver: | |||
| 947 | ) | 972 | ) |
| 948 | 973 | ||
| 949 | def _resolve_tensor_type(self, call_node: ast.Call) -> ir.TensorType: | 974 | def _resolve_tensor_type(self, call_node: ast.Call) -> ir.TensorType: |
| 950 | - """Resolve pl.Tensor((shape), dtype) annotation (legacy).""" | 975 | + """Resolve a pl.Tensor((shape), dtype, optional direction) annotation.""" |
| 951 | result = self._resolve_shaped_type(call_node, "Tensor", ir.TensorType) | 976 | result = self._resolve_shaped_type(call_node, "Tensor", ir.TensorType) |
| 952 | if not isinstance(result, ir.TensorType): | 977 | if not isinstance(result, ir.TensorType): |
| 953 | raise InvalidType("Expected TensorType result") | 978 | raise InvalidType("Expected TensorType result") |
| @@ -959,7 +984,7 @@ class TypeResolver: | |||
| 959 | type_name: str, | 984 | type_name: str, |
| 960 | type_ctor: type[ir.TensorType], | 985 | type_ctor: type[ir.TensorType], |
| 961 | ) -> ir.TensorType: | 986 | ) -> ir.TensorType: |
| 962 | - """Resolve a tensor type from a legacy call annotation. | 987 | + """Resolve a tensor type from a call-style annotation. |
| 963 | 988 | ||
| 964 | Args: | 989 | Args: |
| 965 | call_node: AST Call node for the type constructor | 990 | call_node: AST Call node for the type constructor |
| @@ -972,16 +997,30 @@ class TypeResolver: | |||
| 972 | Raises: | 997 | Raises: |
| 973 | InvalidType: If the call does not carry both shape and dtype | 998 | InvalidType: If the call does not carry both shape and dtype |
| 974 | """ | 999 | """ |
| 975 | - if len(call_node.args) < 2: | 1000 | + if len(call_node.args) not in (2, 3): |
| 976 | raise InvalidType( | 1001 | raise InvalidType( |
| 977 | - f"{type_name} type requires shape and dtype arguments, got {len(call_node.args)}", | 1002 | + f"{type_name} type requires shape, dtype, and optional direction arguments, " |
| 978 | - hint=f"Use pl.{type_name}[[shape], dtype] format", | 1003 | + f"got {len(call_node.args)}", |
| 1004 | + hint=f"Use pl.{type_name}([shape], dtype) or pl.{type_name}([shape], dtype, pl.Input/pl.Output)", | ||
| 979 | parser_retry=True, | 1005 | parser_retry=True, |
| 980 | ) | 1006 | ) |
| 981 | 1007 | ||
| 1008 | + direction = None | ||
| 1009 | + if len(call_node.args) == 3: | ||
| 1010 | + direction = self._resolve_tensor_direction(call_node.args[2]) | ||
| 1011 | + if direction is None: | ||
| 1012 | + raise InvalidType( | ||
| 1013 | + "Tensor direction must be pl.Input or pl.Output", | ||
| 1014 | + span=self._get_span(call_node.args[2]), | ||
| 1015 | + parser_retry=True, | ||
| 1016 | + ) | ||
| 1017 | + | ||
| 982 | shape = self.to_ir_shape(self.parse_shape(call_node.args[0])) | 1018 | shape = self.to_ir_shape(self.parse_shape(call_node.args[0])) |
| 983 | dtype = self.resolve_dtype(call_node.args[1]) | 1019 | dtype = self.resolve_dtype(call_node.args[1]) |
| 984 | - return type_ctor(shape, dtype) | 1020 | + result = type_ctor(shape, dtype) |
| 1021 | + if direction is not None and self._parameter_index is not None: | ||
| 1022 | + self.param_directions[self._parameter_index] = direction | ||
| 1023 | + return result | ||
| 985 | 1024 | ||
| 986 | def _parse_dim_elements(self, elts: list[ast.expr]) -> list[int | ir.Expr]: | 1025 | def _parse_dim_elements(self, elts: list[ast.expr]) -> list[int | ir.Expr]: |
| 987 | """Parse a list of dimension elements (int literal, variable, or evaluable expression). | 1026 | """Parse a list of dimension elements (int literal, variable, or evaluable expression). |
| @@ -11,13 +11,14 @@ | |||
| 11 | 11 | ||
| 12 | """Type wrappers for PyPTO Language DSL. | 12 | """Type wrappers for PyPTO Language DSL. |
| 13 | 13 | ||
| 14 | -This module provides type annotation classes for PyPTO's language DSL: | 14 | +This module provides type annotation helpers for PyPTO's language DSL: |
| 15 | - Scalar: Scalar values with specific data types | 15 | - Scalar: Scalar values with specific data types |
| 16 | - Tensor: Multi-dimensional arrays in global memory | 16 | - Tensor: Multi-dimensional arrays in global memory |
| 17 | """ | 17 | """ |
| 18 | 18 | ||
| 19 | -__all__ = ["DYNAMIC", "STATIC", "Ptr", "Scalar", "Tensor"] | 19 | +__all__ = ["DYNAMIC", "STATIC", "Input", "Output", "Ptr", "Scalar", "Tensor"] |
| 20 | 20 | ||
| 21 | +from pypto_pro.language.typing.direction import Input, Output | ||
| 21 | from pypto_pro.language.typing.ptr import Ptr | 22 | from pypto_pro.language.typing.ptr import Ptr |
| 22 | from pypto_pro.language.typing.scalar import Scalar | 23 | from pypto_pro.language.typing.scalar import Scalar |
| 23 | from pypto_pro.language.typing.shape import DYNAMIC, STATIC | 24 | from pypto_pro.language.typing.shape import DYNAMIC, STATIC |
| @@ -0,0 +1,23 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""Tensor parameter direction used by profiling metadata.""" | ||
| 11 | + | ||
| 12 | +from enum import Enum | ||
| 13 | + | ||
| 14 | +__all__ = ["Input", "Output"] | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +class TensorDirection(Enum): | ||
| 18 | + INPUT = 0 | ||
| 19 | + OUTPUT = 1 | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +Input = TensorDirection.INPUT | ||
| 23 | +Output = TensorDirection.OUTPUT | ||
| @@ -17,6 +17,7 @@ __all__ = ["Tensor"] | |||
| 17 | from collections.abc import Sequence | 17 | from collections.abc import Sequence |
| 18 | 18 | ||
| 19 | from pypto.pypto_impl.ir import DataType, Expr, MemRef, TensorLayout | 19 | from pypto.pypto_impl.ir import DataType, Expr, MemRef, TensorLayout |
| 20 | +from pypto_pro.language.typing.direction import TensorDirection | ||
| 20 | from pypto_pro.language.typing.shape import _ShapePolicy | 21 | from pypto_pro.language.typing.shape import _ShapePolicy |
| 21 | 22 | ||
| 22 | from ..._errors import InvalidOperation, InvalidType | 23 | from ..._errors import InvalidOperation, InvalidType |
| @@ -55,24 +56,27 @@ class Tensor: | |||
| 55 | self, | 56 | self, |
| 56 | shape: Sequence[int | _ShapePolicy | EllipsisType] | None = None, | 57 | shape: Sequence[int | _ShapePolicy | EllipsisType] | None = None, |
| 57 | dtype: DataType | None = None, | 58 | dtype: DataType | None = None, |
| 58 | - expr: Expr | None = None, | 59 | + expr: Expr | TensorDirection | None = None, |
| 59 | layout: TensorLayout | None = None, | 60 | layout: TensorLayout | None = None, |
| 60 | memref: MemRef | None = None, | 61 | memref: MemRef | None = None, |
| 61 | _annotation_only: bool = False, | 62 | _annotation_only: bool = False, |
| 62 | - direction: str | None = None, | ||
| 63 | ): | 63 | ): |
| 64 | """Initialize Tensor. | 64 | """Initialize Tensor. |
| 65 | 65 | ||
| 66 | Args: | 66 | Args: |
| 67 | shape: Shape (for annotation mode) | 67 | shape: Shape (for annotation mode) |
| 68 | dtype: Data type (for annotation mode) | 68 | dtype: Data type (for annotation mode) |
| 69 | - expr: IR expression to wrap (for runtime mode) | 69 | + expr: IR expression to wrap, or Input/Output in a call-style annotation |
| 70 | layout: Optional tensor layout (ND, DN, NZ) | 70 | layout: Optional tensor layout (ND, DN, NZ) |
| 71 | memref: Optional memory reference | 71 | memref: Optional memory reference |
| 72 | _annotation_only: Whether this is annotation-only mode | 72 | _annotation_only: Whether this is annotation-only mode |
| 73 | - direction: Optional direction marker ("in"/"out") from pl.Input/pl.Output | ||
| 74 | """ | 73 | """ |
| 75 | - self.direction = direction | 74 | + if isinstance(expr, TensorDirection): |
| 75 | + if shape is None or dtype is None: | ||
| 76 | + raise ValueError("Tensor direction is only valid for annotation arguments") | ||
| 77 | + expr = None | ||
| 78 | + _annotation_only = True | ||
| 79 | + | ||
| 76 | if expr is not None: | 80 | if expr is not None: |
| 77 | if _annotation_only or shape is not None or dtype is not None: | 81 | if _annotation_only or shape is not None or dtype is not None: |
| 78 | raise InvalidOperation("Runtime Tensor wrapping cannot include annotation arguments") | 82 | raise InvalidOperation("Runtime Tensor wrapping cannot include annotation arguments") |
| @@ -98,32 +102,23 @@ class Tensor: | |||
| 98 | if not isinstance(item, tuple) or len(item) not in (2, 3, 4, 5): | 102 | if not isinstance(item, tuple) or len(item) not in (2, 3, 4, 5): |
| 99 | raise InvalidType( | 103 | raise InvalidType( |
| 100 | "Tensor requires [shape, dtype], [shape, dtype, layout_or_memref_or_view], " | 104 | "Tensor requires [shape, dtype], [shape, dtype, layout_or_memref_or_view], " |
| 101 | - "[shape, dtype, layout, memref], or those plus a direction marker " | 105 | + "[shape, dtype, layout, memref], or those forms with pl.Input/pl.Output" |
| 102 | - "(pl.Input / pl.Output) notation" | ||
| 103 | ) | 106 | ) |
| 104 | 107 | ||
| 105 | - # Direction marker may appear in any position after dtype; extract it so the | 108 | + # Direction is parser metadata. Ignore its enum value during eager Python |
| 106 | - # remaining elements follow the legacy layout/memref shapes. | 109 | + # annotation evaluation; TypeResolver reads and validates it from the AST. |
| 107 | - from pypto_pro.language import _DirectionMarker | 110 | + item = item[:2] + tuple(value for value in item[2:] if not isinstance(value, TensorDirection)) |
| 108 | - | ||
| 109 | - direction = None | ||
| 110 | - elts = list(item) | ||
| 111 | - for idx in range(len(elts) - 1, 1, -1): | ||
| 112 | - if isinstance(elts[idx], _DirectionMarker): | ||
| 113 | - direction = elts[idx].name.lower() | ||
| 114 | - elts.pop(idx) | ||
| 115 | - item = tuple(elts) | ||
| 116 | 111 | ||
| 117 | if len(item) == 4: | 112 | if len(item) == 4: |
| 118 | shape, dtype, layout, memref = item | 113 | shape, dtype, layout, memref = item |
| 119 | - return cls(shape, dtype, layout=layout, memref=memref, _annotation_only=True, direction=direction) | 114 | + return cls(shape, dtype, layout=layout, memref=memref, _annotation_only=True) |
| 120 | if len(item) == 3: | 115 | if len(item) == 3: |
| 121 | shape, dtype, third = item | 116 | shape, dtype, third = item |
| 122 | if isinstance(third, MemRef): | 117 | if isinstance(third, MemRef): |
| 123 | - return cls(shape, dtype, memref=third, _annotation_only=True, direction=direction) | 118 | + return cls(shape, dtype, memref=third, _annotation_only=True) |
| 124 | - return cls(shape, dtype, layout=third, _annotation_only=True, direction=direction) | 119 | + return cls(shape, dtype, layout=third, _annotation_only=True) |
| 125 | shape, dtype = item | 120 | shape, dtype = item |
| 126 | - return cls(shape, dtype, _annotation_only=True, direction=direction) | 121 | + return cls(shape, dtype, _annotation_only=True) |
| 127 | 122 | ||
| 128 | def __repr__(self) -> str: | 123 | def __repr__(self) -> str: |
| 129 | """String representation.""" | 124 | """String representation.""" |
| @@ -36,6 +36,20 @@ class KernelTarget: | |||
| 36 | aiv_per_block: int | 36 | aiv_per_block: int |
| 37 | fat_object: bool | 37 | fat_object: bool |
| 38 | 38 | ||
| 39 | + @property | ||
| 40 | + def entry_qualifier(self) -> str: | ||
| 41 | + """Declare the binary's engines explicitly, including scalar-only kernels.""" | ||
| 42 | + if self.aic_per_block and self.aiv_per_block: | ||
| 43 | + return f"__mix__({self.aic_per_block}, {self.aiv_per_block})" | ||
| 44 | + return "__cube__" if self.aic_per_block else "__vector__" | ||
| 45 | + | ||
| 46 | + @property | ||
| 47 | + def profiler_kernel_type(self) -> int: | ||
| 48 | + """CANN task types: AI_CORE=0, AI_VECTOR_CORE=2, MIX_AIC=4.""" | ||
| 49 | + if self.aic_per_block and self.aiv_per_block: | ||
| 50 | + return 4 | ||
| 51 | + return 0 if self.aic_per_block else 2 | ||
| 52 | + | ||
| 39 | 53 | ||
| 40 | @dataclass(frozen=True) | 54 | @dataclass(frozen=True) |
| 41 | class JitCompileConfig: | 55 | class JitCompileConfig: |
| @@ -139,26 +153,29 @@ _DEFAULT_CCE_JIT_COMPILE_CONFIG = JitCompileConfig( | |||
| 139 | backend=CCE_BACKEND, | 153 | backend=CCE_BACKEND, |
| 140 | kernel_targets={ | 154 | kernel_targets={ |
| 141 | "a2a3": { | 155 | "a2a3": { |
| 142 | - "cube_vec": KernelTarget("dav-c220", aic_per_block=1, aiv_per_block=2, fat_object=True), | 156 | + "cube_vec": KernelTarget("dav-2201", aic_per_block=1, aiv_per_block=2, fat_object=True), |
| 143 | - "cube": KernelTarget("dav-c220-cube", aic_per_block=1, aiv_per_block=0, fat_object=False), | 157 | + "cube": KernelTarget("dav-2201", aic_per_block=1, aiv_per_block=0, fat_object=False), |
| 144 | - "vec": KernelTarget("dav-c220-vec", aic_per_block=0, aiv_per_block=1, fat_object=False), | 158 | + "vec": KernelTarget("dav-2201", aic_per_block=0, aiv_per_block=1, fat_object=False), |
| 145 | }, | 159 | }, |
| 146 | "a5": { | 160 | "a5": { |
| 147 | - "cube_vec": KernelTarget("dav-c310", aic_per_block=1, aiv_per_block=2, fat_object=True), | 161 | + "cube_vec": KernelTarget("dav-3510", aic_per_block=1, aiv_per_block=2, fat_object=True), |
| 148 | - "cube": KernelTarget("dav-c310-cube", aic_per_block=1, aiv_per_block=0, fat_object=False), | 162 | + "cube": KernelTarget("dav-3510", aic_per_block=1, aiv_per_block=0, fat_object=False), |
| 149 | - "vec": KernelTarget("dav-c310-vec", aic_per_block=0, aiv_per_block=1, fat_object=False), | 163 | + "vec": KernelTarget("dav-3510", aic_per_block=0, aiv_per_block=1, fat_object=False), |
| 150 | }, | 164 | }, |
| 151 | }, | 165 | }, |
| 152 | memory_arch_flags={ | 166 | memory_arch_flags={ |
| 153 | "a2a3": "-DMEMORY_BASE", | 167 | "a2a3": "-DMEMORY_BASE", |
| 154 | "a5": "-DREGISTER_BASE", | 168 | "a5": "-DREGISTER_BASE", |
| 155 | }, | 169 | }, |
| 156 | - arch_flags=("--cce-aicore-arch={npu_arch}",), | 170 | + arch_flags=("--npu-arch={npu_arch}",), |
| 157 | - fatobj_flags=("--cce-fatobj-link",), | 171 | + # ASC derives fat objects from the explicit __mix__ entry qualifier. |
| 172 | + fatobj_flags=(), | ||
| 158 | common_flags=( | 173 | common_flags=( |
| 159 | "-fPIC", | 174 | "-fPIC", |
| 160 | "-shared", | 175 | "-shared", |
| 161 | - "-xcce", | 176 | + # The ASC host stub reports the binary's actual kernel type. The legacy |
| 177 | + # CCE stub reports pure vector kernels as AI_CORE, overriding aclprof ranges. | ||
| 178 | + "-xasc", | ||
| 162 | "{mem_arch}", | 179 | "{mem_arch}", |
| 163 | "-O3", | 180 | "-O3", |
| 164 | "-std=c++17", | 181 | "-std=c++17", |
| @@ -185,6 +202,8 @@ _DEFAULT_CCE_JIT_COMPILE_CONFIG = JitCompileConfig( | |||
| 185 | ), | 202 | ), |
| 186 | llvm_arch_args={ | 203 | llvm_arch_args={ |
| 187 | "a2a3": ( | 204 | "a2a3": ( |
| 205 | + "-include", | ||
| 206 | + "kernel_operator.h", | ||
| 188 | "-O3", | 207 | "-O3", |
| 189 | "--cce-disable-kernel-global-attr-check", | 208 | "--cce-disable-kernel-global-attr-check", |
| 190 | "-Wno-parentheses-equality", | 209 | "-Wno-parentheses-equality", |
| @@ -35,6 +35,7 @@ from pypto.pypto_impl import ir | |||
| 35 | from pypto.pypto_impl.codegen import CCECodegen | 35 | from pypto.pypto_impl.codegen import CCECodegen |
| 36 | from pypto.pypto_impl.ir import ConstInt, PtrType, ScalarType, TensorType, TupleType, Var | 36 | from pypto.pypto_impl.ir import ConstInt, PtrType, ScalarType, TensorType, TupleType, Var |
| 37 | from pypto_pro import DataType | 37 | from pypto_pro import DataType |
| 38 | +from pypto_pro.language.typing.direction import TensorDirection | ||
| 38 | from pypto_pro.runtime.compile_config import KernelTarget, get_jit_compile_config | 39 | from pypto_pro.runtime.compile_config import KernelTarget, get_jit_compile_config |
| 39 | 40 | ||
| 40 | from .._errors import ( | 41 | from .._errors import ( |
| @@ -144,8 +145,8 @@ class ParamSpec: | |||
| 144 | dtype: DataType | None # element dtype; None for tiling struct params | 145 | dtype: DataType | None # element dtype; None for tiling struct params |
| 145 | # Tensor dims: positive int = static, str = named dynamic var, -1 = unnamed dynamic; None for ptr/scalar. | 146 | # Tensor dims: positive int = static, str = named dynamic var, -1 = unnamed dynamic; None for ptr/scalar. |
| 146 | shape: list[int | str] | None | 147 | shape: list[int | str] | None |
| 147 | - # Data direction of tensor params: "in" (read-only) or "out" (kernel stores into it). | 148 | + # Data direction of tensor params; non-tensor params leave it unset. |
| 148 | - direction: str | None = None | 149 | + direction: TensorDirection | None = None |
| 149 | 150 | ||
| 150 | 151 | ||
| 151 | @dataclasses.dataclass | 152 | @dataclasses.dataclass |
| @@ -514,28 +515,22 @@ def _infer_dynamic_ub_size(requires_simt: bool, tile_high_water: int) -> int: | |||
| 514 | 515 | ||
| 515 | def _extract_param_specs( | 516 | def _extract_param_specs( |
| 516 | prog, | 517 | prog, |
| 517 | - declared_directions: dict[str, str] | None = None, | 518 | + declared_directions: dict[int, TensorDirection] | None = None, |
| 518 | ) -> list[ParamSpec]: | 519 | ) -> list[ParamSpec]: |
| 519 | """Extract parameter descriptions from the kernel function in an ir.Program. | 520 | """Extract parameter descriptions from the kernel function in an ir.Program. |
| 520 | 521 | ||
| 521 | - Tensor direction comes exclusively from ``pl.Input``/``pl.Output`` annotation | 522 | + Tensor directions are keyed by parameter index because codegen may rename |
| 522 | - markers (``declared_directions``, keyed by source-level param name); params | 523 | + parameters while preserving their order. Unspecified tensors default to |
| 523 | - without a marker default to ``"in"``. | 524 | + TensorDirection.INPUT. |
| 524 | """ | 525 | """ |
| 525 | func = _get_kernel_ir_function(prog) | 526 | func = _get_kernel_ir_function(prog) |
| 526 | declared_directions = declared_directions or {} | 527 | declared_directions = declared_directions or {} |
| 527 | specs: list[ParamSpec] = [] | 528 | specs: list[ParamSpec] = [] |
| 528 | - for var in func.params: | 529 | + for parameter_index, var in enumerate(func.params): |
| 529 | t = var.type | 530 | t = var.type |
| 530 | if isinstance(t, TensorType): | 531 | if isinstance(t, TensorType): |
| 531 | shape = [s.value if isinstance(s, ConstInt) else (s.name if isinstance(s, Var) else -1) for s in t.shape] | 532 | shape = [s.value if isinstance(s, ConstInt) else (s.name if isinstance(s, Var) else -1) for s in t.shape] |
| 532 | - declared = declared_directions.get(var.name) | 533 | + direction = declared_directions.get(parameter_index, TensorDirection.INPUT) |
| 533 | - if declared is None: | ||
| 534 | - # Declared keys use source-level names; IR names may carry a binding | ||
| 535 | - # suffix (``out`` -> ``out_0``) — strip numeric suffix and retry. | ||
| 536 | - base_name = var.name.rsplit("_", 1)[0] if var.name.rsplit("_", 1)[-1].isdigit() else var.name | ||
| 537 | - declared = declared_directions.get(base_name) | ||
| 538 | - direction = "out" if declared in ("out", "output") else "in" | ||
| 539 | specs.append(ParamSpec(var.name, ParamKind.TENSOR, t.dtype, shape, direction)) | 534 | specs.append(ParamSpec(var.name, ParamKind.TENSOR, t.dtype, shape, direction)) |
| 540 | elif isinstance(t, PtrType): | 535 | elif isinstance(t, PtrType): |
| 541 | specs.append(ParamSpec(var.name, ParamKind.PTR, t.dtype, None)) | 536 | specs.append(ParamSpec(var.name, ParamKind.PTR, t.dtype, None)) |
| @@ -946,33 +941,35 @@ def _generate_prof_range_snippet( | |||
| 946 | param_specs: list[ParamSpec], | 941 | param_specs: list[ParamSpec], |
| 947 | dims_in_scope: set, | 942 | dims_in_scope: set, |
| 948 | *, | 943 | *, |
| 944 | + target: KernelTarget, | ||
| 949 | launch_stmt: str, | 945 | launch_stmt: str, |
| 950 | ) -> tuple[str, str, str]: | 946 | ) -> tuple[str, str, str]: |
| 951 | - """Generate the aclprof tensor-info range (push/pop) wrapped around the launch. | 947 | + """Generate tensor metadata for live profiling and cached graph replay. |
| 952 | 948 | ||
| 953 | - Mirrors the asc-devkit torch_library_report_tensor sample: an | 949 | + The helper reports msprof node records while collecting, and independently |
| 954 | - ``aclprofEventAttributes`` carrying ``aclprofTensorInfo`` is pushed right | 950 | + caches op/tensor info on captured tasks, including before collection starts. |
| 955 | - before the ``<<<>>>`` launch and popped right after, so msprof associates | 951 | + Both paths use the same concrete launch shapes, directions and core layout. |
| 956 | - op name/type and per-tensor in/out, dtype, format and shape with the kernel. | 952 | + String registration uses ``aclprofStr2Id`` from libmsprofiler; the |
| 957 | - Reporting uses the ``aclprof*`` interfaces declared in ``acl/acl_prof.h`` | 953 | + ``ProfStr2Id`` alias in libprofapi must not be used (it can crash). |
| 958 | - and exported by libmsprofiler (added to the link line in | 954 | + Metadata failures must never break a launch. |
| 959 | - :func:`_compile_shared_library`); the ``ProfStr2Id`` alias in libprofapi | ||
| 960 | - crashes with std::bad_alloc and must not be used. Failures are ignored: | ||
| 961 | - profiling metadata must never break the launch. | ||
| 962 | - | ||
| 963 | - Captured launches also report node tensor information: some CANN analyzers | ||
| 964 | - select the compiler's kernel node without merging its cached graph tensors. | ||
| 965 | """ | 955 | """ |
| 966 | tensors = [s for s in param_specs if s.kind == ParamKind.TENSOR] | 956 | tensors = [s for s in param_specs if s.kind == ParamKind.TENSOR] |
| 967 | if not tensors: | 957 | if not tensors: |
| 968 | return "", "", "" | 958 | return "", "", "" |
| 969 | 959 | ||
| 960 | + block_nums = "blockDim" | ||
| 961 | + if target.aic_per_block and target.aiv_per_block: | ||
| 962 | + # CANN stores the AIV:AIC ratio in the upper 16 bits, as the ASC node | ||
| 963 | + # reporter does. Keep cached graph metadata consistent with that node. | ||
| 964 | + block_nums = f"(blockDim & 0xffffU) | ({target.aiv_per_block}U << 16)" | ||
| 965 | + | ||
| 970 | tensor_inits = [] | 966 | tensor_inits = [] |
| 971 | for spec in tensors: | 967 | for spec in tensors: |
| 972 | dims = list(spec.shape or []) | 968 | dims = list(spec.shape or []) |
| 973 | shape_tokens = [_prof_shape_token(d, dims_in_scope) for d in dims] | 969 | shape_tokens = [_prof_shape_token(d, dims_in_scope) for d in dims] |
| 974 | padded = shape_tokens[:8] + ["0"] * (8 - min(len(shape_tokens), 8)) | 970 | padded = shape_tokens[:8] + ["0"] * (8 - min(len(shape_tokens), 8)) |
| 975 | - tensor_type = 1 if spec.direction == "out" else 0 | 971 | + direction = spec.direction if spec.direction is not None else TensorDirection.INPUT |
| 972 | + tensor_type = direction.value | ||
| 976 | acl_dtype = _ACL_DTYPE_MAP.get(str(spec.dtype), 0) | 973 | acl_dtype = _ACL_DTYPE_MAP.get(str(spec.dtype), 0) |
| 977 | shape_str = "{" + ", ".join(padded) + "}" | 974 | shape_str = "{" + ", ".join(padded) + "}" |
| 978 | tensor_inits.append( | 975 | tensor_inits.append( |
| @@ -981,48 +978,34 @@ def _generate_prof_range_snippet( | |||
| 981 | ) | 978 | ) |
| 982 | 979 | ||
| 983 | op_name = f"PYPTO_{kernel_name}" | 980 | op_name = f"PYPTO_{kernel_name}" |
| 984 | - # The guard wraps the struct definitions too, so a non-profiling launch skips | 981 | + # Keep tensors alive through the post-launch report/cache call. Outside |
| 985 | - # the tensor table fill entirely; the else branch launches uninstrumented. | 982 | + # collection and capture, skip tensor initialization and string registration. |
| 986 | - # Everything from the definitions through the pop stays in ONE block: | ||
| 987 | - # aclprofRangePushEx hands msprof a pointer to the stack tensors/info, and | ||
| 988 | - # the Tx plugin may read them until the matching pop -- the locals must stay | ||
| 989 | - # in scope across the kernel launch (official sample keeps push/launch/pop in | ||
| 990 | - # one scope for the same reason). ``MsprofGetPath`` (weak, libprofapi) gates | ||
| 991 | - # the ~1.5us push/pop pair on an active collection session: a non-empty | ||
| 992 | - # profiler result path means a profiler is running; a toolkit without the | ||
| 993 | - # symbol links it to null and we report unconditionally, as before. | ||
| 994 | return ( | 983 | return ( |
| 995 | - "#include \"acl/acl_prof.h\"\n" | 984 | + '#include "acl/acl_prof.h"\n' |
| 996 | - "#include \"pypto_profiler.h\"\n" | 985 | + '#include "pypto_profiler.h"\n', |
| 997 | - "// Weak: a toolkit without it links to null and we report unconditionally, as before.\n" | ||
| 998 | - "extern \"C\" __attribute__((weak)) char *MsprofGetPath();\n", | ||
| 999 | " {\n" | 986 | " {\n" |
| 1000 | - " // Skip the whole report unless a profiler is collecting; empty path means off.\n" | 987 | + " // Collection and graph metadata caching independently need tensors.\n" |
| 1001 | - " const char *pyptoProfPath = (MsprofGetPath != nullptr) ? MsprofGetPath() : nullptr;\n" | 988 | + " const bool pyptoProfOn = pypto::GetProfStatus();\n" |
| 1002 | - " const bool pyptoProfOn =\n" | 989 | + " aclrtStreamAttrValue pyptoCaptureAttr{};\n" |
| 1003 | - " (MsprofGetPath == nullptr) || (pyptoProfPath != nullptr && pyptoProfPath[0] != '\\0');\n" | 990 | + " const bool pyptoCaptureOn =\n" |
| 1004 | - " if (pyptoProfOn) {\n" | 991 | + " aclrtGetStreamAttribute(stream, ACL_STREAM_ATTR_CACHE_OP_INFO, &pyptoCaptureAttr) " |
| 992 | + "== ACL_SUCCESS &&\n" | ||
| 993 | + " pyptoCaptureAttr.cacheOpInfoSwitch;\n" | ||
| 994 | + " if (pyptoProfOn || pyptoCaptureOn) {\n" | ||
| 1005 | " aclprofTensor pyptoProfTensors[] = {\n" | 995 | " aclprofTensor pyptoProfTensors[] = {\n" |
| 1006 | + "\n".join(tensor_inits) | 996 | + "\n".join(tensor_inits) |
| 1007 | + "\n };\n" | 997 | + "\n };\n" |
| 1008 | " aclprofTensorInfo pyptoProfInfo{};\n" | 998 | " aclprofTensorInfo pyptoProfInfo{};\n" |
| 1009 | - " aclprofEventAttributes pyptoProfAttrs;\n" | ||
| 1010 | " pyptoProfInfo.opNameId = aclprofStr2Id(\"" + op_name + "\");\n" | 999 | " pyptoProfInfo.opNameId = aclprofStr2Id(\"" + op_name + "\");\n" |
| 1011 | " pyptoProfInfo.opTypeId = aclprofStr2Id(\"PyPTO\");\n" | 1000 | " pyptoProfInfo.opTypeId = aclprofStr2Id(\"PyPTO\");\n" |
| 1012 | " pyptoProfInfo.resv = 0;\n" | 1001 | " pyptoProfInfo.resv = 0;\n" |
| 1013 | f" pyptoProfInfo.tensorNum = {len(tensor_inits)};\n" | 1002 | f" pyptoProfInfo.tensorNum = {len(tensor_inits)};\n" |
| 1014 | - " pyptoProfInfo.kernelType = 0;\n" | 1003 | + f" pyptoProfInfo.kernelType = {target.profiler_kernel_type};\n" |
| 1015 | - " pyptoProfInfo.blockNums = blockDim;\n" | 1004 | + f" pyptoProfInfo.blockNums = {block_nums};\n" |
| 1016 | " pyptoProfInfo.stream = stream;\n" | 1005 | " pyptoProfInfo.stream = stream;\n" |
| 1017 | " pyptoProfInfo.tensors = pyptoProfTensors;\n" | 1006 | " pyptoProfInfo.tensors = pyptoProfTensors;\n" |
| 1018 | - " pyptoProfAttrs.version = 1;\n" | 1007 | + " const uint64_t pyptoProfBegin = pypto::BeginCaptureTensorReport(pyptoProfOn);\n", |
| 1019 | - " pyptoProfAttrs.size = sizeof(pyptoProfAttrs.message);\n" | 1008 | + " pypto::ReportCaptureTensorInfo(pyptoProfInfo, pyptoProfBegin, pyptoCaptureOn);\n" |
| 1020 | - " pyptoProfAttrs.messageType = 0;\n" | ||
| 1021 | - " pyptoProfAttrs.message.tensorInfo = &pyptoProfInfo;\n" | ||
| 1022 | - " (void)aclprofRangePushEx(&pyptoProfAttrs);\n" | ||
| 1023 | - " const uint64_t pyptoProfBegin = pypto::BeginCaptureTensorReport(pyptoProfOn, stream);\n", | ||
| 1024 | - " pypto::ReportCaptureTensorInfo(pyptoProfInfo, pyptoProfBegin);\n" | ||
| 1025 | - " (void)aclprofRangePop();\n" | ||
| 1026 | " } else {\n" | 1009 | " } else {\n" |
| 1027 | + " " + launch_stmt | 1010 | + " " + launch_stmt |
| 1028 | + " }\n" | 1011 | + " }\n" |
| @@ -1030,6 +1013,33 @@ def _generate_prof_range_snippet( | |||
| 1030 | ) | 1013 | ) |
| 1031 | 1014 | ||
| 1032 | 1015 | ||
| 1016 | +def _scalar_launch_abi(typ: str, name: str) -> tuple[str, str, str]: | ||
| 1017 | + """Return the physical entry type, host encoding and device decoding for a scalar. | ||
| 1018 | + | ||
| 1019 | + ASC launch metadata can place an int64 dimension four bytes after a narrow | ||
| 1020 | + scalar, while the device loads it at an eight-byte boundary. Give every | ||
| 1021 | + physical argument an eight-byte slot (pointers already have that size). | ||
| 1022 | + The ctypes caller and the device impl retain their original DSL types. | ||
| 1023 | + FP32 travels as bits, preserving signed zero and NaN payloads without FP64 | ||
| 1024 | + arithmetic on the device. | ||
| 1025 | + """ | ||
| 1026 | + if typ in ("int64_t", "uint64_t"): | ||
| 1027 | + return typ, name, name | ||
| 1028 | + if typ == "float": | ||
| 1029 | + return ( | ||
| 1030 | + "uint64_t", | ||
| 1031 | + f"static_cast<uint64_t>(__builtin_bit_cast(uint32_t, {name}))", | ||
| 1032 | + f"__builtin_bit_cast(float, static_cast<uint32_t>({name}))", | ||
| 1033 | + ) | ||
| 1034 | + if typ in ("int8_t", "int16_t", "int32_t"): | ||
| 1035 | + entry_type = "int64_t" | ||
| 1036 | + elif typ in ("bool", "uint8_t", "uint16_t", "uint32_t"): | ||
| 1037 | + entry_type = "uint64_t" | ||
| 1038 | + else: | ||
| 1039 | + raise InvalidType(f"Unsupported scalar launch type '{typ}' for parameter '{name}'") | ||
| 1040 | + return entry_type, f"static_cast<{entry_type}>({name})", f"static_cast<{typ}>({name})" | ||
| 1041 | + | ||
| 1042 | + | ||
| 1033 | def _generate_caller_cpp( | 1043 | def _generate_caller_cpp( |
| 1034 | kernel_params: list[tuple[str, str, bool]], | 1044 | kernel_params: list[tuple[str, str, bool]], |
| 1035 | kernel_cpp_name: str, | 1045 | kernel_cpp_name: str, |
| @@ -1072,7 +1082,7 @@ def _generate_caller_cpp( | |||
| 1072 | kernel_args.append(f"({typ} *){name}") | 1082 | kernel_args.append(f"({typ} *){name}") |
| 1073 | else: | 1083 | else: |
| 1074 | cpp_params.append(f"{typ} {name}") | 1084 | cpp_params.append(f"{typ} {name}") |
| 1075 | - kernel_args.append(name) | 1085 | + kernel_args.append(_scalar_launch_abi(typ, name)[1]) |
| 1076 | sig = ", ".join(["uint32_t blockDim", "void* stream"] + cpp_params) | 1086 | sig = ", ".join(["uint32_t blockDim", "void* stream"] + cpp_params) |
| 1077 | call_args = ", ".join(kernel_args) | 1087 | call_args = ", ".join(kernel_args) |
| 1078 | 1088 | ||
| @@ -1094,7 +1104,7 @@ def _generate_caller_cpp( | |||
| 1094 | if prof_param_specs: | 1104 | if prof_param_specs: |
| 1095 | dims_in_scope = {name for _, name, _is_ptr in kernel_params} | 1105 | dims_in_scope = {name for _, name, _is_ptr in kernel_params} |
| 1096 | prof_include, prof_push, prof_pop = _generate_prof_range_snippet( | 1106 | prof_include, prof_push, prof_pop = _generate_prof_range_snippet( |
| 1097 | - kernel_name, prof_param_specs, dims_in_scope, launch_stmt=launch_stmt | 1107 | + kernel_name, prof_param_specs, dims_in_scope, target=target, launch_stmt=launch_stmt |
| 1098 | ) | 1108 | ) |
| 1099 | 1109 | ||
| 1100 | return ( | 1110 | return ( |
| @@ -1253,21 +1263,27 @@ def _make_jit_paths(out_dir: str) -> CompilePaths: | |||
| 1253 | def _make_global_entry( | 1263 | def _make_global_entry( |
| 1254 | kernel_name: str, | 1264 | kernel_name: str, |
| 1255 | entry_params: list[tuple[str, str, bool]], | 1265 | entry_params: list[tuple[str, str, bool]], |
| 1266 | + *, | ||
| 1267 | + target: KernelTarget, | ||
| 1256 | ) -> str: | 1268 | ) -> str: |
| 1257 | - """Generate the ``__global__`` entry that forwards 1:1 to ``<kernel_name>_impl``. | 1269 | + """Decode eight-byte launch slots into the original ``<kernel_name>_impl`` types.""" |
| 1258 | - | ||
| 1259 | - The entry mirrors the impl signature exactly (same types/names, incl. a trailing | ||
| 1260 | - ffts_addr), so the forward is a plain pass-through. | ||
| 1261 | - """ | ||
| 1262 | decls = [] | 1270 | decls = [] |
| 1263 | args = [] | 1271 | args = [] |
| 1264 | for typ, name, is_ptr in entry_params: | 1272 | for typ, name, is_ptr in entry_params: |
| 1265 | - decls.append(f"__gm__ {typ}* {name}" if is_ptr else f"{typ} {name}") | 1273 | + if is_ptr: |
| 1266 | - args.append(name) | 1274 | + decls.append(f"__gm__ {typ}* {name}") |
| 1275 | + args.append(name) | ||
| 1276 | + else: | ||
| 1277 | + entry_type, _, decoded = _scalar_launch_abi(typ, name) | ||
| 1278 | + decls.append(f"{entry_type} {name}") | ||
| 1279 | + args.append(decoded) | ||
| 1267 | sig = ", ".join(decls) | 1280 | sig = ", ".join(decls) |
| 1268 | call_args = ", ".join(args) | 1281 | call_args = ", ".join(args) |
| 1269 | 1282 | ||
| 1270 | - return f"__global__ AICORE void {kernel_name}({sig})\n{{\n {kernel_name}_impl({call_args});\n}}\n" | 1283 | + return ( |
| 1284 | + f"__global__ {target.entry_qualifier} void {kernel_name}({sig})\n" | ||
| 1285 | + f"{{\n {kernel_name}_impl({call_args});\n}}\n" | ||
| 1286 | + ) | ||
| 1271 | 1287 | ||
| 1272 | 1288 | ||
| 1273 | def _codegen_target_cce( | 1289 | def _codegen_target_cce( |
| @@ -1275,7 +1291,7 @@ def _codegen_target_cce( | |||
| 1275 | arch: str, | 1291 | arch: str, |
| 1276 | build_dir: str, | 1292 | build_dir: str, |
| 1277 | target: ir.SectionKind, | 1293 | target: ir.SectionKind, |
| 1278 | - declared_directions: dict[str, str] | None = None, | 1294 | + declared_directions: dict[int, TensorDirection] | None = None, |
| 1279 | required_dynamic_ub_size: int = 0, | 1295 | required_dynamic_ub_size: int = 0, |
| 1280 | ) -> CodegenResult: | 1296 | ) -> CodegenResult: |
| 1281 | """CCE codegen for one target-specific Program. | 1297 | """CCE codegen for one target-specific Program. |
| @@ -1428,9 +1444,9 @@ def _parse_and_codegen_targets( | |||
| 1428 | ) | 1444 | ) |
| 1429 | requires_simt = requires_simt or kernel_def.requires_simt | 1445 | requires_simt = requires_simt or kernel_def.requires_simt |
| 1430 | max_vec_tile_end = max(max_vec_tile_end, kernel_def.max_vec_tile_end) | 1446 | max_vec_tile_end = max(max_vec_tile_end, kernel_def.max_vec_tile_end) |
| 1431 | - # pl.Input/pl.Output annotation markers (param name -> "in"/"out"); these are | 1447 | + # Tensor directions are keyed by stable source parameter index; unspecified |
| 1432 | - # the sole source of tensor direction — params without a marker default to "in". | 1448 | + # tensor parameters default to TensorDirection.INPUT. |
| 1433 | - declared_directions = dict(kernel_def.last_param_directions) | 1449 | + declared_directions = kernel_def.last_param_directions |
| 1434 | 1450 | ||
| 1435 | if not any(matched.values()): | 1451 | if not any(matched.values()): |
| 1436 | matched = { | 1452 | matched = { |
| @@ -1668,7 +1684,7 @@ def _build_jit_so( | |||
| 1668 | # CCE: kernel.cpp holds only `<name>_impl`; define the __global__ entry that forwards to it. | 1684 | # CCE: kernel.cpp holds only `<name>_impl`; define the __global__ entry that forwards to it. |
| 1669 | global_entry = "" | 1685 | global_entry = "" |
| 1670 | if cg.needs_global_entry: | 1686 | if cg.needs_global_entry: |
| 1671 | - global_entry = _make_global_entry(cg.kernel_name, cg.entry_params) | 1687 | + global_entry = _make_global_entry(cg.kernel_name, cg.entry_params, target=target) |
| 1672 | 1688 | ||
| 1673 | caller_content = _generate_caller_cpp( | 1689 | caller_content = _generate_caller_cpp( |
| 1674 | kernel_params=cg.kernel_params, | 1690 | kernel_params=cg.kernel_params, |
| @@ -29,6 +29,7 @@ from typing import Any, Callable, TypeVar | |||
| 29 | 29 | ||
| 30 | from pypto.pypto_impl import ir | 30 | from pypto.pypto_impl import ir |
| 31 | from pypto_pro.language.parser._ast_parser import ASTParser | 31 | from pypto_pro.language.parser._ast_parser import ASTParser |
| 32 | +from pypto_pro.language.typing.direction import TensorDirection | ||
| 32 | 33 | ||
| 33 | from .._errors import ( | 34 | from .._errors import ( |
| 34 | NameNotFound, | 35 | NameNotFound, |
| @@ -215,9 +216,8 @@ class KernelDef: | |||
| 215 | self._meta_data = meta_data | 216 | self._meta_data = meta_data |
| 216 | self._tilingkey_consts = tilingkey_consts | 217 | self._tilingkey_consts = tilingkey_consts |
| 217 | self._datatype_consts = datatype_consts | 218 | self._datatype_consts = datatype_consts |
| 218 | - # Populated by parse_target_program: param name -> "in"/"out" from | 219 | + # Populated by parse_target_program: parameter index -> declared direction. |
| 219 | - # pl.Input/pl.Output annotation markers. | 220 | + self._last_param_directions: dict[int, TensorDirection] = {} |
| 220 | - self._last_param_directions: dict[str, str] = {} | ||
| 221 | self._max_vec_tile_end = 0 | 221 | self._max_vec_tile_end = 0 |
| 222 | self._requires_simt = False | 222 | self._requires_simt = False |
| 223 | 223 | ||
| @@ -234,8 +234,8 @@ class KernelDef: | |||
| 234 | return self._func.__name__ | 234 | return self._func.__name__ |
| 235 | 235 | ||
| 236 | @property | 236 | @property |
| 237 | - def last_param_directions(self) -> dict[str, str]: | 237 | + def last_param_directions(self) -> dict[int, TensorDirection]: |
| 238 | - """Direction markers from the most recent parse_target_program call.""" | 238 | + """Directions from the most recent parse_target_program call.""" |
| 239 | return dict(self._last_param_directions) | 239 | return dict(self._last_param_directions) |
| 240 | 240 | ||
| 241 | @property | 241 | @property |
| @@ -332,9 +332,9 @@ class KernelDef: | |||
| 332 | program = ir.Program( | 332 | program = ir.Program( |
| 333 | external_funcs + [ir_func], program_name, program_span, parser.debug_info | 333 | external_funcs + [ir_func], program_name, program_span, parser.debug_info |
| 334 | ) | 334 | ) |
| 335 | - # Direction markers (pl.Input/pl.Output) parsed off the annotations; | 335 | + # Tensor directions are resolved with parameter types and keyed by |
| 336 | - # consumed by the JIT caller for profiling tensor type. | 336 | + # stable parameter index for JIT profiling metadata. |
| 337 | - self._last_param_directions = dict(parser.param_directions) | 337 | + self._last_param_directions = dict(parser.type_resolver.param_directions) |
| 338 | self._max_vec_tile_end = parser.max_vec_tile_end | 338 | self._max_vec_tile_end = parser.max_vec_tile_end |
| 339 | self._requires_simt = parser.requires_simt | 339 | self._requires_simt = parser.requires_simt |
| 340 | return program, parser.matched_target | 340 | return program, parser.matched_target |
| @@ -0,0 +1,93 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""Check scalar values and following pointers/dimensions across the actual ASC launch ABI.""" | ||
| 10 | + | ||
| 11 | +import os | ||
| 12 | +import struct | ||
| 13 | + | ||
| 14 | +import pypto_pro.language as pl | ||
| 15 | +import pytest | ||
| 16 | +import torch | ||
| 17 | +import torch_npu # noqa: F401 -- registers torch.npu | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +@pl.jit() | ||
| 21 | +def scalar_launch_abi_kernel( | ||
| 22 | + flag: pl.DT_BOOL, | ||
| 23 | + x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP32], | ||
| 24 | + s8: pl.DT_INT8, | ||
| 25 | + u8: pl.DT_UINT8, | ||
| 26 | + s16: pl.DT_INT16, | ||
| 27 | + u16: pl.DT_UINT16, | ||
| 28 | + s32: pl.DT_INT32, | ||
| 29 | + u32: pl.DT_UINT32, | ||
| 30 | + value: pl.DT_FP32, | ||
| 31 | + s64: pl.DT_INT64, | ||
| 32 | + u64: pl.DT_UINT64, | ||
| 33 | + out: pl.Tensor[[10], pl.DT_INT64], | ||
| 34 | + real_out: pl.Tensor[[1], pl.DT_FP32], | ||
| 35 | + unsigned_out: pl.Tensor[[1], pl.DT_UINT64], | ||
| 36 | +): | ||
| 37 | + with pl.section_vector(): | ||
| 38 | + pl.setval(out, 0, flag) | ||
| 39 | + pl.setval(out, 1, s8) | ||
| 40 | + pl.setval(out, 2, u8) | ||
| 41 | + pl.setval(out, 3, s16) | ||
| 42 | + pl.setval(out, 4, u16) | ||
| 43 | + pl.setval(out, 5, s32) | ||
| 44 | + pl.setval(out, 6, u32) | ||
| 45 | + pl.setval(out, 7, s64) | ||
| 46 | + pl.setval(out, 8, x.shape[0]) | ||
| 47 | + pl.setval(out, 9, x.shape[1]) | ||
| 48 | + pl.setval(real_out, 0, value) | ||
| 49 | + pl.setval(unsigned_out, 0, u64) | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +@pytest.mark.soc("950") | ||
| 53 | +@pytest.mark.parametrize("capture", [False, True], ids=["eager", "graph"]) | ||
| 54 | +@pytest.mark.parametrize("upper,shape,float_bits", [ | ||
| 55 | + (False, (65, 96), 0x80000000), | ||
| 56 | + (True, (129, 33), 0x7FC12345), | ||
| 57 | + (False, (33, 129), 0xBFA00000), | ||
| 58 | +]) | ||
| 59 | +def test_scalar_launch_abi(capture, upper, shape, float_bits): | ||
| 60 | + torch.npu.set_device(int(os.environ.get("TILE_FWK_DEVICE_ID", "0"))) | ||
| 61 | + x = torch.zeros(shape, dtype=torch.float32, device="npu") | ||
| 62 | + out = torch.full((10,), -17, dtype=torch.int64, device="npu") | ||
| 63 | + real_out = torch.full((1,), -17, dtype=torch.float32, device="npu") | ||
| 64 | + unsigned_out = torch.tensor([17], dtype=torch.uint64).npu() | ||
| 65 | + signed = [(1 << (bits - 1)) - 1 if upper else -(1 << (bits - 1)) for bits in (8, 16, 32, 64)] | ||
| 66 | + unsigned = [(1 << bits) - 1 if upper else 0 for bits in (8, 16, 32, 64)] | ||
| 67 | + value = struct.unpack("f", struct.pack("I", float_bits))[0] | ||
| 68 | + args = (upper, x, signed[0], unsigned[0], signed[1], unsigned[1], signed[2], unsigned[2], | ||
| 69 | + value, signed[3], unsigned[3], out, real_out, unsigned_out) | ||
| 70 | + expected = [int(upper), signed[0], unsigned[0], signed[1], unsigned[1], signed[2], unsigned[2], | ||
| 71 | + signed[3], *shape] | ||
| 72 | + | ||
| 73 | + def check(): | ||
| 74 | + torch.npu.synchronize() | ||
| 75 | + assert out.cpu().tolist() == expected | ||
| 76 | + assert real_out.cpu().view(torch.uint32).item() == float_bits | ||
| 77 | + assert unsigned_out.cpu().item() == unsigned[3] | ||
| 78 | + | ||
| 79 | + scalar_launch_abi_kernel[1](*args) | ||
| 80 | + check() | ||
| 81 | + if capture: | ||
| 82 | + stream = torch.npu.Stream() | ||
| 83 | + graph = torch.npu.NPUGraph() | ||
| 84 | + with torch.npu.graph(graph, stream=stream): | ||
| 85 | + scalar_launch_abi_kernel[1](*args) | ||
| 86 | + for _ in range(2): | ||
| 87 | + # A warmup or prior replay must not conceal a missing graph write. | ||
| 88 | + out.fill_(-17) | ||
| 89 | + real_out.fill_(-17) | ||
| 90 | + unsigned_out.copy_(torch.tensor([17], dtype=torch.uint64)) | ||
| 91 | + torch.npu.synchronize() | ||
| 92 | + graph.replay() | ||
| 93 | + check() | ||
| @@ -10,20 +10,25 @@ | |||
| 10 | # See LICENSE in the root of the software repository for the full text of the License. | 10 | # See LICENSE in the root of the software repository for the full text of the License. |
| 11 | # ----------------------------------------------------------------------------------------------------------- | 11 | # ----------------------------------------------------------------------------------------------------------- |
| 12 | 12 | ||
| 13 | -"""Collect one PyPTO trace and validate both kernel details and trace events.""" | 13 | +"""Validate core type and tensors for eager and captured PyPTO launches.""" |
| 14 | 14 | ||
| 15 | import csv | 15 | import csv |
| 16 | +import ctypes | ||
| 16 | import glob | 17 | import glob |
| 18 | +import importlib | ||
| 17 | import json | 19 | import json |
| 18 | import logging | 20 | import logging |
| 19 | import os | 21 | import os |
| 20 | import sys | 22 | import sys |
| 23 | +import time | ||
| 21 | 24 | ||
| 22 | import pypto_pro.language as pl | 25 | import pypto_pro.language as pl |
| 23 | import pytest | 26 | import pytest |
| 24 | import torch | 27 | import torch |
| 25 | import torch_npu | 28 | import torch_npu |
| 26 | 29 | ||
| 30 | +import pypto | ||
| 31 | + | ||
| 27 | ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | 32 | ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) |
| 28 | ST_DEVICE = f"npu:{ST_DEVICE_ID}" | 33 | ST_DEVICE = f"npu:{ST_DEVICE_ID}" |
| 29 | 34 | ||
| @@ -50,9 +55,35 @@ def _build_experimental_config(): | |||
| 50 | export_type=[torch_npu.profiler.ExportType.Text], | 55 | export_type=[torch_npu.profiler.ExportType.Text], |
| 51 | profiler_level=torch_npu.profiler.ProfilerLevel.Level1, | 56 | profiler_level=torch_npu.profiler.ProfilerLevel.Level1, |
| 52 | aic_metrics=torch_npu.profiler.AiCMetrics.PipeUtilization, | 57 | aic_metrics=torch_npu.profiler.AiCMetrics.PipeUtilization, |
| 58 | + data_simplification=False, | ||
| 59 | + op_attr=True, | ||
| 53 | ) | 60 | ) |
| 54 | 61 | ||
| 55 | 62 | ||
| 63 | +def _kernel_rows(output_dir, kernel_name): | ||
| 64 | + """Check both the PyTorch export and the underlying CANN op summary.""" | ||
| 65 | + for pattern in ("kernel_details.csv", "op_summary_*.csv"): | ||
| 66 | + # Some toolkit builds analyze profiler output in a background process that | ||
| 67 | + # may still be running when the context manager exits; the first profiling | ||
| 68 | + # test in the suite is the most exposed to this cold-start delay. | ||
| 69 | + files = glob.glob(os.path.join(output_dir, "**", pattern), recursive=True) | ||
| 70 | + for _ in range(60): | ||
| 71 | + if files: | ||
| 72 | + break | ||
| 73 | + time.sleep(0.5) | ||
| 74 | + files = glob.glob(os.path.join(output_dir, "**", pattern), recursive=True) | ||
| 75 | + assert files, f"No {pattern} under {output_dir}" | ||
| 76 | + matches = [] | ||
| 77 | + for csv_file in files: | ||
| 78 | + with open(csv_file, "r", encoding="utf-8", newline="") as stream: | ||
| 79 | + for row in csv.DictReader(stream): | ||
| 80 | + if any(kernel_name in row.get(column, "") for column in ("Type", "Name", "OP Type", "Op Name")): | ||
| 81 | + matches.append(row) | ||
| 82 | + assert matches, f"No {kernel_name} record in {files}" | ||
| 83 | + logging.info("PyPTO %s: %s", pattern, matches) | ||
| 84 | + yield matches | ||
| 85 | + | ||
| 86 | + | ||
| 56 | # ============================================================================= | 87 | # ============================================================================= |
| 57 | # 被采集的 kernel — 简单 add 操作 | 88 | # 被采集的 kernel — 简单 add 操作 |
| 58 | # ============================================================================= | 89 | # ============================================================================= |
| @@ -60,7 +91,7 @@ def _build_experimental_config(): | |||
| 60 | def prof_add_kernel( | 91 | def prof_add_kernel( |
| 61 | a: pl.Tensor[[64, 64], pl.DT_FP32], | 92 | a: pl.Tensor[[64, 64], pl.DT_FP32], |
| 62 | b: pl.Tensor[[64, 64], pl.DT_FP32], | 93 | b: pl.Tensor[[64, 64], pl.DT_FP32], |
| 63 | - out: pl.Tensor[[64, 64], pl.DT_FP32], | 94 | + out: pl.Tensor[[64, 64], pl.DT_FP32, pl.Output], |
| 64 | ): | 95 | ): |
| 65 | tt = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) | 96 | tt = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 66 | ta = pl.make_tile(tt, addr=0x0000) | 97 | ta = pl.make_tile(tt, addr=0x0000) |
| @@ -77,21 +108,60 @@ def prof_add_kernel( | |||
| 77 | pl.store(out, tc, [0, 0]) | 108 | pl.store(out, tc, [0, 0]) |
| 78 | 109 | ||
| 79 | 110 | ||
| 80 | -@pytest.mark.soc("950") | 111 | +@pl.jit() |
| 81 | -def test_profiler_api_outputs(tmp_path): | 112 | +def prof_cube_kernel(out: pl.Tensor[[32], pl.DT_INT32, pl.Output]): |
| 82 | - """One real collection supplies kernel_details.csv and a nonempty JSON trace. | 113 | + with pl.section_cube(): |
| 114 | + out[0] = pl.get_block_num() | ||
| 83 | 115 | ||
| 84 | - Warm up the JIT before opening the profiler, then capture one completed launch. | 116 | + |
| 85 | - The CSV still identifies the custom kernel; the trace must contain valid events. | 117 | +@pl.jit() |
| 86 | - """ | 118 | +def prof_mixed_kernel( |
| 119 | + cube: pl.Tensor[[32], pl.DT_INT32, pl.Output], | ||
| 120 | + vector: pl.Tensor[[64], pl.DT_INT32, pl.Output], | ||
| 121 | +): | ||
| 122 | + with pl.section_cube(): | ||
| 123 | + cube[0] = pl.get_block_num() | ||
| 124 | + with pl.section_vector(): | ||
| 125 | + vector[pl.get_block_idx() * 32] = pl.get_subblock_num() | ||
| 126 | + | ||
| 127 | + | ||
| 128 | +def _case(kind): | ||
| 129 | + """Reference values also verify which engines and subblocks actually ran.""" | ||
| 130 | + if kind == "vector": | ||
| 131 | + x = torch.randn(64, 64, device=ST_DEVICE, dtype=torch.float32) | ||
| 132 | + y = torch.randn_like(x) | ||
| 133 | + z = torch.zeros_like(x) | ||
| 134 | + return prof_add_kernel, (x, y, z), (z,), (x + y,), "AI_VECTOR_CORE", "64,64" | ||
| 135 | + cube = torch.zeros(32, dtype=torch.int32, device=ST_DEVICE) | ||
| 136 | + expected_cube = torch.zeros_like(cube) | ||
| 137 | + expected_cube[0] = 1 | ||
| 138 | + if kind == "cube": | ||
| 139 | + return prof_cube_kernel, (cube,), (cube,), (expected_cube,), "AI_CORE", "32" | ||
| 140 | + vector = torch.zeros(64, dtype=torch.int32, device=ST_DEVICE) | ||
| 141 | + expected_vector = torch.zeros_like(vector) | ||
| 142 | + expected_vector[::32] = 2 | ||
| 143 | + return ( | ||
| 144 | + prof_mixed_kernel, (cube, vector), (cube, vector), (expected_cube, expected_vector), "MIX_AIC", "32;64" | ||
| 145 | + ) | ||
| 146 | + | ||
| 147 | + | ||
| 148 | +@pytest.mark.soc("950") | ||
| 149 | +@pytest.mark.skip(reason="parallel read/write") | ||
| 150 | +@pytest.mark.parametrize("kind", ["cube", "vector", "mixed"]) | ||
| 151 | +@pytest.mark.parametrize("mode", ["graph_before_collection", "eager", "graph"]) | ||
| 152 | +@pypto.options(pass_options={"enable_slice": False}) | ||
| 153 | +def test_profiler_api_outputs(tmp_path, kind, mode): | ||
| 154 | + """Check exported tensors and core types, including graphs captured before collection.""" | ||
| 87 | _check_npu() | 155 | _check_npu() |
| 88 | output_dir = str(tmp_path / "profiling_output") | 156 | output_dir = str(tmp_path / "profiling_output") |
| 89 | - x = torch.randn(64, 64, device=ST_DEVICE, dtype=torch.float32) | 157 | + kernel, args, outputs, expected, core_type, output_shapes = _case(kind) |
| 90 | - y = torch.randn(64, 64, device=ST_DEVICE, dtype=torch.float32) | 158 | + kernel[1](*args) |
| 91 | - z = torch.zeros(64, 64, device=ST_DEVICE, dtype=torch.float32) | 159 | + torch.npu.synchronize() |
| 92 | - prof_add_kernel(x, y, z) | 160 | + skip_first = 2 if mode == "graph_before_collection" else 0 |
| 161 | + for actual, reference in zip(outputs, expected): | ||
| 162 | + torch.testing.assert_close(actual, reference) | ||
| 163 | + actual.zero_() | ||
| 93 | torch.npu.synchronize() | 164 | torch.npu.synchronize() |
| 94 | - torch.testing.assert_close(z, x + y) | ||
| 95 | 165 | ||
| 96 | with torch_npu.profiler.profile( | 166 | with torch_npu.profiler.profile( |
| 97 | activities=[torch_npu.profiler.ProfilerActivity.NPU], | 167 | activities=[torch_npu.profiler.ProfilerActivity.NPU], |
| @@ -99,28 +169,49 @@ def test_profiler_api_outputs(tmp_path): | |||
| 99 | record_shapes=False, | 169 | record_shapes=False, |
| 100 | profile_memory=True, | 170 | profile_memory=True, |
| 101 | experimental_config=_build_experimental_config(), | 171 | experimental_config=_build_experimental_config(), |
| 102 | - schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1), | 172 | + schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1, skip_first=skip_first), |
| 103 | on_trace_ready=torch_npu.profiler.tensorboard_trace_handler(output_dir, analyse_flag=True), | 173 | on_trace_ready=torch_npu.profiler.tensorboard_trace_handler(output_dir, analyse_flag=True), |
| 104 | ) as prof: | 174 | ) as prof: |
| 105 | - prof_add_kernel(x, y, z) | 175 | + for step in range(skip_first + 1): |
| 106 | - torch.npu.synchronize() | 176 | + if mode == "eager": |
| 107 | - prof.step() | 177 | + kernel[1](*args) |
| 108 | - torch.testing.assert_close(z, x + y) | 178 | + else: |
| 179 | + if step == 0: | ||
| 180 | + graph = torch.npu.NPUGraph() | ||
| 181 | + with torch.npu.graph(graph): | ||
| 182 | + kernel[1](*args) | ||
| 183 | + graph.replay() | ||
| 184 | + torch.npu.synchronize() | ||
| 185 | + if step < skip_first: | ||
| 186 | + for actual in outputs: | ||
| 187 | + actual.zero_() | ||
| 188 | + torch.npu.synchronize() | ||
| 189 | + prof.step() | ||
| 190 | + for actual, reference in zip(outputs, expected): | ||
| 191 | + torch.testing.assert_close(actual, reference) | ||
| 109 | 192 | ||
| 110 | - kernel_detail_files = glob.glob(os.path.join(output_dir, "**", "kernel_details.csv"), recursive=True) | 193 | + output_dtypes = {"vector": "FLOAT", "cube": "INT32", "mixed": "INT32;INT32"}[kind] |
| 111 | - assert kernel_detail_files, f"No kernel_details.csv under {output_dir}" | 194 | + for matches in _kernel_rows(output_dir, kernel.__name__): |
| 112 | - matches = [] | 195 | + assert len(matches) == 1, matches |
| 113 | - for csv_file in kernel_detail_files: | 196 | + for row in matches: |
| 114 | - with open(csv_file, "r", encoding="utf-8", newline="") as stream: | 197 | + assert row.get("Accelerator Core", row.get("Task Type")) == core_type, row |
| 115 | - for row in csv.DictReader(stream): | 198 | + assert row["Block Num"] == "1", row |
| 116 | - if any("prof_add_kernel" in row.get(column, "") for column in ("Type", "Name")): | 199 | + assert row["Mix Block Num"] == ("2" if kind == "mixed" else "0"), row |
| 117 | - matches.append(row) | 200 | + assert row["Output Shapes"].strip('"') == output_shapes, row |
| 118 | - assert matches, f"No prof_add_kernel record in {kernel_detail_files}" | 201 | + assert row["Output Data Types"] == output_dtypes, row |
| 119 | - logging.info("PyPTO kernel details: %s", matches) | 202 | + if kind == "vector": |
| 203 | + assert row["Input Shapes"].strip('"') == "64,64;64,64", row | ||
| 120 | 204 | ||
| 121 | trace_files = glob.glob(os.path.join(output_dir, "**", "trace_view.json"), recursive=True) | 205 | trace_files = glob.glob(os.path.join(output_dir, "**", "trace_view.json"), recursive=True) |
| 122 | if not trace_files: | 206 | if not trace_files: |
| 123 | trace_files = glob.glob(os.path.join(output_dir, "**", "trace_result.json"), recursive=True) | 207 | trace_files = glob.glob(os.path.join(output_dir, "**", "trace_result.json"), recursive=True) |
| 208 | + for _ in range(20): | ||
| 209 | + if trace_files: | ||
| 210 | + break | ||
| 211 | + time.sleep(0.5) | ||
| 212 | + trace_files = glob.glob(os.path.join(output_dir, "**", "trace_view.json"), recursive=True) | ||
| 213 | + if not trace_files: | ||
| 214 | + trace_files = glob.glob(os.path.join(output_dir, "**", "trace_result.json"), recursive=True) | ||
| 124 | assert trace_files, f"No trace_view.json or trace_result.json under {output_dir}" | 215 | assert trace_files, f"No trace_view.json or trace_result.json under {output_dir}" |
| 125 | for trace_file in trace_files: | 216 | for trace_file in trace_files: |
| 126 | with open(trace_file, "r", encoding="utf-8") as stream: | 217 | with open(trace_file, "r", encoding="utf-8") as stream: |
| @@ -130,5 +221,117 @@ def test_profiler_api_outputs(tmp_path): | |||
| 130 | logging.info("Trace file: %s, events=%d", trace_file, len(events)) | 221 | logging.info("Trace file: %s, events=%d", trace_file, len(events)) |
| 131 | 222 | ||
| 132 | 223 | ||
| 224 | +@pytest.mark.soc("950") | ||
| 225 | +@pytest.mark.parametrize("warm_kernel", [False, True], ids=["loaded_during_collection", "loaded_before_collection"]) | ||
| 226 | +def test_tensor_reports_stop_with_collection(tmp_path, monkeypatch, warm_kernel): | ||
| 227 | + """Count reporting before/during/after collection, including loading a library while profiling.""" | ||
| 228 | + _check_npu() | ||
| 229 | + monkeypatch.setenv("ASCEND_WORK_PATH", str(tmp_path)) | ||
| 230 | + jit = importlib.import_module("pypto_pro.runtime.jit") | ||
| 231 | + generate = jit._generate_caller_cpp | ||
| 232 | + | ||
| 233 | + def instrument(*args, **kwargs): | ||
| 234 | + source = generate(*args, **kwargs) | ||
| 235 | + assert "aclprofRange" not in source | ||
| 236 | + source = source.replace( | ||
| 237 | + "pypto::ReportCaptureTensorInfo(", | ||
| 238 | + "pyptoTestReports += pyptoProfBegin != 0;\n" | ||
| 239 | + " pyptoTestCaches += pyptoCaptureOn;\n" | ||
| 240 | + " pypto::ReportCaptureTensorInfo(", | ||
| 241 | + ) | ||
| 242 | + return ( | ||
| 243 | + "static unsigned pyptoTestReports = 0, pyptoTestCaches = 0;\n" | ||
| 244 | + 'extern "C" unsigned pypto_test_reports(bool live) { return live ? pyptoTestReports : pyptoTestCaches; }\n' | ||
| 245 | + + source | ||
| 246 | + ) | ||
| 247 | + | ||
| 248 | + monkeypatch.setattr(jit, "_generate_caller_cpp", instrument) | ||
| 249 | + | ||
| 250 | + @pl.jit() | ||
| 251 | + def switch_kernel(out: pl.Tensor[[32], pl.DT_INT32, pl.Output]): | ||
| 252 | + with pl.section_cube(): | ||
| 253 | + out[0] = 3 | ||
| 254 | + | ||
| 255 | + out = torch.zeros(32, dtype=torch.int32, device=ST_DEVICE) | ||
| 256 | + expected = torch.zeros_like(out) | ||
| 257 | + expected[0] = 3 | ||
| 258 | + | ||
| 259 | + def launch(): | ||
| 260 | + out.zero_() | ||
| 261 | + switch_kernel(out) | ||
| 262 | + torch.npu.synchronize() | ||
| 263 | + torch.testing.assert_close(out, expected, rtol=0, atol=0) | ||
| 264 | + | ||
| 265 | + def counts(): | ||
| 266 | + compiled, = switch_kernel._compiled_by_signature.values() | ||
| 267 | + counter = compiled.entry.lib.pypto_test_reports | ||
| 268 | + counter.argtypes = [ctypes.c_bool] | ||
| 269 | + counter.restype = ctypes.c_uint | ||
| 270 | + return counter(True), counter(False) | ||
| 271 | + | ||
| 272 | + if warm_kernel: | ||
| 273 | + launch() | ||
| 274 | + assert counts() == (0, 0) | ||
| 275 | + | ||
| 276 | + for session in range(2): | ||
| 277 | + with torch_npu.profiler.profile( | ||
| 278 | + activities=[torch_npu.profiler.ProfilerActivity.NPU], | ||
| 279 | + experimental_config=_build_experimental_config(), | ||
| 280 | + schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1), | ||
| 281 | + on_trace_ready=torch_npu.profiler.tensorboard_trace_handler(str(tmp_path / f"profile_{session}")), | ||
| 282 | + ) as prof: | ||
| 283 | + launch() | ||
| 284 | + assert counts() == (session + 1, 0) | ||
| 285 | + prof.step() | ||
| 286 | + launch() | ||
| 287 | + assert counts() == (session + 1, 0), "Tensor reports continued after collection stopped" | ||
| 288 | + | ||
| 289 | + | ||
| 290 | +@pytest.mark.soc("950") | ||
| 291 | +@pytest.mark.skip(reason="parallel read/write") | ||
| 292 | +def test_graph_replay_preserves_each_launch_shape(tmp_path): | ||
| 293 | + """Two tasks of one dynamic kernel retain distinct shapes across profiled replays.""" | ||
| 294 | + _check_npu() | ||
| 295 | + | ||
| 296 | + @pl.jit() | ||
| 297 | + def shape_kernel(out: pl.Tensor[[pl.DYNAMIC], pl.DT_INT32, pl.Output]): | ||
| 298 | + with pl.section_cube(): | ||
| 299 | + out[0] = out.shape[0] | ||
| 300 | + | ||
| 301 | + outputs = [torch.zeros(n, dtype=torch.int32, device=ST_DEVICE) for n in (32, 64)] | ||
| 302 | + for out in outputs: | ||
| 303 | + shape_kernel(out) | ||
| 304 | + torch.npu.synchronize() | ||
| 305 | + output_dir = str(tmp_path / "profiling_output") | ||
| 306 | + with torch_npu.profiler.profile( | ||
| 307 | + activities=[torch_npu.profiler.ProfilerActivity.NPU], | ||
| 308 | + record_shapes=False, | ||
| 309 | + experimental_config=_build_experimental_config(), | ||
| 310 | + schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=2, repeat=1, skip_first=2), | ||
| 311 | + on_trace_ready=torch_npu.profiler.tensorboard_trace_handler(output_dir), | ||
| 312 | + ) as prof: | ||
| 313 | + for step in range(4): | ||
| 314 | + for out in outputs: | ||
| 315 | + out.zero_() | ||
| 316 | + torch.npu.synchronize() | ||
| 317 | + if step == 0: | ||
| 318 | + graph = torch.npu.NPUGraph() | ||
| 319 | + with torch.npu.graph(graph): | ||
| 320 | + for out in outputs: | ||
| 321 | + shape_kernel(out) | ||
| 322 | + graph.replay() | ||
| 323 | + torch.npu.synchronize() | ||
| 324 | + for out in outputs: | ||
| 325 | + expected = torch.zeros_like(out) | ||
| 326 | + expected[0] = out.numel() | ||
| 327 | + torch.testing.assert_close(out, expected, rtol=0, atol=0) | ||
| 328 | + prof.step() | ||
| 329 | + for matches in _kernel_rows(output_dir, shape_kernel.__name__): | ||
| 330 | + assert sorted(row["Output Shapes"].strip('"') for row in matches) == ["32", "32", "64", "64"] | ||
| 331 | + assert {row["Output Data Types"] for row in matches} == {"INT32"} | ||
| 332 | + assert {row["Output Formats"] for row in matches} == {"ND"} | ||
| 333 | + assert len({(row["Stream ID"], row["Task ID"]) for row in matches}) == 2 | ||
| 334 | + | ||
| 335 | + | ||
| 133 | if __name__ == "__main__": | 336 | if __name__ == "__main__": |
| 134 | sys.exit(pytest.main([__file__, "-q", "-s"])) | 337 | sys.exit(pytest.main([__file__, "-q", "-s"])) |
| @@ -14,10 +14,11 @@ from __future__ import annotations | |||
| 14 | # DSL function bodies are parsed as AST, not executed -suppress pyright errors | 14 | # DSL function bodies are parsed as AST, not executed -suppress pyright errors |
| 15 | # from type-checking the annotations and kwargs inside parsed DSL bodies. | 15 | # from type-checking the annotations and kwargs inside parsed DSL bodies. |
| 16 | import ast | 16 | import ast |
| 17 | +from enum import Enum | ||
| 17 | from typing import TYPE_CHECKING, Any | 18 | from typing import TYPE_CHECKING, Any |
| 18 | 19 | ||
| 19 | from pypto_pro import DataType, ir | 20 | from pypto_pro import DataType, ir |
| 20 | -from pypto_pro._errors import InvalidArgument, InvalidType, NotSupported | 21 | +from pypto_pro._errors import InvalidArgument, InvalidFormat, InvalidType, NotSupported |
| 21 | import pypto_pro.language as pl | 22 | import pypto_pro.language as pl |
| 22 | from pypto_pro.language.parser._expr_evaluator import ExprEvaluator | 23 | from pypto_pro.language.parser._expr_evaluator import ExprEvaluator |
| 23 | from pypto_pro.language.parser._type_resolver import TypeResolver | 24 | from pypto_pro.language.parser._type_resolver import TypeResolver |
| @@ -45,6 +46,93 @@ def test_language_exports_only_dt_dtype_constants(): | |||
| 45 | assert not hasattr(pl, "BOOL") | 46 | assert not hasattr(pl, "BOOL") |
| 46 | 47 | ||
| 47 | 48 | ||
| 49 | +def test_input_and_output_are_public_enum_values(): | ||
| 50 | + assert isinstance(pl.Input, Enum) | ||
| 51 | + assert isinstance(pl.Output, Enum) | ||
| 52 | + assert pl.Input.value == 0 | ||
| 53 | + assert pl.Output.value == 1 | ||
| 54 | + assert type(pl.Input) is type(pl.Output) | ||
| 55 | + assert not hasattr(pl, "TensorDirection") | ||
| 56 | + | ||
| 57 | + for annotation in ( | ||
| 58 | + pl.Tensor[[64], pl.DT_FP32, pl.Output], | ||
| 59 | + pl.Tensor([64], pl.DT_FP32, pl.Output), | ||
| 60 | + ): | ||
| 61 | + assert isinstance(annotation, pl.Tensor) | ||
| 62 | + assert not hasattr(annotation, "direction") | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +@pytest.mark.parametrize( | ||
| 66 | + "code", | ||
| 67 | + [ | ||
| 68 | + "pl.Tensor[[64], pl.DT_FP32, pl.Output, pl.ND, " | ||
| 69 | + "pl.MemRef(pl.MemorySpace.DDR, 0, 1024, 0)]", | ||
| 70 | + "pl.Tensor[[64], pl.DT_FP32, pl.ND, pl.Output, " | ||
| 71 | + "pl.MemRef(pl.MemorySpace.DDR, 0, 1024, 0)]", | ||
| 72 | + "pl.Tensor[[64], pl.DT_FP32, pl.ND, pl.MemRef(pl.MemorySpace.DDR, 0, 1024, 0), " | ||
| 73 | + "pl.Output]", | ||
| 74 | + ], | ||
| 75 | +) | ||
| 76 | +def test_tensor_direction_accepts_any_optional_position_after_dtype(code): | ||
| 77 | + resolver = _make_resolver({"pl": pl}) | ||
| 78 | + node = ast.parse(code, mode="eval").body | ||
| 79 | + | ||
| 80 | + result = resolver.resolve_param_type(node, parameter_name="out", parameter_index=3) | ||
| 81 | + | ||
| 82 | + assert isinstance(result, ir.TensorType) | ||
| 83 | + assert result.memref is not None | ||
| 84 | + assert result.tensor_view.layout == ir.TensorLayout.ND | ||
| 85 | + assert resolver.param_directions == {3: pl.Output} | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +def test_call_style_tensor_direction_is_recorded_by_parameter_index(): | ||
| 89 | + resolver = _make_resolver({"pl": pl}) | ||
| 90 | + node = ast.parse( | ||
| 91 | + "pl.Tensor([64], pl.DT_FP32, pl.Output)", | ||
| 92 | + mode="eval", | ||
| 93 | + ).body | ||
| 94 | + | ||
| 95 | + result = resolver.resolve_param_type(node, parameter_name="out", parameter_index=2) | ||
| 96 | + | ||
| 97 | + assert isinstance(result, ir.TensorType) | ||
| 98 | + assert resolver.param_directions == {2: pl.Output} | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +@pytest.mark.parametrize("direction", ["input", "output", "in", "out"]) | ||
| 102 | +def test_call_style_tensor_direction_rejects_strings(direction): | ||
| 103 | + resolver = _make_resolver({"pl": pl}) | ||
| 104 | + node = ast.parse( | ||
| 105 | + f"pl.Tensor([64], pl.DT_FP32, {direction!r})", | ||
| 106 | + mode="eval", | ||
| 107 | + ).body | ||
| 108 | + | ||
| 109 | + with pytest.raises(InvalidType, match="must be pl.Input or pl.Output"): | ||
| 110 | + resolver.resolve_param_type(node, parameter_name="tensor", parameter_index=0) | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +@pytest.mark.parametrize("direction", ["input", "output", "in", "out"]) | ||
| 114 | +def test_tensor_direction_rejects_strings(direction): | ||
| 115 | + resolver = _make_resolver({"pl": pl}) | ||
| 116 | + node = ast.parse( | ||
| 117 | + f"pl.Tensor[[64], pl.DT_FP32, {direction!r}]", | ||
| 118 | + mode="eval", | ||
| 119 | + ).body | ||
| 120 | + | ||
| 121 | + with pytest.raises(InvalidFormat): | ||
| 122 | + resolver.resolve_param_type(node, parameter_name="tensor", parameter_index=0) | ||
| 123 | + | ||
| 124 | + | ||
| 125 | +def test_tensor_direction_rejects_duplicate_values(): | ||
| 126 | + resolver = _make_resolver({"pl": pl}) | ||
| 127 | + node = ast.parse( | ||
| 128 | + "pl.Tensor[[64], pl.DT_FP32, pl.Input, pl.Output]", | ||
| 129 | + mode="eval", | ||
| 130 | + ).body | ||
| 131 | + | ||
| 132 | + with pytest.raises(InvalidArgument, match="Tensor direction can be specified only once"): | ||
| 133 | + resolver.resolve_param_type(node, parameter_name="out", parameter_index=0) | ||
| 134 | + | ||
| 135 | + | ||
| 48 | def test_resolve_tensor_type_subscript(): | 136 | def test_resolve_tensor_type_subscript(): |
| 49 | """Test resolving tensor type with subscript notation.""" | 137 | """Test resolving tensor type with subscript notation.""" |
| 50 | resolver = _make_resolver() | 138 | resolver = _make_resolver() |
| @@ -14,6 +14,7 @@ from pathlib import Path | |||
| 14 | from unittest.mock import MagicMock | 14 | from unittest.mock import MagicMock |
| 15 | 15 | ||
| 16 | from pypto_pro._errors import InvalidVal, RuntimeFailure | 16 | from pypto_pro._errors import InvalidVal, RuntimeFailure |
| 17 | +import pypto_pro.language as pl | ||
| 17 | from pypto_pro.runtime.compile_config import JitCompileConfig, KernelTarget, get_jit_compile_config | 18 | from pypto_pro.runtime.compile_config import JitCompileConfig, KernelTarget, get_jit_compile_config |
| 18 | import pytest | 19 | import pytest |
| 19 | 20 | ||
| @@ -34,31 +35,45 @@ def future_config(): | |||
| 34 | ) | 35 | ) |
| 35 | 36 | ||
| 36 | 37 | ||
| 37 | -@pytest.mark.parametrize("arch,prefix,memory", [ | 38 | +@pytest.mark.parametrize("arch,npu_arch,memory", [ |
| 38 | - ("a2", "dav-c220", "-DMEMORY_BASE"), | 39 | + ("a2", "dav-2201", "-DMEMORY_BASE"), |
| 39 | - ("a3", "dav-c220", "-DMEMORY_BASE"), | 40 | + ("a3", "dav-2201", "-DMEMORY_BASE"), |
| 40 | - ("a5", "dav-c310", "-DREGISTER_BASE"), | 41 | + ("a5", "dav-3510", "-DREGISTER_BASE"), |
| 41 | ]) | 42 | ]) |
| 42 | -@pytest.mark.parametrize("cube,vector,suffix,cores,fat_object", [ | 43 | +@pytest.mark.parametrize("cube,vector,qualifier,cores,kernel_type", [ |
| 43 | - (True, False, "-cube", (1, 0), False), | 44 | + (True, False, "__cube__", (1, 0), 0), |
| 44 | - (False, True, "-vec", (0, 1), False), | 45 | + (False, True, "__vector__", (0, 1), 2), |
| 45 | - (True, True, "", (1, 2), True), | 46 | + (True, True, "__mix__(1, 2)", (1, 2), 4), |
| 46 | ]) | 47 | ]) |
| 47 | -def test_existing_targets_preserve_compiler_flags_and_geometry( | 48 | +def test_asc_targets_keep_entry_profiling_and_launch_geometry_consistent( |
| 48 | - arch, prefix, memory, cube, vector, suffix, cores, fat_object, | 49 | + arch, npu_arch, memory, cube, vector, qualifier, cores, kernel_type, |
| 49 | ): | 50 | ): |
| 50 | - """An architecture or mode mapping change must not alter either half of the compiled launch ABI.""" | 51 | + """ASC needs explicit core qualifiers; inferring from instructions fails for scalar-only probes.""" |
| 51 | config = get_jit_compile_config() | 52 | config = get_jit_compile_config() |
| 52 | target = config.resolve_kernel_target(arch, has_cube=cube, has_vector=vector) | 53 | target = config.resolve_kernel_target(arch, has_cube=cube, has_vector=vector) |
| 53 | flags = config.build_bisheng_flags(toolkit_home="/toolkit", arch=arch, target=target, enable_print_debug=False) | 54 | flags = config.build_bisheng_flags(toolkit_home="/toolkit", arch=arch, target=target, enable_print_debug=False) |
| 54 | - caller = jit._generate_caller_cpp([], "kernel.cpp", "probe", target=target) | 55 | + entry = jit._make_global_entry("probe", [], target=target) |
| 55 | - assert target.npu_arch == prefix + suffix | 56 | + caller = jit._generate_caller_cpp( |
| 57 | + [], "kernel.cpp", "probe", target=target, global_entry=entry, | ||
| 58 | + prof_param_specs=[jit.ParamSpec("out", jit.ParamKind.TENSOR, "int32", [32], pl.Output)], | ||
| 59 | + ) | ||
| 60 | + assert target.npu_arch == npu_arch | ||
| 56 | assert (target.aic_per_block, target.aiv_per_block) == cores | 61 | assert (target.aic_per_block, target.aiv_per_block) == cores |
| 57 | - assert target.fat_object is fat_object | 62 | + assert "-xasc" in flags |
| 58 | - assert f"--cce-aicore-arch={prefix}{suffix}" in flags | 63 | + assert f"--npu-arch={npu_arch}" in flags |
| 59 | - assert ("--cce-fatobj-link" in flags) is fat_object | 64 | + assert "-xcce" not in flags |
| 65 | + assert "--cce-fatobj-link" not in flags | ||
| 66 | + assert f"__global__ {qualifier} void probe(" in caller | ||
| 67 | + assert f"pyptoProfInfo.kernelType = {kernel_type};" in caller | ||
| 68 | + if cube and vector: | ||
| 69 | + assert "pyptoProfInfo.blockNums = (blockDim & 0xffffU) | (2U << 16);" in caller | ||
| 70 | + else: | ||
| 71 | + assert "pyptoProfInfo.blockNums = blockDim;" in caller | ||
| 60 | assert memory in flags | 72 | assert memory in flags |
| 61 | assert f"ResolveLaunchBlockDim<{cores[0]}, {cores[1]}>" in caller | 73 | assert f"ResolveLaunchBlockDim<{cores[0]}, {cores[1]}>" in caller |
| 74 | + if arch in ("a2", "a3"): | ||
| 75 | + llvm_args = config.build_llvm_args(arch) | ||
| 76 | + assert llvm_args[llvm_args.index("-include") + 1] == "kernel_operator.h" | ||
| 62 | 77 | ||
| 63 | 78 | ||
| 64 | def test_simt_launcher_bakes_inferred_dynamic_ub_into_generated_caller(): | 79 | def test_simt_launcher_bakes_inferred_dynamic_ub_into_generated_caller(): |
| @@ -82,6 +97,7 @@ def test_architecture_specific_mixed_geometry_is_independent(future_config): | |||
| 82 | future = future_config.resolve_kernel_target("future", has_cube=True, has_vector=True) | 97 | future = future_config.resolve_kernel_target("future", has_cube=True, has_vector=True) |
| 83 | assert (a5.aic_per_block, a5.aiv_per_block) == (1, 2) | 98 | assert (a5.aic_per_block, a5.aiv_per_block) == (1, 2) |
| 84 | assert (future.aic_per_block, future.aiv_per_block) == (1, 1) | 99 | assert (future.aic_per_block, future.aiv_per_block) == (1, 1) |
| 100 | + assert "__mix__(1, 1)" in jit._make_global_entry("probe", [], target=future) | ||
| 85 | 101 | ||
| 86 | 102 | ||
| 87 | def test_missing_architecture_is_not_assumed_to_use_a5_geometry(): | 103 | def test_missing_architecture_is_not_assumed_to_use_a5_geometry(): |
| @@ -139,8 +155,8 @@ def test_shared_library_and_caller_use_the_same_resolved_target(monkeypatch, tmp | |||
| 139 | assert len(captured) == 1 | 155 | assert len(captured) == 1 |
| 140 | flags, build_arch, caller = captured[0] | 156 | flags, build_arch, caller = captured[0] |
| 141 | assert build_arch == arch | 157 | assert build_arch == arch |
| 142 | - assert f"--cce-aicore-arch={target.npu_arch}" in flags | 158 | + assert f"--npu-arch={target.npu_arch}" in flags |
| 143 | - assert "--cce-fatobj-link" in flags | 159 | + assert "-xasc" in flags |
| 144 | assert "--cce-enable-print" not in flags | 160 | assert "--cce-enable-print" not in flags |
| 145 | assert "/toolkit/asc/include" in flags | 161 | assert "/toolkit/asc/include" in flags |
| 146 | assert "/toolkit/asc" in flags | 162 | assert "/toolkit/asc" in flags |
| @@ -191,5 +207,5 @@ def test_debug_command_reuses_compiled_target_without_resolving(monkeypatch, tmp | |||
| 191 | kernel_name="probe", build_dir=str(tmp_path), target=target, | 207 | kernel_name="probe", build_dir=str(tmp_path), target=target, |
| 192 | ) | 208 | ) |
| 193 | command = dump._build_debug_compile_cmd(compiled) | 209 | command = dump._build_debug_compile_cmd(compiled) |
| 194 | - assert "--cce-aicore-arch=test-compiled-target" in command | 210 | + assert "--npu-arch=test-compiled-target" in command |
| 195 | - assert "--cce-aicore-arch=dav-c310" not in command | 211 | + assert "--npu-arch=dav-3510" not in command |
| @@ -0,0 +1,143 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Exercise the native collection state across independently loaded launchers.""" | ||
| 10 | + | ||
| 11 | +import os | ||
| 12 | +from pathlib import Path | ||
| 13 | +import subprocess | ||
| 14 | +import sys | ||
| 15 | + | ||
| 16 | +import pytest | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +@pytest.mark.parametrize("registration", ["success", "failure", "no_cann"]) | ||
| 20 | +def test_native_prof_status(tmp_path, registration): | ||
| 21 | + root = Path(__file__).resolve().parents[6] | ||
| 22 | + source = root / "framework/src/interface/pypto_pro/profiler.cpp" | ||
| 23 | + source_flags = ["-MMD", "-MF", str(tmp_path / "backend.so.d")] | ||
| 24 | + header_filters = [] | ||
| 25 | + if registration != "no_cann": | ||
| 26 | + ascend_home = os.environ.get("ASCEND_HOME_PATH") | ||
| 27 | + if not ascend_home: | ||
| 28 | + pytest.skip("CANN headers required to compile the native profiling callback") | ||
| 29 | + header_filters = [str(Path(ascend_home) / "pkg_inc"), str(Path(ascend_home) / "include")] | ||
| 30 | + source_flags += ["-DBUILD_WITH_CANN", "-I", header_filters[0], "-L", str(tmp_path), "-lprofapi"] | ||
| 31 | + stub = tmp_path / "profapi.cpp" | ||
| 32 | + stub.write_text(r""" | ||
| 33 | +#include <cassert> | ||
| 34 | +#include <cstdint> | ||
| 35 | +using Callback = int32_t (*)(uint32_t, void*, uint32_t); | ||
| 36 | +static Callback callback; | ||
| 37 | +extern "C" int32_t MsprofRegisterCallback(uint32_t module, Callback handler) | ||
| 38 | +{ | ||
| 39 | + assert(module == 0x46); | ||
| 40 | + assert(callback == nullptr); | ||
| 41 | +#ifdef FAIL_REGISTRATION | ||
| 42 | + return -1; | ||
| 43 | +#else | ||
| 44 | + callback = handler; | ||
| 45 | + return 0; | ||
| 46 | +#endif | ||
| 47 | +} | ||
| 48 | +extern "C" void command(uint32_t type, uint64_t value, uint32_t length, bool nullData) | ||
| 49 | +{ | ||
| 50 | + assert(callback != nullptr); | ||
| 51 | + assert(callback(type, nullData ? nullptr : &value, length) == 0); | ||
| 52 | +} | ||
| 53 | +""") | ||
| 54 | + launcher = tmp_path / "launcher.cpp" | ||
| 55 | + launcher.write_text('extern "C" bool GetPyptoProfStatus();\n' | ||
| 56 | + 'extern "C" bool query() { return GetPyptoProfStatus(); }\n') | ||
| 57 | + flags = ["-DFAIL_REGISTRATION"] if registration == "failure" else [] | ||
| 58 | + for src, name, extra in ( | ||
| 59 | + (stub, "libprofapi.so", flags), | ||
| 60 | + (source, "backend.so", source_flags), | ||
| 61 | + (launcher, "launcher1.so", []), | ||
| 62 | + (launcher, "launcher2.so", []), | ||
| 63 | + ): | ||
| 64 | + subprocess.run(["g++", "-std=c++17", "-shared", "-fPIC", "-O2", str(src), | ||
| 65 | + "-o", str(tmp_path / name), *extra], check=True, capture_output=True, text=True) | ||
| 66 | + | ||
| 67 | + # Apply the same transitive header rules as the online build to GCC's real | ||
| 68 | + # dependency file, for both CANN and CPU-only configurations. | ||
| 69 | + analysis = subprocess.run([ | ||
| 70 | + sys.executable, str(root / "cmake/scripts/analysis_binary_header_files.py"), | ||
| 71 | + "-s", str(root), "-b", str(tmp_path), "-t", "libtile_fwk_interface.so", | ||
| 72 | + "--target_binary_dir", str(tmp_path), "-o", str(tmp_path / "backend.so"), | ||
| 73 | + "-j", str(root / "cmake/scripts/analysis_binary_header_files.json"), "-f", *header_filters, | ||
| 74 | + ], capture_output=True, text=True) | ||
| 75 | + assert analysis.returncode == 0, analysis.stdout + analysis.stderr | ||
| 76 | + | ||
| 77 | + script = r""" | ||
| 78 | +import ctypes | ||
| 79 | +import sys | ||
| 80 | +backend = ctypes.CDLL('./backend.so', mode=ctypes.RTLD_GLOBAL) | ||
| 81 | +backend.GetPyptoProfStatus.restype = ctypes.c_bool | ||
| 82 | +assert not backend.GetPyptoProfStatus() | ||
| 83 | +if sys.argv[1] != 'success': | ||
| 84 | + sys.exit(0) | ||
| 85 | +prof = ctypes.CDLL('./libprofapi.so') | ||
| 86 | +prof.command.argtypes = [ctypes.c_uint32, ctypes.c_uint64, ctypes.c_uint32, ctypes.c_bool] | ||
| 87 | +launchers = [] | ||
| 88 | +for session in range(2): | ||
| 89 | + prof.command(1, 0x4000, 8, False) | ||
| 90 | + # Each library loads after collection starts, and must see the existing state. | ||
| 91 | + launcher = ctypes.CDLL(f'./launcher{session + 1}.so') | ||
| 92 | + launcher.query.restype = ctypes.c_bool | ||
| 93 | + launchers.append(launcher) | ||
| 94 | + assert all(lib.query() for lib in launchers) | ||
| 95 | + # Malformed and unrelated reporter/step notifications must not stop collection. | ||
| 96 | + for args in [(1, 0, 0, False), (1, 0, 8, True), (2, 0, 8, False), (3, 0, 8, False)]: | ||
| 97 | + prof.command(*args) | ||
| 98 | + assert all(lib.query() for lib in launchers) | ||
| 99 | + prof.command(1, 0, 8, False) | ||
| 100 | + assert all(not lib.query() for lib in launchers) | ||
| 101 | +""" | ||
| 102 | + env = dict(os.environ, LD_LIBRARY_PATH=str(tmp_path)) | ||
| 103 | + subprocess.run([sys.executable, "-c", script, registration], cwd=tmp_path, env=env, | ||
| 104 | + check=True, capture_output=True, text=True) | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +@pytest.mark.parametrize("native_provider", [False, True], ids=["standalone", "pypto_backend"]) | ||
| 108 | +def test_prof_status_dispatch(tmp_path, native_provider): | ||
| 109 | + """A dumped launcher loads without PyPTO; an imported backend owns the live flag when present.""" | ||
| 110 | + ascend_home = os.environ.get("ASCEND_HOME_PATH") | ||
| 111 | + if not ascend_home: | ||
| 112 | + pytest.skip("CANN headers required to compile the packaged profiling helper") | ||
| 113 | + root = Path(__file__).resolve().parents[6] | ||
| 114 | + source = tmp_path / "status.cpp" | ||
| 115 | + source.write_text(r""" | ||
| 116 | +#include "pypto_profiler.h" | ||
| 117 | +static bool nativeStatus; | ||
| 118 | +#ifdef NATIVE_PROVIDER | ||
| 119 | +extern "C" bool GetPyptoProfStatus() { return nativeStatus; } | ||
| 120 | +#endif | ||
| 121 | +extern "C" bool query() { return pypto::GetProfStatus(); } | ||
| 122 | +extern "C" void set_status(bool native) { nativeStatus = native; } | ||
| 123 | +""") | ||
| 124 | + flags = ["-DNATIVE_PROVIDER"] if native_provider else [] | ||
| 125 | + subprocess.run([ | ||
| 126 | + "g++", "-std=c++17", "-shared", "-fPIC", "-O2", str(source), "-o", str(tmp_path / "status.so"), | ||
| 127 | + "-I", str(root / "python/pypto_pro/include"), "-I", str(Path(ascend_home) / "include"), | ||
| 128 | + "-I", str(Path(ascend_home) / "pkg_inc"), *flags, | ||
| 129 | + ], check=True, capture_output=True, text=True) | ||
| 130 | + # A fresh interpreter must not inherit pytest's RTLD_GLOBAL PyPTO backend. | ||
| 131 | + script = r""" | ||
| 132 | +import ctypes | ||
| 133 | +import sys | ||
| 134 | +lib = ctypes.CDLL('./status.so') | ||
| 135 | +lib.query.restype = ctypes.c_bool | ||
| 136 | +lib.set_status.argtypes = [ctypes.c_bool] | ||
| 137 | +for native in [False, True, False, True, False]: | ||
| 138 | + lib.set_status(native) | ||
| 139 | + expected = native if sys.argv[1] == 'True' else False | ||
| 140 | + assert lib.query() == expected | ||
| 141 | +""" | ||
| 142 | + subprocess.run([sys.executable, "-c", script, str(native_provider)], cwd=tmp_path, | ||
| 143 | + check=True, capture_output=True, text=True) | ||
| @@ -0,0 +1,166 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Validate the packaged helper's CANN wire records independently of the exporter.""" | ||
| 10 | + | ||
| 11 | +import os | ||
| 12 | +from pathlib import Path | ||
| 13 | +import subprocess | ||
| 14 | + | ||
| 15 | +import pytest | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def test_native_prof_tensor_info(tmp_path): | ||
| 19 | + ascend_home = os.environ.get("ASCEND_HOME_PATH") | ||
| 20 | + if not ascend_home: | ||
| 21 | + pytest.skip("CANN headers required to compile the packaged profiling helper") | ||
| 22 | + root = Path(__file__).resolve().parents[6] | ||
| 23 | + source = tmp_path / "tensor_info.cpp" | ||
| 24 | + source.write_text(r""" | ||
| 25 | +#include "pypto_profiler.h" | ||
| 26 | +#include <cassert> | ||
| 27 | +#include <vector> | ||
| 28 | + | ||
| 29 | +static std::vector<unsigned char> cached; | ||
| 30 | +static std::vector<MsprofAdditionalInfo> tensors; | ||
| 31 | +static MsprofCompactInfo basic; | ||
| 32 | +static MsprofApi api; | ||
| 33 | +static unsigned cacheCalls, basicCalls, apiCalls, cycles; | ||
| 34 | +static int reportError; | ||
| 35 | + | ||
| 36 | +extern "C" aclError aclrtCacheLastTaskOpInfo(const void* const data, const size_t size) | ||
| 37 | +{ | ||
| 38 | + ++cacheCalls; | ||
| 39 | + const auto* bytes = static_cast<const unsigned char*>(data); | ||
| 40 | + cached.assign(bytes, bytes + size); | ||
| 41 | + return reportError; | ||
| 42 | +} | ||
| 43 | +extern "C" uint64_t MsprofSysCycleTime() { return 100 + ++cycles; } | ||
| 44 | +extern "C" int32_t MsprofReportCompactInfo(uint32_t aging, void* data, uint32_t size) | ||
| 45 | +{ | ||
| 46 | + assert(aging && size == sizeof(basic)); | ||
| 47 | + ++basicCalls; | ||
| 48 | + std::memcpy(&basic, data, size); | ||
| 49 | + return reportError; | ||
| 50 | +} | ||
| 51 | +extern "C" int32_t MsprofReportApi(uint32_t aging, const MsprofApi* data) | ||
| 52 | +{ | ||
| 53 | + assert(aging); | ||
| 54 | + ++apiCalls; | ||
| 55 | + api = *data; | ||
| 56 | + return reportError; | ||
| 57 | +} | ||
| 58 | +extern "C" int32_t MsprofReportAdditionalInfo(uint32_t aging, void* data, uint32_t size) | ||
| 59 | +{ | ||
| 60 | + assert(aging && size == sizeof(MsprofAdditionalInfo)); | ||
| 61 | + MsprofAdditionalInfo record; | ||
| 62 | + std::memcpy(&record, data, size); | ||
| 63 | + tensors.push_back(record); | ||
| 64 | + return reportError; | ||
| 65 | +} | ||
| 66 | +template <typename T> T read(size_t offset) | ||
| 67 | +{ | ||
| 68 | + T value; | ||
| 69 | + assert(offset + sizeof(value) <= cached.size()); | ||
| 70 | + std::memcpy(&value, cached.data() + offset, sizeof(value)); | ||
| 71 | + return value; | ||
| 72 | +} | ||
| 73 | +static void checkTensor(const MsrofTensorData& tensor, unsigned index) | ||
| 74 | +{ | ||
| 75 | + assert(tensor.tensorType == index % 2); | ||
| 76 | + assert(tensor.format == 2 && tensor.dataType == index); | ||
| 77 | + for (unsigned dim = 0; dim < 8; ++dim) { | ||
| 78 | + assert(tensor.shape[dim] == (dim < index % 9 ? 32 + index + dim : 0)); | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | +static void run(bool live, bool capture, unsigned count, int error = 0) | ||
| 82 | +{ | ||
| 83 | + cached.clear(); tensors.clear(); | ||
| 84 | + cacheCalls = basicCalls = apiCalls = cycles = 0; | ||
| 85 | + reportError = error; | ||
| 86 | + std::vector<aclprofTensor> inputs(count); | ||
| 87 | + for (unsigned i = 0; i < count; ++i) { | ||
| 88 | + inputs[i].type = i % 2; | ||
| 89 | + inputs[i].format = 2; | ||
| 90 | + inputs[i].dataType = i; | ||
| 91 | + inputs[i].shapeDim = i % 9; | ||
| 92 | + // Nonzero padding must not leak into either wire format. | ||
| 93 | + for (unsigned dim = 0; dim < 8; ++dim) { | ||
| 94 | + inputs[i].shape[dim] = 32 + i + dim; | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + aclprofTensorInfo info{}; | ||
| 98 | + info.opNameId = 0x1122334455667788; | ||
| 99 | + info.opTypeId = 0x8877665544332211; | ||
| 100 | + info.kernelType = 3; | ||
| 101 | + info.blockNums = (2U << 16) | 7; | ||
| 102 | + info.tensorNum = count; | ||
| 103 | + info.tensors = inputs.data(); | ||
| 104 | + const uint64_t begin = pypto::BeginCaptureTensorReport(live); | ||
| 105 | + assert(begin == (live ? 101 : 0)); | ||
| 106 | + pypto::ReportCaptureTensorInfo(info, begin, capture); | ||
| 107 | + if (capture && count <= 1488) { | ||
| 108 | + assert(cacheCalls == 1 && cached.size() == 48 + 44 * count); | ||
| 109 | + // CANN Runtime's CacheTaskInfo ABI: 48-byte header followed by packed | ||
| 110 | + // 44-byte tensors. These offsets also match machine's host_prof.h. | ||
| 111 | + assert(read<uint32_t>(0) == 3 && read<uint32_t>(4) == ((2U << 16) | 7)); | ||
| 112 | + assert(read<uint64_t>(8) == info.opNameId && read<uint64_t>(16) == info.opTypeId); | ||
| 113 | + assert(read<uint64_t>(24) == 0 && read<uint64_t>(32) == 0); | ||
| 114 | + assert(read<uint32_t>(40) == 0 && read<uint32_t>(44) == count); | ||
| 115 | + for (unsigned i = 0; i < count; ++i) { | ||
| 116 | + checkTensor(read<MsrofTensorData>(48 + 44 * i), i); | ||
| 117 | + } | ||
| 118 | + } else { | ||
| 119 | + assert(cacheCalls == 0 && cached.empty()); | ||
| 120 | + } | ||
| 121 | + assert(basicCalls == live && apiCalls == live); | ||
| 122 | + if (!live) { | ||
| 123 | + assert(cycles == 0 && tensors.empty()); | ||
| 124 | + return; | ||
| 125 | + } | ||
| 126 | + assert(basic.level == MSPROF_REPORT_NODE_LEVEL && basic.type == MSPROF_REPORT_NODE_BASIC_INFO_TYPE); | ||
| 127 | + assert(basic.dataLen == sizeof(MsprofNodeBasicInfo)); | ||
| 128 | + assert(basic.data.nodeBasicInfo.opName == info.opNameId && basic.data.nodeBasicInfo.opType == info.opTypeId); | ||
| 129 | + assert(basic.data.nodeBasicInfo.taskType == info.kernelType && basic.data.nodeBasicInfo.blockDim == 7); | ||
| 130 | + assert(api.level == MSPROF_REPORT_NODE_LEVEL && api.type == MSPROF_REPORT_NODE_LAUNCH_TYPE); | ||
| 131 | + assert(api.itemId == info.opNameId && api.beginTime == begin && api.endTime > begin); | ||
| 132 | + assert(api.threadId == basic.threadId && basic.timeStamp == api.endTime); | ||
| 133 | + assert(tensors.size() == (count + 4) / 5); | ||
| 134 | + unsigned index = 0; | ||
| 135 | + for (const auto& record : tensors) { | ||
| 136 | + assert(record.level == MSPROF_REPORT_NODE_LEVEL && record.type == MSPROF_REPORT_NODE_TENSOR_INFO_TYPE); | ||
| 137 | + assert(record.threadId == api.threadId && record.timeStamp == basic.timeStamp); | ||
| 138 | + assert(record.dataLen == sizeof(MsprofTensorInfo)); | ||
| 139 | + MsprofTensorInfo tensorInfo; | ||
| 140 | + std::memcpy(&tensorInfo, record.data, sizeof(tensorInfo)); | ||
| 141 | + assert(tensorInfo.opName == info.opNameId); | ||
| 142 | + assert(tensorInfo.tensorNum == (count - index < 5 ? count - index : 5)); | ||
| 143 | + for (unsigned i = 0; i < tensorInfo.tensorNum; ++i) { | ||
| 144 | + checkTensor(tensorInfo.tensorData[i], index++); | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + assert(index == count); | ||
| 148 | +} | ||
| 149 | +int main() | ||
| 150 | +{ | ||
| 151 | + run(false, false, 9); | ||
| 152 | + run(false, true, 9); | ||
| 153 | + run(true, false, 9); | ||
| 154 | + run(true, true, 9); | ||
| 155 | + run(true, true, 9, 1); // API failures never suppress the remaining reports or throw. | ||
| 156 | + run(false, true, 1488); // Largest payload below the 64 KiB API limit. | ||
| 157 | + run(false, true, 1489); // Oversized payload is not submitted. | ||
| 158 | +} | ||
| 159 | +""") | ||
| 160 | + binary = tmp_path / "tensor_info" | ||
| 161 | + subprocess.run([ | ||
| 162 | + "g++", "-std=c++17", "-O2", str(source), "-o", str(binary), | ||
| 163 | + "-I", str(root / "python/pypto_pro/include"), "-I", str(Path(ascend_home) / "include"), | ||
| 164 | + "-I", str(Path(ascend_home) / "pkg_inc"), | ||
| 165 | + ], check=True, capture_output=True, text=True) | ||
| 166 | + subprocess.run([str(binary)], check=True, capture_output=True, text=True) | ||
| @@ -9,23 +9,12 @@ | |||
| 9 | # See LICENSE in the root of the software repository for the full text of the License. | 9 | # See LICENSE in the root of the software repository for the full text of the License. |
| 10 | # ----------------------------------------------------------------------------------------------------------- | 10 | # ----------------------------------------------------------------------------------------------------------- |
| 11 | 11 | ||
| 12 | -"""The aclprof tensor-info range embedded in the generated launcher. | 12 | +"""Generated launch metadata for live reporting and captured graph replay.""" |
| 13 | 13 | ||
| 14 | -``_generate_prof_range_snippet`` turns IR param specs into an ``aclprofTensor[]`` | 14 | +import subprocess |
| 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 | 15 | ||
| 28 | import pypto_pro.language as pl | 16 | import pypto_pro.language as pl |
| 17 | +from pypto_pro.runtime.compile_config import get_jit_compile_config | ||
| 29 | from pypto_pro.runtime.jit import ( | 18 | from pypto_pro.runtime.jit import ( |
| 30 | ParamKind, | 19 | ParamKind, |
| 31 | ParamSpec, | 20 | ParamSpec, |
| @@ -36,17 +25,18 @@ from pypto_pro.runtime.jit import ( | |||
| 36 | 25 | ||
| 37 | 26 | ||
| 38 | def _snippet(kernel_name, specs, dims): | 27 | def _snippet(kernel_name, specs, dims): |
| 28 | + target = get_jit_compile_config().resolve_kernel_target("a5", has_cube=False, has_vector=True) | ||
| 39 | return _generate_prof_range_snippet( | 29 | return _generate_prof_range_snippet( |
| 40 | - kernel_name, specs, dims, launch_stmt=" k<<<blockDim, nullptr, stream>>>(a, out);\n" | 30 | + kernel_name, specs, dims, target=target, launch_stmt=" k<<<blockDim, nullptr, stream>>>(a, out);\n" |
| 41 | ) | 31 | ) |
| 42 | 32 | ||
| 43 | 33 | ||
| 44 | -def _spec(name, shape, dtype_str, direction): | 34 | +def _spec(name, shape, dtype_str, direction=pl.Input): |
| 45 | return ParamSpec(name, ParamKind.TENSOR, dtype_str, shape, direction) | 35 | return ParamSpec(name, ParamKind.TENSOR, dtype_str, shape, direction) |
| 46 | 36 | ||
| 47 | 37 | ||
| 48 | -def test_annotation_marker_sets_direction(): | 38 | +def test_output_annotation_sets_direction(): |
| 49 | - """pl.Output in the annotation flows to ParamSpec.direction; omitted defaults to in.""" | 39 | + """pl.Output in the annotation flows to ParamSpec.direction; omitted defaults to INPUT.""" |
| 50 | @pl.jit() | 40 | @pl.jit() |
| 51 | def marked_kernel( | 41 | def marked_kernel( |
| 52 | a: pl.Tensor[[64, 64], pl.DT_FP32], | 42 | a: pl.Tensor[[64, 64], pl.DT_FP32], |
| @@ -58,14 +48,60 @@ def test_annotation_marker_sets_direction(): | |||
| 58 | pl.load(ta, a, [0, 0]) | 48 | pl.load(ta, a, [0, 0]) |
| 59 | pl.store(out, ta, [0, 0]) | 49 | pl.store(out, ta, [0, 0]) |
| 60 | 50 | ||
| 61 | - cube, vector = _parse_and_codegen_targets(marked_kernel.to_kernel_def(), "a5", "") | 51 | + kernel_def = marked_kernel.to_kernel_def() |
| 52 | + cube, vector = _parse_and_codegen_targets(kernel_def, "a5", "") | ||
| 62 | cg = cube or vector | 53 | cg = cube or vector |
| 63 | - assert cg.param_specs[0].direction == "in" | 54 | + assert kernel_def.last_param_directions == {1: pl.Output} |
| 64 | - assert cg.param_specs[1].direction == "out" | 55 | + assert cg.param_specs[0].direction is pl.Input |
| 56 | + assert cg.param_specs[1].direction is pl.Output | ||
| 65 | 57 | ||
| 66 | 58 | ||
| 67 | -def test_no_marker_defaults_to_in(): | 59 | +def test_call_style_output_annotation_sets_direction(): |
| 68 | - """Without pl.Output, a tensor param is input even if the kernel stores into it.""" | 60 | + @pl.jit() |
| 61 | + def marked_kernel( | ||
| 62 | + a: pl.Tensor([64, 64], pl.DT_FP32), | ||
| 63 | + out: pl.Tensor([64, 64], pl.DT_FP32, pl.Output), | ||
| 64 | + ): | ||
| 65 | + tt = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) | ||
| 66 | + ta = pl.make_tile(tt, addr=0x0000) | ||
| 67 | + with pl.section_vector(): | ||
| 68 | + pl.load(ta, a, [0, 0]) | ||
| 69 | + pl.store(out, ta, [0, 0]) | ||
| 70 | + | ||
| 71 | + kernel_def = marked_kernel.to_kernel_def() | ||
| 72 | + cube, vector = _parse_and_codegen_targets(kernel_def, "a5", "") | ||
| 73 | + cg = cube or vector | ||
| 74 | + assert kernel_def.last_param_directions == {1: pl.Output} | ||
| 75 | + assert cg.param_specs[0].direction is pl.Input | ||
| 76 | + assert cg.param_specs[1].direction is pl.Output | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +def test_output_direction_uses_absolute_parameter_index(): | ||
| 80 | + @pl.jit() | ||
| 81 | + def marked_kernel( | ||
| 82 | + size: pl.DT_INT32, | ||
| 83 | + a: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 84 | + out: pl.Tensor[[64, 64], pl.DT_FP32, pl.Output], | ||
| 85 | + ): | ||
| 86 | + tt = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) | ||
| 87 | + ta = pl.make_tile(tt, addr=0x0000) | ||
| 88 | + with pl.section_vector(): | ||
| 89 | + pl.load(ta, a, [0, 0]) | ||
| 90 | + pl.store(out, ta, [0, 0]) | ||
| 91 | + | ||
| 92 | + kernel_def = marked_kernel.to_kernel_def() | ||
| 93 | + cube, vector = _parse_and_codegen_targets(kernel_def, "a5", "") | ||
| 94 | + cg = cube or vector | ||
| 95 | + assert kernel_def.last_param_directions == {2: pl.Output} | ||
| 96 | + assert cg.param_specs[0].kind is ParamKind.SCALAR | ||
| 97 | + assert cg.param_specs[0].direction is None | ||
| 98 | + assert cg.param_specs[1].direction is pl.Input | ||
| 99 | + assert cg.param_specs[2].name == "out_0" | ||
| 100 | + assert cg.param_specs[2].direction is pl.Output | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +def test_omitted_direction_defaults_to_input(): | ||
| 104 | + """An omitted direction defaults to INPUT even if the kernel stores into the tensor.""" | ||
| 69 | 105 | ||
| 70 | @pl.jit() | 106 | @pl.jit() |
| 71 | def unmarked_kernel( | 107 | def unmarked_kernel( |
| @@ -78,44 +114,47 @@ def test_no_marker_defaults_to_in(): | |||
| 78 | 114 | ||
| 79 | cube, vector = _parse_and_codegen_targets(unmarked_kernel.to_kernel_def(), "a5", "") | 115 | cube, vector = _parse_and_codegen_targets(unmarked_kernel.to_kernel_def(), "a5", "") |
| 80 | cg = cube or vector | 116 | cg = cube or vector |
| 81 | - assert cg.param_specs[0].direction == "in" | 117 | + assert cg.param_specs[0].direction is pl.Input |
| 82 | 118 | ||
| 83 | 119 | ||
| 84 | def test_static_shapes_are_literals(): | 120 | def test_static_shapes_are_literals(): |
| 85 | specs = [ | 121 | specs = [ |
| 86 | - _spec("a", [64, 64], "fp32", "in"), | 122 | + _spec("a", [64, 64], "fp32"), |
| 87 | - _spec("b", [64, 64], "fp32", "in"), | 123 | + _spec("b", [64, 64], "fp32"), |
| 88 | - _spec("out", [64, 64], "fp32", "out"), | 124 | + _spec("out", [64, 64], "fp32", pl.Output), |
| 89 | ] | 125 | ] |
| 90 | _inc, push, pop = _snippet("k", specs, set()) | 126 | _inc, push, pop = _snippet("k", specs, set()) |
| 91 | assert '#include "acl/acl_prof.h"' in _inc | 127 | assert '#include "acl/acl_prof.h"' in _inc |
| 92 | - assert "{0, 2, 0, 2, {64, 64, 0, 0, 0, 0, 0, 0}}," in push # a: in | 128 | + assert "{0, 2, 0, 2, {64, 64, 0, 0, 0, 0, 0, 0}}," in push # a: input |
| 93 | - assert "{1, 2, 0, 2, {64, 64, 0, 0, 0, 0, 0, 0}}," in push # out: out | 129 | + assert "{1, 2, 0, 2, {64, 64, 0, 0, 0, 0, 0, 0}}," in push # out: output |
| 94 | - assert 'aclprofRangePushEx(&pyptoProfAttrs);' in push | 130 | + assert 'BeginCaptureTensorReport(pyptoProfOn)' in push |
| 95 | - assert '(void)aclprofRangePop();' in pop | 131 | + assert 'ReportCaptureTensorInfo(pyptoProfInfo, pyptoProfBegin, pyptoCaptureOn)' in pop |
| 132 | + assert 'aclprofRange' not in push + pop | ||
| 133 | + assert 'aclprofEventAttributes' not in push | ||
| 96 | assert "aclprofStr2Id(\"PYPTO_k\")" in push | 134 | assert "aclprofStr2Id(\"PYPTO_k\")" in push |
| 97 | assert "pyptoProfInfo.tensorNum = 3;" in push | 135 | assert "pyptoProfInfo.tensorNum = 3;" in push |
| 136 | + assert "pyptoProfInfo.kernelType = 2;" in push | ||
| 98 | 137 | ||
| 99 | 138 | ||
| 100 | def test_dynamic_dims_reference_launcher_params(): | 139 | def test_dynamic_dims_reference_launcher_params(): |
| 101 | dims = {"a", "b", "out", "__pypto_dyn_a_0", "__pypto_dyn_a_1"} | 140 | dims = {"a", "b", "out", "__pypto_dyn_a_0", "__pypto_dyn_a_1"} |
| 102 | - specs = [_spec("a", ["__pypto_dyn_a_0", "__pypto_dyn_a_1"], "fp32", "in")] | 141 | + specs = [_spec("a", ["__pypto_dyn_a_0", "__pypto_dyn_a_1"], "fp32")] |
| 103 | _inc, push, _pop = _snippet("k", specs, dims) | 142 | _inc, push, _pop = _snippet("k", specs, dims) |
| 104 | assert "{static_cast<uint32_t>(__pypto_dyn_a_0), static_cast<uint32_t>(__pypto_dyn_a_1)," in push | 143 | assert "{static_cast<uint32_t>(__pypto_dyn_a_0), static_cast<uint32_t>(__pypto_dyn_a_1)," in push |
| 105 | 144 | ||
| 106 | 145 | ||
| 107 | def test_unknown_dynamic_degrades_to_zero(): | 146 | def test_unknown_dynamic_degrades_to_zero(): |
| 108 | - specs = [_spec("a", [-1, 8], "fp16", "in")] | 147 | + specs = [_spec("a", [-1, 8], "fp16")] |
| 109 | _inc, push, _pop = _snippet("k", specs, set()) | 148 | _inc, push, _pop = _snippet("k", specs, set()) |
| 110 | assert "{0, 2, 1, 2, {0, 8, 0, 0, 0, 0, 0, 0}}," in push | 149 | assert "{0, 2, 1, 2, {0, 8, 0, 0, 0, 0, 0, 0}}," in push |
| 111 | 150 | ||
| 112 | 151 | ||
| 113 | def test_dtype_mapping(): | 152 | def test_dtype_mapping(): |
| 114 | specs = [ | 153 | specs = [ |
| 115 | - _spec("a", [4], "fp16", "in"), | 154 | + _spec("a", [4], "fp16"), |
| 116 | - _spec("b", [4], "bf16", "in"), | 155 | + _spec("b", [4], "bf16"), |
| 117 | - _spec("c", [4], "int32", "in"), | 156 | + _spec("c", [4], "int32"), |
| 118 | - _spec("d", [4], "nonexistent", "in"), | 157 | + _spec("d", [4], "nonexistent"), |
| 119 | ] | 158 | ] |
| 120 | _inc, push, _pop = _snippet("k", specs, set()) | 159 | _inc, push, _pop = _snippet("k", specs, set()) |
| 121 | assert "{0, 2, 1, 1," in push # fp16 -> 1 | 160 | assert "{0, 2, 1, 1," in push # fp16 -> 1 |
| @@ -128,8 +167,8 @@ def test_no_tensor_params_disables_snippet(): | |||
| 128 | assert _snippet("k", [], set()) == ("", "", "") | 167 | assert _snippet("k", [], set()) == ("", "", "") |
| 129 | 168 | ||
| 130 | 169 | ||
| 131 | -def test_caller_embeds_range_around_launch_static(): | 170 | +def test_caller_embeds_metadata_around_launch_static(): |
| 132 | - """End-to-end caller generation: pl.Output marker flows into the snippet.""" | 171 | + """End-to-end caller generation: pl.Output flows into the snippet.""" |
| 133 | @pl.jit() | 172 | @pl.jit() |
| 134 | def static_kernel( | 173 | def static_kernel( |
| 135 | a: pl.Tensor[[64, 64], pl.DT_FP32], | 174 | a: pl.Tensor[[64, 64], pl.DT_FP32], |
| @@ -158,16 +197,16 @@ def test_caller_embeds_range_around_launch_static(): | |||
| 158 | ) | 197 | ) |
| 159 | assert '#include "acl/acl_prof.h"' in content | 198 | assert '#include "acl/acl_prof.h"' in content |
| 160 | assert 'aclprofStr2Id("PYPTO_static_kernel")' in content | 199 | assert 'aclprofStr2Id("PYPTO_static_kernel")' in content |
| 161 | - push_idx = content.index("aclprofRangePushEx") | 200 | + push_idx = content.index("BeginCaptureTensorReport") |
| 162 | launch_idx = content.index("<<<blockDim") | 201 | launch_idx = content.index("<<<blockDim") |
| 163 | - pop_idx = content.index("aclprofRangePop") | 202 | + pop_idx = content.index("ReportCaptureTensorInfo") |
| 164 | assert push_idx < launch_idx < pop_idx | 203 | assert push_idx < launch_idx < pop_idx |
| 165 | - assert "{0, 2, 0, 2, {64, 64" in content # a: in | 204 | + assert "{0, 2, 0, 2, {64, 64" in content # a: input |
| 166 | - assert "{1, 2, 0, 2, {64, 64" in content # out: out | 205 | + assert "{1, 2, 0, 2, {64, 64" in content # out: output |
| 167 | 206 | ||
| 168 | 207 | ||
| 169 | -def test_guard_wraps_struct_definitions(): | 208 | +def test_metadata_checks_collection_and_capture_independently(): |
| 170 | - """The MsprofGetPath switch wraps the struct definitions; else branch launches bare.""" | 209 | + """Capture before collection caches tensors; live node reports need active collection.""" |
| 171 | @pl.jit() | 210 | @pl.jit() |
| 172 | def bare_kernel( | 211 | def bare_kernel( |
| 173 | a: pl.Tensor[[64, 64], pl.DT_FP32], | 212 | a: pl.Tensor[[64, 64], pl.DT_FP32], |
| @@ -194,14 +233,100 @@ def test_guard_wraps_struct_definitions(): | |||
| 194 | target=target, | 233 | target=target, |
| 195 | prof_param_specs=cg.param_specs, | 234 | prof_param_specs=cg.param_specs, |
| 196 | ) | 235 | ) |
| 197 | - on_idx = content.index("if (pyptoProfOn) {") | 236 | + guard_idx = content.index("if (pyptoProfOn || pyptoCaptureOn) {") |
| 198 | tensors_idx = content.index("aclprofTensor pyptoProfTensors[]") | 237 | tensors_idx = content.index("aclprofTensor pyptoProfTensors[]") |
| 199 | - push_idx = content.index("aclprofRangePushEx") | 238 | + begin_idx = content.index("pypto::BeginCaptureTensorReport(pyptoProfOn)") |
| 239 | + launch_idx = content.index("<<<blockDim") | ||
| 200 | report_idx = content.index("pypto::ReportCaptureTensorInfo") | 240 | report_idx = content.index("pypto::ReportCaptureTensorInfo") |
| 201 | - pop_idx = content.index("aclprofRangePop") | ||
| 202 | else_idx = content.index("} else {") | 241 | else_idx = content.index("} else {") |
| 203 | - assert on_idx < tensors_idx < push_idx # definitions inside the guard | 242 | + assert guard_idx < tensors_idx < begin_idx < launch_idx < report_idx < else_idx |
| 204 | - assert push_idx < report_idx < pop_idx # report lands between launch and pop | 243 | + assert "ACL_STREAM_ATTR_CACHE_OP_INFO" in content |
| 205 | - assert pop_idx < else_idx # pop stays in the same guarded block | 244 | + assert "pyptoCaptureAttr.cacheOpInfoSwitch" in content |
| 206 | - assert content.count("<<<blockDim") == 2 # instrumented branch + bare else branch | 245 | + assert "const bool pyptoProfOn = true;" not in content |
| 207 | - assert "ReportCaptureTensorInfo" not in content[else_idx:] # else launches uninstrumented | 246 | + assert "pypto::GetProfStatus()" in content |
| 247 | + assert "getenv" not in content | ||
| 248 | + assert content.count("<<<blockDim") == 2 | ||
| 249 | + assert "ReportCaptureTensorInfo" not in content[else_idx:] | ||
| 250 | + | ||
| 251 | + | ||
| 252 | +def test_native_metadata_gate(tmp_path): | ||
| 253 | + """Execute the emitted control flow with recording APIs; an ordinary launch must not report.""" | ||
| 254 | + target = get_jit_compile_config().resolve_kernel_target("a5", has_cube=False, has_vector=True) | ||
| 255 | + _inc, push, pop = _generate_prof_range_snippet( | ||
| 256 | + "k", [_spec("a", [64], "fp32", pl.Input)], set(), target=target, launch_stmt=" ++launches;\n" | ||
| 257 | + ) | ||
| 258 | + # Only API types/functions and the device launch are stubs; compile the actual generated guard. | ||
| 259 | + harness = r""" | ||
| 260 | +#include <cassert> | ||
| 261 | +#include <cstdint> | ||
| 262 | +#include <cstdio> | ||
| 263 | +constexpr int ACL_SUCCESS = 0, ACL_STREAM_ATTR_CACHE_OP_INFO = 7; | ||
| 264 | +struct aclrtStreamAttrValue { bool cacheOpInfoSwitch; }; | ||
| 265 | +struct aclprofTensor { uint32_t type, format, dataType, dimNum, shape[8]; }; | ||
| 266 | +struct aclprofTensorInfo { | ||
| 267 | + uint64_t opNameId, opTypeId; | ||
| 268 | + uint32_t resv, tensorNum, kernelType, blockNums; | ||
| 269 | + void* stream; | ||
| 270 | + aclprofTensor* tensors; | ||
| 271 | +}; | ||
| 272 | +static int profiling, capture, queryError, queries, launches, reports, caches, strings, activeBegins; | ||
| 273 | +namespace pypto { | ||
| 274 | +static bool GetProfStatus() { return profiling; } | ||
| 275 | +} | ||
| 276 | +static int aclrtGetStreamAttribute(void* stream, int attribute, aclrtStreamAttrValue* value) | ||
| 277 | +{ | ||
| 278 | + assert(stream == reinterpret_cast<void*>(0x1234)); | ||
| 279 | + assert(attribute == ACL_STREAM_ATTR_CACHE_OP_INFO); | ||
| 280 | + ++queries; | ||
| 281 | + value->cacheOpInfoSwitch = capture; | ||
| 282 | + return queryError; | ||
| 283 | +} | ||
| 284 | +static uint64_t aclprofStr2Id(const char*) { return ++strings; } | ||
| 285 | +namespace pypto { | ||
| 286 | +static uint64_t BeginCaptureTensorReport(bool profiling) | ||
| 287 | +{ | ||
| 288 | + activeBegins += profiling; | ||
| 289 | + return profiling ? 123 : 0; | ||
| 290 | +} | ||
| 291 | +static void ReportCaptureTensorInfo(const aclprofTensorInfo& info, uint64_t begin, bool cache) | ||
| 292 | +{ | ||
| 293 | + assert(launches == 1); | ||
| 294 | + assert(info.tensors[0].shape[0] == 64); | ||
| 295 | + reports += begin != 0; | ||
| 296 | + caches += cache; | ||
| 297 | +} | ||
| 298 | +} | ||
| 299 | +static void launch(uint32_t blockDim, void* stream) | ||
| 300 | +{ | ||
| 301 | +""" + push + " ++launches;\n" + pop + r""" | ||
| 302 | +} | ||
| 303 | +int main() | ||
| 304 | +{ | ||
| 305 | + // Reuse the same stream as collection/capture changes to expose a cached guard. | ||
| 306 | + // Fields: process-wide collection, capture, query error. | ||
| 307 | + const int cases[][3] = {{0, 0, 0}, {0, 1, 0}, {1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 0}}; | ||
| 308 | + for (const auto& test : cases) { | ||
| 309 | + profiling = test[0]; capture = test[1]; queryError = test[2]; | ||
| 310 | + queries = launches = reports = caches = strings = activeBegins = 0; | ||
| 311 | + launch(8, reinterpret_cast<void*>(0x1234)); | ||
| 312 | + std::printf("%d %d %d %d %d %d\n", launches, reports, caches, strings, activeBegins, queries); | ||
| 313 | + } | ||
| 314 | +} | ||
| 315 | +""" | ||
| 316 | + source = tmp_path / "range_gate.cpp" | ||
| 317 | + source.write_text(harness) | ||
| 318 | + binary = tmp_path / "range_gate" | ||
| 319 | + subprocess.run(["g++", "-std=c++17", "-O2", str(source), "-o", str(binary)], | ||
| 320 | + check=True, capture_output=True, text=True) | ||
| 321 | + result = subprocess.run([str(binary)], check=True, capture_output=True, text=True) | ||
| 322 | + actual = [tuple(map(int, line.split())) for line in result.stdout.splitlines()] | ||
| 323 | + # Counts: launches, live reports, caches, registered strings, active begins, capture queries. | ||
| 324 | + assert actual == [ | ||
| 325 | + (1, 0, 0, 0, 0, 1), # No collection, no capture. | ||
| 326 | + (1, 0, 1, 2, 0, 1), # Capture before collection only caches. | ||
| 327 | + (1, 1, 0, 2, 1, 1), # Collection alone reports live metadata. | ||
| 328 | + (1, 1, 1, 2, 1, 1), # Capture during collection must also cache for later replay. | ||
| 329 | + (1, 1, 0, 2, 1, 1), # Collection still reports despite a failed capture query. | ||
| 330 | + (1, 0, 0, 0, 0, 1), # A failed capture query alone does not report. | ||
| 331 | + (1, 0, 0, 0, 0, 1), # Returning to ordinary execution must stop all metadata calls. | ||
| 332 | + ] | ||
| @@ -0,0 +1,127 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""Execute both generated ABI adapters and check physical slot sizes without an NPU.""" | ||
| 10 | + | ||
| 11 | +import ctypes | ||
| 12 | +import importlib | ||
| 13 | +import shutil | ||
| 14 | +import struct | ||
| 15 | +import subprocess | ||
| 16 | + | ||
| 17 | +import pytest | ||
| 18 | + | ||
| 19 | +jit = importlib.import_module("pypto_pro.runtime.jit") | ||
| 20 | + | ||
| 21 | +SCALARS = [ | ||
| 22 | + ("bool", ctypes.c_bool), | ||
| 23 | + ("int8_t", ctypes.c_int8), | ||
| 24 | + ("uint8_t", ctypes.c_uint8), | ||
| 25 | + ("int16_t", ctypes.c_int16), | ||
| 26 | + ("uint16_t", ctypes.c_uint16), | ||
| 27 | + ("int32_t", ctypes.c_int32), | ||
| 28 | + ("uint32_t", ctypes.c_uint32), | ||
| 29 | + ("float", ctypes.c_float), | ||
| 30 | + ("int64_t", ctypes.c_int64), | ||
| 31 | + ("uint64_t", ctypes.c_uint64), | ||
| 32 | +] | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +@pytest.fixture(scope="module") | ||
| 36 | +def native_scalar_launcher(tmp_path_factory): | ||
| 37 | + # Use the same compiler as the ASC launcher, including its C++17 bit-cast builtin. | ||
| 38 | + compiler = shutil.which("bisheng") | ||
| 39 | + if compiler is None: | ||
| 40 | + pytest.skip("bisheng is required to compile the scalar launch adapters") | ||
| 41 | + root = tmp_path_factory.mktemp("scalar_launch_abi") | ||
| 42 | + (root / "runtime").mkdir() | ||
| 43 | + (root / "runtime/rt_ffts.h").write_text("#pragma once\n") | ||
| 44 | + (root / "pypto_launch.h").write_text("""#pragma once | ||
| 45 | +#include <cstdint> | ||
| 46 | +namespace pypto { | ||
| 47 | +template<int, int> int64_t ResolveLaunchBlockDim(uint32_t n, void*) { return n; } | ||
| 48 | +} | ||
| 49 | +""") | ||
| 50 | + params = [(typ, f"v{i}", False) for i, (typ, _) in enumerate(SCALARS)] | ||
| 51 | + # Exercise a pointer between narrow scalars, trailing dimensions and the hidden | ||
| 52 | + # cross-core-sync pointer. None may shift when a preceding scalar is widened. | ||
| 53 | + params.insert(1, ("uint64_t", "out", True)) | ||
| 54 | + params.extend([("int64_t", "rows", False), ("int64_t", "cols", False)]) | ||
| 55 | + entry_params = params + [("int64_t", "ffts_addr", True)] | ||
| 56 | + signature = ", ".join(f"{typ}{'*' if ptr else ''} {name}" for typ, name, ptr in entry_params) | ||
| 57 | + stores = "\n".join( | ||
| 58 | + f" std::memcpy(&out[{i}], &v{i}, sizeof(v{i}));" for i in range(len(SCALARS)) | ||
| 59 | + ) | ||
| 60 | + (root / "kernel.cpp").write_text(f"""#include <cstring> | ||
| 61 | +#define __global__ | ||
| 62 | +#define __vector__ | ||
| 63 | +#define __gm__ | ||
| 64 | +static int64_t syncCookie = 0x12345678; | ||
| 65 | +static void rtGetC2cCtrlAddr(uint64_t* addr, uint32_t* size) | ||
| 66 | +{{ | ||
| 67 | + *addr = reinterpret_cast<uint64_t>(&syncCookie); | ||
| 68 | + *size = sizeof(syncCookie); | ||
| 69 | +}} | ||
| 70 | +static void probe_impl({signature}) | ||
| 71 | +{{ | ||
| 72 | +{stores} | ||
| 73 | + out[10] = rows; | ||
| 74 | + out[11] = cols; | ||
| 75 | + out[12] = *ffts_addr; | ||
| 76 | +}} | ||
| 77 | +""") | ||
| 78 | + target = jit.get_jit_compile_config().resolve_kernel_target("a5", has_cube=False, has_vector=True) | ||
| 79 | + entry = jit._make_global_entry("probe", entry_params, target=target) | ||
| 80 | + entry += """template<class... Args> void CheckLaunchSlots(Args... args) | ||
| 81 | +{ | ||
| 82 | + static_assert(((sizeof(Args) == 8) && ...), "Every physical launch slot must occupy eight bytes"); | ||
| 83 | + probe(args...); | ||
| 84 | +} | ||
| 85 | +""" | ||
| 86 | + caller = jit._generate_caller_cpp( | ||
| 87 | + params, "kernel.cpp", "probe", has_cross_core_sync=True, target=target, global_entry=entry, | ||
| 88 | + ) | ||
| 89 | + # Replace only the ASC dispatch; compile the real host encoder and device decoder. | ||
| 90 | + caller = caller.replace("probe<<<blockDim, nullptr, stream>>>(", "CheckLaunchSlots(") | ||
| 91 | + source = root / "caller.cpp" | ||
| 92 | + source.write_text(caller) | ||
| 93 | + library = root / "caller.so" | ||
| 94 | + result = subprocess.run( | ||
| 95 | + [compiler, "-x", "c++", "-std=c++17", "-O2", "-shared", "-fPIC", f"-I{root}", | ||
| 96 | + str(source), "-o", str(library)], capture_output=True, text=True, | ||
| 97 | + ) | ||
| 98 | + assert result.returncode == 0, result.stderr | ||
| 99 | + lib = ctypes.CDLL(str(library)) | ||
| 100 | + scalar_types = [ctype for _, ctype in SCALARS] | ||
| 101 | + scalar_types.insert(1, ctypes.c_void_p) | ||
| 102 | + lib.call_kernel.argtypes = [ctypes.c_uint32, ctypes.c_void_p, *scalar_types, ctypes.c_int64, ctypes.c_int64] | ||
| 103 | + lib.call_kernel.restype = ctypes.c_int64 | ||
| 104 | + return lib | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +@pytest.mark.parametrize("upper", [False, True]) | ||
| 108 | +@pytest.mark.parametrize("float_bits", [0x00000000, 0x80000000, 0x3FA00000, 0x7F800000, 0xFF800000, 0x7FC12345]) | ||
| 109 | +def test_scalar_launch_round_trip(native_scalar_launcher, upper, float_bits): | ||
| 110 | + values = [] | ||
| 111 | + for typ, ctype in SCALARS: | ||
| 112 | + bits = ctypes.sizeof(ctype) * 8 | ||
| 113 | + if typ == "float": | ||
| 114 | + value = struct.unpack("f", struct.pack("I", float_bits))[0] | ||
| 115 | + elif typ == "bool": | ||
| 116 | + value = upper | ||
| 117 | + elif typ.startswith("uint"): | ||
| 118 | + value = (1 << bits) - 1 if upper else 0 | ||
| 119 | + else: | ||
| 120 | + value = (1 << (bits - 1)) - 1 if upper else -(1 << (bits - 1)) | ||
| 121 | + values.append(value) | ||
| 122 | + # Compare bytes, including signed zero/NaN payloads and the full uint64 range. | ||
| 123 | + expected = [int.from_bytes(bytes(ctype(value)), "little") for (_, ctype), value in zip(SCALARS, values)] | ||
| 124 | + out = (ctypes.c_uint64 * 13)() | ||
| 125 | + values.insert(1, ctypes.addressof(out)) | ||
| 126 | + assert native_scalar_launcher.call_kernel(1, None, *values, 65, 96) == 1 | ||
| 127 | + assert list(out) == [*expected, 65, 96, 0x12345678] | ||