Merged
feat(pass): Attach tile-graph tokens from source op during ExpandFunction #5755
高前程Add on Aug 28
feat(pass): Attach tile-graph tokens from source op during ExpandFunction #5755
Merged
高前程Add on Aug 28
Total: 11 files changed+437-515
@@ -148,7 +148,7 @@ void FunctionCache::UpdateBinCache(const Function& func, CacheValue& value)
148 totalSize += binData.size() + sizeof(uint64_t);148 totalSize += binData.size() + sizeof(uint64_t);
149 binMap[ele.first] = std::move(binData);149 binMap[ele.first] = std::move(binData);
150 } else {150 } else {
151- MACHINE_LOGE(InternalError::MACHINE_INNER_ERROR, "bin path %s is not existed", binPath.c_str());151+ MACHINE_LOGE(InternalError::MACHINE_INNER_ERROR, "bin path %s does not exist", binPath.c_str());
152 abort();152 abort();
153 }153 }
154 }154 }
@@ -39,8 +39,8 @@
39#include "passes/pass_utils/subgraph_utils.h"39#include "passes/pass_utils/subgraph_utils.h"
40#include "passes/pass_utils/pass_utils.h"40#include "passes/pass_utils/pass_utils.h"
41#include "passes/pass_utils/graph_utils.h"41#include "passes/pass_utils/graph_utils.h"
42-#include "interface/tensor/contract_write_token.h"
43#include "interface/tensor/irbuilder.h"42#include "interface/tensor/irbuilder.h"
43+#include "passes/tensor_graph_pass/expand_function.h"
44#include "ir/transforms/printer.h"44#include "ir/transforms/printer.h"
45using namespace npu::tile_fwk;45using namespace npu::tile_fwk;
46 46 
@@ -1768,62 +1768,213 @@ Operation& Function::AddOperation(const std::string& opName, LogicalTensors iOpe
1768 return AddOperation(FindOpcode(opName), iOperands, oOperands);1768 return AddOperation(FindOpcode(opName), iOperands, oOperands);
1769}1769}
1770 1770 
1771+namespace {
1772+ 
1773+LogicalTensorPtr GetSliceParent(const LogicalTensorPtr& tensor)
1774+{
1775+ LogicalTensorPtr parent = nullptr;
1776+ if (tensor == nullptr || !tensor->GetAttr("SLICE_PARENT", parent)) {
1777+ return nullptr;
1778+ }
1779+ return parent;
1780+}
1781+ 
1782+void ResetSliceView(const LogicalTensorPtr& tensor)
1783+{
1784+ int dim = tensor->shape.size();
1785+ tensor->offset = std::vector<int64_t>(dim, 0);
1786+ tensor->dynOffset_ = std::vector<SymbolicScalar>(dim, SymbolicScalar(0));
1787+ tensor->RemoveAttr("SLICE_PARENT");
1788+ tensor->tensor = std::make_shared<RawTensor>(tensor->tensor->datatype, tensor->shape, tensor->tensor->format,
1789+ tensor->tensor->symbol);
1790+}
1791+ 
1792+ir::VarPtr GetPairedNormalToken(const ir::VarPtr& token)
1793+{
1794+ if (token == nullptr) {
1795+ return nullptr;
1796+ }
1797+ return ExpandFunction::GetNormalToken(token);
1798+}
1799+ 
1800+bool SameLogicalTensorPtr(const LogicalTensorPtr& lhs, const LogicalTensorPtr& rhs)
1801+{
1802+ if (lhs == nullptr || rhs == nullptr) {
1803+ return false;
1804+ }
1805+ return lhs.get() == rhs.get() || lhs->GetMagic() == rhs->GetMagic();
1806+}
1807+ 
1808+bool IsCurrentTileOpOperand(const LogicalTensorPtr& tensor, const LogicalTensors& currentOperands)
1809+{
1810+ if (tensor == nullptr) {
1811+ return false;
1812+ }
1813+ auto parent = GetSliceParent(tensor);
1814+ for (const auto& current : currentOperands) {
1815+ if (SameLogicalTensorPtr(tensor, current) || SameLogicalTensorPtr(parent, current)) {
1816+ return true;
1817+ }
1818+ }
1819+ return false;
1820+}
1821+ 
1822+bool HasCurrentTileOpOperand(const LogicalTensors& tensors, const LogicalTensors& currentOperands)
1823+{
1824+ for (const auto& tensor : tensors) {
1825+ if (IsCurrentTileOpOperand(tensor, currentOperands)) {
1826+ return true;
1827+ }
1828+ }
1829+ return false;
1830+}
1831+ 
1832+bool AttachReadToMatchingInputParents(const LogicalTensors& iOperands, const LogicalTensors& currentInputs,
1833+ const ir::VarPtr& token, const ir::VarPtr& normal,
1834+ std::unordered_map<LogicalTensor*, std::vector<ir::VarPtr>>& target)
1835+{
1836+ bool matched = false;
1837+ for (const auto& iOp : iOperands) {
1838+ if (!IsCurrentTileOpOperand(iOp, currentInputs)) {
1839+ continue;
1840+ }
1841+ auto parent = GetSliceParent(iOp);
1842+ if (parent == nullptr || parent->GetReadToken() != token) {
1843+ continue;
1844+ }
1845+ target[iOp.get()].push_back(normal);
1846+ matched = true;
1847+ }
1848+ return matched;
1849+}
1850+ 
1851+bool AttachToOutputParents(const LogicalTensors& oOperands, const LogicalTensors& currentOutputs,
1852+ const ir::VarPtr& normal,
1853+ std::unordered_map<LogicalTensor*, std::vector<ir::VarPtr>>& target)
1854+{
1855+ bool hasParent = false;
1856+ for (const auto& oOp : oOperands) {
1857+ if (!IsCurrentTileOpOperand(oOp, currentOutputs)) {
1858+ continue;
1859+ }
1860+ if (GetSliceParent(oOp) == nullptr) {
1861+ continue;
1862+ }
1863+ target[oOp.get()].push_back(normal);
1864+ hasParent = true;
1865+ }
1866+ return hasParent;
1867+}
1868+ 
1869+struct ExpandTokenPlan {
1870+ std::unordered_map<LogicalTensor*, std::vector<ir::VarPtr>> sliceResultTokens;
1871+ std::unordered_map<LogicalTensor*, std::vector<ir::VarPtr>> contractResultTokens;
1872+ std::unordered_map<LogicalTensor*, std::vector<ir::VarPtr>> contractInputTokens;
1873+ std::vector<ir::VarPtr> opResultTokens;
1874+ std::vector<ir::VarPtr> opInputTokens;
1875+};
1876+ 
1877+void CollectResultTokens(const Operation& tileOp, const LogicalTensors& iOperands, const LogicalTensors& oOperands,
1878+ ExpandTokenPlan& plan)
1879+{
1880+ const auto& currentInputs = tileOp.GetIOperands();
1881+ const auto& currentOutputs = tileOp.GetOOperands();
1882+ for (const auto& token : tileOp.result_token_) {
1883+ auto tokenType = token ? std::dynamic_pointer_cast<const ir::TokenType>(token->GetType()) : nullptr;
1884+ auto normal = GetPairedNormalToken(token);
1885+ if (tokenType == nullptr || normal == nullptr) {
1886+ continue;
1887+ }
1888+ if (tokenType->kind_ == ir::TokenKind::READ) {
1889+ if (!AttachReadToMatchingInputParents(iOperands, currentInputs, token, normal, plan.sliceResultTokens) &&
1890+ HasCurrentTileOpOperand(oOperands, currentOutputs)) {
1891+ plan.opResultTokens.push_back(normal);
1892+ }
1893+ } else if (tokenType->kind_ == ir::TokenKind::WRITE) {
1894+ if (!AttachToOutputParents(oOperands, currentOutputs, normal, plan.contractResultTokens) &&
1895+ HasCurrentTileOpOperand(oOperands, currentOutputs)) {
1896+ plan.opResultTokens.push_back(normal);
1897+ }
1898+ }
1899+ }
1900+}
1901+ 
1902+void CollectInputTokens(const Operation& tileOp, const LogicalTensors& iOperands, const LogicalTensors& oOperands,
1903+ ExpandTokenPlan& plan)
1904+{
1905+ const auto& currentInputs = tileOp.GetIOperands();
1906+ const auto& currentOutputs = tileOp.GetOOperands();
1907+ for (const auto& token : tileOp.tokens_) {
1908+ auto normal = GetPairedNormalToken(token);
1909+ if (normal == nullptr) {
1910+ continue;
1911+ }
1912+ if (!AttachToOutputParents(oOperands, currentOutputs, normal, plan.contractInputTokens) &&
1913+ HasCurrentTileOpOperand(iOperands, currentInputs)) {
1914+ plan.opInputTokens.push_back(normal);
1915+ }
1916+ }
1917+}
1918+ 
1919+ExpandTokenPlan CollectExpandTokenPlan(Operation* currentTileOp, const LogicalTensors& iOperands,
1920+ const LogicalTensors& oOperands)
1921+{
1922+ ExpandTokenPlan plan;
1923+ if (currentTileOp == nullptr) {
1924+ return plan;
1925+ }
1926+ CollectResultTokens(*currentTileOp, iOperands, oOperands, plan);
1927+ CollectInputTokens(*currentTileOp, iOperands, oOperands, plan);
1928+ return plan;
1929+}
1930+ 
1931+void AssignMappedTokens(std::vector<ir::VarPtr>& dst,
1932+ const std::unordered_map<LogicalTensor*, std::vector<ir::VarPtr>>& src, LogicalTensor* key)
1933+{
1934+ auto it = src.find(key);
1935+ if (it != src.end()) {
1936+ dst = it->second;
1937+ }
1938+}
1939+ 
1940+} // namespace
1941+ 
1771Operation& Function::AddOperation(const Opcode opCode, LogicalTensors iOperands, const LogicalTensors& oOperands)1942Operation& Function::AddOperation(const Opcode opCode, LogicalTensors iOperands, const LogicalTensors& oOperands)
1772{1943{
1773- IRBuilder builder;1944+ auto plan = CollectExpandTokenPlan(ExpandFunction::GetCurrentTileOp(), iOperands, oOperands);
1774 CheckTensorDynamicShape(iOperands, opCode);1945 CheckTensorDynamicShape(iOperands, opCode);
1775 1946 
1776- auto ClearOffset = [](LogicalTensorPtr t) {
1777- int dim = t->shape.size();
1778- t->offset = std::vector<int64_t>(dim, 0);
1779- t->dynOffset_ = std::vector<SymbolicScalar>(dim, SymbolicScalar(0));
1780- };
1781- 
1782 const Opcode sliceOpcode = config::GetSliceOpcode();1947 const Opcode sliceOpcode = config::GetSliceOpcode();
1783 const Opcode contractOpcode = config::GetContractOpcode();1948 const Opcode contractOpcode = config::GetContractOpcode();
1784- 
1785- auto cmp = [](ir::VarPtr a, ir::VarPtr b) { return a->name_ < b->name_; };
1786- std::set<ir::VarPtr, decltype(cmp)> tokenSets(cmp);
1787 for (auto& iOp : iOperands) {1949 for (auto& iOp : iOperands) {
1788- LogicalTensorPtr parent = nullptr;1950+ auto parent = GetSliceParent(iOp);
1789- if (iOp->GetAttr("SLICE_PARENT", parent)) {1951+ if (parent == nullptr) {
1790- auto newRaw = std::make_shared<RawTensor>(iOp->tensor->datatype, iOp->shape, iOp->tensor->format,1952+ continue;
1791- iOp->tensor->symbol);
1792- auto& op = AddRawOperation(sliceOpcode, {parent}, {iOp});
1793- op.SetOpAttribute(std::make_shared<ViewOpAttribute>(iOp->offset, iOp->dynOffset_, iOp->dynValidShape_));
1794- if (auto readToken = parent->GetReadToken()) {
1795- if (auto normalToken = IRContext::Get().GetNormalToken(readToken)) {
1796- op.result_token_ = {normalToken};
1797- }
1798- }
1799- ClearOffset(iOp);
1800- iOp->RemoveAttr("SLICE_PARENT");
1801- iOp->tensor = newRaw;
1802- auto tokens = builder.GetDependToken(parent);
1803- tokenSets.insert(tokens.begin(), tokens.end());
1804 }1953 }
1954+ auto& sliceOp = AddRawOperation(sliceOpcode, {parent}, {iOp});
1955+ sliceOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(iOp->offset, iOp->dynOffset_, iOp->dynValidShape_));
1956+ AssignMappedTokens(sliceOp.result_token_, plan.sliceResultTokens, iOp.get());
1957+ ResetSliceView(iOp);
1805 }1958 }
1806 1959 
1807 auto& ret = AddRawOperation(opCode, iOperands, oOperands);1960 auto& ret = AddRawOperation(opCode, iOperands, oOperands);
1961+ if (!plan.opResultTokens.empty()) {
1962+ ret.result_token_ = std::move(plan.opResultTokens);
1963+ }
1964+ if (!plan.opInputTokens.empty()) {
1965+ ret.tokens_ = std::move(plan.opInputTokens);
1966+ }
1808 1967 
1809- std::vector<ir::VarPtr> tokenList(tokenSets.begin(), tokenSets.end());
1810 for (auto& oOp : oOperands) {1968 for (auto& oOp : oOperands) {
1811- LogicalTensorPtr parent = nullptr;1969+ auto parent = GetSliceParent(oOp);
1812- if (oOp->GetAttr("SLICE_PARENT", parent)) {1970+ if (parent == nullptr) {
1813- auto newRaw = std::make_shared<RawTensor>(oOp->tensor->datatype, oOp->shape, oOp->tensor->format,1971+ continue;
1814- oOp->tensor->symbol);
1815- auto& op = AddRawOperation(contractOpcode, {oOp}, {parent});
1816- op.SetAssembleOpAttribute(oOp->offset, oOp->dynOffset_);
1817- ClearOffset(oOp);
1818- oOp->RemoveAttr("SLICE_PARENT");
1819- oOp->tensor = newRaw;
1820- auto deps = builder.GetDependToken(parent);
1821- if (!deps.empty()) {
1822- op.result_token_ = {deps[0]};
1823- }
1824- op.tokens_ = tokenList;
1825- ApplyContractWriteNormalTokens(op, oOp);
1826 }1972 }
1973+ auto& contractOp = AddRawOperation(contractOpcode, {oOp}, {parent});
1974+ contractOp.SetAssembleOpAttribute(oOp->offset, oOp->dynOffset_);
1975+ AssignMappedTokens(contractOp.result_token_, plan.contractResultTokens, oOp.get());
1976+ AssignMappedTokens(contractOp.tokens_, plan.contractInputTokens, oOp.get());
1977+ ResetSliceView(oOp);
1827 }1978 }
1828 return ret;1979 return ret;
1829}1980}
@@ -25,12 +25,12 @@
25#include "tilefwk/symbolic_scalar.h"25#include "tilefwk/symbolic_scalar.h"
26#include "tilefwk/tensor.h"26#include "tilefwk/tensor.h"
27#include "interface/tensor/logical_tensor.h"27#include "interface/tensor/logical_tensor.h"
28-#include "interface/tensor/contract_write_token.h"
29#include "interface/program/program.h"28#include "interface/program/program.h"
30#include "interface/configs/config_manager.h"29#include "interface/configs/config_manager.h"
31#include "interface/utils/common.h"30#include "interface/utils/common.h"
32#include "interface/utils/operator_tracer.h"31#include "interface/utils/operator_tracer.h"
33#include "passes/pass_utils/graph_utils.h"32#include "passes/pass_utils/graph_utils.h"
33+#include "passes/tensor_graph_pass/expand_function.h"
34#include "interface/tensor/irbuilder.h"34#include "interface/tensor/irbuilder.h"
35 35 
36using namespace npu::tile_fwk;36using namespace npu::tile_fwk;
@@ -142,9 +142,47 @@ void PropagateExpandedAssembleOpAttrs(Function& function, const Operation& sourc
142 }142 }
143}143}
144 144 
145+void AttachExpandResultTokens(Operation& sliceOp, Operation& contractOp, Operation* currentTileOp,
146+ const LogicalTensorPtr& matchReadOn)
147+{
148+ if (currentTileOp == nullptr) {
149+ return;
150+ }
151+ for (const auto& token : currentTileOp->result_token_) {
152+ if (token == nullptr) {
153+ continue;
154+ }
155+ auto tokenType = std::dynamic_pointer_cast<const ir::TokenType>(token->GetType());
156+ auto normal = ExpandFunction::GetNormalToken(token);
157+ if (tokenType == nullptr || normal == nullptr) {
158+ continue;
159+ }
160+ if (tokenType->kind_ == ir::TokenKind::READ) {
161+ if (matchReadOn != nullptr && matchReadOn->GetReadToken() != token) {
162+ continue;
163+ }
164+ sliceOp.result_token_.push_back(normal);
165+ } else if (tokenType->kind_ == ir::TokenKind::WRITE) {
166+ contractOp.result_token_.push_back(normal);
167+ }
168+ }
169+}
170+ 
171+void AttachExpandInputTokens(Operation& contractOp, Operation* currentTileOp)
172+{
173+ if (currentTileOp == nullptr) {
174+ return;
175+ }
176+ for (const auto& token : currentTileOp->tokens_) {
177+ auto normal = ExpandFunction::GetNormalToken(token);
178+ if (normal != nullptr) {
179+ contractOp.tokens_.push_back(normal);
180+ }
181+ }
182+}
183+ 
145void TiledAssembleRecursive(Function& function, const TileShape& tileShape, size_t cur, Input& input,184void TiledAssembleRecursive(Function& function, const TileShape& tileShape, size_t cur, Input& input,
146- const std::shared_ptr<LogicalTensor>& result, std::shared_ptr<AssembleOpAttribute> attr,185+ const std::shared_ptr<LogicalTensor>& result, std::shared_ptr<AssembleOpAttribute> attr)
147- const Operation& sourceOp)
148{186{
149 if (cur == input.tensor.GetShape().size()) {187 if (cur == input.tensor.GetShape().size()) {
150 auto operand = input.tensor.GetStorage();188 auto operand = input.tensor.GetStorage();
@@ -163,10 +201,11 @@ void TiledAssembleRecursive(Function& function, const TileShape& tileShape, size
163 auto& sliceOp = function.AddRawOperation(Opcode::OP_SLICE, {operand}, {inputTile});201 auto& sliceOp = function.AddRawOperation(Opcode::OP_SLICE, {operand}, {inputTile});
164 sliceOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(fromOffset, fromDynOffset, tileValidShape));202 sliceOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(fromOffset, fromDynOffset, tileValidShape));
165 203 
166- AttachContractWriteTokenAttrs(result, sourceOp);
167 auto& contractOp = function.AddRawOperation(Opcode::OP_CONTRACT, {inputTile}, {result});204 auto& contractOp = function.AddRawOperation(Opcode::OP_CONTRACT, {inputTile}, {result});
168- ApplyContractWriteNormalTokens(contractOp, result);
169 contractOp.SetAttr("NeedCopy", true);205 contractOp.SetAttr("NeedCopy", true);
206+ auto* currentTileOp = ExpandFunction::GetCurrentTileOp();
207+ AttachExpandResultTokens(sliceOp, contractOp, currentTileOp, operand);
208+ AttachExpandInputTokens(contractOp, currentTileOp);
170 inputTile->SetMemoryTypeOriginal(MemoryType::MEM_UNKNOWN);209 inputTile->SetMemoryTypeOriginal(MemoryType::MEM_UNKNOWN);
171 const auto& baseToOffset = attr->GetToOffset();210 const auto& baseToOffset = attr->GetToOffset();
172 const auto& baseToDynOffset = attr->GetToDynOffset();211 const auto& baseToDynOffset = attr->GetToDynOffset();
@@ -192,7 +231,7 @@ void TiledAssembleRecursive(Function& function, const TileShape& tileShape, size
192 for (int i = 0; i < input.tensor.GetShape()[cur]; i += tileDim) {231 for (int i = 0; i < input.tensor.GetShape()[cur]; i += tileDim) {
193 input.tileInfo.shape[cur] = std::min(input.tensor.GetShape()[cur] - i, tileDim);232 input.tileInfo.shape[cur] = std::min(input.tensor.GetShape()[cur] - i, tileDim);
194 input.tileInfo.offset[cur] = i;233 input.tileInfo.offset[cur] = i;
195- TiledAssembleRecursive(function, tileShape, cur + 1, input, result, attr, sourceOp);234+ TiledAssembleRecursive(function, tileShape, cur + 1, input, result, attr);
196 }235 }
197}236}
198 237 
@@ -229,6 +268,19 @@ void TiledViewOperationRecursive(Function& function, const TileShape& tileShape,
229 auto resultParent = output.tensor.GetStorage();268 auto resultParent = output.tensor.GetStorage();
230 auto& contractOp = function.AddRawOperation(Opcode::OP_CONTRACT, {resultTile}, {resultParent});269 auto& contractOp = function.AddRawOperation(Opcode::OP_CONTRACT, {resultTile}, {resultParent});
231 contractOp.SetAttr("NeedCopy", true);270 contractOp.SetAttr("NeedCopy", true);
271+ auto* currentTileOp = ExpandFunction::GetCurrentTileOp();
272+ if (currentTileOp != nullptr) {
273+ size_t readCount = 0;
274+ for (const auto& token : currentTileOp->result_token_) {
275+ auto tokenType = token ? std::dynamic_pointer_cast<const ir::TokenType>(token->GetType()) : nullptr;
276+ if (tokenType != nullptr && tokenType->kind_ == ir::TokenKind::READ) {
277+ ++readCount;
278+ }
279+ }
280+ FE_ASSERT(FeError::INVALID_VAL, readCount <= 1)
281+ << "VIEW can have at most one READ result token, got " << readCount;
282+ }
283+ AttachExpandResultTokens(viewOp, contractOp, currentTileOp, nullptr);
232 resultTile->SetMemoryTypeOriginal(MemoryType::MEM_UNKNOWN);284 resultTile->SetMemoryTypeOriginal(MemoryType::MEM_UNKNOWN);
233 std::vector<SymbolicScalar> toDynOffset;285 std::vector<SymbolicScalar> toDynOffset;
234 toDynOffset.reserve(output.tileInfo.offset.size());286 toDynOffset.reserve(output.tileInfo.offset.size());
@@ -254,15 +306,14 @@ void TiledViewOperationRecursive(Function& function, const TileShape& tileShape,
254namespace npu::tile_fwk {306namespace npu::tile_fwk {
255 307 
256void TiledAssemble(Function& function, const TileShape& tileShape, const std::shared_ptr<LogicalTensor>& operand,308void TiledAssemble(Function& function, const TileShape& tileShape, const std::shared_ptr<LogicalTensor>& operand,
257- const std::shared_ptr<LogicalTensor>& result, std::shared_ptr<AssembleOpAttribute> attr,309+ const std::shared_ptr<LogicalTensor>& result, std::shared_ptr<AssembleOpAttribute> attr)
258- const Operation& sourceOp)
259{310{
260 ASSERT(VectorErrorCode::ERR_PARAM_INVALID, operand->shape.size() == operand->offset.size())311 ASSERT(VectorErrorCode::ERR_PARAM_INVALID, operand->shape.size() == operand->offset.size())
261 << "operand's shape size and offset size should be equal";312 << "operand's shape size and offset size should be equal";
262 313 
263 TileInfo tileInfo(operand->shape.size(), operand->offset.size());314 TileInfo tileInfo(operand->shape.size(), operand->offset.size());
264 auto input = Input{operand, tileInfo};315 auto input = Input{operand, tileInfo};
265- TiledAssembleRecursive(function, tileShape, 0, input, result, attr, sourceOp);316+ TiledAssembleRecursive(function, tileShape, 0, input, result, attr);
266}317}
267 318 
268void TiledViewOperation(Function& function, const TileShape& tileShape, const LogicalTensorPtr& operand,319void TiledViewOperation(Function& function, const TileShape& tileShape, const LogicalTensorPtr& operand,
@@ -1577,16 +1628,11 @@ void AtomicRMW(const Tensor& t, const std::vector<SymbolicScalar>& dynOffset, Te
1577 1628 
1578void TiledInnerAssemble(Function& function, const TileShape& tileShape, size_t cur,1629void TiledInnerAssemble(Function& function, const TileShape& tileShape, size_t cur,
1579 const std::vector<SymbolicScalar>& initialOffsets, const LogicalTensorPtr& src,1630 const std::vector<SymbolicScalar>& initialOffsets, const LogicalTensorPtr& src,
1580- const LogicalTensorPtr& dst, const LogicalTensorPtr& result, TileInfo& tileInfo,1631+ const LogicalTensorPtr& dst, const LogicalTensorPtr& result, TileInfo& tileInfo)
1581- const Operation& sourceOp)
1582{1632{
1583 if (cur == src->GetShape().size()) {1633 if (cur == src->GetShape().size()) {
1584 auto srcTile = src->View(function, tileInfo.shape, tileInfo.offset);1634 auto srcTile = src->View(function, tileInfo.shape, tileInfo.offset);
1585- AttachContractWriteTokenAttrs(result, sourceOp);
1586 auto& op = function.AddOperation(Opcode::OP_ASSEMBLE_SSA, {srcTile, dst}, {result});1635 auto& op = function.AddOperation(Opcode::OP_ASSEMBLE_SSA, {srcTile, dst}, {result});
1587- if (result->HasAttr(kContractWriteTokenOut) || result->HasAttr(kContractWriteTokenIn)) {
1588- ApplyContractWriteNormalTokens(op, result);
1589- }
1590 auto srcTileOffset = initialOffsets;1636 auto srcTileOffset = initialOffsets;
1591 CHECK_OP(initialOffsets.size() == tileInfo.offset.size());1637 CHECK_OP(initialOffsets.size() == tileInfo.offset.size());
1592 for (size_t i = 0; i < srcTileOffset.size(); i++) {1638 for (size_t i = 0; i < srcTileOffset.size(); i++) {
@@ -1604,7 +1650,7 @@ void TiledInnerAssemble(Function& function, const TileShape& tileShape, size_t c
1604 for (auto i = 0; i < src->shape[cur]; i += vecTile[cur]) {1650 for (auto i = 0; i < src->shape[cur]; i += vecTile[cur]) {
1605 tileInfo.offset[cur] = i;1651 tileInfo.offset[cur] = i;
1606 tileInfo.shape[cur] = std::min(src->shape[cur] - tileInfo.offset[cur], vecTile[cur]);1652 tileInfo.shape[cur] = std::min(src->shape[cur] - tileInfo.offset[cur], vecTile[cur]);
1607- TiledInnerAssemble(function, tileShape, cur + 1, initialOffsets, src, dst, result, tileInfo, sourceOp);1653+ TiledInnerAssemble(function, tileShape, cur + 1, initialOffsets, src, dst, result, tileInfo);
1608 }1654 }
1609}1655}
1610 1656 
@@ -1620,7 +1666,7 @@ void TiledInnerAssemble(Function& function, const TileShape& tileShape, const Op
1620 CHECK_OP(assembleOpAttribute != nullptr);1666 CHECK_OP(assembleOpAttribute != nullptr);
1621 const auto& initialOffsets = assembleOpAttribute->GetToDynOffset();1667 const auto& initialOffsets = assembleOpAttribute->GetToDynOffset();
1622 TileInfo tileInfo(src->GetShape().size(), src->GetOffset().size());1668 TileInfo tileInfo(src->GetShape().size(), src->GetOffset().size());
1623- TiledInnerAssemble(function, tileShape, 0, initialOffsets, src, dst, result, tileInfo, op);1669+ TiledInnerAssemble(function, tileShape, 0, initialOffsets, src, dst, result, tileInfo);
1624}1670}
1625 1671 
1626void TensorInnerAssemble(Function& function, const LogicalTensorPtr& value, const std::vector<SymbolicScalar>& offsets,1672void TensorInnerAssemble(Function& function, const LogicalTensorPtr& value, const std::vector<SymbolicScalar>& offsets,
@@ -2142,7 +2188,7 @@ void ExpandOperationInto(Function& function, const TileShape& tileShape, Opcode
2142 const auto& inputShape = iOperand[0]->GetShape();2188 const auto& inputShape = iOperand[0]->GetShape();
2143 assembleOpAttribute = std::make_shared<AssembleOpAttribute>(std::vector<int64_t>(inputShape.size(), 0));2189 assembleOpAttribute = std::make_shared<AssembleOpAttribute>(std::vector<int64_t>(inputShape.size(), 0));
2144 }2190 }
2145- TiledAssemble(function, GetAssembleExpandTileShape(op), iOperand[0], oOperand[0], assembleOpAttribute, op);2191+ TiledAssemble(function, GetAssembleExpandTileShape(op), iOperand[0], oOperand[0], assembleOpAttribute);
2146 PropagateExpandedAssembleOpAttrs(function, op, opListPreSize);2192 PropagateExpandedAssembleOpAttrs(function, op, opListPreSize);
2147 break;2193 break;
2148 }2194 }
@@ -36,8 +36,7 @@ void ExpandOperationInto(Function& function, const TileShape& tileShape, Opcode
36 const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);36 const std::vector<std::shared_ptr<LogicalTensor>>& oOperand, const Operation& op);
37 37 
38void TiledAssemble(Function& function, const TileShape& tileShape, const LogicalTensorPtr& operand,38void TiledAssemble(Function& function, const TileShape& tileShape, const LogicalTensorPtr& operand,
39- const LogicalTensorPtr& result, std::shared_ptr<AssembleOpAttribute> attr,39+ const LogicalTensorPtr& result, std::shared_ptr<AssembleOpAttribute> attr);
40- const Operation& sourceOp);
41 40 
42void TiledViewOperation(Function& function, const TileShape& tileShape, const LogicalTensorPtr& operand,41void TiledViewOperation(Function& function, const TileShape& tileShape, const LogicalTensorPtr& operand,
43 const LogicalTensorPtr& result, const Operation& op);42 const LogicalTensorPtr& result, const Operation& op);
@@ -1,138 +0,0 @@
1-/**
2- * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3- * This program is free software; you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License).
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10-#pragma once
11- 
12-#include <algorithm>
13-#include <vector>
14- 
15-#include "interface/operation/operation.h"
16-#include "interface/operation/opcode.h"
17-#include "interface/tensor/irbuilder.h"
18-#include "interface/tensor/logical_tensor.h"
19-#include "ir/type.h"
20- 
21-namespace npu::tile_fwk {
22- 
23-inline constexpr const char* kContractWriteTokenOut = "contract_write_token_out";
24-inline constexpr const char* kContractWriteTokenIn = "contract_write_token_in";
25-inline constexpr const char* kContractReadTokenIn = "contract_read_token_in";
26- 
27-inline bool IsMemoryWriteOpcode(Opcode opcode)
28-{
29- return opcode == Opcode::OP_ASSEMBLE || opcode == Opcode::OP_ASSEMBLE_SSA || opcode == Opcode::OP_ATOMIC_RMW;
30-}
31- 
32-inline bool IsWriteSemanticToken(const ir::VarPtr& token)
33-{
34- if (!token) {
35- return false;
36- }
37- auto tokenType = std::dynamic_pointer_cast<const ir::TokenType>(token->GetType());
38- return tokenType != nullptr && tokenType->kind_ == ir::TokenKind::WRITE;
39-}
40- 
41-inline bool IsReadSemanticToken(const ir::VarPtr& token)
42-{
43- if (!token) {
44- return false;
45- }
46- auto tokenType = std::dynamic_pointer_cast<const ir::TokenType>(token->GetType());
47- return tokenType != nullptr && tokenType->kind_ == ir::TokenKind::READ;
48-}
49- 
50-inline std::vector<ir::VarPtr> CollectWriteSemanticTokens(const std::vector<ir::VarPtr>& tokens)
51-{
52- std::vector<ir::VarPtr> writeTokens;
53- for (const auto& token : tokens) {
54- if (IsWriteSemanticToken(token)) {
55- writeTokens.push_back(token);
56- }
57- }
58- return writeTokens;
59-}
60- 
61-inline std::vector<ir::VarPtr> CollectReadSemanticTokens(const std::vector<ir::VarPtr>& tokens)
62-{
63- std::vector<ir::VarPtr> readTokens;
64- for (const auto& token : tokens) {
65- if (IsReadSemanticToken(token)) {
66- readTokens.push_back(token);
67- }
68- }
69- return readTokens;
70-}
71- 
72-inline void SortTokenVars(std::vector<ir::VarPtr>& tokens)
73-{
74- std::sort(tokens.begin(), tokens.end(),
75- [](const ir::VarPtr& lhs, const ir::VarPtr& rhs) { return lhs->name_ < rhs->name_; });
76-}
77- 
78-inline void AppendSemanticNormalTokens(std::vector<ir::VarPtr>& target, const std::vector<ir::VarPtr>& semanticTokens)
79-{
80- for (const auto& semantic : semanticTokens) {
81- if (auto normal = IRContext::Get().GetNormalToken(semantic)) {
82- target.push_back(normal);
83- }
84- }
85-}
86- 
87-inline void AttachContractWriteTokenAttrs(const LogicalTensorPtr& tensor, const Operation& sourceOp)
88-{
89- if (!tensor || !IsMemoryWriteOpcode(sourceOp.GetOpcode())) {
90- return;
91- }
92- auto outTokens = CollectWriteSemanticTokens(sourceOp.result_token_);
93- auto writeInTokens = CollectWriteSemanticTokens(sourceOp.tokens_);
94- auto readInTokens = CollectReadSemanticTokens(sourceOp.tokens_);
95- if (!outTokens.empty()) {
96- tensor->SetAttr(kContractWriteTokenOut, std::move(outTokens));
97- }
98- if (!writeInTokens.empty()) {
99- tensor->SetAttr(kContractWriteTokenIn, std::move(writeInTokens));
100- }
101- if (!readInTokens.empty()) {
102- tensor->SetAttr(kContractReadTokenIn, std::move(readInTokens));
103- }
104-}
105- 
106-inline void ApplyContractWriteNormalTokens(Operation& contractOp, const LogicalTensorPtr& tensor)
107-{
108- if (!tensor) {
109- return;
110- }
111- auto deps = IRContext::Get().GetDependToken(std::static_pointer_cast<ir::Expr>(tensor));
112- if (!deps.empty()) {
113- contractOp.result_token_ = {deps[0]};
114- }
115- if (tensor->HasAttr(kContractReadTokenIn)) {
116- std::vector<ir::VarPtr> readInTokens;
117- tensor->GetAttr(kContractReadTokenIn, readInTokens);
118- AppendSemanticNormalTokens(contractOp.tokens_, readInTokens);
119- SortTokenVars(contractOp.tokens_);
120- tensor->RemoveAttr(kContractReadTokenIn);
121- }
122- if (tensor->HasAttr(kContractWriteTokenOut)) {
123- std::vector<ir::VarPtr> outTokens;
124- tensor->GetAttr(kContractWriteTokenOut, outTokens);
125- AppendSemanticNormalTokens(contractOp.result_token_, outTokens);
126- SortTokenVars(contractOp.result_token_);
127- tensor->RemoveAttr(kContractWriteTokenOut);
128- }
129- if (tensor->HasAttr(kContractWriteTokenIn)) {
130- std::vector<ir::VarPtr> inTokens;
131- tensor->GetAttr(kContractWriteTokenIn, inTokens);
132- AppendSemanticNormalTokens(contractOp.tokens_, inTokens);
133- SortTokenVars(contractOp.tokens_);
134- tensor->RemoveAttr(kContractWriteTokenIn);
135- }
136-}
137- 
138-} // namespace npu::tile_fwk
@@ -78,19 +78,7 @@ ir::VarPtr IRContext::MakeSemanticToken(std::string name, ir::TokenKind kind, ir
78{78{
79 FE_ASSERT(FeError::INVALID_VAL, kind == ir::TokenKind::READ || kind == ir::TokenKind::WRITE)79 FE_ASSERT(FeError::INVALID_VAL, kind == ir::TokenKind::READ || kind == ir::TokenKind::WRITE)
80 << "MakeSemanticToken requires READ or WRITE kind";80 << "MakeSemanticToken requires READ or WRITE kind";
81- auto semantic = MakeVar(std::move(name), ir::GetTokenType(kind), span);81+ return MakeVar(std::move(name), ir::GetTokenType(kind), span);
82- auto normal = MakeVar(semantic->name_ + "_n", ir::GetTokenType(ir::TokenKind::NORMAL), span);
83- semantic_to_normal_.emplace(semantic, normal);
84- return semantic;
85-}
86- 
87-ir::VarPtr IRContext::GetNormalToken(const ir::VarPtr& semantic) const
88-{
89- if (!semantic) {
90- return nullptr;
91- }
92- auto it = semantic_to_normal_.find(semantic);
93- return it != semantic_to_normal_.end() ? it->second : nullptr;
94}82}
95 83 
96Function& DummyFunc()84Function& DummyFunc()
@@ -94,7 +94,6 @@ public:
94 var_counter_.clear();94 var_counter_.clear();
95 all_vars_.clear();95 all_vars_.clear();
96 token_map_.clear();96 token_map_.clear();
97- semantic_to_normal_.clear();
98 ClearTensorDataDescList();97 ClearTensorDataDescList();
99 }98 }
100 99 
@@ -109,14 +108,10 @@ public:
109 std::vector<ir::VarPtr> GetDependToken(Operation& op);108 std::vector<ir::VarPtr> GetDependToken(Operation& op);
110 109 
111 /**110 /**
112- * Create a READ/WRITE semantic token and its paired NORMAL token.111+ * Create a READ/WRITE semantic token used by the tensor graph.
113- * The NORMAL token is registered internally and is not returned.
114 */112 */
115 ir::VarPtr MakeSemanticToken(std::string name, ir::TokenKind kind, ir::Span span);113 ir::VarPtr MakeSemanticToken(std::string name, ir::TokenKind kind, ir::Span span);
116 114 
117- /** Look up the NORMAL token paired with a READ/WRITE semantic token. */
118- ir::VarPtr GetNormalToken(const ir::VarPtr& semantic) const;
119- 
120 int AddTensorDataDesc(const std::shared_ptr<Tensor>& assembleTensor)115 int AddTensorDataDesc(const std::shared_ptr<Tensor>& assembleTensor)
121 {116 {
122 int index = static_cast<int>(getTensorDataDescList.size());117 int index = static_cast<int>(getTensorDataDescList.size());
@@ -141,7 +136,6 @@ private:
141 std::map<std::string, int64_t> var_counter_; // counter for named variable136 std::map<std::string, int64_t> var_counter_; // counter for named variable
142 std::map<std::string, std::string> all_vars_; // unique var name -> var name137 std::map<std::string, std::string> all_vars_; // unique var name -> var name
143 std::unordered_map<ir::ExprPtr, std::vector<ir::VarPtr>> token_map_;138 std::unordered_map<ir::ExprPtr, std::vector<ir::VarPtr>> token_map_;
144- std::unordered_map<ir::VarPtr, ir::VarPtr> semantic_to_normal_;
145 std::vector<std::shared_ptr<Tensor>> getTensorDataDescList;139 std::vector<std::shared_ptr<Tensor>> getTensorDataDescList;
146 bool assembleNewLogicalTensor_{false};140 bool assembleNewLogicalTensor_{false};
147};141};
@@ -19,6 +19,7 @@
19#include "passes/pass_utils/pass_operation_utils.h"19#include "passes/pass_utils/pass_operation_utils.h"
20#include "interface/tensor/raw_tensor.h"20#include "interface/tensor/raw_tensor.h"
21#include "interface/tensor/logical_tensor.h"21#include "interface/tensor/logical_tensor.h"
22+#include "interface/tensor/irbuilder.h"
22#include "tilefwk/tilefwk.h"23#include "tilefwk/tilefwk.h"
23#include "interface/inner/tilefwk.h"24#include "interface/inner/tilefwk.h"
24#include "interface/program/program.h"25#include "interface/program/program.h"
@@ -407,6 +408,23 @@ namespace npu::tile_fwk {
407// OP_SLICE / OP_CONTRACT 仅在 ExpandFunction 展开过程中由 AddOperation 插入,本身已是 tile 级语义408// OP_SLICE / OP_CONTRACT 仅在 ExpandFunction 展开过程中由 AddOperation 插入,本身已是 tile 级语义
408const std::unordered_set<Opcode> ExpandFunction::kNotNeedExpandOps = {Opcode::OP_SLICE, Opcode::OP_CONTRACT,409const std::unordered_set<Opcode> ExpandFunction::kNotNeedExpandOps = {Opcode::OP_SLICE, Opcode::OP_CONTRACT,
409 Opcode::OP_NOP, Opcode::OP_ATOMIC_RMW};410 Opcode::OP_NOP, Opcode::OP_ATOMIC_RMW};
411+thread_local Operation* ExpandFunction::currentTileOp_ = nullptr;
412+thread_local std::unordered_map<ir::VarPtr, ir::VarPtr> ExpandFunction::semanticToNormal_;
413+ 
414+ir::VarPtr ExpandFunction::GetNormalToken(const ir::VarPtr& semantic)
415+{
416+ if (semantic == nullptr) {
417+ return nullptr;
418+ }
419+ auto it = semanticToNormal_.find(semantic);
420+ if (it != semanticToNormal_.end()) {
421+ return it->second;
422+ }
423+ auto normal = IRContext::Get().MakeVar(semantic->name_ + "_n", ir::GetTokenType(ir::TokenKind::NORMAL),
424+ semantic->span_);
425+ semanticToNormal_.emplace(semantic, normal);
426+ return normal;
427+}
410 428 
411Status ExpandFunction::ClearIOOperand(const std::vector<OperationPtr>& tensorOperations) const429Status ExpandFunction::ClearIOOperand(const std::vector<OperationPtr>& tensorOperations) const
412{430{
@@ -490,8 +508,6 @@ void ExpandFunction::ProcessForNotExpandOp(Function& function, Operation& op) co
490 if (op.HasAttribute(OpAttributeKey::rmwMode)) {508 if (op.HasAttribute(OpAttributeKey::rmwMode)) {
491 newOp.SetAttribute(OpAttributeKey::rmwMode, op.GetIntAttribute(OpAttributeKey::rmwMode));509 newOp.SetAttribute(OpAttributeKey::rmwMode, op.GetIntAttribute(OpAttributeKey::rmwMode));
492 }510 }
493- newOp.result_token_ = op.result_token_;
494- newOp.tokens_ = op.tokens_;
495}511}
496 512 
497Status ExpandFunction::DefaultEnabledPreCheck(Function& function)513Status ExpandFunction::DefaultEnabledPreCheck(Function& function)
@@ -586,6 +602,7 @@ Status ExpandFunction::Expandfunction(Function& function) const
586 return SUCCESS;602 return SUCCESS;
587 }603 }
588 function.expandFunctionAccelerate = true;604 function.expandFunctionAccelerate = true;
605+ SemanticToNormalGuard semanticToNormalGuard;
589 function.SetGraphType(GraphType::TILE_GRAPH);606 function.SetGraphType(GraphType::TILE_GRAPH);
590 607 
591 std::vector<OperationPtr> tensorOperations;608 std::vector<OperationPtr> tensorOperations;
@@ -674,6 +691,7 @@ Status ExpandFunction::ExpandOperation(Function& function, Operation& op) const
674 config::SetPassOption(SG_SET_OOO_SCOPE, std::vector<int64_t>{-1});691 config::SetPassOption(SG_SET_OOO_SCOPE, std::vector<int64_t>{-1});
675 }692 }
676 } scopeConfigGuard;693 } scopeConfigGuard;
694+ CurrentTileOpGuard currentTileOpGuard(op);
677 ExpandOperationInto(function, op.GetTileShape(), op.GetOpcode(), op.GetIOperands(), op.GetOOperands(), op);695 ExpandOperationInto(function, op.GetTileShape(), op.GetOpcode(), op.GetIOperands(), op.GetOOperands(), op);
678 return SUCCESS;696 return SUCCESS;
679}697}
@@ -16,11 +16,13 @@
16#ifndef PASS_EXPAND_FUNCTION_H_16#ifndef PASS_EXPAND_FUNCTION_H_
17#define PASS_EXPAND_FUNCTION_H_17#define PASS_EXPAND_FUNCTION_H_
18 18 
19+#include <unordered_map>
19#include <unordered_set>20#include <unordered_set>
20#include <sstream>21#include <sstream>
21#include "passes/pass_interface/pass.h"22#include "passes/pass_interface/pass.h"
22#include "interface/operation/opcode.h"23#include "interface/operation/opcode.h"
23#include "interface/operation/operation.h"24#include "interface/operation/operation.h"
25+#include "ir/expr.h"
24 26 
25namespace npu::tile_fwk {27namespace npu::tile_fwk {
26class ExpandFunction : public Pass {28class ExpandFunction : public Pass {
@@ -30,6 +32,9 @@ public:
30 Status DefaultEnabledPreCheck(Function& function) override;32 Status DefaultEnabledPreCheck(Function& function) override;
31 Status PostCheck(Function& function) override;33 Status PostCheck(Function& function) override;
32 34 
35+ static Operation* GetCurrentTileOp() { return currentTileOp_; }
36+ static ir::VarPtr GetNormalToken(const ir::VarPtr& semantic);
37+ 
33private:38private:
34 Status RunOnFunction(Function& function) override;39 Status RunOnFunction(Function& function) override;
35 Status Expandfunction(Function& function) const;40 Status Expandfunction(Function& function) const;
@@ -41,6 +46,20 @@ private:
41 void ProcessForNotExpandOp(Function& function, Operation& op) const;46 void ProcessForNotExpandOp(Function& function, Operation& op) const;
42 void DoHealthCheckBefore(Function& function, const std::string& folderPath) override;47 void DoHealthCheckBefore(Function& function, const std::string& folderPath) override;
43 48 
49+ struct CurrentTileOpGuard {
50+ explicit CurrentTileOpGuard(Operation& op) { currentTileOp_ = &op; }
51+ ~CurrentTileOpGuard() { currentTileOp_ = nullptr; }
52+ CurrentTileOpGuard(const CurrentTileOpGuard&) = delete;
53+ CurrentTileOpGuard& operator=(const CurrentTileOpGuard&) = delete;
54+ };
55+ 
56+ struct SemanticToNormalGuard {
57+ SemanticToNormalGuard() { semanticToNormal_.clear(); }
58+ ~SemanticToNormalGuard() { semanticToNormal_.clear(); }
59+ };
60+ 
61+ static thread_local Operation* currentTileOp_;
62+ static thread_local std::unordered_map<ir::VarPtr, ir::VarPtr> semanticToNormal_;
44 static const std::unordered_set<Opcode> kNotNeedExpandOps;63 static const std::unordered_set<Opcode> kNotNeedExpandOps;
45};64};
46} // namespace npu::tile_fwk65} // namespace npu::tile_fwk
@@ -16,6 +16,7 @@
16#include <gtest/gtest.h>16#include <gtest/gtest.h>
17#include <vector>17#include <vector>
18#include <string>18#include <string>
19+#include "ir/type.h"
19#include "interface/function/function.h"20#include "interface/function/function.h"
20#include "interface/operation/attribute.h"21#include "interface/operation/attribute.h"
21#include "tilefwk/tilefwk.h"22#include "tilefwk/tilefwk.h"
@@ -131,6 +132,20 @@ int CountSliceOpsOnInputWithShape(Function& function, const LogicalTensorPtr& in
131 return count;132 return count;
132}133}
133 134 
135+bool HasNormalTokenNamed(const std::vector<ir::VarPtr>& tokens, const std::string& namePart)
136+{
137+ for (const auto& token : tokens) {
138+ if (token == nullptr || token->name_.find(namePart) == std::string::npos) {
139+ continue;
140+ }
141+ auto tokenType = std::dynamic_pointer_cast<const ir::TokenType>(token->GetType());
142+ if (tokenType != nullptr && tokenType->kind_ == ir::TokenKind::NORMAL) {
143+ return true;
144+ }
145+ }
146+ return false;
147+}
148+ 
134} // namespace149} // namespace
135 150 
136struct ScopeCfg {151struct ScopeCfg {
@@ -1086,5 +1101,126 @@ TEST_F(TestExpandFunctionPass, AssembleDerivesVecTileFromCubeMatmulProducer)
1086 EXPECT_EQ(CountSliceOpsOnInputWithShape(*func, matmulOut, {kCubeM, kCubeM}), 0);1101 EXPECT_EQ(CountSliceOpsOnInputWithShape(*func, matmulOut, {kCubeM, kCubeM}), 0);
1087}1102}
1088 1103 
1104+TEST_F(TestExpandFunctionPass, ComputeOpReadGoesToSliceAndWriteGoesToContract)
1105+{
1106+ TileShape::Current().SetVecTile(kNumExpSix, kNumExpSix);
1107+ auto func = std::make_shared<Function>(Program::GetInstance(), "ComputeOpTokenAttach", "ComputeOpTokenAttach",
1108+ nullptr);
1109+ ASSERT_NE(func, nullptr);
1110+ 
1111+ std::vector<int64_t> shape = {kNumExpSix, kNumExpSix};
1112+ auto lhs = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1113+ auto rhs = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1114+ auto out = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1115+ 
1116+ auto& addOp = PassOperationUtils::AddOperation(*func, Opcode::OP_ADD, {lhs, rhs}, {out});
1117+ addOp.tileShape_.SetVecTile(kNumExpSix, kNumExpSix);
1118+ 
1119+ auto readSemantic = IRContext::Get().MakeSemanticToken("lhs_r", ir::TokenKind::READ, ir::Span::Unknown());
1120+ auto writeSemantic = IRContext::Get().MakeSemanticToken("out_w", ir::TokenKind::WRITE, ir::Span::Unknown());
1121+ auto depSemantic = IRContext::Get().MakeSemanticToken("dep_w", ir::TokenKind::WRITE, ir::Span::Unknown());
1122+ lhs->SetReadToken(readSemantic);
1123+ addOp.result_token_ = {readSemantic, writeSemantic};
1124+ addOp.tokens_ = {depSemantic};
1125+ 
1126+ func->inCasts_.push_back(lhs);
1127+ func->inCasts_.push_back(rhs);
1128+ func->outCasts_.push_back(out);
1129+ func->SetGraphType(GraphType::TENSOR_GRAPH);
1130+ 
1131+ ExpandFunction expandPass;
1132+ ASSERT_EQ(expandPass.RunOnFunction(*func), SUCCESS);
1133+ 
1134+ bool sliceHasRead = false;
1135+ bool rhsSliceHasRead = false;
1136+ bool contractHasWrite = false;
1137+ bool contractHasDep = false;
1138+ bool addHasRead = false;
1139+ for (auto& op : func->Operations(false)) {
1140+ if (op.GetOpcode() == Opcode::OP_SLICE && !op.GetIOperands().empty() && op.GetIOperands()[0] == lhs) {
1141+ sliceHasRead = sliceHasRead || HasNormalTokenNamed(op.result_token_, "lhs_r");
1142+ }
1143+ if (op.GetOpcode() == Opcode::OP_SLICE && !op.GetIOperands().empty() && op.GetIOperands()[0] == rhs) {
1144+ rhsSliceHasRead = rhsSliceHasRead || HasNormalTokenNamed(op.result_token_, "lhs_r");
1145+ }
1146+ if (op.GetOpcode() == Opcode::OP_CONTRACT && !op.GetOOperands().empty() && op.GetOOperands()[0] == out) {
1147+ contractHasWrite = contractHasWrite || HasNormalTokenNamed(op.result_token_, "out_w");
1148+ contractHasDep = contractHasDep || HasNormalTokenNamed(op.tokens_, "dep_w");
1149+ }
1150+ if (op.GetOpcode() == Opcode::OP_ADD) {
1151+ addHasRead = addHasRead || HasNormalTokenNamed(op.result_token_, "lhs_r");
1152+ }
1153+ }
1154+ EXPECT_TRUE(sliceHasRead);
1155+ EXPECT_FALSE(rhsSliceHasRead);
1156+ EXPECT_TRUE(contractHasWrite);
1157+ EXPECT_TRUE(contractHasDep);
1158+ EXPECT_FALSE(addHasRead);
1159+}
1160+ 
1161+TEST_F(TestExpandFunctionPass, AssembleWriteGoesToContractAndConsumedOnNextAssemble)
1162+{
1163+ TileShape::Current().SetVecTile(kNumExpSix, kNumExpSix);
1164+ auto func = std::make_shared<Function>(Program::GetInstance(), "AssembleTokenAttach", "AssembleTokenAttach",
1165+ nullptr);
1166+ ASSERT_NE(func, nullptr);
1167+ 
1168+ std::vector<int64_t> shape = {kNumExpSix, kNumExpSix};
1169+ auto src1 = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1170+ auto src2 = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1171+ auto out = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1172+ auto assembleAttr1 = CreateAssembleOpAttr();
1173+ auto assembleAttr2 = CreateAssembleOpAttr();
1174+ 
1175+ auto& firstAssemble = PassOperationUtils::AddOperation(*func, Opcode::OP_ASSEMBLE, {src1}, {out});
1176+ auto& secondAssemble = PassOperationUtils::AddOperation(*func, Opcode::OP_ASSEMBLE, {src2}, {out});
1177+ firstAssemble.SetOpAttribute(assembleAttr1);
1178+ secondAssemble.SetOpAttribute(assembleAttr2);
1179+ firstAssemble.tileShape_.SetVecTile(kNumExpSix, kNumExpSix);
1180+ secondAssemble.tileShape_.SetVecTile(kNumExpSix, kNumExpSix);
1181+ 
1182+ auto readSemantic = IRContext::Get().MakeSemanticToken("src1_r", ir::TokenKind::READ, ir::Span::Unknown());
1183+ auto firstWrite = IRContext::Get().MakeSemanticToken("out_w1", ir::TokenKind::WRITE, ir::Span::Unknown());
1184+ auto secondWrite = IRContext::Get().MakeSemanticToken("out_w2", ir::TokenKind::WRITE, ir::Span::Unknown());
1185+ src1->SetReadToken(readSemantic);
1186+ firstAssemble.result_token_ = {readSemantic, firstWrite};
1187+ secondAssemble.result_token_ = {secondWrite};
1188+ secondAssemble.tokens_ = {firstWrite};
1189+ 
1190+ func->inCasts_.push_back(src1);
1191+ func->inCasts_.push_back(src2);
1192+ func->outCasts_.push_back(out);
1193+ func->SetGraphType(GraphType::TENSOR_GRAPH);
1194+ 
1195+ ExpandFunction expandPass;
1196+ ASSERT_EQ(expandPass.RunOnFunction(*func), SUCCESS);
1197+ 
1198+ bool src1SliceHasRead = false;
1199+ int contractWithFirstWrite = 0;
1200+ int contractWithSecondWrite = 0;
1201+ int contractConsumingFirstWrite = 0;
1202+ for (auto& op : func->Operations(false)) {
1203+ if (op.GetOpcode() == Opcode::OP_SLICE && !op.GetIOperands().empty() && op.GetIOperands()[0] == src1) {
1204+ src1SliceHasRead = src1SliceHasRead || HasNormalTokenNamed(op.result_token_, "src1_r");
1205+ }
1206+ if (op.GetOpcode() != Opcode::OP_CONTRACT) {
1207+ continue;
1208+ }
1209+ if (HasNormalTokenNamed(op.result_token_, "out_w1")) {
1210+ ++contractWithFirstWrite;
1211+ }
1212+ if (HasNormalTokenNamed(op.result_token_, "out_w2")) {
1213+ ++contractWithSecondWrite;
1214+ }
1215+ if (HasNormalTokenNamed(op.tokens_, "out_w1")) {
1216+ ++contractConsumingFirstWrite;
1217+ }
1218+ }
1219+ EXPECT_TRUE(src1SliceHasRead);
1220+ EXPECT_EQ(contractWithFirstWrite, 1);
1221+ EXPECT_EQ(contractWithSecondWrite, 1);
1222+ EXPECT_EQ(contractConsumingFirstWrite, 1);
1223+}
1224+ 
1089} // namespace tile_fwk1225} // namespace tile_fwk
1090} // namespace npu1226} // namespace npu
@@ -1,291 +0,0 @@
1-/**
2- * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License).
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_expandfunction_cascade_assemble_waw.cpp
13- * \brief ExpandFunction UT for assemble WAW write-token propagation; RAW read-token via AddOperation.
14- */
15- 
16-#include <algorithm>
17-#include <vector>
18- 
19-#include <gtest/gtest.h>
20- 
21-#include "interface/configs/config_manager.h"
22-#include "interface/function/function.h"
23-#include "interface/operation/attribute.h"
24-#include "interface/tensor/contract_write_token.h"
25-#include "interface/tensor/irbuilder.h"
26-#include "ir/type.h"
27-#include "passes/pass_utils/pass_operation_utils.h"
28-#include "passes/tensor_graph_pass/expand_function.h"
29-#include "symbolic_scalar_test_utils.h"
30-#include "tilefwk/tilefwk.h"
31-#include "interface/inner/tilefwk.h"
32- 
33-namespace npu::tile_fwk {
34-namespace {
35- 
36-constexpr uint16_t kTileDim = 64u;
37- 
38-void EnableSliceAndContract()
39-{
40- config::SetPassOption(ENABLE_SLICE, true);
41- ASSERT_TRUE(config::EnableSlice());
42- EXPECT_EQ(config::GetSliceOpcode(), Opcode::OP_SLICE);
43- EXPECT_EQ(config::GetContractOpcode(), Opcode::OP_CONTRACT);
44-}
45- 
46-bool ContainsToken(const std::vector<ir::VarPtr>& tokens, const ir::VarPtr& target)
47-{
48- return std::find(tokens.begin(), tokens.end(), target) != tokens.end();
49-}
50- 
51-bool IsNormalToken(const ir::VarPtr& token)
52-{
53- if (!token) {
54- return false;
55- }
56- auto tokenType = std::dynamic_pointer_cast<const ir::TokenType>(token->GetType());
57- return tokenType != nullptr && tokenType->kind_ == ir::TokenKind::NORMAL;
58-}
59- 
60-std::vector<Operation*> CollectOpsByOpcode(Function& function, Opcode opcode)
61-{
62- std::vector<Operation*> ops;
63- for (auto& op : function.Operations(false)) {
64- if (op.GetOpcode() == opcode) {
65- ops.push_back(&op);
66- }
67- }
68- return ops;
69-}
70- 
71-std::shared_ptr<AssembleOpAttribute> CreateZeroOffsetAssembleAttr()
72-{
73- std::vector<int64_t> toOffset = {0, 0};
74- std::vector<SymbolicScalar> dynOffset = {CreateTestScalarVar("sym0"), CreateTestScalarVar("sym1")};
75- return std::make_shared<AssembleOpAttribute>(toOffset, dynOffset);
76-}
77- 
78-void InjectCascadeAssembleWriteTokens(const std::vector<Operation*>& assembleOps, ir::VarPtr& firstWriteNormal,
79- ir::VarPtr& secondWriteNormal)
80-{
81- ASSERT_EQ(assembleOps.size(), 2U);
82- 
83- auto& ctx = IRContext::Get();
84- ir::Span span = ir::Span::Unknown();
85- auto firstWriteSemantic = ctx.MakeSemanticToken("out_w1", ir::TokenKind::WRITE, span);
86- auto secondWriteSemantic = ctx.MakeSemanticToken("out_w2", ir::TokenKind::WRITE, span);
87- firstWriteNormal = ctx.GetNormalToken(firstWriteSemantic);
88- secondWriteNormal = ctx.GetNormalToken(secondWriteSemantic);
89- ASSERT_NE(firstWriteNormal, nullptr);
90- ASSERT_NE(secondWriteNormal, nullptr);
91- 
92- assembleOps[0]->result_token_ = {firstWriteSemantic};
93- assembleOps[1]->result_token_ = {secondWriteSemantic};
94- assembleOps[1]->tokens_ = {firstWriteSemantic};
95-}
96- 
97-void InjectReadBeforeWriteAssembleTokens(Operation& assembleOp, ir::VarPtr& readNormal, ir::VarPtr& writeNormal)
98-{
99- auto& ctx = IRContext::Get();
100- ir::Span span = ir::Span::Unknown();
101- auto readSemantic = ctx.MakeSemanticToken("buf_r", ir::TokenKind::READ, span);
102- auto writeSemantic = ctx.MakeSemanticToken("buf_w", ir::TokenKind::WRITE, span);
103- readNormal = ctx.GetNormalToken(readSemantic);
104- writeNormal = ctx.GetNormalToken(writeSemantic);
105- ASSERT_NE(readNormal, nullptr);
106- ASSERT_NE(writeNormal, nullptr);
107- 
108- assembleOp.result_token_ = {writeSemantic};
109- assembleOp.tokens_ = {readSemantic};
110-}
111- 
112-void ExpectNoSemanticWriteTokensOnContract(const std::vector<Operation*>& contractOps)
113-{
114- for (const auto* contractOp : contractOps) {
115- for (const auto& token : contractOp->result_token_) {
116- EXPECT_FALSE(IsWriteSemanticToken(token));
117- }
118- for (const auto& token : contractOp->tokens_) {
119- EXPECT_FALSE(IsWriteSemanticToken(token));
120- }
121- }
122-}
123- 
124-} // namespace
125- 
126-class TestExpandFunctionAssembleTokenPropagation : public ::testing::Test {
127-protected:
128- void SetUp() override
129- {
130- Program::GetInstance().Reset();
131- config::Reset();
132- EnableSliceAndContract();
133- config::SetHostOption(COMPILE_STAGE, CS_EXECUTE_GRAPH);
134- TileShape::Current().SetVecTile(kTileDim, kTileDim);
135- }
136- 
137- void TearDown() override { Program::GetInstance().Reset(); }
138-};
139- 
140-/*
141- * Cascading assemble WAW on the same outCast:
142- * src1 -> assemble -> out
143- * src2 -> assemble -> out (depends on first write token)
144- *
145- * Run ExpandFunction only (with enable_slice=true so slice/contract path is active)
146- * and verify write semantic tokens propagate to contract ops
147- * as paired NORMAL tokens (result_token_ for producer write, tokens_ for consumer write).
148- */
149-TEST_F(TestExpandFunctionAssembleTokenPropagation, CascadeAssembleWriteAfterWriteTokenPropagation)
150-{
151- EnableSliceAndContract();
152- 
153- auto function = std::make_shared<Function>(Program::GetInstance(), "CascadeAssembleWAW", "CascadeAssembleWAW",
154- nullptr);
155- ASSERT_NE(function, nullptr);
156- 
157- std::vector<int64_t> shape = {kTileDim, kTileDim};
158- auto src1 = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
159- auto src2 = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
160- auto outCast = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
161- 
162- auto assembleAttr = CreateZeroOffsetAssembleAttr();
163- auto& firstAssemble = PassOperationUtils::AddOperation(*function, Opcode::OP_ASSEMBLE, {src1}, {outCast});
164- auto& secondAssemble = PassOperationUtils::AddOperation(*function, Opcode::OP_ASSEMBLE, {src2}, {outCast});
165- firstAssemble.SetOpAttribute(assembleAttr);
166- secondAssemble.SetOpAttribute(assembleAttr);
167- firstAssemble.tileShape_.SetVecTile({kTileDim, kTileDim});
168- secondAssemble.tileShape_.SetVecTile({kTileDim, kTileDim});
169- 
170- function->inCasts_.push_back(src1);
171- function->inCasts_.push_back(src2);
172- function->outCasts_.push_back(outCast);
173- function->SetGraphType(GraphType::TENSOR_GRAPH);
174- 
175- auto assembleOps = CollectOpsByOpcode(*function, Opcode::OP_ASSEMBLE);
176- ir::VarPtr firstWriteNormal;
177- ir::VarPtr secondWriteNormal;
178- InjectCascadeAssembleWriteTokens(assembleOps, firstWriteNormal, secondWriteNormal);
179- 
180- ExpandFunction expandPass;
181- EXPECT_EQ(expandPass.RunOnFunction(*function), SUCCESS);
182- EXPECT_EQ(function->GetGraphType(), GraphType::TILE_GRAPH);
183- 
184- EXPECT_TRUE(CollectOpsByOpcode(*function, Opcode::OP_ASSEMBLE).empty());
185- 
186- const auto sliceOpcode = config::GetSliceOpcode();
187- const auto contractOpcode = config::GetContractOpcode();
188- auto sliceOps = CollectOpsByOpcode(*function, sliceOpcode);
189- auto contractOps = CollectOpsByOpcode(*function, contractOpcode);
190- EXPECT_EQ(sliceOpcode, Opcode::OP_SLICE);
191- EXPECT_EQ(contractOpcode, Opcode::OP_CONTRACT);
192- ASSERT_EQ(sliceOps.size(), 2U);
193- ASSERT_EQ(contractOps.size(), 2U);
194- 
195- auto& firstContract = *contractOps[0];
196- auto& secondContract = *contractOps[1];
197- 
198- ASSERT_EQ(firstContract.result_token_.size(), 1U);
199- EXPECT_EQ(firstContract.result_token_.front(), firstWriteNormal);
200- EXPECT_TRUE(IsNormalToken(firstContract.result_token_.front()));
201- EXPECT_FALSE(ContainsToken(firstContract.tokens_, firstWriteNormal));
202- 
203- ASSERT_EQ(secondContract.result_token_.size(), 1U);
204- EXPECT_EQ(secondContract.result_token_.front(), secondWriteNormal);
205- EXPECT_TRUE(IsNormalToken(secondContract.result_token_.front()));
206- ASSERT_EQ(secondContract.tokens_.size(), 1U);
207- EXPECT_EQ(secondContract.tokens_.front(), firstWriteNormal);
208- EXPECT_TRUE(IsNormalToken(secondContract.tokens_.front()));
209- 
210- ExpectNoSemanticWriteTokensOnContract(contractOps);
211-}
212- 
213-/*
214- * Write-after-read (WAR) on outCast via TiledAssemble (AddRawOperation path):
215- * assemble.tokens_ carries consumed READ semantic; ExpandFunction should place its NORMAL pair
216- * on contract.tokens_ (input dependency), while this write's NORMAL goes to contract.result_token_.
217- */
218-TEST_F(TestExpandFunctionAssembleTokenPropagation, AssembleWriteAfterReadTokenOnContractInput)
219-{
220- EnableSliceAndContract();
221- 
222- auto function = std::make_shared<Function>(Program::GetInstance(), "AssembleWriteAfterRead",
223- "AssembleWriteAfterRead", nullptr);
224- ASSERT_NE(function, nullptr);
225- 
226- std::vector<int64_t> shape = {kTileDim, kTileDim};
227- auto src = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
228- auto outCast = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
229- 
230- auto assembleAttr = CreateZeroOffsetAssembleAttr();
231- auto& assembleOp = PassOperationUtils::AddOperation(*function, Opcode::OP_ASSEMBLE, {src}, {outCast});
232- assembleOp.SetOpAttribute(assembleAttr);
233- assembleOp.tileShape_.SetVecTile({kTileDim, kTileDim});
234- 
235- function->inCasts_.push_back(src);
236- function->outCasts_.push_back(outCast);
237- function->SetGraphType(GraphType::TENSOR_GRAPH);
238- 
239- ir::VarPtr readNormal;
240- ir::VarPtr writeNormal;
241- InjectReadBeforeWriteAssembleTokens(assembleOp, readNormal, writeNormal);
242- 
243- ExpandFunction expandPass;
244- EXPECT_EQ(expandPass.RunOnFunction(*function), SUCCESS);
245- 
246- auto contractOps = CollectOpsByOpcode(*function, config::GetContractOpcode());
247- ASSERT_EQ(contractOps.size(), 1U);
248- 
249- auto& contract = *contractOps[0];
250- ASSERT_EQ(contract.result_token_.size(), 1U);
251- EXPECT_EQ(contract.result_token_.front(), writeNormal);
252- ASSERT_EQ(contract.tokens_.size(), 1U);
253- EXPECT_EQ(contract.tokens_.front(), readNormal);
254- ExpectNoSemanticWriteTokensOnContract(contractOps);
255-}
256- 
257-/*
258- * Read-after-write (RAW): parent tensor carries readToken_ from InferTokenPass;
259- * AddOperation inserts input slice and propagates read NORMAL to slice.result_token_.
260- */
261-TEST_F(TestExpandFunctionAssembleTokenPropagation, ReadAfterWriteSliceTokenViaAddOperation)
262-{
263- EnableSliceAndContract();
264- 
265- auto function = std::make_shared<Function>(Program::GetInstance(), "ReadAfterWriteSliceToken",
266- "ReadAfterWriteSliceToken", nullptr);
267- ASSERT_NE(function, nullptr);
268- 
269- std::vector<int64_t> shape = {kTileDim, kTileDim};
270- auto parent = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
271- auto output = IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
272- 
273- auto& ctx = IRContext::Get();
274- ir::Span span = ir::Span::Unknown();
275- auto readSemantic = ctx.MakeSemanticToken("out_r", ir::TokenKind::READ, span);
276- auto readNormal = ctx.GetNormalToken(readSemantic);
277- ASSERT_NE(readNormal, nullptr);
278- parent->SetReadToken(readSemantic);
279- 
280- auto inputTile = parent->View(*function, shape, {0, 0});
281- function->AddOperation(Opcode::OP_EXP, {inputTile}, {output});
282- 
283- const auto sliceOpcode = config::GetSliceOpcode();
284- auto sliceOps = CollectOpsByOpcode(*function, sliceOpcode);
285- ASSERT_EQ(sliceOps.size(), 1U);
286- ASSERT_EQ(sliceOps[0]->result_token_.size(), 1U);
287- EXPECT_EQ(sliceOps[0]->result_token_.front(), readNormal);
288- EXPECT_TRUE(IsNormalToken(sliceOps[0]->result_token_.front()));
289-}
290- 
291-} // namespace npu::tile_fwk