Merged
fix(codegen): Propagate parallel task exceptions instead of swallowing them #5266
anyangleAdd on Aug 4
fix(codegen): Propagate parallel task exceptions instead of swallowing them #5266
Merged
Merged fromquadrate/pypto_aylcompile_fixintocann/pyptomaster
Total: 17 files changed+490-151
| @@ -30,7 +30,7 @@ set_debug_options(*, | |||
| 30 | 30 | ||
| 31 | | 参数名 | 输入/输出 | 说明 | | 31 | | 参数名 | 输入/输出 | 说明 | |
| 32 | |----------------------|-----------|----------------------------------------------------------------------| | 32 | |----------------------|-----------|----------------------------------------------------------------------| |
| 33 | -| compile_debug_mode | 输入 | 含义:设置编译阶段调试模式 <br> 说明:0:代表默认不使能编译阶段调试模式; <br> 1:代表图使能编译阶段调试模式,一键开启图编译相关配置,当前仅包括计算图; <br> 2:代表使能固定CCE功能,一键开启固定设备侧代码输出路径、不覆盖已存在的CCE文件、单线程编译; <br> 类型:int <br> 取值范围:0、1 或 2 <br> 默认值:0 <br> 影响Pass范围:NA | | 33 | +| compile_debug_mode | 输入 | 含义:设置编译阶段调试模式 <br> 说明:0:代表默认不使能编译阶段调试模式; <br> 1:代表图使能编译阶段调试模式,一键开启图编译相关配置,当前仅包括计算图; <br> 2:代表使能固定CCE功能,一键开启固定设备侧代码输出路径、不覆盖已存在的CCE文件;并行编译线程数仍由 `codegen.parallel_compile` 控制,kernel 名按任务身份确定性编号,多线程编译产物可复现; <br> 类型:int <br> 取值范围:0、1 或 2 <br> 默认值:0 <br> 影响Pass范围:NA | |
| 34 | | runtime_debug_mode | 输入 | 含义:设置执行阶段调试模式 <br> 说明:0:代表默认不使能执行阶段调试模式; <br> 1:代表使能执行阶段调试模式,一键开启图执行相关配置,当前仅包括泳道图; <br> 2:代表使能 AICORE_MODEL 仿真模式; <br> 3:代表使能运行时依赖正确性校验数据 dump; <br> 4:代表使能运行时 GM 内存越界检查; <br> 类型:int <br> 取值范围:0、1、2、3 或 4 <br> 默认值:0 <br> 影响Pass范围:NA | | 34 | | runtime_debug_mode | 输入 | 含义:设置执行阶段调试模式 <br> 说明:0:代表默认不使能执行阶段调试模式; <br> 1:代表使能执行阶段调试模式,一键开启图执行相关配置,当前仅包括泳道图; <br> 2:代表使能 AICORE_MODEL 仿真模式; <br> 3:代表使能运行时依赖正确性校验数据 dump; <br> 4:代表使能运行时 GM 内存越界检查; <br> 类型:int <br> 取值范围:0、1、2、3 或 4 <br> 默认值:0 <br> 影响Pass范围:NA | |
| 35 | | dump_pass_graph | 输入 | 含义:指定一个或多个Pass开启计算图dump和IR打印 <br> 说明:空列表表示不启用;配置为Pass标识符列表时,仅对匹配Pass开启计算图dump和IR打印,其它Pass不输出计算图和IR。若配置了不存在的Pass标识符,该标识符不会命中任何Pass,并输出告警。 <br> 类型:List[str] <br> 默认值:[] <br> 影响Pass范围:指定Pass | | 35 | | dump_pass_graph | 输入 | 含义:指定一个或多个Pass开启计算图dump和IR打印 <br> 说明:空列表表示不启用;配置为Pass标识符列表时,仅对匹配Pass开启计算图dump和IR打印,其它Pass不输出计算图和IR。若配置了不存在的Pass标识符,该标识符不会命中任何Pass,并输出告警。 <br> 类型:List[str] <br> 默认值:[] <br> 影响Pass范围:指定Pass | |
| 36 | 36 | ||
| @@ -41,6 +41,7 @@ void:Set方法无返回值。设置操作成功即生效。 | |||
| 41 | ## 约束说明 | 41 | ## 约束说明 |
| 42 | 42 | ||
| 43 | - 当 compile_debug_mode=2(固定CCE)时,设备侧代码输出路径由环境变量 ASCEND_WORK_PATH 决定(`$ASCEND_WORK_PATH/pypto/<name>`);若未设置 ASCEND_WORK_PATH,则输出到当前工作目录。此模式下 TILE_FWK_OUTPUT_DIR 不参与设备侧代码路径计算。 | 43 | - 当 compile_debug_mode=2(固定CCE)时,设备侧代码输出路径由环境变量 ASCEND_WORK_PATH 决定(`$ASCEND_WORK_PATH/pypto/<name>`);若未设置 ASCEND_WORK_PATH,则输出到当前工作目录。此模式下 TILE_FWK_OUTPUT_DIR 不参与设备侧代码路径计算。 |
| 44 | +- compile_debug_mode=2 等效于同时开启 `codegen.fixed_output_path` 并关闭 `codegen.force_overwrite`;已存在的 CCE 文件不会被覆盖,便于在固定路径下反复修改 CCE 调试。 | ||
| 44 | - dump_pass_graph 配置项填写的是当前Pass策略中的Pass标识符(identifier),例如"RemoveRedundantReshape",不是C++中的PassName枚举值。 | 45 | - dump_pass_graph 配置项填写的是当前Pass策略中的Pass标识符(identifier),例如"RemoveRedundantReshape",不是C++中的PassName枚举值。 |
| 45 | - dump_pass_graph 支持配置多个Pass标识符;列表中未匹配当前Pass策略的标识符会被忽略,并输出告警。若列表中所有标识符均未匹配,则不会输出任何Pass的计算图或IR。 | 46 | - dump_pass_graph 支持配置多个Pass标识符;列表中未匹配当前Pass策略的标识符会被忽略,并输出告警。若列表中所有标识符均未匹配,则不会输出任何Pass的计算图或IR。 |
| 46 | - 当 compile_debug_mode=1 与 dump_pass_graph 同时设置时,compile_debug_mode=1 优先,最终开启所有Pass的计算图dump和IR打印。 | 47 | - 当 compile_debug_mode=1 与 dump_pass_graph 同时设置时,compile_debug_mode=1 优先,最终开启所有Pass的计算图dump和IR打印。 |
| @@ -24,7 +24,7 @@ | |||
| 24 | namespace npu::tile_fwk { | 24 | namespace npu::tile_fwk { |
| 25 | class CodeGen { | 25 | class CodeGen { |
| 26 | public: | 26 | public: |
| 27 | - explicit CodeGen(const CodeGenCtx& ctx) : ctx_(ctx.includePath, ctx.cceDir, ctx.isMainBlock) {}; | 27 | + explicit CodeGen(const CodeGenCtx& ctx) : ctx_(ctx) {}; |
| 28 | 28 | ||
| 29 | void GenCode(Function& topFunc); | 29 | void GenCode(Function& topFunc); |
| 30 | 30 | ||
| @@ -140,12 +140,15 @@ struct CodeGenCtx { | |||
| 140 | std::string cceDir; | 140 | std::string cceDir; |
| 141 | bool isMainBlock{false}; | 141 | bool isMainBlock{false}; |
| 142 | bool isDynamicAligned{false}; | 142 | bool isDynamicAligned{false}; |
| 143 | + int devRootIndex{0}; | ||
| 143 | CodeGenCtx() = default; | 144 | CodeGenCtx() = default; |
| 144 | - CodeGenCtx(std::string inPath, std::string cmpPath, bool isMainBlk = false, bool isDynAligned = false) | 145 | + CodeGenCtx(std::string inPath, std::string cmpPath, bool isMainBlk = false, bool isDynAligned = false, |
| 146 | + int devRootIdx = 0) | ||
| 145 | : includePath(std::move(inPath)), | 147 | : includePath(std::move(inPath)), |
| 146 | cceDir(std::move(cmpPath)), | 148 | cceDir(std::move(cmpPath)), |
| 147 | isMainBlock(isMainBlk), | 149 | isMainBlock(isMainBlk), |
| 148 | - isDynamicAligned(isDynAligned) | 150 | + isDynamicAligned(isDynAligned), |
| 151 | + devRootIndex(devRootIdx) | ||
| 149 | {} | 152 | {} |
| 150 | bool IsCCEPathEmpty() const { return cceDir.empty(); } | 153 | bool IsCCEPathEmpty() const { return cceDir.empty(); } |
| 151 | bool IsIncludePathEmpty() const { return includePath.empty(); } | 154 | bool IsIncludePathEmpty() const { return includePath.empty(); } |
| @@ -14,9 +14,11 @@ | |||
| 14 | */ | 14 | */ |
| 15 | #include "codegen_npu.h" | 15 | #include "codegen_npu.h" |
| 16 | 16 | ||
| 17 | +#include <algorithm> | ||
| 17 | #include <cstring> | 18 | #include <cstring> |
| 18 | #include <error.h> | 19 | #include <error.h> |
| 19 | #include <fstream> | 20 | #include <fstream> |
| 21 | +#include <map> | ||
| 20 | 22 | ||
| 21 | #include "codegen/utils/parallel_execute.h" | 23 | #include "codegen/utils/parallel_execute.h" |
| 22 | #include "codegen_op_npu.h" | 24 | #include "codegen_op_npu.h" |
| @@ -106,21 +108,61 @@ void CodeGenNPU::GenCommentBeforeFuncHeader(Function& subFunc, std::ostringstrea | |||
| 106 | CODEGEN_LOGI("function hash is: %s", subFunc.GetFunctionHash().c_str()); | 108 | CODEGEN_LOGI("function hash is: %s", subFunc.GetFunctionHash().c_str()); |
| 107 | } | 109 | } |
| 108 | 110 | ||
| 109 | -std::string CodeGenNPU::GenKernelName(Function& topFunc, uint64_t programId) | 111 | +uint64_t CompileInfo::GetDeterministicSubId() const |
| 112 | +{ | ||
| 113 | + ASSERT(GenCodeErr::GEN_OP_CODE_FAILED, | ||
| 114 | + devRootIndex_ >= 0 && static_cast<uint64_t>(devRootIndex_) <= SUB_ID_DEV_ROOT_MAX) | ||
| 115 | + << "devRootIndex " << devRootIndex_ << " is out of the deterministic kernel id range [0, " | ||
| 116 | + << SUB_ID_DEV_ROOT_MAX << "]"; | ||
| 117 | + ASSERT(GenCodeErr::GEN_OP_CODE_FAILED, subProgramId_ <= SUB_ID_PROGRAM_MAX) | ||
| 118 | + << "subProgramId " << subProgramId_ << " is out of the deterministic kernel id range [0, " << SUB_ID_PROGRAM_MAX | ||
| 119 | + << "]"; | ||
| 120 | + | ||
| 121 | + uint64_t subId = static_cast<uint64_t>(devRootIndex_) << SUB_ID_DEV_ROOT_SHIFT; | ||
| 122 | + subId |= subProgramId_ << SUB_ID_PROGRAM_SHIFT; | ||
| 123 | + subId |= isMainBlock_ ? 1UL : 0UL; | ||
| 124 | + | ||
| 125 | + // Fold 64-bit hash into the high 32 bits so the full key is a pure bit-field concat. | ||
| 126 | + const uint64_t foldedHash = (topFuncHash_ ^ (topFuncHash_ >> SUB_ID_HASH_BITS)) & SUB_ID_HASH_MASK; | ||
| 127 | + subId |= foldedHash << SUB_ID_HASH_SHIFT; | ||
| 128 | + return subId; | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +/* Once the id no longer matches identity one-to-one, two kernels share a name and | ||
| 132 | + * the link-time symbol clash is hard to trace back here. Validate at generation: | ||
| 133 | + * regenerating the same CCE is fine (the same op must get the same name), but two | ||
| 134 | + * different CCEs with the same name means the bit fields are insufficient. | ||
| 135 | + */ | ||
| 136 | +void CheckKernelNameUnique(const std::string& kernelName, const std::string& cceFileName) | ||
| 137 | +{ | ||
| 138 | + static std::mutex registryMutex; | ||
| 139 | + static std::map<std::string, std::string> nameRegistry; | ||
| 140 | + | ||
| 141 | + std::lock_guard<std::mutex> lock(registryMutex); | ||
| 142 | + auto [iter, inserted] = nameRegistry.emplace(kernelName, cceFileName); | ||
| 143 | + ASSERT(GenCodeErr::GEN_OP_CODE_FAILED, inserted || iter->second == cceFileName) | ||
| 144 | + << "kernel name " << kernelName << " is shared by two kernels: " << iter->second << " and " << cceFileName; | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +std::string CodeGenNPU::GenKernelName(Function& topFunc, const CompileInfo& compileInfo) | ||
| 110 | { | 148 | { |
| 111 | std::ostringstream kernelName; | 149 | std::ostringstream kernelName; |
| 112 | - kernelName << topFunc.GetMagicName() << "_" << programId; | 150 | + uint64_t tilingKey = compileInfo.GetDeterministicSubId(); |
| 113 | - uint64_t tilingKey = OpInfoManager::GetInstance().GetNewSubTilingKey(); | 151 | + /* Keep funcHash in the kernel name to match CCE file naming; subTilingKey |
| 114 | - kernelName << "_" << std::to_string(tilingKey); | 152 | + * uniqueness comes from the 64-bit packed identity fields. |
| 153 | + */ | ||
| 154 | + kernelName << topFunc.GetMagicName() << "_" << topFunc.GetFunctionHash() << "_" << compileInfo.GetSubProgramId() | ||
| 155 | + << "_" << std::to_string(tilingKey); | ||
| 156 | + CheckKernelNameUnique(kernelName.str(), compileInfo.GetCCEFileName()); | ||
| 115 | return kernelName.str(); | 157 | return kernelName.str(); |
| 116 | } | 158 | } |
| 117 | 159 | ||
| 118 | -std::string CodeGenNPU::GenFuncHeader(uint64_t programId, Function& topFunc, CompileInfo& compileInfo) const | 160 | +std::string CodeGenNPU::GenFuncHeader(Function& topFunc, CompileInfo& compileInfo) const |
| 119 | { | 161 | { |
| 120 | std::ostringstream funcHeader; | 162 | std::ostringstream funcHeader; |
| 121 | funcHeader << "extern \"C\" [aicore] void "; | 163 | funcHeader << "extern \"C\" [aicore] void "; |
| 122 | // kernel name | 164 | // kernel name |
| 123 | - auto kernelName = GenKernelName(topFunc, programId); | 165 | + auto kernelName = GenKernelName(topFunc, compileInfo); |
| 124 | compileInfo.SetKernelName(kernelName); | 166 | compileInfo.SetKernelName(kernelName); |
| 125 | funcHeader << kernelName; | 167 | funcHeader << kernelName; |
| 126 | // kernel func param | 168 | // kernel func param |
| @@ -159,7 +201,7 @@ void CodeGenNPU::GenFuncBodyBefore(const std::pair<uint64_t, Function*>& subFunc | |||
| 159 | GenInclude(topFunc, oss); | 201 | GenInclude(topFunc, oss); |
| 160 | GenCommentBeforeFuncHeader(*subFuncPair.second, oss); | 202 | GenCommentBeforeFuncHeader(*subFuncPair.second, oss); |
| 161 | GenDDRChecker(oss); | 203 | GenDDRChecker(oss); |
| 162 | - oss << GenFuncHeader(subFuncPair.first, topFunc, compileInfo); | 204 | + oss << GenFuncHeader(topFunc, compileInfo); |
| 163 | } | 205 | } |
| 164 | 206 | ||
| 165 | void CodeGenNPU::GenFuncEnd(std::ostringstream& oss) const { oss << "}\n"; } | 207 | void CodeGenNPU::GenFuncEnd(std::ostringstream& oss) const { oss << "}\n"; } |
| @@ -759,6 +801,10 @@ void CodeGenNPU::GenerateMakefile(const std::string& makefilePath) const | |||
| 759 | return; | 801 | return; |
| 760 | } | 802 | } |
| 761 | 803 | ||
| 804 | + // 任务按并行完成顺序入列,排序后写出才能让Makefile内容与线程调度无关 | ||
| 805 | + std::sort(compileTasks_.begin(), compileTasks_.end(), | ||
| 806 | + [](const CompileTaskInfo& lhs, const CompileTaskInfo& rhs) { return lhs.outputPath < rhs.outputPath; }); | ||
| 807 | + | ||
| 762 | makefile << "# Auto-generated Makefile for parallel compilation\n"; | 808 | makefile << "# Auto-generated Makefile for parallel compilation\n"; |
| 763 | 809 | ||
| 764 | makefile << "all: "; | 810 | makefile << "all: "; |
| @@ -42,6 +42,28 @@ struct CompileTaskInfo { | |||
| 42 | std::string compileCmd; | 42 | std::string compileCmd; |
| 43 | }; | 43 | }; |
| 44 | 44 | ||
| 45 | +/* The 64-bit subTilingKey embedded in the kernel name must be reproducible under | ||
| 46 | + * multi-threaded codegen; otherwise fixed-CCE debug cannot match on-disk symbol | ||
| 47 | + * names with the names allocated in this compile. The id is therefore derived | ||
| 48 | + * from the task identity, not from completion order. | ||
| 49 | + * Layout (pure concat, LSB -> MSB): | ||
| 50 | + * [0:0] isMainBlock (1) | ||
| 51 | + * [1:19] subProgramId (19) | ||
| 52 | + * [20:31] devRootIndex (12) | ||
| 53 | + * [32:63] folded topFuncHash (32) = low32(hash ^ (hash >> 32)) | ||
| 54 | + * All fields are fixed before tasks are dispatched and can be read safely in parallel. | ||
| 55 | + */ | ||
| 56 | +constexpr uint32_t SUB_ID_MAIN_BLOCK_BITS = 1U; | ||
| 57 | +constexpr uint32_t SUB_ID_PROGRAM_BITS = 19U; | ||
| 58 | +constexpr uint32_t SUB_ID_DEV_ROOT_BITS = 12U; | ||
| 59 | +constexpr uint32_t SUB_ID_HASH_BITS = 32U; | ||
| 60 | +constexpr uint32_t SUB_ID_PROGRAM_SHIFT = SUB_ID_MAIN_BLOCK_BITS; | ||
| 61 | +constexpr uint32_t SUB_ID_DEV_ROOT_SHIFT = SUB_ID_PROGRAM_SHIFT + SUB_ID_PROGRAM_BITS; | ||
| 62 | +constexpr uint32_t SUB_ID_HASH_SHIFT = SUB_ID_DEV_ROOT_SHIFT + SUB_ID_DEV_ROOT_BITS; | ||
| 63 | +constexpr uint64_t SUB_ID_PROGRAM_MAX = (1UL << SUB_ID_PROGRAM_BITS) - 1UL; | ||
| 64 | +constexpr uint64_t SUB_ID_DEV_ROOT_MAX = (1UL << SUB_ID_DEV_ROOT_BITS) - 1UL; | ||
| 65 | +constexpr uint64_t SUB_ID_HASH_MASK = (1UL << SUB_ID_HASH_BITS) - 1UL; | ||
| 66 | + | ||
| 45 | class CompileInfo { | 67 | class CompileInfo { |
| 46 | public: | 68 | public: |
| 47 | CompileInfo(Function& topFunc, const CodeGenCtx& ctx, const std::pair<uint64_t, Function*>& subFuncPair, | 69 | CompileInfo(Function& topFunc, const CodeGenCtx& ctx, const std::pair<uint64_t, Function*>& subFuncPair, |
| @@ -49,7 +71,10 @@ public: | |||
| 49 | : userSpecCCEDir_(ctx.cceDir), | 71 | : userSpecCCEDir_(ctx.cceDir), |
| 50 | isCube_(isCube), | 72 | isCube_(isCube), |
| 51 | attr_(subFuncPair.second->GetLeafFuncAttribute()), | 73 | attr_(subFuncPair.second->GetLeafFuncAttribute()), |
| 52 | - isMainBlock_(ctx.isMainBlock) | 74 | + isMainBlock_(ctx.isMainBlock), |
| 75 | + subProgramId_(subFuncPair.first), | ||
| 76 | + devRootIndex_(ctx.devRootIndex), | ||
| 77 | + topFuncHash_(topFunc.GetFunctionHash().GetHash()) | ||
| 53 | { | 78 | { |
| 54 | Init(topFunc, subFuncPair.first); | 79 | Init(topFunc, subFuncPair.first); |
| 55 | }; | 80 | }; |
| @@ -65,6 +90,9 @@ public: | |||
| 65 | void SetFuncDeclare(const std::string& funcDeclare) { funcDeclare_ = funcDeclare; } | 90 | void SetFuncDeclare(const std::string& funcDeclare) { funcDeclare_ = funcDeclare; } |
| 66 | std::string GetFuncDeclare() const { return funcDeclare_; } | 91 | std::string GetFuncDeclare() const { return funcDeclare_; } |
| 67 | bool IsCube() const { return isCube_; } | 92 | bool IsCube() const { return isCube_; } |
| 93 | + uint64_t GetSubProgramId() const { return subProgramId_; } | ||
| 94 | + const std::string& GetCCEFileName() const { return cceFileName_; } | ||
| 95 | + uint64_t GetDeterministicSubId() const; | ||
| 68 | 96 | ||
| 69 | protected: | 97 | protected: |
| 70 | void Init(Function& topFunc, uint64_t subProgramId) | 98 | void Init(Function& topFunc, uint64_t subProgramId) |
| @@ -115,6 +143,9 @@ protected: | |||
| 115 | std::string funcDeclare_; | 143 | std::string funcDeclare_; |
| 116 | std::shared_ptr<LeafFuncAttribute> attr_{nullptr}; | 144 | std::shared_ptr<LeafFuncAttribute> attr_{nullptr}; |
| 117 | bool isMainBlock_{false}; | 145 | bool isMainBlock_{false}; |
| 146 | + uint64_t subProgramId_{0}; | ||
| 147 | + int devRootIndex_{0}; | ||
| 148 | + uint64_t topFuncHash_{0}; | ||
| 118 | }; | 149 | }; |
| 119 | 150 | ||
| 120 | class CodeGenNPU : public CodeGenCCE { | 151 | class CodeGenNPU : public CodeGenCCE { |
| @@ -139,10 +170,10 @@ protected: | |||
| 139 | CompileInfo& compileInfo, std::ostringstream& oss) const; | 170 | CompileInfo& compileInfo, std::ostringstream& oss) const; |
| 140 | void GenInclude(const Function& topFunc, std::ostringstream& oss) const; | 171 | void GenInclude(const Function& topFunc, std::ostringstream& oss) const; |
| 141 | void GenCommentBeforeFuncHeader(Function& subFunc, std::ostringstream& oss) const; | 172 | void GenCommentBeforeFuncHeader(Function& subFunc, std::ostringstream& oss) const; |
| 142 | - std::string GenFuncHeader(uint64_t programId, Function& topFunc, CompileInfo& compileInfo) const; | 173 | + std::string GenFuncHeader(Function& topFunc, CompileInfo& compileInfo) const; |
| 143 | virtual void GenFuncBody(Function& subFunc, Function& topFunc, std::ostringstream& oss) = 0; | 174 | virtual void GenFuncBody(Function& subFunc, Function& topFunc, std::ostringstream& oss) = 0; |
| 144 | void GenFuncEnd(std::ostringstream& oss) const; | 175 | void GenFuncEnd(std::ostringstream& oss) const; |
| 145 | - static std::string GenKernelName(Function& topFunc, uint64_t programId); | 176 | + static std::string GenKernelName(Function& topFunc, const CompileInfo& compileInfo); |
| 146 | 177 | ||
| 147 | void GenCodeToBinaryTask(std::ostringstream& code, const CompileInfo& compileInfo, | 178 | void GenCodeToBinaryTask(std::ostringstream& code, const CompileInfo& compileInfo, |
| 148 | const std::string& compileOptions) const; | 179 | const std::string& compileOptions) const; |
| @@ -196,12 +196,8 @@ void PrintIndent(std::ostringstream& os, int scopeLevel) | |||
| 196 | 196 | ||
| 197 | unsigned GetCGThreadNum() | 197 | unsigned GetCGThreadNum() |
| 198 | { | 198 | { |
| 199 | - unsigned threadNum; | 199 | + // kernel名已按任务身份确定性编号,固定CCE场景不必再退化为单线程 |
| 200 | - if (config::IsFixedCceMode()) { | 200 | + unsigned threadNum = ConfigManager::Instance().GetCodeGenConfig(KEY_PARALLEL_COMPILE, 1u); |
| 201 | - threadNum = 1; | ||
| 202 | - } else { | ||
| 203 | - threadNum = ConfigManager::Instance().GetCodeGenConfig(KEY_PARALLEL_COMPILE, 1u); | ||
| 204 | - } | ||
| 205 | unsigned cpuCores = std::thread::hardware_concurrency(); | 201 | unsigned cpuCores = std::thread::hardware_concurrency(); |
| 206 | if (cpuCores != 0 && threadNum > cpuCores * CORE_NUM_MULTIPLE) { | 202 | if (cpuCores != 0 && threadNum > cpuCores * CORE_NUM_MULTIPLE) { |
| 207 | return cpuCores * CORE_NUM_MULTIPLE; | 203 | return cpuCores * CORE_NUM_MULTIPLE; |
| @@ -15,56 +15,77 @@ | |||
| 15 | 15 | ||
| 16 | #include "parallel_execute.h" | 16 | #include "parallel_execute.h" |
| 17 | 17 | ||
| 18 | -#include <thread> | 18 | +#include <cstddef> |
| 19 | +#include <deque> | ||
| 20 | +#include <future> | ||
| 19 | #include <mutex> | 21 | #include <mutex> |
| 20 | #include <optional> | 22 | #include <optional> |
| 21 | -#include <deque> | 23 | +#include <thread> |
| 24 | +#include <vector> | ||
| 22 | 25 | ||
| 23 | namespace npu::tile_fwk { | 26 | namespace npu::tile_fwk { |
| 24 | namespace { | 27 | namespace { |
| 25 | -class ThreadSafeTaskQueue { | 28 | +class ThreadSafeIndexQueue { |
| 26 | public: | 29 | public: |
| 27 | - explicit ThreadSafeTaskQueue(const std::deque<Task>& v) { q = v; } | 30 | + explicit ThreadSafeIndexQueue(std::deque<size_t> indices) { q_ = std::move(indices); } |
| 28 | - explicit ThreadSafeTaskQueue(std::deque<Task>&& v) { q = std::move(v); } | ||
| 29 | 31 | ||
| 30 | - std::optional<Task> GetTask() | 32 | + std::optional<size_t> GetIndex() |
| 31 | { | 33 | { |
| 32 | - const std::lock_guard<std::mutex> taskLock(m); | 34 | + const std::lock_guard<std::mutex> taskLock(m_); |
| 33 | 35 | ||
| 34 | - if (q.empty()) { | 36 | + if (q_.empty()) { |
| 35 | return std::nullopt; | 37 | return std::nullopt; |
| 36 | } | 38 | } |
| 37 | 39 | ||
| 38 | - Task e = q.front(); | 40 | + size_t index = q_.front(); |
| 39 | - q.pop_front(); | 41 | + q_.pop_front(); |
| 40 | - | 42 | + return index; |
| 41 | - return e; | ||
| 42 | } | 43 | } |
| 43 | 44 | ||
| 44 | private: | 45 | private: |
| 45 | - std::deque<Task> q; | 46 | + std::deque<size_t> q_; |
| 46 | - std::mutex m; | 47 | + std::mutex m_; |
| 47 | }; | 48 | }; |
| 48 | 49 | ||
| 49 | -void TaskRunner(ThreadSafeTaskQueue& taskQueue) | 50 | +using PackagedTask = std::packaged_task<void()>; |
| 51 | + | ||
| 52 | +struct TaskBatch { | ||
| 53 | + std::vector<PackagedTask> packagedTasks; | ||
| 54 | + std::vector<std::future<void>> futures; | ||
| 55 | + | ||
| 56 | + explicit TaskBatch(std::deque<Task> tasks) | ||
| 57 | + { | ||
| 58 | + packagedTasks.reserve(tasks.size()); | ||
| 59 | + futures.reserve(tasks.size()); | ||
| 60 | + while (!tasks.empty()) { | ||
| 61 | + packagedTasks.emplace_back(std::move(tasks.front())); | ||
| 62 | + tasks.pop_front(); | ||
| 63 | + futures.push_back(packagedTasks.back().get_future()); | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | +}; | ||
| 67 | + | ||
| 68 | +void TaskRunner(ThreadSafeIndexQueue& indexQueue, TaskBatch& batch) | ||
| 50 | { | 69 | { |
| 51 | while (true) { | 70 | while (true) { |
| 52 | - auto taskMaybe = taskQueue.GetTask(); | 71 | + auto indexMaybe = indexQueue.GetIndex(); |
| 53 | - if (!taskMaybe) { | 72 | + if (!indexMaybe) { |
| 54 | break; | 73 | break; |
| 55 | } | 74 | } |
| 56 | 75 | ||
| 57 | - auto& task = taskMaybe.value(); | 76 | + batch.packagedTasks[indexMaybe.value()](); |
| 58 | - try { | 77 | + } |
| 59 | - task(); | 78 | +} |
| 60 | - } catch (const std::exception& e) { | 79 | + |
| 61 | - CODEGEN_LOGE(FwkErr::TASK_RUN_FAILED, "Parallel task exception: %s", e.what()); | 80 | +void WaitTaskFutures(std::vector<std::future<void>>& futures) |
| 62 | - } catch (...) { | 81 | +{ |
| 63 | - CODEGEN_LOGE(FwkErr::TASK_RUN_FAILED, "Parallel task unknown exception"); | 82 | + for (auto& future : futures) { |
| 83 | + if (future.valid()) { | ||
| 84 | + future.get(); | ||
| 64 | } | 85 | } |
| 65 | } | 86 | } |
| 66 | } | 87 | } |
| 67 | -}; // namespace | 88 | +} // namespace |
| 68 | 89 | ||
| 69 | void ParallelExecuteAndWait(unsigned threadNum, std::deque<Task> tasks) | 90 | void ParallelExecuteAndWait(unsigned threadNum, std::deque<Task> tasks) |
| 70 | { | 91 | { |
| @@ -72,30 +93,33 @@ void ParallelExecuteAndWait(unsigned threadNum, std::deque<Task> tasks) | |||
| 72 | threadNum = 1; | 93 | threadNum = 1; |
| 73 | } | 94 | } |
| 74 | 95 | ||
| 75 | - if (threadNum == 1) { | 96 | + TaskBatch batch(std::move(tasks)); |
| 76 | - // no need to use extra thread if only one thread is needed | ||
| 77 | - for (auto& task : tasks) { | ||
| 78 | - try { | ||
| 79 | - task(); | ||
| 80 | - } catch (const std::exception& e) { | ||
| 81 | - CODEGEN_LOGE(FwkErr::TASK_RUN_FAILED, "Parallel task exception: %s", e.what()); | ||
| 82 | - } catch (...) { | ||
| 83 | - CODEGEN_LOGE(FwkErr::TASK_RUN_FAILED, "Parallel task unknown exception"); | ||
| 84 | - } | ||
| 85 | - } | ||
| 86 | 97 | ||
| 98 | + if (threadNum == 1) { | ||
| 99 | + for (size_t i = 0; i < batch.packagedTasks.size(); ++i) { | ||
| 100 | + batch.packagedTasks[i](); | ||
| 101 | + batch.futures[i].get(); | ||
| 102 | + } | ||
| 87 | return; | 103 | return; |
| 88 | } | 104 | } |
| 89 | 105 | ||
| 90 | - ThreadSafeTaskQueue taskQueue(std::move(tasks)); | 106 | + std::deque<size_t> indices; |
| 107 | + for (size_t i = 0; i < batch.packagedTasks.size(); ++i) { | ||
| 108 | + indices.push_back(i); | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + ThreadSafeIndexQueue indexQueue(std::move(indices)); | ||
| 91 | 112 | ||
| 92 | std::vector<std::thread> threadPool; | 113 | std::vector<std::thread> threadPool; |
| 114 | + threadPool.reserve(threadNum); | ||
| 93 | for (unsigned i = 0; i < threadNum; i++) { | 115 | for (unsigned i = 0; i < threadNum; i++) { |
| 94 | - threadPool.emplace_back(TaskRunner, std::ref(taskQueue)); | 116 | + threadPool.emplace_back(TaskRunner, std::ref(indexQueue), std::ref(batch)); |
| 95 | } | 117 | } |
| 96 | 118 | ||
| 97 | - for (auto& tth : threadPool) { | 119 | + for (auto& worker : threadPool) { |
| 98 | - tth.join(); | 120 | + worker.join(); |
| 99 | } | 121 | } |
| 122 | + | ||
| 123 | + WaitTaskFutures(batch.futures); | ||
| 100 | } | 124 | } |
| 101 | } // namespace npu::tile_fwk | 125 | } // namespace npu::tile_fwk |
| @@ -544,8 +544,8 @@ | |||
| 544 | "compile_debug_mode": { | 544 | "compile_debug_mode": { |
| 545 | "type": "integer", | 545 | "type": "integer", |
| 546 | "label": { | 546 | "label": { |
| 547 | - "zh": "设置编译阶段调试模式。0:不使能;1:使能,一键开启图编译相关配置(如计算图);2:使能,一键开启固定CCE功能(固定设备侧代码输出路径、不覆盖已存在的CCE文件、单线程编译)。", | 547 | + "zh": "设置编译阶段调试模式。0:不使能;1:使能,一键开启图编译相关配置(如计算图);2:使能,一键开启固定CCE功能(固定设备侧代码输出路径、不覆盖已存在的CCE文件);并行编译线程数由 codegen.parallel_compile 控制,kernel 名确定性编号保证多线程产物可复现。", |
| 548 | - "en": "Set debug mode during compilation stage. 0: disabled; 1: enabled, one-click to enable graph compilation related configurations (e.g. compute graph); 2: enabled, one-click to enable fixed CCE (fix device-side code output path, do not overwrite existing CCE files, single-thread compilation)." | 548 | + "en": "Set debug mode during compilation stage. 0: disabled; 1: enabled, one-click to enable graph compilation related configurations (e.g. compute graph); 2: enabled, one-click to enable fixed CCE (fix device-side code output path, do not overwrite existing CCE files); parallel compile threads are controlled by codegen.parallel_compile, and deterministic kernel naming keeps multi-thread outputs reproducible." |
| 549 | }, | 549 | }, |
| 550 | "minimum": 0, | 550 | "minimum": 0, |
| 551 | "maximum": 2 | 551 | "maximum": 2 |
| @@ -22,32 +22,7 @@ OpInfoManager& OpInfoManager::GetInstance() | |||
| 22 | return instance; | 22 | return instance; |
| 23 | } | 23 | } |
| 24 | 24 | ||
| 25 | -// need add check | 25 | +uint64_t OpInfoManager::GetOpTilingKey() const { return DEFAULT_OP_TILING_KEY; } |
| 26 | -void OpInfoManager::SetOpTilingKey(uint64_t opTilingKey) | ||
| 27 | -{ | ||
| 28 | - opTilingKey_ = (opTilingKey & MAIN_KEY_MASK); | ||
| 29 | - return; | ||
| 30 | -} | ||
| 31 | - | ||
| 32 | -uint64_t OpInfoManager::GetOpTilingKey() const { return opTilingKey_; } | ||
| 33 | - | ||
| 34 | -// need check | ||
| 35 | -uint64_t OpInfoManager::GetNewSubTilingKey() | ||
| 36 | -{ | ||
| 37 | - std::lock_guard<std::mutex> lock(mtx_); | ||
| 38 | - subTilingKey_++; | ||
| 39 | - if (subTilingKey_ > MAIN_KEY_MASK) { | ||
| 40 | - subTilingKey_ = 1; | ||
| 41 | - } | ||
| 42 | - uint64_t cur_key = (subTilingKey_ << SUB_KEY_OFFSET) | opTilingKey_; | ||
| 43 | - return cur_key; | ||
| 44 | -} | ||
| 45 | - | ||
| 46 | -uint64_t OpInfoManager::GetCurSubTilingKey() const | ||
| 47 | -{ | ||
| 48 | - uint64_t cur_key = (subTilingKey_ << SUB_KEY_OFFSET) | opTilingKey_; | ||
| 49 | - return cur_key; | ||
| 50 | -} | ||
| 51 | 26 | ||
| 52 | void OpInfoManager::SetOpType(const std::string& opType) | 27 | void OpInfoManager::SetOpType(const std::string& opType) |
| 53 | { | 28 | { |
| @@ -17,23 +17,18 @@ | |||
| 17 | 17 | ||
| 18 | #include <map> | 18 | #include <map> |
| 19 | #include <vector> | 19 | #include <vector> |
| 20 | -#include <mutex> | ||
| 21 | #include "tilefwk/tensor.h" | 20 | #include "tilefwk/tensor.h" |
| 22 | 21 | ||
| 23 | namespace npu::tile_fwk { | 22 | namespace npu::tile_fwk { |
| 24 | -constexpr uint64_t MAIN_KEY_MASK = 0xFFFFFFFF; | 23 | +// Top-level dy_kernel / KERNEL_ENTRY tilingKey; leaf subTilingKey is produced by codegen separately. |
| 25 | -constexpr uint64_t SUB_KEY_OFFSET = 32UL; | 24 | +constexpr uint64_t DEFAULT_OP_TILING_KEY = 0UL; |
| 26 | -constexpr uint64_t SUB_KEY_MASK = 0xFFFFFFFF00000000; | ||
| 27 | 25 | ||
| 28 | class OpInfoManager { | 26 | class OpInfoManager { |
| 29 | public: | 27 | public: |
| 30 | OpInfoManager() = default; | 28 | OpInfoManager() = default; |
| 31 | ~OpInfoManager() = default; | 29 | ~OpInfoManager() = default; |
| 32 | static OpInfoManager& GetInstance(); | 30 | static OpInfoManager& GetInstance(); |
| 33 | - void SetOpTilingKey(uint64_t opTilingKey); | ||
| 34 | uint64_t GetOpTilingKey() const; | 31 | uint64_t GetOpTilingKey() const; |
| 35 | - uint64_t GetNewSubTilingKey(); | ||
| 36 | - uint64_t GetCurSubTilingKey() const; | ||
| 37 | void SetOpType(const std::string& opType); | 32 | void SetOpType(const std::string& opType); |
| 38 | const std::string& GetOpType() const; | 33 | const std::string& GetOpType() const; |
| 39 | bool IsNotFabinCompile(); | 34 | bool IsNotFabinCompile(); |
| @@ -45,10 +40,7 @@ public: | |||
| 45 | void SetControlBinHandle(void* controlFlowBindHandle); | 40 | void SetControlBinHandle(void* controlFlowBindHandle); |
| 46 | 41 | ||
| 47 | private: | 42 | private: |
| 48 | - std::mutex mtx_; | ||
| 49 | std::string opType_ = "PyPTO"; | 43 | std::string opType_ = "PyPTO"; |
| 50 | - uint64_t opTilingKey_{0}; | ||
| 51 | - uint64_t subTilingKey_{0}; | ||
| 52 | std::vector<uint8_t> controlBuffer_ = {'0'}; | 44 | std::vector<uint8_t> controlBuffer_ = {'0'}; |
| 53 | std::vector<char> customJson_ = {'0'}; | 45 | std::vector<char> customJson_ = {'0'}; |
| 54 | std::string controlFlowSoPath_; | 46 | std::string controlFlowSoPath_; |
| @@ -947,15 +947,18 @@ static void RunCodeGenStage(const std::shared_ptr<DyndevFunctionAttribute>& attr | |||
| 947 | 947 | ||
| 948 | std::deque<std::function<void(void)>> tasks; | 948 | std::deque<std::function<void(void)>> tasks; |
| 949 | for (auto& devRoot : attr->funcGroup.devRootList) { | 949 | for (auto& devRoot : attr->funcGroup.devRootList) { |
| 950 | - std::function<void(void)> task = [&devRoot, &attr, &leafDict, &leafDictMutex]() { | 950 | + // Capture the index before dispatch so parallel tasks do not touch devRootList. |
| 951 | + int devRootIndex = attr->funcGroup.devRootList.GetIndex(devRoot); | ||
| 952 | + std::function<void(void)> task = [&devRoot, &attr, &leafDict, &leafDictMutex, devRootIndex]() { | ||
| 951 | Function* devTile = attr->rootTileDict[devRoot]; | 953 | Function* devTile = attr->rootTileDict[devRoot]; |
| 952 | bool isDynamicAligned = devTile->paramConfigs_.dynamicAlignedOps; | 954 | bool isDynamicAligned = devTile->paramConfigs_.dynamicAlignedOps; |
| 953 | - npu::tile_fwk::CodeGenCtx codeGenCtx("", config::GetEmitPath("kernel_aicore"), false, isDynamicAligned); | 955 | + npu::tile_fwk::CodeGenCtx codeGenCtx("", config::GetEmitPath("kernel_aicore"), false, isDynamicAligned, |
| 956 | + devRootIndex); | ||
| 954 | npu::tile_fwk::CodeGen codeGen(codeGenCtx); | 957 | npu::tile_fwk::CodeGen codeGen(codeGenCtx); |
| 955 | COMPILER_LOGI("Function :[%s] starts executing codegen and binary compilation", | 958 | COMPILER_LOGI("Function :[%s] starts executing codegen and binary compilation", |
| 956 | devTile->GetMagicName().c_str()); | 959 | devTile->GetMagicName().c_str()); |
| 957 | codeGen.GenCode(*devTile); | 960 | codeGen.GenCode(*devTile); |
| 958 | - MainBlockCondBulider::Gencode(devTile); | 961 | + MainBlockCondBulider::Gencode(devTile, devRootIndex); |
| 959 | 962 | ||
| 960 | std::lock_guard<std::mutex> lock(leafDictMutex); | 963 | std::lock_guard<std::mutex> lock(leafDictMutex); |
| 961 | for (auto& [psgId, leaf] : devRoot->programs_) { | 964 | for (auto& [psgId, leaf] : devRoot->programs_) { |
| @@ -228,11 +228,12 @@ SymbolicScalar MainBlockCondBulider::BuildMainBlockExpression() | |||
| 228 | return cond; | 228 | return cond; |
| 229 | } | 229 | } |
| 230 | 230 | ||
| 231 | -void MainBlockCondBulider::Gencode(Function* function) | 231 | +void MainBlockCondBulider::Gencode(Function* function, int devRootIndex) |
| 232 | { | 232 | { |
| 233 | if (IsEnableVF()) { | 233 | if (IsEnableVF()) { |
| 234 | bool isDynamicAligned = function->paramConfigs_.dynamicAlignedOps; | 234 | bool isDynamicAligned = function->paramConfigs_.dynamicAlignedOps; |
| 235 | - npu::tile_fwk::CodeGenCtx codeGenCtxMainBlock("", config::GetEmitPath("kernel_aicore"), true, isDynamicAligned); | 235 | + npu::tile_fwk::CodeGenCtx codeGenCtxMainBlock("", config::GetEmitPath("kernel_aicore"), true, isDynamicAligned, |
| 236 | + devRootIndex); | ||
| 236 | npu::tile_fwk::CodeGen codeGenMainBlock(codeGenCtxMainBlock); | 237 | npu::tile_fwk::CodeGen codeGenMainBlock(codeGenCtxMainBlock); |
| 237 | codeGenMainBlock.GenCode(*function); | 238 | codeGenMainBlock.GenCode(*function); |
| 238 | } | 239 | } |
| @@ -28,7 +28,7 @@ public: | |||
| 28 | void CollectCallopMainBlockConds(Function* func); | 28 | void CollectCallopMainBlockConds(Function* func); |
| 29 | void CollectLeafMainBlockConds(Function* func, const std::vector<SymbolicScalar>& linearArgList); | 29 | void CollectLeafMainBlockConds(Function* func, const std::vector<SymbolicScalar>& linearArgList); |
| 30 | SymbolicScalar BuildMainBlockExpression(); | 30 | SymbolicScalar BuildMainBlockExpression(); |
| 31 | - static void Gencode(Function* function); | 31 | + static void Gencode(Function* function, int devRootIndex = 0); |
| 32 | const std::vector<SymbolicScalar>& GetCondGroup() const; | 32 | const std::vector<SymbolicScalar>& GetCondGroup() const; |
| 33 | const std::unordered_set<std::string>& GetCondStrSet() const; | 33 | const std::unordered_set<std::string>& GetCondStrSet() const; |
| 34 | 34 | ||
| @@ -0,0 +1,156 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025 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 test_codegen_kernel_name.cpp | ||
| 13 | + * \brief Unit test for deterministic kernel numbering under parallel codegen. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <set> | ||
| 17 | +#include <thread> | ||
| 18 | +#include <vector> | ||
| 19 | + | ||
| 20 | +#include <gtest/gtest.h> | ||
| 21 | + | ||
| 22 | +#include "interface/function/function.h" | ||
| 23 | +#include "codegen/npu/codegen_npu.h" | ||
| 24 | +#include "test_codegen_utils.h" | ||
| 25 | + | ||
| 26 | +namespace npu::tile_fwk { | ||
| 27 | +namespace { | ||
| 28 | +constexpr int THREAD_NUM = 128; | ||
| 29 | +constexpr int DEV_ROOT_NUM = 8; | ||
| 30 | +constexpr uint64_t PROGRAM_NUM = 16; | ||
| 31 | + | ||
| 32 | +struct KernelIdentity { | ||
| 33 | + int devRootIndex; | ||
| 34 | + uint64_t subProgramId; | ||
| 35 | + bool isMainBlock; | ||
| 36 | +}; | ||
| 37 | + | ||
| 38 | +std::vector<KernelIdentity> BuildIdentities() | ||
| 39 | +{ | ||
| 40 | + std::vector<KernelIdentity> identities; | ||
| 41 | + for (int devRoot = 0; devRoot < DEV_ROOT_NUM; ++devRoot) { | ||
| 42 | + for (uint64_t program = 0; program < PROGRAM_NUM; ++program) { | ||
| 43 | + identities.push_back({devRoot, program, false}); | ||
| 44 | + identities.push_back({devRoot, program, true}); | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | + return identities; | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +uint64_t MakeKernelKey(Function& topFunc, const KernelIdentity& identity) | ||
| 51 | +{ | ||
| 52 | + CodeGenCtx ctx("", "", identity.isMainBlock, false, identity.devRootIndex); | ||
| 53 | + std::pair<uint64_t, Function*> subFuncPair{identity.subProgramId, topFunc.rootFunc_->programs_[0]}; | ||
| 54 | + CompileInfo compileInfo(topFunc, ctx, subFuncPair, false); | ||
| 55 | + return compileInfo.GetDeterministicSubId(); | ||
| 56 | +} | ||
| 57 | +} // namespace | ||
| 58 | + | ||
| 59 | +class TestCodegenKernelName : public CodegenTestBase { | ||
| 60 | +public: | ||
| 61 | + TestCodegenKernelName() | ||
| 62 | + : CodegenTestBase({.compileStage = CS_EXECUTE_GRAPH, | ||
| 63 | + .setTileTensor = true, | ||
| 64 | + .tileTensorValue = true, | ||
| 65 | + .setIdGen = true, | ||
| 66 | + .resetTileTensorOnTearDown = true}) | ||
| 67 | + {} | ||
| 68 | +}; | ||
| 69 | + | ||
| 70 | +TEST_F(TestCodegenKernelName, SubTilingKeyDiffersPerFuncHashWithSameStructuredSlot) | ||
| 71 | +{ | ||
| 72 | + // Two GenMockFuncDyn in one Program without Reset() crashes in RemoveCallOpViewAssemble | ||
| 73 | + // (GetGraphInfo dereferences empty producers). Build them sequentially with Reset. | ||
| 74 | + KernelIdentity identity{1, 0, false}; | ||
| 75 | + | ||
| 76 | + Function* functionA = GenMockFuncDyn("kernel_hash_a"); | ||
| 77 | + ASSERT_NE(functionA, nullptr); | ||
| 78 | + const uint64_t hashA = functionA->GetFunctionHash().GetHash(); | ||
| 79 | + const uint64_t keyA = MakeKernelKey(*functionA, identity); | ||
| 80 | + | ||
| 81 | + Program::GetInstance().Reset(); | ||
| 82 | + config::Reset(); | ||
| 83 | + config::SetHostOption(COMPILE_STAGE, CS_EXECUTE_GRAPH); | ||
| 84 | + config::SetCodeGenConfig(KEY_CODEGEN_SUPPORT_TILE_TENSOR, true); | ||
| 85 | + IdGen<IdType::FUNCTION>::Inst().SetId(DummyFuncMagic); | ||
| 86 | + | ||
| 87 | + Function* functionB = GenMockFuncDyn("kernel_hash_b"); | ||
| 88 | + ASSERT_NE(functionB, nullptr); | ||
| 89 | + const uint64_t hashB = functionB->GetFunctionHash().GetHash(); | ||
| 90 | + const uint64_t keyB = MakeKernelKey(*functionB, identity); | ||
| 91 | + | ||
| 92 | + ASSERT_NE(hashA, hashB); | ||
| 93 | + EXPECT_NE(keyA, keyB); | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +TEST_F(TestCodegenKernelName, SubTilingKeyPacksDecodableFields) | ||
| 97 | +{ | ||
| 98 | + Function* function = GenMockFuncDyn("kernel_id_decode"); | ||
| 99 | + ASSERT_NE(function, nullptr); | ||
| 100 | + | ||
| 101 | + KernelIdentity identity{3, 7, true}; | ||
| 102 | + uint64_t key = MakeKernelKey(*function, identity); | ||
| 103 | + | ||
| 104 | + EXPECT_EQ(key & 1UL, 1UL); | ||
| 105 | + EXPECT_EQ((key >> SUB_ID_PROGRAM_SHIFT) & SUB_ID_PROGRAM_MAX, identity.subProgramId); | ||
| 106 | + EXPECT_EQ((key >> SUB_ID_DEV_ROOT_SHIFT) & SUB_ID_DEV_ROOT_MAX, static_cast<uint64_t>(identity.devRootIndex)); | ||
| 107 | + | ||
| 108 | + uint64_t hash = function->GetFunctionHash().GetHash(); | ||
| 109 | + uint64_t folded = (hash ^ (hash >> SUB_ID_HASH_BITS)) & SUB_ID_HASH_MASK; | ||
| 110 | + EXPECT_EQ((key >> SUB_ID_HASH_SHIFT) & SUB_ID_HASH_MASK, folded); | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +TEST_F(TestCodegenKernelName, SubTilingKeyIsUniquePerIdentity) | ||
| 114 | +{ | ||
| 115 | + Function* function = GenMockFuncDyn("kernel_id_unique"); | ||
| 116 | + ASSERT_NE(function, nullptr); | ||
| 117 | + ASSERT_NE(function->rootFunc_->programs_[0], nullptr); | ||
| 118 | + | ||
| 119 | + auto identities = BuildIdentities(); | ||
| 120 | + std::set<uint64_t> keys; | ||
| 121 | + for (const auto& identity : identities) { | ||
| 122 | + keys.insert(MakeKernelKey(*function, identity)); | ||
| 123 | + } | ||
| 124 | + EXPECT_EQ(keys.size(), identities.size()); | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +TEST_F(TestCodegenKernelName, SubTilingKeyIsStableAcrossThreadCounts) | ||
| 128 | +{ | ||
| 129 | + Function* function = GenMockFuncDyn("kernel_id_stable"); | ||
| 130 | + ASSERT_NE(function, nullptr); | ||
| 131 | + ASSERT_NE(function->rootFunc_->programs_[0], nullptr); | ||
| 132 | + | ||
| 133 | + auto identities = BuildIdentities(); | ||
| 134 | + std::vector<uint64_t> serialKeys; | ||
| 135 | + for (const auto& identity : identities) { | ||
| 136 | + serialKeys.push_back(MakeKernelKey(*function, identity)); | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + // Ids are derived from task identity only, so parallel allocation must match serial keys exactly. | ||
| 140 | + std::vector<uint64_t> parallelKeys(identities.size(), 0); | ||
| 141 | + std::vector<std::thread> threads; | ||
| 142 | + for (int t = 0; t < THREAD_NUM; ++t) { | ||
| 143 | + threads.emplace_back([&identities, ¶llelKeys, function, t]() { | ||
| 144 | + for (size_t i = t; i < identities.size(); i += THREAD_NUM) { | ||
| 145 | + parallelKeys[i] = MakeKernelKey(*function, identities[i]); | ||
| 146 | + } | ||
| 147 | + }); | ||
| 148 | + } | ||
| 149 | + for (auto& thread : threads) { | ||
| 150 | + thread.join(); | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + EXPECT_EQ(parallelKeys, serialKeys); | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +} // namespace npu::tile_fwk | ||
| @@ -0,0 +1,152 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2025 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 test_parallel_execute.cpp | ||
| 13 | + * \brief Unit test for ParallelExecuteAndWait exception propagation. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <atomic> | ||
| 17 | +#include <chrono> | ||
| 18 | +#include <deque> | ||
| 19 | +#include <stdexcept> | ||
| 20 | +#include <string> | ||
| 21 | +#include <thread> | ||
| 22 | + | ||
| 23 | +#include <gtest/gtest.h> | ||
| 24 | + | ||
| 25 | +#include "codegen/utils/parallel_execute.h" | ||
| 26 | + | ||
| 27 | +namespace npu::tile_fwk { | ||
| 28 | +namespace { | ||
| 29 | + | ||
| 30 | +std::deque<Task> MakeIncrementTasks(int count, std::atomic<int>& counter) | ||
| 31 | +{ | ||
| 32 | + std::deque<Task> tasks; | ||
| 33 | + for (int i = 0; i < count; ++i) { | ||
| 34 | + tasks.emplace_back([&counter]() { counter.fetch_add(1, std::memory_order_relaxed); }); | ||
| 35 | + } | ||
| 36 | + return tasks; | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +} // namespace | ||
| 40 | + | ||
| 41 | +TEST(TestParallelExecute, SingleThreadRunsAllTasks) | ||
| 42 | +{ | ||
| 43 | + std::atomic<int> counter{0}; | ||
| 44 | + ParallelExecuteAndWait(1, MakeIncrementTasks(5, counter)); | ||
| 45 | + EXPECT_EQ(counter.load(), 5); | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +TEST(TestParallelExecute, MultiThreadRunsAllTasks) | ||
| 49 | +{ | ||
| 50 | + std::atomic<int> counter{0}; | ||
| 51 | + ParallelExecuteAndWait(4, MakeIncrementTasks(20, counter)); | ||
| 52 | + EXPECT_EQ(counter.load(), 20); | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +TEST(TestParallelExecute, ZeroThreadNumTreatedAsOne) | ||
| 56 | +{ | ||
| 57 | + std::atomic<int> counter{0}; | ||
| 58 | + ParallelExecuteAndWait(0, MakeIncrementTasks(3, counter)); | ||
| 59 | + EXPECT_EQ(counter.load(), 3); | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +TEST(TestParallelExecute, EmptyTaskQueueCompletes) | ||
| 63 | +{ | ||
| 64 | + std::deque<Task> tasks; | ||
| 65 | + EXPECT_NO_THROW(ParallelExecuteAndWait(4, std::move(tasks))); | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +TEST(TestParallelExecute, SingleThreadPropagatesStdException) | ||
| 69 | +{ | ||
| 70 | + std::deque<Task> tasks; | ||
| 71 | + tasks.emplace_back([]() { throw std::runtime_error("single thread boom"); }); | ||
| 72 | + EXPECT_THROW(ParallelExecuteAndWait(1, std::move(tasks)), std::runtime_error); | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +TEST(TestParallelExecute, SingleThreadPreservesExceptionMessage) | ||
| 76 | +{ | ||
| 77 | + const std::string msg = "specific parallel task error"; | ||
| 78 | + std::deque<Task> tasks; | ||
| 79 | + tasks.emplace_back([&msg]() { throw std::runtime_error(msg); }); | ||
| 80 | + | ||
| 81 | + try { | ||
| 82 | + ParallelExecuteAndWait(1, std::move(tasks)); | ||
| 83 | + FAIL() << "Expected std::runtime_error"; | ||
| 84 | + } catch (const std::runtime_error& e) { | ||
| 85 | + EXPECT_STREQ(e.what(), msg.c_str()); | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +TEST(TestParallelExecute, SingleThreadStopsSubsequentTasksOnError) | ||
| 90 | +{ | ||
| 91 | + std::atomic<int> counter{0}; | ||
| 92 | + std::deque<Task> tasks; | ||
| 93 | + tasks.emplace_back([]() { throw std::runtime_error("fail early"); }); | ||
| 94 | + tasks.emplace_back([&counter]() { counter.fetch_add(1, std::memory_order_relaxed); }); | ||
| 95 | + | ||
| 96 | + EXPECT_THROW(ParallelExecuteAndWait(1, std::move(tasks)), std::runtime_error); | ||
| 97 | + EXPECT_EQ(counter.load(), 0); | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +TEST(TestParallelExecute, SingleThreadPropagatesUnknownException) | ||
| 101 | +{ | ||
| 102 | + std::deque<Task> tasks; | ||
| 103 | + tasks.emplace_back([]() { throw 42; }); | ||
| 104 | + | ||
| 105 | + bool caught = false; | ||
| 106 | + try { | ||
| 107 | + ParallelExecuteAndWait(1, std::move(tasks)); | ||
| 108 | + } catch (...) { | ||
| 109 | + caught = true; | ||
| 110 | + } | ||
| 111 | + EXPECT_TRUE(caught); | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +TEST(TestParallelExecute, MultiThreadPropagatesStdException) | ||
| 115 | +{ | ||
| 116 | + std::deque<Task> tasks; | ||
| 117 | + tasks.emplace_back([]() { throw std::runtime_error("multi thread boom"); }); | ||
| 118 | + tasks.emplace_back([]() {}); | ||
| 119 | + EXPECT_THROW(ParallelExecuteAndWait(4, std::move(tasks)), std::runtime_error); | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +TEST(TestParallelExecute, MultiThreadPropagatesUnknownException) | ||
| 123 | +{ | ||
| 124 | + std::deque<Task> tasks; | ||
| 125 | + tasks.emplace_back([]() { throw 42; }); | ||
| 126 | + tasks.emplace_back([]() {}); | ||
| 127 | + | ||
| 128 | + bool caught = false; | ||
| 129 | + try { | ||
| 130 | + ParallelExecuteAndWait(4, std::move(tasks)); | ||
| 131 | + } catch (...) { | ||
| 132 | + caught = true; | ||
| 133 | + } | ||
| 134 | + EXPECT_TRUE(caught); | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +TEST(TestParallelExecute, MultiThreadExceptionPropagatesAfterWorkersJoin) | ||
| 138 | +{ | ||
| 139 | + std::atomic<int> startedAfterFailure{0}; | ||
| 140 | + std::deque<Task> tasks; | ||
| 141 | + tasks.emplace_back([]() { throw std::runtime_error("trigger stop"); }); | ||
| 142 | + for (int i = 0; i < 8; ++i) { | ||
| 143 | + tasks.emplace_back([&startedAfterFailure]() { | ||
| 144 | + std::this_thread::sleep_for(std::chrono::milliseconds(5)); | ||
| 145 | + startedAfterFailure.fetch_add(1, std::memory_order_relaxed); | ||
| 146 | + }); | ||
| 147 | + } | ||
| 148 | + | ||
| 149 | + EXPECT_THROW(ParallelExecuteAndWait(4, std::move(tasks)), std::runtime_error); | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +} // namespace npu::tile_fwk | ||
| @@ -29,43 +29,11 @@ public: | |||
| 29 | void TearDown() override {} | 29 | void TearDown() override {} |
| 30 | }; | 30 | }; |
| 31 | 31 | ||
| 32 | -TEST_F(TestOpInfoManager, SetAndGetOpTilingKey) | 32 | +TEST_F(TestOpInfoManager, GetOpTilingKeyDefault) |
| 33 | { | 33 | { |
| 34 | auto& mgr = OpInfoManager::GetInstance(); | 34 | auto& mgr = OpInfoManager::GetInstance(); |
| 35 | - uint64_t key = 0x123456789ABCDULL; | 35 | + EXPECT_EQ(mgr.GetOpTilingKey(), DEFAULT_OP_TILING_KEY); |
| 36 | - mgr.SetOpTilingKey(key); | 36 | + EXPECT_EQ(mgr.GetOpTilingKey(), 0UL); |
| 37 | - uint64_t result = mgr.GetOpTilingKey(); | ||
| 38 | - EXPECT_EQ(result, key & MAIN_KEY_MASK); | ||
| 39 | -} | ||
| 40 | - | ||
| 41 | -TEST_F(TestOpInfoManager, SetOpTilingKeyMasked) | ||
| 42 | -{ | ||
| 43 | - auto& mgr = OpInfoManager::GetInstance(); | ||
| 44 | - uint64_t keyWithSub = 0xFFF123456789ABCDULL; | ||
| 45 | - mgr.SetOpTilingKey(keyWithSub); | ||
| 46 | - uint64_t result = mgr.GetOpTilingKey(); | ||
| 47 | - EXPECT_EQ(result, keyWithSub & MAIN_KEY_MASK); | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | -TEST_F(TestOpInfoManager, GetNewSubTilingKeyIncrementing) | ||
| 51 | -{ | ||
| 52 | - auto& mgr = OpInfoManager::GetInstance(); | ||
| 53 | - mgr.SetOpTilingKey(100); | ||
| 54 | - uint64_t k1 = mgr.GetNewSubTilingKey(); | ||
| 55 | - uint64_t k2 = mgr.GetNewSubTilingKey(); | ||
| 56 | - EXPECT_NE(k1, k2); | ||
| 57 | - uint64_t mainKey = 100 & MAIN_KEY_MASK; | ||
| 58 | - EXPECT_EQ(k1 & MAIN_KEY_MASK, mainKey); | ||
| 59 | - EXPECT_EQ(k2 & MAIN_KEY_MASK, mainKey); | ||
| 60 | -} | ||
| 61 | - | ||
| 62 | -TEST_F(TestOpInfoManager, GetCurSubTilingKeyNoIncrement) | ||
| 63 | -{ | ||
| 64 | - auto& mgr = OpInfoManager::GetInstance(); | ||
| 65 | - mgr.SetOpTilingKey(200); | ||
| 66 | - uint64_t k1 = mgr.GetCurSubTilingKey(); | ||
| 67 | - uint64_t k2 = mgr.GetCurSubTilingKey(); | ||
| 68 | - EXPECT_EQ(k1, k2); | ||
| 69 | } | 37 | } |
| 70 | 38 | ||
| 71 | TEST_F(TestOpInfoManager, SetAndGetOpType) | 39 | TEST_F(TestOpInfoManager, SetAndGetOpType) |
| @@ -118,14 +86,3 @@ TEST_F(TestOpInfoManager, SetAndGetControlBinHandle) | |||
| 118 | EXPECT_NE(result, nullptr); | 86 | EXPECT_NE(result, nullptr); |
| 119 | mgr.GetCustomOpJsonPath() = ""; | 87 | mgr.GetCustomOpJsonPath() = ""; |
| 120 | } | 88 | } |
| 121 | - | ||
| 122 | -TEST_F(TestOpInfoManager, SubTilingKeyComposition) | ||
| 123 | -{ | ||
| 124 | - auto& mgr = OpInfoManager::GetInstance(); | ||
| 125 | - mgr.SetOpTilingKey(0xABC); | ||
| 126 | - uint64_t composite = mgr.GetNewSubTilingKey(); | ||
| 127 | - uint64_t mainPart = composite & MAIN_KEY_MASK; | ||
| 128 | - uint64_t subPart = (composite & SUB_KEY_MASK) >> SUB_KEY_OFFSET; | ||
| 129 | - EXPECT_EQ(mainPart, 0xABC & MAIN_KEY_MASK); | ||
| 130 | - EXPECT_GE(subPart, 1u); | ||
| 131 | -} | ||
| @@ -515,7 +515,9 @@ def set_debug_options( | |||
| 515 | 0: disabled; | 515 | 0: disabled; |
| 516 | 1: enabled, one-click to enable graph compilation related configs (e.g. compute graph); | 516 | 1: enabled, one-click to enable graph compilation related configs (e.g. compute graph); |
| 517 | 2: enabled, one-click to enable fixed CCE (fix device-side code output path, | 517 | 2: enabled, one-click to enable fixed CCE (fix device-side code output path, |
| 518 | - do not overwrite existing CCE files, single-thread compilation). | 518 | + do not overwrite existing CCE files). Parallel compile threads are still |
| 519 | + controlled by codegen.parallel_compile; kernel names are deterministically | ||
| 520 | + assigned so multi-thread codegen outputs remain reproducible. | ||
| 519 | 521 | ||
| 520 | runtime_debug_mode : int | 522 | runtime_debug_mode : int |
| 521 | Whether to enable debug mode during execution stage. | 523 | Whether to enable debug mode during execution stage. |
为啥要限制32位?64位不行吗?