Merged
feat(function): Add parallel tag in op assemble #5057
高前程Add on Jul 24
feat(function): Add parallel tag in op assemble #5057
Merged
高前程Add on Jul 24
Total: 12 files changed+125-13
@@ -19,7 +19,7 @@
19## 函数原型19## 函数原型
20 20 
21```python21```python
22-assemble(input: Tensor, offsets: List[Union[int, SymbolicScalar]], out: Tensor) -> None22+assemble(input: Tensor, offsets: List[Union[int, SymbolicScalar]], out: Tensor, parallel: bool = False) -> None
23 23 
24assemble(inputs: List[Tuple[Tensor, List[Union[int, SymbolicScalar]]]], out: Tensor, parallel: bool = False) -> None24assemble(inputs: List[Tuple[Tensor, List[Union[int, SymbolicScalar]]]], out: Tensor, parallel: bool = False) -> None
25```25```
@@ -32,7 +32,7 @@ assemble(inputs: List[Tuple[Tensor, List[Union[int, SymbolicScalar]]]], out: Ten
32| inputs | 输入 | 源操作数和输出偏移组成的Tuple列表。<br>单个支持的数据类型为:PyPto支持的数据类型。<br>不支持空Tensor;Shape Size不大于2147483647(即INT32_MAX)。 |32| inputs | 输入 | 源操作数和输出偏移组成的Tuple列表。<br>单个支持的数据类型为:PyPto支持的数据类型。<br>不支持空Tensor;Shape Size不大于2147483647(即INT32_MAX)。 |
33| offsets | 输入 | 相对于目标输出的偏移。<br>需要保证offsets小于out的Shape。 |33| offsets | 输入 | 相对于目标输出的偏移。<br>需要保证offsets小于out的Shape。 |
34| out | 输出 | 目的操作数,需要和input的维度数量一致。<br>支持的数据类型为:PyPto支持的数据类型。<br>不支持空Tensor;Shape Size不大于2147483647(即INT32_MAX)。 |34| out | 输出 | 目的操作数,需要和input的维度数量一致。<br>支持的数据类型为:PyPto支持的数据类型。<br>不支持空Tensor;Shape Size不大于2147483647(即INT32_MAX)。 |
35-| parallel | 输入 | 是否并行执行。<br>默认值为False |35+| parallel | 输入 | 是否允许并行写回。默认值为False;当写回区域互不重叠、可安全并行时,应显式传入`parallel=True`。 |
36 36 
37## 返回值说明37## 返回值说明
38 38 
@@ -42,6 +42,7 @@ assemble(inputs: List[Tuple[Tensor, List[Union[int, SymbolicScalar]]]], out: Ten
42 42 
431. 输出Tensor out的valid shape需由用户在调用assemble前确保正确,该接口不会自动推导。431. 输出Tensor out的valid shape需由用户在调用assemble前确保正确,该接口不会自动推导。
442. 输入张量input和输出张量out的维度数量需要一致。442. 输入张量input和输出张量out的维度数量需要一致。
45+3. 当多个assemble对同一out的重叠区域存在写后写依赖,且这些写回分布在不同loop迭代或不同function中时,默认`parallel=False`已保证写回按依赖顺序串行执行,框架会在对应outcast上标记`NORMAL`,供后续调度按串行写处理。若写回区域互不重叠、可安全并行,应显式传入`parallel=True`。
45 46 
46## 调用示例47## 调用示例
47 48 
@@ -73,3 +74,22 @@ pypto.assemble([(x, offsets), (y, [2, 2])], out)
73 [0, 0, 1, 1],74 [0, 0, 1, 1],
74 [0, 0, 1, 1]]75 [0, 0, 1, 1]]
75```76```
77+ 
78+### 跨loop / 跨function的串行写回
79+ 
80+当同一输出在不同loop迭代或不同function之间存在写后写依赖、必须串行assemble时,默认行为即为串行写回;也可显式传入`parallel=False`:
81+ 
82+```python
83+# 跨loop:后一次写依赖前一次写的结果,默认串行
84+for i in pypto.loop(0, n, name="SEQ_WRITE"):
85+ tile = ...
86+ pypto.assemble(tile, [i * tile_m, 0], out)
87+ 
88+# 跨function:下游function继续写同一out的重叠区域时,同样默认串行
89+pypto.assemble(partial, [offset_m, offset_n], out)
90+```
91+ 
92+说明:
93+ 
94+- 单tensor与批量多源assemble在未传`parallel`时均默认为False;需要并行写回时显式传入`parallel=True`。
95+- 若各次assemble写回区域不重叠且需并行调度,应设置`parallel=True`。
@@ -130,7 +130,7 @@ Tensor View(const Tensor& operand, const std::vector<int64_t>& shapes,
130 const std::vector<SymbolicScalar>& newValidShapes, const std::vector<SymbolicScalar>& newOffsets);130 const std::vector<SymbolicScalar>& newValidShapes, const std::vector<SymbolicScalar>& newOffsets);
131 131 
132Tensor Assemble(const std::vector<std::pair<Tensor, std::vector<int64_t>>>& tensors);132Tensor Assemble(const std::vector<std::pair<Tensor, std::vector<int64_t>>>& tensors);
133-void Assemble(const Tensor& tensor, const std::vector<SymbolicScalar>& dynOffset, Tensor& dest);133+void Assemble(const Tensor& tensor, const std::vector<SymbolicScalar>& dynOffset, Tensor& dest, bool parallel = false);
134 134 
135struct AssembleItem {135struct AssembleItem {
136 Tensor tensor;136 Tensor tensor;
@@ -137,6 +137,7 @@ const std::string OpAttributeKey::rmwMode = "op_attr_rmw_mode";
137const std::string OpAttributeKey::transDataOffset = "TRANSDATA_OFFSET";137const std::string OpAttributeKey::transDataOffset = "TRANSDATA_OFFSET";
138const std::string OpAttributeKey::isConv = "isConv";138const std::string OpAttributeKey::isConv = "isConv";
139const std::string OpAttributeKey::writeConflict = "write_conflict";139const std::string OpAttributeKey::writeConflict = "write_conflict";
140+const std::string OpAttributeKey::parallel = "parallel";
140 141 
141const std::string ConvOpAttributeKey::cin = "CIN";142const std::string ConvOpAttributeKey::cin = "CIN";
142const std::string ConvOpAttributeKey::cout = "COUT";143const std::string ConvOpAttributeKey::cout = "COUT";
@@ -154,6 +154,7 @@ public:
154 static const std::string transDataOffset;154 static const std::string transDataOffset;
155 static const std::string isConv;155 static const std::string isConv;
156 static const std::string writeConflict;156 static const std::string writeConflict;
157+ static const std::string parallel;
157};158};
158 159 
159const std::string CONV_GROUPS_ATTR = "op_attr_groups";160const std::string CONV_GROUPS_ATTR = "op_attr_groups";
@@ -1340,17 +1340,18 @@ Tensor Assemble(const std::vector<std::pair<Tensor, std::vector<int64_t>>>& tens
1340}1340}
1341 1341 
1342Operation& TensorDInnerAssemble(Function& function, const LogicalTensorPtr& operand, const LogicalTensorPtr& result,1342Operation& TensorDInnerAssemble(Function& function, const LogicalTensorPtr& operand, const LogicalTensorPtr& result,
1343- const std::vector<SymbolicScalar>& dynOffset)1343+ const std::vector<SymbolicScalar>& dynOffset, bool parallel)
1344{1344{
1345 std::vector<int64_t> offset = SymbolicScalar::Concrete(dynOffset, 0);1345 std::vector<int64_t> offset = SymbolicScalar::Concrete(dynOffset, 0);
1346 auto& op = function.AddOperation(Opcode::OP_ASSEMBLE, {operand}, {result});1346 auto& op = function.AddOperation(Opcode::OP_ASSEMBLE, {operand}, {result});
1347 op.SetAssembleOpAttribute(offset, dynOffset);1347 op.SetAssembleOpAttribute(offset, dynOffset);
1348 op.SetAttribute("dassemble", true);1348 op.SetAttribute("dassemble", true);
1349+ op.SetAttribute(OpAttributeKey::parallel, parallel);
1349 function.UpdateTensorDataUsage(op);1350 function.UpdateTensorDataUsage(op);
1350 return op;1351 return op;
1351}1352}
1352 1353 
1353-void Assemble(const Tensor& tensor, const std::vector<SymbolicScalar>& dynOffset, Tensor& dest)1354+void Assemble(const Tensor& tensor, const std::vector<SymbolicScalar>& dynOffset, Tensor& dest, bool parallel)
1354{1355{
1355 DECLARE_TRACER();1356 DECLARE_TRACER();
1356 1357 
@@ -1368,7 +1369,7 @@ void Assemble(const Tensor& tensor, const std::vector<SymbolicScalar>& dynOffset
1368 CHECK_OP(dest.GetDataType() == tensor.GetDataType()) << "Assemble: src and dest requires same dtype";1369 CHECK_OP(dest.GetDataType() == tensor.GetDataType()) << "Assemble: src and dest requires same dtype";
1369 1370 
1370 auto& func = *Program::GetInstance().GetCurrentFunction();1371 auto& func = *Program::GetInstance().GetCurrentFunction();
1371- TensorDInnerAssemble(func, tensor.GetStorage(), dest.GetStorage(), dynOffset);1372+ TensorDInnerAssemble(func, tensor.GetStorage(), dest.GetStorage(), dynOffset, parallel);
1372 Program::GetInstance().GetTensorSlotManager()->TensorWrite(dest, SlotProperty::ASSEMBLE_DST);1373 Program::GetInstance().GetTensorSlotManager()->TensorWrite(dest, SlotProperty::ASSEMBLE_DST);
1373}1374}
1374 1375 
@@ -134,6 +134,9 @@ std::shared_ptr<LogicalTensor> LogicalTensor::Clone(Function& dstFunc, bool crea
134 newTensor->readyTime_ = readyTime_;134 newTensor->readyTime_ = readyTime_;
135 newTensor->remainingTime_ = remainingTime_;135 newTensor->remainingTime_ = remainingTime_;
136 newTensor->dynOffset_ = dynOffset_;136 newTensor->dynOffset_ = dynOffset_;
137+ if (HasAttr("NORMAL")) {
138+ newTensor->SetAttr("NORMAL", true);
139+ }
137 dstFunc.GetTensorMap().Insert(newTensor, false);140 dstFunc.GetTensorMap().Insert(newTensor, false);
138 return newTensor;141 return newTensor;
139}142}
@@ -161,6 +164,9 @@ ir::VarPtr LogicalTensor::Clone(bool shareRawTensor) const
161 newTensor->readyTime_ = readyTime_;164 newTensor->readyTime_ = readyTime_;
162 newTensor->remainingTime_ = remainingTime_;165 newTensor->remainingTime_ = remainingTime_;
163 newTensor->dynOffset_ = dynOffset_;166 newTensor->dynOffset_ = dynOffset_;
167+ if (HasAttr("NORMAL")) {
168+ newTensor->SetAttr("NORMAL", true);
169+ }
164 170 
165 return std::static_pointer_cast<const ir::Var>(newTensor);171 return std::static_pointer_cast<const ir::Var>(newTensor);
166}172}
@@ -229,6 +229,20 @@ bool MayOverlap(const std::vector<Operation*>& prods)
229 }229 }
230 return false;230 return false;
231}231}
232+ 
233+bool IsSerialDassemble(const Operation* prod)
234+{
235+ if (prod == nullptr || prod->GetOpcode() != Opcode::OP_ASSEMBLE) {
236+ return false;
237+ }
238+ if (prod->GetIOperands().size() != 1) {
239+ return false;
240+ }
241+ if (!prod->HasAttr(OpAttributeKey::parallel)) {
242+ return false;
243+ }
244+ return !prod->GetBoolAttribute(OpAttributeKey::parallel);
245+}
232} // namespace246} // namespace
233 247 
234Status FunctionUtils::InferOutcastWriteConflict(Function& function)248Status FunctionUtils::InferOutcastWriteConflict(Function& function)
@@ -247,6 +261,9 @@ Status FunctionUtils::InferOutcastWriteConflict(Function& function)
247 if (prod->GetOpcode() == Opcode::OP_ASSEMBLE || prod->GetOpcode() == Opcode::OP_ASSEMBLE_SSA) {261 if (prod->GetOpcode() == Opcode::OP_ASSEMBLE || prod->GetOpcode() == Opcode::OP_ASSEMBLE_SSA) {
248 prods.push_back(prod);262 prods.push_back(prod);
249 }263 }
264+ if (IsSerialDassemble(prod)) {
265+ outcast->SetAttr("NORMAL", true);
266+ }
250 }267 }
251 if (MayOverlap(prods)) {268 if (MayOverlap(prods)) {
252 outcast->SetAttr(OpAttributeKey::writeConflict, true);269 outcast->SetAttr(OpAttributeKey::writeConflict, true);
@@ -62,4 +62,46 @@ TEST(PassTest, InferMemoryConflictInferOutputWriteConflict)
62 }62 }
63 EXPECT_EQ(cnt, 3);63 EXPECT_EQ(cnt, 3);
64}64}
65+ 
66+TEST(PassTest, InferMemoryConflictAssembleParallelFalseMarksNormalAndCloneKeepsIt)
67+{
68+ std::vector<int64_t> shape{-1, 32};
69+ Tensor serialOut(DT_FP32, shape, "serial_out");
70+ Tensor parallelOut(DT_FP32, shape, "parallel_out");
71+ 
72+ Function* loopFunc = nullptr;
73+ FUNCTION("MAIN", {serialOut, parallelOut})
74+ {
75+ TileShape::Current().SetVecTile(32, 32);
76+ LOOP("LOOP", FunctionType::DYNAMIC_LOOP, idx, LoopRange(32))
77+ {
78+ loopFunc = Program::GetInstance().GetCurrentFunction();
79+ auto t = Full(1.0, DT_FP32, {32, 32});
80+ // Cross-loop WAW serial write: parallel=false should mark outcast NORMAL.
81+ Assemble(t, {idx * 32, 0}, serialOut, false);
82+ // Default parallel=true should not mark NORMAL.
83+ Assemble(t, {idx * 32, 0}, parallelOut, true);
84+ }
85+ }
86+ 
87+ const std::string strategyName = "InferAssembleNormalAttrTestStrategy";
88+ PassManager::Instance().RegisterStrategy(strategyName, {{"InferMemoryConflict", PassName::INFER_MEMORY_CONFLICT}});
89+ EXPECT_EQ(PassManager::Instance().RunPass(Program::GetInstance(), *loopFunc, strategyName), SUCCESS);
90+ 
91+ int matched = 0;
92+ for (auto out : loopFunc->GetOriginOutcast()) {
93+ if (out->tensor->GetSymbol() == "serial_out") {
94+ EXPECT_TRUE(out->HasAttr("NORMAL"));
95+ EXPECT_FALSE(out->HasAttr(OpAttributeKey::writeConflict));
96+ auto cloned = out->Clone(*loopFunc, true);
97+ ASSERT_NE(cloned, nullptr);
98+ EXPECT_TRUE(cloned->HasAttr("NORMAL")) << "NORMAL should be inherited by LogicalTensor::Clone";
99+ matched++;
100+ } else if (out->tensor->GetSymbol() == "parallel_out") {
101+ EXPECT_FALSE(out->HasAttr("NORMAL"));
102+ matched++;
103+ }
104+ }
105+ EXPECT_EQ(matched, 2);
106+}
65} // namespace npu::tile_fwk107} // namespace npu::tile_fwk
@@ -22,7 +22,12 @@ from .tensor import Tensor
22 22 
23 23 
24@overload24@overload
25-def assemble(src: Tensor, offsets: List[Union[int, SymbolicScalar]], dst: Tensor) -> None:25+def assemble(
26+ src: Tensor,
27+ offsets: List[Union[int, SymbolicScalar]],
28+ dst: Tensor,
29+ parallel: bool = False,
30+) -> None:
26 """31 """
27 Assembles a small Tensor into a larger Tensor based on specified offsets.32 Assembles a small Tensor into a larger Tensor based on specified offsets.
28 33 
@@ -37,6 +42,10 @@ def assemble(src: Tensor, offsets: List[Union[int, SymbolicScalar]], dst: Tensor
37 42 
38 dst: Tensor43 dst: Tensor
39 The larger output tensor that will contain the assembled input tensor44 The larger output tensor that will contain the assembled input tensor
45+ 
46+ parallel : bool, optional
47+ Whether assemble can be executed in parallel. Defaults to False.
48+ 
40 Examples49 Examples
41 ---------50 ---------
42 x = pypto.tensor([2, 2], pypto.data_type.DT_FP32)51 x = pypto.tensor([2, 2], pypto.data_type.DT_FP32)
@@ -61,7 +70,9 @@ def assemble(src: Tensor, offsets: List[Union[int, SymbolicScalar]], dst: Tensor
61 70 
62@overload71@overload
63def assemble(72def assemble(
64- srcs: Sequence[Tuple[Tensor, List[Union[int, SymbolicScalar]]]], dst: Tensor, parallel: bool = False73+ srcs: Sequence[Tuple[Tensor, List[Union[int, SymbolicScalar]]]],
74+ dst: Tensor,
75+ parallel: bool = False,
65) -> None:76) -> None:
66 """77 """
67 Assembles multiple small Tensors into a larger Tensor based on specified offsets.78 Assembles multiple small Tensors into a larger Tensor based on specified offsets.
@@ -73,6 +84,10 @@ def assemble(
73 84 
74 dst: Tensor85 dst: Tensor
75 The larger output tensor86 The larger output tensor
87+ 
88+ parallel : bool, optional
89+ Whether assemble can be executed in parallel. Defaults to False.
90+ 
76 Examples91 Examples
77 ---------92 ---------
78 x = pypto.tensor([2, 2], pypto.DT_FP32)93 x = pypto.tensor([2, 2], pypto.DT_FP32)
@@ -107,7 +122,7 @@ def assemble(*args, parallel: bool = False) -> None:
107 pypto_impl.Assemble(srcs, dst.base(), parallel)122 pypto_impl.Assemble(srcs, dst.base(), parallel)
108 else:123 else:
109 src, offsets, dst = args124 src, offsets, dst = args
110- pypto_impl.Assemble(src.base(), to_syms(offsets), dst.base())125+ pypto_impl.Assemble(src.base(), to_syms(offsets), dst.base(), parallel)
111 126 
112 127 
113def min(a: "SymbolicScalar | int", b: "SymbolicScalar | int") -> "SymbolicScalar":128def min(a: "SymbolicScalar | int", b: "SymbolicScalar | int") -> "SymbolicScalar":
@@ -778,7 +778,7 @@ def Assemble(a: List[Tuple[Tensor, List[SymbolicScalar]]], dst: Tensor,
778 778 
779 779 
780@overload780@overload
781-def Assemble(a: Tensor, offset: List[SymbolicScalar], dst: Tensor) -> None: ...781+def Assemble(a: Tensor, offset: List[SymbolicScalar], dst: Tensor, parallel: bool = True) -> None: ...
782 782 
783 783 
784def AtomicRMW(src: Tensor, offsets: List[SymbolicScalar], dst: Tensor, mode: AtomicRMWMode) -> None: ...784def AtomicRMW(src: Tensor, offsets: List[SymbolicScalar], dst: Tensor, mode: AtomicRMWMode) -> None: ...
@@ -734,10 +734,10 @@ void BindOperation(py::module_& m)
734 "Tensor assemble");734 "Tensor assemble");
735 m.def(735 m.def(
736 "Assemble",736 "Assemble",
737- [](const Tensor& tensor, const std::vector<SymbolicScalar>& dynOffset, Tensor& dest) {737+ [](const Tensor& tensor, const std::vector<SymbolicScalar>& dynOffset, Tensor& dest, bool parallel = false) {
738- npu::tile_fwk::Assemble(tensor, dynOffset, dest);738+ npu::tile_fwk::Assemble(tensor, dynOffset, dest, parallel);
739 },739 },
740- "Tensor dassemble");740+ py::arg("tensor"), py::arg("dynOffset"), py::arg("dest"), py::arg("parallel") = false, "Tensor dassemble");
741 m.def(741 m.def(
742 "AtomicRMW",742 "AtomicRMW",
743 [](const Tensor& src, const std::vector<SymbolicScalar>& offsets, Tensor& dst, AtomicRMWMode mode) {743 [](const Tensor& src, const std::vector<SymbolicScalar>& offsets, Tensor& dst, AtomicRMWMode mode) {
@@ -10,6 +10,7 @@
10# -----------------------------------------------------------------------------------------------------------10# -----------------------------------------------------------------------------------------------------------
11""" """11""" """
12 12 
13+ 
13import pytest14import pytest
14 15 
15import pypto16import pypto
@@ -104,6 +105,14 @@ def test_tensor_batch_assemble():
104 )105 )
105 106 
106 107 
108+def test_single_assemble_explicit_parallel():
109+ src = pypto.tensor((32, 32), pypto.DT_FP32, "src")
110+ dst = pypto.tensor((32, 32), pypto.DT_FP32, "dst")
111+ 
112+ with pypto.function("MAIN", src, dst):
113+ pypto.set_vec_tile_shapes(32, 32)
114+ pypto.assemble(src, [0, 0], dst, parallel=True)
115+ 
107def test_view_dimension_mismatch_shapes():116def test_view_dimension_mismatch_shapes():
108 """Test that shapes dimension mismatch with operand raises error (LogicalTensor constraint)"""117 """Test that shapes dimension mismatch with operand raises error (LogicalTensor constraint)"""
109 x_shape = [4, 8, 16]118 x_shape = [4, 8, 16]