Merged
perf(pass): Optimize DuplicateOp and AssignMemoryType for large graphs #4959
CatherieAdd on Jul 20
perf(pass): Optimize DuplicateOp and AssignMemoryType for large graphs #4959
Merged
Merged fromCatherie/pyptomy_dup_op_optimizeintocann/pyptomaster
Total: 7 files changed+126-47
| @@ -83,6 +83,23 @@ def get_logger() -> logging.Logger: | |||
| 83 | return _logger | 83 | return _logger |
| 84 | 84 | ||
| 85 | 85 | ||
| 86 | +def fmt_dur(seconds: float) -> str: | ||
| 87 | + """Format duration with adaptive unit for readability. | ||
| 88 | + | ||
| 89 | + Avoids misleading '0.000' display for sub-millisecond passes. | ||
| 90 | + | ||
| 91 | + < 1ms -> 'NNNus' (e.g. 0.000018s -> '18us') | ||
| 92 | + < 1s -> 'N.NNms' (e.g. 0.000277s -> '0.28ms') | ||
| 93 | + >= 1s -> 'NN.NNNs' (e.g. 77.189s -> '77.189s') | ||
| 94 | + """ | ||
| 95 | + if seconds < 0.001: | ||
| 96 | + return f"{seconds * 1_000_000:.0f}us" | ||
| 97 | + elif seconds < 1.0: | ||
| 98 | + return f"{seconds * 1000:.2f}ms" | ||
| 99 | + else: | ||
| 100 | + return f"{seconds:.3f}s" | ||
| 101 | + | ||
| 102 | + | ||
| 86 | @dataclass | 103 | @dataclass |
| 87 | class PassPerfData: | 104 | class PassPerfData: |
| 88 | """Pass performance data with execution count support""" | 105 | """Pass performance data with execution count support""" |
| @@ -326,14 +343,14 @@ class PassPerfAnalyzer: | |||
| 326 | has_comparison = any(d.durations_before for d in sorted_data) | 343 | has_comparison = any(d.durations_before for d in sorted_data) |
| 327 | 344 | ||
| 328 | if has_comparison: | 345 | if has_comparison: |
| 329 | - header = (f"{'Pass Name':<30} | {'Count':<5} | {'Avg(s)':<8} | " | 346 | + header = (f"{'Pass Name':<30} | {'Count':<5} | {'Avg':<9} | " |
| 330 | - f"{'Target(s)':<9} | {'Total(s)':<9} | " | 347 | + f"{'Target(s)':<9} | {'Total':<9} | " |
| 331 | f"{'Time%':<6} | {'Improve%':<8} | {'Status'}") | 348 | f"{'Time%':<6} | {'Improve%':<8} | {'Status'}") |
| 332 | lg.info(header) | 349 | lg.info(header) |
| 333 | lg.info("-" * 160) | 350 | lg.info("-" * 160) |
| 334 | else: | 351 | else: |
| 335 | - header = (f"{'Pass Name':<30} | {'Count':<5} | {'Avg(s)':<8} | " | 352 | + header = (f"{'Pass Name':<30} | {'Count':<5} | {'Avg':<9} | " |
| 336 | - f"{'Target(s)':<9} | {'Total(s)':<9} | " | 353 | + f"{'Target(s)':<9} | {'Total':<9} | " |
| 337 | f"{'Time%':<6} | {'Status'}") | 354 | f"{'Time%':<6} | {'Status'}") |
| 338 | lg.info(header) | 355 | lg.info(header) |
| 339 | lg.info("-" * 130) | 356 | lg.info("-" * 130) |
| @@ -344,13 +361,13 @@ class PassPerfAnalyzer: | |||
| 344 | 361 | ||
| 345 | if has_comparison and data.durations_before: | 362 | if has_comparison and data.durations_before: |
| 346 | improve = f"{data.improvement_percent:+.1f}%" | 363 | improve = f"{data.improvement_percent:+.1f}%" |
| 347 | - row = (f"{data.name:<30} | {data.count:<5} | {data.avg_duration_s:<8.3f} | " | 364 | + row = (f"{data.name:<30} | {data.count:<5} | {fmt_dur(data.avg_duration_s):<9} | " |
| 348 | - f"{dynamic_threshold:<9.2f} | {data.duration_s:<9.3f} | " | 365 | + f"{dynamic_threshold:<9.2f} | {fmt_dur(data.duration_s):<9} | " |
| 349 | f"{time_percent:<6} | {improve:<8} | {status}") | 366 | f"{time_percent:<6} | {improve:<8} | {status}") |
| 350 | lg.info(row) | 367 | lg.info(row) |
| 351 | else: | 368 | else: |
| 352 | - row = (f"{data.name:<30} | {data.count:<5} | {data.avg_duration_s:<8.3f} | " | 369 | + row = (f"{data.name:<30} | {data.count:<5} | {fmt_dur(data.avg_duration_s):<9} | " |
| 353 | - f"{dynamic_threshold:<9.2f} | {data.duration_s:<9.3f} | " | 370 | + f"{dynamic_threshold:<9.2f} | {fmt_dur(data.duration_s):<9} | " |
| 354 | f"{time_percent:<6} | {status}") | 371 | f"{time_percent:<6} | {status}") |
| 355 | lg.info(row) | 372 | lg.info(row) |
| 356 | 373 | ||
| @@ -366,7 +383,7 @@ class PassPerfAnalyzer: | |||
| 366 | lg.info("=" * 140) | 383 | lg.info("=" * 140) |
| 367 | lg.info("Passes Exceeding Dynamic Threshold:") | 384 | lg.info("Passes Exceeding Dynamic Threshold:") |
| 368 | for i, (data, threshold) in enumerate(exceeding, 1): | 385 | for i, (data, threshold) in enumerate(exceeding, 1): |
| 369 | - msg = (f" {i}. {data.name}: avg {data.avg_duration_s:.1f}s > " | 386 | + msg = (f" {i}. {data.name}: avg {fmt_dur(data.avg_duration_s)} > " |
| 370 | f"target {threshold:.1f}s (ops: {data.ops}, count: {data.count}, " | 387 | f"target {threshold:.1f}s (ops: {data.ops}, count: {data.count}, " |
| 371 | f"time%: {data.time_percent:.1f}%)") | 388 | f"time%: {data.time_percent:.1f}%)") |
| 372 | lg.info(msg) | 389 | lg.info(msg) |
| @@ -8,13 +8,13 @@ | |||
| 8 | # See LICENSE in the root of the software repository for the full text of the License. | 8 | # See LICENSE in the root of the software repository for the full text of the License. |
| 9 | # ----------------------------------------------------------------------------------------------------------- | 9 | # ----------------------------------------------------------------------------------------------------------- |
| 10 | # ============================================================================= | 10 | # ============================================================================= |
| 11 | -# run_with_timeout.sh - 带超时控制的命令执行脚本 | 11 | +# run_with_timeout.sh - 带超时控制的命令执行脚本(进程组信号传播版) |
| 12 | # ============================================================================= | 12 | # ============================================================================= |
| 13 | # 功能: | 13 | # 功能: |
| 14 | -# 1. 执行指定命令 | 14 | +# 1. 在独立进程组中执行命令(set -m 作业控制) |
| 15 | # 2. 监控执行时间 | 15 | # 2. 监控执行时间 |
| 16 | -# 3. 超时后发送 SIGINT (Ctrl+C) | 16 | +# 3. 超时后向整个进程组发送信号(Python 父进程 + C++ 子进程均能收到) |
| 17 | -# 4. 等待进程优雅退出 | 17 | +# 4. 三级信号升级:SIGINT(10s) -> SIGTERM(5s) -> SIGKILL |
| 18 | # 5. 返回合适的退出码 | 18 | # 5. 返回合适的退出码 |
| 19 | # | 19 | # |
| 20 | # 参数: | 20 | # 参数: |
| @@ -28,56 +28,89 @@ | |||
| 28 | # 使用示例: | 28 | # 使用示例: |
| 29 | # bash run_with_timeout.sh 300 python3 test.py | 29 | # bash run_with_timeout.sh 300 python3 test.py |
| 30 | # bash run_with_timeout.sh 600 python3 test.py --run-mode npu | 30 | # bash run_with_timeout.sh 600 python3 test.py --run-mode npu |
| 31 | +# | ||
| 32 | +# === 信号传播原理 === | ||
| 33 | +# 原方案仅 kill -INT $CMD_PID,信号只发给 Python 父进程, | ||
| 34 | +# C++ 编译子进程(fork 出来的)收不到信号继续运行。 | ||
| 35 | +# | ||
| 36 | +# 本方案启用 set -m(作业控制),使后台命令运行在独立进程组中, | ||
| 37 | +# 进程组 ID (PGID) == 命令 PID。通过 kill -INT -$PGID 向整个进程组 | ||
| 38 | +# 发送信号,Python 父进程和所有 C++ 子进程都能收到。 | ||
| 31 | # ============================================================================= | 39 | # ============================================================================= |
| 32 | 40 | ||
| 33 | -set -e | 41 | +# 启用作业控制:后台命令自动获得独立进程组,PGID == PID |
| 42 | +# 这是信号能传播到子进程的关键 | ||
| 43 | +set -m | ||
| 34 | 44 | ||
| 35 | # 参数处理 | 45 | # 参数处理 |
| 36 | TIMEOUT_SECONDS=${1:-300} # 默认5分钟 | 46 | TIMEOUT_SECONDS=${1:-300} # 默认5分钟 |
| 37 | -SCRIPT_CMD="${@:2}" # 要执行的命令 | 47 | +shift # 移除超时参数,剩余为命令 |
| 48 | +SCRIPT_CMD=("$@") # 保存命令数组 | ||
| 38 | 49 | ||
| 39 | echo "=========================================" | 50 | echo "=========================================" |
| 40 | -echo "执行命令: $SCRIPT_CMD" | 51 | +echo "执行命令: ${SCRIPT_CMD[*]}" |
| 41 | echo "超时设置: ${TIMEOUT_SECONDS} 秒" | 52 | echo "超时设置: ${TIMEOUT_SECONDS} 秒" |
| 53 | +echo "进程组模式: 已启用 (set -m)" | ||
| 42 | echo "=========================================" | 54 | echo "=========================================" |
| 43 | 55 | ||
| 44 | -# 后台执行命令 | 56 | +# 在后台执行命令(作业控制确保它获得独立进程组) |
| 45 | -$SCRIPT_CMD & | 57 | +"${SCRIPT_CMD[@]}" & |
| 46 | CMD_PID=$! | 58 | CMD_PID=$! |
| 59 | +# set -m 下,后台作业的 PID == 进程组 ID (PGID) | ||
| 60 | +PGID=$CMD_PID | ||
| 47 | 61 | ||
| 48 | -# 监控进程(后台) | 62 | +# 监控进程(后台子 shell) |
| 49 | ( | 63 | ( |
| 50 | - sleep $TIMEOUT_SECONDS | 64 | + sleep "$TIMEOUT_SECONDS" |
| 51 | - if ps -p $CMD_PID > /dev/null 2>&1; then | 65 | + if kill -0 "$CMD_PID" 2>/dev/null; then |
| 52 | echo "" | 66 | echo "" |
| 53 | echo "⚠️ 算子执行已超过 ${TIMEOUT_SECONDS} 秒" | 67 | echo "⚠️ 算子执行已超过 ${TIMEOUT_SECONDS} 秒" |
| 54 | - echo "⚠️ 自动发送 Ctrl+C 信号中断执行..." | 68 | + echo "⚠️ 向进程组 (PGID=$PGID) 发送 SIGINT 信号..." |
| 55 | echo "✓ Pass 编译日志已保存,将继续性能分析" | 69 | echo "✓ Pass 编译日志已保存,将继续性能分析" |
| 56 | - kill -INT $CMD_PID 2>/dev/null | 70 | + |
| 57 | - wait $CMD_PID 2>/dev/null | 71 | + # 第1级:SIGINT 到整个进程组(优雅退出,Ctrl+C 等效) |
| 72 | + kill -INT -"$PGID" 2>/dev/null | ||
| 73 | + | ||
| 74 | + # 等待 10 秒让进程优雅退出(刷新日志、释放资源) | ||
| 75 | + sleep 10 | ||
| 76 | + | ||
| 77 | + # 第2级:如果仍在运行,升级为 SIGTERM | ||
| 78 | + if kill -0 "$CMD_PID" 2>/dev/null; then | ||
| 79 | + echo "⚠️ SIGINT 后进程仍在运行,升级为 SIGTERM..." | ||
| 80 | + kill -TERM -"$PGID" 2>/dev/null | ||
| 81 | + sleep 5 | ||
| 82 | + fi | ||
| 83 | + | ||
| 84 | + # 第3级:最终手段 SIGKILL(不可被忽略) | ||
| 85 | + if kill -0 "$CMD_PID" 2>/dev/null; then | ||
| 86 | + echo "⚠️ SIGTERM 后进程仍在运行,升级为 SIGKILL..." | ||
| 87 | + kill -KILL -"$PGID" 2>/dev/null | ||
| 88 | + fi | ||
| 89 | + | ||
| 90 | + wait "$CMD_PID" 2>/dev/null | ||
| 58 | fi | 91 | fi |
| 59 | ) & | 92 | ) & |
| 60 | TIMEOUT_PID=$! | 93 | TIMEOUT_PID=$! |
| 61 | 94 | ||
| 62 | # 等待命令完成 | 95 | # 等待命令完成 |
| 63 | -wait $CMD_PID | 96 | +wait "$CMD_PID" 2>/dev/null |
| 64 | EXIT_CODE=$? | 97 | EXIT_CODE=$? |
| 65 | 98 | ||
| 66 | -# 清理监控进程 | 99 | +# 清理监控进程(如果命令正常完成,监控进程还在 sleep) |
| 67 | -kill $TIMEOUT_PID 2>/dev/null | 100 | +kill "$TIMEOUT_PID" 2>/dev/null |
| 68 | -wait $TIMEOUT_PID 2>/dev/null | 101 | +wait "$TIMEOUT_PID" 2>/dev/null |
| 69 | 102 | ||
| 70 | # 处理退出码 | 103 | # 处理退出码 |
| 71 | -if [ $EXIT_CODE -eq 130 ] || [ $EXIT_CODE -eq 137 ]; then | 104 | +# 130 = SIGINT (128+2), 137 = SIGKILL (128+9), 143 = SIGTERM (128+15) |
| 72 | - # 130 = SIGINT (Ctrl+C), 137 = SIGKILL | 105 | +if [ "$EXIT_CODE" -eq 130 ] || [ "$EXIT_CODE" -eq 137 ] || [ "$EXIT_CODE" -eq 143 ]; then |
| 73 | echo "" | 106 | echo "" |
| 74 | echo "✓ 算子执行被中断(退出码: $EXIT_CODE)" | 107 | echo "✓ 算子执行被中断(退出码: $EXIT_CODE)" |
| 75 | echo "✓ Pass 编译日志已保存,可以继续性能分析" | 108 | echo "✓ Pass 编译日志已保存,可以继续性能分析" |
| 76 | exit 0 # 正常退出,允许继续后续步骤 | 109 | exit 0 # 正常退出,允许继续后续步骤 |
| 77 | -elif [ $EXIT_CODE -ne 0 ]; then | 110 | +elif [ "$EXIT_CODE" -ne 0 ]; then |
| 78 | echo "" | 111 | echo "" |
| 79 | echo "✗ 算子执行失败,退出码: $EXIT_CODE" | 112 | echo "✗ 算子执行失败,退出码: $EXIT_CODE" |
| 80 | - exit $EXIT_CODE | 113 | + exit "$EXIT_CODE" |
| 81 | else | 114 | else |
| 82 | echo "" | 115 | echo "" |
| 83 | echo "✓ 算子执行完成" | 116 | echo "✓ 算子执行完成" |
| @@ -44,6 +44,7 @@ namespace npu::tile_fwk { | |||
| 44 | Status AssignMemoryType::RunOnFunction(Function& function) | 44 | Status AssignMemoryType::RunOnFunction(Function& function) |
| 45 | { | 45 | { |
| 46 | APASS_LOG_INFO_F(Elements::Function, "===> Start AssignMemoryType."); | 46 | APASS_LOG_INFO_F(Elements::Function, "===> Start AssignMemoryType."); |
| 47 | + function.SortOperations(SortOperationsMode::LIGHTWEIGHT); | ||
| 47 | RETURN_IF_NOT_SUCCESS(AssignConfirmedMemoryTypes(function)); | 48 | RETURN_IF_NOT_SUCCESS(AssignConfirmedMemoryTypes(function)); |
| 48 | RETURN_IF_NOT_SUCCESS(InferUncertainMemoryTypes(function)); | 49 | RETURN_IF_NOT_SUCCESS(InferUncertainMemoryTypes(function)); |
| 49 | RETURN_IF_NOT_SUCCESS(ResolveMemoryUnknowns(function)); | 50 | RETURN_IF_NOT_SUCCESS(ResolveMemoryUnknowns(function)); |
| @@ -1888,8 +1889,9 @@ Status AssignMemoryType::InsertConvertOpsAndInferShape(Function& function) | |||
| 1888 | existingOps.insert(&op); | 1889 | existingOps.insert(&op); |
| 1889 | } | 1890 | } |
| 1890 | RETURN_IF_NOT_SUCCESS(inserter.DoInsertion(function)); | 1891 | RETURN_IF_NOT_SUCCESS(inserter.DoInsertion(function)); |
| 1892 | + function.SortOperations(SortOperationsMode::LIGHTWEIGHT); | ||
| 1891 | std::vector<Operation*> addedOps; | 1893 | std::vector<Operation*> addedOps; |
| 1892 | - for (auto& op : function.Operations()) { | 1894 | + for (auto& op : function.Operations(false)) { |
| 1893 | if (existingOps.find(&op) == existingOps.end()) { | 1895 | if (existingOps.find(&op) == existingOps.end()) { |
| 1894 | addedOps.push_back(&op); | 1896 | addedOps.push_back(&op); |
| 1895 | } | 1897 | } |
| @@ -235,7 +235,7 @@ Status ConvertInserter::RecordConflict(Function& function) | |||
| 235 | { | 235 | { |
| 236 | oldRawToNewRaw.clear(); | 236 | oldRawToNewRaw.clear(); |
| 237 | converts.clear(); | 237 | converts.clear(); |
| 238 | - std::vector<int> visitedTensor; | 238 | + std::unordered_set<int> visitedTensor; |
| 239 | for (const auto& op : function.Operations()) { | 239 | for (const auto& op : function.Operations()) { |
| 240 | for (auto& iOperand : op.iOperand) { | 240 | for (auto& iOperand : op.iOperand) { |
| 241 | if (iOperand->GetProducers().size() >= 1) { | 241 | if (iOperand->GetProducers().size() >= 1) { |
| @@ -273,7 +273,7 @@ Status ConvertInserter::RecordConflict(Function& function) | |||
| 273 | InsertConvertOpForEachConsumer(function, op, oOperand, consumers, paths); | 273 | InsertConvertOpForEachConsumer(function, op, oOperand, consumers, paths); |
| 274 | 274 | ||
| 275 | // step6:标记已处理 | 275 | // step6:标记已处理 |
| 276 | - visitedTensor.push_back(oOperand->magic); | 276 | + visitedTensor.insert(oOperand->magic); |
| 277 | } | 277 | } |
| 278 | } | 278 | } |
| 279 | } | 279 | } |
| @@ -456,10 +456,10 @@ Status ConvertInserter::ConstructPath(MemoryType from, MemoryType to, std::vecto | |||
| 456 | } | 456 | } |
| 457 | 457 | ||
| 458 | bool ConvertInserter::SkipOperand(const std::shared_ptr<LogicalTensor>& oOperand, | 458 | bool ConvertInserter::SkipOperand(const std::shared_ptr<LogicalTensor>& oOperand, |
| 459 | - const std::vector<int>& visitedTensor) const | 459 | + const std::unordered_set<int>& visitedTensor) const |
| 460 | { | 460 | { |
| 461 | return ((conflictMap.find(oOperand->magic) == conflictMap.end()) || | 461 | return ((conflictMap.find(oOperand->magic) == conflictMap.end()) || |
| 462 | - (std::find(visitedTensor.begin(), visitedTensor.end(), oOperand->magic) != visitedTensor.end())); | 462 | + (visitedTensor.find(oOperand->magic) != visitedTensor.end())); |
| 463 | } | 463 | } |
| 464 | 464 | ||
| 465 | bool ConvertInserter::isAllProducerAssemble(const std::shared_ptr<LogicalTensor>& oOperand) const | 465 | bool ConvertInserter::isAllProducerAssemble(const std::shared_ptr<LogicalTensor>& oOperand) const |
| @@ -593,7 +593,7 @@ Status ConvertInserter::DoInsertion(Function& function) | |||
| 593 | return status; | 593 | return status; |
| 594 | } | 594 | } |
| 595 | InsertConvertOps(function); | 595 | InsertConvertOps(function); |
| 596 | - APASS_LOG_INFO_F(Elements::Function, "After Insert Convert, total op Num: %zu.", function.Operations().size()); | 596 | + APASS_LOG_INFO_F(Elements::Function, "After Insert Convert, total op Num: %zu.", function.GetOperationSize()); |
| 597 | return SUCCESS; | 597 | return SUCCESS; |
| 598 | } | 598 | } |
| 599 | } // namespace tile_fwk | 599 | } // namespace tile_fwk |
| @@ -17,6 +17,7 @@ | |||
| 17 | #define PASS_CONVERT_OP_INSERTER_H_ | 17 | #define PASS_CONVERT_OP_INSERTER_H_ |
| 18 | 18 | ||
| 19 | #include <unordered_map> | 19 | #include <unordered_map> |
| 20 | +#include <unordered_set> | ||
| 20 | #include <set> | 21 | #include <set> |
| 21 | 22 | ||
| 22 | #include "interface/function/function.h" | 23 | #include "interface/function/function.h" |
| @@ -111,7 +112,8 @@ public: | |||
| 111 | const std::shared_ptr<LogicalTensor>& oOperand, const Operation& op) const; | 112 | const std::shared_ptr<LogicalTensor>& oOperand, const Operation& op) const; |
| 112 | 113 | ||
| 113 | // 检查tensor是否需要跳过 | 114 | // 检查tensor是否需要跳过 |
| 114 | - bool SkipOperand(const std::shared_ptr<LogicalTensor>& oOperand, const std::vector<int>& visitedTensor) const; | 115 | + bool SkipOperand(const std::shared_ptr<LogicalTensor>& oOperand, |
| 116 | + const std::unordered_set<int>& visitedTensor) const; | ||
| 115 | 117 | ||
| 116 | // 检查tensor生产者是否都是assemble | 118 | // 检查tensor生产者是否都是assemble |
| 117 | bool isAllProducerAssemble(const std::shared_ptr<LogicalTensor>& oOperand) const; | 119 | bool isAllProducerAssemble(const std::shared_ptr<LogicalTensor>& oOperand) const; |
| @@ -185,10 +185,30 @@ Status DuplicateOp::ProcessOp(Function& function, Operation& operation, std::vec | |||
| 185 | return SUCCESS; | 185 | return SUCCESS; |
| 186 | } | 186 | } |
| 187 | 187 | ||
| 188 | +void DuplicateOp::PushProducers(const LogicalTensors& operands, std::stack<Operation*>& stack, | ||
| 189 | + std::unordered_set<int>& visitedOps, std::unordered_set<int>& visitedTensors) const | ||
| 190 | +{ | ||
| 191 | + for (const auto& iOperand : operands) { | ||
| 192 | + if (iOperand == nullptr) { | ||
| 193 | + continue; | ||
| 194 | + } | ||
| 195 | + if (!visitedTensors.insert(iOperand->GetMagic()).second) { | ||
| 196 | + continue; | ||
| 197 | + } | ||
| 198 | + for (auto& producer : iOperand->GetProducers()) { | ||
| 199 | + if (visitedOps.find(producer->GetOpMagic()) == visitedOps.end()) { | ||
| 200 | + stack.push(producer); | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | + } | ||
| 204 | +} | ||
| 205 | + | ||
| 188 | Status DuplicateOp::Process(Function& function, std::vector<Operation*>& newOps) const | 206 | Status DuplicateOp::Process(Function& function, std::vector<Operation*>& newOps) const |
| 189 | { | 207 | { |
| 190 | std::stack<Operation*> stack; | 208 | std::stack<Operation*> stack; |
| 191 | - std::unordered_set<Operation*> visited; | 209 | + std::unordered_set<int> visitedOps; |
| 210 | + std::unordered_set<int> visitedTensors; | ||
| 211 | + visitedOps.reserve(function.GetOperationSize()); | ||
| 192 | for (const auto& outcast : function.GetOutcast()) { | 212 | for (const auto& outcast : function.GetOutcast()) { |
| 193 | for (auto op : outcast->GetProducers()) { | 213 | for (auto op : outcast->GetProducers()) { |
| 194 | stack.push(op); | 214 | stack.push(op); |
| @@ -196,21 +216,22 @@ Status DuplicateOp::Process(Function& function, std::vector<Operation*>& newOps) | |||
| 196 | while (!stack.empty()) { | 216 | while (!stack.empty()) { |
| 197 | Operation* CurrentOp = stack.top(); | 217 | Operation* CurrentOp = stack.top(); |
| 198 | stack.pop(); | 218 | stack.pop(); |
| 199 | - if (visited.find(CurrentOp) != visited.end()) { | 219 | + if (!visitedOps.insert(CurrentOp->GetOpMagic()).second) { |
| 200 | continue; | 220 | continue; |
| 201 | } | 221 | } |
| 202 | - visited.insert(CurrentOp); | ||
| 203 | if (ProcessOp(function, *CurrentOp, newOps) != SUCCESS) { | 222 | if (ProcessOp(function, *CurrentOp, newOps) != SUCCESS) { |
| 204 | APASS_LOG_ERROR_F(Elements::Operation, "ProcessOp failed."); | 223 | APASS_LOG_ERROR_F(Elements::Operation, "ProcessOp failed."); |
| 205 | return FAILED; | 224 | return FAILED; |
| 206 | } | 225 | } |
| 207 | - for (auto& iOperand : CurrentOp->iOperand) { | 226 | + PushProducers(CurrentOp->iOperand, stack, visitedOps, visitedTensors); |
| 208 | - for (auto& producer : iOperand->GetProducers()) { | ||
| 209 | - stack.push(producer); | ||
| 210 | - } | ||
| 211 | - } | ||
| 212 | } | 227 | } |
| 213 | } | 228 | } |
| 229 | + | ||
| 230 | + // Skip DCE + SortOperations when no duplication occurred. | ||
| 231 | + if (newOps.empty()) { | ||
| 232 | + return SUCCESS; | ||
| 233 | + } | ||
| 234 | + | ||
| 214 | DeadOperationEliminator eliminator; | 235 | DeadOperationEliminator eliminator; |
| 215 | eliminator.EliminateDeadOperationBackward(function); | 236 | eliminator.EliminateDeadOperationBackward(function); |
| 216 | return SUCCESS; | 237 | return SUCCESS; |
| @@ -15,6 +15,8 @@ | |||
| 15 | 15 | ||
| 16 | #pragma once | 16 | #pragma once |
| 17 | 17 | ||
| 18 | +#include <stack> | ||
| 19 | +#include <unordered_set> | ||
| 18 | #include <vector> | 20 | #include <vector> |
| 19 | #include "passes/pass_interface/pass.h" | 21 | #include "passes/pass_interface/pass.h" |
| 20 | namespace npu::tile_fwk { | 22 | namespace npu::tile_fwk { |
| @@ -33,6 +35,8 @@ private: | |||
| 33 | Status RunOnFunction(Function& function) override; | 35 | Status RunOnFunction(Function& function) override; |
| 34 | Status ProcessOp(Function& function, Operation& operation, std::vector<Operation*>& newOps) const; | 36 | Status ProcessOp(Function& function, Operation& operation, std::vector<Operation*>& newOps) const; |
| 35 | Status Process(Function& function, std::vector<Operation*>& newOps) const; | 37 | Status Process(Function& function, std::vector<Operation*>& newOps) const; |
| 38 | + void PushProducers(const LogicalTensors& operands, std::stack<Operation*>& stack, | ||
| 39 | + std::unordered_set<int>& visitedOps, std::unordered_set<int>& visitedTensors) const; | ||
| 36 | Status ProcessGatherIn(Function& function, Operation& operation, std::vector<Operation*>& newOps) const; | 40 | Status ProcessGatherIn(Function& function, Operation& operation, std::vector<Operation*>& newOps) const; |
| 37 | Status ProcessView(Function& function, Operation& operation, std::vector<Operation*>& newOps) const; | 41 | Status ProcessView(Function& function, Operation& operation, std::vector<Operation*>& newOps) const; |
| 38 | }; | 42 | }; |