Merged
feat(Pass): Assume_divisible for dual_dst #5527
feat(Pass): Assume_divisible for dual_dst #5527
Merged
gggxinmengAdd on Aug 18
Total: 29 files changed+1898-702
@@ -208,6 +208,7 @@
208 - [pypto.view](tensor_api/operation/pypto-view.md)208 - [pypto.view](tensor_api/operation/pypto-view.md)
209 - [pypto.where](tensor_api/operation/pypto-where.md)209 - [pypto.where](tensor_api/operation/pypto-where.md)
210 - [pypto.zeros](tensor_api/operation/pypto-zeros.md)210 - [pypto.zeros](tensor_api/operation/pypto-zeros.md)
211+ - [pypto.experimental.assume_divisible](tensor_api/operation/pypto-experimental-assume_divisible.md)
211 - [数据类型](tensor_api/datatype/index.md)212 - [数据类型](tensor_api/datatype/index.md)
212 - [CachePolicy](tensor_api/datatype/CachePolicy.md)213 - [CachePolicy](tensor_api/datatype/CachePolicy.md)
213 - [CastMode](tensor_api/datatype/CastMode.md)214 - [CastMode](tensor_api/datatype/CastMode.md)
@@ -31,7 +31,7 @@ set_debug_options(*,
31| 参数名 | 输入/输出 | 说明 |31| 参数名 | 输入/输出 | 说明 |
32|----------------------|-----------|----------------------------------------------------------------------|32|----------------------|-----------|----------------------------------------------------------------------|
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 |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 内存越界检查,并在控制流入口对每个由用户显式登记并规范化后的 `assume_divisible` 假设表达式生成运行时整除断言;生成代码使用实际运行时值计算表达式,未显式登记的编译器推导表达式不检查; <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 
37## 返回值说明37## 返回值说明
@@ -50,6 +50,7 @@ pypto-exp
50pypto-exp250pypto-exp2
51pypto-expand_clone51pypto-expand_clone
52pypto-expand_exp_dif52pypto-expand_exp_dif
53+pypto-experimental-assume_divisible
53pypto-experimental-gather_in_l154pypto-experimental-gather_in_l1
54pypto-experimental-gather_in_ub55pypto-experimental-gather_in_ub
55pypto-experimental-get_operation_options56pypto-experimental-get_operation_options
@@ -0,0 +1,51 @@
1+# pypto.experimental.assume_divisible
2+ 
lyz0328
lyz0328lyz0328Sep 8

新增接口需要同步修改docs/zh/api/index_hiascend.md

likedislike
gggxinmeng
gggxinmeng
Sep 8 Comments:
likedislike
3+## 产品支持情况
4+ 
5+<!-- npu="950" id1 -->
6+- Ascend 950PR/Ascend 950DT:支持
7+<!-- end id1 -->
8+<!-- npu="A3" id2 -->
9+- Atlas A3 训练系列产品/Atlas A3 推理系列产品:支持
10+<!-- end id2 -->
11+<!-- npu="910b" id3 -->
12+- Atlas A2 训练系列产品/Atlas A2 推理系列产品:支持
13+<!-- end id3 -->
14+ 
15+## 功能说明
16+ 
17+声明符号标量表达式在运行时一定可以被指定整数整除。该接口返回表示expr的SymbolicScalar:SymbolicScalar输入原样返回,int输入会转换为SymbolicScalar。同时,接口在Program上注册规范化后的编译优化假设。例如,已知动态长度vm是tile大小的整数倍时,编译器可据此化简逐tile的动态valid_shape,从而使能dualdst等依赖静态valid shape的优化。
18+ 
lyz0328
lyz0328lyz0328Sep 8

接口或参数统一不使用上引号包裹

likedislike
gggxinmeng
gggxinmeng
Sep 8 Comments:
likedislike
19+## 函数原型
20+ 
21+```python
22+assume_divisible(expr: SymbolicScalar | int, divisor: int) -> SymbolicScalar
23+```
24+ 
25+## 参数说明
26+ 
27+| 参数名 | 输入/输出 | 说明 |
28+|---|---|---|
29+| expr | 输入 | 要声明整除关系的符号标量表达式或整数常量。 |
30+| divisor | 输入 | 整除因子,必须为正整数。 |
31+ 
32+## 返回值说明
33+ 
34+返回表示expr的SymbolicScalar。SymbolicScalar输入原样返回,int输入会转换为SymbolicScalar。
35+ 
36+## 约束说明
37+ 
38+- 默认情况下,这是无运行时检查的语义契约。用户必须保证运行时始终满足expr % divisor == 0;违约可能导致静默错误结果。
39+- 开启runtime_debug_mode=4后,编译器会将每个由用户显式登记并规范化后的假设表达式转换为控制流入口处的取模断言;生成代码使用实际运行时值计算该表达式,违约时报错。未通过assume_divisible显式登记的编译器推导表达式不检查。
40+- 接口只提供优化信息,不改变expr的值,也不会将动态表达式替换为divisor。
41+- 假设在Program上登记,同一Program中的所有Function均可查询。
42+- 编译期常量不能整除时会抛出ValueError;可以整除时为平凡no-op。
43+- divisor <= 0时会抛出ValueError。
44+ 
45+## 调用示例
46+ 
47+```python
48+tile_m = 128
49+valid_m = pypto.experimental.assume_divisible(a.shape[0], tile_m)
50+tile = pypto.view(mm, [tile_m, 128], [0, 0], valid_shape=[valid_m, 128])
51+```
@@ -33,6 +33,8 @@ view(input: Tensor, shape: List[int] = None, offsets: List[Union[int, SymbolicSc
33| valid_shape | 输入 | 取出视图块的有效数据大小。<br>需要保证valid_shape小于input的Shape;在类似page_attention场景下,当输入的kv_cache等张量包含无效数据时,无法正确推导输出的validshape,需要手动传入; |33| valid_shape | 输入 | 取出视图块的有效数据大小。<br>需要保证valid_shape小于input的Shape;在类似page_attention场景下,当输入的kv_cache等张量包含无效数据时,无法正确推导输出的validshape,需要手动传入; |
34| dtype | 输入 | 返回值的数据类型,允许将输入数据解读为不同数据类型 |34| dtype | 输入 | 返回值的数据类型,允许将输入数据解读为不同数据类型 |
35 35 
36+`valid_shape` 可以配合 `pypto.experimental.assume_divisible` 使用。当某个动态标量已知可被 tile shape 整除时,可通过 `assume_divisible` 声明该事实,帮助编译器消除该轴逐 tile 动态 valid shape,使能 dualdst 等依赖静态 valid shape 的优化。
37+ 
36## 返回值说明38## 返回值说明
37 39 
38返回输出Tensor,Tensor的数据类型和input相同,Shape为参数shape指定大小,若指定了valid\_shape,则真实大小为valid\_shape。若指定dtype,则会将输入按照dtype进行读取。40返回输出Tensor,Tensor的数据类型和input相同,Shape为参数shape指定大小,若指定了valid\_shape,则真实大小为valid\_shape。若指定dtype,则会将输入按照dtype进行读取。
@@ -583,8 +583,8 @@
583 "runtime_debug_mode": {583 "runtime_debug_mode": {
584 "type": "integer",584 "type": "integer",
585 "label": {585 "label": {
586- "zh": "设置执行阶段调试模式。0:不使能;1:使能,一键开启图执行相关配置(如泳道图);2:使能,一键开启端到端Host侧仿真;3:使能,运行时依赖正确性校验数据 dump;4:使能, 运行时GM内存越界检查",586+ "zh": "设置执行阶段调试模式。0:不使能;1:使能,一键开启图执行相关配置(如泳道图);2:使能,一键开启端到端Host侧仿真;3:使能,运行时依赖正确性校验数据 dump;4:使能,运行时GM内存越界检查,并在控制流入口对每个由用户显式登记并规范化后的assume_divisible假设表达式生成取模断言;未显式登记的编译器推导表达式不检查",
587- "en": "Set debug mode during execution stage. 0: disabled; 1: enabled, one-click to enable execution-related configs (e.g. swimlane graph); 2: enable, One-click start of end-to-end host-side simulation; 3: enable, runtime dependency-verification data dump; 4: enable, runtime GM memory out-of-bounds check."587+ "en": "Set debug mode during execution stage. 0: disabled; 1: enabled, one-click to enable execution-related configs (e.g. swimlane graph); 2: enable, One-click start of end-to-end host-side simulation; 3: enable, runtime dependency-verification data dump; 4: enable, runtime GM memory out-of-bounds checks and emit modulo assertions at the control-flow entry for every explicitly registered, normalized assume_divisible expression; compiler-derived expressions that were not explicitly registered are not checked."
588 },588 },
589 "minimum": 0,589 "minimum": 0,
590 "maximum": 4590 "maximum": 4
@@ -16,7 +16,6 @@
16#include "rebuildable_attribute.h"16#include "rebuildable_attribute.h"
17 17 
18#include "tilefwk/pypto_fwk_log.h"18#include "tilefwk/pypto_fwk_log.h"
19-#include "interface/function/function.h"
20 19 
21namespace npu::tile_fwk {20namespace npu::tile_fwk {
22 21 
@@ -94,6 +94,8 @@ public:
94 attrDict_[func][name] = base;94 attrDict_[func][name] = base;
95 }95 }
96 96 
97+ void Clear() { attrDict_.clear(); }
98+ 
97 RebuildableAttributeManager() = default;99 RebuildableAttributeManager() = default;
98 100 
99private:101private:
@@ -15,6 +15,7 @@
15 15 
16#include <sstream>16#include <sstream>
17#include <iostream>17#include <iostream>
18+#include <algorithm>
18#include <fstream>19#include <fstream>
19#include <unordered_set>20#include <unordered_set>
20 21 
@@ -92,6 +93,7 @@ void Program::Reset()
92 IRContext::Get().Reset();93 IRContext::Get().Reset();
93 ResetTensorSlotManager();94 ResetTensorSlotManager();
94 // KernelBinary::pinnedGraph_ holds shared_ptr refs; clearing the map must not ~Function.95 // KernelBinary::pinnedGraph_ holds shared_ptr refs; clearing the map must not ~Function.
96+ divisibleAssumptions_.clear();
95 functionmap_.clear();97 functionmap_.clear();
96 functionMagicNameStack_.clear();98 functionMagicNameStack_.clear();
97 currentFunctionMagicName_ = PROGRAM_ENTRY_FUNCTION_NAME;99 currentFunctionMagicName_ = PROGRAM_ENTRY_FUNCTION_NAME;
@@ -820,4 +822,27 @@ std::shared_ptr<Function> Program::GetFunctionSharedPtr(Function* rawPtr)
820 FE_LOGW("not find function ptr in function map");822 FE_LOGW("not find function ptr in function map");
821 return nullptr;823 return nullptr;
822}824}
825+ 
826+void Program::RegisterDivisibleAssumption(const SymbolicScalar& expr, int64_t divisor)
827+{
828+ const auto normalizedExpr = expr.Simplify();
829+ const auto key = normalizedExpr.Dump();
830+ auto it = divisibleAssumptions_.try_emplace(key, DivisibleAssumption{normalizedExpr, {}}).first;
831+ it->second.divisors.insert(divisor);
832+}
833+ 
834+bool Program::IsKnownDivisible(const SymbolicScalar& expr, int64_t divisor) const
835+{
836+ if (divisor <= 0) {
837+ return false;
838+ }
839+ if (expr.ConcreteValid()) {
840+ return expr.Concrete() % divisor == 0;
841+ }
842+ const auto key = expr.Simplify().Dump();
843+ const auto it = divisibleAssumptions_.find(key);
844+ return it != divisibleAssumptions_.end() && std::any_of(it->second.divisors.begin(), it->second.divisors.end(),
845+ [divisor](int64_t d) { return d % divisor == 0; });
846+}
847+ 
823} // namespace npu::tile_fwk848} // namespace npu::tile_fwk
@@ -15,6 +15,8 @@
15 15 
16#pragma once16#pragma once
17 17 
18+#include <set>
19+#include <unordered_map>
18#include "interface/function/function.h"20#include "interface/function/function.h"
19#include "interface/cache/function_cache.h"21#include "interface/cache/function_cache.h"
20 22 
@@ -25,6 +27,11 @@
25namespace npu::tile_fwk {27namespace npu::tile_fwk {
26class ConfigScope;28class ConfigScope;
27 29 
30+struct DivisibleAssumption {
31+ SymbolicScalar expression;
32+ std::set<int64_t> divisors;
33+};
34+ 
28class Program {35class Program {
29public: // public api for torch36public: // public api for torch
30 std::vector<Function*> functionSequence_;37 std::vector<Function*> functionSequence_;
@@ -126,6 +133,13 @@ public: // public api for torch
126 void ClearEmptyHiddenFunction();133 void ClearEmptyHiddenFunction();
127 void SetParamConfig(Function* func, const std::shared_ptr<ConfigScope>& configScope) const;134 void SetParamConfig(Function* func, const std::shared_ptr<ConfigScope>& configScope) const;
128 135 
136+ void RegisterDivisibleAssumption(const SymbolicScalar& expr, int64_t divisor);
137+ bool IsKnownDivisible(const SymbolicScalar& expr, int64_t divisor) const;
138+ const std::unordered_map<std::string, DivisibleAssumption>& GetDivisibleAssumptions() const
139+ {
140+ return divisibleAssumptions_;
141+ }
142+ 
129private:143private:
130 std::string name_;144 std::string name_;
131 std::vector<std::string> functionMagicNameStack_;145 std::vector<std::string> functionMagicNameStack_;
@@ -137,6 +151,7 @@ private:
137 FunctionCache functionCache_;151 FunctionCache functionCache_;
138 std::unordered_set<Tensor*> aliveTensors_;152 std::unordered_set<Tensor*> aliveTensors_;
139 std::map<std::string, std::shared_ptr<npu::tile_fwk::Function>> functionmap_;153 std::map<std::string, std::shared_ptr<npu::tile_fwk::Function>> functionmap_;
154+ std::unordered_map<std::string, DivisibleAssumption> divisibleAssumptions_;
140 155 
141 void CreateInitFunction();156 void CreateInitFunction();
142 Operation* FinishCurrentFunction(const std::shared_ptr<TensorSlotScope>& scope, bool generateCall);157 Operation* FinishCurrentFunction(const std::shared_ptr<TensorSlotScope>& scope, bool generateCall);
@@ -778,6 +778,10 @@ int GetRootFuncNum(std::shared_ptr<DyndevFunctionAttribute> attr)
778static void CollectExpressions(IrBackendContext& ctx, FunctionCache& cache, Linker& linker, Function* function,778static void CollectExpressions(IrBackendContext& ctx, FunctionCache& cache, Linker& linker, Function* function,
779 bool useNewIr)779 bool useNewIr)
780{780{
781+ for (const auto& [key, assumption] : Program::GetInstance().GetDivisibleAssumptions()) {
782+ (void)key;
783+ linker.GetSymbolTable()->AddSymbolFromExpression(assumption.expression);
784+ }
781 if (useNewIr) {785 if (useNewIr) {
782 MACHINE_LOGI("BuildControlFlow: using new SCF IR traversal");786 MACHINE_LOGI("BuildControlFlow: using new SCF IR traversal");
783 FindAllExpressionFromIR(ctx, cache, linker, function);787 FindAllExpressionFromIR(ctx, cache, linker, function);
@@ -15,6 +15,7 @@
15#include <unordered_set>15#include <unordered_set>
16 16 
17#include "interface/configs/config_manager.h"17#include "interface/configs/config_manager.h"
18+#include "interface/program/program.h"
18#include "interface/machine/device/tilefwk/core_func_data.h"19#include "interface/machine/device/tilefwk/core_func_data.h"
19#include "interface/operation/operation.h"20#include "interface/operation/operation.h"
20#include "interface/program/program.h"21#include "interface/program/program.h"
@@ -275,6 +276,7 @@ void BuildControlFlowDynamic(ControlFlowEmitCtx& ctx, Function* func, int indent
275 if (NeedCrossDie(func)) {276 if (NeedCrossDie(func)) {
276 ctx.controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "RUNTIME_RootGetDieId(" << 0 << ");\n";277 ctx.controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "RUNTIME_RootGetDieId(" << 0 << ");\n";
277 }278 }
279+ EmitAssumeDivisibleChecks(ctx, indent + 1);
278 for (auto& callee : GetCalleeList(ctx.cache, func)) {280 for (auto& callee : GetCalleeList(ctx.cache, func)) {
279 BuildControlFlow(ctx, callee, indent + 1);281 BuildControlFlow(ctx, callee, indent + 1);
280 }282 }
@@ -296,6 +298,39 @@ const std::unordered_map<std::string, std::string>* GetInputCseMap(const Control
296 return nullptr;298 return nullptr;
297}299}
298 300 
301+void EmitAssumeDivisibleChecks(ControlFlowEmitCtx& ctx, int indent)
302+{
303+ // Mode 4 emits host-side modulo checks for every explicitly registered assumption. The expression is normalized
304+ // when registered and lowered here to ordinary C/C++; runtime executes it with the actual dynamic values.
305+ if (config::GetDebugOption<int64_t>(CFG_RUNTIME_DBEUG_MODE) != CFG_RUNTIME_DEBUG_GM_OUT_OF_BOUNDS) {
306+ return;
307+ }
308+ 
309+ const auto& assumptions = Program::GetInstance().GetDivisibleAssumptions();
310+ const auto* getInputCseMap = GetInputCseMap(ctx);
311+ std::vector<std::string> keys;
312+ keys.reserve(assumptions.size());
313+ for (const auto& [key, assumption] : assumptions) {
314+ (void)assumption;
315+ keys.push_back(key);
316+ }
317+ std::sort(keys.begin(), keys.end());
318+ for (const auto& key : keys) {
319+ const auto& assumption = assumptions.at(key);
320+ const auto& expression = assumption.expression;
321+ if (!expression.IsValid()) {
322+ continue;
323+ }
324+ const std::string runtimeValue = SymbolicExpressionTable::BuildExpression(expression.Raw(), getInputCseMap);
325+ for (const int64_t divisor : assumption.divisors) {
326+ ctx.controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "if ((" << runtimeValue << " % " << divisor
327+ << ") != 0) {\n";
328+ ctx.controlFlowOss << std::setw((indent + 1) * TABSIZE) << ' ' << "__builtin_trap();\n";
329+ ctx.controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "}\n";
330+ }
331+ }
332+}
333+ 
299void EmitDynloopCondTree(ControlFlowEmitCtx& ctx, const std::shared_ptr<DynloopFunctionPathNode>& node, int condIndent)334void EmitDynloopCondTree(ControlFlowEmitCtx& ctx, const std::shared_ptr<DynloopFunctionPathNode>& node, int condIndent)
300{335{
301 if (!node->cond.IsValid()) {336 if (!node->cond.IsValid()) {
@@ -335,7 +370,6 @@ void EmitDynamicLoopOpen(ControlFlowEmitCtx& ctx, Function* func, const std::sha
335 }370 }
336 MarkValueDependDisableCache(ctx, func);371 MarkValueDependDisableCache(ctx, func);
337 InsertWaitCoreStartForLoopBounds(attr, ctx.controlFlowOss, ctx.valDependTensorMeta, indent);372 InsertWaitCoreStartForLoopBounds(attr, ctx.controlFlowOss, ctx.valDependTensorMeta, indent);
338- 
339 const auto* getInputCseMap = GetInputCseMap(ctx);373 const auto* getInputCseMap = GetInputCseMap(ctx);
340 const std::string iterVar = "VAR_" + attr->iterSymbolName;374 const std::string iterVar = "VAR_" + attr->iterSymbolName;
341 const std::string iterBegin = SymbolicExpressionTable::BuildExpression(attr->Begin().Raw(), getInputCseMap);375 const std::string iterBegin = SymbolicExpressionTable::BuildExpression(attr->Begin().Raw(), getInputCseMap);
@@ -46,6 +46,8 @@ struct ControlFlowEmitCtx {
46 46 
47void BuildControlFlow(ControlFlowEmitCtx& ctx, Function* func, int indent);47void BuildControlFlow(ControlFlowEmitCtx& ctx, Function* func, int indent);
48 48 
49+void EmitAssumeDivisibleChecks(ControlFlowEmitCtx& ctx, int indent);
50+ 
49void GenerateExpression(SymbolicExpressionTable* exprTable, int devRootKey, const std::string& expName,51void GenerateExpression(SymbolicExpressionTable* exprTable, int devRootKey, const std::string& expName,
50 std::vector<std::string>& exprSrcFiles, std::ostringstream& controlFlowOss,52 std::vector<std::string>& exprSrcFiles, std::ostringstream& controlFlowOss,
51 std::ostringstream& exprHeaderOss, int indent, const GetInputCse* getInputCse);53 std::ostringstream& exprHeaderOss, int indent, const GetInputCse* getInputCse);
@@ -478,6 +478,12 @@ void BuildControlFlowFromIR(IrBackendContext& ctx, FunctionCache& cache, Linker&
478 controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "RUNTIME_RootGetDieId(" << 0 << ");\n";478 controlFlowOss << std::setw(indent * TABSIZE) << ' ' << "RUNTIME_RootGetDieId(" << 0 << ");\n";
479 }479 }
480 480 
481+ ControlFlowEmitCtx cfCtx{cache, linker, sectionName, slotIdxMapping,
482+ group, rootTileDict, controlFlowOss, expressionOss,
483+ exprHeaderOss, expName, exprSrcFiles, valDependTensorMeta,
484+ ctx.getInputCse};
485+ EmitAssumeDivisibleChecks(cfCtx, indent + 1);
486+ 
481 if (func->body_ != nullptr) {487 if (func->body_ != nullptr) {
482 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, func->body_, func, slotIdxMapping, group,488 VisitIRStmtForControlFlow(ctx, cache, linker, sectionName, func->body_, func, slotIdxMapping, group,
483 rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent + 1, expName,489 rootTileDict, controlFlowOss, expressionOss, exprHeaderOss, indent + 1, expName,
@@ -578,14 +578,18 @@ void DualDstEngine::SetDualDstCopyAttr(Operation* C, LogicalTensorPtr l0cIn, con
578 int64_t direction = dualDstL0CDirection_.count(l0cIn) ? dualDstL0CDirection_[l0cIn] : 0;578 int64_t direction = dualDstL0CDirection_.count(l0cIn) ? dualDstL0CDirection_[l0cIn] : 0;
579 std::vector<int64_t> realShape = (direction == 0) ? std::vector<int64_t>{eM + lM, eN} :579 std::vector<int64_t> realShape = (direction == 0) ? std::vector<int64_t>{eM + lM, eN} :
580 std::vector<int64_t>{eM, eN + lN};580 std::vector<int64_t>{eM, eN + lN};
581- std::vector<SymbolicScalar> validShape;581+ auto validShape = attrE->GetToDynValidShape();
582- validShape.reserve(realShape.size());582+ if (validShape.size() != kCopyUbGeometryDimCount) {
583- for (auto dim : realShape)583+ validShape = OpImmediate::Specified(realShape);
584- validShape.push_back(SymbolicScalar(dim));584+ } else {
585+ // Only the split axis becomes the combined full tile. The orthogonal
586+ // axis may still be dynamic and must keep the original valid shape.
587+ validShape[direction] = OpImmediate::Specified(realShape[direction]);
588+ }
585 589 
586 auto copyAttr = std::make_shared<CopyOpAttribute>(590 auto copyAttr = std::make_shared<CopyOpAttribute>(
587 attrE->GetFromOffset(), p.tensorEarly->GetMemoryTypeOriginal(), OpImmediate::Specified(realShape),591 attrE->GetFromOffset(), p.tensorEarly->GetMemoryTypeOriginal(), OpImmediate::Specified(realShape),
588- OpImmediate::Specified(l0cIn->tensor->GetDynRawShape()), OpImmediate::Specified(validShape));592+ OpImmediate::Specified(l0cIn->tensor->GetDynRawShape()), validShape);
589 copyAttr->SetToOffset(attrE->GetToOffset());593 copyAttr->SetToOffset(attrE->GetToOffset());
590 C->SetOpAttribute(copyAttr);594 C->SetOpAttribute(copyAttr);
591 C->SetAttribute(OpAttributeKey::splitMN, direction);595 C->SetAttribute(OpAttributeKey::splitMN, direction);
@@ -14,7 +14,10 @@
14 */14 */
15 15 
16#include <queue>16#include <queue>
17+#include <optional>
17#include "interface/function/function.h"18#include "interface/function/function.h"
19+#include "interface/program/program.h"
20+#include "interface/operation/attribute.h"
18#include "infer_dyn_shape.h"21#include "infer_dyn_shape.h"
19#include "passes/pass_check/infer_dyn_shape_checker.h"22#include "passes/pass_check/infer_dyn_shape_checker.h"
20#include "passes/pass_log/pass_log.h"23#include "passes/pass_log/pass_log.h"
@@ -24,6 +27,264 @@
24 27 
25namespace npu {28namespace npu {
26namespace tile_fwk {29namespace tile_fwk {
30+using RawPtr = RawSymbolicScalarPtr;
31+ 
32+// 从 SymbolicScalar 节点中提取立即数值。
33+static std::optional<int64_t> GetImmediate(const RawPtr& raw)
34+{
35+ if (raw != nullptr && raw->IsImmediate()) {
36+ return raw->GetImmediateValue();
37+ }
38+ return std::nullopt;
39+}
40+ 
41+// 判断表达式节点是否为指定的 SymbolicScalar 操作码。
42+static bool IsOpcode(const RawPtr& raw, SymbolicOpcode opcode)
43+{
44+ return raw != nullptr && raw->IsExpression() && raw->GetExpressionOpcode() == opcode;
45+}
46+ 
47+// 从二元 min/max 表达式中拆出立即数和另一个操作数。
48+static bool SplitExtremaWithImmediate(const RawPtr& raw, SymbolicOpcode opcode, int64_t immediate, RawPtr& other)
49+{
50+ if (!IsOpcode(raw, opcode)) {
51+ return false;
52+ }
53+ const auto& operands = raw->GetExpressionOperandList();
54+ if (operands.size() != 2) {
55+ return false;
56+ }
57+ if (GetImmediate(operands[0]) == immediate) {
58+ other = operands[1];
59+ return true;
60+ }
61+ if (GetImmediate(operands[1]) == immediate) {
62+ other = operands[0];
63+ return true;
64+ }
65+ return false;
66+}
67+ 
68+// 匹配 min(value, upper),其中 upper 必须是立即数。
69+static bool ExtractMinWithUpper(const RawPtr& raw, RawPtr& value, int64_t& upper)
70+{
71+ if (!IsOpcode(raw, SymbolicOpcode::T_MOP_MIN)) {
72+ return false;
73+ }
74+ const auto& operands = raw->GetExpressionOperandList();
75+ if (operands.size() != 2) {
76+ return false;
77+ }
78+ if (auto immediate = GetImmediate(operands[0]); immediate.has_value()) {
79+ upper = *immediate;
80+ value = operands[1];
81+ return true;
82+ }
83+ if (auto immediate = GetImmediate(operands[1]); immediate.has_value()) {
84+ upper = *immediate;
85+ value = operands[0];
86+ return true;
87+ }
88+ return false;
89+}
90+ 
91+// 化简正确性依赖以下三个前提,均由 assume_divisible API 契约和 Tile Graph 展开方式共同保证:
92+// 1. 用户通过 assume_divisible(vm, T) 显式声明 vm % T == 0;
93+// 2. 循环展开采用 ceil 除法 count = ceil(vm / T),当 vm % T == 0 时 count = vm / T;
94+// 3. 循环条件 idx ∈ [0, count),即 idx * T < vm,因此 vm - idx * T >= T > 0。
95+// unroll 展开不破坏该前提:展开范围向下取整到 unroll 倍数 (count / unroll * unroll),
96+// 保证展开内每个 tile 对应的 idx + n < count,即 vm - (idx + n) * T >= T。
97+// 综上,每次执行的迭代中 vm - idx * T >= T,min(vm - idx * T, cap) = cap(cap <= T 的倍数),
98+// cap 恒等于实际值,化简为常量是安全的。
99+// 若用户未注册 assume_divisible,SimplifyAllValidShapes 的门禁会跳过化简,
100+// 避免 cap 不等于实际值时错误化简。
101+ 
102+// 递归查询表达式是否能够被 divisor 整除。
103+// 该查询同时消费 Program 中登记的假设和加减乘的结构信息。
104+static constexpr size_t MAX_DIVISIBLE_RECURSION_DEPTH = 64;
105+ 
106+static bool IsExprDivisible(const Function& function, const SymbolicScalar& expr, int64_t divisor, size_t depth = 0)
107+{
108+ if (depth >= MAX_DIVISIBLE_RECURSION_DEPTH) {
109+ return false;
110+ }
111+ if (Program::GetInstance().IsKnownDivisible(expr, divisor)) {
112+ return true;
113+ }
114+ const auto raw = expr.Raw();
115+ if (!raw || !raw->IsExpression()) {
116+ return false;
117+ }
118+ const auto opcode = raw->GetExpressionOpcode();
119+ const auto& operands = raw->GetExpressionOperandList();
120+ if ((opcode == SymbolicOpcode::T_BOP_ADD || opcode == SymbolicOpcode::T_BOP_SUB) && operands.size() == 2) {
121+ return IsExprDivisible(function, SymbolicScalar(operands[0]), divisor, depth + 1) &&
122+ IsExprDivisible(function, SymbolicScalar(operands[1]), divisor, depth + 1);
123+ }
124+ if (opcode == SymbolicOpcode::T_BOP_MUL && operands.size() == 2) {
125+ return IsExprDivisible(function, SymbolicScalar(operands[0]), divisor, depth + 1) ||
126+ IsExprDivisible(function, SymbolicScalar(operands[1]), divisor, depth + 1);
127+ }
128+ return false;
129+}
130+ 
131+// 证明 value - accumulatedOffset 至少包含一个完整 tile。
132+// View valid shape 表达式形如 min(max(min(vm - idx*T, cap) - offset, 0), tile),
133+// 其中 cap = (n+1)*T,offset = n*T,n 为展开内第 n 个子 tile。
134+// 根据上述化简前提,循环条件保证 vm - idx*T >= T,因此:
135+// - 展开内第 n 个子 tile 满足 vm - (idx+n)*T >= T,即 vm - idx*T >= (n+1)*T = cap;
136+// - min(vm - idx*T, cap) = cap(cap 为上界且实际值 >= cap);
137+// - cap - accumulatedOffset = (n+1)*T - n*T = T >= tile。
138+// 沿表达式树递归下沉 offset,不假设当前 cap 属于哪一层 View。
139+// 递归深度上限 MAX_DIVISIBLE_RECURSION_DEPTH 防止深表达式栈溢出。
140+static bool IsFullTileAfterOffset(const Function& function, const RawPtr& raw, int64_t accumulatedOffset, int64_t tile,
141+ size_t depth = 0)
142+{
143+ if (raw == nullptr || tile <= 0 || depth >= MAX_DIVISIBLE_RECURSION_DEPTH) {
144+ return false;
145+ }
146+ 
147+ if (raw->IsExpression()) {
148+ const auto opcode = raw->GetExpressionOpcode();
149+ const auto& operands = raw->GetExpressionOperandList();
150+ if (operands.size() == 2 && opcode == SymbolicOpcode::T_BOP_SUB) {
151+ const auto delta = GetImmediate(operands[1]);
152+ if (delta.has_value() && *delta >= 0) {
153+ return IsFullTileAfterOffset(function, operands[0], accumulatedOffset + *delta, tile, depth + 1);
154+ }
155+ }
156+ if (operands.size() == 2 && opcode == SymbolicOpcode::T_BOP_ADD) {
157+ for (size_t valueIndex = 0; valueIndex < operands.size(); ++valueIndex) {
158+ const auto delta = GetImmediate(operands[1 - valueIndex]);
159+ if (delta.has_value() && *delta <= 0) {
160+ return IsFullTileAfterOffset(function, operands[valueIndex], accumulatedOffset - *delta, tile,
161+ depth + 1);
162+ }
163+ }
164+ }
165+ 
166+ RawPtr value;
167+ int64_t cap = 0;
168+ if (ExtractMinWithUpper(raw, value, cap)) {
169+ // min(value, cap) - accumulatedOffset >= tile 时,两个分支
170+ // 都必须达到同一个 tile 下界。
171+ const int64_t remainingCap = cap - accumulatedOffset;
172+ if (remainingCap < tile || remainingCap % tile != 0) {
173+ APASS_LOG_DEBUG_F(
174+ Elements::Function,
175+ "[AssumeDivisible][CapFail] func=%s expr=%s cap=%ld offset=%ld tile=%ld remaining=%ld",
176+ function.GetMagicName().c_str(), SymbolicScalar(raw).Dump().c_str(), cap, accumulatedOffset, tile,
177+ remainingCap);
178+ return false;
179+ }
180+ return IsFullTileAfterOffset(function, value, accumulatedOffset, tile, depth + 1);
181+ }
182+ }
183+ 
184+ // 到达最内层源表达式(如 vm 或 vm - idx*T)后,由整除假设和累计 View offset 建立
185+ // tile 对齐的下界。循环条件 idx*T < vm 保证 vm - idx*T > 0,
186+ // 结合 vm % T == 0 可推导出 vm - idx*T >= T,化简安全。
187+ const bool divisible = IsExprDivisible(function, SymbolicScalar(raw), tile);
188+ const bool aligned = accumulatedOffset % tile == 0;
189+ if (!divisible || !aligned) {
190+ APASS_LOG_DEBUG_F(Elements::Function,
191+ "[AssumeDivisible][SourceFail] func=%s expr=%s tile=%ld divisible=%d offset=%ld aligned=%d",
192+ function.GetMagicName().c_str(), SymbolicScalar(raw).Dump().c_str(), tile, divisible ? 1 : 0,
193+ accumulatedOffset, aligned ? 1 : 0);
194+ }
195+ return divisible && aligned;
196+}
197+ 
198+// 将已经化简的 View/Slice output valid shape 同步回非空 attr,避免后续 InferShape 恢复旧表达式。
199+static void SyncViewValidShapeAttribute(Operation& op)
200+{
201+ if (op.GetOpcode() != Opcode::OP_VIEW && op.GetOpcode() != Opcode::OP_SLICE) {
202+ return;
203+ }
204+ auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(op.GetOpAttribute());
205+ if (viewAttr == nullptr) {
206+ return;
207+ }
208+ auto& validShape = viewAttr->GetToDynValidShape();
209+ if (validShape.empty() || op.GetOOperands().empty()) {
210+ return;
211+ }
212+ const auto& output = op.GetOOperands()[0];
213+ if (output == nullptr || output->GetDynValidShape().empty()) {
214+ return;
215+ }
216+ // View 构造时会将同一份 valid shape 同时写入 output 和 attr。
217+ // output 化简完成后同步更新 attr,避免 ViewInferFunc 恢复化简前的表达式。
218+ validShape = output->GetDynValidShape();
219+}
220+ 
221+// CopyInInferFunc 优先使用 output tensor 的 valid shape,但仅在 toDynValidShape 为空时回填 attr。
222+// 主动覆盖非空旧 attr,保证后续直接读取 CopyOpAttribute 的 codegen/pass 与 tensor 看到同一结果。
223+static void SyncCopyInValidShapeAttribute(Operation& op)
224+{
225+ if (op.GetOpcode() != Opcode::OP_COPY_IN) {
226+ return;
227+ }
228+ auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());
229+ if (copyAttr == nullptr || op.GetOOperands().empty()) {
230+ return;
231+ }
232+ const auto& output = op.GetOOperands()[0];
233+ if (output == nullptr || output->GetDynValidShape().empty()) {
234+ return;
235+ }
236+ copyAttr->SetToDynValidShape(OpImmediate::Specified(output->GetDynValidShape()));
zhangyuebing

【🟡 建议修改】SyncCopyInValidShapeAttribute 的"主动覆盖非空旧 attr"路径缺少 UT 看护

View 的 attr 同步路径已有 AssumeDivisible_SimplifiesExplicitViewValidShapeAttribute 覆盖,但 CopyIn 这条路径没有任何 UT:它改变了 CopyInInferFunc 原有"仅在 toDynValidShape 为空时回填"的语义(主动覆盖非空 attr),属于行为变化点,应有回归看护。建议补一个镜像 View 用例的测试:构造带非空 toDynValidShape 的 OP_COPY_IN + 注册假设的动态 valid shape,验证 RunOnFunction 后 attr 与 output tensor 均为化简值且一致。

另建议补一条混合用例:同一 function 内 VIEW + COPY_IN + L0C_COPY_UB 共存,一次 RunOnFunction 验证 SimplifyAllValidShapes → RecordStaticValidShapeOnL0CCopyUB → InferShape 的整体联动——目前三个环节各自只有单环节 UT,组合路径(尤其是 InferShape 不会从 attr 恢复旧表达式)未被端到端验证。

likedislike
gggxinmeng
gggxinmeng
Sep 4 Comments:
likedislike
237+}
238+ 
239+SymbolicScalar InferDynShape::SimplifyValidShapeWithAssumptions(const Function& function,
240+ const SymbolicScalar& shape) const
241+{
242+ const auto simplified = shape.Simplify();
243+ RawPtr clampedValue;
244+ int64_t tile = 0;
245+ if (!ExtractMinWithUpper(simplified.Raw(), clampedValue, tile) || tile <= 0) {
246+ return simplified;
247+ }
248+ RawPtr value = clampedValue;
249+ RawPtr nonNegativeValue;
250+ if (SplitExtremaWithImmediate(clampedValue, SymbolicOpcode::T_MOP_MAX, 0, nonNegativeValue)) {
251+ value = nonNegativeValue;
252+ }
253+ 
254+ // 递归下沉各层 View 的立即数 offset,并检查嵌套 min cap。
255+ // 同时支持 min(max(E, 0), tile) 和显式的 min(E, tile),
256+ // 覆盖直接 tile 以及父/子/孙 View。无法匹配的表达式保持不变。
257+ if (!IsFullTileAfterOffset(function, value, 0, tile)) {
258+ return simplified;
259+ }
260+ APASS_LOG_DEBUG_F(Elements::Function, "[AssumeDivisible][Simplified] func=%s expr=%s result=%ld",
261+ function.GetMagicName().c_str(), simplified.Dump().c_str(), tile);
262+ return SymbolicScalar(tile);
263+}
264+ 
265+// 只遍历 op 的 output tensor 做一次化简;相关 attr 只同步 output 的结果,不重复化简。
266+void InferDynShape::SimplifyAllValidShapes(Function& function)
267+{
268+ if (Program::GetInstance().GetDivisibleAssumptions().empty()) {
269+ return;
270+ }
271+ for (auto& op : function.Operations(false)) {
272+ for (const auto& outTensor : op.GetOOperands()) {
273+ if (outTensor == nullptr) {
274+ continue;
275+ }
276+ auto& validShape = outTensor->GetDynValidShape();
277+ if (validShape.empty()) {
278+ continue;
279+ }
280+ for (auto& dim : validShape) {
281+ dim = SimplifyValidShapeWithAssumptions(function, dim);
282+ }
283+ }
284+ SyncViewValidShapeAttribute(op);
285+ SyncCopyInValidShapeAttribute(op);
286+ }
287+}
27Status InferDynShape::PostCheck(Function& function)288Status InferDynShape::PostCheck(Function& function)
28{289{
29 InferDynShapeChecker checker;290 InferDynShapeChecker checker;
@@ -40,6 +301,7 @@ Status InferDynShape::RunOnFunction(Function& function)
40 // 在这一步之前先把 OP_L0C_COPY_UB 的 UB 输出 validShape 快照到 op 属性,301 // 在这一步之前先把 OP_L0C_COPY_UB 的 UB 输出 validShape 快照到 op 属性,
41 // 供 dualdst_fuse 在融合候选判定阶段优先使用。本函数与 InferShape 完全解耦,302 // 供 dualdst_fuse 在融合候选判定阶段优先使用。本函数与 InferShape 完全解耦,
42 // 不影响原有逻辑;若 op 输出 validShape 含动态成分则直接跳过 (回退 dyn 比较)。303 // 不影响原有逻辑;若 op 输出 validShape 含动态成分则直接跳过 (回退 dyn 比较)。
304+ SimplifyAllValidShapes(function);
43 RecordStaticValidShapeOnL0CCopyUB(function);305 RecordStaticValidShapeOnL0CCopyUB(function);
44 if (InferShapeUtils::InferShape(function) != SUCCESS) {306 if (InferShapeUtils::InferShape(function) != SUCCESS) {
45 APASS_LOG_ERROR_F(Elements::Function, "InferShape failed; Please check the InferShape method.");307 APASS_LOG_ERROR_F(Elements::Function, "InferShape failed; Please check the InferShape method.");
@@ -26,6 +26,8 @@ public:
26 ~InferDynShape() override {}26 ~InferDynShape() override {}
27 Status RunOnFunction(Function& function) override;27 Status RunOnFunction(Function& function) override;
28 Status PostCheck(Function& function) override;28 Status PostCheck(Function& function) override;
29+ SymbolicScalar SimplifyValidShapeWithAssumptions(const Function& function, const SymbolicScalar& shape) const;
30+ void SimplifyAllValidShapes(Function& function);
29 void RecordStaticValidShapeOnL0CCopyUB(Function& function);31 void RecordStaticValidShapeOnL0CCopyUB(Function& function);
30};32};
31} // namespace tile_fwk33} // namespace tile_fwk
@@ -31,12 +31,18 @@
31#include "interface/tensor/irbuilder.h"31#include "interface/tensor/irbuilder.h"
32#include "interface/utils/id_gen.h"32#include "interface/utils/id_gen.h"
33#include "machine/host/backend.h"33#include "machine/host/backend.h"
34+#include "machine/host/control_flow_codegen.h"
34#include "machine/host/expr_generator.h"35#include "machine/host/expr_generator.h"
35#include "machine/host/ir_backend.h"36#include "machine/host/ir_backend.h"
36#include "tilefwk/tilefwk.h"37#include "tilefwk/tilefwk.h"
37 38 
38using namespace npu::tile_fwk;39using namespace npu::tile_fwk;
39 40 
41+namespace npu::tile_fwk {
42+void EmitDynamicLoopOpen(ControlFlowEmitCtx& ctx, Function* func, const std::shared_ptr<DynloopFunctionAttribute>& attr,
43+ int indent);
44+}
45+ 
40namespace {46namespace {
41ir::Span Sp() { return ir::Span("test_ir_backend", 1, 1); }47ir::Span Sp() { return ir::Span("test_ir_backend", 1, 1); }
42 48 
@@ -116,6 +122,17 @@ struct GetInputCseTestSetup {
116 122 
117 void Bind(IrBackendContext& irBackendCtx) { irBackendCtx.getInputCse = &getInputCse; }123 void Bind(IrBackendContext& irBackendCtx) { irBackendCtx.getInputCse = &getInputCse; }
118};124};
125+ 
126+size_t CountOccurrences(const std::string& text, const std::string& needle)
127+{
128+ size_t count = 0;
129+ size_t pos = 0;
130+ while ((pos = text.find(needle, pos)) != std::string::npos) {
131+ ++count;
132+ pos += needle.size();
133+ }
134+ return count;
135+}
119} // namespace136} // namespace
120 137 
121class TestSuite_IrBackend : public testing::Test {138class TestSuite_IrBackend : public testing::Test {
@@ -137,8 +154,141 @@ struct ControlFlowCtx {
137 ValDependTensorMeta meta;154 ValDependTensorMeta meta;
138};155};
139 156 
157+std::string EmitLegacyControlFlowEntryAndDynamicLoopOpen(
158+ int64_t runtimeDebugMode, const std::vector<std::pair<SymbolicScalar, int64_t>>& assumptions,
159+ const std::vector<SymbolicScalar>& runtimeSymbols)
160+{
161+ config::SetDebugOption(CFG_RUNTIME_DBEUG_MODE, runtimeDebugMode);
162+ DynFuncFixture dynFixture;
163+ LinkerFixture linkerFixture;
164+ ControlFlowCtx ctx;
165+ const std::string sectionName = ".pypto";
166+ const std::string expName = "expression.h";
167+ auto loop = std::make_shared<Function>(Program::GetInstance(), "assume_loop_magic", "assume_loop",
168+ dynFixture.dynFunc.get());
169+ loop->SetFunctionType(FunctionType::DYNAMIC_LOOP);
170+ LoopRange range(SymbolicScalar(0), SymbolicScalar(4), SymbolicScalar(1));
171+ auto attr = std::make_shared<DynloopFunctionAttribute>("loop_idx", range, range);
172+ loop->SetDynloopAttribute(attr);
173+ for (const auto& [expression, divisor] : assumptions) {
174+ Program::GetInstance().RegisterDivisibleAssumption(expression, divisor);
175+ }
176+ for (const auto& symbol : runtimeSymbols) {
177+ linkerFixture.symbolTable.AddSymbol(symbol);
178+ }
179+ ControlFlowEmitCtx emitCtx{ctx.cache,
180+ *linkerFixture.linker,
181+ sectionName,
182+ ctx.slotIdxMapping,
183+ ctx.group,
184+ ctx.rootTileDict,
185+ ctx.controlFlowOss,
186+ ctx.expressionOss,
187+ ctx.exprHeaderOss,
188+ expName,
189+ ctx.exprSrcFiles,
190+ ctx.meta,
191+ nullptr};
192+ EmitAssumeDivisibleChecks(emitCtx, 1);
193+ EmitDynamicLoopOpen(emitCtx, loop.get(), attr, 1);
194+ return ctx.controlFlowOss.str();
195+}
196+ 
140static ir::ForStmtPtr AsForStmt(const ir::StmtPtr& stmt) { return std::dynamic_pointer_cast<const ir::ForStmt>(stmt); }197static ir::ForStmtPtr AsForStmt(const ir::StmtPtr& stmt) { return std::dynamic_pointer_cast<const ir::ForStmt>(stmt); }
141 198 
199+TEST_F(TestSuite_IrBackend, Mode4EmitsRuntimeCheckBeforeLoop)
200+{
201+ SymbolicScalar vm("vm");
202+ const auto source = EmitLegacyControlFlowEntryAndDynamicLoopOpen(CFG_RUNTIME_DEBUG_GM_OUT_OF_BOUNDS, {{vm, 128}},
203+ {vm});
204+ const auto checkPos = source.find("if ((VALUE_vm % 128) != 0) {");
205+ const auto loopPos = source.find("LOOP(");
206+ ASSERT_NE(checkPos, std::string::npos);
207+ ASSERT_NE(loopPos, std::string::npos);
208+ EXPECT_LT(checkPos, loopPos);
209+ EXPECT_NE(source.find("__builtin_trap();"), std::string::npos);
210+ EXPECT_EQ(CountOccurrences(source, "% 128"), 1U);
211+ EXPECT_EQ(CountOccurrences(source, "__builtin_trap();"), 1U);
212+}
213+ 
214+TEST_F(TestSuite_IrBackend, NonMode4DoesNotEmitRuntimeCheck)
215+{
216+ SymbolicScalar vm("vm");
217+ for (const int64_t mode : {int64_t{0}, CFG_RUNTIME_DEBUG_VERIFY}) {
218+ const auto source = EmitLegacyControlFlowEntryAndDynamicLoopOpen(mode, {{vm, 128}}, {vm});
219+ EXPECT_EQ(source.find("% 128"), std::string::npos) << "runtime_debug_mode=" << mode;
220+ EXPECT_EQ(source.find("__builtin_trap();"), std::string::npos) << "runtime_debug_mode=" << mode;
221+ }
222+}
223+ 
224+TEST_F(TestSuite_IrBackend, Mode4EmitsRuntimeCheckForCompositeExpression)
225+{
226+ SymbolicScalar qEnd("q_end");
227+ SymbolicScalar qStart("q_start");
228+ const auto source = EmitLegacyControlFlowEntryAndDynamicLoopOpen(CFG_RUNTIME_DEBUG_GM_OUT_OF_BOUNDS,
229+ {{qEnd - qStart, 128}}, {qEnd, qStart});
230+ 
231+ EXPECT_NE(source.find("VALUE_q_end - VALUE_q_start"), std::string::npos);
232+ EXPECT_NE(source.find("% 128"), std::string::npos);
233+ EXPECT_EQ(CountOccurrences(source, "__builtin_trap();"), 1U);
234+}
235+ 
236+TEST_F(TestSuite_IrBackend, Mode4EmitsRuntimeCheckForDirectInputShapeCall)
237+{
238+ const auto inputShape = ExprPtrToSymbolicScalar(MakeGetInputShapeDimExpr("ARG_source", 0));
239+ const auto source = EmitLegacyControlFlowEntryAndDynamicLoopOpen(CFG_RUNTIME_DEBUG_GM_OUT_OF_BOUNDS,
240+ {{inputShape, 128}}, {});
241+ 
242+ EXPECT_NE(source.find("RUNTIME_GetInputShapeDim"), std::string::npos);
243+ EXPECT_NE(source.find("% 128"), std::string::npos);
244+ EXPECT_EQ(CountOccurrences(source, "__builtin_trap();"), 1U);
245+}
246+ 
247+TEST_F(TestSuite_IrBackend, BuildControlFlow_Mode4EmitsRootRuntimeCheckOnce)
248+{
249+ config::SetDebugOption(CFG_RUNTIME_DBEUG_MODE, CFG_RUNTIME_DEBUG_GM_OUT_OF_BOUNDS);
250+ DynFuncFixture dynFixture;
251+ LinkerFixture linkerFixture;
252+ ControlFlowCtx ctx;
253+ 
254+ const std::string workDir = "control_flow_assume_divisible_" + std::to_string(getpid());
255+ const std::string emitDir = workDir + "/pypto/kernel_aicpu";
256+ ASSERT_EQ(mkdir(workDir.c_str(), 0755), 0);
257+ ASSERT_EQ(mkdir((workDir + "/pypto").c_str(), 0755), 0);
258+ ASSERT_EQ(mkdir(emitDir.c_str(), 0755), 0);
259+ setenv("ASCEND_WORK_PATH", workDir.c_str(), 1);
260+ config::SetCodeGenConfig(KEY_FIXED_OUTPUT_PATH, true);
261+ 
262+ SymbolicScalar vm("vm");
263+ Program::GetInstance().RegisterDivisibleAssumption(vm, 128);
264+ linkerFixture.symbolTable.AddSymbol(vm);
265+ const std::string sectionName = ".pypto";
266+ const std::string expName = "expression.h";
267+ ControlFlowEmitCtx emitCtx{ctx.cache,
268+ *linkerFixture.linker,
269+ sectionName,
270+ ctx.slotIdxMapping,
271+ ctx.group,
272+ ctx.rootTileDict,
273+ ctx.controlFlowOss,
274+ ctx.expressionOss,
275+ ctx.exprHeaderOss,
276+ expName,
277+ ctx.exprSrcFiles,
278+ ctx.meta,
279+ nullptr};
280+ 
281+ BuildControlFlow(emitCtx, dynFixture.dynFunc.get(), 0);
282+ const auto output = ctx.controlFlowOss.str();
283+ EXPECT_NE(output.find("ControlFlowEntry"), std::string::npos);
284+ EXPECT_EQ(CountOccurrences(output, "% 128"), 1U);
285+ EXPECT_EQ(CountOccurrences(output, "__builtin_trap();"), 1U);
286+ 
287+ unsetenv("ASCEND_WORK_PATH");
288+ std::string rmCmd = "rm -rf " + workDir;
289+ ASSERT_EQ(system(rmCmd.c_str()), 0);
290+}
291+ 
142TEST_F(TestSuite_IrBackend, ExprPtrToSymbolicScalar_AllCases)292TEST_F(TestSuite_IrBackend, ExprPtrToSymbolicScalar_AllCases)
143{293{
144 EXPECT_FALSE(ExprPtrToSymbolicScalar(nullptr).IsValid());294 EXPECT_FALSE(ExprPtrToSymbolicScalar(nullptr).IsValid());
@@ -621,6 +771,47 @@ TEST_F(TestSuite_IrBackend, BuildControlFlowFromIR_EmitsGetInputCseStackInits)
621 ASSERT_EQ(system(rmCmd.c_str()), 0);771 ASSERT_EQ(system(rmCmd.c_str()), 0);
622}772}
623 773 
774+TEST_F(TestSuite_IrBackend, BuildControlFlowFromIR_Mode4EmitsRuntimeCheck)
775+{
776+ config::SetDebugOption(CFG_RUNTIME_DBEUG_MODE, CFG_RUNTIME_DEBUG_GM_OUT_OF_BOUNDS);
777+ DynFuncFixture dynFixture;
778+ LinkerFixture linkerFixture;
779+ ControlFlowCtx ctx;
780+ 
781+ const std::string workDir = "ir_backend_assume_divisible_" + std::to_string(getpid());
782+ const std::string emitDir = workDir + "/pypto/kernel_aicpu";
783+ ASSERT_EQ(mkdir(workDir.c_str(), 0755), 0);
784+ ASSERT_EQ(mkdir((workDir + "/pypto").c_str(), 0755), 0);
785+ ASSERT_EQ(mkdir(emitDir.c_str(), 0755), 0);
786+ setenv("ASCEND_WORK_PATH", workDir.c_str(), 1);
787+ config::SetCodeGenConfig(KEY_FIXED_OUTPUT_PATH, true);
788+ 
789+ SymbolicScalar vm("vm");
790+ Program::GetInstance().RegisterDivisibleAssumption(vm, 128);
791+ linkerFixture.symbolTable.AddSymbol(vm);
792+ auto loopVar = IRContext::Get().MakeVar("loop_idx", std::make_shared<ir::ScalarType>(ir::DataType::INT64), Sp());
793+ const auto forStmt = Builder().CreateForStmt(
794+ loopVar, Builder().CreateConstInt(0).AsExpr(), Builder().CreateConstInt(4).AsExpr(),
795+ Builder().CreateConstInt(1).AsExpr(), {}, Builder().CreateSeqStmts({}, Sp()), {}, Sp());
796+ dynFixture.dynFunc->body_ = Builder().CreateSeqStmts({forStmt}, Sp());
797+ 
798+ BuildControlFlowFromIR(ctx.irBackendCtx, ctx.cache, *linkerFixture.linker, ".pypto", dynFixture.dynFunc.get(),
799+ ctx.slotIdxMapping, ctx.group, ctx.rootTileDict, ctx.controlFlowOss, ctx.expressionOss,
800+ ctx.exprHeaderOss, 0, "expr", ctx.exprSrcFiles, ctx.meta);
801+ const auto output = ctx.controlFlowOss.str();
802+ const auto checkPos = output.find("if ((VALUE_vm % 128) != 0) {");
803+ const auto loopPos = output.find(" LOOP(");
804+ ASSERT_NE(checkPos, std::string::npos);
805+ ASSERT_NE(loopPos, std::string::npos);
806+ EXPECT_LT(checkPos, loopPos);
807+ EXPECT_EQ(CountOccurrences(output, "% 128"), 1U);
808+ EXPECT_EQ(CountOccurrences(output, "__builtin_trap();"), 1U);
809+ 
810+ unsetenv("ASCEND_WORK_PATH");
811+ std::string rmCmd = "rm -rf " + workDir;
812+ ASSERT_EQ(system(rmCmd.c_str()), 0);
813+}
814+ 
624TEST_F(TestSuite_IrBackend, FindExprFromIfStmt_RegistersReturnVars)815TEST_F(TestSuite_IrBackend, FindExprFromIfStmt_RegistersReturnVars)
625{816{
626 IrBackendContext irBackendCtx;817 IrBackendContext irBackendCtx;
@@ -16,6 +16,7 @@
16#include "gtest/gtest.h"16#include "gtest/gtest.h"
17 17 
18#include "interface/tensor/logical_tensor.h"18#include "interface/tensor/logical_tensor.h"
19+#include "interface/program/program.h"
19#include "tilefwk/tilefwk.h"20#include "tilefwk/tilefwk.h"
20#include "interface/tensor/irbuilder.h"21#include "interface/tensor/irbuilder.h"
21#include "passes/pass_utils/pass_operation_utils.h"22#include "passes/pass_utils/pass_operation_utils.h"
@@ -91,8 +92,351 @@ void RunInferShapeAndExpect(const std::shared_ptr<Function>& currFunctionPtr, St
91 std::cout << currFunctionPtr->Dump() << std::endl;92 std::cout << currFunctionPtr->Dump() << std::endl;
92 EXPECT_EQ(inferShapeTest.PostCheck(*currFunctionPtr), expected);93 EXPECT_EQ(inferShapeTest.PostCheck(*currFunctionPtr), expected);
93}94}
95+ 
94} // namespace96} // namespace
95 97 
98+TEST_F(InferShapeTest, AssumeDivisible_SimplifiesNestedViewTileInChildFunction)
99+{
100+ auto root = std::make_shared<Function>(Program::GetInstance(), "assume_root", "assume_root", nullptr);
101+ auto child = std::make_shared<Function>(Program::GetInstance(), "assume_child", "assume_child", root.get());
102+ SymbolicScalar q("q");
103+ SymbolicScalar tileIndex("tile_index");
104+ 
105+ // These are the two 64-wide child views of a 128-wide parent tile.
106+ const auto firstValid = std::min(std::max(std::min(q - tileIndex * 128, 128), 0), 64);
107+ const auto secondValid = std::min(std::max(std::min(q - tileIndex * 128, 128) - 64, 0), 64);
108+ const auto validWithoutMax = std::min(q - tileIndex * 128, 64);
109+ Program::GetInstance().RegisterDivisibleAssumption(q, 128);
110+ 
111+ InferDynShape pass;
112+ const auto firstResult = pass.SimplifyValidShapeWithAssumptions(*child, firstValid);
113+ const auto secondResult = pass.SimplifyValidShapeWithAssumptions(*child, secondValid);
114+ const auto noMaxResult = pass.SimplifyValidShapeWithAssumptions(*child, validWithoutMax);
115+ EXPECT_TRUE(firstResult.ConcreteValid());
116+ EXPECT_TRUE(secondResult.ConcreteValid());
117+ EXPECT_TRUE(noMaxResult.ConcreteValid());
118+ EXPECT_EQ(firstResult.Concrete(), 64);
119+ EXPECT_EQ(secondResult.Concrete(), 64);
120+ EXPECT_EQ(noMaxResult.Concrete(), 64);
121+ EXPECT_TRUE(Program::GetInstance().IsKnownDivisible(q, 64));
122+ EXPECT_TRUE(Program::GetInstance().IsKnownDivisible(q, 64));
123+}
124+ 
125+TEST_F(InferShapeTest, AssumeDivisible_SimplifiesObservedFlashAttentionValidShapes)
126+{
127+ auto function = std::make_shared<Function>(Program::GetInstance(), "assume_fa_dump", "assume_fa_dump", nullptr);
128+ SymbolicScalar qEnd("q_end");
129+ SymbolicScalar qStart("q_start");
130+ SymbolicScalar kEnd("k_end");
131+ SymbolicScalar kStart("k_start");
132+ SymbolicScalar loopIdx3("loop_idx_3");
133+ SymbolicScalar loopIdx4("loop_idx_4");
134+ 
135+ // Q/K mirror cu_seqlens_[loop_idx_1 + 1] - cu_seqlens_[loop_idx_1].
136+ const SymbolicScalar q = qEnd - qStart;
137+ const SymbolicScalar k = kEnd - kStart;
138+ const SymbolicScalar yq = q - loopIdx3 * 128;
139+ const SymbolicScalar yk = k - loopIdx4 * 128;
140+ Program::GetInstance().RegisterDivisibleAssumption(q, 128);
141+ Program::GetInstance().RegisterDivisibleAssumption(k, 128);
142+ 
143+ // 5.1 - 5.4: observed K-side 128 tile valid shapes.
144+ const auto kTile0 = std::min(std::max(std::min(yk, 128), 0), 128);
145+ const auto kTile1 = std::min(std::max(std::min(yk, 256) + -128, 0), 128);
146+ const auto kTile2 = std::min(std::max(std::min(yk, 384) + -256, 0), 128);
147+ const auto kTile3 = std::min(std::max(std::min(yk, 512) + -384, 0), 128);
148+ const auto kTile4 = std::min(std::max(std::min(yk, 640) + -512, 0), 128);
149+ 
150+ // 5.5: observed 128 -> 64 Q-side child Views.
151+ const auto qChild1 = std::min(std::max(std::min(yq, 128) + -64, 0), 64);
152+ const auto qChild0 = std::min(std::max(std::min(yq, 128), 0), 64);
153+ 
154+ InferDynShape pass;
155+ const std::vector<SymbolicScalar> expected128 = {kTile0, kTile1, kTile2, kTile3, kTile4};
156+ for (const auto& validShape : expected128) {
157+ const auto result = pass.SimplifyValidShapeWithAssumptions(*function, validShape);
158+ ASSERT_TRUE(result.ConcreteValid());
159+ EXPECT_EQ(result.Concrete(), 128);
160+ }
161+ for (const auto& validShape : {qChild0, qChild1}) {
162+ const auto result = pass.SimplifyValidShapeWithAssumptions(*function, validShape);
163+ ASSERT_TRUE(result.ConcreteValid());
164+ EXPECT_EQ(result.Concrete(), 64);
165+ }
166+}
167+ 
168+TEST_F(InferShapeTest, AssumeDivisible_SimplifiesMultiLevelViewTile)
169+{
170+ auto function = std::make_shared<Function>(Program::GetInstance(), "assume_multi_level", "assume_multi_level",
171+ nullptr);
172+ SymbolicScalar q("q");
173+ SymbolicScalar tileIndex("tile_index");
174+ Program::GetInstance().RegisterDivisibleAssumption(q, 128);
175+ 
176+ // A 128 -> 64 -> 32 View chain. The expression intentionally retains
177+ // nested min caps and offsets instead of relying on prior algebraic
178+ // normalization.
179+ const auto valid = std::min(std::max(std::min(std::min(q - tileIndex * 128, 256) - 64, 128) - 32, 0), 32);
180+ 
181+ InferDynShape pass;
182+ const auto result = pass.SimplifyValidShapeWithAssumptions(*function, valid);
183+ ASSERT_TRUE(result.ConcreteValid());
184+ EXPECT_EQ(result.Concrete(), 32);
185+}
186+ 
187+TEST_F(InferShapeTest, AssumeDivisible_DoesNotSimplifyWithoutAssumption)
188+{
189+ auto function = std::make_shared<Function>(Program::GetInstance(), "assume_none", "assume_none", nullptr);
190+ SymbolicScalar q("q");
191+ SymbolicScalar tileIndex("tile_index");
192+ const auto valid = std::min(std::max(std::min(q - tileIndex * 128, 128) - 64, 0), 64);
193+ 
194+ InferDynShape pass;
195+ const auto result = pass.SimplifyValidShapeWithAssumptions(*function, valid);
196+ EXPECT_FALSE(result.ConcreteValid());
197+}
198+ 
199+TEST_F(InferShapeTest, AssumeDivisible_DoesNotSimplifyNonAlignedRemainingCap)
200+{
201+ auto function = std::make_shared<Function>(Program::GetInstance(), "assume_non_aligned", "assume_non_aligned",
202+ nullptr);
203+ SymbolicScalar q("q");
204+ Program::GetInstance().RegisterDivisibleAssumption(q, 64);
205+ 
206+ // P - D is 66, which cannot represent a sequence of complete 64 tiles.
207+ const auto valid = std::min(std::max(std::min(q, 130) - 64, 0), 64);
208+ 
209+ InferDynShape pass;
210+ const auto result = pass.SimplifyValidShapeWithAssumptions(*function, valid);
211+ EXPECT_FALSE(result.ConcreteValid());
212+}
213+ 
214+TEST_F(InferShapeTest, AssumeDivisible_SimplifiesExplicitViewValidShapeAttribute)
215+{
216+ auto function = std::make_shared<Function>(Program::GetInstance(), "assume_explicit_view", "assume_explicit_view",
217+ nullptr);
218+ const std::vector<int64_t> shape = {64, 64};
219+ auto input = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{});
220+ auto output = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{});
221+ SymbolicScalar q("q");
222+ SymbolicScalar n("n");
223+ SymbolicScalar tileIndex("tile_index");
224+ Program::GetInstance().RegisterDivisibleAssumption(q, 128);
225+ 
226+ const auto validM = std::min(std::max(std::min(q - tileIndex * 128, 128) - 64, 0), 64);
227+ auto viewAttr = std::make_shared<ViewOpAttribute>(
228+ std::vector<int64_t>{0, 0}, MEM_UNKNOWN, std::vector<SymbolicScalar>{}, std::vector<SymbolicScalar>{validM, n});
229+ PassOperationUtils::AddOperation(*function, Opcode::OP_VIEW, {input}, {output},
230+ [&viewAttr](Operation& op) { op.SetOpAttribute(viewAttr); });
231+ function->inCasts_.push_back(input);
232+ function->outCasts_.push_back(output);
233+ 
234+ InferDynShape pass;
235+ ASSERT_EQ(pass.RunOnFunction(*function), SUCCESS);
236+ const auto& attrValidShape = viewAttr->GetToDynValidShape();
237+ ASSERT_EQ(attrValidShape.size(), 2);
238+ EXPECT_TRUE(attrValidShape[0].ConcreteValid());
239+ EXPECT_EQ(attrValidShape[0].Concrete(), 64);
240+ EXPECT_EQ(attrValidShape[1].Dump(), n.Dump());
241+ EXPECT_TRUE(output->GetDynValidShape()[0].ConcreteValid());
242+ EXPECT_EQ(output->GetDynValidShape()[0].Concrete(), 64);
243+}
244+ 
245+TEST_F(InferShapeTest, AssumeDivisible_SimplifiesCopyInValidShapeAttribute)
246+{
247+ auto function = std::make_shared<Function>(Program::GetInstance(), "assume_copyin", "assume_copyin", nullptr);
248+ const std::vector<int64_t> shape = {64, 64};
249+ const auto shapeImmediate = OpImmediate::Specified(shape);
250+ SymbolicScalar vm("vm");
251+ SymbolicScalar n("n");
252+ SymbolicScalar tileIndex("tile_index");
253+ Program::GetInstance().RegisterDivisibleAssumption(vm, 128);
254+ 
255+ const auto validM = std::min(std::max(std::min(vm - tileIndex * 128, 128) + -64, 0), 64);
256+ auto input = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{});
257+ auto output = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{validM, n});
258+ auto copyInAttr = CreateCopyInAttribute(OpImmediate::Specified({0, 0}), MEM_UB, shapeImmediate, shapeImmediate);
259+ copyInAttr->SetToDynValidShape(OpImmediate::Specified(std::vector<SymbolicScalar>{validM, n}));
260+ PassOperationUtils::AddOperation(
261+ *function, Opcode::OP_COPY_IN, {input}, {output},
262+ [&copyInAttr](Operation& op) { op.SetOpAttribute(copyInAttr); }, ir::Span::Unknown(), false);
263+ function->inCasts_.push_back(input);
264+ function->outCasts_.push_back(output);
265+ 
266+ InferDynShape pass;
267+ pass.SimplifyAllValidShapes(*function);
268+ 
269+ const auto attrValidShape = OpImmediate::ToSpecified(copyInAttr->GetToDynValidShape());
270+ ASSERT_EQ(attrValidShape.size(), 2);
271+ EXPECT_TRUE(attrValidShape[0].ConcreteValid());
272+ EXPECT_EQ(attrValidShape[0].Concrete(), 64);
273+ EXPECT_EQ(attrValidShape[1].Dump(), n.Dump());
274+ EXPECT_TRUE(output->GetDynValidShape()[0].ConcreteValid());
275+ EXPECT_EQ(output->GetDynValidShape()[0].Concrete(), 64);
276+}
277+ 
278+TEST_F(InferShapeTest, AssumeDivisible_ViewCopyInL0CCopyUB_CoexistSimplifyAndInferShape)
279+{
280+ auto function = std::make_shared<Function>(Program::GetInstance(), "assume_coexist", "assume_coexist", nullptr);
281+ const std::vector<int64_t> shape = {64};
282+ const auto shapeImmediate = OpImmediate::Specified(shape);
283+ SymbolicScalar vm("vm");
284+ SymbolicScalar tileIndex("tile_index");
285+ Program::GetInstance().RegisterDivisibleAssumption(vm, 128);
286+ 
287+ const auto dynamicValid = std::min(std::max(std::min(vm - tileIndex * 128, 128) + -64, 0), 64);
288+ 
289+ auto copyInInput = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{});
290+ auto copyInOutput = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{dynamicValid});
291+ auto copyInAttr = CreateCopyInAttribute(OpImmediate::Specified({0}), MEM_UB, shapeImmediate, shapeImmediate);
292+ copyInAttr->SetToDynValidShape(OpImmediate::Specified(std::vector<SymbolicScalar>{dynamicValid}));
293+ PassOperationUtils::AddOperation(
294+ *function, Opcode::OP_COPY_IN, {copyInInput}, {copyInOutput},
295+ [&copyInAttr](Operation& op) { op.SetOpAttribute(copyInAttr); }, ir::Span::Unknown(), false);
296+ 
297+ auto viewInput = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{dynamicValid});
298+ auto viewOutput = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{dynamicValid});
299+ auto viewAttr = std::make_shared<ViewOpAttribute>(
300+ std::vector<int64_t>{0}, MEM_UNKNOWN, std::vector<SymbolicScalar>{}, std::vector<SymbolicScalar>{dynamicValid});
301+ PassOperationUtils::AddOperation(*function, Opcode::OP_VIEW, {viewInput}, {viewOutput},
302+ [&viewAttr](Operation& op) { op.SetOpAttribute(viewAttr); });
303+ 
304+ auto l0cInput = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{dynamicValid});
305+ auto l0cOutput = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{dynamicValid});
306+ auto l0cAttr = CreateCopyOutAttribute(MEM_UB, OpImmediate::Specified({0}), shapeImmediate, shapeImmediate);
307+ PassOperationUtils::AddOperation(
308+ *function, Opcode::OP_L0C_COPY_UB, {l0cInput}, {l0cOutput},
309+ [&l0cAttr](Operation& op) { op.SetOpAttribute(l0cAttr); }, ir::Span::Unknown(), false);
310+ 
311+ function->inCasts_.push_back(copyInInput);
312+ function->inCasts_.push_back(viewInput);
313+ function->inCasts_.push_back(l0cInput);
314+ function->outCasts_.push_back(copyInOutput);
315+ function->outCasts_.push_back(viewOutput);
316+ function->outCasts_.push_back(l0cOutput);
317+ 
318+ InferDynShape pass;
319+ pass.SimplifyAllValidShapes(*function);
320+ 
321+ const auto copyInAttrValid = OpImmediate::ToSpecified(copyInAttr->GetToDynValidShape());
322+ ASSERT_EQ(copyInAttrValid.size(), 1);
323+ EXPECT_TRUE(copyInAttrValid[0].ConcreteValid());
324+ EXPECT_EQ(copyInAttrValid[0].Concrete(), 64);
325+ 
326+ const auto& viewAttrValid = viewAttr->GetToDynValidShape();
327+ ASSERT_EQ(viewAttrValid.size(), 1);
328+ EXPECT_TRUE(viewAttrValid[0].ConcreteValid());
329+ EXPECT_EQ(viewAttrValid[0].Concrete(), 64);
330+ 
331+ EXPECT_TRUE(copyInOutput->GetDynValidShape()[0].ConcreteValid());
332+ EXPECT_EQ(copyInOutput->GetDynValidShape()[0].Concrete(), 64);
333+ EXPECT_TRUE(viewOutput->GetDynValidShape()[0].ConcreteValid());
334+ EXPECT_EQ(viewOutput->GetDynValidShape()[0].Concrete(), 64);
335+}
336+ 
337+TEST_F(InferShapeTest, AssumeDivisible_RegistersOnRootFunctionAndStoresOwnAssumption)
338+{
339+ auto root = std::make_shared<Function>(Program::GetInstance(), "assume_owner_root", "assume_owner_root", nullptr);
340+ root->SetFunctionType(FunctionType::DYNAMIC);
341+ auto loop = std::make_shared<Function>(Program::GetInstance(), "assume_owner_loop", "assume_owner_loop",
342+ root.get());
343+ loop->SetFunctionType(FunctionType::DYNAMIC_LOOP);
344+ auto child = std::make_shared<Function>(Program::GetInstance(), "assume_owner_child", "assume_owner_child",
345+ loop.get());
346+ child->SetFunctionType(FunctionType::STATIC);
347+ child->SetGraphType(GraphType::BLOCK_GRAPH);
348+ SymbolicScalar vm("vm");
349+ 
350+ Program::GetInstance().RegisterDivisibleAssumption(vm, 128);
351+ 
352+ const auto& rootAssumptions = Program::GetInstance().GetDivisibleAssumptions();
353+ const auto it = rootAssumptions.find(vm.Simplify().Dump());
354+ ASSERT_NE(it, rootAssumptions.end());
355+ EXPECT_EQ(it->second.expression.Dump(), vm.Dump());
356+ EXPECT_EQ(it->second.divisors, std::set<int64_t>({128}));
357+ EXPECT_TRUE(Program::GetInstance().IsKnownDivisible(vm, 64));
358+}
359+ 
360+TEST_F(InferShapeTest, AssumeDivisible_StoresNormalizedExpressionIndependentOfRegistrationOrder)
361+{
362+ auto derivedFirst = std::make_shared<Function>(Program::GetInstance(), "assume_derived_first",
363+ "assume_derived_first", nullptr);
364+ auto symbolFirst = std::make_shared<Function>(Program::GetInstance(), "assume_symbol_first", "assume_symbol_first",
365+ nullptr);
366+ SymbolicScalar vm("vm");
367+ SymbolicScalar offset("offset");
368+ const auto equivalentExpr = (vm - offset) + offset;
369+ const auto key = vm.Simplify().Dump();
370+ 
371+ Program::GetInstance().RegisterDivisibleAssumption(equivalentExpr, 64);
372+ Program::GetInstance().RegisterDivisibleAssumption(vm, 128);
373+ Program::GetInstance().RegisterDivisibleAssumption(vm, 128);
374+ Program::GetInstance().RegisterDivisibleAssumption(equivalentExpr, 64);
375+ 
376+ for (size_t idx = 0; idx < 2U; idx++) {
377+ const auto& assumptions = Program::GetInstance().GetDivisibleAssumptions();
378+ const auto it = assumptions.find(key);
379+ ASSERT_NE(it, assumptions.end());
380+ EXPECT_TRUE(it->second.expression.IsSymbol());
381+ EXPECT_EQ(it->second.expression.Dump(), vm.Dump());
382+ EXPECT_EQ(it->second.divisors, std::set<int64_t>({64, 128}));
383+ }
384+}
385+ 
386+TEST_F(InferShapeTest, AssumeDivisible_RunOnFunctionSavesSimplifiedValidShapeInStaticSnapshot)
387+{
388+ auto function = std::make_shared<Function>(Program::GetInstance(), "assume_snapshot", "assume_snapshot", nullptr);
389+ const std::vector<int64_t> shape = {64};
390+ const auto shapeImmediate = OpImmediate::Specified(shape);
391+ SymbolicScalar vm("vm");
392+ SymbolicScalar tileIndex("tile_index");
393+ const auto dynamicValid = std::min(std::max(vm - tileIndex * 128, 0), 64);
394+ auto input = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{dynamicValid});
395+ auto output = IRBuilder().CreateTensorVar(DT_FP32, shape, std::vector<SymbolicScalar>{dynamicValid});
396+ auto copyAttr = CreateCopyOutAttribute(MEM_UB, OpImmediate::Specified({0}), shapeImmediate, shapeImmediate);
397+ auto& copyOp = PassOperationUtils::AddOperation(
398+ *function, Opcode::OP_L0C_COPY_UB, {input}, {output},
399+ [&copyAttr](Operation& op) { op.SetOpAttribute(copyAttr); }, ir::Span::Unknown(), false);
400+ function->inCasts_.push_back(input);
401+ function->outCasts_.push_back(output);
402+ Program::GetInstance().RegisterDivisibleAssumption(vm, 128);
403+ 
404+ InferDynShape pass;
405+ ASSERT_EQ(pass.RunOnFunction(*function), SUCCESS);
406+ 
407+ ASSERT_TRUE(copyOp.HasAttribute(OpAttributeKey::staticValidShape));
408+ const auto staticValidShape = copyOp.GetVectorIntAttribute<int64_t>(OpAttributeKey::staticValidShape);
409+ ASSERT_EQ(staticValidShape.size(), 1U);
410+ EXPECT_EQ(staticValidShape[0], 64);
411+}
412+ 
413+TEST_F(InferShapeTest, AssumeDivisible_ChildQueriesRootAssumption)
414+{
415+ auto root = std::make_shared<Function>(Program::GetInstance(), "assume_root", "assume_root", nullptr);
416+ SymbolicScalar q("q");
417+ 
418+ Program::GetInstance().RegisterDivisibleAssumption(q, 128);
419+ auto child = std::make_shared<Function>(Program::GetInstance(), "assume_child", "assume_child", root.get());
420+ 
421+ EXPECT_TRUE(Program::GetInstance().IsKnownDivisible(q, 128));
422+ EXPECT_TRUE(Program::GetInstance().IsKnownDivisible(q, 64));
423+}
424+ 
425+TEST_F(InferShapeTest, AssumeDivisible_RegistrationIsSharedThroughRootFunction)
426+{
427+ auto root = std::make_shared<Function>(Program::GetInstance(), "assume_root_sibling", "assume_root_sibling",
428+ nullptr);
429+ SymbolicScalar q("q_sibling");
430+ auto child = std::make_shared<Function>(Program::GetInstance(), "assume_child_sibling", "assume_child_sibling",
431+ root.get());
432+ auto sibling = std::make_shared<Function>(Program::GetInstance(), "assume_sibling", "assume_sibling", root.get());
433+ 
434+ Program::GetInstance().RegisterDivisibleAssumption(q, 128);
435+ 
436+ EXPECT_TRUE(Program::GetInstance().IsKnownDivisible(q, 128));
437+ EXPECT_FALSE(Program::GetInstance().GetDivisibleAssumptions().empty());
438+}
439+ 
96TEST_F(InferShapeTest, TestAdd)440TEST_F(InferShapeTest, TestAdd)
97{441{
98 auto currFunctionPtr = std::make_shared<Function>(Program::GetInstance(), "TestAddInferShape", "TestAddInferShape",442 auto currFunctionPtr = std::make_shared<Function>(Program::GetInstance(), "TestAddInferShape", "TestAddInferShape",
@@ -3546,6 +3546,64 @@ TEST_F(ScheduleOoOTest, DualDst_RunDualDstFuse_ActuallyFusesAndMutatesFunction)
3546 dualdst_ut::ExpectFusedMetadata(s, g, before);3546 dualdst_ut::ExpectFusedMetadata(s, g, before);
3547}3547}
3548 3548 
3549+TEST_F(ScheduleOoOTest, DualDst_FusedCopyPreservesDynamicValidShapeOnNonSplitAxis)
zhangyuebing

【🟡 建议修改】本用例仅覆盖 direction=0(M 轴切分、N 轴动态)的场景,建议补 direction=1 镜像用例

本用例用 {TILE_M*2, TILE_N} 的 L0C shape 和 {TILE_M, 0} 偏移触发 M 轴融合,验证 fusedValid = {2*TILE_M, "n"}。而 SetDualDstCopyAttr 中 validShape[direction] = OpImmediate::Specified(realShape[direction]) 对 direction=1(N 轴切分、M 轴保留动态表达式)是另一条执行路径,目前没有任何"动态正交轴 + direction=1"的用例(已有的 N 切分用例如 DualDst_AllocQueryHelpers_AfterFuse 均为全静态 valid shape)。建议补镜像用例:L0C shape {TILE_M, TILE_N*2}、偏移 {0, TILE_N}、validShape {"m", TILE_N},断言 fusedValid = {"m", 2*TILE_N}。

顺带确认一点:正交轴直接沿用 attrE 的 dyn valid shape,融合候选判定是否已保证 attrL 的正交轴表达式与 attrE 一致?若无显式保证,建议在 DEBUG 下加一致性校验,避免早/晚 copy 正交轴表达式不一致时融合属性只反映 early 一侧。

likedislike
gggxinmeng
gggxinmeng
Sep 4 Comments:
likedislike
3550+{
3551+ auto g = dualdst_ut::BuildDualDstGraph_2({dualdst_ut::TILE_M * 2, dualdst_ut::TILE_N},
3552+ {dualdst_ut::TILE_M, dualdst_ut::TILE_N}, {0, 0}, {dualdst_ut::TILE_M, 0});
3553+ const std::vector<SymbolicScalar> validShape = {SymbolicScalar(dualdst_ut::TILE_M), SymbolicScalar("n")};
3554+ for (Operation* copy : {g.copy0, g.copy1}) {
3555+ copy->GetOutputOperand(0)->UpdateDynValidShape(validShape);
3556+ auto attr = std::dynamic_pointer_cast<CopyOpAttribute>(copy->GetOpAttribute());
3557+ ASSERT_NE(attr, nullptr);
3558+ attr->SetToDynValidShape(OpImmediate::Specified(validShape));
3559+ }
3560+ 
3561+ OoOScheduler s(*g.func);
3562+ ASSERT_EQ(s.Init(g.func->Operations().DuplicatedOpList(), CORE_INIT_CONFIGS_HARDWARE_TWO), SUCCESS);
3563+ dualdst_ut::InjectCoreMap(s, g);
3564+ s.SetEnableDualDst(true);
3565+ ASSERT_EQ(s.dualDstEngine_.RunDualDstFuse(), SUCCESS);
3566+ 
3567+ Operation* dual = dualdst_ut::FindDualDstOp(*g.func);
3568+ ASSERT_NE(dual, nullptr);
3569+ auto attr = std::dynamic_pointer_cast<CopyOpAttribute>(dual->GetOpAttribute());
3570+ ASSERT_NE(attr, nullptr);
3571+ const auto fusedValid = OpImmediate::ToSpecified(attr->GetToDynValidShape());
3572+ ASSERT_EQ(fusedValid.size(), 2u);
3573+ ASSERT_TRUE(fusedValid[0].ConcreteValid());
3574+ EXPECT_EQ(fusedValid[0].Concrete(), dualdst_ut::TILE_M * 2);
3575+ EXPECT_EQ(fusedValid[1].Dump(), "n");
3576+}
3577+ 
3578+TEST_F(ScheduleOoOTest, DualDst_FusedCopyPreservesDynamicValidShapeOnNonSplitAxis_DirectionN)
3579+{
3580+ auto g = dualdst_ut::BuildDualDstGraph_2({dualdst_ut::TILE_M, dualdst_ut::TILE_N * 2},
3581+ {dualdst_ut::TILE_M, dualdst_ut::TILE_N}, {0, 0}, {0, dualdst_ut::TILE_N});
3582+ const std::vector<SymbolicScalar> validShape = {SymbolicScalar("m"), SymbolicScalar(dualdst_ut::TILE_N)};
3583+ for (Operation* copy : {g.copy0, g.copy1}) {
3584+ copy->GetOutputOperand(0)->UpdateDynValidShape(validShape);
3585+ auto attr = std::dynamic_pointer_cast<CopyOpAttribute>(copy->GetOpAttribute());
3586+ ASSERT_NE(attr, nullptr);
3587+ attr->SetToDynValidShape(OpImmediate::Specified(validShape));
3588+ }
3589+ 
3590+ OoOScheduler s(*g.func);
3591+ ASSERT_EQ(s.Init(g.func->Operations().DuplicatedOpList(), CORE_INIT_CONFIGS_HARDWARE_TWO), SUCCESS);
3592+ dualdst_ut::InjectCoreMap(s, g);
3593+ s.SetEnableDualDst(true);
3594+ ASSERT_EQ(s.dualDstEngine_.RunDualDstFuse(), SUCCESS);
3595+ 
3596+ Operation* dual = dualdst_ut::FindDualDstOp(*g.func);
3597+ ASSERT_NE(dual, nullptr);
3598+ auto attr = std::dynamic_pointer_cast<CopyOpAttribute>(dual->GetOpAttribute());
3599+ ASSERT_NE(attr, nullptr);
3600+ const auto fusedValid = OpImmediate::ToSpecified(attr->GetToDynValidShape());
3601+ ASSERT_EQ(fusedValid.size(), 2u);
3602+ EXPECT_EQ(fusedValid[0].Dump(), "m");
3603+ ASSERT_TRUE(fusedValid[1].ConcreteValid());
3604+ EXPECT_EQ(fusedValid[1].Concrete(), dualdst_ut::TILE_N * 2);
3605+}
3606+ 
3549// 验证融合后两个 UB_ALLOC 互相记录 pairedDualDstAlloc,3607// 验证融合后两个 UB_ALLOC 互相记录 pairedDualDstAlloc,
3550// 且 L0C_ALLOC 不会被误标记为 DualDst alloc。3608// 且 L0C_ALLOC 不会被误标记为 DualDst alloc。
3551TEST_F(ScheduleOoOTest, DualDst_AllocQueryHelpers_AfterFuse)3609TEST_F(ScheduleOoOTest, DualDst_AllocQueryHelpers_AfterFuse)
@@ -591,7 +591,10 @@ def set_debug_options(
591 1: enabled, one-click to enable execution-related configs (e.g. swimlane graph);591 1: enabled, one-click to enable execution-related configs (e.g. swimlane graph);
592 2: enable AICORE_MODEL simulation;592 2: enable AICORE_MODEL simulation;
593 3: enable runtime dependency-verification data dump;593 3: enable runtime dependency-verification data dump;
594- 4: enable runtime GM memory out-of-bounds check.594+ 4: enable runtime GM memory out-of-bounds checks and emit modulo assertions
595+ at the control-flow entry for every explicitly registered, normalized
596+ `assume_divisible` expression; compiler-derived expressions that were
597+ not explicitly registered are not checked.
595 598 
596 dump_pass_graph : List[str]599 dump_pass_graph : List[str]
597 Pass identifiers to dump computation graph and print IR. Empty list disables it.600 Pass identifiers to dump computation graph and print IR. Empty list disables it.
@@ -12,6 +12,7 @@
12 12 
13from .gather import gather_in_l1, gather_in_ub # noqa: F40113from .gather import gather_in_l1, gather_in_ub # noqa: F401
14from .operation import (14from .operation import (
15+ assume_divisible, # noqa: F401
15 get_operation_options, # noqa: F40116 get_operation_options, # noqa: F401
16 nop, # noqa: F40117 nop, # noqa: F401
17 online_softmax, # noqa: F40118 online_softmax, # noqa: F401
@@ -15,9 +15,57 @@ from typing import Dict, List, Optional, Tuple, Union
15from .. import pypto_impl15from .. import pypto_impl
16from .._op_wrapper import op_wrapper16from .._op_wrapper import op_wrapper
17from ..config import get_current_scope, set_options17from ..config import get_current_scope, set_options
18+from ..symbolic_scalar import SymbolicScalar
18from ..tensor import Tensor19from ..tensor import Tensor
19 20 
20 21 
22+def assume_divisible(expr: "SymbolicScalar | int", divisor: int) -> "SymbolicScalar":
23+ """
24+ Assume that ``expr`` is divisible by ``divisor`` at runtime.
25+ 
26+ Returns a ``SymbolicScalar`` representing ``expr``. ``SymbolicScalar`` inputs
27+ are returned unchanged; ``int`` inputs are converted. The normalized assumption
28+ is registered on the Program, enabling the compiler to simplify
29+ dynamic valid-shape expressions (e.g. ``min(max(vm - off, 0), T)`` → ``T``)
30+ when the user knows the runtime value is always a multiple of ``divisor``.
31+ 
32+ By default, this assumption is unchecked at runtime. With
33+ ``runtime_debug_mode=4``, codegen lowers every explicitly registered,
34+ normalized assumption expression to a modulo assertion at the control-flow
35+ entry.
36+ 
37+ If ``expr`` is a compile-time constant:
38+ - ``expr % divisor != 0`` → raises ``ValueError`` (assumption is provably false)
39+ - ``expr % divisor == 0`` → no-op (trivially true)
40+ 
41+ Parameters
42+ ----------
43+ expr : SymbolicScalar | int
44+ The runtime scalar expression assumed to be divisible.
45+ divisor : int
46+ The divisor (must be positive).
47+ 
48+ Returns
49+ -------
50+ SymbolicScalar
51+ A symbolic scalar representing ``expr``. Symbolic inputs are returned
52+ unchanged; integer inputs are converted.
53+ """
54+ if isinstance(expr, int):
55+ expr = SymbolicScalar(expr)
56+ if divisor <= 0:
57+ raise ValueError(f"divisor must be positive, got {divisor}")
58+ if expr.is_concrete() and int(expr) % divisor != 0:
59+ raise ValueError(f"assume_divisible: constant {int(expr)} is not divisible by {divisor}")
60+ from ..functions import get_current_function
61+ 
62+ func = get_current_function()
63+ if func is None:
64+ return expr
65+ func.base.RegisterDivisibleAssumption(expr, divisor)
66+ return expr
67+ 
68+ 
21@op_wrapper69@op_wrapper
22def transposed_batchmatmul(tensor_a: Tensor, tensor_b: Tensor, out_dtype) -> Tensor:70def transposed_batchmatmul(tensor_a: Tensor, tensor_b: Tensor, out_dtype) -> Tensor:
23 """71 """
@@ -1,248 +1,256 @@
1-# PTO Frontend Developer Documentation1+# PTO 前端开发者文档
2 2 
3-## Overview3+> 说明:本中文文档为英文版 `developer_doc.md` 的翻译版本;若中英文内容存在出入或歧义,请**以英文版为准**。
4 4 
5-The PTO Frontend is responsible for parsing Python functions decorated with `@pypto.frontend.jit` or `@pypto.frontend.function` and converting them into PTO intermediate representation (IR). The frontend provides a high-level, Python-native interface for writing optimized tensor computation kernels while maintaining full control over low-level execution details.5+## 概览
6 6 
7-This document provides a comprehensive guide for developers working on or extending the PTO frontend parser.7+PTO 前端负责解析使用 `@pypto.frontend.jit` 或 `@pypto.frontend.function` 装饰的 Python 函数,并将其转换为 PTO 中间表示(IR)。前端为编写高性能张量计算内核提供了一个高级、Python 原生的接口,同时允许用户对底层执行细节保持完全控制。
8 8 
9-## Architecture9+本文档为参与 PTO 前端解析器开发、维护或扩展的开发者提供一份全面指南。
10 10 
11-### Parsing Pipeline11+## 架构
12 12 
13-The frontend follows a multi-stage pipeline from source code to executable IR:13+### 解析流水线
14 14 
15-**Stage 1: Source Extraction** - The `Source` class extracts the source code from a decorated function using Python's `inspect` module. It handles various edge cases including Jupyter notebooks, nested classes, and maintains source location information for error reporting.15+前端采用从源代码到可执行 IR 的多阶段流水线:
16 16 
17-**Stage 2: Python AST Parsing** - The source code is parsed into Python's standard Abstract Syntax Tree (AST) using the built-in `ast.parse()` function.17+**阶段 1:源代码提取** —— `Source` 类使用 Python 的 `inspect` 模块从被装饰的函数中提取源代码。它处理包含 Jupyter notebook、嵌套类等多种边界情况,并保留源位置(source location)信息以支持错误报告。
18 18 
19-**Stage 3: Doc AST Conversion** - Python AST nodes are converted to "doc AST" nodes, which provide a stable interface independent of Python version changes. This abstraction layer ensures compatibility across Python versions (minimum 3.9+).19+**阶段 2:Python AST 解析** —— 使用内置的 `ast.parse()` 将源代码解析为 Python 标准抽象语法树(AST)。
20 20 
21-**Stage 4: Liveness Analysis** - The `LivenessAnalyzer` walks the doc AST to determine when variables are last used, enabling automatic memory management by inserting deletion points.21+**阶段 3:Doc AST 转换** —— 将 Python AST 节点转换为 “doc AST” 节点。doc AST 提供了一个独立于 Python 版本变化的稳定接口。这一抽象层确保跨 Python 版本兼容(最低 3.9+)。
22 22 
23-**Stage 5: Parsing & IR Generation** - The `Parser` class uses the visitor pattern to traverse the doc AST and generate PTO IR constructs. During this phase, the parser maintains variable scopes using the `Context` class, evaluates expressions using the `ExprEvaluator`, and reports errors using the `Diagnostics` system.23+**阶段 4:活性分析(Liveness Analysis)** —— `LivenessAnalyzer` 遍历 doc AST,确定变量的最后一次使用位置,从而通过插入删除点来实现自动内存管理。
24 24 
25-**Stage 6: Lazy Execution** - The `JitCallableWrapper` defers actual parsing until the first function call, allowing for dynamic shape binding and cost model evaluation before compilation.25+**阶段 5:解析与 IR 生成** —— `Parser` 类使用访问者(visitor)模式遍历 doc AST 并生成 PTO IR。在此阶段,解析器通过 `Context` 类维护变量作用域,通过 `ExprEvaluator` 计算表达式,并通过 `Diagnostics` 系统报告错误。
26 26 
27-## Module Structure and Responsibilities27+**阶段 6:惰性执行(Lazy Execution)** —— `JitCallableWrapper` 将实际解析延迟到函数第一次调用时执行,以便在编译前进行动态形状绑定与代价模型评估。
28 28 
29-### Core Modules29+## 模块结构与职责
30+ 
31+### 核心模块
30 32 
31#### `__init__.py`33#### `__init__.py`
32 34 
33-The main entry point that exports the public API:35+对外导出公共 API 的主要入口:
34-- `jit` decorator for JIT compilation36+- `jit`:用于 JIT 编译的装饰器
35-- `function` decorator for inline function expansion37+- `function`:用于内联函数展开的装饰器
36-- `dynamic()` function for creating symbolic dimensions38+- `dynamic()`:用于创建符号维度(symbolic dimensions)
37 39 
38#### `parser/entry.py`40#### `parser/entry.py`
39 41 
40-Provides the entry points and wrapper classes for JIT compilation:42+提供 JIT 编译的入口函数与包装器类:
41-- `parse()`: Main parsing function that orchestrates the pipeline43+- `parse()`:主解析函数,负责编排整体流水线
42-- `jit()`: Decorator factory for JIT compilation with options44+- `jit()`:JIT 编译的装饰器工厂(带选项)
43-- `function`: Decorator for nested function inline expansion45+- `function`:用于嵌套函数内联展开的装饰器
44-- `JitCallableWrapper`: Makes parsed functions callable with torch tensors46+- `JitCallableWrapper`:使已解析函数可用 torch 张量调用
45-- Helper functions for tensor data conversion and shape matching47+- 张量数据转换与形状匹配的辅助函数
46 48 
47-Key Responsibilities:49+关键职责:
48-- Bridging the frontend parser with runtime execution50+- 将前端解析器与运行时执行桥接起来
49-- Managing lazy parsing and caching51+- 管理惰性解析与缓存
50-- Handling dynamic dimension binding52+- 处理动态维度绑定
51-- Integrating cost model evaluation53+- 集成代价模型评估
52-- Converting between torch tensors and PTO tensor data54+- 在 torch 张量与 PTO 张量数据之间进行转换
53 55 
54#### `parser/parser.py`56#### `parser/parser.py`
55 57 
56-The heart of the frontend, containing the main `Parser` class that implements the visitor pattern to traverse the doc AST and generate PTO IR. This is the largest module at 1558 lines.58+前端的核心模块,包含主 `Parser` 类。该类实现访问者模式以遍历 doc AST 并生成 PTO IR。该模块规模最大(约 1558 行)。
57 59 
58-Key Responsibilities:60+关键职责:
59-- AST traversal using visitor pattern61+- 使用访问者模式遍历 AST
60-- Variable scope management via Context62+- 通过 Context 进行变量作用域管理
61-- Expression evaluation via ExprEvaluator63+- 通过 ExprEvaluator 进行表达式求值
62-- Statement and expression parsing64+- 解析语句与表达式
63-- Control flow handling (if/else, for loops)65+- 处理控制流(if/else、for 循环)
64-- Function signature extraction66+- 提取函数签名(输入/输出)
65-- Automatic variable deletion based on liveness analysis67+- 基于活性分析自动插入变量删除点
66-- Nested function inlining68+- 内联展开嵌套函数
67 69 
68-The parser maintains several important pieces of state:70+解析器维护的关键状态包括:
69-- `diag`: Diagnostics instance for error reporting71+- `diag`:Diagnostics 实例,用于错误报告
70-- `context`: Context instance for variable scoping72+- `context`:Context 实例,用于变量作用域管理
71-- `delete_after`: Mapping from statement IDs to variables to delete73+- `delete_after`:从语句 ID 映射到需删除变量的表
72-- `_signature_cache`: Cached function signature (inputs/outputs)74+- `_signature_cache`:缓存的函数签名(输入/输出)
73 75 
74#### `parser/context.py`76#### `parser/context.py`
75 77 
76-Manages variable scoping and lifetime during parsing using a stack-based approach.78+使用基于栈(stack)的方式管理解析期间的变量作用域与生命周期。
77 79 
78-Key Classes:80+关键类:
79-- `ContextFrame`: Represents a single scope (block or function body)81+- `ContextFrame`:表示单个作用域(代码块或函数体)
80-- `Context`: Stack of frames with variable name-to-value mappings82+- `Context`:由多个 frame 组成的栈,维护变量名到值的映射
81 83 
82-Key Responsibilities:84+关键职责:
83-- Tracking variable definitions and shadowing85+- 跟踪变量定义与遮蔽(shadowing)
84-- Providing context managers for automatic scope cleanup86+- 提供上下文管理器,用于自动作用域清理
85-- Supporting variable updates within scopes87+- 支持在作用域内更新变量
86-- Managing marked-for-deletion variables from liveness analysis88+- 管理来自活性分析的“标记为删除”变量
87 89 
88-The context system allows the parser to maintain proper variable scoping across nested blocks (if statements, loops, function bodies) while supporting Python's shadowing semantics.90+Context 系统使解析器能够在嵌套代码块(if、循环、函数体)之间维持正确的变量作用域,同时支持 Python 的遮蔽语义。
89 91 
90#### `parser/diagnostics.py`92#### `parser/diagnostics.py`
91 93 
92-Comprehensive error reporting system with rich, user-friendly error messages.94+完整的错误报告系统,提供丰富且用户友好的错误信息。
93 95 
94-Key Classes:96+关键类:
95-- `Source`: Source code representation with location tracking97+- `Source`:源代码表示与位置跟踪
96-- `Span`: Source location span (file, line, column ranges)98+- `Span`:源位置范围(文件、行列范围)
97-- `DiagnosticLevel`: Error severity levels (BUG, ERROR, WARNING, INFO, DEBUG)99+- `DiagnosticLevel`:错误级别(BUG、ERROR、WARNING、INFO、DEBUG)
98-- `DiagnosticItem`: Individual diagnostic message with location100+- `DiagnosticItem`:带位置信息的单条诊断消息
@@ -0,0 +1,458 @@
1+# PTO Frontend Developer Documentation
2+ 
3+## Overview
4+ 
5+The PTO Frontend is responsible for parsing Python functions decorated with `@pypto.frontend.jit` or `@pypto.frontend.function` and converting them into PTO intermediate representation (IR). The frontend provides a high-level, Python-native interface for writing optimized tensor computation kernels while maintaining full control over low-level execution details.
6+ 
7+This document provides a comprehensive guide for developers working on or extending the PTO frontend parser.
8+ 
9+## Architecture
10+ 
11+### Parsing Pipeline
12+ 
13+The frontend follows a multi-stage pipeline from source code to executable IR:
14+ 
15+**Stage 1: Source Extraction** - The `Source` class extracts the source code from a decorated function using Python's `inspect` module. It handles various edge cases including Jupyter notebooks, nested classes, and maintains source location information for error reporting.
16+ 
17+**Stage 2: Python AST Parsing** - The source code is parsed into Python's standard Abstract Syntax Tree (AST) using the built-in `ast.parse()` function.
18+ 
19+**Stage 3: Doc AST Conversion** - Python AST nodes are converted to "doc AST" nodes, which provide a stable interface independent of Python version changes. This abstraction layer ensures compatibility across Python versions (minimum 3.9+).
20+ 
21+**Stage 4: Liveness Analysis** - The `LivenessAnalyzer` walks the doc AST to determine when variables are last used, enabling automatic memory management by inserting deletion points.
22+ 
23+**Stage 5: Parsing & IR Generation** - The `Parser` class uses the visitor pattern to traverse the doc AST and generate PTO IR constructs. During this phase, the parser maintains variable scopes using the `Context` class, evaluates expressions using the `ExprEvaluator`, and reports errors using the `Diagnostics` system.
24+ 
25+**Stage 6: Lazy Execution** - The `JitCallableWrapper` defers actual parsing until the first function call, allowing for dynamic shape binding and cost model evaluation before compilation.
26+ 
27+## Module Structure and Responsibilities
28+ 
29+### Core Modules
30+ 
31+#### `__init__.py`
32+ 
33+The main entry point that exports the public API:
34+- `jit` decorator for JIT compilation
35+- `function` decorator for inline function expansion
36+- `dynamic()` function for creating symbolic dimensions
37+ 
38+#### `parser/entry.py`
39+ 
40+Provides the entry points and wrapper classes for JIT compilation:
41+- `parse()`: Main parsing function that orchestrates the pipeline
42+- `jit()`: Decorator factory for JIT compilation with options
43+- `function`: Decorator for nested function inline expansion
44+- `JitCallableWrapper`: Makes parsed functions callable with torch tensors
45+- Helper functions for tensor data conversion and shape matching
46+ 
47+Key Responsibilities:
48+- Bridging the frontend parser with runtime execution
49+- Managing lazy parsing and caching
50+- Handling dynamic dimension binding
51+- Integrating cost model evaluation
52+- Converting between torch tensors and PTO tensor data
53+ 
54+#### `parser/parser.py`
55+ 
56+The heart of the frontend, containing the main `Parser` class that implements the visitor pattern to traverse the doc AST and generate PTO IR. This is the largest module at 1558 lines.
57+ 
58+Key Responsibilities:
59+- AST traversal using visitor pattern
60+- Variable scope management via Context
61+- Expression evaluation via ExprEvaluator
62+- Statement and expression parsing
63+- Control flow handling (if/else, for loops)
64+- Function signature extraction
65+- Automatic variable deletion based on liveness analysis
66+- Nested function inlining
67+ 
68+The parser maintains several important pieces of state:
69+- `diag`: Diagnostics instance for error reporting
70+- `context`: Context instance for variable scoping
71+- `delete_after`: Mapping from statement IDs to variables to delete
72+- `_signature_cache`: Cached function signature (inputs/outputs)
73+ 
74+#### `parser/context.py`
75+ 
76+Manages variable scoping and lifetime during parsing using a stack-based approach.
77+ 
78+Key Classes:
79+- `ContextFrame`: Represents a single scope (block or function body)
80+- `Context`: Stack of frames with variable name-to-value mappings
81+ 
82+Key Responsibilities:
83+- Tracking variable definitions and shadowing
84+- Providing context managers for automatic scope cleanup
85+- Supporting variable updates within scopes
86+- Managing marked-for-deletion variables from liveness analysis
87+ 
88+The context system allows the parser to maintain proper variable scoping across nested blocks (if statements, loops, function bodies) while supporting Python's shadowing semantics.
89+ 
90+#### `parser/diagnostics.py`
91+ 
92+Comprehensive error reporting system with rich, user-friendly error messages.
93+ 
94+Key Classes:
95+- `Source`: Source code representation with location tracking
96+- `Span`: Source location span (file, line, column ranges)
97+- `DiagnosticLevel`: Error severity levels (BUG, ERROR, WARNING, INFO, DEBUG)
98+- `DiagnosticItem`: Individual diagnostic message with location
99+- `Diagnostics`: Main diagnostics manager
100+- `DiagnosticContext`: Context for collecting diagnostics
101+ 
102+Key Responsibilities:
103+- Pretty-printing errors with source context and color coding
104+- Showing multiple lines of context around error locations
105+- Supporting different diagnostic levels
106+- Handling special cases (Jupyter notebooks, nested classes)
107+- Providing location information for all AST nodes
108+ 
109+Error messages include:
110+- Color-coded severity levels
111+- File name and line/column numbers
112+- Source code context (2 lines before, 4 lines after)
113+- Caret indicators (^) pointing to the error location
114+ 
115+#### `parser/error.py`
116+ 
117+Exception classes for parser errors with customizable backtrace control.
118+ 
119+Key Classes:
120+- `ParserError`: Base exception associating errors with AST nodes
121+- `RenderedParserError`: Indicates error already formatted and displayed
122+ 
123+Key Features:
124+- Environment variable `PTO_BACKTRACE` controls whether full backtraces are shown
125+- Default behavior (PTO_BACKTRACE=0) shows only user-friendly error messages
126+- Setting PTO_BACKTRACE=1 enables full Python stack traces for debugging
127+- Automatic cleanup of multiprocessing child processes on error
128+ 
129+#### `parser/evaluator.py`
130+ 
131+Evaluates Python expressions during parsing to resolve concrete values.
132+ 
133+Key Class:
134+- `ExprEvaluator`: Expression evaluator using Python's `compile()` and `eval()`
135+ 
136+Key Responsibilities:
137+- Evaluating type annotations (e.g., `pypto.Tensor((N, M), pypto.DT_FP32)`)
138+- Resolving constant expressions
139+- Converting SymbolicScalar to concrete values when possible
140+- Providing proper error context for evaluation failures
141+ 
142+The evaluator operates on the parser's variable table, allowing access to both user-defined variables and the pypto module namespace.
143+ 
144+#### `parser/liveness.py`
145+ 
146+Implements liveness analysis for automatic memory management.
147+ 
148+Key Class:
149+- `LivenessAnalyzer`: AST visitor that tracks variable uses and definitions
150+ 
151+Key Responsibilities:
152+- Recording all uses of each variable
153+- Identifying last-use points for automatic deletion
154+- Handling loop-aware analysis (variables used in loops)
155+- Respecting exempt variables (function parameters, explicit deletes)
156+- Generating deletion point mapping (statement ID → variable names)
157+ 
158+The analyzer helps reduce memory usage by automatically deleting variables that are no longer needed, without requiring manual `del` statements from users.
159+ 
160+#### `parser/doc.py`
161+ 
162+Registry system for bidirectional conversion between Python AST and doc AST.
163+ 
164+Key Classes:
165+- `Entry`: Mapping entry storing conversion functions
166+- `Registry`: Global registry of all AST node conversions
167+ 
168+Key Functions:
169+- `parse()`: Parse source string to doc AST
170+- `to_doc()`: Convert Python AST node to doc AST node
171+- `from_doc()`: Convert doc AST node to Python AST node
172+- `register()`: Register conversion functions for new node types
173+ 
174+Key Responsibilities:
175+- Maintaining bidirectional AST conversion mappings
176+- Providing extensible registration system
177+- Supporting visitor and transformer patterns
178+- Handling node type resolution
179+ 
180+#### `parser/doc_core.py`
181+ 
182+Defines the core AST node classes that mirror Python's standard AST.
183+ 
184+Key Base Classes:
185+- `AST`: Base class for all doc AST nodes
186+- `NodeVisitor`: Base class for AST traversal
187+- `NodeTransformer`: Base class for AST transformation
188+ 
189+Node Categories:
190+- `mod`: Module-level nodes (Module, Interactive, Expression)
191+- `stmt`: Statement nodes (FunctionDef, Assign, For, If, Return, etc.)
192+- `expr`: Expression nodes (BinOp, Call, Name, Constant, etc.)
193+- `operator`: Arithmetic operators (Add, Sub, Mult, Div, etc.)
194+- `boolop`: Boolean operators (And, Or)
195+- `unaryop`: Unary operators (Not, UAdd, USub, Invert)
196+- `cmpop`: Comparison operators (Eq, Lt, Gt, etc.)
197+ 
198+This abstraction layer ensures the parser works consistently across Python versions by providing a stable interface independent of changes to Python's standard AST.
199+ 
200+## Key Concepts
201+ 
202+### Diagnostic System with Source Locations
203+ 
204+Every AST node carries source location information (line number, column offset, end line, end column). When an error occurs, the `Diagnostics` system uses this information to:
205+ 
206+1. Read the original source file
207+2. Extract context lines (2 before, 4 after the error)
208+3. Highlight the error line with color
209+4. Add caret indicators (^) pointing to the exact error location
210+5. Print the error message with severity level
211+ 
212+This provides a user experience similar to modern compilers like Rust or Clang.
213+ 
214+### Liveness Analysis for Memory Management
215+ 
216+The `LivenessAnalyzer` performs a static analysis pass over the AST before parsing to determine optimal deletion points:
217+ 
218+1. **Track definitions**: Record where each variable is defined
219+2. **Track uses**: Record all uses of each variable in order
220+3. **Compute last use**: Identify the statement where each variable is last used
221+4. **Generate deletion points**: Create a mapping from statement IDs to variables to delete
222+ 
223+During parsing, after executing each statement, the parser checks if any variables should be deleted and marks them for cleanup. This optimization is especially important for large tensor operations where memory usage is critical.
224+ 
225+Special cases handled:
226+- Loop variables are exempt from auto-deletion
227+- Variables used in loops are deleted after the loop exits (not per-iteration)
228+- Variables defined inside loops can be deleted per-iteration
229+- Explicit `del` statements mark variables as exempt from auto-deletion
230+ 
231+### Doc AST Abstraction Layer
232+ 
233+The doc AST provides a stable interface that isolates the parser from Python AST changes. Benefits:
234+ 
235+**Version Independence**: Python's AST can change between versions (e.g., Python 3.8 added position information). The doc AST provides a consistent interface.
236+ 
237+**Simplified Interface**: Removes unnecessary Python features (e.g., type comments, async/await) that aren't supported in PTO scripts.
238+ 
239+**Extensibility**: Makes it easier to add custom AST nodes or attributes specific to PTO.
240+ 
241+**Bidirectional Conversion**: The registry system allows converting between Python AST and doc AST in both directions, useful for debugging and AST manipulation.
242+ 
243+## Usage Examples
244+ 
245+### Basic Kernel with JIT Decorator
246+ 
247+```python
248+import pypto
249+ 
250+N = 1024
251+M = 1024
252+ 
253+@pypto.frontend.jit()
254+def basic_addsub(
255+ a: pypto.Tensor((N, M), pypto.DT_FP32),
256+ b: pypto.Tensor((N, M), pypto.DT_FP32),
257+ c: pypto.Tensor((N, M), pypto.DT_FP32),
258+ d: pypto.Tensor((N, M), pypto.DT_FP32),
259+):
260+ pypto.set_vec_tile_shapes(32, 32)
261+ 
262+ c[:] = pypto.add(a, b)
263+ d[:] = pypto.sub(a, b)
264+```
265+ 
266+**What the parser does:**
267+1. Extracts the function signature to determine inputs and outputs
268+2. Parses the function body into doc AST
269+3. Creates PTO tensor IR nodes for `c` and `d`
270+4. Converts `pypto.add(a, b)` and `pypto.sub(a, b)` into PTO operation IR
271+5. Handles the slice assignment `c[:] = ...` as tensor fill operations
272+ 
273+### Dynamic Dimensions
274+ 
275+```python
276+import pypto
277+ 
278+N = pypto.DYNAMIC # Symbolic dimension
279+M = 1024
280+ 
281+@pypto.frontend.jit()
282+def basic_dynamic(
283+ a: pypto.Tensor((N, M), pypto.DT_FP32),
284+ b: pypto.Tensor((N, M), pypto.DT_FP32),
285+ out: pypto.Tensor((N, M), pypto.DT_FP32),
286+):
287+ pypto.set_vec_tile_shapes(32, 32)
288+ 
289+ # N is symbolic here, resolved at runtime
290+ for bs_idx in pypto.loop(32):
291+ tile_a = pypto.view(a, (32, 1024), [bs_idx * 32, 0])
292+ tile_b = pypto.view(b, (32, 1024), [bs_idx * 32, 0])
293+ out[bs_idx * 32: (bs_idx + 1) * 32, :] = pypto.add(tile_a, tile_b)
294+ 
295+```
296+ 
297+**What the parser does:**
298+1. Recognizes `N` as a SymbolicScalar (marked by `pypto.DYNAMIC`)
299+2. Keeps `N` symbolic during parsing
300+3. During first execution, binds `N` to the actual input shape
301+4. Validates that all uses of `N` are consistent
302+5. Generates IR with symbolic dimension that gets resolved at runtime
303+ 
304+### Loop Constructs
305+ 
306+```python
307+@pypto.frontend.jit()
308+def basic_loop(
309+ a: pypto.Tensor((N, M), pypto.DT_FP32),
310+ b: pypto.Tensor((N, M), pypto.DT_FP32),
311+ out: pypto.Tensor((N, M), pypto.DT_FP32),
312+):
313+ pypto.set_vec_tile_shapes(32, 32)
314+ 
315+ for _ in pypto.loop(10):
316+ a[:] = pypto.add(a, b)
317+ out[:] = a
318+ 
319+```
320+ 
321+**What the parser does:**
322+1. Recognizes `pypto.loop(10)` as a special loop construct
323+2. Generates PTO loop IR with iteration count of 10
324+3. Handles loop body as a nested scope
325+4. The loop variable `_` is marked as exempt from auto-deletion
326+5. Variables used in loop (a, b) are not deleted until after loop exits
327+ 
328+### Nested Function Inlining
329+ 
330+```python
331+@pypto.frontend.function
332+def inner_add(
333+ x: pypto.Tensor((8,), pypto.DT_FP32),
334+ bias: pypto.Tensor((8,), pypto.DT_FP32),
335+ out: pypto.Tensor((8,), pypto.DT_FP32),
336+):
337+ out[:] = pypto.add(x, bias)
338+ 
339+ 
340+@pypto.frontend.jit
341+def outer_kernel(
342+ a: pypto.Tensor((8,), pypto.DT_FP32),
343+ b: pypto.Tensor((8,), pypto.DT_FP32),
344+ out: pypto.Tensor((8,), pypto.DT_FP32),
345+):
346+ pypto.set_vec_tile_shapes(1, 1, 16, 32)
347+ inner_add(a, b, out) # Inlined during parsing
348+ 
349+```
350+ 
351+**What the parser does:**
352+1. Marks `inner_add` with `NestedFunctionMarker` (not compiled separately)
353+2. When parsing `outer_kernel`, recognizes call to `inner_add`
354+3. Inlines the body of `inner_add` into `outer_kernel`
355+4. Handles parameter mapping (x→a, bias→b)
356+5. Generates a single PTO function with the inlined code
357+ 
358+### Control Flow
359+ 
360+```python
361+@pypto.frontend.jit()
362+def conditional_kernel(
363+ a: pypto.Tensor((N, M), pypto.DT_FP32),
364+ b: pypto.Tensor((N, M), pypto.DT_FP32),
365+ out: pypto.Tensor((N, M), pypto.DT_FP32),
366+ flag: bool,
367+):
368+ 
369+ if flag:
370+ out[:] = pypto.add(a, b)
371+ else:
372+ out[:] = pypto.sub(a, b)
373+```
374+ 
375+**What the parser does:**
376+1. Evaluates the condition `flag` at parse time if it's a constant
377+2. If the condition is known, can optimize by only generating IR for the taken branch
378+3. If the condition is runtime-determined, generates conditional IR
379+4. Handles variable scoping properly (out is visible in both branches)
380+ 
381+## Best Practices
382+ 
383+### Code Organization
384+ 
385+**Group related visitor methods together** in parser.py:
386+- Statement visitors (visit_assign, visit_for, visit_if, etc.)
387+- Expression visitors (visit_call, visit_bin_op, visit_name, etc.)
388+- Helper methods (private methods with `_` prefix)
389+ 
390+**Keep visitor methods focused** - each should handle one node type and delegate to helpers for complex logic.
391+ 
392+**Use descriptive variable names** - prefer `input_tensors` over `inputs`, `loop_iterator` over `i`.
393+ 
394+### Error Handling
395+ 
396+**Provide actionable error messages:**
397+- Bad: "Invalid syntax"
398+- Good: "Expected tensor type annotation, got 'list'. Use pypto.Tensor((shape,), dtype) instead."
399+ 
400+**Include context in errors:**
401+- Show what was expected vs. what was found
402+- Suggest fixes when possible
403+- Reference documentation for complex features
404+ 
405+**Use appropriate diagnostic levels:**
406+- ERROR: For user errors that prevent compilation
407+- WARNING: For potentially problematic code that still compiles
408+- INFO: For informational messages during debugging
409+- BUG: For internal parser errors that shouldn't happen
410+ 
411+### Type Annotations
412+ 
413+**Fully annotate public APIs:**
414+```python
415+def parse(program: Source, extra_vars: Optional[dict[str, Any]] = None) -> Any:
416+ """Parse a PTO script program."""
417+ pass
418+```
419+ 
420+**Annotate class attributes:**
421+```python
422+class Parser:
423+ diag: Diagnostics
424+ context: Context
425+ delete_after: dict[int, set[str]]
426+```
427+ 
428+**Use proper Optional and Union types:**
429+```python
430+def visit_node(self, node: Optional[doc.AST]) -> Union[str, int, None]:
431+ pass
432+```
433+ 
434+### Documentation
435+ 
436+**Write docstrings for all public APIs** following NumPy style.
437+ 
438+**Document non-obvious logic** with inline comments explaining the "why":
439+```python
440+# We need to pop the frame before adding the variable to avoid
441+# shadowing issues when the variable name conflicts with a loop variable
442+self.context.frames.pop()
443+self.context.add(var_name, value)
444+```
445+ 
446+**Keep documentation up-to-date** - when changing code, update the corresponding docstrings and comments.
447+ 
448+### Function-level assumption table
449+ 
450+`pypto.experimental.assume_divisible(expr, divisor)` returns a `SymbolicScalar` representing `expr`; `SymbolicScalar` inputs are returned unchanged, while `int` inputs are converted. It also records a compile-time assumption on the Program. The table stores `expr.Simplify()` and uses its `Dump()` as the key, so the stored expression and key have the same normalized form and equivalent expressions share an assumption. All Functions in the same Program can query the assumption.
451+ 
452+`InferDynShape` consumes the assumption before static valid-shape snapshots are recorded. This lets later passes such as dualdst use the static path while preserving dynamic valid shapes on non-split axes. By default, the API is an unchecked contract. With `runtime_debug_mode=4`, codegen lowers every explicitly registered, normalized assumption expression to a modulo assertion at the control-flow entry; generated code evaluates the expression using actual runtime values. Compiler-derived expressions that were not explicitly registered are not checked.
453+ 
454+## Conclusion
455+ 
456+The PTO Frontend provides a powerful and extensible system for parsing Python code into optimized tensor computation IR. By understanding the architecture, key concepts, and existing extension mechanisms documented here, developers can effectively work with, maintain, and debug the frontend parser.
457+ 
458+For questions or issues, please refer to the source code documentation, test cases, or reach out to the PTO development team.
@@ -1,459 +0,0 @@
1-# PTO 前端开发者文档
2- 
3-> 说明:本中文文档为英文版 `developer_doc.md` 的翻译版本;若中英文内容存在出入或歧义,请**以英文版为准**。
4- 
5-## 概览
6- 
7-PTO 前端负责解析使用 `@pypto.frontend.jit` 或 `@pypto.frontend.function` 装饰的 Python 函数,并将其转换为 PTO 中间表示(IR)。前端为编写高性能张量计算内核提供了一个高级、Python 原生的接口,同时允许用户对底层执行细节保持完全控制。
8- 
9-本文档为参与 PTO 前端解析器开发、维护或扩展的开发者提供一份全面指南。
10- 
11-## 架构
12- 
13-### 解析流水线
14- 
15-前端采用从源代码到可执行 IR 的多阶段流水线:
16- 
17-**阶段 1:源代码提取** —— `Source` 类使用 Python 的 `inspect` 模块从被装饰的函数中提取源代码。它处理包含 Jupyter notebook、嵌套类等多种边界情况,并保留源位置(source location)信息以支持错误报告。
18- 
19-**阶段 2:Python AST 解析** —— 使用内置的 `ast.parse()` 将源代码解析为 Python 标准抽象语法树(AST)。
20- 
21-**阶段 3:Doc AST 转换** —— 将 Python AST 节点转换为 “doc AST” 节点。doc AST 提供了一个独立于 Python 版本变化的稳定接口。这一抽象层确保跨 Python 版本兼容(最低 3.9+)。
22- 
23-**阶段 4:活性分析(Liveness Analysis)** —— `LivenessAnalyzer` 遍历 doc AST,确定变量的最后一次使用位置,从而通过插入删除点来实现自动内存管理。
24- 
25-**阶段 5:解析与 IR 生成** —— `Parser` 类使用访问者(visitor)模式遍历 doc AST 并生成 PTO IR。在此阶段,解析器通过 `Context` 类维护变量作用域,通过 `ExprEvaluator` 计算表达式,并通过 `Diagnostics` 系统报告错误。
26- 
27-**阶段 6:惰性执行(Lazy Execution)** —— `JitCallableWrapper` 将实际解析延迟到函数第一次调用时执行,以便在编译前进行动态形状绑定与代价模型评估。
28- 
29-## 模块结构与职责
30- 
31-### 核心模块
32- 
33-#### `__init__.py`
34- 
35-对外导出公共 API 的主要入口:
36-- `jit`:用于 JIT 编译的装饰器
37-- `function`:用于内联函数展开的装饰器
38-- `dynamic()`:用于创建符号维度(symbolic dimensions)
39- 
40-#### `parser/entry.py`
41- 
42-提供 JIT 编译的入口函数与包装器类:
43-- `parse()`:主解析函数,负责编排整体流水线
44-- `jit()`:JIT 编译的装饰器工厂(带选项)
45-- `function`:用于嵌套函数内联展开的装饰器
46-- `JitCallableWrapper`:使已解析函数可用 torch 张量调用
47-- 张量数据转换与形状匹配的辅助函数
48- 
49-关键职责:
50-- 将前端解析器与运行时执行桥接起来
51-- 管理惰性解析与缓存
52-- 处理动态维度绑定
53-- 集成代价模型评估
54-- 在 torch 张量与 PTO 张量数据之间进行转换
55- 
56-#### `parser/parser.py`
57- 
58-前端的核心模块,包含主 `Parser` 类。该类实现访问者模式以遍历 doc AST 并生成 PTO IR。该模块规模最大(约 1558 行)。
59- 
60-关键职责:
61-- 使用访问者模式遍历 AST
62-- 通过 Context 进行变量作用域管理
63-- 通过 ExprEvaluator 进行表达式求值
64-- 解析语句与表达式
65-- 处理控制流(if/else、for 循环)
66-- 提取函数签名(输入/输出)
67-- 基于活性分析自动插入变量删除点
68-- 内联展开嵌套函数
69- 
70-解析器维护的关键状态包括:
71-- `diag`:Diagnostics 实例,用于错误报告
72-- `context`:Context 实例,用于变量作用域管理
73-- `delete_after`:从语句 ID 映射到需删除变量的表
74-- `_signature_cache`:缓存的函数签名(输入/输出)
75- 
76-#### `parser/context.py`
77- 
78-使用基于栈(stack)的方式管理解析期间的变量作用域与生命周期。
79- 
80-关键类:
81-- `ContextFrame`:表示单个作用域(代码块或函数体)
82-- `Context`:由多个 frame 组成的栈,维护变量名到值的映射
83- 
84-关键职责:
85-- 跟踪变量定义与遮蔽(shadowing)
86-- 提供上下文管理器,用于自动作用域清理
87-- 支持在作用域内更新变量
88-- 管理来自活性分析的“标记为删除”变量
89- 
90-Context 系统使解析器能够在嵌套代码块(if、循环、函数体)之间维持正确的变量作用域,同时支持 Python 的遮蔽语义。
91- 
92-#### `parser/diagnostics.py`
93- 
94-完整的错误报告系统,提供丰富且用户友好的错误信息。
95- 
96-关键类:
97-- `Source`:源代码表示与位置跟踪
98-- `Span`:源位置范围(文件、行列范围)
99-- `DiagnosticLevel`:错误级别(BUG、ERROR、WARNING、INFO、DEBUG)
100-- `DiagnosticItem`:带位置信息的单条诊断消息
101-- `Diagnostics`:诊断管理器
102-- `DiagnosticContext`:用于收集诊断信息的上下文
103- 
104-关键职责:
105-- 带源代码上下文的美观错误输出(含颜色)
106-- 在错误位置附近显示多行上下文
107-- 支持不同诊断级别
108-- 处理特殊情况(Jupyter notebooks、嵌套类)
109-- 为所有 AST 节点提供位置信息
110- 
111-错误信息包含:
112-- 颜色区分的严重级别
113-- 文件名与行/列号
114-- 源代码上下文(前 2 行、后 4 行)
115-- 指向错误位置的插入符(^)
116- 
117-#### `parser/error.py`
118- 
119-解析器错误的异常类,并提供可配置的回溯(backtrace)控制。
120- 
121-关键类:
122-- `ParserError`:基础异常,将错误与 AST 节点关联
123-- `RenderedParserError`:表示错误已格式化并显示
124- 
125-关键特性:
126-- 环境变量 `PTO_BACKTRACE` 控制是否展示完整回溯
127-- 默认行为(`PTO_BACKTRACE=0`)只显示用户友好的错误信息
128-- 设置 `PTO_BACKTRACE=1` 开启完整 Python 栈追踪,便于调试
129-- 出错时自动清理多进程子进程
130- 
131-#### `parser/evaluator.py`
132- 
133-在解析期间对 Python 表达式求值,以解析出具体值。
134- 
135-关键类:
136-- `ExprEvaluator`:使用 Python 的 `compile()` 与 `eval()` 的表达式求值器
137- 
138-关键职责:
139-- 计算类型注解(例如 `pypto.Tensor((N, M), pypto.DT_FP32)`)
140-- 解析常量表达式
141-- 尽可能将 SymbolicScalar 转换为具体值
142-- 在求值失败时提供正确的错误上下文
143- 
144-求值器基于解析器的变量表运行,因此能够访问用户定义变量以及 `pypto` 模块命名空间。
145- 
146-#### `parser/liveness.py`
147- 
148-实现用于自动内存管理的活性分析。
149- 
150-关键类:
151-- `LivenessAnalyzer`:用于跟踪变量使用与定义的 AST visitor
152- 
153-关键职责:
154-- 记录每个变量的所有使用点
155-- 找出每个变量的最后使用位置以便自动删除
156-- 处理“循环感知”的分析(变量在循环中的使用)
157-- 尊重被豁免变量(函数参数、显式删除)
158-- 生成删除点映射(语句 ID → 变量名)
159- 
160-该分析通过自动删除不再需要的变量来降低内存使用,尤其适用于大型张量运算,而不要求用户手写 `del`。
161- 
162-处理的特殊情况:
163-- 循环变量不参与自动删除
164-- 在循环中使用的变量在循环结束后删除(而非每次迭代)
165-- 在循环内定义的变量可按迭代删除
166-- 显式 `del` 会将变量标记为不参与自动删除
167- 
168-#### `parser/doc.py`
169- 
170-用于 Python AST 与 doc AST 之间双向转换的注册系统。
171- 
172-关键类:
173-- `Entry`:存储转换函数的映射条目
174-- `Registry`:全局注册表,记录所有 AST 节点转换
175- 
176-关键函数:
177-- `parse()`:将源字符串解析为 doc AST
178-- `to_doc()`:将 Python AST 节点转换为 doc AST 节点
179-- `from_doc()`:将 doc AST 节点转换回 Python AST 节点
180-- `register()`:为新节点类型注册转换函数
181- 
182-关键职责:
183-- 维护双向 AST 转换映射
184-- 提供可扩展的注册机制
185-- 支持 visitor/transformer 模式
186-- 处理节点类型解析
187- 
188-#### `parser/doc_core.py`
189- 
190-定义核心 AST 节点类,镜像 Python 标准 AST。
191- 
192-关键基类:
193-- `AST`:所有 doc AST 节点的基类
194-- `NodeVisitor`:AST 遍历基类
195-- `NodeTransformer`:AST 变换基类
196- 
197-节点类别:
198-- `mod`:模块级节点(Module、Interactive、Expression)
199-- `stmt`:语句节点(FunctionDef、Assign、For、If、Return 等)
200-- `expr`:表达式节点(BinOp、Call、Name、Constant 等)
201-- `operator`:算术运算符(Add、Sub、Mult、Div 等)
202-- `boolop`:布尔运算符(And、Or)
203-- `unaryop`:一元运算符(Not、UAdd、USub、Invert)
204-- `cmpop`:比较运算符(Eq、Lt、Gt 等)
205- 
206-该抽象层通过提供稳定接口,确保解析器可跨 Python 版本一致工作,从而不受 Python 标准 AST 变更的影响。
207- 
208-## 关键概念
209- 
210-### 带源位置的诊断系统
211- 
212-每个 AST 节点都携带源位置(行号、列偏移、结束行、结束列)。当发生错误时,`Diagnostics` 系统使用这些信息来:
213- 
214-1. 读取原始源文件
215-2. 提取上下文行(前 2 行、后 4 行)
216-3. 用颜色高亮错误行
217-4. 用插入符(^)指向精确错误位置
218-5. 输出带严重级别的错误信息
219- 
220-这提供了类似 Rust 或 Clang 等现代编译器的使用体验。
221- 
222-### 用于内存管理的活性分析
223- 
224-`LivenessAnalyzer` 在解析前对 AST 执行静态分析,计算最优删除点:
225- 
226-1. **跟踪定义**:记录每个变量的定义位置
227-2. **跟踪使用**:按顺序记录每个变量的所有使用点
228-3. **计算最后使用**:确定每个变量最后一次被使用的语句
229-4. **生成删除点**:创建映射(语句 ID → 需要删除的变量名集合)
230- 
231-在解析阶段,每执行完一条语句后,解析器会检查是否有变量需要被删除,并将它们标记为待清理。该优化对大型张量操作尤为关键,可显著降低内存占用。
232- 
233-处理的特殊情况:
234-- 循环变量不参与自动删除
235-- 在循环中使用的变量在循环结束后删除(而非每次迭代)
236-- 在循环内定义的变量可按迭代删除
237-- 显式 `del` 语句会将变量标记为不参与自动删除
238- 
239-### Doc AST 抽象层
240- 
241-doc AST 提供稳定接口,将解析器与 Python AST 的变更隔离开来。其优势包括:
242- 
243-**版本无关性**:Python AST 在不同版本之间可能变化(例如 Python 3.8 增加了位置信息)。doc AST 提供一致接口。
244- 
245-**简化接口**:移除 PTO 脚本不支持的特性(例如 type comments、async/await)。
246- 
247-**可扩展性**:更易于添加自定义 AST 节点或 PTO 特有属性。
248- 
249-**双向转换**:注册系统支持 Python AST 与 doc AST 的双向转换,可用于调试与 AST 操作。
250- 
251-## 使用示例
252- 
253-### 使用 JIT 装饰器的基础内核
254- 
255-```python
256-import pypto
257- 
258-N = 1024
259-M = 1024
260- 
261-@pypto.frontend.jit()
262-def basic_addsub(
263- a: pypto.Tensor((N, M), pypto.DT_FP32),
264- b: pypto.Tensor((N, M), pypto.DT_FP32),
265- c: pypto.Tensor((N, M), pypto.DT_FP32),
266- d: pypto.Tensor((N, M), pypto.DT_FP32),
267-):
268- pypto.set_vec_tile_shapes(32, 32)
269- 
270- c[:] = pypto.add(a, b)
271- d[:] = pypto.sub(a, b)
272-```
273- 
274-**解析器会做什么:**
275-1. 提取函数签名以确定输入与输出
276-2. 将函数体解析为 doc AST
277-3. 为 `c` 与 `d` 创建 PTO 张量 IR 节点
278-4. 将 `pypto.add(a, b)` 与 `pypto.sub(a, b)` 转换为 PTO 操作 IR
279-5. 将切片赋值 `c[:] = ...` 处理为张量填充(fill)操作
280- 
281-### 动态维度
282- 
283-```python
284-import pypto
285- 
286-N = pypto.DYNAMIC # 符号维度
287-M = 1024
288- 
289-@pypto.frontend.jit()
290-def basic_dynamic(
291- a: pypto.Tensor((N, M), pypto.DT_FP32),
292- b: pypto.Tensor((N, M), pypto.DT_FP32),
293- out: pypto.Tensor((N, M), pypto.DT_FP32)
294-):
295- pypto.set_vec_tile_shapes(32, 32)
296- 
297- # 此处 N 为符号量,在运行时解析
298- for bs_idx in pypto.loop(32):
299- tile_a = pypto.view(a, (32, 1024), [bs_idx * 32, 0])
300- tile_b = pypto.view(b, (32, 1024), [bs_idx * 32, 0])
301- out[bs_idx * 32: (bs_idx + 1) * 32, :] = pypto.add(tile_a, tile_b)
302- 
303- 
304-```
305- 
306-**解析器会做什么:**
307-1. 将 `N` 识别为 SymbolicScalar(由 `pypto.DYNAMIC` 标记)
308-2. 解析期间保持 `N` 为符号量
309-3. 第一次执行时,将 `N` 绑定为实际输入形状
310-4. 校验 `N` 的所有使用保持一致
311-5. 生成含符号维度的 IR,并在运行时解析该符号维度
312- 
313-### 循环结构
314- 
315-```python
316-@pypto.frontend.jit()
317-def basic_loop(
318- a: pypto.Tensor((N, M), pypto.DT_FP32),
319- b: pypto.Tensor((N, M), pypto.DT_FP32),
320- out: pypto.Tensor((N, M), pypto.DT_FP32),
321-):
322- pypto.set_vec_tile_shapes(32, 32)
323- 
324- for _ in pypto.loop(10):
325- a[:] = pypto.add(a, b)
326- out[:] = a
327-```
328- 
329-**解析器会做什么:**
330-1. 将 `pypto.loop(10)` 识别为特殊循环结构
331-2. 生成迭代次数为 10 的 PTO loop IR
332-3. 将循环体作为嵌套作用域处理
333-4. 循环变量 `_` 被标记为不参与自动删除
334-5. 在循环中使用的变量(a、b)不会被删除,直到循环结束
335- 
336-### 嵌套函数内联
337- 
338-```python
339-@pypto.frontend.function
340-def inner_add(
341- x: pypto.Tensor((8,), pypto.DT_FP32),
342- bias: pypto.Tensor((8,), pypto.DT_FP32),
343- out: pypto.Tensor((8,), pypto.DT_FP32),
344-):
345- out[:] = pypto.add(x, bias)
346- 
347- 
348-@pypto.frontend.jit
349-def outer_kernel(
350- a: pypto.Tensor((8,), pypto.DT_FP32),
351- b: pypto.Tensor((8,), pypto.DT_FP32),
352- out: pypto.Tensor((8,), pypto.DT_FP32),
353-):
354- pypto.set_vec_tile_shapes(1, 1, 16, 32)
355- inner_add(a, b, out) # 解析期间被内联
356-```
357- 
358-**解析器会做什么:**
359-1. 用 `NestedFunctionMarker` 标记 `inner_add`(不会单独编译)
360-2. 解析 `outer_kernel` 时识别对 `inner_add` 的调用
361-3. 将 `inner_add` 的函数体内联到 `outer_kernel`
362-4. 处理参数映射(x→a,bias→b)
363-5. 生成一个包含内联代码的单一 PTO 函数
364- 
365-### 控制流
366- 
367-```python
368-@pypto.frontend.jit()
369-def conditional_kernel(
370- a: pypto.Tensor((N, M), pypto.DT_FP32),
371- b: pypto.Tensor((N, M), pypto.DT_FP32),
372- out: pypto.Tensor((N, M), pypto.DT_FP32),
373- flag: bool,
374-):
375- 
376- if flag:
377- out[:] = pypto.add(a, b)
378- else:
379- out[:] = pypto.sub(a, b)
380-```
381- 
382-**解析器会做什么:**
383-1. 若条件 `flag` 为常量,则在解析期对其求值
384-2. 如果条件已知,可通过仅生成被选分支的 IR 来进行优化
385-3. 如果条件由运行时决定,则生成条件分支 IR
386-4. 正确处理变量作用域(`result` 在两个分支中都可见)
387- 
388-## 最佳实践
389- 
390-### 代码组织
391- 
392-**在 parser.py 中将相关 visitor 方法分组**:
393-- 语句 visitor(visit_assign、visit_for、visit_if 等)
394-- 表达式 visitor(visit_call、visit_bin_op、visit_name 等)
395-- 辅助方法(以下划线 `_` 开头的私有方法)
396- 
397-**保持 visitor 方法聚焦**:每个方法只处理一种节点类型,复杂逻辑委托给辅助函数。
398- 
399-**使用更具描述性的变量名**:优先使用 `input_tensors` 而非 `inputs`,使用 `loop_iterator` 而非 `i`。
400- 
401-### 错误处理
402- 
403-**提供可操作的错误信息:**
404-- 不佳:“Invalid syntax”
405-- 更好:“Expected tensor type annotation, got 'list'. Use pypto.Tensor((shape,), dtype) instead.”
406- 
407-**在错误信息中包含上下文:**
408-- 说明期望内容与实际内容
409-- 尽可能给出修复建议
410-- 对复杂特性引用文档
411- 
412-**使用合适的诊断级别:**
413-- ERROR:会阻止编译的用户错误
414-- WARNING:可能有问题但仍可编译的代码
415-- INFO:调试时的提示信息
416-- BUG:不应该发生的解析器内部错误
417- 
418-### 类型注解
419- 
420-**为公共 API 完整添加注解:**
421-```python
422-def parse(program: Source, extra_vars: Optional[dict[str, Any]] = None) -> Any:
423- """Parse a PTO script program."""
424- pass
425-```
426- 
427-**为类属性添加注解:**
428-```python
429-class Parser:
430- diag: Diagnostics
431- context: Context
432- delete_after: dict[int, set[str]]
433-```
434- 
435-**正确使用 Optional 与 Union:**
436-```python
437-def visit_node(self, node: Optional[doc.AST]) -> Union[str, int, None]:
438- pass
439-```
440- 
441-### 文档
442- 
443-**为所有公共 API 编写 NumPy 风格 docstring。**
444- 
445-**对不直观的逻辑写明“为什么”而不是“做什么”的注释:**
446-```python
447-# We need to pop the frame before adding the variable to avoid
448-# shadowing issues when the variable name conflicts with a loop variable
449-self.context.frames.pop()
450-self.context.add(var_name, value)
451-```
452- 
453-**保持文档更新**:当修改代码时,同步更新对应 docstring 与注释。
454- 
455-## 总结
456- 
457-PTO 前端提供了强大且可扩展的系统,用于将 Python 代码解析为高性能张量计算 IR。理解本文档中的架构、关键概念与扩展机制后,开发者将能更高效地维护、调试并扩展前端解析器。
458- 
459-如有问题,请参考源码注释、测试用例,或联系 PTO 开发团队。
@@ -79,7 +79,19 @@ void BindFunction(py::module_& m)
79 })79 })
80 .def_property_readonly(80 .def_property_readonly(
81 "original_body", [](const Function& self) -> ir::SeqStmtsPtr { return self.originalBody_; },81 "original_body", [](const Function& self) -> ir::SeqStmtsPtr { return self.originalBody_; },
82- "Original function body statement");82+ "Original function body statement")
83+ .def(
84+ "RegisterDivisibleAssumption",
85+ [](Function&, const SymbolicScalar& expr, int64_t divisor) {
86+ Program::GetInstance().RegisterDivisibleAssumption(expr, divisor);
87+ },
88+ py::arg("expr"), py::arg("divisor"), "Register an assumption that expr is divisible by divisor")
89+ .def(
90+ "IsKnownDivisible",
91+ [](const Function&, const SymbolicScalar& expr, int64_t divisor) {
92+ return Program::GetInstance().IsKnownDivisible(expr, divisor);
93+ },
94+ py::arg("expr"), py::arg("divisor"), "Check if expr is known to be divisible by divisor");
83 95 
84 // Add a function to get the last function from the Program96 // Add a function to get the last function from the Program
85 m.def(97 m.def(
@@ -0,0 +1,79 @@
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+"""Runtime checks emitted for ``assume_divisible`` in runtime_debug_mode=4."""
12+ 
13+import os
14+import signal
15+import subprocess
16+import sys
17+import tempfile
18+ 
19+DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ 
21+_RUNTIME_CASE_SCRIPT = """
22+import os
23+import sys
24+ 
25+import torch
26+import pypto
27+ 
28+torch.npu.set_device({device_id})
29+ 
30+@pypto.frontend.jit(
31+ debug_options={{"runtime_debug_mode": 4}},
32+ runtime_options={{"run_mode": pypto.RunMode.NPU}},
33+)
34+def kernel(
35+ source: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP32),
36+ destination: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP32),
37+):
38+ pypto.set_vec_tile_shapes(1, 8)
39+ for row in pypto.loop(source.shape[0], name="ASSUME_DIVISIBLE_LOOP", idx_name="row"):
40+ pypto.experimental.assume_divisible(source.shape[0], 128)
41+ tile = pypto.view(source, [1, 8], [row, 0])
42+ pypto.assemble(tile, [row, 0], destination)
43+ 
44+device = "npu:{device_id}"
45+source = torch.arange({rows} * 8, dtype=torch.float32, device=device).reshape({rows}, 8)
46+destination = torch.zeros_like(source)
47+kernel(source, destination)
48+torch.npu.synchronize()
49+assert torch.equal(destination.cpu(), source.cpu())
50+"""
51+ 
52+ 
53+def _run_isolated(rows):
54+ script = _RUNTIME_CASE_SCRIPT.format(device_id=DEVICE_ID, rows=rows)
55+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
56+ f.write(script)
57+ f.flush()
58+ script_path = f.name
59+ try:
60+ return subprocess.run(
61+ [sys.executable, script_path],
62+ check=False,
63+ capture_output=True,
64+ text=True,
65+ env=os.environ.copy(),
66+ timeout=300,
67+ )
68+ finally:
69+ os.unlink(script_path)
70+ 
71+ 
72+def test_mode4_assume_divisible_accepts_divisible_runtime_value():
73+ result = _run_isolated(128)
74+ assert result.returncode == 0, result.stderr
75+ 
76+ 
77+def test_mode4_assume_divisible_traps_on_violation():
78+ result = _run_isolated(130)
79+ assert result.returncode in {-signal.SIGILL, -signal.SIGTRAP}, result.stderr
@@ -0,0 +1,38 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software; you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+import pytest
13+ 
14+import pypto
15+ 
16+ 
17+@pytest.mark.parametrize("divisor", [0, -1])
18+def test_assume_divisible_rejects_non_positive_divisor(divisor):
19+ with pytest.raises(ValueError, match="divisor must be positive"):
20+ pypto.experimental.assume_divisible(pypto.SymbolicScalar("vm"), divisor)
21+ 
22+ 
23+def test_assume_divisible_accepts_divisible_constant():
24+ result = pypto.experimental.assume_divisible(256, 128)
25+ 
26+ assert result.is_concrete()
27+ assert result.concrete() == 256
28+ 
29+ 
30+def test_assume_divisible_rejects_non_divisible_constant():
31+ with pytest.raises(ValueError, match="constant 130 is not divisible by 128"):
32+ pypto.experimental.assume_divisible(130, 128)
33+ 
34+ 
35+def test_assume_divisible_returns_symbolic_input_unchanged():
36+ vm = pypto.SymbolicScalar("vm")
37+ 
38+ assert pypto.experimental.assume_divisible(vm, 128) is vm