Merged
refactor(pypto_pro): remove sync_all soft mode #6617
xuxinlei321Add on Sep 22
refactor(pypto_pro): remove sync_all soft mode #6617
Merged
xuxinlei321Add on Sep 22
Total: 19 files changed+45-562
@@ -298,7 +298,6 @@
298 - [pypto_pro.language.ReluPreMode](pro_api/SIMD-API/basic_data_structures/ReluPreMode.md)298 - [pypto_pro.language.ReluPreMode](pro_api/SIMD-API/basic_data_structures/ReluPreMode.md)
299 - [pypto_pro.language.RoundMode](pro_api/SIMD-API/basic_data_structures/RoundMode.md)299 - [pypto_pro.language.RoundMode](pro_api/SIMD-API/basic_data_structures/RoundMode.md)
300 - [pypto_pro.language.STPhase](pro_api/SIMD-API/basic_data_structures/STPhase.md)300 - [pypto_pro.language.STPhase](pro_api/SIMD-API/basic_data_structures/STPhase.md)
301- - [pypto_pro.language.SyncAllMode](pro_api/SIMD-API/basic_data_structures/SyncAllMode.md)
302 - [pypto_pro.language.SyncCoreType](pro_api/SIMD-API/basic_data_structures/SyncCoreType.md)301 - [pypto_pro.language.SyncCoreType](pro_api/SIMD-API/basic_data_structures/SyncCoreType.md)
303 - [pypto_pro.language.Tensor](pro_api/SIMD-API/basic_data_structures/Tensor.md)302 - [pypto_pro.language.Tensor](pro_api/SIMD-API/basic_data_structures/Tensor.md)
304 - [pypto_pro.language.TensorLayout](pro_api/SIMD-API/basic_data_structures/TensorLayout.md)303 - [pypto_pro.language.TensorLayout](pro_api/SIMD-API/basic_data_structures/TensorLayout.md)
@@ -1,26 +0,0 @@
1-# pypto_pro.language.SyncAllMode
2- 
3-## 产品支持情况
4- 
5-<!-- npu="950" id1 -->
6-- Ascend 950PR&950DT系列产品:支持
7-<!-- end id1 -->
8-<!-- npu="A3" id2 -->
9-- Atlas A3系列产品:不支持
10-<!-- end id2 -->
11-<!-- npu="910b" id3 -->
12-- Atlas A2系列产品:不支持
13-<!-- end id3 -->
14- 
15-## 功能说明
16- 
17-SyncAllMode是指定sync_all同步实现模式的枚举,当前仅支持HARD模式。
18- 
19-## 原型定义
20- 
21-```python
22-PYPTO_DECLARE_ENUM(SyncAllMode,
23- HARD, # 使用FFTS硬件同步,不需要workspace
24- SOFT # 使用GM共享状态同步,当前暂不支持
25-)
26-```
@@ -18,7 +18,6 @@ Ptr
18ReluPreMode18ReluPreMode
19RoundMode19RoundMode
20STPhase20STPhase
21-SyncAllMode
22SyncCoreType21SyncCoreType
23Tensor22Tensor
24TensorLayout23TensorLayout
@@ -16,16 +16,14 @@
16 16 
17在多个AIV核、多个AIC核,或AIV与AIC核之间建立核间屏障。参与同步的核到达sync_all后等待,直到本轮所有参与核均已到达,再继续执行。17在多个AIV核、多个AIC核,或AIV与AIC核之间建立核间屏障。参与同步的核到达sync_all后等待,直到本轮所有参与核均已到达,再继续执行。
18 18 
19-当前仅支持HARD模式,使用FFTS硬件同步,不需要workspace。19+使用FFTS硬件同步。
20 20 
21## 函数原型21## 函数原型
22 22 
23```python23```python
24pypto_pro.language.system.sync_all(24pypto_pro.language.system.sync_all(
25- workspaces: Optional[List] = None,
26 *,25 *,
27 core_type: SyncCoreType = pypto_pro.language.SyncCoreType.MIX,26 core_type: SyncCoreType = pypto_pro.language.SyncCoreType.MIX,
28- mode: SyncAllMode = pypto_pro.language.SyncAllMode.HARD,
29) -> None27) -> None
30```28```
31 29 
@@ -33,9 +31,7 @@ pypto_pro.language.system.sync_all(
33 31 
34| 参数 | 输入/输出 | 说明 |32| 参数 | 输入/输出 | 说明 |
35|---|---|---|33|---|---|---|
36-| workspaces | 输入 | 可选,当前仅支持HARD模式,不使用workspace,保持默认值None或传空列表。 |
37| core_type | 输入 | 可选,[pypto_pro.language.SyncCoreType](../basic_data_structures/SyncCoreType.md)枚举值,指定参与屏障的核类型,默认为pypto_pro.language.SyncCoreType.MIX。该参数不指定参与核数量。 |34| core_type | 输入 | 可选,[pypto_pro.language.SyncCoreType](../basic_data_structures/SyncCoreType.md)枚举值,指定参与屏障的核类型,默认为pypto_pro.language.SyncCoreType.MIX。该参数不指定参与核数量。 |
38-| mode | 输入 | 可选,[pypto_pro.language.SyncAllMode](../basic_data_structures/SyncAllMode.md)枚举值,指定同步实现模式,默认为pypto_pro.language.SyncAllMode.HARD,当前仅支持pypto_pro.language.SyncAllMode.HARD。 |
39 35 
40## 约束说明36## 约束说明
41 37 
@@ -44,7 +40,7 @@ pypto_pro.language.system.sync_all(
44- 多流或多个算子并发执行,且并发算子申请的核数总和超过物理核数时,如果至少两个并发算子使用sync_all,部分核可能因未被调度而无法到达屏障,造成死锁。须保证每个同步算子所需的核能够同时执行。40- 多流或多个算子并发执行,且并发算子申请的核数总和超过物理核数时,如果至少两个并发算子使用sync_all,部分核可能因未被调度而无法到达屏障,造成死锁。须保证每个同步算子所需的核能够同时执行。
45- sync_all建立参与核之间的屏障。屏障前后需要跨核读写GM数据时,还需满足相应的数据可见性要求。41- sync_all建立参与核之间的屏障。屏障前后需要跨核读写GM数据时,还需满足相应的数据可见性要求。
46- 与set_cross_core/wait_cross_core并用时,两侧的MIX屏障必须位于该SET/WAIT对的同一侧;禁止Cube侧先执行sync_all再SET、Vector侧先WAIT再执行sync_all,否则会形成环形等待。42- 与set_cross_core/wait_cross_core并用时,两侧的MIX屏障必须位于该SET/WAIT对的同一侧;禁止Cube侧先执行sync_all再SET、Vector侧先WAIT再执行sync_all,否则会形成环形等待。
47-- HARD模式会占用核间同步事件ID:AIV_ONLY在AIV侧占用14,AIC_ONLY在AIC侧占用11;MIX在AIC侧占用11~13、在AIV侧占用12~13,MIX 1:2场景的AIC还会占用28和29。与set_cross_core/wait_cross_core同时使用时,不得将这些事件ID用于尚未完成的手工核间同步。43+- sync_all会占用核间同步事件ID:AIV_ONLY在AIV侧占用14,AIC_ONLY在AIC侧占用11;MIX在AIC侧占用11~13、在AIV侧占用12~13,MIX 1:2场景的AIC还会占用28和29。与set_cross_core/wait_cross_core同时使用时,不得将这些事件ID用于尚未完成的手工核间同步。
48 44 
49## 返回值说明45## 返回值说明
50 46 
@@ -52,7 +48,7 @@ pypto_pro.language.system.sync_all(
52 48 
53## 调用示例49## 调用示例
54 50 
55-下面是纯Vector Kernel展示HARD AIV_ONLY屏障的放置方式。各AIV按核号处理互不重叠的行,TileGroup和auto_mutex负责核内pipe依赖;sync_all位于循环外,使所有参与AIV在本阶段结束后再越过屏障。51+下面是纯Vector Kernel展示AIV_ONLY屏障的放置方式。各AIV按核号处理互不重叠的行,TileGroup和auto_mutex负责核内pipe依赖;sync_all位于循环外,使所有参与AIV在本阶段结束后再越过屏障。
56 52 
57```python53```python
58import pypto_pro.language as pl54import pypto_pro.language as pl
@@ -78,23 +74,21 @@ def sync_all_kernel(
78 pl.store(out, tile_out, [row, 0])74 pl.store(out, tile_out, [row, 0])
79 75 
80 pl.system.sync_all(76 pl.system.sync_all(
81- mode=pl.SyncAllMode.HARD,
82 core_type=pl.SyncCoreType.AIV_ONLY,77 core_type=pl.SyncCoreType.AIV_ONLY,
83 )78 )
84```79```
85 80 
86-该示例使用HARD AIV_ONLY屏障,不需要传入workspaces。81+该示例使用AIV_ONLY屏障。
87 82 
88-### HARD模式83+### 核类型
89 84 
90-HARD模式的三种core_type调用方式如下。以下片段分别用于对应类型的Kernel。85+三种core_type调用方式如下。以下片段分别用于对应类型的Kernel。
91 86 
92```python87```python
93# 纯Vector Kernel:所有参与AIV都执行88# 纯Vector Kernel:所有参与AIV都执行
94with pl.section_vector():89with pl.section_vector():
95 # ... Vector阶段计算90 # ... Vector阶段计算
96 pl.system.sync_all(91 pl.system.sync_all(
97- mode=pl.SyncAllMode.HARD,
98 core_type=pl.SyncCoreType.AIV_ONLY,92 core_type=pl.SyncCoreType.AIV_ONLY,
99 )93 )
100 94 
@@ -102,7 +96,6 @@ with pl.section_vector():
102with pl.section_cube():96with pl.section_cube():
103 # ... Cube阶段计算97 # ... Cube阶段计算
104 pl.system.sync_all(98 pl.system.sync_all(
105- mode=pl.SyncAllMode.HARD,
106 core_type=pl.SyncCoreType.AIC_ONLY,99 core_type=pl.SyncCoreType.AIC_ONLY,
107 )100 )
108 101 
@@ -110,14 +103,12 @@ with pl.section_cube():
110with pl.section_cube():103with pl.section_cube():
111 # ... Cube阶段计算104 # ... Cube阶段计算
112 pl.system.sync_all(105 pl.system.sync_all(
113- mode=pl.SyncAllMode.HARD,
114 core_type=pl.SyncCoreType.MIX,106 core_type=pl.SyncCoreType.MIX,
115 )107 )
116 108 
117with pl.section_vector():109with pl.section_vector():
118 # ... Vector阶段计算110 # ... Vector阶段计算
119 pl.system.sync_all(111 pl.system.sync_all(
120- mode=pl.SyncAllMode.HARD,
121 core_type=pl.SyncCoreType.MIX,112 core_type=pl.SyncCoreType.MIX,
122 )113 )
123```114```
@@ -142,8 +142,6 @@ PYPTO_DECLARE_ENUM(CrossCoreSyncMode, INTER_BLOCK, INTER_SUBBLOCK, INTRA_BLOCK,
142 142 
143PYPTO_DECLARE_ENUM(SyncCoreType, AIV_ONLY, AIC_ONLY, MIX)143PYPTO_DECLARE_ENUM(SyncCoreType, AIV_ONLY, AIC_ONLY, MIX)
144 144 
145-PYPTO_DECLARE_ENUM(SyncAllMode, HARD, SOFT)
146- 
147PYPTO_DECLARE_ENUM(CacheLine, SINGLE_CACHE_LINE, ENTIRE_DATA_CACHE)145PYPTO_DECLARE_ENUM(CacheLine, SINGLE_CACHE_LINE, ENTIRE_DATA_CACHE)
148 146 
149PYPTO_DECLARE_ENUM(DcciDst, AUTO, CACHELINE_OUT, CACHELINE_UB, CACHELINE_ALL, CACHELINE_ATOMIC)147PYPTO_DECLARE_ENUM(DcciDst, AUTO, CACHELINE_OUT, CACHELINE_UB, CACHELINE_ALL, CACHELINE_ATOMIC)
@@ -58,95 +58,6 @@ bool IsDcciTensorOffset(const ExprPtr& offset)
58 return true;58 return true;
59}59}
60 60 
61-TypePtr DeduceSyncAllType(const std::vector<ExprPtr>& args, const std::vector<std::pair<std::string, std::any>>& kwargs)
62-{
63- int mode = 0; // SyncAllMode::HARD = 0
64- int core_type = 2; // SyncCoreType::MIX = 2
65- for (const auto& [key, value] : kwargs) {
66- if (key == "mode")
67- mode = std::any_cast<int>(value);
68- if (key == "core_type")
69- core_type = std::any_cast<int>(value);
70- }
71- 
72- if (mode == 0) { // HARD
73- // args[0] is an empty MakeTuple for hard mode
74- if (!args.empty()) {
75- auto tuple = As<MakeTuple>(args[0]);
76- PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, !tuple || tuple->elements_.empty())
77- << "system.sync_all hard mode does not accept workspace arguments";
78- }
79- } else if (mode == 1) { // SOFT
80- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, core_type == 0 || core_type == 1 || core_type == 2)
81- << "system.sync_all soft mode core_type must be AIV_ONLY(0), AIC_ONLY(1), or MIX(2), got " << core_type;
82- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1)
83- << "system.sync_all soft mode requires exactly 1 argument (workspaces list), got " << args.size();
84- 
85- // Unpack MakeTuple elements and classify by type
86- auto tuple = As<MakeTuple>(args[0]);
87- PRO_IR_CHECK(ExternalError::INVALID_TYPE, tuple)
88- << "system.sync_all soft mode: workspaces argument must be a list/tuple";
89- 
90- bool has_gm = false, has_ub = false, has_l1 = false, has_used_cores = false;
91- for (const auto& elem : tuple->elements_) {
92- auto elem_type = elem->GetType();
93- if (As<TensorType>(elem_type)) {
94- PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !has_gm)
95- << "system.sync_all: duplicate gm_workspace (TensorType) in workspaces list";
96- has_gm = true;
97- } else if (auto tile_type = As<TileType>(elem_type)) {
98- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, tile_type->memref_.has_value())
99- << "system.sync_all: workspace tile must have memref";
100- auto space = tile_type->memref_.value()->memorySpace_;
101- if (space == MemorySpace::Vec) {
102- PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !has_ub)
103- << "system.sync_all: duplicate ub_workspace (Vec TileType) in workspaces list";
104- has_ub = true;
105- } else if (space == MemorySpace::Mat) {
106- PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !has_l1)
107- << "system.sync_all: duplicate l1_workspace (Mat TileType) in workspaces list";
108- has_l1 = true;
109- } else {
110- PRO_IR_CHECK(ExternalError::INVALID_OPERATION, false)
111- << "system.sync_all: workspace tile must be Vec or Mat, got " << static_cast<int>(space);
112- }
113- } else if (IsIntScalar(elem)) {
114- PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !has_used_cores)
115- << "system.sync_all: duplicate used_cores (int scalar) in workspaces list";
116- has_used_cores = true;
117- } else {
118- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, false)
119- << "system.sync_all: unrecognized element type in workspaces list: " << elem_type->TypeName();
120- }
121- }
122- 
123- // Validate required workspaces per core_type
124- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_gm)
125- << "system.sync_all soft mode: workspaces list must contain a gm_workspace (TensorType)";
126- if (core_type == 0) { // AIV_ONLY
127- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_ub)
128- << "system.sync_all soft aiv_only: workspaces list must contain ub_workspace (Vec TileType)";
129- PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, !has_l1)
130- << "system.sync_all soft aiv_only: l1_workspace (Mat TileType) is not allowed";
131- } else if (core_type == 1) { // AIC_ONLY
132- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_l1)
133- << "system.sync_all soft aic_only: workspaces list must contain l1_workspace (Mat TileType)";
134- PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, !has_ub)
135- << "system.sync_all soft aic_only: ub_workspace (Vec TileType) is not allowed";
136- } else { // MIX
137- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_ub)
138- << "system.sync_all soft mix: workspaces list must contain ub_workspace (Vec TileType)";
139- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_l1)
140- << "system.sync_all soft mix: workspaces list must contain l1_workspace (Mat TileType)";
141- }
142- } else {
143- PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, false)
144- << "system.sync_all: mode must be HARD(0) or SOFT(1), got " << mode;
145- }
146- 
147- return GetUnknownType();
148-}
149- 
150} // namespace61} // namespace
151 62 
152// ============================================================================63// ============================================================================
@@ -259,18 +170,13 @@ REGISTER_OP("system.wait_cross_core_dyn")
259 .f_deduce_type(DeduceUnknownType);170 .f_deduce_type(DeduceUnknownType);
260 171 
261// Register system.sync_all (Global Core Synchronization)172// Register system.sync_all (Global Core Synchronization)
262-// Delegates to pto-isa SYNCALL<SyncAllMode, SyncCoreType>() / pto.syncall MLIR op.173+// Delegates to pto-isa SYNCALL<SyncCoreType>() / pto.syncall MLIR op.
263-// Hard mode (default): no arguments.
264-// Soft mode: workspaces list passed as a single MakeTuple arg.
265-// Backend codegen dispatches by type: TensorType→gm, Vec TileType→ub, Mat TileType→l1, ScalarType→used_cores.
266REGISTER_OP("system.sync_all")174REGISTER_OP("system.sync_all")
267- .set_description("Global core synchronization (hard or soft mode)")175+ .set_description("Global core synchronization")
268 .set_op_category("SyncOp")176 .set_op_category("SyncOp")
269- .add_argument("workspaces",177+ .no_argument()
270- "Soft mode workspace list as MakeTuple (Tensor gm + Tile ub/l1 + optional int used_cores)")
271- .set_attr<int>("mode")
272 .set_attr<int>("core_type")178 .set_attr<int>("core_type")
273- .f_deduce_type(DeduceSyncAllType);179+ .f_deduce_type(DeduceUnknownType);
274 180 
275// Register system.dcci (Data Cache Clean and Invalid)181// Register system.dcci (Data Cache Clean and Invalid)
276// Arguments:182// Arguments:
@@ -2065,13 +2065,12 @@ REGISTER_BACKEND_OP(BackendCCE, "system.mutex_unlock_dyn")
2065// ============================================================================2065// ============================================================================
2066// Global Core Synchronization (sync_all)2066// Global Core Synchronization (sync_all)
2067// ============================================================================2067// ============================================================================
2068-// Delegates to pto-isa SYNCALL<SyncAllMode, SyncCoreType>(...) / SYNCALL<SyncCoreType>().2068+// Delegates to pto-isa SYNCALL<SyncCoreType>().
2069 2069 
2070static std::string MakeSystemSyncAllCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)2070static std::string MakeSystemSyncAllCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
2071{2071{
2072 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);2072 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
2073 2073 
2074- auto mode = static_cast<ir::SyncAllMode>(op->HasKwarg("mode") ? op->GetKwarg<int>("mode") : 0);
2075 auto core_type = static_cast<ir::SyncCoreType>(op->HasKwarg("core_type") ? op->GetKwarg<int>("core_type") : 2);2074 auto core_type = static_cast<ir::SyncCoreType>(op->HasKwarg("core_type") ? op->GetKwarg<int>("core_type") : 2);
2076 2075 
2077 std::string core_type_tok;2076 std::string core_type_tok;
@@ -2082,46 +2081,7 @@ static std::string MakeSystemSyncAllCodegenCCE(const ir::CallPtr& op, codegen::C
2082 else2081 else
2083 core_type_tok = "SyncCoreType::Mix";2082 core_type_tok = "SyncCoreType::Mix";
2084 2083 
2085- if (mode == ir::SyncAllMode::HARD) {2084+ codegen.Emit("SYNCALL<" + core_type_tok + ">();");
2086- // args[0] is an empty MakeTuple for hard mode
2087- codegen.Emit("SYNCALL<" + core_type_tok + ">();");
2088- return "";
2089- }
2090- 
2091- // Soft mode: args[0] is a MakeTuple with workspace elements, dispatch by type
2092- PRO_CODEGEN_CHECK(ExternalError::INVALID_ARGUMENT, op->args_.size() == 1)
2093- << "system.sync_all expects 1 arg (workspaces tuple)";
2094- auto tuple = ir::As<ir::MakeTuple>(op->args_[0]);
2095- PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, tuple) << "system.sync_all: workspaces must be a tuple";
2096- 
2097- std::string gm, ub, l1, used_cores = "0";
2098- for (const auto& elem : tuple->elements_) {
2099- auto elem_type = elem->GetType();
2100- if (ir::As<ir::TensorType>(elem_type)) {
2101- gm = codegen.GetExprAsCode(elem);
2102- } else if (auto tile_type = ir::As<ir::TileType>(elem_type)) {
2103- auto space = tile_type->memref_.value()->memorySpace_;
2104- if (space == ir::MemorySpace::Vec) {
2105- ub = codegen.GetExprAsCode(elem);
2106- } else if (space == ir::MemorySpace::Mat) {
2107- l1 = codegen.GetExprAsCode(elem);
2108- }
2109- } else if (ir::As<ir::ScalarType>(elem_type)) {
2110- used_cores = codegen.GetExprAsCode(elem);
2111- }
2112- }
2113- 
2114- std::ostringstream oss;
2115- oss << "SYNCALL<SyncAllMode::Soft, " << core_type_tok << ">(" << gm;
2116- if (core_type == ir::SyncCoreType::AIV_ONLY) {
2117- oss << ", " << ub;
2118- } else if (core_type == ir::SyncCoreType::AIC_ONLY) {
2119- oss << ", " << l1;
2120- } else { // MIX
2121- oss << ", " << ub << ", " << l1;
2122- }
2123- oss << ", " << used_cores << ");";
2124- codegen.Emit(oss.str());
2125 return "";2085 return "";
2126}2086}
2127 2087 
@@ -1130,14 +1130,13 @@ TEST(BackendCceOpsTest, BlockSubviewInVFSectionSupportsScalarOffset)
1130}1130}
1131 1131 
1132// ============================================================================1132// ============================================================================
1133-// Sync all (HARD mode)1133+// Sync all
1134// ============================================================================1134// ============================================================================
1135 1135 
1136TEST(BackendCceOpsTest, SyncAllHardMix)1136TEST(BackendCceOpsTest, SyncAllHardMix)
1137{1137{
1138- auto empty_tuple = std::make_shared<const ir::MakeTuple>(std::vector<ir::ExprPtr>{}, ir::Span::Unknown());1138+ Kwargs kwargs = {};
1139- Kwargs kwargs = {{"mode", 0}};1139+ auto call = std::make_shared<const ir::Call>("system.sync_all", std::vector<ir::ExprPtr>{}, kwargs,
1140- auto call = std::make_shared<const ir::Call>("system.sync_all", std::vector<ir::ExprPtr>{empty_tuple}, kwargs,
1141 ir::Span::Unknown());1140 ir::Span::Unknown());
1142 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());1141 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
1143 1142 
@@ -1148,9 +1147,8 @@ TEST(BackendCceOpsTest, SyncAllHardMix)
1148 1147 
1149TEST(BackendCceOpsTest, SyncAllHardAIVOnly)1148TEST(BackendCceOpsTest, SyncAllHardAIVOnly)
1150{1149{
1151- auto empty_tuple = std::make_shared<const ir::MakeTuple>(std::vector<ir::ExprPtr>{}, ir::Span::Unknown());1150+ Kwargs kwargs = {{"core_type", 0}};
1152- Kwargs kwargs = {{"mode", 0}, {"core_type", 0}};1151+ auto call = std::make_shared<const ir::Call>("system.sync_all", std::vector<ir::ExprPtr>{}, kwargs,
1153- auto call = std::make_shared<const ir::Call>("system.sync_all", std::vector<ir::ExprPtr>{empty_tuple}, kwargs,
1154 ir::Span::Unknown());1152 ir::Span::Unknown());
1155 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());1153 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
1156 1154 
@@ -1159,32 +1157,6 @@ TEST(BackendCceOpsTest, SyncAllHardAIVOnly)
1159 EXPECT_NE(generated.find("SYNCALL<SyncCoreType::AIVOnly>();"), std::string::npos);1157 EXPECT_NE(generated.find("SYNCALL<SyncCoreType::AIVOnly>();"), std::string::npos);
1160}1158}
1161 1159 
1162-TEST(BackendCceOpsTest, SyncAllSoftUsesCoreSpecificWorkspaces)
1163-{
1164- auto gm = MakeTensorVar("gm", {64}, ir::DataType::UINT8);
1165- auto ub = MakeVar("ub", MakeTileType({16, 16}, ir::DataType::FP16, ir::MemorySpace::Vec));
1166- auto l1 = MakeVar("l1", MakeTileType({16, 16}, ir::DataType::FP16, ir::MemorySpace::Mat));
1167- auto used_cores = MakeVar("used_cores", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
1168- 
1169- auto make_sync_all = [&](ir::SyncCoreType core_type, std::vector<ir::ExprPtr> workspaces) {
1170- Kwargs kwargs = {{"mode", static_cast<int>(ir::SyncAllMode::SOFT)}, {"core_type", static_cast<int>(core_type)}};
1171- return std::make_shared<const ir::Call>(
1172- "system.sync_all", std::vector<ir::ExprPtr>{MakeTuple(std::move(workspaces))}, kwargs, ir::Span::Unknown());
1173- };
1174- 
1175- auto aiv_code = RunCodegen("system.sync_all", make_sync_all(ir::SyncCoreType::AIV_ONLY, {gm, ub, used_cores}));
1176- EXPECT_NE(aiv_code.find("SYNCALL<SyncAllMode::Soft, SyncCoreType::AIVOnly>(gm, ub, used_cores);"),
1177- std::string::npos);
1178- 
1179- auto aic_code = RunCodegen("system.sync_all", make_sync_all(ir::SyncCoreType::AIC_ONLY, {gm, l1, used_cores}));
1180- EXPECT_NE(aic_code.find("SYNCALL<SyncAllMode::Soft, SyncCoreType::AICOnly>(gm, l1, used_cores);"),
1181- std::string::npos);
1182- 
1183- auto mix_code = RunCodegen("system.sync_all", make_sync_all(ir::SyncCoreType::MIX, {gm, ub, l1, used_cores}));
1184- EXPECT_NE(mix_code.find("SYNCALL<SyncAllMode::Soft, SyncCoreType::Mix>(gm, ub, l1, used_cores);"),
1185- std::string::npos);
1186-}
1187- 
1188// ============================================================================1160// ============================================================================
1189// DCCI (tensor)1161// DCCI (tensor)
1190// ============================================================================1162// ============================================================================
@@ -46,7 +46,6 @@ __all__ = [
46 "QuantMode",46 "QuantMode",
47 "CrossCoreSyncMode",47 "CrossCoreSyncMode",
48 "SyncCoreType",48 "SyncCoreType",
49- "SyncAllMode",
50 "CacheLine",49 "CacheLine",
51 "DcciDst",50 "DcciDst",
52 "MaskPattern",51 "MaskPattern",
@@ -224,7 +223,6 @@ from .pypto_impl.ir import (
224 StoreDist,223 StoreDist,
225 STPhase,224 STPhase,
226 Sub,225 Sub,
227- SyncAllMode,
228 SyncCoreType,226 SyncCoreType,
229 TensorLayout,227 TensorLayout,
230 TensorOpStmt,228 TensorOpStmt,
@@ -27,7 +27,6 @@ from pypto.pypto_impl.ir import (
27 Expr,27 Expr,
28 PipeType,28 PipeType,
29 Span,29 Span,
30- SyncAllMode,
31 SyncCoreType,30 SyncCoreType,
32)31)
33 32 
@@ -320,53 +319,24 @@ def wait_cross_core(
320 319 
321 320 
322def sync_all(321def sync_all(
323- workspaces: list[Expr | int] | None = None,
324 *,322 *,
325 core_type: SyncCoreType = SyncCoreType.MIX,323 core_type: SyncCoreType = SyncCoreType.MIX,
326- mode: SyncAllMode = SyncAllMode.HARD,
327 span: Span | None = None,324 span: Span | None = None,
328) -> Call:325) -> Call:
329 """Global core synchronization (delegates to pto-isa SYNCALL).326 """Global core synchronization (delegates to pto-isa SYNCALL).
330 327 
331- Hard mode (default): no workspace needed, uses FFTS hardware signal.328+ Uses FFTS hardware signal.
332- Soft mode: requires workspace buffers for GM-polling synchronization.
333 329 
334 Args:330 Args:
335- workspaces: List of workspace parameters for soft mode. Dispatched by type:
336- - TensorType → gm_workspace (required for soft mode)
337- - Vec TileType → ub_workspace (required for aiv_only/mix)
338- - Mat TileType → l1_workspace (required for aic_only/mix)
339- - int/Expr scalar → used_cores (optional, defaults to 0 = all cores)
340- Defaults to empty list. Not needed for hard mode.
341 core_type: ``pl.SyncCoreType.AIV_ONLY``, ``pl.SyncCoreType.AIC_ONLY``, or ``pl.SyncCoreType.MIX`` (default).331 core_type: ``pl.SyncCoreType.AIV_ONLY``, ``pl.SyncCoreType.AIC_ONLY``, or ``pl.SyncCoreType.MIX`` (default).
342 AIV-only syncs vector cores only; Mix syncs both AIC and AIV cores.332 AIV-only syncs vector cores only; Mix syncs both AIC and AIV cores.
343- mode: ``pl.SyncAllMode.HARD`` (default) or ``pl.SyncAllMode.SOFT``.
344- Hard mode uses FFTS hardware; Soft mode uses GM workspace polling.
345 span: Optional source span for debugging (auto-captured if not provided).333 span: Optional source span for debugging (auto-captured if not provided).
346 334 
347 Returns:335 Returns:
348 Call expression for global core synchronization.336 Call expression for global core synchronization.
349 """337 """
350- if workspaces is None:
351- workspaces = []
352- 
353- kwargs: dict[str, object] = {"mode": mode, "core_type": core_type}
354- # Resolved before the checks below so their errors can report a location.
355 actual_span = _get_span_or_capture(span)338 actual_span = _get_span_or_capture(span)
356- 339+ return _ir_core.create_op_call("system.sync_all", [], {"core_type": core_type}, actual_span)
357- if mode == SyncAllMode.HARD:
358- if workspaces:
359- raise NotSupported("Hard mode sync_all does not accept workspace arguments", span=actual_span)
360- elif mode == SyncAllMode.SOFT:
361- if not workspaces:
362- raise InvalidArgument(
363- "Soft mode sync_all requires workspaces list (e.g. [gm, ub])", span=actual_span
364- )
365- 
366- # Build args[0]: always a MakeTuple (empty for hard, populated for soft)
367- ws_tuple = _to_make_tuple(workspaces)
368- 
369- return _ir_core.create_op_call("system.sync_all", [ws_tuple], kwargs, actual_span)
370 340 
371 341 
372def dcci(342def dcci(
@@ -616,9 +586,10 @@ def _parse_system_sync_dst(self, call: ast.Call):
616@op_impl("system.sync_all")586@op_impl("system.sync_all")
617def _parse_system_sync_all(self, call: ast.Call):587def _parse_system_sync_all(self, call: ast.Call):
618 span = self.span_tracker.get_span(call)588 span = self.span_tracker.get_span(call)
589+ if call.args:
590+ raise InvalidArgument("sync_all does not accept positional arguments", span=span)
619 kwargs = self.parse_op_kwargs(call)591 kwargs = self.parse_op_kwargs(call)
620- workspaces = self.parse_expression(call.args[0]) if call.args else None592+ return sync_all(**kwargs, span=span)
621- return sync_all(workspaces, **kwargs, span=span)
622 593 
623 594 
624@op_impl("system.set_mm_layout_transform")595@op_impl("system.set_mm_layout_transform")
@@ -52,7 +52,6 @@ __all__ = [
52 "QuantMode",52 "QuantMode",
53 "CrossCoreSyncMode",53 "CrossCoreSyncMode",
54 "SyncCoreType",54 "SyncCoreType",
55- "SyncAllMode",
56 "CacheLine",55 "CacheLine",
57 "DcciDst",56 "DcciDst",
58 "DT_FP4",57 "DT_FP4",
@@ -256,7 +255,6 @@ from pypto.ir import (
256 SqueezeMode,255 SqueezeMode,
257 StoreDist,256 StoreDist,
258 STPhase,257 STPhase,
259- SyncAllMode,
260 SyncCoreType,258 SyncCoreType,
261 VFRoundMode,259 VFRoundMode,
262)260)
@@ -580,10 +580,6 @@ void BindTypeClass(py::module_& ir)
580 .value("AIC_ONLY", ir::SyncCoreType::AIC_ONLY, "Sync cube cores only")580 .value("AIC_ONLY", ir::SyncCoreType::AIC_ONLY, "Sync cube cores only")
581 .value("MIX", ir::SyncCoreType::MIX, "Sync both AIC and AIV cores");581 .value("MIX", ir::SyncCoreType::MIX, "Sync both AIC and AIV cores");
582 582 
583- py::enum_<ir::SyncAllMode>(ir, "SyncAllMode", "Synchronization mode for sync_all")
584- .value("HARD", ir::SyncAllMode::HARD, "Hardware FFTS signal (default)")
585- .value("SOFT", ir::SyncAllMode::SOFT, "GM workspace polling");
586- 
587 py::enum_<ir::CacheLine>(ir, "CacheLine", "Cache line scope for DCCI")583 py::enum_<ir::CacheLine>(ir, "CacheLine", "Cache line scope for DCCI")
588 .value("SINGLE_CACHE_LINE", ir::CacheLine::SINGLE_CACHE_LINE, "Single cache line")584 .value("SINGLE_CACHE_LINE", ir::CacheLine::SINGLE_CACHE_LINE, "Single cache line")
589 .value("ENTIRE_DATA_CACHE", ir::CacheLine::ENTIRE_DATA_CACHE, "Entire data cache");585 .value("ENTIRE_DATA_CACHE", ir::CacheLine::ENTIRE_DATA_CACHE, "Entire data cache");
@@ -187,7 +187,7 @@ def four_stage_kernel(
187 with pl.section_cube():187 with pl.section_cube():
188 a_use_hi(i, a_hi, a_left)188 a_use_hi(i, a_hi, a_left)
189 189 
190- pl.system.sync_all(mode=pl.SyncAllMode.HARD, core_type=pl.SyncCoreType.MIX)190+ pl.system.sync_all(core_type=pl.SyncCoreType.MIX)
191 191 
192 for j in pl.range(0, NT):192 for j in pl.range(0, NT):
193 with pl.section_vector():193 with pl.section_vector():
@@ -245,7 +245,7 @@ def mixed_preload_kernel(
245 with pl.section_cube():245 with pl.section_cube():
246 a_use_lo(i, a_lo, a_left)246 a_use_lo(i, a_lo, a_left)
247 247 
248- pl.system.sync_all(mode=pl.SyncAllMode.HARD, core_type=pl.SyncCoreType.MIX)248+ pl.system.sync_all(core_type=pl.SyncCoreType.MIX)
249 249 
250 for j in pl.range(0, NT):250 for j in pl.range(0, NT):
251 with pl.section_vector():251 with pl.section_vector():
@@ -554,7 +554,9 @@ def for_while_if_not_break_continue_kernel(
554 tile_b = b_db.next()554 tile_b = b_db.next()
555 tile_c = c_db.next()555 tile_c = c_db.next()
556 pl.load_tile(tile_a, x, [i, j])556 pl.load_tile(tile_a, x, [i, j])
557+ pl.system.bar_mte2()
557 pl.load_tile(tile_b, y, [i, j])558 pl.load_tile(tile_b, y, [i, j])
559+ pl.system.bar_mte2()
558 if not j >= 1 and not i >= 1:560 if not j >= 1 and not i >= 1:
559 pl.add(tile_c, tile_a, tile_b)561 pl.add(tile_c, tile_a, tile_b)
560 pl.store_tile(z, tile_c, [i, j])562 pl.store_tile(z, tile_c, [i, j])
@@ -1,227 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3-# CANN Open Software License Agreement Version 2.0 (the "License").
4-# Please refer to the License for details. You may not use this file except in compliance with the License.
5-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7-# See LICENSE in the root of the software repository for the full text of the License.
8-# -----------------------------------------------------------------------------------------------------------
9- 
10-"""Quantization, type cast, and scatter ops.
11- 
12-Doc: docs/zh/api/pro_api/SIMD-API/计算API/{量化, Memory矢量计算/类型转换, Memory矢量计算/离散与聚合}
13- 
14-make_tile_group + auto_mutex style. Verifies quant/dequant,
15-pl.cast type conversion, and scatter correctness.
16-"""
17- 
18-import logging
19-import os
20- 
21-import pypto_pro.language as pl
22-import pytest
23-import torch
24- 
25-ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
26-ST_DEVICE = f"npu:{ST_DEVICE_ID}"
27- 
28- 
29-def _require_a5(device):
30- try:
31- torch.npu.set_device(device)
32- except RuntimeError as exc:
33- pytest.skip(f"NPU unavailable: {exc}")
34- name = torch.npu.get_device_name()
35- if "Ascend950" not in name:
36- pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
37- 
38- 
39-# ===========================================================================
40-# quant —— 对称量化 FP32 -> INT8,per-row scale [64,1]
41-# ===========================================================================
42-@pl.jit(auto_mutex=True)
43-def quant_kernel(
44- src: pl.Tensor[[64, 128], pl.DT_FP32],
45- scale: pl.Tensor[[64, 1], pl.DT_FP32],
46- out: pl.Tensor[[64, 128], pl.DT_INT8],
47-):
48- tile_src = pl.make_tile_group(
49- type=pl.TileType(shape=[64, 128], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec),
50- addrs=0x0000,
51- mutex_ids=[0],
52- )
53- tile_scale = pl.make_tile_group(
54- type=pl.TileType(shape=[64, 1], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addrs=0x8000, mutex_ids=[1]
55- )
56- tile_out = pl.make_tile_group(
57- type=pl.TileType(shape=[64, 128], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec),
58- addrs=0xA000,
59- mutex_ids=[2],
60- )
61- with pl.section_vector():
62- cur_src = tile_src.current()
63- cur_scale = tile_scale.current()
64- cur_out = tile_out.current()
65- pl.load(cur_src, src, [0, 0])
66- pl.load(cur_scale, scale, [0, 0])
67- pl.quant(cur_out, cur_src, cur_scale, mode=pl.QuantMode.SYM)
68- pl.store(out, cur_out, [0, 0])
69- 
70- 
71-@pytest.mark.soc("950")
72-def test_quant():
73- device = ST_DEVICE
74- _require_a5(device)
75- torch.manual_seed(0)
76- src = torch.randn(64, 128, device=device, dtype=torch.float32)
77- scale = torch.rand(64, 1, device=device, dtype=torch.float32) + 0.01
78- out = torch.zeros(64, 128, device=device, dtype=torch.int8)
79- quant_kernel(src, scale, out)
80- torch.npu.synchronize()
81- out_ref = torch.clamp(torch.round(src * scale), -128, 127).to(torch.int8)
82- torch.testing.assert_close(out, out_ref)
83- logging.info("quant result equal!")
84- 
85- 
86-# ===========================================================================
87-# dequant —— INT8 -> FP32,per-row scale + offset
88-# ===========================================================================
89-@pl.jit(auto_mutex=True)
90-def dequant_kernel(
91- src: pl.Tensor[[64, 128], pl.DT_INT8],
92- scale: pl.Tensor[[64, 1], pl.DT_FP32],
93- offset: pl.Tensor[[64, 1], pl.DT_FP32],
94- out: pl.Tensor[[64, 128], pl.DT_FP32],
95-):
96- tile_src = pl.make_tile_group(
97- type=pl.TileType(shape=[64, 128], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec),
98- addrs=0x0000,
99- mutex_ids=[0],
100- )
101- tile_scale = pl.make_tile_group(
102- type=pl.TileType(shape=[64, 1], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addrs=0x4000, mutex_ids=[1]
103- )
104- tile_offset = pl.make_tile_group(
105- type=pl.TileType(shape=[64, 1], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addrs=0x5000, mutex_ids=[2]
106- )
107- tile_out = pl.make_tile_group(
108- type=pl.TileType(shape=[64, 128], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec),
109- addrs=0x6000,
110- mutex_ids=[3],
111- )
112- with pl.section_vector():
113- cur_src = tile_src.current()
114- cur_scale = tile_scale.current()
115- cur_offset = tile_offset.current()
116- cur_out = tile_out.current()
117- pl.load(cur_src, src, [0, 0])
118- pl.load(cur_scale, scale, [0, 0])
119- pl.load(cur_offset, offset, [0, 0])
120- pl.dequant(cur_out, cur_src, cur_scale, cur_offset)
121- pl.store(out, cur_out, [0, 0])
122- 
123- 
124-@pytest.mark.soc("950")
125-def test_dequant():
126- device = ST_DEVICE
127- _require_a5(device)
128- torch.manual_seed(0)
129- src = torch.randint(-128, 127, (64, 128), device=device, dtype=torch.int8)
130- scale = torch.rand(64, 1, device=device, dtype=torch.float32) + 0.01
131- offset = torch.zeros(64, 1, device=device, dtype=torch.float32)
132- out = torch.zeros(64, 128, device=device, dtype=torch.float32)
133- dequant_kernel(src, scale, offset, out)
134- torch.npu.synchronize()
135- out_ref = (src.to(torch.float32) - offset) * scale
136- torch.testing.assert_close(out, out_ref, rtol=1e-2, atol=1e-2)
137- logging.info("dequant result equal!")
138- 
139- 
140-# ===========================================================================
141-# cast —— 类型转换 FP16 -> FP32(目标类型由 out tile 推断)
142-# ===========================================================================
143-@pl.jit(auto_mutex=True)
144-def cast_kernel(
145- src: pl.Tensor[[64, 128], pl.DT_FP16],
146- out: pl.Tensor[[64, 128], pl.DT_FP32],
147-):
148- tt_in = pl.TileType(shape=[64, 128], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)
149- tt_out = pl.TileType(shape=[64, 128], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
150- tile_src = pl.make_tile_group(type=tt_in, addrs=0x0000, mutex_ids=[0])
151- tile_out = pl.make_tile_group(type=tt_out, addrs=0x4000, mutex_ids=[1])
152- with pl.section_vector():
153- cur_src = tile_src.current()
154- cur_out = tile_out.current()
155- pl.load(cur_src, src, [0, 0])
156- pl.cast(cur_out, cur_src, mode=pl.RoundMode.CAST_ROUND)
157- pl.store(out, cur_out, [0, 0])
158- 
159- 
160-@pytest.mark.soc("950")
161-def test_cast():
162- device = ST_DEVICE
163- _require_a5(device)
164- torch.manual_seed(0)
165- src = torch.randn(64, 128, device=device, dtype=torch.float16)
166- out = torch.zeros(64, 128, device=device, dtype=torch.float32)
167- cast_kernel(src, out)
168- torch.npu.synchronize()
169- torch.testing.assert_close(out, src.float(), rtol=1e-2, atol=1e-2)
170- logging.info("cast result equal!")
171- 
172- 
173-# ===========================================================================
174-# scatter —— dst_flat[indices[i,j]] = src[i,j],index 为目的的扁平元素偏移
175-# ===========================================================================
176-@pl.jit(auto_mutex=True)
177-def scatter_kernel(
178- src: pl.Tensor[[64, 128], pl.DT_FP32],
179- indices: pl.Tensor[[64, 128], pl.DT_INT32],
180- dst: pl.Tensor[[64, 128], pl.DT_FP32],
181-):
182- tile_src = pl.make_tile_group(
183- type=pl.TileType(shape=[64, 128], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec),
184- addrs=0x0000,
185- mutex_ids=[0],
186- )
187- tile_idx = pl.make_tile_group(
188- type=pl.TileType(shape=[64, 128], dtype=pl.DT_INT32, target_memory=pl.MemorySpace.Vec),
189- addrs=0x8000,
190- mutex_ids=[1],
191- )
192- tile_dst = pl.make_tile_group(
193- type=pl.TileType(shape=[64, 128], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec),
194- addrs=0x10000,
195- mutex_ids=[2],
196- )
197- with pl.section_vector():
198- cur_src = tile_src.current()
199- cur_idx = tile_idx.current()
200- cur_dst = tile_dst.current()
201- pl.load(cur_src, src, [0, 0])
202- pl.load(cur_idx, indices, [0, 0])
203- pl.scatter(cur_dst, cur_src, cur_idx)
204- pl.store(dst, cur_dst, [0, 0])
205- 
206- 
207-@pytest.mark.soc("950")
208-def test_scatter():
209- device = ST_DEVICE
210- _require_a5(device)
211- torch.manual_seed(0)
212- shape = [64, 128]
213- src = torch.rand(shape, device=device, dtype=torch.float32)
214- # 用排列,保证每个 dst 位置只被写一次(无写冲突)
215- num_elements = shape[0] * shape[1]
216- indices = torch.randperm(num_elements, device=device).to(torch.int32).reshape(shape)
217- dst = torch.zeros(shape, device=device, dtype=torch.float32)
218- scatter_kernel(src, indices, dst)
219- torch.npu.synchronize()
220- dst_ref = torch.zeros(num_elements, device="cpu", dtype=torch.float32)
221- src_cpu, idx_cpu = src.cpu(), indices.cpu()
222- for i in range(shape[0]):
223- for j in range(shape[1]):
224- dst_ref[idx_cpu[i, j].item()] = src_cpu[i, j]
225- dst_ref = dst_ref.reshape(shape).to(device)
226- torch.testing.assert_close(dst, dst_ref, rtol=1e-2, atol=1e-2)
227- logging.info("scatter result equal!")
@@ -88,7 +88,6 @@ def sync_all_kernel(
88 pl.store(out, tile_out, [row, 0])88 pl.store(out, tile_out, [row, 0])
89 89 
90 pl.system.sync_all(90 pl.system.sync_all(
91- mode=pl.SyncAllMode.HARD,
92 core_type=pl.SyncCoreType.AIV_ONLY,91 core_type=pl.SyncCoreType.AIV_ONLY,
93 )92 )
94 93 
@@ -490,7 +490,7 @@ def test_builder_if_with_runtime_op():
490 490 
491 b.begin_function("f", sp)491 b.begin_function("f", sp)
492 b.begin_if(ir.ConstBool(True, sp), sp)492 b.begin_if(ir.ConstBool(True, sp), sp)
493- sync = pypto_impl.ir.create_op_call("system.sync_all", [], {"mode": 0, "core_type": 2}, sp)493+ sync = pypto_impl.ir.create_op_call("system.sync_all", [], {"core_type": 2}, sp)
494 b.emit(ir.EvalStmt(sync, sp))494 b.emit(ir.EvalStmt(sync, sp))
495 if_stmt = b.end_if(sp)495 if_stmt = b.end_if(sp)
496 func = b.end_function(sp)496 func = b.end_function(sp)
@@ -12,8 +12,7 @@
12 12 
13Each test compiles a @pl.jit with pl.system.sync_all() and verifies that the13Each test compiles a @pl.jit with pl.system.sync_all() and verifies that the
14generated CCE C++ output contains the expected SYNCALL calls with the correct14generated CCE C++ output contains the expected SYNCALL calls with the correct
15-mode and core_type attributes. Covered cases include the default Mix/hard mode15+core_type attribute. Covered cases include the default Mix and explicit AIVOnly.
16-plus explicit AIVOnly/Mix and soft mode variants.
17"""16"""
18 17 
19import logging18import logging
@@ -29,7 +28,7 @@ def _compile_to_cce(kernel) -> str:
29 28 
30 29 
31# ---------------------------------------------------------------------------30# ---------------------------------------------------------------------------
32-# Hard mode kernels31+# Kernels
33# ---------------------------------------------------------------------------32# ---------------------------------------------------------------------------
34 33 
35 34 
@@ -54,40 +53,7 @@ def _sync_all_aiv_only_kernel(
54 53 
55 54 
56# ---------------------------------------------------------------------------55# ---------------------------------------------------------------------------
57-# Soft mode kernels56+# CCE C++ tests
58-# ---------------------------------------------------------------------------
59- 
60- 
61-@pl.jit
62-def _sync_all_soft_aiv_only_kernel(
63- a: pl.Tensor[[64, 128], pl.DT_FP16],
64- sync_gm: pl.Tensor[[384], pl.DT_INT32],
65-):
66- tile_type = pl.TileType(shape=[64, 128], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)
67- tile_a = pl.make_tile(tile_type, addr=0x0000)
68- pl.load(tile_a, a, [0, 0])
69- sync_ub_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT32, target_memory=pl.MemorySpace.Vec)
70- sync_ub = pl.make_tile(sync_ub_type, addr=0x3000)
71- pl.system.sync_all([sync_gm, sync_ub], mode=pl.SyncAllMode.SOFT, core_type=pl.SyncCoreType.AIV_ONLY)
72- 
73- 
74-@pl.jit
75-def _sync_all_soft_mix_kernel(
76- a: pl.Tensor[[64, 128], pl.DT_FP16],
77- sync_gm: pl.Tensor[[384], pl.DT_INT32],
78-):
79- tile_type = pl.TileType(shape=[64, 128], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)
80- tile_a = pl.make_tile(tile_type, addr=0x0000)
81- pl.load(tile_a, a, [0, 0])
82- sync_ub_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT32, target_memory=pl.MemorySpace.Vec)
83- sync_ub = pl.make_tile(sync_ub_type, addr=0x3000)
84- sync_l1_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT32, target_memory=pl.MemorySpace.Mat)
85- sync_l1 = pl.make_tile(sync_l1_type, addr=0x4000)
86- pl.system.sync_all([sync_gm, sync_ub, sync_l1], mode=pl.SyncAllMode.SOFT, core_type=pl.SyncCoreType.MIX)
87- 
88- 
89-# ---------------------------------------------------------------------------
90-# CCE C++ tests - Hard mode
91# ---------------------------------------------------------------------------57# ---------------------------------------------------------------------------
92 58 
93 59 
@@ -103,23 +69,6 @@ def test_sync_all_aiv_only_cce():
103 assert "SYNCALL<SyncCoreType::AIVOnly>()" in cpp69 assert "SYNCALL<SyncCoreType::AIVOnly>()" in cpp
104 70 
105 71 
106-# ---------------------------------------------------------------------------
107-# CCE C++ tests - Soft mode
108-# ---------------------------------------------------------------------------
109- 
110- 
111-def test_sync_all_soft_aiv_only_cce():
112- cpp = _compile_to_cce(_sync_all_soft_aiv_only_kernel)
113- logging.info("CCE C++ output:\n%s", cpp)
114- assert "SYNCALL<SyncAllMode::Soft, SyncCoreType::AIVOnly>" in cpp
115- 
116- 
117-def test_sync_all_soft_mix_cce():
118- cpp = _compile_to_cce(_sync_all_soft_mix_kernel)
119- logging.info("CCE C++ output:\n%s", cpp)
120- assert "SYNCALL<SyncAllMode::Soft, SyncCoreType::Mix>" in cpp
121- 
122- 
123# ---------------------------------------------------------------------------72# ---------------------------------------------------------------------------
124# Negative: old manual-expansion primitives should NOT appear73# Negative: old manual-expansion primitives should NOT appear
125# ---------------------------------------------------------------------------74# ---------------------------------------------------------------------------
@@ -159,17 +159,6 @@ def test_sync_all_core_type_rejects_plain_integer():
159 func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)159 func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)
160 160 
161 161 
162-def test_sync_all_mode_rejects_plain_integer():
163- with pytest.raises(InvalidVal, match="'mode' expects an enum value"):
164- 
165- @pl.jit(auto_mutex=False)
166- def func(_jit_entry: pl.DT_INT64):
167- pl.system.sync_all(mode=0)
168- 
169- 
170- func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)
171- 
172- 
173@pytest.mark.parametrize("event_id", [True, False])162@pytest.mark.parametrize("event_id", [True, False])
174def test_sync_event_id_rejects_bool(event_id):163def test_sync_event_id_rejects_bool(event_id):
175 @pl.jit(auto_mutex=False)164 @pl.jit(auto_mutex=False)
@@ -340,14 +329,23 @@ def test_manual_mutex_has_no_auto_candidate_metadata(builder):
340 assert "mutex_ids" not in str(call)329 assert "mutex_ids" not in str(call)
341 330 
342 331 
343-def test_sync_all_hard_mode_rejects_workspaces_in_frontend():332+def test_sync_all_rejects_workspaces_in_frontend():
344- with pytest.raises(NotSupported, match="Hard mode sync_all does not accept workspace arguments"):333+ with pytest.raises(TypeError, match="positional argument"):
345- pl.system.sync_all([0], mode=pl.SyncAllMode.HARD)334+ pl.system.sync_all([0])
346 335 
347 336 
348-def test_sync_all_soft_mode_requires_workspaces_in_frontend():337+def test_sync_all_rejects_mode_in_frontend():
349- with pytest.raises(ValueError, match="Soft mode sync_all requires workspaces list"):338+ with pytest.raises(TypeError, match="unexpected keyword argument 'mode'"):
350- pl.system.sync_all(mode=pl.SyncAllMode.SOFT)339+ pl.system.sync_all(mode=0)
340+ 
341+ 
342+def test_sync_all_rejects_workspaces_in_parser():
343+ @pl.jit(auto_mutex=False)
344+ def func(_jit_entry: pl.DT_INT64):
345+ pl.system.sync_all([0])
346+ 
347+ with pytest.raises(InvalidArgument, match="does not accept positional arguments"):
348+ func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)
351 349 
352 350 
353def test_complex_integer_event_id_expression_is_accepted():351def test_complex_integer_event_id_expression_is_accepted():