Merged
feat(interpreter): Interpreter recently fix #6122
dingbo929Add on Sep 10
feat(interpreter): Interpreter recently fix #6122
Merged
dingbo929Add on Sep 10
Merged fromDeleted :9.2.0intocann/pypto9.2.0
Total: 10 files changed+201-58
@@ -236,6 +236,7 @@ public:
236 const std::string& LogFile();236 const std::string& LogFile();
237 void ResetLog(const std::string& path = "");237 void ResetLog(const std::string& path = "");
238 void SetLogRotationEnabled(bool enabled) { logRotationEnabled_ = enabled; }238 void SetLogRotationEnabled(bool enabled) { logRotationEnabled_ = enabled; }
239+ bool IsLogRotationEnabled() const { return logRotationEnabled_; }
239 240 
240private:241private:
241 GlobalPassConfigs globalPassConfigs_;242 GlobalPassConfigs globalPassConfigs_;
@@ -824,6 +824,14 @@ void ExecuteOpRange(ExecuteOperationContext* ctx)
824 int64_t tileIdxVal = tileIdx.Concrete();824 int64_t tileIdxVal = tileIdx.Concrete();
825 Element tileIdxElem = Element(start.GetDataType(), tileIdxVal);825 Element tileIdxElem = Element(start.GetDataType(), tileIdxVal);
826 curStart = start + step * tileIdxElem;826 curStart = start + step * tileIdxElem;
827+ } else {
828+ std::vector<OpImmediate> dynScalarImmList = {OpImmediate::Specified(tileIdx)};
829+ auto resolved = ctx->opInter->EvaluateOpImmediate(ctx->frame, dynScalarImmList);
830+ if (!resolved.empty()) {
831+ int64_t tileIdxVal = resolved[0];
832+ Element tileIdxElem = Element(start.GetDataType(), tileIdxVal);
833+ curStart = start + step * tileIdxElem;
834+ }
827 }835 }
828 }836 }
829 Element end;837 Element end;
@@ -312,15 +312,16 @@ bool FlowVerifier::VerifyResult(const std::vector<std::shared_ptr<LogicalTensor>
312 INTERPRETER_LOGE_FULL(VerifyResultScene::VERIFY_RESULT_MISMATCH,312 INTERPRETER_LOGE_FULL(VerifyResultScene::VERIFY_RESULT_MISMATCH,
313 "%s Verify for %zu data view list index %zu result FAILED", key.c_str(),313 "%s Verify for %zu data view list index %zu result FAILED", key.c_str(),
314 goldenDataViewList.size(), k);314 goldenDataViewList.size(), k);
315- INTERPRETER_LOGE_FULL(VerifyResultScene::VERIFY_RESULT_MISMATCH, "[VERIFY:FAIL] %s, %s, %s, %s, %s",315+ INTERPRETER_LOGE_TO_FILE(functionInterpreter_->execDumpErrorFile, VerifyResultScene::VERIFY_RESULT_MISMATCH,
316- functionInterpreter_->execDumpPassName.c_str(),316+ "[VERIFY:FAIL] %s, %s, %s, %s, %s", functionInterpreter_->execDumpPassName.c_str(),
317- functionInterpreter_->execDumpFunPath.c_str(),317+ functionInterpreter_->execDumpFunPath.c_str(),
318- functionInterpreter_->GetLoopSymbolString().c_str(),318+ functionInterpreter_->GetLoopSymbolString().c_str(),
319- std::to_string(tensorDatalist[k]->GetRawTensor()->GetRawMagic()).c_str(),319+ std::to_string(tensorDatalist[k]->GetRawTensor()->GetRawMagic()).c_str(),
320- tensorDatalist[k]->GetRawTensor()->GetSymbol().c_str());320+ tensorDatalist[k]->GetRawTensor()->GetSymbol().c_str());
321 std::ostringstream oss;321 std::ostringstream oss;
322 tensorGraphResult.DumpDataDetail(oss);322 tensorGraphResult.DumpDataDetail(oss);
323- INTERPRETER_LOGE_FULL(VerifyResultScene::VERIFY_RESULT_MISMATCH, "%s", oss.str().c_str());323+ INTERPRETER_LOGE_TO_FILE(functionInterpreter_->execDumpErrorFile, VerifyResultScene::VERIFY_RESULT_MISMATCH,
324+ "%s", oss.str().c_str());
324 ProgrameInfo[toIndex(ProgrameInfoCsvHeader::verifyResult)] = "FAIL";325 ProgrameInfo[toIndex(ProgrameInfoCsvHeader::verifyResult)] = "FAIL";
325 result = false;326 result = false;
326 } else {327 } else {
@@ -529,7 +530,8 @@ void FlowVerifier::VerifyTensorGraph(Function* entry,
529 }530 }
530 } catch (std::exception& e) {531 } catch (std::exception& e) {
531 std::string msg = e.what();532 std::string msg = e.what();
532- INTERPRETER_LOGE_FULL(VerifyResultScene::VERIFY_RESULT_MISMATCH, "%s", ParseErrorMsg(msg).c_str());533+ INTERPRETER_LOGE_TO_FILE(functionInterpreter_->execDumpErrorFile, VerifyResultScene::VERIFY_RESULT_MISMATCH,
534+ "%s", ParseErrorMsg(msg).c_str());
533 WriteException();535 WriteException();
534 throw std::runtime_error(e.what());536 throw std::runtime_error(e.what());
535 }537 }
@@ -616,7 +618,8 @@ void FlowVerifier::VerifyPass(Function* func, int passIndex, const std::string&
616 func->GetMagicName().c_str(), passIdentifier.c_str(), passIndex, captureIndex,618 func->GetMagicName().c_str(), passIdentifier.c_str(), passIndex, captureIndex,
617 e.what());619 e.what());
618 std::string msg = e.what();620 std::string msg = e.what();
619- INTERPRETER_LOGE_FULL(VerifyResultScene::VERIFY_RESULT_MISMATCH, "%s", ParseErrorMsg(msg).c_str());621+ INTERPRETER_LOGE_TO_FILE(functionInterpreter_->execDumpErrorFile, VerifyResultScene::VERIFY_RESULT_MISMATCH,
622+ "%s", ParseErrorMsg(msg).c_str());
620 WriteException();623 WriteException();
621 checkResult = false;624 checkResult = false;
622 continue;625 continue;
@@ -13,6 +13,10 @@
13 * \brief Interpreter logging helpers and macros implementation.13 * \brief Interpreter logging helpers and macros implementation.
14 */14 */
15 15 
16+#ifndef _GNU_SOURCE
17+#define _GNU_SOURCE
18+#endif
19+ 
16#include "interface/interpreter/interpreter_log.h"20#include "interface/interpreter/interpreter_log.h"
17 21 
18#include <cinttypes>22#include <cinttypes>
@@ -23,7 +27,6 @@
23#include <algorithm>27#include <algorithm>
24#include <mutex>28#include <mutex>
25#include <string>29#include <string>
26-#include <unordered_map>
27#include <sys/syscall.h>30#include <sys/syscall.h>
28#include <unistd.h>31#include <unistd.h>
29 32 
@@ -90,19 +93,22 @@ int GetGlobalLogThreshold()
90 return threshold;93 return threshold;
91}94}
92 95 
93-const std::unordered_map<LogLevel, int>& CanonicalLevelMap()
94-{
95- static const std::unordered_map<LogLevel, int> kMap = {
96- {LogLevel::kDebug, 0}, {LogLevel::kInfo, 1}, {LogLevel::kWarn, 2}, {LogLevel::kError, 3}, {LogLevel::kEvent, 5},
97- };
98- return kMap;
99-}
100- 
101int ToCanonicalLevel(LogLevel level)96int ToCanonicalLevel(LogLevel level)
102{97{
103- const auto& levelMap = CanonicalLevelMap();98+ switch (level) {
104- const auto it = levelMap.find(level);99+ case LogLevel::kDebug:
105- return it != levelMap.end() ? it->second : kDefaultGlobalLogThreshold;100+ return 0;
101+ case LogLevel::kInfo:
102+ return 1;
103+ case LogLevel::kWarn:
104+ return 2;
105+ case LogLevel::kError:
106+ return 3;
107+ case LogLevel::kEvent:
108+ return 5;
109+ default:
110+ return kDefaultGlobalLogThreshold;
111+ }
106}112}
107 113 
108struct LogContext {114struct LogContext {
@@ -212,7 +218,7 @@ bool FormatLogMessage(const char* fmt, va_list args, LogFormatScratch& scratch)
212 return formattedOk;218 return formattedOk;
213}219}
214 220 
215-void EmitLogLineToOutputs(LogLevel level, const char* msgPtr)221+void WritePrefixedLine(FILE* file, LogLevel level, const char* msgPtr)
216{222{
217 std::time_t now = std::time(nullptr);223 std::time_t now = std::time(nullptr);
218 std::tm localTm{};224 std::tm localTm{};
@@ -221,26 +227,10 @@ void EmitLogLineToOutputs(LogLevel level, const char* msgPtr)
221 (void)std::strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", &localTm);227 (void)std::strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", &localTm);
222 const uint64_t threadId = static_cast<uint64_t>(syscall(SYS_gettid));228 const uint64_t threadId = static_cast<uint64_t>(syscall(SYS_gettid));
223 const char* levelStr = LevelToString(level);229 const char* levelStr = LevelToString(level);
224- 230+ fprintf(file, "[%s][%s][tid:%" PRIu64 "] %s\n", timeBuf, levelStr, threadId, msgPtr);
225- auto& context = GetLogContext();
226- std::lock_guard<std::mutex> lock(context.mutex);
227- if (context.logFile == nullptr) {
228- context.logFile = fopen(context.logFilePath.c_str(), "a");
229- if (context.logFile == nullptr) {
230- return;
231- }
232- }
233- 
234- fprintf(context.logFile, "[%s][%s][tid:%" PRIu64 "] %s\n", timeBuf, levelStr, threadId, msgPtr);
235- fflush(context.logFile);
236- if (context.printToStdout) {
237- fprintf(stdout, "[%s][%s][tid:%" PRIu64 "] %s\n", timeBuf, levelStr, threadId, msgPtr);
238- fflush(stdout);
239- }
240}231}
241 232 
242-void WriteLine(LogLevel level, const char* fmt, va_list args) __attribute__((format(printf, 2, 0)));233+__attribute__((format(printf, 3, 0))) void WriteLineImpl(FILE* file, LogLevel level, const char* fmt, va_list args)
243-void WriteLine(LogLevel level, const char* fmt, va_list args)
244{234{
245 constexpr size_t kStackBufSize = 1024U;235 constexpr size_t kStackBufSize = 1024U;
246 char stackBuf[kStackBufSize];236 char stackBuf[kStackBufSize];
@@ -249,7 +239,24 @@ void WriteLine(LogLevel level, const char* fmt, va_list args)
249 if (!FormatLogMessage(fmt, args, scratch)) {239 if (!FormatLogMessage(fmt, args, scratch)) {
250 return;240 return;
251 }241 }
252- EmitLogLineToOutputs(level, scratch.msg);242+ if (file != nullptr) {
243+ WritePrefixedLine(file, level, scratch.msg);
244+ fflush(file);
245+ return;
246+ }
247+ auto& context = GetLogContext();
248+ std::lock_guard<std::mutex> lock(context.mutex);
249+ if (context.logFile == nullptr) {
250+ context.logFile = fopen(context.logFilePath.c_str(), "a");
251+ if (context.logFile == nullptr) {
252+ return;
253+ }
254+ }
255+ WritePrefixedLine(context.logFile, level, scratch.msg);
256+ fflush(context.logFile);
257+ if (context.printToStdout) {
258+ WritePrefixedLine(stdout, level, scratch.msg);
259+ }
253}260}
254} // namespace261} // namespace
255 262 
@@ -277,7 +284,19 @@ void Log(LogLevel level, const char* fmt, ...)
277 284 
278 va_list args;285 va_list args;
279 va_start(args, fmt);286 va_start(args, fmt);
280- WriteLine(level, fmt, args);287+ WriteLineImpl(nullptr, level, fmt, args);
288+ va_end(args);
289+}
290+ 
291+void LogToFile(FILE* file, LogLevel level, const char* fmt, ...)
292+{
293+ if (file == nullptr || !ShouldWriteLevel(level)) {
294+ return;
295+ }
296+ 
297+ va_list args;
298+ va_start(args, fmt);
299+ WriteLineImpl(file, level, fmt, args);
281 va_end(args);300 va_end(args);
282}301}
283} // namespace npu::tile_fwk::interpreter302} // namespace npu::tile_fwk::interpreter
@@ -16,6 +16,7 @@
16#pragma once16#pragma once
17 17 
18#include <cstdarg>18#include <cstdarg>
19+#include <cstdio>
19#include <cstdint>20#include <cstdint>
20#include <string>21#include <string>
21 22 
@@ -25,6 +26,7 @@ enum class LogLevel : uint8_t { kDebug = 0, kInfo, kWarn, kEvent, kError };
25const std::string& LogFilePath();26const std::string& LogFilePath();
26void SetLogFilePath(const std::string& path);27void SetLogFilePath(const std::string& path);
27void Log(LogLevel level, const char* fmt, ...) __attribute__((format(printf, 2, 3)));28void Log(LogLevel level, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
29+void LogToFile(FILE* file, LogLevel level, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
28} // namespace npu::tile_fwk::interpreter30} // namespace npu::tile_fwk::interpreter
29 31 
30#define INTERPRETER_LOGD(...) npu::tile_fwk::interpreter::Log(npu::tile_fwk::interpreter::LogLevel::kDebug, __VA_ARGS__)32#define INTERPRETER_LOGD(...) npu::tile_fwk::interpreter::Log(npu::tile_fwk::interpreter::LogLevel::kDebug, __VA_ARGS__)
@@ -38,3 +40,8 @@ void Log(LogLevel level, const char* fmt, ...) __attribute__((format(printf, 2,
38 static_cast<uint32_t>(errCode) & 0xFFFFF, #errCode, ##__VA_ARGS__)40 static_cast<uint32_t>(errCode) & 0xFFFFF, #errCode, ##__VA_ARGS__)
39 41 
40#define INTERPRETER_LOGE_FULL(errCode, fmt, ...) INTERPRETER_LOGE(errCode, fmt, ##__VA_ARGS__)42#define INTERPRETER_LOGE_FULL(errCode, fmt, ...) INTERPRETER_LOGE(errCode, fmt, ##__VA_ARGS__)
43+ 
44+#define INTERPRETER_LOGE_TO_FILE(file, errCode, fmt, ...) \
45+ npu::tile_fwk::interpreter::LogToFile(file, npu::tile_fwk::interpreter::LogLevel::kError, \
46+ "ErrCode: F%05X! Enum: %s " fmt, static_cast<uint32_t>(errCode) & 0xFFFFF, \
47+ #errCode, ##__VA_ARGS__)
@@ -186,7 +186,8 @@ void TiledAssembleRecursive(Function& function, const TileShape& tileShape, size
186{186{
187 if (cur == input.tensor.GetShape().size()) {187 if (cur == input.tensor.GetShape().size()) {
188 auto operand = input.tensor.GetStorage();188 auto operand = input.tensor.GetStorage();
189- auto inputTile = operand->View(function, input.tileInfo.shape, input.tileInfo.offset);189+ auto inputTile = std::make_shared<LogicalTensor>(function, operand->Datatype(), input.tileInfo.shape,
190+ operand->Format(), operand->Symbol());
190 191 
191 std::vector<int64_t> fromOffset = input.tileInfo.offset;192 std::vector<int64_t> fromOffset = input.tileInfo.offset;
192 std::vector<SymbolicScalar> fromDynOffset;193 std::vector<SymbolicScalar> fromDynOffset;
@@ -239,7 +240,9 @@ void TiledViewOperationRecursive(Function& function, const TileShape& tileShape,
239 const std::shared_ptr<LogicalTensor>& operand, std::shared_ptr<ViewOpAttribute> attr)240 const std::shared_ptr<LogicalTensor>& operand, std::shared_ptr<ViewOpAttribute> attr)
240{241{
241 if (cur == output.tensor.GetShape().size()) {242 if (cur == output.tensor.GetShape().size()) {
242- auto resultTile = output.tensor.GetStorage()->View(function, output.tileInfo.shape, output.tileInfo.offset);243+ auto resultParent = output.tensor.GetStorage();
244+ auto resultTile = std::make_shared<LogicalTensor>(function, resultParent->Datatype(), output.tileInfo.shape,
245+ resultParent->Format(), resultParent->Symbol());
243 const auto& baseFromOffset = attr->GetFromOffset();246 const auto& baseFromOffset = attr->GetFromOffset();
244 const auto& baseFromDynOffset = attr->GetFromDynOffset();247 const auto& baseFromDynOffset = attr->GetFromDynOffset();
245 size_t offsetSize = std::min(baseFromOffset.size(), output.tileInfo.offset.size());248 size_t offsetSize = std::min(baseFromOffset.size(), output.tileInfo.offset.size());
@@ -255,7 +258,7 @@ void TiledViewOperationRecursive(Function& function, const TileShape& tileShape,
255 newFromDynOffset.push_back(baseFromDynOffset[i] + SymbolicScalar(output.tileInfo.offset[i]));258 newFromDynOffset.push_back(baseFromDynOffset[i] + SymbolicScalar(output.tileInfo.offset[i]));
256 }259 }
257 }260 }
258- auto tileValidShape = GetViewValidShape(operand->GetDynValidShape(), newFromOffset, newFromDynOffset,261+ auto tileValidShape = GetViewValidShape(attr->GetToDynValidShape(), output.tileInfo.offset, {},
259 output.tileInfo.shape);262 output.tileInfo.shape);
260 resultTile->UpdateDynValidShape(tileValidShape);263 resultTile->UpdateDynValidShape(tileValidShape);
261 auto& viewOp = function.AddRawOperation(Opcode::OP_SLICE, {operand}, {resultTile});264 auto& viewOp = function.AddRawOperation(Opcode::OP_SLICE, {operand}, {resultTile});
@@ -265,7 +268,6 @@ void TiledViewOperationRecursive(Function& function, const TileShape& tileShape,
265 }268 }
266 viewOp.SetOpAttribute(viewAttr);269 viewOp.SetOpAttribute(viewAttr);
267 270 
268- auto resultParent = output.tensor.GetStorage();
269 auto& contractOp = function.AddRawOperation(Opcode::OP_CONTRACT, {resultTile}, {resultParent});271 auto& contractOp = function.AddRawOperation(Opcode::OP_CONTRACT, {resultTile}, {resultParent});
270 contractOp.SetAttr("NeedCopy", true);272 contractOp.SetAttr("NeedCopy", true);
271 auto* currentTileOp = ExpandFunction::GetCurrentTileOp();273 auto* currentTileOp = ExpandFunction::GetCurrentTileOp();
@@ -143,7 +143,7 @@ void RecordFunc::EndFunction()
143 recordLoopFunc_.reset();143 recordLoopFunc_.reset();
144 }144 }
145 145 
146- if (IsVerifyEnable()) {146+ if (IsVerifyEnable() && ConfigManager::Instance().IsLogRotationEnabled()) {
147 FE_LOGI("FlowVerify has been enabled.");147 FE_LOGI("FlowVerify has been enabled.");
148 config::SetRunDataOption(KEY_VERIFY_PATH, config::GetAbsoluteTopFolder() + "/verify");148 config::SetRunDataOption(KEY_VERIFY_PATH, config::GetAbsoluteTopFolder() + "/verify");
149 }149 }
@@ -18,6 +18,8 @@
18#include "interface/operation/attribute.h"18#include "interface/operation/attribute.h"
19#include "tensor/symbolic_scalar.h"19#include "tensor/symbolic_scalar.h"
20 20 
21+#include <string>
22+ 
21namespace npu::tile_fwk {23namespace npu::tile_fwk {
22namespace {24namespace {
23ScalarImmediateType EvaluateSymbolicCallRuntimeGetInputShapeDimSize(EvaluateSymbol* evaluateSymbol,25ScalarImmediateType EvaluateSymbolicCallRuntimeGetInputShapeDimSize(EvaluateSymbol* evaluateSymbol,
@@ -63,14 +65,21 @@ ScalarImmediateType EvaluateSymbolicCallRuntimeGetTensorDataInt32(EvaluateSymbol
63{65{
64 UNUSED(offsetList);66 UNUSED(offsetList);
65 auto inoutDataPair = evaluateSymbol->GetInoutDataPair();67 auto inoutDataPair = evaluateSymbol->GetInoutDataPair();
66- std::shared_ptr<LogicalTensorData> view;68+ FE_ASSERT(inoutDataPair != nullptr) << "GetTensorData eval failed: current frame has no FunctionIODataPair, ioType="
67- if (ioType == GET_TENSOR_DATA_OPERAND_IOTYPE_INCAST) {69+ << ioType << ", ioTypeIndex=" << ioTypeIndex;
68- view = inoutDataPair->GetIncastDataViewList()[ioTypeIndex];70+ FE_ASSERT(ioType == GET_TENSOR_DATA_OPERAND_IOTYPE_INCAST || ioType == GET_TENSOR_DATA_OPERAND_IOTYPE_OUTCAST)
69- } else if (ioType == GET_TENSOR_DATA_OPERAND_IOTYPE_OUTCAST) {71+ << "GetTensorData eval failed: invalid ioType=" << ioType << ", ioTypeIndex=" << ioTypeIndex;
70- view = inoutDataPair->GetOutcastDataViewList()[ioTypeIndex];72+ const auto& viewList = (ioType == GET_TENSOR_DATA_OPERAND_IOTYPE_INCAST) ? inoutDataPair->GetIncastDataViewList() :
71- } else {73+ inoutDataPair->GetOutcastDataViewList();
72- FE_ASSERT(false);74+ FE_ASSERT(ioTypeIndex >= 0 && static_cast<size_t>(ioTypeIndex) < viewList.size())
73- }75+ << "GetTensorData eval failed: " << (ioType == GET_TENSOR_DATA_OPERAND_IOTYPE_INCAST ? "incast" : "outcast")
76+ << " index " << ioTypeIndex << " out of range (list size=" << viewList.size()
77+ << "); the (ioType, ioTypeIndex) of RUNTIME_GetTensorDataInt32 symbol is not "
78+ "remapped after graph transform (op moved to another function)";
79+ std::shared_ptr<LogicalTensorData> view = viewList[ioTypeIndex];
80+ FE_ASSERT(view != nullptr) << "GetTensorData eval failed: "
81+ << (ioType == GET_TENSOR_DATA_OPERAND_IOTYPE_INCAST ? "incast" : "outcast") << " index "
82+ << ioTypeIndex << " resolved a null data view";
74 auto elt = view->GetElement(0);83 auto elt = view->GetElement(0);
75 auto ret = static_cast<ScalarImmediateType>(elt.Cast<int64_t>());84 auto ret = static_cast<ScalarImmediateType>(elt.Cast<int64_t>());
76 return ret;85 return ret;
@@ -2585,11 +2585,12 @@ TEST_F(DynamicOpsTest, Range)
2585 std::string logOutput = CaptureLogFileAndEcho([]() {2585 std::string logOutput = CaptureLogFileAndEcho([]() {
2586 config::SetVerifyOption(KEY_ENABLE_PASS_VERIFY, true);2586 config::SetVerifyOption(KEY_ENABLE_PASS_VERIFY, true);
2587 config::SetVerifyOption(KEY_PASS_VERIFY_SAVE_TENSOR, true);2587 config::SetVerifyOption(KEY_PASS_VERIFY_SAVE_TENSOR, true);
2588+ TileShape::Current().SetVecTile(2);
2588 2589 
2589- int64_t size = 5;
2590 Element start(DT_INT32, 1);2590 Element start(DT_INT32, 1);
2591- Element end(DT_INT32, 10);2591+ Element end(DT_INT32, 99);
2592 Element step(DT_INT32, 2);2592 Element step(DT_INT32, 2);
2593+ int64_t size = 49;
2593 2594 
2594 Tensor out(DT_INT32, {size}, "out");2595 Tensor out(DT_INT32, {size}, "out");
2595 ProgramData::GetInstance().AppendInputs({});2596 ProgramData::GetInstance().AppendInputs({});
@@ -2597,7 +2598,10 @@ TEST_F(DynamicOpsTest, Range)
2597 RawTensorData::CreateConstantTensor<int32_t>(out, 0),2598 RawTensorData::CreateConstantTensor<int32_t>(out, 0),
2598 });2599 });
2599 2600 
2600- std::vector<int32_t> expected_data = {1, 3, 5, 7, 9};2601+ std::vector<int32_t> expected_data(size);
2602+ for (int64_t i = 0; i < size; ++i) {
2603+ expected_data[i] = static_cast<int32_t>(1 + i * 2);
2604+ }
2601 ProgramData::GetInstance().AppendGoldens({2605 ProgramData::GetInstance().AppendGoldens({
2602 RawTensorData::CreateTensor<int32_t>(out, expected_data),2606 RawTensorData::CreateTensor<int32_t>(out, expected_data),
2603 });2607 });
@@ -147,6 +147,23 @@ bool HasNormalTokenNamed(const std::vector<ir::VarPtr>& tokens, const std::strin
147 return false;147 return false;
148}148}
149 149 
150+void ExpectSliceContractHaveDistinctRaws(Function& function)
151+{
152+ for (auto& op : function.Operations(false)) {
153+ if (op.GetOpcode() != Opcode::OP_SLICE && op.GetOpcode() != Opcode::OP_CONTRACT) {
154+ continue;
155+ }
156+ EXPECT_FALSE(op.GetIOperands().empty());
157+ EXPECT_FALSE(op.GetOOperands().empty());
158+ if (op.GetIOperands().empty() || op.GetOOperands().empty() || op.GetIOperands()[0] == nullptr ||
159+ op.GetOOperands()[0] == nullptr) {
160+ continue;
161+ }
162+ EXPECT_NE(op.GetIOperands()[0]->GetRawTensor(), op.GetOOperands()[0]->GetRawTensor())
163+ << op.GetOpcodeStr() << "[" << op.GetOpMagic() << "] input/output share the same RawTensor";
164+ }
165+}
166+ 
150} // namespace167} // namespace
151 168 
152struct ScopeCfg {169struct ScopeCfg {
@@ -346,6 +363,7 @@ TEST_F(TestExpandFunctionPass, ExpandFunctionUTest2)
346 EXPECT_EQ(slice_num, kNumOne);363 EXPECT_EQ(slice_num, kNumOne);
347 EXPECT_EQ(contract_num, kNumOne);364 EXPECT_EQ(contract_num, kNumOne);
348 EXPECT_EQ(nop_num, kNumOne);365 EXPECT_EQ(nop_num, kNumOne);
366+ ExpectSliceContractHaveDistinctRaws(*currFunctionPtr);
349}367}
350 368 
351/*369/*
@@ -506,6 +524,7 @@ TEST_F(TestExpandFunctionPass, AssembleReshapeToOutcastWithTokenShouldExpand)
506 EXPECT_EQ(sliceNum, kNumOne);524 EXPECT_EQ(sliceNum, kNumOne);
507 EXPECT_EQ(contractNum, kNumOne);525 EXPECT_EQ(contractNum, kNumOne);
508 EXPECT_TRUE(contractHasWrite);526 EXPECT_TRUE(contractHasWrite);
527+ ExpectSliceContractHaveDistinctRaws(*currFunctionPtr);
509}528}
510 529 
511/*530/*
@@ -555,6 +574,7 @@ TEST_F(TestExpandFunctionPass, AssembleReshapeToNonOutcastShouldExpand)
555 EXPECT_EQ(assembleNum, kNumZero);574 EXPECT_EQ(assembleNum, kNumZero);
556 EXPECT_EQ(sliceNum, kNumOne);575 EXPECT_EQ(sliceNum, kNumOne);
557 EXPECT_EQ(contractNum, kNumOne);576 EXPECT_EQ(contractNum, kNumOne);
577+ ExpectSliceContractHaveDistinctRaws(*currFunctionPtr);
558}578}
559 579 
560/*580/*
@@ -607,6 +627,7 @@ TEST_F(TestExpandFunctionPass, AssembleReshapeToOutcastWithDeletedReshapeShouldE
607 EXPECT_EQ(assembleNum, kNumZero);627 EXPECT_EQ(assembleNum, kNumZero);
608 EXPECT_EQ(sliceNum, kNumOne);628 EXPECT_EQ(sliceNum, kNumOne);
609 EXPECT_EQ(contractNum, kNumOne);629 EXPECT_EQ(contractNum, kNumOne);
630+ ExpectSliceContractHaveDistinctRaws(*currFunctionPtr);
610}631}
611 632 
612/*633/*
@@ -1434,5 +1455,74 @@ TEST_F(TestExpandFunctionPass, AssembleWriteGoesToContractAndConsumedOnNextAssem
1434 EXPECT_EQ(contractConsumingFirstWrite, 1);1455 EXPECT_EQ(contractConsumingFirstWrite, 1);
1435}1456}
1436 1457 
1458+// VIEW toDynValidShape is tighter than input-clip. Expanded SLICEs must inherit
1459+// the per-tile clip of that VIEW attr, not GetViewValidShape(input, fromOffset).
1460+TEST_F(TestExpandFunctionPass, ViewExpandSlicesToDynValidShape)
1461+{
1462+ auto currFunctionPtr = std::make_shared<Function>(Program::GetInstance(), "TestExpandViewValidShape",
1463+ "TestExpandViewValidShape", nullptr);
1464+ ASSERT_NE(currFunctionPtr, nullptr);
1465+ 
1466+ std::vector<int64_t> shape = {kNumExpSix, kNumExpSix};
1467+ std::vector<int64_t> tileShape = {kNumExpFive, kNumExpSix};
1468+ auto inCast = npu::tile_fwk::IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1469+ auto viewOut = npu::tile_fwk::IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1470+ auto expOut = npu::tile_fwk::IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1471+ auto outCast = npu::tile_fwk::IRBuilder().CreateTensorVar(DT_FP32, shape, CreateTestConstIntVector(shape));
1472+ 
1473+ auto tighterValid = SymbolicScalar::FromConcrete({10, kNumExpSix});
1474+ viewOut->UpdateDynValidShape(tighterValid);
1475+ 
1476+ auto& viewOp = PassOperationUtils::AddOperation(*currFunctionPtr, Opcode::OP_VIEW, {inCast}, {viewOut});
1477+ auto& expOp = PassOperationUtils::AddOperation(*currFunctionPtr, Opcode::OP_EXP, {viewOut}, {expOut});
1478+ auto& assembleOp = PassOperationUtils::AddOperation(*currFunctionPtr, Opcode::OP_ASSEMBLE, {expOut}, {outCast});
1479+ 
1480+ std::vector<int64_t> offsets = {0, 0};
1481+ viewOp.SetOpAttribute(
1482+ std::make_shared<ViewOpAttribute>(offsets, SymbolicScalar::FromConcrete(offsets), tighterValid));
1483+ assembleOp.SetOpAttribute(CreateAssembleOpAttr());
1484+ viewOp.tileShape_.SetVecTile(tileShape);
1485+ expOp.tileShape_.SetVecTile(tileShape);
1486+ assembleOp.tileShape_.SetVecTile(tileShape);
1487+ 
1488+ currFunctionPtr->inCasts_.push_back(inCast);
1489+ currFunctionPtr->outCasts_.push_back(outCast);
1490+ currFunctionPtr->SetGraphType(GraphType::TENSOR_GRAPH);
1491+ 
1492+ ExpandFunction expand;
1493+ EXPECT_EQ(expand.RunOnFunction(*currFunctionPtr), SUCCESS);
1494+ 
1495+ auto expectFirst = GetViewValidShape(tighterValid, {0, 0}, {}, tileShape);
1496+ auto expectSecond = GetViewValidShape(tighterValid, {kNumExpFive, 0}, {}, tileShape);
1497+ bool sawFirst = false;
1498+ bool sawSecond = false;
1499+ for (auto& op : currFunctionPtr->Operations(false)) {
1500+ if (op.GetOpcode() != Opcode::OP_SLICE || op.GetIOperands().empty() || op.GetIOperands()[0] != inCast) {
1501+ continue;
1502+ }
1503+ auto sliceAttr = std::dynamic_pointer_cast<ViewOpAttribute>(op.GetOpAttribute());
1504+ ASSERT_NE(sliceAttr, nullptr);
1505+ ASSERT_FALSE(op.GetOOperands().empty());
1506+ const auto& fromOffset = sliceAttr->GetFromOffset();
1507+ ASSERT_GE(fromOffset.size(), 1u);
1508+ const auto& expect = (fromOffset[0] == 0) ? expectFirst : expectSecond;
1509+ if (fromOffset[0] == 0) {
1510+ sawFirst = true;
1511+ } else if (fromOffset[0] == kNumExpFive) {
1512+ sawSecond = true;
1513+ } else {
1514+ continue;
1515+ }
1516+ ASSERT_EQ(sliceAttr->GetToDynValidShape().size(), expect.size());
1517+ ASSERT_EQ(op.GetOOperands()[0]->GetDynValidShape().size(), expect.size());
1518+ for (size_t i = 0; i < expect.size(); ++i) {
1519+ EXPECT_EQ(sliceAttr->GetToDynValidShape()[i].Dump(), expect[i].Dump());
1520+ EXPECT_EQ(op.GetOOperands()[0]->GetDynValidShape()[i].Dump(), expect[i].Dump());
1521+ }
1522+ }
1523+ EXPECT_TRUE(sawFirst);
1524+ EXPECT_TRUE(sawSecond);
1525+}
1526+ 
1437} // namespace tile_fwk1527} // namespace tile_fwk
1438} // namespace npu1528} // namespace npu