Merged
feat(machine): Support offline compilation and packaging #4974
W4termyAdd on Jul 21
feat(machine): Support offline compilation and packaging #4974
Merged
Merged fromW4termy/pyptojdintocann/pyptomaster
Total: 34 files changed+3072-6
| @@ -119,6 +119,7 @@ if (ENABLE_FEATURE_PYTHON_FRONT_END) | |||
| 119 | tile_fwk_codegen | 119 | tile_fwk_codegen |
| 120 | tile_fwk_compiler | 120 | tile_fwk_compiler |
| 121 | tile_fwk_runtime | 121 | tile_fwk_runtime |
| 122 | + tile_fwk_bundle | ||
| 122 | tile_fwk_simulation | 123 | tile_fwk_simulation |
| 123 | tile_fwk_simulation_pv | 124 | tile_fwk_simulation_pv |
| 124 | ) | 125 | ) |
| @@ -183,6 +184,16 @@ if (ENABLE_FEATURE_PYTHON_FRONT_END) | |||
| 183 | PATTERN ".git" EXCLUDE | 184 | PATTERN ".git" EXCLUDE |
| 184 | ) | 185 | ) |
| 185 | 186 | ||
| 187 | + # 3. kernel bundle 对外 ABI 头文件 | ||
| 188 | + # libtile_fwk_bundle.so 的调用方(脱离编译前端, 仅消费 .pyptokb)需要 | ||
| 189 | + install(DIRECTORY framework/include/tile_fwk_bundle/ | ||
| 190 | + DESTINATION ${PyPTO_WhlName}/lib/include/tile_fwk_bundle | ||
| 191 | + PATTERN "*.h" | ||
| 192 | + PATTERN "*.hpp" | ||
| 193 | + PATTERN ".svn" EXCLUDE | ||
| 194 | + PATTERN ".git" EXCLUDE | ||
| 195 | + ) | ||
| 196 | + | ||
| 186 | # 安装 在线编译二进制必需文件 | 197 | # 安装 在线编译二进制必需文件 |
| 187 | 198 | ||
| 188 | # 1. cmake 配置文件 | 199 | # 1. cmake 配置文件 |
| @@ -115,6 +115,27 @@ | |||
| 115 | ] | 115 | ] |
| 116 | } | 116 | } |
| 117 | }, | 117 | }, |
| 118 | + "libtile_fwk_bundle.so": { | ||
| 119 | + "Source-Header": { | ||
| 120 | + "Self": [ | ||
| 121 | + "framework/src/machine/runtime/bundle/" | ||
| 122 | + ], | ||
| 123 | + "Area": [ | ||
| 124 | + "framework/src/adapter", | ||
| 125 | + "framework/src/interface/", | ||
| 126 | + "framework/src/passes/", | ||
| 127 | + "framework/src/machine/", | ||
| 128 | + "framework/src/utils" | ||
| 129 | + ], | ||
| 130 | + "Include": [ | ||
| 131 | + "framework/include/" | ||
| 132 | + ], | ||
| 133 | + "WhiteList": [ | ||
| 134 | + ], | ||
| 135 | + "BlackList": [ | ||
| 136 | + ] | ||
| 137 | + } | ||
| 138 | + }, | ||
| 118 | "libtile_fwk_runtime.so": { | 139 | "libtile_fwk_runtime.so": { |
| 119 | "Source-Header": { | 140 | "Source-Header": { |
| 120 | "Self": [ | 141 | "Self": [ |
| @@ -0,0 +1,57 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file pypto_bundle_api.h | ||
| 13 | + * \brief Two-operation C ABI for a PyPTO kernel bundle (.pyptokb): Workspace + Launch, in a path-based and an | ||
| 14 | + * in-memory flavor. | ||
| 15 | + * | ||
| 16 | + * Each entry takes a single unified tensor list (all operands including outputs, indexed by flat position). Init / | ||
| 17 | + * Load / Unload / device-memory are internalized: an idempotent load (cached by hashKey) seeds the AiCpu .so from | ||
| 18 | + * the bundle, arch-checks, and registers the kernel, all lazily. | ||
| 19 | + */ | ||
| 20 | + | ||
| 21 | +#ifndef PYPTO_BUNDLE_API_H | ||
| 22 | +#define PYPTO_BUNDLE_API_H | ||
| 23 | + | ||
| 24 | +#include <stdint.h> | ||
| 25 | + | ||
| 26 | +#ifdef __cplusplus | ||
| 27 | +extern "C" { | ||
| 28 | +#endif | ||
| 29 | + | ||
| 30 | +typedef struct { // one tensor operand passed across the C ABI | ||
| 31 | + void* addr; // device memory address | ||
| 32 | + int32_t dataType; // matches the internal DataType enum (tilefwk/data_type.h) | ||
| 33 | + int32_t rank; | ||
| 34 | + int64_t shape[8]; // up to 8 dims | ||
| 35 | +} PyptoTensorDesc; | ||
| 36 | + | ||
| 37 | +/* Workspace query for the given tensor shapes. Returns the workspace bytes the caller must allocate before Launch | ||
| 38 | + * (0 on failure / no workspace). Pure host computation: does NOT initialize the device. */ | ||
| 39 | +uint64_t PyptoWorkspace(const char* path, const PyptoTensorDesc* tensors, uint32_t nTensors); | ||
| 40 | + | ||
| 41 | +/* Launch the bundle on the given tensors. workspaceAddr may be NULL when PyptoWorkspace returned 0. The first | ||
| 42 | + * Launch of the process lazily initializes the runtime. sync!=0 waits for completion. Returns 0 on success. */ | ||
| 43 | +int PyptoLaunch(const char* path, const PyptoTensorDesc* tensors, uint32_t nTensors, void* workspaceAddr, void* stream, | ||
| 44 | + int sync); | ||
| 45 | + | ||
| 46 | +/* In-memory variants: same semantics, but `bundleData`/`bundleSize` is a caller-loaded .pyptokb byte image. */ | ||
| 47 | +uint64_t PyptoWorkspaceFromMemory(const void* bundleData, uint64_t bundleSize, const PyptoTensorDesc* tensors, | ||
| 48 | + uint32_t nTensors); | ||
| 49 | + | ||
| 50 | +int PyptoLaunchFromMemory(const void* bundleData, uint64_t bundleSize, const PyptoTensorDesc* tensors, | ||
| 51 | + uint32_t nTensors, void* workspaceAddr, void* stream, int sync); | ||
| 52 | + | ||
| 53 | +#ifdef __cplusplus | ||
| 54 | +} | ||
| 55 | +#endif | ||
| 56 | + | ||
| 57 | +#endif // PYPTO_BUNDLE_API_H | ||
| @@ -9,6 +9,17 @@ | |||
| 9 | # ----------------------------------------------------------------------------------------------------------- | 9 | # ----------------------------------------------------------------------------------------------------------- |
| 10 | 10 | ||
| 11 | file(GLOB_RECURSE _Runtime_Srcs *.cpp) | 11 | file(GLOB_RECURSE _Runtime_Srcs *.cpp) |
| 12 | +# The kernel-bundle load/query/launch half ships as its own ABI library (libtile_fwk_bundle.so, see bundle/ | ||
| 13 | +# CMakeLists.txt) and must NOT be linked into tile_fwk_runtime as well. Only the pack half stays here, because | ||
| 14 | +# its hooks are called from emulation_launcher.cpp / kernel_binary.cpp -- that is what would otherwise make the | ||
| 15 | +# two targets circularly dependent. | ||
| 16 | +# | ||
| 17 | +# The split is by DIRECTORY, not by a file whitelist: everything directly under bundle/ belongs to the ABI | ||
| 18 | +# library, the pack half lives one level down in bundle/pack/ and is picked up by the recursive glob above. | ||
| 19 | +# bundle/CMakeLists.txt globs its own sources with the same non-recursive pattern, so new files on either side | ||
| 20 | +# land in the right target automatically with no list to keep in sync. | ||
| 21 | +file(GLOB _Bundle_Load_Srcs ${CMAKE_CURRENT_SOURCE_DIR}/bundle/*.cpp) | ||
| 22 | +list(REMOVE_ITEM _Runtime_Srcs ${_Bundle_Load_Srcs}) | ||
| 12 | file(GLOB_RECURSE _Device_Srcs ${PTO_FWK_SRC_ROOT}/framework/src/machine/device/*.cpp) | 23 | file(GLOB_RECURSE _Device_Srcs ${PTO_FWK_SRC_ROOT}/framework/src/machine/device/*.cpp) |
| 13 | file(GLOB _Device_Utils_Srcs | 24 | file(GLOB _Device_Utils_Srcs |
| 14 | ${PTO_FWK_SRC_ROOT}/framework/src/machine/utils/dynamic/dev_encode_function.cpp | 25 | ${PTO_FWK_SRC_ROOT}/framework/src/machine/utils/dynamic/dev_encode_function.cpp |
| @@ -45,3 +56,6 @@ target_link_libraries(tile_fwk_runtime | |||
| 45 | 56 | ||
| 46 | PTO_Fwk_AnalysisTargetHeaderFiles(TARGET tile_fwk_runtime) | 57 | PTO_Fwk_AnalysisTargetHeaderFiles(TARGET tile_fwk_runtime) |
| 47 | PTO_Fwk_AnalysisTargetSymbols(TARGET tile_fwk_runtime) | 58 | PTO_Fwk_AnalysisTargetSymbols(TARGET tile_fwk_runtime) |
| 59 | + | ||
| 60 | +# Standalone kernel-bundle ABI library; must come after tile_fwk_runtime, which it links against. | ||
| 61 | +add_subdirectory(bundle) | ||
| @@ -0,0 +1,252 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2025-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 | +# libtile_fwk_bundle.so -- the standalone .pyptokb consumer ABI (PyptoWorkspace / PyptoLaunch [+FromMemory]). | ||
| 12 | +# | ||
| 13 | +# Only the LOAD/QUERY/LAUNCH half of the bundle code lives in THIS directory. The PACK half lives one level down | ||
| 14 | +# in pack/ and stays in tile_fwk_runtime, because its hooks are called from the runtime's own emulation/launch | ||
| 15 | +# paths; splitting on that boundary is what keeps the two targets acyclic. | ||
| 16 | +# | ||
| 17 | +# The glob is deliberately non-recursive so pack/ is excluded by directory rather than by a file list: the | ||
| 18 | +# runtime's own CMakeLists.txt removes ${CMAKE_CURRENT_SOURCE_DIR}/bundle/*.cpp from its recursive glob with the | ||
| 19 | +# same pattern, so the two targets stay in sync as files are added on either side. | ||
| 20 | +file(GLOB _TileFwkBundle_Srcs ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) | ||
| 21 | + | ||
| 22 | +# Export only the four C entry points; everything else (registry/loader/dev-cache internals) stays local so the | ||
| 23 | +# library presents exactly the documented ABI surface. Shared by both flavours below. | ||
| 24 | +set(_TileFwkBundle_VerScript ${CMAKE_CURRENT_SOURCE_DIR}/tile_fwk_bundle.version) | ||
| 25 | + | ||
| 26 | +add_library(tile_fwk_bundle SHARED) | ||
| 27 | +target_sources(tile_fwk_bundle PRIVATE ${_TileFwkBundle_Srcs}) | ||
| 28 | +target_compile_definitions(tile_fwk_bundle | ||
| 29 | + PUBLIC | ||
| 30 | + $<BUILD_INTERFACE:$<$<BOOL:${ENABLE_STEST_INTERPRETER_CONFIG}>:ENABLE_STEST_INTERPRETER_CONFIG>> | ||
| 31 | +) | ||
| 32 | +target_link_libraries(tile_fwk_bundle | ||
| 33 | + PRIVATE | ||
| 34 | + -Wl,--no-as-needed | ||
| 35 | + tile_fwk_runtime | ||
| 36 | + tile_fwk_interface | ||
| 37 | + tile_fwk_codegen | ||
| 38 | + tile_fwk_compiler | ||
| 39 | + tile_fwk_adapter | ||
| 40 | + tile_fwk_platform | ||
| 41 | + tile_fwk_cann_host_runtime | ||
| 42 | + tile_fwk_utils | ||
| 43 | + -Wl,--as-needed | ||
| 44 | + $<BUILD_INTERFACE:json> | ||
| 45 | + intf_pub_cxx17 | ||
| 46 | + tile_fwk_intf_pub | ||
| 47 | + dl | ||
| 48 | + c_sec | ||
| 49 | +) | ||
| 50 | +target_link_options(tile_fwk_bundle PRIVATE "-Wl,--version-script=${_TileFwkBundle_VerScript}") | ||
| 51 | +set_target_properties(tile_fwk_bundle PROPERTIES LINK_DEPENDS ${_TileFwkBundle_VerScript}) | ||
| 52 | + | ||
| 53 | +PTO_Fwk_AnalysisTargetHeaderFiles(TARGET tile_fwk_bundle) | ||
| 54 | +PTO_Fwk_AnalysisTargetSymbols(TARGET tile_fwk_bundle) | ||
| 55 | + | ||
| 56 | +# --------------------------------------------------------------------------------------------------------------- | ||
| 57 | +# Optional: libtile_fwk_bundle_standalone.so -- same four symbols, but self-contained. | ||
| 58 | +# | ||
| 59 | +# WHY: the plain tile_fwk_bundle above still needs libtile_fwk_runtime.so (and transitively interface/adapter/ | ||
| 60 | +# platform/utils) present on the target machine. This flavour statically absorbs that whole closure so a consumer | ||
| 61 | +# that only runs .pyptokb files can ship ONE .so. CANN itself is never absorbed -- it is dlopen'd by name at | ||
| 62 | +# runtime (adapter/manager/plugin_handler.cpp), so it never appears in DT_NEEDED either way. | ||
| 63 | +# | ||
| 64 | +# OFF by default ON PURPOSE: it recompiles ~195 upstream sources into its own objects (they cannot be shared, | ||
| 65 | +# because sharing them would mean editing the upstream CMakeLists outside this directory), which roughly doubles | ||
| 66 | +# a full build. Turn it on only when producing a delivery artifact: | ||
| 67 | +# cmake -DENABLE_TILE_FWK_BUNDLE_STANDALONE=ON ... | ||
| 68 | +# | ||
| 69 | +# CONSTRAINT: this library must NOT be loaded into a process that also loads the regular pypto stack. Both would | ||
| 70 | +# carry their own copy of every Meyers singleton on the closure (Platform::Instance, DeviceRunner::Get, | ||
| 71 | +# ConfigManager::Instance, OpInfoManager, plus the bundle's own registry/dev-cache), so state set through one | ||
| 72 | +# would be invisible to the other -- silent divergence, not a crash. Pure .pyptokb consumers satisfy this | ||
| 73 | +# naturally; anything that also drives the Python frontend must use the plain tile_fwk_bundle instead. | ||
| 74 | +# --------------------------------------------------------------------------------------------------------------- | ||
| 75 | +option(ENABLE_TILE_FWK_BUNDLE_STANDALONE "Build the self-contained libtile_fwk_bundle_standalone.so" OFF) | ||
| 76 | + | ||
| 77 | +if (ENABLE_TILE_FWK_BUNDLE_STANDALONE) | ||
| 78 | + set(_FwkRoot ${PTO_FWK_SRC_ROOT}/framework/src) | ||
| 79 | + | ||
| 80 | + # The upstream source globs are directory-scoped variables, so they are not visible here; they are re-globbed | ||
| 81 | + # with the SAME patterns as the upstream CMakeLists. Keeping the patterns (rather than a file list) means new | ||
| 82 | + # upstream files are picked up automatically. The upstream per-target compile definitions / include dirs are | ||
| 83 | + # NOT visible either and are restated below -- if upstream changes those, this target must be updated to match. | ||
| 84 | + file(GLOB _SA_Interface_Srcs | ||
| 85 | + ${_FwkRoot}/interface/compiler_monitor/*.cpp | ||
| 86 | + ${_FwkRoot}/interface/core/*.cpp | ||
| 87 | + ${_FwkRoot}/interface/ir/*.cpp | ||
| 88 | + ${_FwkRoot}/interface/ir/op/*.cpp | ||
| 89 | + ${_FwkRoot}/interface/ir/op/*/*.cpp | ||
| 90 | + ${_FwkRoot}/interface/ir/reporter/*.cpp | ||
| 91 | + ${_FwkRoot}/interface/ir/transforms/*.cpp | ||
| 92 | + ${_FwkRoot}/interface/ir/transforms/utils/*.cpp | ||
| 93 | + ${_FwkRoot}/interface/ir/verifier/*.cpp | ||
| 94 | + ${_FwkRoot}/interface/schema/*.cpp | ||
| 95 | + ${_FwkRoot}/interface/configs/*.cpp | ||
| 96 | + ${_FwkRoot}/interface/tensor/*.cpp | ||
| 97 | + ${_FwkRoot}/interface/program/*.cpp | ||
| 98 | + ${_FwkRoot}/interface/function/*.cpp | ||
| 99 | + ${_FwkRoot}/interface/interpreter/*.cpp | ||
| 100 | + ${_FwkRoot}/interface/utils/*.cpp | ||
| 101 | + ${_FwkRoot}/interface/plugin/*.cpp | ||
| 102 | + ${_FwkRoot}/interface/operation/*.cpp | ||
| 103 | + ${_FwkRoot}/interface/operation/vector/*.cpp | ||
| 104 | + ${_FwkRoot}/interface/operation/distributed/*.cpp | ||
| 105 | + ${_FwkRoot}/interface/cache/*.cpp | ||
| 106 | + ${_FwkRoot}/interface/machine/*.cpp | ||
| 107 | + ${_FwkRoot}/interface/machine/host/*.cpp | ||
| 108 | + ${_FwkRoot}/interface/registry/*.cpp | ||
| 109 | + ) | ||
| 110 | + file(GLOB_RECURSE _SA_PyptoPro_Srcs | ||
| 111 | + ${_FwkRoot}/interface/pypto_pro/backend/*.cpp | ||
| 112 | + ${_FwkRoot}/interface/pypto_pro/codegen/*.cpp | ||
| 113 | + ) | ||
| 114 | + # framework/src/passes lives in its own directory but injects itself into tile_fwk_interface | ||
| 115 | + # (passes/CMakeLists.txt: target_sources(tile_fwk_interface ...)), so it is part of the interface library | ||
| 116 | + # even though it is outside interface/. Missing it shows up as undefined CommonUtils::* at dlopen time. | ||
| 117 | + file(GLOB_RECURSE _SA_Passes_Srcs ${_FwkRoot}/passes/*.cpp) | ||
| 118 | + file(GLOB_RECURSE _SA_Utils_Srcs | ||
| 119 | + ${_FwkRoot}/utils/host_log/*.cpp | ||
| 120 | + ${_FwkRoot}/utils/error_manager/*.cpp | ||
| 121 | + ${_FwkRoot}/utils/file_utils.cpp | ||
| 122 | + ) | ||
| 123 | + file(GLOB _SA_Platform_Srcs | ||
| 124 | + ${_FwkRoot}/platform/*.cpp | ||
| 125 | + ${_FwkRoot}/platform/parser/*.cpp | ||
| 126 | + ${_FwkRoot}/platform/parser/simulation_platform/*.cpp | ||
| 127 | + ) | ||
| 128 | + file(GLOB_RECURSE _SA_Adapter_Srcs | ||
| 129 | + ${_FwkRoot}/adapter/api/*.cpp | ||
| 130 | + ${_FwkRoot}/adapter/manager/*.cpp | ||
| 131 | + ${_FwkRoot}/adapter/stubs/*.cpp | ||
| 132 | + ) | ||
| 133 | + file(GLOB _SA_CannHostRt_Srcs ${_FwkRoot}/cann_host_runtime/*.cpp) | ||
| 134 | + | ||
| 135 | + # Runtime half: everything tile_fwk_runtime builds, plus the bundle load-side sources, plus the two | ||
| 136 | + # dev_encode TUs that only libtile_fwk_compiler exports (DevControlFlowCache::Init and | ||
| 137 | + # DevAscendProgram::GetCtrlFlowCacheSlottedOutcastBlockCount). Pulling those two files in directly -- rather | ||
| 138 | + # than moving them out of the compiler glob upstream -- is what keeps this change inside bundle/. | ||
| 139 | + file(GLOB_RECURSE _SA_Runtime_Srcs ${_FwkRoot}/machine/runtime/*.cpp) | ||
| 140 | + list(REMOVE_ITEM _SA_Runtime_Srcs ${_TileFwkBundle_Srcs}) | ||
| 141 | + file(GLOB_RECURSE _SA_Device_Srcs ${_FwkRoot}/machine/device/*.cpp) | ||
| 142 | + file(GLOB_RECURSE _SA_Simulation_Srcs ${_FwkRoot}/machine/simulation/*.cpp) | ||
| 143 | + file(GLOB _SA_DevUtils_Srcs | ||
| 144 | + ${_FwkRoot}/machine/utils/dynamic/dev_encode_function.cpp | ||
| 145 | + ${_FwkRoot}/machine/utils/dynamic/dev_encode_function_dupped_data.cpp | ||
| 146 | + ${_FwkRoot}/machine/utils/dynamic/dev_encode_program.cpp | ||
| 147 | + ${_FwkRoot}/machine/utils/dynamic/dev_cell_match_dump.cpp | ||
| 148 | + ${_FwkRoot}/machine/utils/dynamic/dev_encode_program_ctrlflow_cache.cpp | ||
| 149 | + ${_FwkRoot}/machine/utils/dynamic/dev_workspace.cpp | ||
| 150 | + ${_FwkRoot}/machine/utils/dynamic/dev_encode.cpp | ||
| 151 | + ${_FwkRoot}/machine/utils/dynamic/dev_encode_workspace.cpp | ||
| 152 | + ) | ||
| 153 | + | ||
| 154 | + add_library(tile_fwk_bundle_standalone SHARED) | ||
| 155 | + target_sources(tile_fwk_bundle_standalone PRIVATE | ||
| 156 | + ${_TileFwkBundle_Srcs} | ||
| 157 | + ${_SA_Interface_Srcs} ${_SA_PyptoPro_Srcs} ${_SA_Passes_Srcs} | ||
| 158 | + ${_SA_Utils_Srcs} ${_SA_Platform_Srcs} ${_SA_Adapter_Srcs} ${_SA_CannHostRt_Srcs} | ||
| 159 | + ${_SA_Runtime_Srcs} ${_SA_Device_Srcs} ${_SA_Simulation_Srcs} ${_SA_DevUtils_Srcs} | ||
| 160 | + ) | ||
| 161 | + set_target_properties(tile_fwk_bundle_standalone PROPERTIES OUTPUT_NAME tile_fwk_bundle_standalone) | ||
| 162 | + | ||
| 163 | + # Include dirs / definitions restated from the upstream targets (see note above the globs). | ||
| 164 | + target_include_directories(tile_fwk_bundle_standalone | ||
| 165 | + PRIVATE | ||
| 166 | + ${_FwkRoot}/interface | ||
| 167 | + ${_FwkRoot}/utils | ||
| 168 | + ${_FwkRoot}/adapter | ||
| 169 | + ${_FwkRoot}/cost_model | ||
| 170 | + ${PTO_FWK_SRC_ROOT}/framework/include/pypto_pro | ||
| 171 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:${ASCEND_CANN_PACKAGE_PATH}/pkg_inc>> | ||
| 172 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/base>> | ||
| 173 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/profiling>> | ||
| 174 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/runtime>> | ||
| 175 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/runtime/runtime>> | ||
| 176 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:${ASCEND_CANN_PACKAGE_PATH}/include/experiment/runtime>> | ||
| 177 | + ) | ||
| 178 | + target_compile_definitions(tile_fwk_bundle_standalone | ||
| 179 | + PRIVATE | ||
| 180 | + $<$<BOOL:${ENABLE_TESTS}>:ENABLE_TESTS> | ||
| 181 | + $<BUILD_INTERFACE:$<$<BOOL:${ENABLE_STEST_INTERPRETER_CONFIG}>:ENABLE_STEST_INTERPRETER_CONFIG>> | ||
| 182 | + $<BUILD_INTERFACE:$<$<AND:$<BOOL:${BUILD_WITH_CANN}>,$<NOT:$<BOOL:${ENABLE_UTEST}>>>:BUILD_WITH_CANN>> | ||
| 183 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN_MOBILE}>:BUILD_WITH_CANN_MOBILE>> | ||
| 184 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:PROCESSOR_SUBPATH="${CMAKE_SYSTEM_PROCESSOR}-linux">> | ||
| 185 | + ) | ||
| 186 | + target_link_directories(tile_fwk_bundle_standalone | ||
| 187 | + PRIVATE | ||
| 188 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:${ASCEND_CANN_PACKAGE_PATH}/lib64>> | ||
| 189 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:/usr/local/Ascend/driver/lib64/driver>> | ||
| 190 | + $<BUILD_INTERFACE:$<$<BOOL:${BUILD_WITH_CANN}>:${ASCEND_CANN_PACKAGE_PATH}/${CMAKE_SYSTEM_PROCESSOR}-linux/devlib>> | ||
| 191 | + ) | ||
| 192 | + # No pypto libraries here on purpose -- only the header-only / INTERFACE deps and system libs. | ||
| 193 | + # c_sec is deliberately absent: it is handled just below so the shared flavour stays out of DT_NEEDED. | ||
| 194 | + target_link_libraries(tile_fwk_bundle_standalone | ||
| 195 | + PRIVATE | ||
| 196 | + $<BUILD_INTERFACE:json> | ||
| 197 | + intf_pub_cxx17 | ||
| 198 | + tile_fwk_intf_pub | ||
| 199 | + dl rt | ||
| 200 | + Threads::Threads | ||
| 201 | + ) | ||
| 202 | + # c_sec normally resolves to a shared libc_sec.so, which would be the one pypto-side runtime dependency left | ||
| 203 | + # in DT_NEEDED. Absorb the static archive instead when one is available, so the delivered .so needs nothing | ||
| 204 | + # from the pypto/CANN lib directory at load time. Falls back to the shared flavour when absent. | ||
| 205 | + # | ||
| 206 | + # `c_sec` is an IMPORTED SHARED target, so linking it puts libc_sec.so back into DT_NEEDED. Take the include | ||
| 207 | + # dir only -- via the header-only INTERFACE target `c_sec_headers` declared by cann-cmake's Findsecurec.cmake | ||
| 208 | + # -- and link the archive explicitly. (Guarded: the target name belongs to cann-cmake, not to us.) | ||
| 209 | + find_library(_TileFwkBundle_CSecStatic | ||
| 210 | + NAMES libc_sec.a | ||
| 211 | + PATHS ${ASCEND_CANN_PACKAGE_PATH}/${CMAKE_SYSTEM_PROCESSOR}-linux/lib64 | ||
| 212 | + ${ASCEND_CANN_PACKAGE_PATH}/lib64 | ||
| 213 | + ${PYPTO_THIRD_PARTY_PATH}/${CMAKE_BUILD_TYPE}/lib | ||
| 214 | + NO_DEFAULT_PATH | ||
| 215 | + ) | ||
| 216 | + if (_TileFwkBundle_CSecStatic) | ||
| 217 | + if (TARGET c_sec_headers) | ||
| 218 | + target_link_libraries(tile_fwk_bundle_standalone PRIVATE c_sec_headers) | ||
| 219 | + else () | ||
| 220 | + # Older cann-cmake without the header-only target: fall back to the include dir off `c_sec` itself. | ||
| 221 | + get_target_property(_CSecIncDir c_sec INTERFACE_INCLUDE_DIRECTORIES) | ||
| 222 | + target_include_directories(tile_fwk_bundle_standalone PRIVATE ${_CSecIncDir}) | ||
| 223 | + endif () | ||
| 224 | + target_link_libraries(tile_fwk_bundle_standalone PRIVATE ${_TileFwkBundle_CSecStatic}) | ||
| 225 | + # Do not re-export the absorbed archive's symbols from this .so; only the four ABI entries are public. | ||
| 226 | + target_link_options(tile_fwk_bundle_standalone PRIVATE "-Wl,--exclude-libs,ALL") | ||
| 227 | + message(STATUS "tile_fwk_bundle_standalone: absorbing static c_sec ${_TileFwkBundle_CSecStatic}") | ||
| 228 | + else () | ||
| 229 | + target_link_libraries(tile_fwk_bundle_standalone PRIVATE c_sec) | ||
| 230 | + message(STATUS "tile_fwk_bundle_standalone: no static c_sec found; libc_sec.so stays a runtime dependency") | ||
| 231 | + endif () | ||
| 232 | + # Section-level GC: the closure touches well under 1% of the interface library's exported symbols, so most of | ||
| 233 | + # what gets compiled in is dead weight without this. | ||
| 234 | + target_compile_options(tile_fwk_bundle_standalone PRIVATE -ffunction-sections -fdata-sections) | ||
| 235 | + target_link_options(tile_fwk_bundle_standalone PRIVATE | ||
| 236 | + "-Wl,--gc-sections" | ||
| 237 | + "-Wl,--version-script=${_TileFwkBundle_VerScript}" | ||
| 238 | + # Fail at LINK time on any unresolved symbol. Without this a source-glob gap (e.g. a directory that | ||
| 239 | + # injects itself into an upstream target from elsewhere) links cleanly and only surfaces as an | ||
| 240 | + # "undefined symbol" OSError when the consumer dlopen's the delivered .so. | ||
| 241 | + "-Wl,--no-undefined" | ||
| 242 | + ) | ||
| 243 | + set_target_properties(tile_fwk_bundle_standalone PROPERTIES LINK_DEPENDS ${_TileFwkBundle_VerScript}) | ||
| 244 | + | ||
| 245 | + # The aicpu backend .so (tile_fwk_server) is built by the separate `cann_device` ExternalProject | ||
| 246 | + # (cmake/device/CMakeLists.txt), so it is NOT a target in this host tree -- an unguarded | ||
| 247 | + # add_dependencies() here fails configure outright with "dependency target does not exist". | ||
| 248 | + # Depend on it only when it really is a host target; the device build is otherwise driven by its own entry. | ||
| 249 | + if (BUILD_WITH_CANN AND TARGET tile_fwk_server) | ||
| 250 | + add_dependencies(tile_fwk_bundle_standalone tile_fwk_server) | ||
| 251 | + endif () | ||
| 252 | +endif () | ||
| @@ -0,0 +1,53 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_crc32.h | ||
| 13 | + * \brief Standard IEEE-802.3 CRC32 (reflected poly 0xEDB88320). Header-only, table computed on first use. | ||
| 14 | + * Matches zlib crc32() / `cksum -o3`, so a packed .pyptokb can be verified with off-the-shelf tools. | ||
| 15 | + */ | ||
| 16 | + | ||
| 17 | +#pragma once | ||
| 18 | + | ||
| 19 | +#include <cstddef> | ||
| 20 | +#include <cstdint> | ||
| 21 | + | ||
| 22 | +namespace npu::tile_fwk::bundle { | ||
| 23 | + | ||
| 24 | +inline const uint32_t* Crc32Table() | ||
| 25 | +{ | ||
| 26 | + static uint32_t table[256]; | ||
| 27 | + static bool inited = false; | ||
| 28 | + if (!inited) { | ||
| 29 | + for (uint32_t i = 0; i < 256; ++i) { | ||
| 30 | + uint32_t c = i; | ||
| 31 | + for (int k = 0; k < 8; ++k) { | ||
| 32 | + c = (c & 1U) ? (0xEDB88320U ^ (c >> 1)) : (c >> 1); | ||
| 33 | + } | ||
| 34 | + table[i] = c; | ||
| 35 | + } | ||
| 36 | + inited = true; | ||
| 37 | + } | ||
| 38 | + return table; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +// CRC32 of a byte range. Chainable via the `crc` seed (pass 0 for a fresh computation). | ||
| 42 | +inline uint32_t Crc32(const void* data, size_t len, uint32_t crc = 0) | ||
| 43 | +{ | ||
| 44 | + const uint32_t* table = Crc32Table(); | ||
| 45 | + const uint8_t* p = static_cast<const uint8_t*>(data); | ||
| 46 | + crc = crc ^ 0xFFFFFFFFU; | ||
| 47 | + for (size_t i = 0; i < len; ++i) { | ||
| 48 | + crc = table[(crc ^ p[i]) & 0xFFU] ^ (crc >> 8); | ||
| 49 | + } | ||
| 50 | + return crc ^ 0xFFFFFFFFU; | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,84 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_dev_cache.cpp | ||
| 13 | + * \brief Implementation of the per-bundle control-flow-cache device buffer singleton. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "machine/runtime/bundle/kernel_bundle_dev_cache.h" | ||
| 17 | + | ||
| 18 | +#include "machine/runtime/memory_utils/device_memory_utils.h" | ||
| 19 | +#include "tilefwk/pypto_fwk_log.h" | ||
| 20 | + | ||
| 21 | +namespace npu::tile_fwk::bundle { | ||
| 22 | + | ||
| 23 | +KernelBundleDevCache& KernelBundleDevCache::Instance() | ||
| 24 | +{ | ||
| 25 | + static KernelBundleDevCache instance; | ||
| 26 | + return instance; | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +uint8_t* KernelBundleDevCache::GetOrCopy(uint64_t key, const std::vector<uint8_t>& hostCtrlCache) | ||
| 30 | +{ | ||
| 31 | + if (hostCtrlCache.empty()) { | ||
| 32 | + return nullptr; // launch path rebuilds the cache at runtime when absent | ||
| 33 | + } | ||
| 34 | + std::lock_guard<std::mutex> lk(mutex_); | ||
| 35 | + auto it = cache_.find(key); | ||
| 36 | + if (it != cache_.end()) { | ||
| 37 | + return it->second; // reuse the device buffer copied on a previous launch | ||
| 38 | + } | ||
| 39 | + // Huge-page path -> DevMemoryPool, so the destructor free stays consistent with the sentinel-checked teardown. | ||
| 40 | + dynamic::DeviceMemoryUtils devMem(true); | ||
| 41 | + uint8_t* dev = devMem.CopyToDev(const_cast<uint8_t*>(hostCtrlCache.data()), hostCtrlCache.size(), nullptr); | ||
| 42 | + cache_[key] = dev; | ||
🟡 Medium Priority 在 触发条件:首次 launch 时设备内存紧张, 建议:在将 dev 指针存入缓存前检查是否为 nullptr,若为 nullptr 则记录错误日志并直接返回 nullptr,不写入缓存,使得后续调用可以重试分配。 ![]() ![]() Incorrect? | |||
| 43 | + MACHINE_LOGI("[kernel-bundle] dev-cache: copied ctrl-flow cache key=%#lx size=%zuB (cached, reused hereafter)", key, | ||
| 44 | + hostCtrlCache.size()); | ||
| 45 | + return dev; | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +uint8_t* KernelBundleDevCache::GetOrAllocCellMatch(uint64_t key, uint64_t bytes) | ||
| 49 | +{ | ||
| 50 | + if (bytes == 0) { | ||
| 51 | + return nullptr; // op has no dynamic cell-match table for this shape | ||
| 52 | + } | ||
| 53 | + std::lock_guard<std::mutex> lk(mutex_); | ||
| 54 | + auto it = cellMatchCache_.find(key); | ||
| 55 | + if (it != cellMatchCache_.end() && it->second.addr != nullptr && it->second.capacity >= bytes) { | ||
| 56 | + return it->second.addr; // reuse the buffer allocated on a previous launch | ||
| 57 | + } | ||
| 58 | + dynamic::DeviceMemoryUtils devMem(true); | ||
| 59 | + if (it != cellMatchCache_.end() && it->second.addr != nullptr) { | ||
| 60 | + devMem.Free(it->second.addr); // a later shape needs a bigger pool: release the smaller buffer first | ||
| 61 | + } | ||
| 62 | + uint8_t* dev = devMem.AllocDev(static_cast<size_t>(bytes), nullptr); | ||
| 63 | + cellMatchCache_[key] = CellMatchBuf{dev, bytes}; | ||
| 64 | + MACHINE_LOGI("[kernel-bundle] dev-cache: alloc cell-match pool key=%#lx size=%luB (cached, reused hereafter)", key, | ||
| 65 | + static_cast<unsigned long>(bytes)); | ||
| 66 | + return dev; | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +KernelBundleDevCache::~KernelBundleDevCache() | ||
| 70 | +{ | ||
| 71 | + // Release every cached device buffer at once. Runs only on a normal process exit; the STs use os._exit(0), | ||
| 72 | + // which skips static destructors (the OS reclaims device memory on process death). | ||
| 73 | + dynamic::DeviceMemoryUtils devMem(true); | ||
| 74 | + for (auto& kv : cache_) { | ||
| 75 | + devMem.Free(kv.second); | ||
| 76 | + } | ||
| 77 | + cache_.clear(); | ||
| 78 | + for (auto& kv : cellMatchCache_) { | ||
| 79 | + devMem.Free(kv.second.addr); | ||
| 80 | + } | ||
| 81 | + cellMatchCache_.clear(); | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,59 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_dev_cache.h | ||
| 13 | + * \brief Process-wide cache of per-bundle control-flow-cache DEVICE buffers. | ||
| 14 | + * | ||
| 15 | + * The packed base-0 control-flow cache is copied host->device once per bundle (keyed by LoadedBundle::bundleKey, | ||
| 16 | + * a content digest -- NOT hashKey, which is equal across shape variants of one op) and reused across launches. | ||
| 17 | + * All cached device buffers are released together in the singleton destructor at process exit. | ||
| 18 | + */ | ||
| 19 | + | ||
| 20 | +#pragma once | ||
| 21 | + | ||
| 22 | +#include <cstdint> | ||
| 23 | +#include <mutex> | ||
| 24 | +#include <unordered_map> | ||
| 25 | +#include <vector> | ||
| 26 | + | ||
| 27 | +namespace npu::tile_fwk::bundle { | ||
| 28 | + | ||
| 29 | +class KernelBundleDevCache { | ||
| 30 | +public: | ||
| 31 | + static KernelBundleDevCache& Instance(); | ||
| 32 | + | ||
| 33 | + // Return the device pointer holding `hostCtrlCache` for `key`, copying host->device once and caching it for | ||
| 34 | + // reuse. Returns nullptr when `hostCtrlCache` is empty. Freed only in the destructor at exit. | ||
| 35 | + uint8_t* GetOrCopy(uint64_t key, const std::vector<uint8_t>& hostCtrlCache); | ||
| 36 | + | ||
| 37 | + // Return a device buffer of at least `bytes` for bundle `key`'s cell-match metadata pool, allocated once and | ||
| 38 | + // reused (grown if a later launch needs more). Returns nullptr when bytes==0. The device inits the pool in | ||
| 39 | + // place, so no host->device copy here. Freed in the destructor. | ||
| 40 | + uint8_t* GetOrAllocCellMatch(uint64_t key, uint64_t bytes); | ||
| 41 | + | ||
| 42 | + KernelBundleDevCache(const KernelBundleDevCache&) = delete; | ||
| 43 | + KernelBundleDevCache& operator=(const KernelBundleDevCache&) = delete; | ||
| 44 | + | ||
| 45 | +private: | ||
| 46 | + KernelBundleDevCache() = default; | ||
| 47 | + ~KernelBundleDevCache(); | ||
| 48 | + | ||
| 49 | + struct CellMatchBuf { | ||
| 50 | + uint8_t* addr{nullptr}; | ||
| 51 | + uint64_t capacity{0}; | ||
| 52 | + }; | ||
| 53 | + | ||
| 54 | + std::mutex mutex_; | ||
| 55 | + std::unordered_map<uint64_t, uint8_t*> cache_; // bundleKey -> device ctrl-flow-cache buffer | ||
| 56 | + std::unordered_map<uint64_t, CellMatchBuf> cellMatchCache_; // bundleKey -> device cell-match metadata pool | ||
| 57 | +}; | ||
| 58 | + | ||
| 59 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,82 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_format.h | ||
| 13 | + * \brief TLV on-disk format for the PyPTO kernel bundle (.pyptokb). | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#pragma once | ||
| 17 | + | ||
| 18 | +#include <cstdint> | ||
| 19 | +#include <cstdlib> | ||
| 20 | +#include <string> | ||
| 21 | + | ||
| 22 | +namespace npu::tile_fwk::bundle { | ||
| 23 | + | ||
| 24 | +constexpr uint64_t kBundleMagic = 0x00424B4F54505950ULL; // "PYPTOKB\0" (little-endian) | ||
| 25 | +constexpr uint32_t kBundleVersion = 1; | ||
| 26 | +constexpr uint32_t kValueAlign = 4096; // 4KB page alignment (mmap + page-wise CopyDataToDevice) | ||
| 27 | + | ||
| 28 | +enum class TlvType : uint32_t { | ||
| 29 | + AicoreKernel = 1, // dy_kernel_<hash>_0.o, opaque ELF blob for device | ||
| 30 | + AicpuSo = 2, // libtilefwk_backend_server.so, globally shared | ||
| 31 | + DevProgram = 3, // EncodeDevAscendProgram flat binary, base-0 relative offsets | ||
| 32 | + CtrlFlowCache = 4, // DevControlFlowCache blob (v1: single static-shape snapshot) | ||
| 33 | + SymbolMeta = 5, // JSON: dynamic-workspace SymbolicScalar trees + inputSymbolDict (may be empty/absent) | ||
| 34 | +}; | ||
| 35 | + | ||
| 36 | +struct BundleHeader { // 64 bytes | ||
| 37 | + uint64_t magic; | ||
| 38 | + uint32_t version; | ||
| 39 | + uint32_t flags; | ||
| 40 | + uint32_t tlvCount; | ||
| 41 | + uint32_t headerSize; | ||
| 42 | + uint64_t totalSize; | ||
| 43 | + uint8_t reserved[28]; | ||
| 44 | + uint32_t headerCrc32; // CRC32 over the first 60 bytes | ||
| 45 | +}; | ||
| 46 | +static_assert(sizeof(BundleHeader) == 64, "BundleHeader must be 64 bytes"); | ||
| 47 | + | ||
| 48 | +struct TlvHeader { // 32 bytes | ||
| 49 | + uint32_t type; // TlvType | ||
| 50 | + uint32_t flags; | ||
| 51 | + uint64_t valueOffset; // absolute file offset of value (4KB aligned) | ||
| 52 | + uint64_t valueLength; // value length in bytes (excluding padding) | ||
| 53 | + uint32_t valueCrc32; // CRC32 over value bytes | ||
| 54 | + uint32_t reserved; | ||
| 55 | +}; | ||
| 56 | +static_assert(sizeof(TlvHeader) == 32, "TlvHeader must be 32 bytes"); | ||
| 57 | + | ||
| 58 | +// Feature switch. Packing is enabled only when env PYPTO_ENABLE_KERNEL_BUNDLE == "1". | ||
| 59 | +// Read from the environment exactly once and cached: the launch path queries this on every launch, so a | ||
| 60 | +// getenv() per call would be pure overhead in the (far more common) bundle-disabled scenario. As a consequence | ||
| 61 | +// the variable must be set before the first launch; changing it mid-process has no effect. | ||
| 62 | +inline bool IsKernelBundleEnabled() | ||
| 63 | +{ | ||
| 64 | + static const bool enabled = []() { | ||
| 65 | + const char* v = std::getenv("PYPTO_ENABLE_KERNEL_BUNDLE"); | ||
| 66 | + return v != nullptr && v[0] == '1' && v[1] == '\0'; | ||
| 67 | + }(); | ||
| 68 | + return enabled; | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +// Output path for the produced bundle. Overridable via PYPTO_KERNEL_BUNDLE_PATH; defaults to ./foo.pyptokb. | ||
| 72 | +// Cached on first use for the same reason as the switch above. | ||
| 73 | +inline const std::string& KernelBundleOutPath() | ||
| 74 | +{ | ||
| 75 | + static const std::string path = []() { | ||
| 76 | + const char* p = std::getenv("PYPTO_KERNEL_BUNDLE_PATH"); | ||
| 77 | + return (p != nullptr && p[0] != '\0') ? std::string(p) : std::string("foo.pyptokb"); | ||
| 78 | + }(); | ||
| 79 | + return path; | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,225 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_launch.cpp | ||
| 13 | + * \brief Self-contained offline bundle launch (see header). Kept out of device_launcher.cpp on purpose. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "machine/runtime/bundle/kernel_bundle_launch.h" | ||
| 17 | + | ||
| 18 | +#include <atomic> | ||
| 19 | +#include <cstddef> | ||
| 20 | +#include <string> | ||
| 21 | +#include <vector> | ||
| 22 | + | ||
| 23 | +#include "securec.h" | ||
| 24 | +#include "tilefwk/pypto_fwk_log.h" | ||
| 25 | +#include "tilefwk/error_code.h" | ||
| 26 | +#include "adapter/api/acl_api.h" | ||
| 27 | +#include "adapter/api/msprof_api.h" | ||
| 28 | +#include "interface/utils/op_info_manager.h" | ||
| 29 | +#include "machine/runtime/bundle/kernel_bundle_dev_cache.h" | ||
| 30 | +#include "machine/runtime/context/stream_context.h" | ||
| 31 | +#include "machine/runtime/context/device_launcher_context.h" | ||
| 32 | +#include "machine/runtime/runner/runtime_utils.h" | ||
| 33 | +#include "machine/runtime/launcher/device_launcher.h" | ||
| 34 | +#include "machine/runtime/launcher/cell_match_dynamic.h" | ||
| 35 | + | ||
| 36 | +namespace npu::tile_fwk::dynamic { | ||
| 37 | + | ||
| 38 | +namespace { | ||
| 39 | +// aicpu launch primitive (topology from devProg), kept here so device_launcher stays free of bundle code. | ||
| 40 | +int BundleLaunchAicpu(RtAicpuArgsEx& rtArgs, DevAscendProgram* devProg) | ||
| 41 | +{ | ||
| 42 | + auto ctrlStream = GetStreamContext().GetCtrlStream(); | ||
| 43 | + auto schedStream = GetStreamContext().GetScheStream(); | ||
| 44 | + auto& devRunner = DeviceRunner::Get(); | ||
| 45 | + int ret = 0; | ||
| 46 | + auto args = (AiCpuArgs*)rtArgs.args; | ||
| 47 | + const int nrAicpu = static_cast<int>(devProg->devArgs.nrAicpu); | ||
| 48 | + const bool launchSchedSameCluster = static_cast<int>(devProg->devArgs.launchSchedSameCluster); | ||
| 49 | + if (launchSchedSameCluster) { | ||
| 50 | + MACHINE_LOGW("When available AICPUs are insufficient, execute export PYPTO_LAUNCH_SCHED_SAME_CLUSTER=false" | ||
| 51 | + "to disable the constraint that forces scheduling threads onto the same cluster."); | ||
| 52 | + } | ||
| 53 | + args->kArgs.parameter.ctrlBlockNum = static_cast<int>(devProg->ctrlBlockDim); | ||
| 54 | + auto startTime = MspfSysCycleTime(); | ||
| 55 | + args->kArgs.parameter.runMode = RUN_SPLITTED_STREAM_CTRL; | ||
| 56 | + ret = RuntimeAicpuKernelLaunchExWithArgs(static_cast<uint32_t>(npu::tile_fwk::RtKernelType::AICPU_KFC), | ||
| 57 | + "AST_DYN_AICPU", 1, &rtArgs, nullptr, ctrlStream, | ||
| 58 | + RT_KERNEL_USE_SPECIAL_TIMEOUT); | ||
| 59 | + devRunner.ReportHostProfInfo(ctrlStream, startTime, 1, MSPF_GE_TASK_TYPE_AI_CPU, false); | ||
| 60 | + if (ret != RT_SUCCESS) { | ||
| 61 | + return ret; | ||
| 62 | + } | ||
| 63 | + args->kArgs.parameter.runMode = RUN_SPLITTED_STREAM_SCHE; | ||
| 64 | + startTime = MspfSysCycleTime(); | ||
| 65 | + const int scheCpuNum = static_cast<int>(devProg->devArgs.scheCpuNum); | ||
| 66 | + ret = RuntimeAicpuKernelLaunchExWithArgs(static_cast<uint32_t>(npu::tile_fwk::RtKernelType::AICPU_KFC), | ||
| 67 | + "AST_DYN_AICPU", nrAicpu, &rtArgs, nullptr, schedStream, | ||
| 68 | + RT_KERNEL_USE_SPECIAL_TIMEOUT); | ||
| 69 | + devRunner.ReportHostProfInfo(schedStream, startTime, scheCpuNum, MSPF_GE_TASK_TYPE_AI_CPU, false); | ||
| 70 | + return ret; | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +// aicore launch primitive: bundle always runs debugEnable=false, so the debug-sync branch is omitted. | ||
| 74 | +int BundleLaunchAicore(AclRtStream aicoreStream, void* kernel, RtArgsEx& rtArgs, RtTaskCfgInfo& rtTaskCfg, | ||
| 75 | + DevAscendProgram* devProg) | ||
| 76 | +{ | ||
| 77 | + auto& devRunner = DeviceRunner::Get(); | ||
| 78 | + auto tilingKey = OpInfoManager::GetInstance().GetOpTilingKey(); | ||
| 79 | + int blockDim = static_cast<int>(devProg->ctrlBlockDim); | ||
| 80 | + if (blockDim == 0) { | ||
| 81 | + blockDim = static_cast<int>(devProg->devArgs.nrValidAic); | ||
| 82 | + } | ||
| 83 | + auto startTime = MspfSysCycleTime(); | ||
| 84 | + auto ret = RuntimeKernelLaunchWithHandleV2(kernel, tilingKey, blockDim, &rtArgs, nullptr, aicoreStream, &rtTaskCfg); | ||
| 85 | + devRunner.ReportHostProfInfo(aicoreStream, startTime, blockDim, MSPF_GE_TASK_TYPE_MIX_AIC, true); | ||
| 86 | + return ret; | ||
| 87 | +} | ||
| 88 | +} // namespace | ||
| 89 | + | ||
| 90 | +int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binHandle, uint64_t cacheKey, | ||
| 91 | + const std::vector<DeviceTensorData>& tensorList, | ||
| 92 | + const std::vector<uint8_t>& hostCtrlFlowCache, | ||
| 93 | + const std::vector<DevDynamicCellMatchStridePatch>& cellMatchStridePatches, | ||
| 94 | + void* workspaceAddr, RtStream aicoreStream, bool streamSynchronize, | ||
| 95 | + const DeviceLauncherConfig& config) | ||
| 96 | +{ | ||
| 97 | + (void)config; | ||
| 98 | + MACHINE_LOGI("Kernel Launch (bundle)"); | ||
| 99 | + if (binHandle == nullptr) { | ||
| 100 | + MACHINE_LOGE(HostLauncherErr::REGISTER_KERNEL_FAILED, "[kernel-bundle] null kernel bin handle."); | ||
| 101 | + return -1; | ||
| 102 | + } | ||
| 103 | + aicoreStream = aicoreStream == nullptr ? GetContextAiCoreStream() : aicoreStream; | ||
| 104 | + | ||
| 105 | + int rc = AclInit(nullptr); | ||
| 106 | + if (rc != 0 && rc != ACLRT_ERROR_REPEAT_INITIALIZE) { | ||
| 107 | + return rc; | ||
| 108 | + } | ||
| 109 | + DeviceLauncher::CheckAscendDriverVersionOnboard(); | ||
| 110 | + CheckDeviceId(); | ||
| 111 | + | ||
| 112 | + auto* devProg = reinterpret_cast<DevAscendProgram*>(const_cast<uint8_t*>(devProgBinary.data())); | ||
| 113 | + | ||
| 114 | + // Control-flow cache: copied host->device once per bundle, reused across launches (freed at process exit). | ||
| 115 | + uint8_t* devCtrlCache = bundle::KernelBundleDevCache::Instance().GetOrCopy(cacheKey, hostCtrlFlowCache); | ||
| 116 | + | ||
| 117 | + // Build AiCpuArgs buffer: one unified operand list ([nTensors, 0], outputs folded in), then the trailing | ||
| 118 | + // cell-match stride patch count + patches (device applies via ApplyDynamicCellMatchDescPatchesFromLaunchArgs). | ||
| 119 | + const uint64_t tensorCount = tensorList.size(); | ||
| 120 | + const size_t argSize = sizeof(AiCpuArgs) + 2 * sizeof(int64_t) + tensorCount * sizeof(DevTensorData) + | ||
| 121 | + sizeof(uint64_t) + cellMatchStridePatches.size() * sizeof(DevDynamicCellMatchStridePatch); | ||
| 122 | + std::vector<int64_t> aicpuArgBuf((argSize + sizeof(int64_t) - 1) / sizeof(int64_t), 0); | ||
| 123 | + auto* aicpuArgs = new (aicpuArgBuf.data()) AiCpuArgs(); | ||
| 124 | + aicpuArgs->kArgs.inputs = nullptr; | ||
| 125 | + aicpuArgs->kArgs.outputs = nullptr; | ||
| 126 | + | ||
| 127 | + // Fill device-side kArgs: cfgdata (base-0 devProg), metadata, distributed ctx. Topology is re-derived from | ||
| 128 | + // the target platform in DeviceInitTilingData. | ||
| 129 | + DeviceMemoryUtils devMem; | ||
| 130 | + DeviceLauncher::FillDeviceKernelArgs(devMem, const_cast<std::vector<uint8_t>&>(devProgBinary), aicpuArgs->kArgs, | ||
| 131 | + std::vector<std::string>{}); | ||
| 132 | + | ||
| 133 | + // Fill tensor descriptors: [nTensors, 0] then the flat tensor array (kernel addresses operands by position). | ||
| 134 | + int64_t* inputp = reinterpret_cast<int64_t*>(aicpuArgs + 1); | ||
| 135 | + inputp[0] = static_cast<int64_t>(tensorCount); | ||
| 136 | + inputp[1] = 0; // nOut: outputs are folded into tensorList | ||
| 137 | + auto* tensorData = reinterpret_cast<DevTensorData*>(inputp + 2); | ||
| 138 | + for (const auto& t : tensorList) { | ||
| 139 | + tensorData->address = reinterpret_cast<uint64_t>(t.GetAddr()); | ||
| 140 | + tensorData->dataType = t.GetDataType(); | ||
| 141 | + const auto& shape = t.GetShape(); | ||
| 142 | + tensorData->shape.dimSize = static_cast<int>(shape.size()); | ||
| 143 | + for (int j = 0; j < tensorData->shape.dimSize; ++j) { | ||
| 144 | + tensorData->shape.dim[j] = shape[j]; | ||
| 145 | + } | ||
| 146 | + tensorData++; | ||
| 147 | + } | ||
| 148 | + // Trailing cell-match stride patch count (0 when empty) + patch array, after the flat tensor list. | ||
| 149 | + WriteDynamicCellMatchStridePatchesToLaunchArgs(inputp, cellMatchStridePatches); | ||
| 150 | + | ||
| 151 | + // Per-launch kArgs (ctrl cache device ptr / workspace / monotonic round / dynamic mem budgets). | ||
| 152 | + static std::atomic<int64_t> bundleSequence{0}; | ||
| 153 | + aicpuArgs->kArgs.ctrlFlowCache = reinterpret_cast<int64_t*>(devCtrlCache); | ||
| 154 | + aicpuArgs->kArgs.workspace = reinterpret_cast<int64_t*>(workspaceAddr); | ||
| 155 | + aicpuArgs->kArgs.parameter.globalRound = ++bundleSequence; | ||
| 156 | + aicpuArgs->kArgs.maxDynamicAssembleOutcastMem = devProg->memBudget.tensor.maxDynamicAssembleOutcastMem; | ||
| 157 | + aicpuArgs->kArgs.maxDynamicCellMatchTableMem = devProg->memBudget.metadata.maxDynamicCellMatchTableMem; | ||
| 158 | + | ||
| 159 | + // Dynamic cell-match metadata pool: a standalone device buffer (size = memBudget.metadata.dynamicCellMatch, | ||
| 160 | + // computed in EvalWorkspaceForShapes), allocated once per bundle and reused. The device (device_ctrl InitDyn) | ||
| 161 | + // overwrites devArgs.dynamicCellMatch{Addr,Capacity} from these kArgs and inits the pool in place. | ||
| 162 | + const uint64_t dynamicCellMatchBytes = devProg->memBudget.metadata.dynamicCellMatch; | ||
| 163 | + uint8_t* cellMatchAddr = bundle::KernelBundleDevCache::Instance().GetOrAllocCellMatch(cacheKey, | ||
| 164 | + dynamicCellMatchBytes); | ||
| 165 | + aicpuArgs->kArgs.runtimeDynamicCellMatchAddr = reinterpret_cast<uint64_t>(cellMatchAddr); | ||
| 166 | + aicpuArgs->kArgs.runtimeDynamicCellMatchCapacity = cellMatchAddr != nullptr ? dynamicCellMatchBytes : 0; | ||
| 167 | + | ||
| 168 | + // rt args. | ||
| 169 | + RtAicpuArgsEx rtAicpuArgs; | ||
| 170 | + (void)memset_s(&rtAicpuArgs, sizeof(RtAicpuArgsEx), 0, sizeof(RtAicpuArgsEx)); | ||
| 171 | + rtAicpuArgs.kernelNameAddrOffset = offsetof(AiCpuArgs, kernelName); | ||
| 172 | + rtAicpuArgs.soNameAddrOffset = offsetof(AiCpuArgs, soName); | ||
| 173 | + rtAicpuArgs.hostInputInfoNum = 1; | ||
| 174 | + RtHostInputInfo hostInfo; | ||
| 175 | + hostInfo.addrOffset = offsetof(AiCpuArgs, kArgs.inputs); | ||
| 176 | + hostInfo.dataOffset = sizeof(AiCpuArgs); | ||
| 177 | + rtAicpuArgs.hostInputInfoPtr = &hostInfo; | ||
| 178 | + rtAicpuArgs.timeout = AICPU_EXECUTE_TIMEOUT; | ||
| 179 | + rtAicpuArgs.args = aicpuArgs; | ||
| 180 | + rtAicpuArgs.argsSize = static_cast<uint32_t>(aicpuArgBuf.size() * sizeof(int64_t)); | ||
| 181 | + | ||
| 182 | + std::vector<void*> kernelArgs(0x7, nullptr); | ||
| 183 | + RtArgsEx rtAicoreArgs; | ||
| 184 | + (void)memset_s(&rtAicoreArgs, sizeof(RtArgsEx), 0, sizeof(RtArgsEx)); | ||
| 185 | + rtAicoreArgs.args = kernelArgs.data(); | ||
| 186 | + rtAicoreArgs.argsSize = static_cast<uint32_t>(kernelArgs.size() * sizeof(void*)); | ||
| 187 | + | ||
| 188 | + RtTaskCfgInfo rtTaskCfg; | ||
| 189 | + (void)memset_s(&rtTaskCfg, sizeof(RtTaskCfgInfo), 0, sizeof(RtTaskCfgInfo)); | ||
| 190 | + rtTaskCfg.schemMode = static_cast<uint8_t>(RtSchemModeType::BATCH); | ||
| 191 | + | ||
| 192 | + // Launch (mirrors KernelModule::Launch), reusing the public DeviceLauncher helpers. | ||
| 193 | + const bool isCaptureMode = DeviceLauncher::IsCaptureMode(); | ||
| 194 | + rc = DeviceLauncher::LaunchSyncTask(aicoreStream, isCaptureMode, /*launchEarlyMode=*/0); | ||
| 195 | + if (rc != RT_SUCCESS) { | ||
| 196 | + return rc; | ||
| 197 | + } | ||
| 198 | + DeviceLauncher::SetDevPerfAddr(false, isCaptureMode); | ||
| 199 | + | ||
| 200 | + rc = BundleLaunchAicpu(rtAicpuArgs, devProg); | ||
| 201 | + if (rc != RT_SUCCESS) { | ||
| 202 | + MACHINE_LOGE(HostLauncherErr::LAUNCH_BUILTIN_OP_NULL_FAILED, "[kernel-bundle] launch aicpu failed: %d", rc); | ||
| 203 | + return rc; | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + static const char kBundleKernelName[] = "PyPTO_bundle_kernel"; | ||
| 207 | + kernelArgs[0] = const_cast<char*>(kBundleKernelName); | ||
| 208 | + kernelArgs[4] = reinterpret_cast<int64_t*>(aicpuArgs + 1); // inputp | ||
| 209 | + kernelArgs[5] = aicpuArgs->kArgs.cfgdata; // 5 is cfgdata | ||
| 210 | + kernelArgs[6] = reinterpret_cast<DevTensorData*>(reinterpret_cast<int64_t*>(aicpuArgs + 1) + 2); | ||
| 211 | + | ||
| 212 | + rc = BundleLaunchAicore(aicoreStream, static_cast<RtBinHandle>(binHandle), rtAicoreArgs, rtTaskCfg, devProg); | ||
| 213 | + if (rc != RT_SUCCESS) { | ||
| 214 | + MACHINE_LOGE(HostLauncherErr::REGISTER_KERNEL_FAILED, "[kernel-bundle] launch aicore failed: %d", rc); | ||
| 215 | + return rc; | ||
| 216 | + } | ||
| 217 | + | ||
| 218 | + if (streamSynchronize) { | ||
| 219 | + rc = DeviceRunner::Get().DynamicLaunchSynchronize(GetContextScheStream(), GetContextCtrlStream(), aicoreStream); | ||
| 220 | + } | ||
| 221 | + MACHINE_LOGI("finish Kernel Launch (bundle)."); | ||
| 222 | + return rc; | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +} // namespace npu::tile_fwk::dynamic | ||
| @@ -0,0 +1,43 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_launch.h | ||
| 13 | + * \brief Self-contained offline launch for a packed kernel bundle. | ||
| 14 | + * | ||
| 15 | + * Lives outside device_launcher so that file needs no bundle code. Reads topology from the packed | ||
| 16 | + * DevAscendProgram (no Function) and reuses only public DeviceLauncher helpers. | ||
| 17 | + */ | ||
| 18 | + | ||
| 19 | +#pragma once | ||
| 20 | + | ||
| 21 | +#include <cstdint> | ||
| 22 | +#include <vector> | ||
| 23 | + | ||
| 24 | +#include "adapter/api/runtime_define.h" // RtStream | ||
| 25 | +#include "machine/runtime/launcher/device_launcher_types.h" // DeviceTensorData, DeviceLauncherConfig | ||
| 26 | +#include "machine/utils/dynamic/dev_encode_tensor.h" // DevDynamicCellMatchStridePatch | ||
| 27 | + | ||
| 28 | +namespace npu::tile_fwk::dynamic { | ||
| 29 | + | ||
| 30 | +// Launch a packed bundle once. `devProgBinary` stays base-0 (device relocates); `binHandle` is a pre-registered | ||
| 31 | +// RtBinHandle; `cacheKey` (= LoadedBundle::bundleKey, a content digest -- NOT hashKey, which collides across | ||
| 32 | +// shape variants of one op) keys the process-wide ctrl-flow-cache device buffer. `tensorList` is the unified | ||
| 33 | +// operand list ([nTensors, 0], outputs folded in). `cellMatchStridePatches` are the per-shape patches from | ||
| 34 | +// EvalWorkspaceForShapes (empty when no cell-match table), which must already have patched `devProgBinary`'s | ||
| 35 | +// memBudget for the launch shape. Returns 0 on success. | ||
| 36 | +int LaunchBundleKernelOnce(const std::vector<uint8_t>& devProgBinary, void* binHandle, uint64_t cacheKey, | ||
| 37 | + const std::vector<DeviceTensorData>& tensorList, | ||
| 38 | + const std::vector<uint8_t>& hostCtrlFlowCache, | ||
| 39 | + const std::vector<DevDynamicCellMatchStridePatch>& cellMatchStridePatches, | ||
| 40 | + void* workspaceAddr, RtStream aicoreStream, bool streamSynchronize, | ||
| 41 | + const DeviceLauncherConfig& config = DeviceLauncherConfig()); | ||
| 42 | + | ||
| 43 | +} // namespace npu::tile_fwk::dynamic | ||
| @@ -0,0 +1,150 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_loader.cpp | ||
| 13 | + * \brief Implementation of the kernel bundle loader. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "machine/runtime/bundle/kernel_bundle_loader.h" | ||
| 17 | + | ||
| 18 | +#include <cstring> | ||
| 19 | + | ||
| 20 | +#include "machine/runtime/bundle/kernel_bundle_crc32.h" | ||
| 21 | +#include "machine/runtime/bundle/kernel_bundle_format.h" | ||
| 22 | +#include "utils/file_utils.h" | ||
| 23 | +#include "tilefwk/error_code.h" | ||
| 24 | +#include "tilefwk/pypto_fwk_log.h" | ||
| 25 | + | ||
| 26 | +namespace npu::tile_fwk::bundle { | ||
| 27 | + | ||
| 28 | +namespace { | ||
| 29 | +// Copy one TLV value out of the (possibly transient) source image into a buffer the LoadedBundle owns. | ||
| 30 | +// | ||
| 31 | +// No host-side alignment is required or attempted here: every segment reaches the device through | ||
| 32 | +// DeviceMemoryUtils::CopyToDev, which memcpy's from the host pointer, and the online path feeds the very same | ||
| 33 | +// call with a plain std::vector (DyndevFunctionAttribute::devProgBinary). The 4KB alignment in the on-disk | ||
| 34 | +// layout (kValueAlign) exists for the file/mmap side only. Do not "restore" a std::vector-based alignment | ||
| 35 | +// claim here -- the default allocator only guarantees alignof(max_align_t). | ||
| 36 | +std::vector<uint8_t> CopySegment(const uint8_t* src, size_t len) | ||
| 37 | +{ | ||
| 38 | + std::vector<uint8_t> v(len); | ||
| 39 | + if (len != 0) { | ||
| 40 | + std::memcpy(v.data(), src, len); | ||
| 41 | + } | ||
| 42 | + return v; | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +// Fold one TLV's identity (type, content CRC, length) into a running 64-bit FNV-1a digest. The result | ||
| 46 | +// identifies the bundle by CONTENT, which is what the registry keys on -- see the bundleKey comment in | ||
| 47 | +// kernel_bundle_loader.h for why hashKey cannot serve that role. | ||
| 48 | +void FoldTlvIntoBundleKey(uint64_t& key, uint32_t type, uint32_t crc, uint64_t len) | ||
| 49 | +{ | ||
| 50 | + constexpr uint64_t kFnvPrime = 0x00000100000001B3ULL; | ||
| 51 | + for (uint64_t word : {static_cast<uint64_t>(type), static_cast<uint64_t>(crc), len}) { | ||
| 52 | + for (int byte = 0; byte < 8; ++byte) { | ||
| 53 | + key = (key ^ ((word >> (byte * 8)) & 0xFFULL)) * kFnvPrime; | ||
| 54 | + } | ||
| 55 | + } | ||
| 56 | +} | ||
| 57 | +} // namespace | ||
| 58 | + | ||
| 59 | +std::shared_ptr<LoadedBundle> KernelBundleLoader::LoadFromMemory(const uint8_t* p, size_t n) | ||
| 60 | +{ | ||
| 61 | + if (p == nullptr || n < sizeof(BundleHeader)) { | ||
| 62 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] buffer too small: %zu", n); | ||
| 63 | + return nullptr; | ||
| 64 | + } | ||
| 65 | + BundleHeader hdr{}; | ||
| 66 | + std::memcpy(&hdr, p, sizeof(BundleHeader)); | ||
| 67 | + if (hdr.magic != kBundleMagic) { | ||
| 68 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] bad magic %#lx", hdr.magic); | ||
| 69 | + return nullptr; | ||
| 70 | + } | ||
| 71 | + if (hdr.version > kBundleVersion) { | ||
| 72 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] unsupported version %u > %u", hdr.version, | ||
| 73 | + kBundleVersion); | ||
| 74 | + return nullptr; | ||
| 75 | + } | ||
| 76 | + if (hdr.totalSize != n) { | ||
| 77 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] size mismatch: header=%lu actual=%zu", hdr.totalSize, | ||
| 78 | + n); | ||
| 79 | + return nullptr; | ||
| 80 | + } | ||
| 81 | + if (Crc32(p, sizeof(BundleHeader) - sizeof(uint32_t)) != hdr.headerCrc32) { | ||
| 82 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] header CRC mismatch"); | ||
| 83 | + return nullptr; | ||
| 84 | + } | ||
| 85 | + const uint64_t tlvRegion = sizeof(BundleHeader) + static_cast<uint64_t>(hdr.tlvCount) * sizeof(TlvHeader); | ||
| 86 | + if (tlvRegion > n) { | ||
| 87 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] TLV table out of range"); | ||
| 88 | + return nullptr; | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + auto b = std::make_shared<LoadedBundle>(); | ||
| 92 | + uint64_t bundleKey = 0xCBF29CE484222325ULL; // FNV-1a offset basis | ||
| 93 | + for (uint32_t i = 0; i < hdr.tlvCount; ++i) { | ||
| 94 | + TlvHeader t{}; | ||
| 95 | + std::memcpy(&t, p + sizeof(BundleHeader) + static_cast<size_t>(i) * sizeof(TlvHeader), sizeof(TlvHeader)); | ||
| 96 | + if (t.valueOffset > n || t.valueLength > n - t.valueOffset) { | ||
| 97 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] TLV[%u] value out of range", i); | ||
| 98 | + return nullptr; | ||
| 99 | + } | ||
| 100 | + const uint8_t* vp = p + t.valueOffset; | ||
| 101 | + if (Crc32(vp, t.valueLength) != t.valueCrc32) { | ||
| 102 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] TLV[%u] value CRC mismatch", i); | ||
| 103 | + return nullptr; | ||
| 104 | + } | ||
| 105 | + FoldTlvIntoBundleKey(bundleKey, t.type, t.valueCrc32, t.valueLength); | ||
| 106 | + switch (static_cast<TlvType>(t.type)) { | ||
| 107 | + case TlvType::AicoreKernel: | ||
| 108 | + b->aicoreKernel = CopySegment(vp, t.valueLength); | ||
| 109 | + break; | ||
| 110 | + case TlvType::AicpuSo: | ||
| 111 | + b->aicpuSo = CopySegment(vp, t.valueLength); | ||
| 112 | + break; | ||
| 113 | + case TlvType::DevProgram: | ||
| 114 | + b->devProgram = CopySegment(vp, t.valueLength); | ||
| 115 | + break; | ||
| 116 | + case TlvType::CtrlFlowCache: | ||
| 117 | + b->ctrlFlowCache = CopySegment(vp, t.valueLength); | ||
| 118 | + break; | ||
| 119 | + case TlvType::SymbolMeta: | ||
| 120 | + b->symbolMeta = CopySegment(vp, t.valueLength); | ||
| 121 | + break; | ||
| 122 | + default: | ||
| 123 | + MACHINE_LOGI("[kernel-bundle] skip unknown TLV type %u", t.type); | ||
| 124 | + break; | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | + if (b->devProgram.empty()) { | ||
| 128 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] missing DEV_PROGRAM segment"); | ||
| 129 | + return nullptr; | ||
| 130 | + } | ||
| 131 | + b->bundleKey = bundleKey; | ||
| 132 | + MACHINE_LOGI("[kernel-bundle] loaded: bundleKey=%#lx hashKey=%#lx workspaceSize=%lu archInfo=%u ctrlCache=%zuB " | ||
| 133 | + "symbolMeta=%zuB", | ||
| 134 | + b->bundleKey, b->GetHashKey(), b->GetWorkspaceSize(), b->GetArchInfo(), b->ctrlFlowCache.size(), | ||
| 135 | + b->symbolMeta.size()); | ||
| 136 | + return b; | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +std::shared_ptr<LoadedBundle> KernelBundleLoader::LoadFromFile(const std::string& path) | ||
| 140 | +{ | ||
| 141 | + bool ok = false; | ||
| 142 | + std::vector<uint8_t> raw = ReadFile(path, &ok); | ||
| 143 | + if (!ok || raw.empty()) { | ||
| 144 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] failed to read %s", path.c_str()); | ||
| 145 | + return nullptr; | ||
| 146 | + } | ||
| 147 | + return LoadFromMemory(raw.data(), raw.size()); | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,67 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_loader.h | ||
| 13 | + * \brief Loads a .pyptokb into memory and exposes its segments. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#pragma once | ||
| 17 | + | ||
| 18 | +#include <cstdint> | ||
| 19 | +#include <memory> | ||
| 20 | +#include <string> | ||
| 21 | +#include <vector> | ||
| 22 | + | ||
| 23 | +#include "machine/utils/dynamic/dev_encode_program.h" | ||
| 24 | +#include "machine/utils/dynamic/dev_encode_tensor.h" | ||
| 25 | + | ||
| 26 | +namespace npu::tile_fwk::bundle { | ||
| 27 | + | ||
| 28 | +struct LoadedBundle { | ||
| 29 | + // Content-derived identity, folded by the loader from every TLV's (type, value CRC32, value length). | ||
| 30 | + // | ||
| 31 | + // This -- NOT hashKey -- is what the registry caches on. hashKey comes from the IR structure only, so two | ||
| 32 | + // bundles of the same op built for different runtime shapes carry the SAME hashKey while holding different | ||
| 33 | + // devProgram bytes; keying the cache on it would silently hand the first bundle back for the second load | ||
| 34 | + // and run the wrong program. Two bundles share a bundleKey only when they are byte-identical. | ||
| 35 | + uint64_t bundleKey{0}; | ||
| 36 | + | ||
| 37 | + std::vector<uint8_t> aicoreKernel; // .o raw | ||
| 38 | + std::vector<uint8_t> aicpuSo; // .so raw | ||
| 39 | + std::vector<uint8_t> devProgram; // kept base-0 (device-side reloc) | ||
| 40 | + std::vector<uint8_t> ctrlFlowCache; // DevControlFlowCache blob (may be empty for old bundles) | ||
| 41 | + std::vector<uint8_t> symbolMeta; // JSON dynamic-workspace symbols (empty -> static workspace fallback) | ||
| 42 | + | ||
| 43 | + // Per-shape dynamic cell-match stride patches, computed host-side by EvalWorkspaceForShapes and written into | ||
| 44 | + // the aicpu launch args. Empty for ops with no dynamic cell-match table. | ||
| 45 | + std::vector<dynamic::DevDynamicCellMatchStridePatch> cellMatchStridePatches; | ||
| 46 | + | ||
| 47 | + // Header scalars read directly from the base-0 buffer without reloc. | ||
| 48 | + const dynamic::DevAscendProgram* Head() const | ||
| 49 | + { | ||
| 50 | + return reinterpret_cast<const dynamic::DevAscendProgram*>(devProgram.data()); | ||
| 51 | + } | ||
| 52 | + uint64_t GetWorkspaceSize() const { return Head()->memBudget.Total(); } | ||
| 53 | + uint64_t GetHashKey() const { return Head()->hashKey; } | ||
| 54 | + uint64_t GetConfigKey() const { return Head()->configKey; } | ||
| 55 | + uint32_t GetArchInfo() const { return static_cast<uint32_t>(Head()->devArgs.archInfo); } | ||
| 56 | + | ||
| 57 | + bool HasCtrlFlowCache() const { return !ctrlFlowCache.empty(); } | ||
| 58 | + bool HasSymbolMeta() const { return !symbolMeta.empty(); } | ||
| 59 | +}; | ||
| 60 | + | ||
| 61 | +class KernelBundleLoader { | ||
| 62 | +public: | ||
| 63 | + static std::shared_ptr<LoadedBundle> LoadFromFile(const std::string& path); | ||
| 64 | + static std::shared_ptr<LoadedBundle> LoadFromMemory(const uint8_t* p, size_t n); | ||
| 65 | +}; | ||
| 66 | + | ||
| 67 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,105 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_registry.cpp | ||
| 13 | + * \brief Implementation of the kernel bundle registry singleton. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "machine/runtime/bundle/kernel_bundle_registry.h" | ||
| 17 | + | ||
| 18 | +#include "machine/runtime/launcher/device_launcher_binding.h" | ||
| 19 | +#include "tilefwk/error_code.h" | ||
| 20 | +#include "tilefwk/pypto_fwk_log.h" | ||
| 21 | + | ||
| 22 | +namespace npu::tile_fwk::bundle { | ||
| 23 | + | ||
| 24 | +KernelBundleRegistry& KernelBundleRegistry::GetInstance() | ||
| 25 | +{ | ||
| 26 | + static KernelBundleRegistry instance; | ||
| 27 | + return instance; | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +std::shared_ptr<LoadedBundle> KernelBundleRegistry::CacheByContent(std::shared_ptr<LoadedBundle> loaded) | ||
| 31 | +{ | ||
| 32 | + if (loaded == nullptr) { | ||
| 33 | + return nullptr; | ||
| 34 | + } | ||
| 35 | + std::lock_guard<std::mutex> lk(mutex_); | ||
| 36 | + auto it = byContent_.find(loaded->bundleKey); | ||
| 37 | + if (it != byContent_.end()) { | ||
| 38 | + return it->second; // idempotent: byte-identical bundle already loaded | ||
| 39 | + } | ||
| 40 | + // Same op, different shape: identical hashKey but a different bundle. Supported (both live side by side, | ||
| 41 | + // each under its own bundleKey), logged because it also shows up when a stale .pyptokb is loaded by mistake. | ||
| 42 | + for (const auto& kv : byContent_) { | ||
| 43 | + if (kv.second->GetHashKey() == loaded->GetHashKey()) { | ||
| 44 | + MACHINE_LOGW("[kernel-bundle] hashKey %#lx now has a 2nd distinct bundle (bundleKey %#lx vs %#lx); " | ||
| 45 | + "expected when the same op is packed for several shapes", | ||
| 46 | + loaded->GetHashKey(), kv.second->bundleKey, loaded->bundleKey); | ||
| 47 | + break; | ||
| 48 | + } | ||
| 49 | + } | ||
| 50 | + byContent_[loaded->bundleKey] = loaded; | ||
| 51 | + return loaded; | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +std::shared_ptr<LoadedBundle> KernelBundleRegistry::LoadOrGet(const std::string& path) | ||
| 55 | +{ | ||
| 56 | + return CacheByContent(KernelBundleLoader::LoadFromFile(path)); | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +std::shared_ptr<LoadedBundle> KernelBundleRegistry::LoadOrGetFromMemory(const uint8_t* data, size_t n) | ||
| 60 | +{ | ||
| 61 | + return CacheByContent(KernelBundleLoader::LoadFromMemory(data, n)); | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +void* KernelBundleRegistry::GetOrRegisterKernel(uint64_t bundleKey, const std::vector<uint8_t>& kernelBin) | ||
| 65 | +{ | ||
| 66 | + std::lock_guard<std::mutex> lk(mutex_); | ||
| 67 | + auto it = kernelHandles_.find(bundleKey); | ||
| 68 | + if (it != kernelHandles_.end() && it->second != nullptr) { | ||
| 69 | + return it->second; | ||
| 70 | + } | ||
| 71 | + void* hdl = dynamic::RegisterKernelBinary(kernelBin); | ||
| 72 | + if (hdl == nullptr) { | ||
| 73 | + MACHINE_LOGE(DevCommonErr::PARAM_CHECK_FAILED, "[kernel-bundle] RegisterKernelBinary failed"); | ||
| 74 | + return nullptr; | ||
| 75 | + } | ||
| 76 | + kernelHandles_[bundleKey] = hdl; | ||
| 77 | + return hdl; | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +void KernelBundleRegistry::Unload(uint64_t bundleKey) | ||
| 81 | +{ | ||
| 82 | + std::lock_guard<std::mutex> lk(mutex_); | ||
| 83 | + auto kh = kernelHandles_.find(bundleKey); | ||
| 84 | + if (kh != kernelHandles_.end()) { | ||
| 85 | + if (kh->second != nullptr) { | ||
| 86 | + dynamic::UnregisterKernelBinary(kh->second); | ||
| 87 | + } | ||
| 88 | + kernelHandles_.erase(kh); | ||
| 89 | + } | ||
| 90 | + byContent_.erase(bundleKey); | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +void KernelBundleRegistry::UnloadAll() | ||
| 94 | +{ | ||
| 95 | + std::lock_guard<std::mutex> lk(mutex_); | ||
| 96 | + for (auto& kv : kernelHandles_) { | ||
| 97 | + if (kv.second != nullptr) { | ||
| 98 | + dynamic::UnregisterKernelBinary(kv.second); | ||
| 99 | + } | ||
| 100 | + } | ||
| 101 | + kernelHandles_.clear(); | ||
| 102 | + byContent_.clear(); | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,61 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_registry.h | ||
| 13 | + * \brief Singleton that owns loaded bundles and their registered kernel handles. | ||
| 14 | + * The AICPU .so is copied to device by DeviceRunner::Init() (InitAiCpuSoBin), not here. | ||
| 15 | + */ | ||
| 16 | + | ||
| 17 | +#pragma once | ||
| 18 | + | ||
| 19 | +#include <cstdint> | ||
| 20 | +#include <memory> | ||
| 21 | +#include <mutex> | ||
| 22 | +#include <string> | ||
| 23 | +#include <unordered_map> | ||
| 24 | + | ||
| 25 | +#include "machine/runtime/bundle/kernel_bundle_loader.h" | ||
| 26 | + | ||
| 27 | +namespace npu::tile_fwk::bundle { | ||
| 28 | + | ||
| 29 | +class KernelBundleRegistry { | ||
| 30 | +public: | ||
| 31 | + static KernelBundleRegistry& GetInstance(); | ||
| 32 | + | ||
| 33 | + // Idempotent by LoadedBundle::bundleKey (content digest, see kernel_bundle_loader.h): re-loading the same | ||
| 34 | + // .pyptokb returns the cached bundle, while two shape-variants of one op -- same hashKey, different bytes -- | ||
| 35 | + // are kept as separate entries instead of aliasing onto each other. | ||
| 36 | + std::shared_ptr<LoadedBundle> LoadOrGet(const std::string& path); | ||
| 37 | + // Same, but parsing from an in-memory .pyptokb image (client-loaded bytes; never touches a disk path). | ||
| 38 | + std::shared_ptr<LoadedBundle> LoadOrGetFromMemory(const uint8_t* data, size_t n); | ||
| 39 | + | ||
| 40 | + // Register the .o once per bundleKey; cache the returned RtBinHandle. | ||
| 41 | + void* GetOrRegisterKernel(uint64_t bundleKey, const std::vector<uint8_t>& kernelBin); | ||
| 42 | + | ||
| 43 | + void Unload(uint64_t bundleKey); | ||
| 44 | + void UnloadAll(); | ||
| 45 | + | ||
| 46 | + KernelBundleRegistry(const KernelBundleRegistry&) = delete; | ||
| 47 | + KernelBundleRegistry& operator=(const KernelBundleRegistry&) = delete; | ||
| 48 | + | ||
| 49 | +private: | ||
| 50 | + KernelBundleRegistry() = default; | ||
| 51 | + ~KernelBundleRegistry() = default; | ||
| 52 | + | ||
| 53 | + // Idempotent-by-bundleKey caching shared by LoadOrGet / LoadOrGetFromMemory. | ||
| 54 | + std::shared_ptr<LoadedBundle> CacheByContent(std::shared_ptr<LoadedBundle> loaded); | ||
| 55 | + | ||
| 56 | + mutable std::mutex mutex_; | ||
| 57 | + std::unordered_map<uint64_t, std::shared_ptr<LoadedBundle>> byContent_; | ||
| 58 | + std::unordered_map<uint64_t, void*> kernelHandles_; // RtBinHandle per bundleKey | ||
| 59 | +}; | ||
| 60 | + | ||
| 61 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,109 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_workspace.cpp | ||
| 13 | + * \brief Load-side dynamic-workspace evaluation (see header). The pack-side counterpart is pack/kernel_bundle_pack.cpp, | ||
| 14 | + * which stays in tile_fwk_runtime while this file ships in libtile_fwk_bundle.so. | ||
| 15 | + */ | ||
| 16 | + | ||
| 17 | +#include "machine/runtime/bundle/kernel_bundle_workspace.h" | ||
| 18 | + | ||
| 19 | +#include <exception> | ||
| 20 | +#include <string> | ||
| 21 | +#include <unordered_map> | ||
| 22 | + | ||
| 23 | +#include <nlohmann/json.hpp> | ||
| 24 | + | ||
| 25 | +#include "machine/runtime/bundle/kernel_bundle_loader.h" | ||
| 26 | +#include "machine/runtime/launcher/device_launcher_binding.h" | ||
| 27 | +#include "machine/runtime/launcher/cell_match_dynamic.h" | ||
| 28 | +#include "interface/function/function.h" | ||
| 29 | +#include "interface/tensor/symbolic_scalar.h" | ||
| 30 | +#include "tilefwk/pypto_fwk_log.h" | ||
| 31 | + | ||
| 32 | +namespace npu::tile_fwk::bundle { | ||
| 33 | + | ||
| 34 | +uint64_t EvalWorkspaceForShapes(LoadedBundle& bundle, const std::vector<dynamic::DeviceTensorData>& inputs, | ||
| 35 | + const std::vector<dynamic::DeviceTensorData>& outputs) | ||
| 36 | +{ | ||
| 37 | + auto* devProg = reinterpret_cast<dynamic::DevAscendProgram*>(bundle.devProgram.data()); | ||
| 38 | + if (devProg == nullptr) { | ||
| 39 | + return 0; | ||
| 40 | + } | ||
| 41 | + if (bundle.symbolMeta.empty()) { | ||
| 42 | + return devProg->memBudget.Total(); // old/static bundle: no dynamic trees, keep baked constant | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + nlohmann::json root; | ||
| 46 | + try { | ||
| 47 | + root = nlohmann::json::parse(bundle.symbolMeta.begin(), bundle.symbolMeta.end()); | ||
| 48 | + } catch (const std::exception& e) { | ||
| 49 | + MACHINE_LOGW("[kernel-bundle] SymbolMeta parse failed (%s); using static workspace", e.what()); | ||
| 50 | + return devProg->memBudget.Total(); | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + // Rebuild the recording-time symbol dict; the Evaluator resolves runtime shape dims from the tensors, so the | ||
| 54 | + // dynamism comes from `inputs`/`outputs`, not this dict. | ||
| 55 | + std::unordered_map<std::string, ScalarImmediateType> symbolDict; | ||
| 56 | + if (root.contains("symbols")) { | ||
| 57 | + for (auto it = root["symbols"].begin(); it != root["symbols"].end(); ++it) { | ||
| 58 | + symbolDict[it.key()] = static_cast<ScalarImmediateType>(it.value().get<int64_t>()); | ||
| 59 | + } | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + // Mirror ExportedOperator::GetWorkSpaceSize / RefillDynamicMemBudgets: evaluate the trees against the real | ||
| 63 | + // shapes and write the concrete values into memBudget in place. | ||
| 64 | + dynamic::Evaluator eval{symbolDict, &inputs, &outputs}; | ||
| 65 | + | ||
| 66 | + // Rebuild + apply the dynamic cell-match stride patches for these shapes. The patched host desc rides to the | ||
| 67 | + // device with the devProgram; the same patches also go into the launch args (re-applied on device via | ||
| 68 | + // ApplyDynamicCellMatchDescPatchesFromLaunchArgs). Without this the device reads a stale baked stride. | ||
| 69 | + bundle.cellMatchStridePatches.clear(); | ||
| 70 | + if (root.contains("cellMatchLaunch")) { | ||
| 71 | + std::vector<DyndevFunctionAttribute::DynamicCellMatchLaunchMeta> metaList; | ||
| 72 | + for (const auto& m : root["cellMatchLaunch"]) { | ||
| 73 | + DyndevFunctionAttribute::DynamicCellMatchLaunchMeta lm; | ||
| 74 | + lm.slotIndex = m.at("slot").get<int>(); | ||
| 75 | + lm.descOffset = m.at("descOffset").get<uint64_t>(); | ||
| 76 | + lm.cellShape = m.at("cellShape").get<std::vector<int>>(); | ||
| 77 | + for (const auto& row : m.at("cand")) { | ||
| 78 | + std::vector<SymbolicScalar> dims; | ||
| 79 | + for (const auto& e : row) { | ||
| 80 | + dims.push_back(LoadSymbolicScalar(e)); | ||
| 81 | + } | ||
| 82 | + lm.candidateRawDims.push_back(std::move(dims)); | ||
| 83 | + } | ||
| 84 | + metaList.push_back(std::move(lm)); | ||
| 85 | + } | ||
| 86 | + bundle.cellMatchStridePatches = dynamic::PrepareDynamicCellMatchDescPatches(metaList, eval); | ||
| 87 | + dynamic::PatchHostDynamicCellMatchTableDesc(devProg, bundle.cellMatchStridePatches); | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + if (root.contains("assembleMem")) { | ||
| 91 | + const SymbolicScalar assembleMem = LoadSymbolicScalar(root["assembleMem"]); | ||
| 92 | + if (assembleMem.IsValid()) { | ||
| 93 | + devProg->memBudget.tensor.maxDynamicAssembleOutcastMem = static_cast<uint64_t>(eval.Evaluate(assembleMem)); | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | + if (root.contains("cellMatchMem")) { | ||
| 97 | + const SymbolicScalar cellMatchMem = LoadSymbolicScalar(root["cellMatchMem"]); | ||
| 98 | + if (cellMatchMem.IsValid()) { | ||
| 99 | + devProg->memBudget.metadata.maxDynamicCellMatchTableMem = static_cast<uint64_t>( | ||
| 100 | + eval.Evaluate(cellMatchMem)); | ||
| 101 | + const uint64_t slotNum = devProg->memBudget.metadata.dynamicCellMatchSlotNum; | ||
| 102 | + devProg->memBudget.metadata.dynamicCellMatch = slotNum * | ||
| 103 | + devProg->memBudget.metadata.maxDynamicCellMatchTableMem; | ||
| 104 | + } | ||
| 105 | + } | ||
| 106 | + return devProg->memBudget.Total(); | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,41 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_workspace.h | ||
| 13 | + * \brief Load-side dynamic-workspace evaluation for the kernel bundle. | ||
| 14 | + * | ||
| 15 | + * Rebuilds an Evaluator from the SymbolMeta TLV and computes the workspace size for the real input shapes. | ||
| 16 | + * The matching pack-side serialization lives in pack/kernel_bundle_pack.h (a different target; see that header). | ||
| 17 | + */ | ||
| 18 | + | ||
| 19 | +#pragma once | ||
| 20 | + | ||
| 21 | +#include <cstdint> | ||
| 22 | +#include <vector> | ||
| 23 | + | ||
| 24 | +namespace npu::tile_fwk { | ||
| 25 | + | ||
| 26 | +namespace dynamic { | ||
| 27 | +class DeviceTensorData; | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +namespace bundle { | ||
| 31 | + | ||
| 32 | +struct LoadedBundle; | ||
| 33 | + | ||
| 34 | +// Evaluate the workspace size for the given tensor shapes and patch the bundle's in-memory devProgram memBudget | ||
| 35 | +// in place. Falls back to the static memBudget.Total() when the bundle has no SymbolMeta segment (old bundles) | ||
| 36 | +// or on parse failure. | ||
| 37 | +uint64_t EvalWorkspaceForShapes(LoadedBundle& bundle, const std::vector<dynamic::DeviceTensorData>& inputs, | ||
| 38 | + const std::vector<dynamic::DeviceTensorData>& outputs); | ||
| 39 | + | ||
| 40 | +} // namespace bundle | ||
| 41 | +} // namespace npu::tile_fwk | ||
| @@ -0,0 +1,149 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_pack.cpp | ||
| 13 | + * \brief Pack side of the kernel bundle: symbol serialization + the .pyptokb pack hook (see header). | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "machine/runtime/bundle/pack/kernel_bundle_pack.h" | ||
| 17 | + | ||
| 18 | +#include <string> | ||
| 19 | + | ||
| 20 | +#include <nlohmann/json.hpp> | ||
| 21 | + | ||
| 22 | +#include "machine/runtime/bundle/kernel_bundle_format.h" | ||
| 23 | +#include "machine/runtime/bundle/pack/kernel_bundle_packer.h" | ||
| 24 | +#include "interface/function/function.h" | ||
| 25 | +#include "interface/tensor/symbolic_scalar.h" | ||
| 26 | +#include "utils/file_utils.h" | ||
| 27 | +#include "tilefwk/pypto_fwk_log.h" | ||
| 28 | + | ||
| 29 | +namespace npu::tile_fwk::bundle { | ||
| 30 | + | ||
| 31 | +namespace { | ||
| 32 | +constexpr int kSymbolMetaVersion = 1; | ||
| 33 | +} // namespace | ||
| 34 | + | ||
| 35 | +std::vector<uint8_t> SerializeWorkspaceSymbols(const DyndevFunctionAttribute& dynAttr) | ||
| 36 | +{ | ||
| 37 | + // Only emit a SymbolMeta segment when there is a dynamic tree to evaluate; a fully static op gets no segment | ||
| 38 | + // and the loader keeps reading the baked memBudget.Total() constant. | ||
| 39 | + const bool hasAssemble = dynAttr.maxDynamicAssembleOutcastMem.IsValid(); | ||
| 40 | + const bool hasCellMatch = dynAttr.maxDynamicCellMatchTableMem.IsValid(); | ||
| 41 | + if (!hasAssemble && !hasCellMatch) { | ||
| 42 | + return {}; | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + nlohmann::json root = nlohmann::json::object(); | ||
| 46 | + root["v"] = kSymbolMetaVersion; | ||
| 47 | + if (hasAssemble) { | ||
| 48 | + root["assembleMem"] = ToJson(dynAttr.maxDynamicAssembleOutcastMem); | ||
| 49 | + } | ||
| 50 | + if (hasCellMatch) { | ||
| 51 | + root["cellMatchMem"] = ToJson(dynAttr.maxDynamicCellMatchTableMem); | ||
| 52 | + } | ||
| 53 | + // Recording-time symbol dict: bare symbols the Evaluator can't derive from tensor shapes at runtime. | ||
| 54 | + nlohmann::json syms = nlohmann::json::object(); | ||
| 55 | + for (const auto& kv : dynAttr.inputSymbolDict) { | ||
| 56 | + syms[kv.first] = static_cast<int64_t>(kv.second); | ||
| 57 | + } | ||
| 58 | + root["symbols"] = std::move(syms); | ||
| 59 | + | ||
| 60 | + // Dynamic cell-match launch metas: per slot, the desc offset into the base-0 devProgram plus the symbolic | ||
| 61 | + // candidate raw dims. The load side re-evaluates these against the launch shapes to rebuild the stride patches | ||
| 62 | + // (else the device reads stale strides -> AICPU execute failure, retcode 507018). | ||
| 63 | + if (!dynAttr.dynamicCellMatchLaunchMetaList.empty()) { | ||
| 64 | + nlohmann::json metas = nlohmann::json::array(); | ||
| 65 | + for (const auto& lm : dynAttr.dynamicCellMatchLaunchMetaList) { | ||
| 66 | + nlohmann::json m = nlohmann::json::object(); | ||
| 67 | + m["slot"] = lm.slotIndex; | ||
| 68 | + m["descOffset"] = static_cast<uint64_t>(lm.descOffset); | ||
| 69 | + m["cellShape"] = lm.cellShape; | ||
| 70 | + nlohmann::json cand = nlohmann::json::array(); | ||
| 71 | + for (const auto& dims : lm.candidateRawDims) { | ||
| 72 | + nlohmann::json row = nlohmann::json::array(); | ||
| 73 | + for (const auto& expr : dims) { | ||
| 74 | + row.push_back(ToJson(expr)); | ||
| 75 | + } | ||
| 76 | + cand.push_back(std::move(row)); | ||
| 77 | + } | ||
| 78 | + m["cand"] = std::move(cand); | ||
| 79 | + metas.push_back(std::move(m)); | ||
| 80 | + } | ||
| 81 | + root["cellMatchLaunch"] = std::move(metas); | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + const std::string dumped = root.dump(); | ||
| 85 | + MACHINE_LOGI("[kernel-bundle] serialized SymbolMeta: %zuB (assemble=%d cellMatch=%d symbols=%zu cmLaunch=%zu)", | ||
| 86 | + dumped.size(), static_cast<int>(hasAssemble), static_cast<int>(hasCellMatch), | ||
| 87 | + dynAttr.inputSymbolDict.size(), dynAttr.dynamicCellMatchLaunchMetaList.size()); | ||
| 88 | + return std::vector<uint8_t>(dumped.begin(), dumped.end()); | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +void MaybePackKernelBundle(const DyndevFunctionAttribute& dynAttr, const std::vector<uint8_t>& ctrlFlowCache) | ||
| 92 | +{ | ||
| 93 | + if (!IsKernelBundleEnabled()) { | ||
| 94 | + return; | ||
| 95 | + } | ||
| 96 | + // For value-dependent control flow (empty ctrlFlowCache) the CTRL_FLOW_CACHE segment is omitted; the launch | ||
| 97 | + // passes ctrlFlowCache=nullptr so the on-device interpreter resolves loop bounds from tensor values at runtime. | ||
| 98 | + KernelBundlePacker packer; | ||
| 99 | + packer.SetAicoreKernel(dynAttr.kernelBinary); | ||
| 100 | + packer.SetAicpuSo(ReadFile(GetPyptoLibPath() + "/libtilefwk_backend_server.so")); | ||
| 101 | + packer.SetDevProgram(dynAttr.devProgBinary); // host-side base-0; workspaceSize/hashKey in header | ||
| 102 | + if (!ctrlFlowCache.empty()) { | ||
| 103 | + packer.SetCtrlFlowCache(ctrlFlowCache); | ||
| 104 | + } | ||
| 105 | + // Dynamic-workspace trees + inputSymbolDict. Empty for fully-static ops. | ||
| 106 | + packer.SetSymbolMeta(SerializeWorkspaceSymbols(dynAttr)); | ||
| 107 | + packer.Pack(KernelBundleOutPath()); | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +KernelBundlePackHook& KernelBundlePackHook::Instance() | ||
| 111 | +{ | ||
| 112 | + static KernelBundlePackHook instance; | ||
| 113 | + return instance; | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +void KernelBundlePackHook::StashCtrlFlowCache(const DyndevFunctionAttribute* dynAttr, const uint8_t* cache, size_t size) | ||
| 117 | +{ | ||
| 118 | + if (!IsKernelBundleEnabled() || dynAttr == nullptr || cache == nullptr || size == 0) { | ||
| 119 | + return; | ||
| 120 | + } | ||
| 121 | + std::lock_guard<std::mutex> lk(mutex_); | ||
| 122 | + stashedFor_ = dynAttr; | ||
| 123 | + stashedCache_.assign(cache, cache + size); | ||
| 124 | + MACHINE_LOGI("[kernel-bundle] stashed ctrl-flow cache (%zuB) for pack at launch", size); | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +void KernelBundlePackHook::MaybePack(const DyndevFunctionAttribute* dynAttr) | ||
| 128 | +{ | ||
| 129 | + if (!IsKernelBundleEnabled() || dynAttr == nullptr) { | ||
| 130 | + return; | ||
| 131 | + } | ||
| 132 | + std::vector<uint8_t> cache; | ||
| 133 | + { | ||
| 134 | + std::lock_guard<std::mutex> lk(mutex_); | ||
| 135 | + if (!packed_.insert(dynAttr).second) { | ||
| 136 | + return; // already packed this op in this process | ||
| 137 | + } | ||
| 138 | + if (stashedFor_ == dynAttr) { | ||
| 139 | + cache = std::move(stashedCache_); | ||
| 140 | + stashedCache_.clear(); | ||
| 141 | + stashedFor_ = nullptr; | ||
| 142 | + } | ||
| 143 | + } | ||
| 144 | + // An empty cache here is not an error: value-dependent ops never build one, and MaybePackKernelBundle omits | ||
| 145 | + // the CTRL_FLOW_CACHE segment so the device interpreter resolves control flow from tensor values instead. | ||
| 146 | + MaybePackKernelBundle(*dynAttr, cache); | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,79 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_pack.h | ||
| 13 | + * \brief Pack-side entry points for the kernel bundle (.pyptokb). | ||
| 14 | + * | ||
| 15 | + * Lives in tile_fwk_runtime, NOT in libtile_fwk_bundle.so: the pack hooks are called from the compile/emulation and | ||
| 16 | + * launch paths inside the runtime, whereas the load/query/launch side is the standalone ABI library. Keeping the | ||
| 17 | + * two halves in separate targets is what breaks the otherwise circular dependency between them. | ||
| 18 | + */ | ||
| 19 | + | ||
| 20 | +#pragma once | ||
| 21 | + | ||
| 22 | +#include <cstddef> | ||
| 23 | +#include <cstdint> | ||
| 24 | +#include <mutex> | ||
| 25 | +#include <unordered_set> | ||
| 26 | +#include <vector> | ||
| 27 | + | ||
| 28 | +namespace npu::tile_fwk { | ||
| 29 | + | ||
| 30 | +struct DyndevFunctionAttribute; | ||
| 31 | + | ||
| 32 | +namespace bundle { | ||
| 33 | + | ||
| 34 | +// Serialize the dynamic-workspace symbolic trees + inputSymbolDict into a JSON byte blob. | ||
| 35 | +// Returns empty when the op has no dynamic workspace trees (static bundle -> loader keeps the baked constant). | ||
| 36 | +std::vector<uint8_t> SerializeWorkspaceSymbols(const DyndevFunctionAttribute& dynAttr); | ||
| 37 | + | ||
| 38 | +// Write a .pyptokb for an already-compiled function attribute. No-op unless the bundle is enabled. | ||
| 39 | +// Pass an EMPTY `ctrlFlowCache` for value-dependent (RUNTIME_FUNCKEY_CACHESTOP) ops: the bundle omits the | ||
| 40 | +// CTRL_FLOW_CACHE segment and the device resolves control flow from tensor values at launch. | ||
| 41 | +void MaybePackKernelBundle(const DyndevFunctionAttribute& dynAttr, const std::vector<uint8_t>& ctrlFlowCache); | ||
| 42 | + | ||
| 43 | +// Decouples WHERE the control-flow cache exists from WHERE packing is decided. | ||
| 44 | +// | ||
| 45 | +// The fully relocated base-0 cache only exists for one moment, deep inside the emulation build, but packing must | ||
| 46 | +// not be decided there -- it would put a feature hook in the middle of a build routine, and the value-dependent | ||
| 47 | +// case (which never builds a cache) would need a second hook somewhere else. So the build path only STASHES the | ||
| 48 | +// bytes, and DeviceLauncher::PrepareLaunch -- the single choke point every launch passes through -- decides and | ||
| 49 | +// packs exactly once. | ||
| 50 | +// | ||
| 51 | +// Both entry points are no-ops when the bundle is disabled, so the non-bundle path pays one cached bool test. | ||
| 52 | +class KernelBundlePackHook { | ||
| 53 | +public: | ||
| 54 | + static KernelBundlePackHook& Instance(); | ||
| 55 | + | ||
| 56 | + // Hand over the freshly built base-0 control-flow cache for `dynAttr`. Does not pack. | ||
| 57 | + void StashCtrlFlowCache(const DyndevFunctionAttribute* dynAttr, const uint8_t* cache, size_t size); | ||
| 58 | + | ||
| 59 | + // Pack `dynAttr` once per process. Uses the cache stashed for this op, or an empty one when nothing was | ||
| 60 | + // stashed -- which is exactly the value-dependent case, whose bundle omits the CTRL_FLOW_CACHE segment. | ||
| 61 | + void MaybePack(const DyndevFunctionAttribute* dynAttr); | ||
| 62 | + | ||
| 63 | + KernelBundlePackHook(const KernelBundlePackHook&) = delete; | ||
| 64 | + KernelBundlePackHook& operator=(const KernelBundlePackHook&) = delete; | ||
| 65 | + | ||
| 66 | +private: | ||
| 67 | + KernelBundlePackHook() = default; | ||
| 68 | + ~KernelBundlePackHook() = default; | ||
| 69 | + | ||
| 70 | + std::mutex mutex_; | ||
| 71 | + // Single slot on purpose: the output path (PYPTO_KERNEL_BUNDLE_PATH) is one file, so a process can only ever | ||
| 72 | + // produce one meaningful bundle. Keyed so a stash from op A is never packed into op B's bundle. | ||
| 73 | + const DyndevFunctionAttribute* stashedFor_{nullptr}; | ||
| 74 | + std::vector<uint8_t> stashedCache_; | ||
| 75 | + std::unordered_set<const DyndevFunctionAttribute*> packed_; | ||
| 76 | +}; | ||
| 77 | + | ||
| 78 | +} // namespace bundle | ||
| 79 | +} // namespace npu::tile_fwk | ||
| @@ -0,0 +1,101 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_packer.cpp | ||
| 13 | + * \brief Implementation of the kernel bundle packer. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "machine/runtime/bundle/pack/kernel_bundle_packer.h" | ||
| 17 | + | ||
| 18 | +#include <array> | ||
| 19 | +#include <cstring> | ||
| 20 | + | ||
| 21 | +#include "machine/runtime/bundle/kernel_bundle_crc32.h" | ||
| 22 | +#include "machine/runtime/bundle/kernel_bundle_format.h" | ||
| 23 | +#include "utils/file_utils.h" | ||
| 24 | +#include "tilefwk/error_code.h" | ||
| 25 | +#include "tilefwk/pypto_fwk_log.h" | ||
| 26 | + | ||
| 27 | +namespace npu::tile_fwk::bundle { | ||
| 28 | + | ||
| 29 | +namespace { | ||
| 30 | +inline uint64_t AlignUp(uint64_t v, uint64_t a) { return (v + a - 1) / a * a; } | ||
| 31 | +} // namespace | ||
| 32 | + | ||
| 33 | +std::vector<uint8_t> KernelBundlePacker::Build() const | ||
| 34 | +{ | ||
| 35 | + // Segment order matches TlvType numbering. Empty segments (e.g. ctrlFlowCache) are still emitted | ||
| 36 | + // as zero-length TLVs so the loader can distinguish "absent" from "present but empty". | ||
| 37 | + struct Seg { | ||
| 38 | + TlvType type; | ||
| 39 | + const std::vector<uint8_t>* data; | ||
| 40 | + }; | ||
| 41 | + const std::array<Seg, 5> segs = {{ | ||
| 42 | + {TlvType::AicoreKernel, &aicoreKernel_}, | ||
| 43 | + {TlvType::AicpuSo, &aicpuSo_}, | ||
| 44 | + {TlvType::DevProgram, &devProgram_}, | ||
| 45 | + {TlvType::CtrlFlowCache, &ctrlFlowCache_}, | ||
| 46 | + {TlvType::SymbolMeta, &symbolMeta_}, | ||
| 47 | + }}; | ||
| 48 | + const uint32_t tlvCount = static_cast<uint32_t>(segs.size()); | ||
| 49 | + | ||
| 50 | + // Layout: [BundleHeader][TlvHeader * N] ...padding... [value blocks, each 4KB aligned]. | ||
| 51 | + const uint64_t headerRegion = sizeof(BundleHeader) + static_cast<uint64_t>(tlvCount) * sizeof(TlvHeader); | ||
| 52 | + | ||
| 53 | + std::array<TlvHeader, 5> tlvs{}; | ||
| 54 | + uint64_t cursor = AlignUp(headerRegion, kValueAlign); | ||
| 55 | + for (uint32_t i = 0; i < tlvCount; ++i) { | ||
| 56 | + const auto& d = *segs[i].data; | ||
| 57 | + tlvs[i].type = static_cast<uint32_t>(segs[i].type); | ||
| 58 | + tlvs[i].flags = 0; | ||
| 59 | + tlvs[i].valueOffset = cursor; | ||
| 60 | + tlvs[i].valueLength = d.size(); | ||
| 61 | + tlvs[i].valueCrc32 = Crc32(d.data(), d.size()); | ||
| 62 | + tlvs[i].reserved = 0; | ||
| 63 | + cursor = AlignUp(cursor + d.size(), kValueAlign); | ||
| 64 | + } | ||
| 65 | + const uint64_t totalSize = cursor; | ||
| 66 | + | ||
| 67 | + std::vector<uint8_t> buf(totalSize, 0); | ||
| 68 | + | ||
| 69 | + BundleHeader hdr{}; | ||
| 70 | + hdr.magic = kBundleMagic; | ||
| 71 | + hdr.version = kBundleVersion; | ||
| 72 | + hdr.flags = 0; | ||
| 73 | + hdr.tlvCount = tlvCount; | ||
| 74 | + hdr.headerSize = static_cast<uint32_t>(headerRegion); | ||
| 75 | + hdr.totalSize = totalSize; | ||
| 76 | + hdr.headerCrc32 = Crc32(&hdr, sizeof(BundleHeader) - sizeof(uint32_t)); | ||
| 77 | + | ||
| 78 | + std::memcpy(buf.data(), &hdr, sizeof(BundleHeader)); | ||
| 79 | + std::memcpy(buf.data() + sizeof(BundleHeader), tlvs.data(), tlvCount * sizeof(TlvHeader)); | ||
| 80 | + for (uint32_t i = 0; i < tlvCount; ++i) { | ||
| 81 | + const auto& d = *segs[i].data; | ||
| 82 | + if (!d.empty()) { | ||
| 83 | + std::memcpy(buf.data() + tlvs[i].valueOffset, d.data(), d.size()); | ||
| 84 | + } | ||
| 85 | + } | ||
| 86 | + return buf; | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +bool KernelBundlePacker::Pack(const std::string& outPath) const | ||
| 90 | +{ | ||
| 91 | + std::vector<uint8_t> buf = Build(); | ||
| 92 | + bool ok = SaveFile(outPath, buf.data(), buf.size()); | ||
| 93 | + if (ok) { | ||
| 94 | + MACHINE_LOGI("[kernel-bundle] packed %zu bytes -> %s", buf.size(), outPath.c_str()); | ||
| 95 | + } else { | ||
| 96 | + MACHINE_LOGE(DevCommonErr::FILE_ERROR, "[kernel-bundle] failed to write bundle to %s", outPath.c_str()); | ||
| 97 | + } | ||
| 98 | + return ok; | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,49 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file kernel_bundle_packer.h | ||
| 13 | + * \brief Packs the TLV segments into a single .pyptokb bundle. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#pragma once | ||
| 17 | + | ||
| 18 | +#include <cstdint> | ||
| 19 | +#include <string> | ||
| 20 | +#include <vector> | ||
| 21 | + | ||
| 22 | +namespace npu::tile_fwk::bundle { | ||
| 23 | + | ||
| 24 | +class KernelBundlePacker { | ||
| 25 | +public: | ||
| 26 | + void SetAicoreKernel(std::vector<uint8_t> o) { aicoreKernel_ = std::move(o); } | ||
| 27 | + void SetAicpuSo(std::vector<uint8_t> so) { aicpuSo_ = std::move(so); } | ||
| 28 | + // devProgBinary must already be base-0 (RelocProgram(this, 0)). | ||
| 29 | + void SetDevProgram(std::vector<uint8_t> prog) { devProgram_ = std::move(prog); } | ||
| 30 | + // DevControlFlowCache blob, usedCacheSize bytes, base-0. Optional (may be empty). | ||
| 31 | + void SetCtrlFlowCache(std::vector<uint8_t> cache) { ctrlFlowCache_ = std::move(cache); } | ||
| 32 | + // Serialized dynamic-workspace symbol metadata (JSON). Optional; empty -> loader falls back to static. | ||
| 33 | + void SetSymbolMeta(std::vector<uint8_t> meta) { symbolMeta_ = std::move(meta); } | ||
| 34 | + | ||
| 35 | + // Serialize the assembled bundle into `outPath`. Returns true on success. | ||
| 36 | + bool Pack(const std::string& outPath) const; | ||
| 37 | + | ||
| 38 | + // Serialize the assembled bundle into an in-memory buffer (used by round-trip tests). | ||
| 39 | + std::vector<uint8_t> Build() const; | ||
| 40 | + | ||
| 41 | +private: | ||
| 42 | + std::vector<uint8_t> aicoreKernel_; | ||
| 43 | + std::vector<uint8_t> aicpuSo_; | ||
| 44 | + std::vector<uint8_t> devProgram_; | ||
| 45 | + std::vector<uint8_t> ctrlFlowCache_; | ||
| 46 | + std::vector<uint8_t> symbolMeta_; | ||
| 47 | +}; | ||
| 48 | + | ||
| 49 | +} // namespace npu::tile_fwk::bundle | ||
| @@ -0,0 +1,169 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025-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 | +/*! | ||
| 12 | + * \file pypto_bundle_api.cpp | ||
| 13 | + * \brief Implementation of the two-interface path-based kernel-bundle C ABI. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "tile_fwk_bundle/pypto_bundle_api.h" | ||
| 17 | + | ||
| 18 | +#include <memory> | ||
| 19 | +#include <vector> | ||
| 20 | + | ||
| 21 | +#include "machine/runtime/bundle/kernel_bundle_registry.h" | ||
| 22 | +#include "machine/runtime/bundle/kernel_bundle_workspace.h" | ||
| 23 | +#include "machine/runtime/bundle/kernel_bundle_launch.h" | ||
| 24 | +#include "machine/runtime/launcher/device_launcher.h" | ||
| 25 | +#include "machine/runtime/launcher/device_launcher_binding.h" | ||
| 26 | +#include "machine/runtime/runner/device_runner.h" | ||
| 27 | +#include "tilefwk/data_type.h" | ||
| 28 | +#include "tilefwk/error_code.h" | ||
| 29 | +#include "tilefwk/platform.h" | ||
| 30 | +#include "tilefwk/pypto_fwk_log.h" | ||
| 31 | + | ||
| 32 | +namespace { | ||
| 33 | +using namespace npu::tile_fwk; | ||
| 34 | +using namespace npu::tile_fwk::bundle; | ||
| 35 | +using npu::tile_fwk::dynamic::DeviceLauncher; | ||
| 36 | +using npu::tile_fwk::dynamic::DeviceTensorData; | ||
| 37 | + | ||
| 38 | +std::vector<DeviceTensorData> ToDeviceTensors(const PyptoTensorDesc* descs, uint32_t n) | ||
| 39 | +{ | ||
| 40 | + std::vector<DeviceTensorData> out; | ||
| 41 | + if (descs == nullptr) { | ||
| 42 | + return out; | ||
| 43 | + } | ||
| 44 | + out.reserve(n); | ||
| 45 | + for (uint32_t i = 0; i < n; ++i) { | ||
| 46 | + const PyptoTensorDesc& d = descs[i]; | ||
| 47 | + const int32_t rank = (d.rank < 0) ? 0 : (d.rank > 8 ? 8 : d.rank); | ||
| 48 | + std::vector<int64_t> shape(d.shape, d.shape + rank); | ||
| 49 | + out.emplace_back(static_cast<DataType>(d.dataType), d.addr, shape); | ||
| 50 | + } | ||
| 51 | + return out; | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +// Post-load prep shared by the path and in-memory entries: seed the AiCpu backend .so from the bundle's AICPU_SO | ||
| 55 | +// segment before any DeviceRunner::Init(), arch-check, and register the aicore .o. Stays pure host (no Get()). | ||
| 56 | +std::shared_ptr<LoadedBundle> PrepareBundle(std::shared_ptr<LoadedBundle> bundle) | ||
| 57 | +{ | ||
| 58 | + if (bundle == nullptr) { | ||
| 59 | + return nullptr; | ||
| 60 | + } | ||
| 61 | + if (!bundle->aicpuSo.empty()) { | ||
| 62 | + // Harmless to set repeatedly; only the first Get() (inside the first Launch) consumes it. | ||
| 63 | + DeviceRunner::SetAiCpuSoOverride(bundle->aicpuSo); | ||
| 64 | + } else { | ||
| 65 | + MACHINE_LOGW("[kernel-bundle] bundle has no AICPU_SO segment; will fall back to on-disk backend .so"); | ||
| 66 | + } | ||
| 67 | + const uint32_t targetArch = static_cast<uint32_t>(Platform::Instance().GetSoc().GetNPUArch()); | ||
| 68 | + if (bundle->GetArchInfo() != targetArch) { | ||
| 69 | + MACHINE_LOGE(DevCommonErr::PARAM_CHECK_FAILED, "[kernel-bundle] arch mismatch: bundle=%u target=%u", | ||
| 70 | + bundle->GetArchInfo(), targetArch); | ||
| 71 | + return nullptr; | ||
| 72 | + } | ||
| 73 | + if (KernelBundleRegistry::GetInstance().GetOrRegisterKernel(bundle->bundleKey, bundle->aicoreKernel) == nullptr) { | ||
| 74 | + return nullptr; | ||
| 75 | + } | ||
| 76 | + return bundle; | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +// Idempotent load-or-get from a disk path. | ||
| 80 | +std::shared_ptr<LoadedBundle> EnsureLoaded(const char* path) | ||
| 81 | +{ | ||
| 82 | + if (path == nullptr) { | ||
| 83 | + MACHINE_LOGE(DevCommonErr::PARAM_CHECK_FAILED, "[kernel-bundle] null path"); | ||
| 84 | + return nullptr; | ||
| 85 | + } | ||
| 86 | + return PrepareBundle(KernelBundleRegistry::GetInstance().LoadOrGet(path)); | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +// Idempotent load-or-get from an in-memory .pyptokb image (client already loaded the bytes; no disk path). | ||
| 90 | +std::shared_ptr<LoadedBundle> EnsureLoadedFromMemory(const void* data, size_t size) | ||
| 91 | +{ | ||
| 92 | + if (data == nullptr || size == 0) { | ||
| 93 | + MACHINE_LOGE(DevCommonErr::PARAM_CHECK_FAILED, "[kernel-bundle] null/empty bundle image"); | ||
| 94 | + return nullptr; | ||
| 95 | + } | ||
| 96 | + return PrepareBundle( | ||
| 97 | + KernelBundleRegistry::GetInstance().LoadOrGetFromMemory(reinterpret_cast<const uint8_t*>(data), size)); | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +// Shared query/launch bodies (bundle already prepared). `tensors` is the unified operand list. | ||
| 101 | +uint64_t WorkspaceImpl(const std::shared_ptr<LoadedBundle>& bundle, const PyptoTensorDesc* tensors, uint32_t n) | ||
| 102 | +{ | ||
| 103 | + if (bundle == nullptr) { | ||
| 104 | + return 0; | ||
| 105 | + } | ||
| 106 | + // Pure host workspace evaluation; patches the bundle's in-memory memBudget in place. Does NOT init the device. | ||
| 107 | + std::vector<DeviceTensorData> inputs = ToDeviceTensors(tensors, n); | ||
| 108 | + static const std::vector<DeviceTensorData> kNoOutputs; | ||
| 109 | + return EvalWorkspaceForShapes(*bundle, inputs, kNoOutputs); | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +int LaunchImpl(const std::shared_ptr<LoadedBundle>& bundle, const PyptoTensorDesc* tensors, uint32_t n, | ||
| 113 | + void* workspaceAddr, void* stream, int sync) | ||
| 114 | +{ | ||
| 115 | + if (bundle == nullptr) { | ||
| 116 | + MACHINE_LOGE(DevCommonErr::PARAM_CHECK_FAILED, "[kernel-bundle] EnsureLoaded failed for launch"); | ||
| 117 | + return -1; | ||
| 118 | + } | ||
| 119 | + void* binHandle = KernelBundleRegistry::GetInstance().GetOrRegisterKernel(bundle->bundleKey, bundle->aicoreKernel); | ||
| 120 | + if (binHandle == nullptr) { | ||
| 121 | + return -1; | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + std::vector<DeviceTensorData> inputs = ToDeviceTensors(tensors, n); | ||
| 125 | + static const std::vector<DeviceTensorData> kNoOutputs; | ||
| 126 | + | ||
| 127 | + // Re-evaluate + patch memBudget for THIS shape before building kArgs. Idempotent if Workspace already ran on | ||
| 128 | + // the same shape; required when Launch is called standalone. | ||
| 129 | + (void)EvalWorkspaceForShapes(*bundle, inputs, kNoOutputs); | ||
| 130 | + | ||
| 131 | + // blockdim = op parallelism baked into the packed program (ctrlBlockDim / nrValidAic). | ||
| 132 | + const auto* head = bundle->Head(); | ||
| 133 | + dynamic::DeviceLauncherConfig config; | ||
| 134 | + config.blockdim = head->ctrlBlockDim != 0 ? static_cast<int>(head->ctrlBlockDim) : | ||
| 135 | + static_cast<int>(head->devArgs.nrValidAic); | ||
| 136 | + | ||
| 137 | + return dynamic::LaunchBundleKernelOnce(bundle->devProgram, binHandle, bundle->bundleKey, inputs, | ||
| 138 | + bundle->ctrlFlowCache, bundle->cellMatchStridePatches, workspaceAddr, | ||
| 139 | + static_cast<RtStream>(stream), sync != 0, config); | ||
| 140 | +} | ||
| 141 | +} // namespace | ||
| 142 | + | ||
| 143 | +extern "C" { | ||
| 144 | + | ||
| 145 | +uint64_t PyptoWorkspace(const char* path, const PyptoTensorDesc* tensors, uint32_t nTensors) | ||
| 146 | +{ | ||
| 147 | + return WorkspaceImpl(EnsureLoaded(path), tensors, nTensors); | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +int PyptoLaunch(const char* path, const PyptoTensorDesc* tensors, uint32_t nTensors, void* workspaceAddr, void* stream, | ||
| 151 | + int sync) | ||
| 152 | +{ | ||
| 153 | + return LaunchImpl(EnsureLoaded(path), tensors, nTensors, workspaceAddr, stream, sync); | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +uint64_t PyptoWorkspaceFromMemory(const void* bundleData, uint64_t bundleSize, const PyptoTensorDesc* tensors, | ||
| 157 | + uint32_t nTensors) | ||
| 158 | +{ | ||
| 159 | + return WorkspaceImpl(EnsureLoadedFromMemory(bundleData, static_cast<size_t>(bundleSize)), tensors, nTensors); | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +int PyptoLaunchFromMemory(const void* bundleData, uint64_t bundleSize, const PyptoTensorDesc* tensors, | ||
| 163 | + uint32_t nTensors, void* workspaceAddr, void* stream, int sync) | ||
| 164 | +{ | ||
| 165 | + return LaunchImpl(EnsureLoadedFromMemory(bundleData, static_cast<size_t>(bundleSize)), tensors, nTensors, | ||
| 166 | + workspaceAddr, stream, sync); | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +} // extern "C" | ||
| @@ -0,0 +1,13 @@ | |||
| 1 | +/* Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | + * Linker version script for libtile_fwk_bundle.so: expose only the documented .pyptokb C ABI | ||
| 3 | + * (see pypto_bundle_api.h) and hide every internal symbol. | ||
| 4 | + */ | ||
| 5 | +{ | ||
| 6 | + global: | ||
| 7 | + PyptoWorkspace; | ||
| 8 | + PyptoLaunch; | ||
| 9 | + PyptoWorkspaceFromMemory; | ||
| 10 | + PyptoLaunchFromMemory; | ||
| 11 | + local: | ||
| 12 | + *; | ||
| 13 | +}; | ||
| @@ -130,13 +130,19 @@ bool TryBuildDynamicCellMatchDesc(const DyndevFunctionAttribute::DynamicCellMatc | |||
| 130 | 130 | ||
| 131 | std::vector<DevDynamicCellMatchStridePatch> PrepareDynamicCellMatchDescPatches(const DyndevFunctionAttribute& dynAttr, | 131 | std::vector<DevDynamicCellMatchStridePatch> PrepareDynamicCellMatchDescPatches(const DyndevFunctionAttribute& dynAttr, |
| 132 | Evaluator& eval) | 132 | Evaluator& eval) |
| 133 | +{ | ||
| 134 | + return PrepareDynamicCellMatchDescPatches(dynAttr.dynamicCellMatchLaunchMetaList, eval); | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +std::vector<DevDynamicCellMatchStridePatch> PrepareDynamicCellMatchDescPatches( | ||
| 138 | + const std::vector<DyndevFunctionAttribute::DynamicCellMatchLaunchMeta>& launchMetaList, Evaluator& eval) | ||
| 133 | { | 139 | { |
| 134 | std::vector<DevDynamicCellMatchStridePatch> patches; | 140 | std::vector<DevDynamicCellMatchStridePatch> patches; |
| 135 | - if (dynAttr.dynamicCellMatchLaunchMetaList.empty()) { | 141 | + if (launchMetaList.empty()) { |
| 136 | return patches; | 142 | return patches; |
| 137 | } | 143 | } |
| 138 | 144 | ||
| 139 | - for (const auto& launchMeta : dynAttr.dynamicCellMatchLaunchMetaList) { | 145 | + for (const auto& launchMeta : launchMetaList) { |
| 140 | DevCellMatchTableDesc patchedDesc; | 146 | DevCellMatchTableDesc patchedDesc; |
| 141 | bool ready = TryBuildDynamicCellMatchDesc(launchMeta, eval, patchedDesc); | 147 | bool ready = TryBuildDynamicCellMatchDesc(launchMeta, eval, patchedDesc); |
| 142 | if (!ready) { | 148 | if (!ready) { |
| @@ -30,6 +30,10 @@ struct Evaluator; | |||
| 30 | std::vector<DevDynamicCellMatchStridePatch> PrepareDynamicCellMatchDescPatches(const DyndevFunctionAttribute& dynAttr, | 30 | std::vector<DevDynamicCellMatchStridePatch> PrepareDynamicCellMatchDescPatches(const DyndevFunctionAttribute& dynAttr, |
| 31 | Evaluator& eval); | 31 | Evaluator& eval); |
| 32 | 32 | ||
| 33 | +// Overload for the kernel-bundle load path (launch-meta list only, no Function). | ||
| 34 | +std::vector<DevDynamicCellMatchStridePatch> PrepareDynamicCellMatchDescPatches( | ||
| 35 | + const std::vector<DyndevFunctionAttribute::DynamicCellMatchLaunchMeta>& launchMetaList, Evaluator& eval); | ||
| 36 | + | ||
| 33 | void PatchHostDynamicCellMatchTableDesc(DevAscendProgram* hostDevProg, | 37 | void PatchHostDynamicCellMatchTableDesc(DevAscendProgram* hostDevProg, |
| 34 | const std::vector<DevDynamicCellMatchStridePatch>& patches); | 38 | const std::vector<DevDynamicCellMatchStridePatch>& patches); |
| 35 | 39 | ||
| @@ -30,6 +30,7 @@ | |||
| 30 | #include "machine/runtime/launcher/emulation_launcher.h" | 30 | #include "machine/runtime/launcher/emulation_launcher.h" |
| 31 | #include "machine/runtime/launcher/aicore_model_launcher.h" | 31 | #include "machine/runtime/launcher/aicore_model_launcher.h" |
| 32 | #include "machine/runtime/launcher/ctrl_flow_cache_manager.h" | 32 | #include "machine/runtime/launcher/ctrl_flow_cache_manager.h" |
| 33 | +#include "machine/runtime/bundle/pack/kernel_bundle_pack.h" | ||
| 33 | #include "machine/runtime/runner/kernel_binary.h" | 34 | #include "machine/runtime/runner/kernel_binary.h" |
| 34 | #include "machine/host/perf_analysis.h" | 35 | #include "machine/host/perf_analysis.h" |
| 35 | #include "interface/program/program.h" | 36 | #include "interface/program/program.h" |
| @@ -541,6 +542,10 @@ uint8_t* DeviceLauncher::PrepareLaunch(KernelBinary* kernel, std::vector<DeviceT | |||
| 541 | // findOrBuildDevCache===>kermode FindCtrlFlowcache | 542 | // findOrBuildDevCache===>kermode FindCtrlFlowcache |
| 542 | uint8_t* ctrlFlowCache = cacheMgr.FindOrBuildDevCache(kernel, tensors); | 543 | uint8_t* ctrlFlowCache = cacheMgr.FindOrBuildDevCache(kernel, tensors); |
| 543 | HOST_PERF_TRACE(TracePhase::FindCtrlFlowCache); | 544 | HOST_PERF_TRACE(TracePhase::FindCtrlFlowCache); |
| 545 | + // The one place kernel-bundle packing is decided, for every launch mode and both cache flavours. The cache | ||
| 546 | + // build above has by now stashed its bytes with the hook (value-dependent ops stash nothing, which is what | ||
| 547 | + // makes their bundle cacheless). No-op unless PYPTO_ENABLE_KERNEL_BUNDLE=1; packs once per op. | ||
| 548 | + bundle::KernelBundlePackHook::Instance().MaybePack(kernel->GetFunction()->GetDyndevAttribute().get()); | ||
| 544 | // emulation launch | 549 | // emulation launch |
| 545 | if (launchMode == LaunchMode::DEVICE_RT) { | 550 | if (launchMode == LaunchMode::DEVICE_RT) { |
| 546 | return ctrlFlowCache; | 551 | return ctrlFlowCache; |
| @@ -21,6 +21,7 @@ | |||
| 21 | #include "machine/runtime/launcher/device_launcher.h" | 21 | #include "machine/runtime/launcher/device_launcher.h" |
| 22 | #include "machine/runtime/runner/runtime_utils.h" | 22 | #include "machine/runtime/runner/runtime_utils.h" |
| 23 | #include "machine/runtime/launcher/device_launcher_binding.h" | 23 | #include "machine/runtime/launcher/device_launcher_binding.h" |
| 24 | +#include "machine/runtime/bundle/pack/kernel_bundle_pack.h" | ||
| 24 | 25 | ||
| 25 | extern "C" int DynTileFwkBackendKernelServer(void* targ); | 26 | extern "C" int DynTileFwkBackendKernelServer(void* targ); |
| 26 | 27 | ||
| @@ -237,6 +238,11 @@ int EmulationLauncher::BuildControlFlowCacheWithEmulationTensorData( | |||
| 237 | if (outCtrlFlowCache) { | 238 | if (outCtrlFlowCache) { |
| 238 | *outCtrlFlowCache = hostCtrlFlowCache; | 239 | *outCtrlFlowCache = hostCtrlFlowCache; |
| 239 | } | 240 | } |
| 241 | + | ||
| 242 | + // Hand the freshly relocated base-0 cache to the pack hook. Packing itself is decided at the launch choke | ||
| 243 | + // point (DeviceLauncher::PrepareLaunch), not here -- see KernelBundlePackHook. | ||
| 244 | + bundle::KernelBundlePackHook::Instance().StashCtrlFlowCache( | ||
| 245 | + dynAttr.get(), reinterpret_cast<const uint8_t*>(hostCtrlFlowCache), hostCtrlFlowCache->usedCacheSize); | ||
| 240 | return rc; | 246 | return rc; |
| 241 | } | 247 | } |
| 242 | 248 | ||
| @@ -51,6 +51,9 @@ constexpr uint32_t HIGHT_BIT = 16; | |||
| 51 | constexpr uint32_t SUB_CORE = 3; | 51 | constexpr uint32_t SUB_CORE = 3; |
| 52 | constexpr uint32_t AIV_PER_AICORE = 2; | 52 | constexpr uint32_t AIV_PER_AICORE = 2; |
| 53 | constexpr uint32_t AICPU_NUM_OF_RUN_AICPU_TASKS = 1; | 53 | constexpr uint32_t AICPU_NUM_OF_RUN_AICPU_TASKS = 1; |
| 54 | +// AiCpu backend .so bytes from a kernel bundle; when non-empty, InitAiCpuSoBin uses these instead of the | ||
| 55 | +// on-disk copy. Set before Init() runs, so no locking is needed. | ||
| 56 | +std::vector<uint8_t> g_aicpuSoOverride; | ||
| 54 | } // namespace | 57 | } // namespace |
| 55 | 58 | ||
| 56 | DeviceRunner::~DeviceRunner() {} | 59 | DeviceRunner::~DeviceRunner() {} |
| @@ -204,22 +207,33 @@ int DeviceRunner::DynamicLaunchSynchronize(RtStream schedStream, RtStream ctrlSt | |||
| 204 | return rcAicore + rcAicpu + rcCtrl; | 207 | return rcAicore + rcAicpu + rcCtrl; |
| 205 | } | 208 | } |
| 206 | 209 | ||
| 210 | +void DeviceRunner::SetAiCpuSoOverride(std::vector<uint8_t> soBytes) { g_aicpuSoOverride = std::move(soBytes); } | ||
| 211 | + | ||
| 207 | void DeviceRunner::InitAiCpuSoBin(DeviceArgs& devArgs) | 212 | void DeviceRunner::InitAiCpuSoBin(DeviceArgs& devArgs) |
| 208 | { | 213 | { |
| 209 | - std::string fileName = GetPyptoLibPath() + "/libtilefwk_backend_server.so"; | 214 | + std::vector<uint8_t> buffer; |
| 210 | - auto buffer = ReadFile(fileName); | 215 | + std::string source; |
| 216 | + if (!g_aicpuSoOverride.empty()) { | ||
| 217 | + buffer = g_aicpuSoOverride; // bundle-supplied .so takes precedence over the on-disk copy | ||
| 218 | + source = "kernel-bundle AICPU_SO"; | ||
| 219 | + } else { | ||
| 220 | + std::string fileName = GetPyptoLibPath() + "/libtilefwk_backend_server.so"; | ||
| 221 | + source = fileName; | ||
| 222 | + buffer = ReadFile(fileName); | ||
| 223 | + } | ||
| 211 | if (buffer.empty()) { | 224 | if (buffer.empty()) { |
| 212 | MACHINE_LOGE(DevCommonErr::FILE_ERROR, | 225 | MACHINE_LOGE(DevCommonErr::FILE_ERROR, |
| 213 | - "Read bin form tilefwk_backend_server.so failed, please check the so[%s]", fileName.c_str()); | 226 | + "Read bin form tilefwk_backend_server.so failed, please check the so[%s]", source.c_str()); |
| 214 | return; | 227 | return; |
| 215 | } | 228 | } |
| 216 | void* devBufferPtr = CopyDataToDevice(buffer.data(), buffer.size()); | 229 | void* devBufferPtr = CopyDataToDevice(buffer.data(), buffer.size()); |
| 217 | if (devBufferPtr == nullptr) { | 230 | if (devBufferPtr == nullptr) { |
| 218 | - MACHINE_LOGE(DevCommonErr::MEMCPY_FAILED, "Failed to copy buffer of [%s] to device.", fileName.c_str()); | 231 | + MACHINE_LOGE(DevCommonErr::MEMCPY_FAILED, "Failed to copy buffer of [%s] to device.", source.c_str()); |
| 219 | return; | 232 | return; |
| 220 | } | 233 | } |
| 221 | devArgs.aicpuSoBin = reinterpret_cast<uint64_t>(devBufferPtr); | 234 | devArgs.aicpuSoBin = reinterpret_cast<uint64_t>(devBufferPtr); |
| 222 | devArgs.aicpuSoLen = buffer.size(); | 235 | devArgs.aicpuSoLen = buffer.size(); |
| 236 | + MACHINE_LOGI("[aicpu-so] init backend server .so from %s, len=%zu", source.c_str(), buffer.size()); | ||
| 223 | HOST_PERF_TRACE(TracePhase::RunDevKernelInitAicpuSo); | 237 | HOST_PERF_TRACE(TracePhase::RunDevKernelInitAicpuSo); |
| 224 | } | 238 | } |
| 225 | 239 | ||
| @@ -15,6 +15,7 @@ | |||
| 15 | 15 | ||
| 16 | #pragma once | 16 | #pragma once |
| 17 | 17 | ||
| 18 | +#include <cstdint> | ||
| 18 | #include <vector> | 19 | #include <vector> |
| 19 | #include <mutex> | 20 | #include <mutex> |
| 20 | #include "machine/runtime/runner/host_prof.h" | 21 | #include "machine/runtime/runner/host_prof.h" |
| @@ -57,6 +58,10 @@ public: | |||
| 57 | void SyncProfData(bool debugEnable); | 58 | void SyncProfData(bool debugEnable); |
| 58 | void SetDebugEnable(); | 59 | void SetDebugEnable(); |
| 59 | 60 | ||
| 61 | + // Use bundle-supplied AiCpu backend .so bytes for Init() instead of the on-disk copy. | ||
| 62 | + // Must be called before Init(); a later call has no effect. | ||
| 63 | + static void SetAiCpuSoOverride(std::vector<uint8_t> soBytes); | ||
| 64 | + | ||
| 60 | private: | 65 | private: |
| 61 | DeviceRunner() = default; | 66 | DeviceRunner() = default; |
| 62 | ~DeviceRunner(); | 67 | ~DeviceRunner(); |
| @@ -0,0 +1,11 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Kernel-bundle (.pyptokb) test package.""" | ||
| @@ -0,0 +1,223 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Shared plumbing for the kernel-bundle STs: the .pyptokb TLV reader and the 4-symbol C ABI binding. | ||
| 12 | + | ||
| 13 | +Deliberately free of top-level ``pypto`` / ``torch`` imports so the pytest driver can read a bundle's | ||
| 14 | +segment table without dragging the whole frontend into the collector process. | ||
| 15 | +Mirrors ``framework/src/machine/runtime/bundle/kernel_bundle_format.h`` and | ||
| 16 | +``framework/include/tile_fwk_bundle/pypto_bundle_api.h``. | ||
| 17 | +""" | ||
| 18 | +import ctypes | ||
| 19 | +import os | ||
| 20 | +import struct | ||
| 21 | + | ||
| 22 | +BUNDLE_MAGIC = b"PYPTOKB\0" | ||
| 23 | +BUNDLE_VERSION = 1 | ||
| 24 | + | ||
| 25 | +# TlvType (kernel_bundle_format.h). A segment that exists but is empty is still written as a 0-length TLV, | ||
| 26 | +# which is what distinguishes "absent" from "present but empty" -- the value-dependent ops rely on that. | ||
| 27 | +TLV_AICORE_KERNEL = 1 | ||
| 28 | +TLV_AICPU_SO = 2 | ||
| 29 | +TLV_DEV_PROGRAM = 3 | ||
| 30 | +TLV_CTRL_FLOW_CACHE = 4 | ||
| 31 | +TLV_SYMBOL_META = 5 | ||
| 32 | + | ||
| 33 | +TLV_NAMES = { | ||
| 34 | + TLV_AICORE_KERNEL: "AicoreKernel", | ||
| 35 | + TLV_AICPU_SO: "AicpuSo", | ||
| 36 | + TLV_DEV_PROGRAM: "DevProgram", | ||
| 37 | + TLV_CTRL_FLOW_CACHE: "CtrlFlowCache", | ||
| 38 | + TLV_SYMBOL_META: "SymbolMeta", | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +_HEADER_SIZE = 64 | ||
| 42 | +_TLV_SIZE = 32 | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class BundleTlv: | ||
| 46 | + """One parsed TLV entry.""" | ||
| 47 | + | ||
| 48 | + def __init__(self, type_id: int, offset: int, length: int, crc32: int): | ||
| 49 | + self.type_id = type_id | ||
| 50 | + self.offset = offset | ||
| 51 | + self.length = length | ||
| 52 | + self.crc32 = crc32 | ||
| 53 | + | ||
| 54 | + @property | ||
| 55 | + def name(self) -> str: | ||
| 56 | + return TLV_NAMES.get(self.type_id, f"Unknown({self.type_id})") | ||
| 57 | + | ||
| 58 | + def __repr__(self) -> str: | ||
| 59 | + return f"<Tlv {self.name} offset={self.offset} length={self.length}>" | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def read_bundle_tlvs(path: str) -> dict: | ||
| 63 | + """Parse the .pyptokb header + TLV table. Returns {type_id: BundleTlv}. | ||
| 64 | + | ||
| 65 | + Validates the container envelope only (magic / version / totalSize); the per-segment CRCs are the | ||
| 66 | + loader's job and are covered by the fact that the consume step actually loads the file. | ||
| 67 | + """ | ||
| 68 | + file_size = os.path.getsize(path) | ||
| 69 | + with open(path, "rb") as f: | ||
| 70 | + header = f.read(_HEADER_SIZE) | ||
| 71 | + if len(header) != _HEADER_SIZE: | ||
| 72 | + raise ValueError(f"{path}: truncated bundle header ({len(header)}B)") | ||
| 73 | + magic = header[:8] | ||
| 74 | + version, _flags, tlv_count, _header_size = struct.unpack_from("<IIII", header, 8) | ||
| 75 | + total_size, = struct.unpack_from("<Q", header, 24) | ||
| 76 | + if magic != BUNDLE_MAGIC: | ||
| 77 | + raise ValueError(f"{path}: bad magic {magic!r}, expected {BUNDLE_MAGIC!r}") | ||
| 78 | + if version != BUNDLE_VERSION: | ||
| 79 | + raise ValueError(f"{path}: bundle version {version}, expected {BUNDLE_VERSION}") | ||
| 80 | + if total_size != file_size: | ||
| 81 | + raise ValueError(f"{path}: header totalSize={total_size} but file is {file_size}B") | ||
| 82 | + | ||
| 83 | + tlvs = {} | ||
| 84 | + for _ in range(tlv_count): | ||
| 85 | + raw = f.read(_TLV_SIZE) | ||
| 86 | + if len(raw) != _TLV_SIZE: | ||
| 87 | + raise ValueError(f"{path}: truncated TLV table") | ||
| 88 | + type_id, _tlv_flags = struct.unpack_from("<II", raw, 0) | ||
| 89 | + offset, length = struct.unpack_from("<QQ", raw, 8) | ||
| 90 | + crc32, = struct.unpack_from("<I", raw, 24) | ||
| 91 | + if offset + length > file_size: | ||
| 92 | + raise ValueError(f"{path}: TLV {type_id} runs past EOF ({offset}+{length} > {file_size})") | ||
| 93 | + tlvs[type_id] = BundleTlv(type_id, offset, length, crc32) | ||
| 94 | + return tlvs | ||
| 95 | + | ||
| 96 | + | ||
| 97 | +def read_symbol_meta(path: str) -> str: | ||
| 98 | + """Return the SymbolMeta segment as text ('' when the segment is absent or empty).""" | ||
| 99 | + tlv = read_bundle_tlvs(path).get(TLV_SYMBOL_META) | ||
| 100 | + if tlv is None or tlv.length == 0: | ||
| 101 | + return "" | ||
| 102 | + with open(path, "rb") as f: | ||
| 103 | + f.seek(tlv.offset) | ||
| 104 | + return f.read(tlv.length).decode("utf-8", "replace") | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +class PyptoTensorDesc(ctypes.Structure): | ||
| 108 | + """pypto_bundle_api.h PyptoTensorDesc.""" | ||
| 109 | + | ||
| 110 | + _fields_ = [ | ||
| 111 | + ("addr", ctypes.c_void_p), | ||
| 112 | + ("dataType", ctypes.c_int32), | ||
| 113 | + ("rank", ctypes.c_int32), | ||
| 114 | + ("shape", ctypes.c_int64 * 8), | ||
| 115 | + ] | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +def dtype_enum(torch_dtype) -> int: | ||
| 119 | + """Map a torch dtype onto the internal DataType enum value (tilefwk/data_type.h). | ||
| 120 | + | ||
| 121 | + Resolved through the pypto enum rather than hard-coded, so a reordering of DATA_TYPE_ALL cannot | ||
| 122 | + silently desync the ST from the runtime. | ||
| 123 | + """ | ||
| 124 | + import torch | ||
| 125 | + | ||
| 126 | + import pypto | ||
| 127 | + | ||
| 128 | + mapping = { | ||
| 129 | + torch.float32: pypto.DT_FP32, | ||
| 130 | + torch.float16: pypto.DT_FP16, | ||
| 131 | + torch.bfloat16: pypto.DT_BF16, | ||
| 132 | + torch.int32: pypto.DT_INT32, | ||
| 133 | + torch.int64: pypto.DT_INT64, | ||
| 134 | + torch.int8: pypto.DT_INT8, | ||
| 135 | + torch.uint8: pypto.DT_UINT8, | ||
| 136 | + torch.bool: pypto.DT_BOOL, | ||
| 137 | + } | ||
| 138 | + if torch_dtype not in mapping: | ||
| 139 | + raise ValueError(f"no DataType mapping for {torch_dtype}") | ||
| 140 | + return int(mapping[torch_dtype]) | ||
| 141 | + | ||
| 142 | + | ||
| 143 | +def make_desc(tensor) -> PyptoTensorDesc: | ||
| 144 | + """Build a PyptoTensorDesc from a device torch tensor.""" | ||
| 145 | + desc = PyptoTensorDesc() | ||
| 146 | + desc.addr = ctypes.c_void_p(tensor.data_ptr()) | ||
| 147 | + desc.dataType = dtype_enum(tensor.dtype) | ||
| 148 | + desc.rank = tensor.dim() | ||
| 149 | + if tensor.dim() > len(desc.shape): | ||
| 150 | + raise ValueError(f"rank {tensor.dim()} exceeds the {len(desc.shape)}-dim PyptoTensorDesc") | ||
| 151 | + for i in range(tensor.dim()): | ||
| 152 | + desc.shape[i] = tensor.shape[i] | ||
| 153 | + return desc | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +def make_desc_array(tensors): | ||
| 157 | + """Build the unified operand array (inputs then outputs, nOut folded in) the ABI expects.""" | ||
| 158 | + return (PyptoTensorDesc * len(tensors))(*[make_desc(t) for t in tensors]) | ||
| 159 | + | ||
| 160 | + | ||
| 161 | +def bundle_so_path() -> str: | ||
| 162 | + """Locate libtile_fwk_bundle.so. PYPTO_BUNDLE_SO overrides it (e.g. to point at the standalone form).""" | ||
| 163 | + override = os.environ.get("PYPTO_BUNDLE_SO") | ||
| 164 | + if override: | ||
| 165 | + return override | ||
| 166 | + import pypto | ||
| 167 | + | ||
| 168 | + return os.path.join(os.path.dirname(os.path.abspath(pypto.__file__)), "lib", "libtile_fwk_bundle.so") | ||
| 169 | + | ||
| 170 | + | ||
| 171 | +def load_bundle_lib(): | ||
| 172 | + """dlopen the bundle ABI and declare its 4 exported symbols.""" | ||
| 173 | + lib = ctypes.CDLL(bundle_so_path(), mode=ctypes.RTLD_GLOBAL) | ||
| 174 | + desc_p = ctypes.POINTER(PyptoTensorDesc) | ||
| 175 | + | ||
| 176 | + lib.PyptoWorkspace.restype = ctypes.c_uint64 | ||
| 177 | + lib.PyptoWorkspace.argtypes = [ctypes.c_char_p, desc_p, ctypes.c_uint32] | ||
| 178 | + lib.PyptoLaunch.restype = ctypes.c_int | ||
| 179 | + lib.PyptoLaunch.argtypes = [ | ||
| 180 | + ctypes.c_char_p, desc_p, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, | ||
| 181 | + ] | ||
| 182 | + lib.PyptoWorkspaceFromMemory.restype = ctypes.c_uint64 | ||
| 183 | + lib.PyptoWorkspaceFromMemory.argtypes = [ctypes.c_void_p, ctypes.c_uint64, desc_p, ctypes.c_uint32] | ||
| 184 | + lib.PyptoLaunchFromMemory.restype = ctypes.c_int | ||
| 185 | + lib.PyptoLaunchFromMemory.argtypes = [ | ||
| 186 | + ctypes.c_void_p, ctypes.c_uint64, desc_p, ctypes.c_uint32, | ||
| 187 | + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, | ||
| 188 | + ] | ||
| 189 | + return lib | ||
| 190 | + | ||
| 191 | + | ||
| 192 | +class BundleClient: | ||
| 193 | + """Thin facade over the two-call ABI, selecting the path or the in-memory variant.""" | ||
| 194 | + | ||
| 195 | + def __init__(self, bundle_path: str, api: str = "path"): | ||
| 196 | + if api not in ("path", "memory"): | ||
| 197 | + raise ValueError(f"api must be 'path' or 'memory', got {api!r}") | ||
| 198 | + self.api = api | ||
| 199 | + self.lib = load_bundle_lib() | ||
| 200 | + self._path_c = bundle_path.encode() | ||
| 201 | + self._blob = None | ||
| 202 | + self._blob_ptr = None | ||
| 203 | + self._blob_len = 0 | ||
| 204 | + if api == "memory": | ||
| 205 | + # The client already holds the image in its own buffer; the ABI never touches the disk path. | ||
| 206 | + with open(bundle_path, "rb") as f: | ||
| 207 | + self._blob = f.read() | ||
| 208 | + self._blob_ptr = ctypes.cast(ctypes.c_char_p(self._blob), ctypes.c_void_p) | ||
| 209 | + self._blob_len = len(self._blob) | ||
| 210 | + | ||
| 211 | + def workspace(self, descs) -> int: | ||
| 212 | + """Query the workspace byte count for these shapes. Pure host: does not init the device.""" | ||
| 213 | + n = len(descs) | ||
| 214 | + if self.api == "path": | ||
| 215 | + return self.lib.PyptoWorkspace(self._path_c, descs, n) | ||
| 216 | + return self.lib.PyptoWorkspaceFromMemory(self._blob_ptr, self._blob_len, descs, n) | ||
| 217 | + | ||
| 218 | + def launch(self, descs, workspace_ptr, stream=None, sync=1) -> int: | ||
| 219 | + n = len(descs) | ||
| 220 | + if self.api == "path": | ||
| 221 | + return self.lib.PyptoLaunch(self._path_c, descs, n, workspace_ptr, stream, sync) | ||
| 222 | + return self.lib.PyptoLaunchFromMemory( | ||
| 223 | + self._blob_ptr, self._blob_len, descs, n, workspace_ptr, stream, sync) | ||
| @@ -0,0 +1,379 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Kernel-bundle scenario worker: the pack half and the consume half of each .pyptokb case. | ||
| 12 | + | ||
| 13 | +Run as a subprocess by ``test_kernel_bundle.py``; never imported by the pytest process itself. | ||
| 14 | +Two phases must be separate processes because the consume half plays the role of a downstream that only | ||
| 15 | +has ``libtile_fwk_bundle.so`` + a ``.pyptokb`` -- no compiler front end, no recorded Program state. | ||
| 16 | + | ||
| 17 | + python3 bundle_cases.py pack <case> <bundle_path> | ||
| 18 | + python3 bundle_cases.py consume <case> <bundle_path> [--api path|memory] | ||
| 19 | + | ||
| 20 | +Cases: | ||
| 21 | + static_add non-value-dependent, static workspace (0 B); packed through the emulation hook, so the | ||
| 22 | + bundle carries a NON-EMPTY CtrlFlowCache snapshot. | ||
| 23 | + dyn_cellmatch non-value-dependent but dynamically shaped: SymbolMeta carries real symbolic trees plus | ||
| 24 | + the dynamic cell-match launch metas, so workspace is re-evaluated per launch shape. | ||
| 25 | + value_depend_pa value-dependent control flow (loop bounds read from act_seqs tensor VALUES). Packed | ||
| 26 | + through the value-depend hook, so the CtrlFlowCache segment is EMPTY and the on-device | ||
| 27 | + interpreter resolves the trip counts at launch. | ||
| 28 | +""" | ||
| 29 | +import argparse | ||
| 30 | +import ctypes | ||
| 31 | +import os | ||
| 32 | +import sys | ||
| 33 | + | ||
| 34 | +# This worker runs as a standalone script (python3 bundle_cases.py ...), not under pytest, so the tests root | ||
| 35 | +# has to reach sys.path before the st.* imports below -- hence the E402 waivers, as elsewhere in the tree. | ||
| 36 | +_TESTS_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 37 | +if _TESTS_ROOT not in sys.path: | ||
| 38 | + sys.path.insert(0, _TESTS_ROOT) | ||
| 39 | + | ||
| 40 | +import torch # noqa: E402 | ||
| 41 | +import torch_npu # noqa: E402, F401 -- registers the npu backend | ||
| 42 | + | ||
| 43 | +import pypto # noqa: E402 | ||
| 44 | +from st.bundle.bundle_abi import BundleClient, make_desc_array # noqa: E402 | ||
| 45 | +from st.operator.test_page_attention import ( # noqa: E402 | ||
| 46 | + TileConfig, | ||
| 47 | + op_page_attention, | ||
| 48 | + op_page_attention_golden, | ||
| 49 | +) | ||
| 50 | +from st.pypto_test import TestBuilder # noqa: E402 | ||
| 51 | +from st.test_cellmatch_case import B_STATIC, D_STATIC, H_STATIC, k_tmp_to_d_emb # noqa: E402 | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +# --------------------------------------------------------------------------------------------------- | ||
| 55 | +# shared helpers | ||
| 56 | +# --------------------------------------------------------------------------------------------------- | ||
| 57 | +def _device(): | ||
| 58 | + dev_id = int(os.environ.get("TILE_FWK_DEVICE_ID", "0")) | ||
| 59 | + torch.npu.set_device(dev_id) | ||
| 60 | + return dev_id, f"npu:{dev_id}" | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +def _alloc_workspace(size: int, device: str): | ||
| 64 | + """Allocate the caller-owned workspace. Returns (keepalive_tensor, void_ptr); (None, None) when 0.""" | ||
| 65 | + if size == 0: | ||
| 66 | + return None, None | ||
| 67 | + buf = torch.empty(size, dtype=torch.uint8, device=device) | ||
| 68 | + return buf, ctypes.c_void_p(buf.data_ptr()) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _max_diff(actual: torch.Tensor, golden: torch.Tensor) -> float: | ||
| 72 | + return (actual.detach().cpu().float() - golden.detach().cpu().float()).abs().max().item() | ||
| 73 | + | ||
| 74 | + | ||
| 75 | +def _check(label: str, actual: torch.Tensor, golden: torch.Tensor, tol: float): | ||
| 76 | + diff = _max_diff(actual, golden) | ||
| 77 | + print(f"[ST] {label}: max diff = {diff:.6f} (tol {tol})") | ||
| 78 | + assert diff < tol, f"{label}: output mismatch, max_diff={diff} >= {tol}" | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +# --------------------------------------------------------------------------------------------------- | ||
| 82 | +# case: static_add -- non-value-dependent, static, zero workspace | ||
| 83 | +# --------------------------------------------------------------------------------------------------- | ||
| 84 | +ADD_SHAPE = (1, 4, 1, 64) | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +def _make_add_kernel(): | ||
| 88 | + @pypto.frontend.jit(runtime_options={"run_mode": pypto.RunMode.NPU}) | ||
| 89 | + def add_kernel( | ||
| 90 | + x: pypto.Tensor([...], pypto.DT_FP32), | ||
| 91 | + y: pypto.Tensor([...], pypto.DT_FP32), | ||
| 92 | + out: pypto.Tensor([...], pypto.DT_FP32), | ||
| 93 | + ): | ||
| 94 | + pypto.set_vec_tile_shapes(1, 4, 1, 64) | ||
| 95 | + out[:] = x + y | ||
| 96 | + | ||
| 97 | + return add_kernel | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def _add_inputs(device: str): | ||
| 101 | + torch.manual_seed(7) | ||
| 102 | + x = torch.rand(ADD_SHAPE, dtype=torch.float32, device=device) | ||
| 103 | + y = torch.rand(ADD_SHAPE, dtype=torch.float32, device=device) | ||
| 104 | + out = torch.zeros(ADD_SHAPE, dtype=torch.float32, device=device) | ||
| 105 | + return x, y, out | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def pack_static_add(): | ||
| 109 | + _, device = _device() | ||
| 110 | + x, y, out = _add_inputs(device) | ||
| 111 | + _make_add_kernel()(x, y, out) | ||
| 112 | + torch.npu.synchronize() | ||
| 113 | + _check("pack-run add", out, x + y, 3e-3) | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +def consume_static_add(bundle_path: str, api: str): | ||
| 117 | + _, device = _device() | ||
| 118 | + client = BundleClient(bundle_path, api) | ||
| 119 | + x, y, out = _add_inputs(device) | ||
| 120 | + | ||
| 121 | + # Unified operand list: outputs are folded into the input list, addressed by position. | ||
| 122 | + descs = make_desc_array([x, y, out]) | ||
| 123 | + | ||
| 124 | + # 1) workspace query -- pure host, must not touch the device. | ||
| 125 | + ws_size = client.workspace(descs) | ||
| 126 | + print(f"[ST] workspace size = {ws_size}") | ||
| 127 | + assert ws_size == 0, f"static add should need no workspace, got {ws_size}" | ||
| 128 | + | ||
| 129 | + # 2) launch. | ||
| 130 | + ws_keep, ws_ptr = _alloc_workspace(ws_size, device) | ||
| 131 | + rc = client.launch(descs, ws_ptr, None, 1) | ||
| 132 | + assert rc == 0, f"PyptoLaunch rc={rc}" | ||
| 133 | + torch.npu.synchronize() | ||
| 134 | + del ws_keep | ||
| 135 | + | ||
| 136 | + _check(f"add ({api} API)", out, x + y, 3e-3) | ||
| 137 | + | ||
| 138 | + | ||
| 139 | +# --------------------------------------------------------------------------------------------------- | ||
| 140 | +# case: dyn_cellmatch -- non-value-dependent, dynamic shapes + dynamic cell-match workspace | ||
| 141 | +# --------------------------------------------------------------------------------------------------- | ||
| 142 | +# Reuses the kernel and the shape constants from the dynamic cell-match ST so the two cannot drift apart. | ||
| 143 | +CM_PACK_L = 125 | ||
| 144 | +# Host-only workspace probes. The v1 CtrlFlowCache is a single static-shape snapshot, so only the packed | ||
| 145 | +# shape may actually be launched -- see the note in test_kernel_bundle.py. | ||
| 146 | +CM_PROBE_LENGTHS = [64, 125, 2000] | ||
| 147 | + | ||
| 148 | + | ||
| 149 | +def _cm_inputs(seq_len: int, device: str): | ||
| 150 | + torch.manual_seed(44 + seq_len) | ||
| 151 | + dy = torch.randn(B_STATIC, seq_len, H_STATIC, D_STATIC, dtype=torch.float32, device=device) | ||
| 152 | + weight = torch.randn(H_STATIC, D_STATIC, D_STATIC, dtype=torch.float32, device=device) | ||
| 153 | + d_emb = torch.zeros(B_STATIC, seq_len, D_STATIC, dtype=torch.float32, device=device) | ||
| 154 | + return dy, weight, d_emb | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +def _cm_golden(dy: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: | ||
| 158 | + return (dy[:, :, 0, :].reshape(-1, dy.shape[-1]) @ weight[0].T).reshape(dy.shape[0], dy.shape[1], dy.shape[-1]) | ||
| 159 | + | ||
| 160 | + | ||
| 161 | +def pack_dyn_cellmatch(): | ||
| 162 | + _, device = _device() | ||
| 163 | + dy, weight, d_emb = _cm_inputs(CM_PACK_L, device) | ||
| 164 | + k_tmp_to_d_emb(dy, weight, d_emb) | ||
| 165 | + torch.npu.synchronize() | ||
| 166 | + _check(f"pack-run cellmatch L={CM_PACK_L}", d_emb, _cm_golden(dy, weight), 1e-3) | ||
| 167 | + | ||
| 168 | + | ||
| 169 | +def consume_dyn_cellmatch(bundle_path: str, api: str): | ||
| 170 | + _, device = _device() | ||
| 171 | + client = BundleClient(bundle_path, api) | ||
| 172 | + | ||
| 173 | + # 1) Dynamic workspace evaluation: the same bundle, queried at several shapes. This exercises the | ||
| 174 | + # SymbolMeta symbolic trees (RUNTIME_GetInputShapeDim over ARG_dy) and the dynamic cell-match | ||
| 175 | + # stride re-patching. A bundle with a baked constant would return the same number every time. | ||
| 176 | + sizes = [] | ||
| 177 | + for seq_len in CM_PROBE_LENGTHS: | ||
| 178 | + dy, weight, d_emb = _cm_inputs(seq_len, device) | ||
| 179 | + ws = client.workspace(make_desc_array([dy, weight, d_emb])) | ||
| 180 | + print(f"[ST] workspace(L={seq_len}) = {ws}") | ||
| 181 | + sizes.append(ws) | ||
| 182 | + del dy, weight, d_emb | ||
| 183 | + assert all(s > 0 for s in sizes), f"dynamic workspace must be non-zero, got {sizes}" | ||
| 184 | + assert sizes == sorted(sizes) and len(set(sizes)) == len(sizes), ( | ||
| 185 | + f"workspace must grow strictly with the sequence length, got " | ||
| 186 | + f"{dict(zip(CM_PROBE_LENGTHS, sizes))} -- symbol evaluation likely fell back to a baked constant" | ||
| 187 | + ) | ||
| 188 | + | ||
| 189 | + # 2) Launch at the packed shape and check the numerics end to end. | ||
| 190 | + dy, weight, d_emb = _cm_inputs(CM_PACK_L, device) | ||
| 191 | + descs = make_desc_array([dy, weight, d_emb]) | ||
| 192 | + ws_size = client.workspace(descs) | ||
| 193 | + ws_keep, ws_ptr = _alloc_workspace(ws_size, device) | ||
| 194 | + assert ws_size > 0, "expected a non-zero workspace at the packed shape" | ||
| 195 | + rc = client.launch(descs, ws_ptr, None, 1) | ||
| 196 | + assert rc == 0, f"PyptoLaunch rc={rc}" | ||
| 197 | + torch.npu.synchronize() | ||
| 198 | + del ws_keep | ||
| 199 | + | ||
| 200 | + _check(f"cellmatch L={CM_PACK_L} ({api} API)", d_emb, _cm_golden(dy, weight), 1e-3) | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +# --------------------------------------------------------------------------------------------------- | ||
| 204 | +# case: value_depend_pa -- value-dependent control flow (page attention) | ||
| 205 | +# --------------------------------------------------------------------------------------------------- | ||
| 206 | +# Loop trip counts come from act_seqs tensor VALUES (`cur_seq = act_seqs[b_idx]` -> GetTensorData -> | ||
| 207 | +# bn_per_batch), which sets devProg->disableCtrlFlowCache. Every shape below is held constant across the | ||
| 208 | +# two value sets -- the cache size is pinned by PA_MAX_BLOCKS, not by max(act_seqs) -- so the only thing | ||
| 209 | +# that differs between the two consume launches is the tensor CONTENT. | ||
| 210 | +PA_BLOCK_SIZE = 128 | ||
| 211 | +PA_MAX_BLOCKS = 4 # blocks reserved per batch; pins block_table / kv-cache shapes | ||
| 212 | +PA_BATCH = 4 | ||
| 213 | +PA_N_TILE = 32 | ||
| 214 | + | ||
| 215 | +PA_ACT_SEQS_PACKED = [512, 512, 512, 512] # bn_per_batch = [4, 4, 4, 4] | ||
| 216 | +PA_ACT_SEQS_ALT = [128, 512, 256, 384] # bn_per_batch = [1, 4, 2, 3] -- same shapes, different values | ||
| 217 | + | ||
| 218 | +PA_TOL = 5e-4 | ||
| 219 | + | ||
| 220 | + | ||
| 221 | +def _pa_params(): | ||
| 222 | + return { | ||
| 223 | + "block_size": PA_BLOCK_SIZE, | ||
| 224 | + "tile_config": TileConfig( | ||
| 225 | + head_num_q_tile=PA_N_TILE, | ||
| 226 | + c1_tile_shape=(32, 32, 64, 64, 128, 128), | ||
| 227 | + v1_tile_shape=(32, 64), | ||
| 228 | + c2_tile_shape=(32, 32, 64, 64, 128, 128), | ||
| 229 | + v2_tile_shape=(32, 64), | ||
| 230 | + ), | ||
| 231 | + "max_unroll_times": 1, | ||
| 232 | + "is_nz_format": False, | ||
| 233 | + "b": PA_BATCH, | ||
| 234 | + "n_q": 32, | ||
| 235 | + "block_num": PA_BATCH * PA_MAX_BLOCKS, | ||
| 236 | + "dtype": torch.float32, | ||
| 237 | + "s_q": 1, | ||
| 238 | + "n_kv": 1, | ||
| 239 | + "kv_lora_rank": 512, | ||
| 240 | + "qk_rope_dim": 64, | ||
| 241 | + "n_tile": PA_N_TILE, | ||
| 242 | + } | ||
| 243 | + | ||
| 244 | + | ||
| 245 | +def _pa_make_inputs(params, act_seqs, device: str, seed: int = 11): | ||
| 246 | + """Build the 7-operand input list on CPU or device. Shapes depend only on params, never on act_seqs.""" | ||
| 247 | + b = params["b"] | ||
| 248 | + n_q = params["n_q"] | ||
| 249 | + s_q = params["s_q"] | ||
| 250 | + n_kv = params["n_kv"] | ||
| 251 | + kv_lora_rank = params["kv_lora_rank"] | ||
| 252 | + qk_rope_dim = params["qk_rope_dim"] | ||
| 253 | + block_size = params["block_size"] | ||
| 254 | + block_num = params["block_num"] | ||
| 255 | + dtype = params["dtype"] | ||
| 256 | + d_q = kv_lora_rank + qk_rope_dim | ||
| 257 | + | ||
| 258 | + max_seq = max(act_seqs) | ||
| 259 | + assert max_seq <= PA_MAX_BLOCKS * block_size, ( | ||
| 260 | + f"act_seqs {act_seqs} exceeds the {PA_MAX_BLOCKS * block_size}-token reservation") | ||
| 261 | + | ||
| 262 | + torch.manual_seed(seed) | ||
| 263 | + q_bnsd = (torch.rand([b * n_q * s_q, d_q], dtype=dtype) * 2 - 1).to(device) | ||
| 264 | + k_cache = (torch.rand([block_num, block_size, n_kv * d_q], dtype=dtype) * 2 - 1).to(device) | ||
| 265 | + v_cache = (torch.rand([block_num, block_size, n_kv * kv_lora_rank], dtype=dtype) * 2 - 1).to(device) | ||
| 266 | + | ||
| 267 | + # Identity block mapping: batch bi owns physical blocks [bi*PA_MAX_BLOCKS, (bi+1)*PA_MAX_BLOCKS). | ||
| 268 | + block_table = torch.arange(0, block_num, dtype=torch.int32).reshape(b, PA_MAX_BLOCKS).to(device) | ||
| 269 | + act = torch.tensor(act_seqs, dtype=torch.int32).to(device) | ||
| 270 | + | ||
| 271 | + nope_h = n_kv * kv_lora_rank | ||
| 272 | + q_nope = q_bnsd[:, :kv_lora_rank].contiguous() | ||
| 273 | + q_rope = q_bnsd[:, kv_lora_rank:].contiguous() | ||
| 274 | + k_cache_nope = k_cache[:, :, :nope_h].reshape(block_num * block_size, nope_h).contiguous() | ||
| 275 | + k_cache_rope = k_cache[:, :, nope_h:].reshape(block_num * block_size, n_kv * qk_rope_dim).contiguous() | ||
| 276 | + v_cache_2d = v_cache.reshape(block_num * block_size, nope_h).contiguous() | ||
| 277 | + return [q_nope, k_cache_nope, v_cache_2d, q_rope, k_cache_rope, block_table, act] | ||
| 278 | + | ||
| 279 | + | ||
| 280 | +def _pa_golden(params, inputs): | ||
| 281 | + cpu_inputs = [t.cpu() for t in inputs] | ||
| 282 | + out, = op_page_attention_golden(params, *cpu_inputs, None) | ||
| 283 | + return out | ||
| 284 | + | ||
| 285 | + | ||
| 286 | +def pack_value_depend_pa(): | ||
| 287 | + class _PABundlePack(TestBuilder): | ||
| 288 | + def get_input_from_param(self): | ||
| 289 | + # TestBuilder feeds the host-side run-once path, which wants CPU tensors. | ||
| 290 | + inputs = _pa_make_inputs(self.params, self.params["act_seqs"], "cpu") | ||
| 291 | + self.setup_inputs(*inputs) | ||
| 292 | + self.set_tol(rtol=PA_TOL, atol=PA_TOL) | ||
| 293 | + # Mirrors PATest: the golden's trailing attention_out slot is unused, params rides along. | ||
| 294 | + return inputs + [self.params] | ||
| 295 | + | ||
| 296 | + params = _pa_params() | ||
| 297 | + params["act_seqs"] = PA_ACT_SEQS_PACKED | ||
| 298 | + _PABundlePack(params, op_page_attention, op_page_attention_golden, tiling=PA_N_TILE)() | ||
| 299 | + | ||
| 300 | + | ||
| 301 | +def consume_value_depend_pa(bundle_path: str, api: str): | ||
| 302 | + _, device = _device() | ||
| 303 | + client = BundleClient(bundle_path, api) | ||
| 304 | + params = _pa_params() | ||
| 305 | + | ||
| 306 | + # Both launches reuse the one loaded bundle. Identical shapes, different act_seqs VALUES: if the device | ||
| 307 | + # were replaying a host-baked control-flow cache instead of resolving trip counts from the tensor, the | ||
| 308 | + # second case would read the wrong number of KV blocks and miss the golden. | ||
| 309 | + goldens = {} | ||
| 310 | + for label, act_seqs in (("packed", PA_ACT_SEQS_PACKED), ("alt", PA_ACT_SEQS_ALT)): | ||
| 311 | + inputs = _pa_make_inputs(params, act_seqs, device) | ||
| 312 | + out = torch.zeros( | ||
| 313 | + params["b"] * params["n_q"] * params["s_q"], params["kv_lora_rank"], | ||
| 314 | + dtype=params["dtype"], device=device) | ||
| 315 | + descs = make_desc_array(inputs + [out]) | ||
| 316 | + | ||
| 317 | + ws_size = client.workspace(descs) | ||
| 318 | + print(f"[ST] {label} act_seqs={act_seqs}: workspace = {ws_size}") | ||
| 319 | + ws_keep, ws_ptr = _alloc_workspace(ws_size, device) | ||
| 320 | + rc = client.launch(descs, ws_ptr, None, 1) | ||
| 321 | + assert rc == 0, f"{label}: PyptoLaunch rc={rc}" | ||
| 322 | + torch.npu.synchronize() | ||
| 323 | + del ws_keep | ||
| 324 | + | ||
| 325 | + golden = _pa_golden(params, inputs) | ||
| 326 | + goldens[label] = golden | ||
| 327 | + _check(f"page-attention {label} ({api} API)", out.reshape(golden.shape), golden, PA_TOL) | ||
| 328 | + | ||
| 329 | + # Guard the guard: the two value sets share a seed, so they differ only through act_seqs. If they no | ||
| 330 | + # longer drive the output apart, the pair of launches above would pass even on a device that ignored | ||
| 331 | + # the tensor values entirely, and this case would stop testing value dependency at all. | ||
| 332 | + spread = _max_diff(goldens["packed"], goldens["alt"]) | ||
| 333 | + print(f"[ST] golden spread between the two act_seqs value sets = {spread:.6f}") | ||
| 334 | + assert spread > PA_TOL * 10, ( | ||
| 335 | + f"act_seqs {PA_ACT_SEQS_PACKED} vs {PA_ACT_SEQS_ALT} barely move the result (spread={spread}); " | ||
| 336 | + f"pick value sets whose per-batch block counts differ more" | ||
| 337 | + ) | ||
| 338 | + | ||
| 339 | + | ||
| 340 | +# --------------------------------------------------------------------------------------------------- | ||
| 341 | +# registry + CLI | ||
| 342 | +# --------------------------------------------------------------------------------------------------- | ||
| 343 | +CASES = { | ||
| 344 | + "static_add": (pack_static_add, consume_static_add), | ||
| 345 | + "dyn_cellmatch": (pack_dyn_cellmatch, consume_dyn_cellmatch), | ||
| 346 | + "value_depend_pa": (pack_value_depend_pa, consume_value_depend_pa), | ||
| 347 | +} | ||
| 348 | + | ||
| 349 | + | ||
| 350 | +def main(): | ||
| 351 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 352 | + parser.add_argument("phase", choices=["pack", "consume"]) | ||
| 353 | + parser.add_argument("case", choices=sorted(CASES)) | ||
| 354 | + parser.add_argument("bundle_path") | ||
| 355 | + parser.add_argument("--api", choices=["path", "memory"], default="path") | ||
| 356 | + args = parser.parse_args() | ||
| 357 | + | ||
| 358 | + pack_fn, consume_fn = CASES[args.case] | ||
| 359 | + if args.phase == "pack": | ||
| 360 | + # Packing is gated by these two env vars; the driver sets them, assert rather than silently no-op. | ||
| 361 | + assert os.environ.get("PYPTO_ENABLE_KERNEL_BUNDLE") == "1", "PYPTO_ENABLE_KERNEL_BUNDLE must be 1" | ||
| 362 | + assert os.environ.get("PYPTO_KERNEL_BUNDLE_PATH") == args.bundle_path, \ | ||
| 363 | + "PYPTO_KERNEL_BUNDLE_PATH must match the requested bundle path" | ||
| 364 | + pack_fn() | ||
| 365 | + assert os.path.exists(args.bundle_path), f"no bundle produced at {args.bundle_path}" | ||
| 366 | + print(f"[ST] packed {args.case} -> {args.bundle_path} ({os.path.getsize(args.bundle_path)} B)") | ||
| 367 | + else: | ||
| 368 | + consume_fn(args.bundle_path, args.api) | ||
| 369 | + print(f"[ST] consumed {args.case} via the {args.api} API") | ||
| 370 | + | ||
| 371 | + | ||
| 372 | +if __name__ == "__main__": | ||
| 373 | + main() | ||
| 374 | + # The runtime singletons (DeviceRunner/DevicePerf) are torn down at interpreter exit, AFTER torch_npu has | ||
| 375 | + # already dropped the NPU context -- that races into a double free in ~DevicePerf. Everything under test | ||
| 376 | + # has been asserted by this point, so flush and exit hard rather than run the static destructors. | ||
| 377 | + sys.stdout.flush() | ||
| 378 | + sys.stderr.flush() | ||
| 379 | + os._exit(0) | ||
| @@ -0,0 +1,165 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Delivery smoke test for the SELF-CONTAINED kernel-bundle library (libtile_fwk_bundle_standalone.so). | ||
| 12 | + | ||
| 13 | +Stands in for a downstream that only consumes .pyptokb files: it loads ONE .so by absolute path, next to ONE | ||
| 14 | +.pyptokb, and proves nothing else from the pypto install tree is needed. | ||
| 15 | + | ||
| 16 | + python3 standalone_delivery_smoke.py <standalone.so> <bundle.pyptokb> | ||
| 17 | + | ||
| 18 | +Driven by ``test_kernel_bundle.py::test_bundle_standalone_delivery``, which assembles the delivery directory | ||
| 19 | +first; runnable by hand too (see bundle/E2E_MANUAL.md section 5). | ||
| 20 | + | ||
| 21 | +TWO RULES THIS FILE MUST KEEP -- both are constraints, not style: | ||
| 22 | + | ||
| 23 | +1. **Never import pypto, and never reuse st/bundle/bundle_abi.py.** The standalone library statically absorbs | ||
| 24 | + the whole pypto closure, so loading it into a process that also holds the regular pypto stack gives every | ||
| 25 | + Meyers singleton on that closure (Platform::Instance, DeviceRunner::Get, ConfigManager::Instance, | ||
| 26 | + OpInfoManager, plus the bundle's own registry and dev-cache) two independent copies -- silent state | ||
| 27 | + divergence, not a crash. See bundle/CMakeLists.txt and BUNDLE_FLOW.md section 7.2. That is why the | ||
| 28 | + PyptoTensorDesc / ABI boilerplate below is duplicated from bundle_abi.py rather than imported: bundle_abi | ||
| 29 | + resolves the DataType enum through ``import pypto``. Do not DRY these two together. | ||
| 30 | + | ||
| 31 | +2. **The .so needs a configs/ directory beside it.** GetPyptoLibPath() (utils/file_utils.cpp) uses dladdr to | ||
| 32 | + find the directory of its OWN .so, and ConfigManager plus the platform ini parsing read configs/ relative | ||
| 33 | + to it. Missing it reports ErrCode F29002 / FeError::INVALID_FILE. This is a data-file dependency; static | ||
| 34 | + linking cannot absorb it. | ||
| 35 | +""" | ||
| 36 | +import ctypes | ||
| 37 | +import os | ||
| 38 | +import sys | ||
| 39 | + | ||
| 40 | +import torch | ||
| 41 | +import torch_npu # noqa: F401 -- registers the npu backend | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +class PyptoTensorDesc(ctypes.Structure): | ||
| 45 | + """pypto_bundle_api.h PyptoTensorDesc. Duplicated on purpose -- see rule 1 in the module docstring.""" | ||
| 46 | + | ||
| 47 | + _fields_ = [ | ||
| 48 | + ("addr", ctypes.c_void_p), | ||
| 49 | + ("dataType", ctypes.c_int32), | ||
| 50 | + ("rank", ctypes.c_int32), | ||
| 51 | + ("shape", ctypes.c_int64 * 8), | ||
| 52 | + ] | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +# DataType enum index for DT_FP32, i.e. the position of DT_FP32 in DATA_TYPE_ALL (tilefwk/data_type.h): | ||
| 56 | +# DT_INT4=0 INT8=1 INT16=2 INT32=3 INT64=4 FP8=5 FP16=6 FP32=7 BF16=8 ... | ||
| 57 | +# Hard-coded because rule 1 forbids importing pypto to resolve it; overridable if the enum is ever reordered. | ||
| 58 | +# Today the device compute path reads only address/shape from DevTensorData, but the exception dump and the | ||
| 59 | +# profiling path do read dataType (device_exception_dump.cpp, aicore_dump.h, host_prof.cpp) and size tensors | ||
| 60 | +# with BitsOf(dataType)/8 -- a wrong value there silently corrupts the dump rather than the result. | ||
| 61 | +DT_FP32 = int(os.environ.get("PYPTO_ST_DT_FP32", "7")) | ||
| 62 | + | ||
| 63 | +# The op the reference bundle was packed with: examples/00_hello_world style elementwise add. | ||
| 64 | +ADD_SHAPE = (1, 4, 1, 64) | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +def make_desc(tensor, dtype_val: int) -> PyptoTensorDesc: | ||
| 68 | + desc = PyptoTensorDesc() | ||
| 69 | + desc.addr = ctypes.c_void_p(tensor.data_ptr()) | ||
| 70 | + desc.dataType = dtype_val | ||
| 71 | + desc.rank = tensor.dim() | ||
| 72 | + for i in range(tensor.dim()): | ||
| 73 | + desc.shape[i] = tensor.shape[i] | ||
| 74 | + return desc | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def _exit(code: int): | ||
| 78 | + # os._exit skips the static destructors (device teardown races torch_npu), but it also skips flushing | ||
| 79 | + # stdout, which is block-buffered whenever output is redirected. Flush explicitly or the log is lost. | ||
| 80 | + sys.stdout.flush() | ||
| 81 | + sys.stderr.flush() | ||
| 82 | + os._exit(code) | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def assert_self_contained(so_path): | ||
| 86 | + """Fail if any pypto shared object got mapped: that would mean the .so was not actually self-contained. | ||
| 87 | + | ||
| 88 | + This is the property the whole flavour exists for, and it is invisible in the numeric result -- a build | ||
| 89 | + that regressed to pulling in libtile_fwk_runtime.so would still compute the right answer here. | ||
| 90 | + | ||
| 91 | + The library under test is excluded by name: it is itself called libtile_fwk_bundle_standalone.so, so it | ||
| 92 | + matches the very prefix this check scans for. Everything else starting with those prefixes is a leak. | ||
| 93 | + """ | ||
| 94 | + with open("/proc/self/maps", "r") as f: | ||
| 95 | + mapped = f.read() | ||
| 96 | + under_test = os.path.basename(so_path) | ||
| 97 | + leaked = sorted({ | ||
| 98 | + os.path.basename(line.split()[-1]) | ||
| 99 | + for line in mapped.splitlines() | ||
| 100 | + if line.split() | ||
| 101 | + and os.path.basename(line.split()[-1]).startswith(("libtile_fwk", "libpypto_ctrl")) | ||
| 102 | + and os.path.basename(line.split()[-1]) != under_test | ||
| 103 | + }) | ||
| 104 | + if leaked: | ||
| 105 | + print(f"[ST] FAILED: pypto libraries pulled into the process: {leaked}") | ||
| 106 | + _exit(1) | ||
| 107 | + print("[ST] self-containment: no pypto shared objects mapped besides the library under test") | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +def main(): | ||
| 111 | + if len(sys.argv) < 3: | ||
| 112 | + print(f"usage: {os.path.basename(sys.argv[0])} <standalone.so> <bundle.pyptokb>") | ||
| 113 | + _exit(2) | ||
| 114 | + so_path, bundle_path = sys.argv[1], sys.argv[2] | ||
| 115 | + dev_id = int(os.environ.get("TILE_FWK_DEVICE_ID", "0")) | ||
| 116 | + torch.npu.set_device(dev_id) | ||
| 117 | + | ||
| 118 | + configs_dir = os.path.join(os.path.dirname(os.path.abspath(so_path)), "configs") | ||
| 119 | + if not os.path.isdir(configs_dir): | ||
| 120 | + print(f"[ST] FAILED: no configs/ beside {so_path} -- see rule 2 in this file's docstring") | ||
| 121 | + _exit(1) | ||
| 122 | + | ||
| 123 | + lib = ctypes.CDLL(so_path, mode=ctypes.RTLD_GLOBAL) | ||
| 124 | + lib.PyptoWorkspace.restype = ctypes.c_uint64 | ||
| 125 | + lib.PyptoWorkspace.argtypes = [ctypes.c_char_p, ctypes.POINTER(PyptoTensorDesc), ctypes.c_uint32] | ||
| 126 | + lib.PyptoLaunch.restype = ctypes.c_int | ||
| 127 | + lib.PyptoLaunch.argtypes = [ | ||
| 128 | + ctypes.c_char_p, ctypes.POINTER(PyptoTensorDesc), ctypes.c_uint32, | ||
| 129 | + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, | ||
| 130 | + ] | ||
| 131 | + print(f"[ST] loaded {so_path}") | ||
| 132 | + assert_self_contained(so_path) | ||
| 133 | + | ||
| 134 | + x = torch.rand(ADD_SHAPE, dtype=torch.float32, device=f"npu:{dev_id}") | ||
| 135 | + y = torch.rand(ADD_SHAPE, dtype=torch.float32, device=f"npu:{dev_id}") | ||
| 136 | + out = torch.empty(ADD_SHAPE, dtype=torch.float32, device=f"npu:{dev_id}") | ||
| 137 | + tensors = (PyptoTensorDesc * 3)(make_desc(x, DT_FP32), make_desc(y, DT_FP32), make_desc(out, DT_FP32)) | ||
| 138 | + | ||
| 139 | + path_c = bundle_path.encode() | ||
| 140 | + ws_size = lib.PyptoWorkspace(path_c, tensors, 3) | ||
| 141 | + print(f"[ST] workspace size = {ws_size}") | ||
| 142 | + ws_keep = None | ||
| 143 | + ws_ptr = None | ||
| 144 | + if ws_size > 0: | ||
| 145 | + ws_keep = torch.empty(ws_size, dtype=torch.uint8, device=f"npu:{dev_id}") | ||
| 146 | + ws_ptr = ctypes.c_void_p(ws_keep.data_ptr()) | ||
| 147 | + | ||
| 148 | + rc = lib.PyptoLaunch(path_c, tensors, 3, ws_ptr, None, 1) | ||
| 149 | + if rc != 0: | ||
| 150 | + print(f"[ST] FAILED: PyptoLaunch rc={rc}") | ||
| 151 | + _exit(1) | ||
| 152 | + torch.npu.synchronize() | ||
| 153 | + del ws_keep | ||
| 154 | + | ||
| 155 | + diff = (out - (x + y)).abs().max().item() | ||
| 156 | + print(f"[ST] max diff = {diff:.6f}") | ||
| 157 | + if diff > 1e-5: | ||
| 158 | + print("[ST] FAILED: numeric mismatch") | ||
| 159 | + _exit(1) | ||
| 160 | + print("✓ self-contained kernel-bundle delivery ST passed (one .so + one .pyptokb, no pypto install)") | ||
| 161 | + _exit(0) | ||
| 162 | + | ||
| 163 | + | ||
| 164 | +if __name__ == "__main__": | ||
| 165 | + main() | ||


🟠 High Priority
changed line:
kernel_bundle_crc32.h第 23-38 行的Crc32Table()函数。affected behavior: 函数使用手动的
static bool inited标志 +static uint32_t table[256]实现惰性初始化,但该"双重检查"模式在 C++11 及之后的标准中不是线程安全的——多线程并发首次调用Crc32()时,一个线程可能正在写table,另一个线程同时通过!inited检查并开始读table,构成 data race(未定义行为)。failure mode: 当
Crc32()被多线程并发调用时(例如多个 Python 线程同时触发 bundle 加载),未定义行为可能导致读取到部分初始化的 CRC 表、产生错误的 CRC 值,从而导致合法的 bundle 被拒绝或非法 bundle 被接受。suggested fix: 将
Crc32Table()改为利用 C++11 保证线程安全的静态局部变量初始化机制:使用一个立即调用的 lambda 初始化static const表,或使用std::call_once+std::once_flag。建议:使用 C++11 保证线程安全的静态局部变量初始化,让编译器处理同步:将查表逻辑放入一个立即调用的 lambda 中,其结果用于初始化
static const表。