Merged
fix(machine): improve log quality in cellmatch code and remove Chinese from test strings. #5565
chaizhengtongAdd on Aug 20
fix(machine): improve log quality in cellmatch code and remove Chinese from test strings. #5565
Merged
chaizhengtongAdd on Aug 20
Total: 9 files changed+223-213
@@ -39,7 +39,7 @@ void ResetRuntimeDynamicCellMatchPoolHost(uint64_t addr, uint64_t capacityBytes,
39 // (0x00000000FFFFFFFF). Stitch compares full uint64 opId against AICORE_TASK_INIT.39 // (0x00000000FFFFFFFF). Stitch compares full uint64 opId against AICORE_TASK_INIT.
40 ASSERT((capacityBytes % sizeof(uint64_t)) == 0)40 ASSERT((capacityBytes % sizeof(uint64_t)) == 0)
41 << "ResetRuntimeDynamicCellMatchPoolHost: capacity not uint64 aligned, addr=" << addr41 << "ResetRuntimeDynamicCellMatchPoolHost: capacity not uint64 aligned, addr=" << addr
42- << " capacity=" << capacityBytes;42+ << " capacityBytes=" << capacityBytes;
43 const size_t numWords = static_cast<size_t>(capacityBytes / sizeof(uint64_t));43 const size_t numWords = static_cast<size_t>(capacityBytes / sizeof(uint64_t));
44 44 
45 if (!isDevice) {45 if (!isDevice) {
@@ -66,7 +66,7 @@ void ResetRuntimeDynamicCellMatchPoolHost(uint64_t addr, uint64_t capacityBytes,
66 auto ret = NormalizedRtMemcpy(dst + byteOffset, bytes, chunk, bytes, RtMemcpyKind::HOST_TO_DEVICE);66 auto ret = NormalizedRtMemcpy(dst + byteOffset, bytes, chunk, bytes, RtMemcpyKind::HOST_TO_DEVICE);
67 if (ret != RT_SUCCESS) {67 if (ret != RT_SUCCESS) {
68 ASSERT(false) << "ResetRuntimeDynamicCellMatchPoolHost device memcpy failed, addr=" << addr68 ASSERT(false) << "ResetRuntimeDynamicCellMatchPoolHost device memcpy failed, addr=" << addr
69- << " capacity=" << capacityBytes << " offset=" << byteOffset << " ret=" << ret;69+ << " capacityBytes=" << capacityBytes << " offsetBytes=" << byteOffset << " ret=" << ret;
70 return;70 return;
71 }71 }
72 remaining -= n;72 remaining -= n;
@@ -94,7 +94,8 @@ bool TryBuildDynamicCellMatchDesc(const DyndevFunctionAttribute::DynamicCellMatc
94 int64_t tensorDim = eval.Evaluate(expr);94 int64_t tensorDim = eval.Evaluate(expr);
95 int64_t cellDim = std::max<int64_t>(patchedDesc.GetCellShape(d), 1);95 int64_t cellDim = std::max<int64_t>(patchedDesc.GetCellShape(d), 1);
96 int64_t tile = (tensorDim + cellDim - 1) / cellDim;96 int64_t tile = (tensorDim + cellDim - 1) / cellDim;
97- ASSERT(tile > 0) << "Invalid tile for dynamic cell match slot=" << launchMeta.slotIndex << ", dim=" << d;97+ ASSERT(tile > 0) << "Invalid tile for dynamic cell match slot=" << launchMeta.slotIndex << ", dim=" << d
98+ << ", tile=" << tile << ", expected > 0";
98 currentStride[d] = tile;99 currentStride[d] = tile;
99 }100 }
100 if (c == 0) {101 if (c == 0) {
@@ -146,7 +147,8 @@ std::vector<DevDynamicCellMatchStridePatch> PrepareDynamicCellMatchDescPatches(
146 DevCellMatchTableDesc patchedDesc;147 DevCellMatchTableDesc patchedDesc;
147 bool ready = TryBuildDynamicCellMatchDesc(launchMeta, eval, patchedDesc);148 bool ready = TryBuildDynamicCellMatchDesc(launchMeta, eval, patchedDesc);
148 if (!ready) {149 if (!ready) {
149- ASSERT(false) << "dynamic cell match launch prepare failed, slot=" << launchMeta.slotIndex;150+ ASSERT(false) << "Dynamic cell match launch prepare failed, slot=" << launchMeta.slotIndex
151+ << ", stride inconsistent across candidates or candidateRawDims invalid";
150 }152 }
151 DevDynamicCellMatchStridePatch patch;153 DevDynamicCellMatchStridePatch patch;
152 patch.descOffset = launchMeta.descOffset;154 patch.descOffset = launchMeta.descOffset;
@@ -197,8 +199,10 @@ void ValidateDynamicCellMatchTableMemBudget(const DyndevFunctionAttribute& dynAt
197 const auto* desc = reinterpret_cast<const DevCellMatchTableDesc*>(cfgBytes + launchMeta.descOffset);199 const auto* desc = reinterpret_cast<const DevCellMatchTableDesc*>(cfgBytes + launchMeta.descOffset);
198 const uint64_t cellMatchStride0 = desc->stride.dimStride[0];200 const uint64_t cellMatchStride0 = desc->stride.dimStride[0];
199 ASSERT(DevCommonErr::PARAM_CHECK_FAILED, cellMatchStride0 < static_cast<uint64_t>(MAX_CELLMATCHSSTRIDE))201 ASSERT(DevCommonErr::PARAM_CHECK_FAILED, cellMatchStride0 < static_cast<uint64_t>(MAX_CELLMATCHSSTRIDE))
200- << " Dynamic cell match slot=" << launchMeta.slotIndex << " stitch results in excessive memory consumption,"202+ << "Dynamic cell match slot=" << launchMeta.slotIndex << " stitch results in excessive memory consumption,"
201- << "Please appropriately configure the view shape and tile shape, and ensure aligned with the input shape.";203+ << " cellMatchStride0=" << cellMatchStride0 << ", maxAllowed=" << MAX_CELLMATCHSSTRIDE
204+ << ". Please appropriately configure the view shape and tile shape, and ensure it is aligned with the "
205+ "input shape.";
202 }206 }
203}207}
204 208 
@@ -181,7 +181,7 @@ void PyPTOExceptionInfoCallBack(AclRtExceptionInfo* exceptionInfo)
181 printf("[Error]: %s, device_id: %u, stream_id: %u, task_id: %u, retcode: %u, kernelName: %s\n", errMsg,181 printf("[Error]: %s, device_id: %u, stream_id: %u, task_id: %u, retcode: %u, kernelName: %s\n", errMsg,
182 exceptionInfo->deviceid, exceptionInfo->streamid, exceptionInfo->taskid, exceptionInfo->retcode, kernelName);182 exceptionInfo->deviceid, exceptionInfo->streamid, exceptionInfo->taskid, exceptionInfo->retcode, kernelName);
183 printf(" Rectify the fault based on the error information in the ascend log.\n");183 printf(" Rectify the fault based on the error information in the ascend log.\n");
184- printf("PyPTO error: PyPTO Inner Error. Please rectify the fault based on the error information "184+ printf("PyPTO error: PyPTO Internal Error. Please rectify the fault based on the error information "
185 "in the ascend log. (function PyPTOExceptionInfoCallBack)\n");185 "in the ascend log. (function PyPTOExceptionInfoCallBack)\n");
186}186}
187 187 
@@ -313,7 +313,7 @@ void DeviceWorkspaceAllocator::TryAllocateDynamicCellMatchForAssembleSlot(Device
313 metadataAllocators_.dynamicCellMatch.AvailableSlots());313 metadataAllocators_.dynamicCellMatch.AvailableSlots());
314 WsAllocation dynamicCellMatchAlloc = metadataAllocators_.dynamicCellMatch.Allocate();314 WsAllocation dynamicCellMatchAlloc = metadataAllocators_.dynamicCellMatch.Allocate();
315 DEV_ASSERT_MSG(WsErr::WORKSPACE_INIT_RESOURCE_ERROR, dynamicCellMatchAlloc.ptr != 0,315 DEV_ASSERT_MSG(WsErr::WORKSPACE_INIT_RESOURCE_ERROR, dynamicCellMatchAlloc.ptr != 0,
316- "Dynamic cell match metadata alloc failed, size=%" PRIu64, dynamicCellMatchSlotBytes);316+ "Dynamic cell match metadata alloc failed, sizeBytes=%" PRIu64, dynamicCellMatchSlotBytes);
317 dynamicCellMatchAlloc.parallelWsId = curParallelWsId;317 dynamicCellMatchAlloc.parallelWsId = curParallelWsId;
318 partialUpdate->cellMatchRuntimePartialUpdateTable = DevRelocVector<uint64_t>(318 partialUpdate->cellMatchRuntimePartialUpdateTable = DevRelocVector<uint64_t>(
319 0, reinterpret_cast<uint64_t*>(dynamicCellMatchAlloc.ptr));319 0, reinterpret_cast<uint64_t*>(dynamicCellMatchAlloc.ptr));
@@ -106,7 +106,7 @@ TEST(DeviceErrorTrackingTest, PyPTOExceptionInfoCallBackOutputsCorrectInfo)
106 EXPECT_NE(output.find("task_id: 123"), std::string::npos);106 EXPECT_NE(output.find("task_id: 123"), std::string::npos);
107 EXPECT_NE(output.find("retcode: 507015"), std::string::npos);107 EXPECT_NE(output.find("retcode: 507015"), std::string::npos);
108 EXPECT_NE(output.find("kernelName: test_kernel"), std::string::npos);108 EXPECT_NE(output.find("kernelName: test_kernel"), std::string::npos);
109- EXPECT_NE(output.find("PyPTO Inner Error"), std::string::npos);109+ EXPECT_NE(output.find("PyPTO Internal Error"), std::string::npos);
110}110}
111 111 
112TEST(DeviceErrorTrackingTest, InitializeErrorCallbackExecutesNormally)112TEST(DeviceErrorTrackingTest, InitializeErrorCallbackExecutesNormally)
@@ -114,10 +114,13 @@ def _find_input(output_dir: str, name: str, preferred_relative_path: str) -> str
114 if name in files:114 if name in files:
115 matches.append(os.path.abspath(os.path.join(root, name)))115 matches.append(os.path.abspath(os.path.join(root, name)))
116 if not matches:116 if not matches:
117- raise FileNotFoundError(f"未在 output 目录中找到 {name}: {output_dir}")117+ raise FileNotFoundError(f"{name} not found in output directory: {output_dir}")
118 if len(matches) > 1:118 if len(matches) > 1:
119 joined = "\n ".join(sorted(matches))119 joined = "\n ".join(sorted(matches))
120- raise ValueError(f"发现多个 {name},无法确认所属运行,请传入单次运行的 output 目录:\n {joined}")120+ raise ValueError(
121+ f"Multiple {name} found, cannot determine which run they belong to. "
122+ f"Please pass a single-run output directory:\n {joined}"
123+ )
121 preferred = os.path.abspath(preferred)124 preferred = os.path.abspath(preferred)
122 return preferred if preferred in matches else matches[0]125 return preferred if preferred in matches else matches[0]
123 126 
@@ -135,14 +138,14 @@ def resolve_inputs(output_dir: str) -> Tuple[str, str]:
135def _header_index(path: str, reader) -> Dict[str, int]:138def _header_index(path: str, reader) -> Dict[str, int]:
136 header = next(reader, None)139 header = next(reader, None)
137 if not header:140 if not header:
138- raise ValueError(f"文件为空或缺少表头: {path}")141+ raise ValueError(f"File is empty or missing header: {path}")
139 return {name.strip(): index for index, name in enumerate(header)}142 return {name.strip(): index for index, name in enumerate(header)}
140 143 
141 144 
142def _require_columns(path: str, columns: Dict[str, int], required: Set[str]):145def _require_columns(path: str, columns: Dict[str, int], required: Set[str]):
143 missing = sorted(required - set(columns))146 missing = sorted(required - set(columns))
144 if missing:147 if missing:
145- raise ValueError(f"{path} 缺少必要字段: {', '.join(missing)}")148+ raise ValueError(f"{path} missing required columns: {', '.join(missing)}")
146 149 
147 150 
148def load_dyn_topo(path: str) -> Dict[TaskKey, TopoTask]:151def load_dyn_topo(path: str) -> Dict[TaskKey, TopoTask]:
@@ -176,10 +179,10 @@ def load_dyn_topo(path: str) -> Dict[TaskKey, TopoTask]:
176 ],179 ],
177 )180 )
178 except (IndexError, ValueError) as error:181 except (IndexError, ValueError) as error:
179- raise ValueError(f"{path}:{row_number} dyn_topo 行解析失败: {error}") from error182+ raise ValueError(f"{path}:{row_number} dyn_topo row parse failed: {error}") from error
180 if key in tasks:183 if key in tasks:
181 raise ValueError(184 raise ValueError(
182- f"{path}:{row_number} 存在重复 (seqNo, taskId)=({key.seq_no}, {key.task_id})"185+ f"{path}:{row_number} duplicate (seqNo, taskId)=({key.seq_no}, {key.task_id})"
183 )186 )
184 tasks[key] = task187 tasks[key] = task
185 return tasks188 return tasks
@@ -222,15 +225,15 @@ def load_accesses(path: str) -> Tuple[Dict[TaskKey, List[Access]], Counter]:
222 raw_magic_text = row[raw_magic_column].strip()225 raw_magic_text = row[raw_magic_column].strip()
223 raw_magic = int(raw_magic_text) if raw_magic_text else None226 raw_magic = int(raw_magic_text) if raw_magic_text else None
224 except (IndexError, ValueError) as error:227 except (IndexError, ValueError) as error:
225- raise ValueError(f"{path}:{row_number} access 行解析失败: {error}") from error228+ raise ValueError(f"{path}:{row_number} access row parse failed: {error}") from error
226 229 
227 if access_type not in {"R", "W"}:230 if access_type not in {"R", "W"}:
228- raise ValueError(f"{path}:{row_number} accessType 不是 R/W: {access_type!r}")231+ raise ValueError(f"{path}:{row_number} accessType is not R/W: {access_type!r}")
229 expected_task_id = (func_idx << TASK_OP_BITS) | (op_idx & 0xffff)232 expected_task_id = (func_idx << TASK_OP_BITS) | (op_idx & 0xffff)
230 if task_id != expected_task_id:233 if task_id != expected_task_id:
231 raise ValueError(234 raise ValueError(
232- f"{path}:{row_number} taskId={task_id} 与 "235+ f"{path}:{row_number} taskId={task_id} vs "
233- f"(funcIdx << 16 | opIdx)={expected_task_id} 不一致"236+ f"(funcIdx << 16 | opIdx)={expected_task_id} mismatch"
234 )237 )
235 operand_counter_key = (seq_no, task_id, access_type)238 operand_counter_key = (seq_no, task_id, access_type)
236 operand_index = operand_counters[operand_counter_key]239 operand_index = operand_counters[operand_counter_key]
@@ -276,8 +279,8 @@ def validate_task_sets(topo_tasks: Dict[TaskKey, TopoTask], accesses: Dict[TaskK
276 examples = ", ".join(f"({key.seq_no},{key.task_id})" for key in missing[:10])279 examples = ", ".join(f"({key.seq_no},{key.task_id})" for key in missing[:10])
277 suffix = " ..." if len(missing) > 10 else ""280 suffix = " ..." if len(missing) > 10 else ""
278 raise ValueError(281 raise ValueError(
279- f"有 {len(missing)} 个 access task 无对应 dyn_topo 节点: {examples}{suffix}。"282+ f"{len(missing)} access task(s) have no corresponding dyn_topo node: {examples}{suffix}."
280- "请确认两个文件来自同一次运行。"283+ "Please confirm both files are from the same run."
281 )284 )
282 285 
283 286 
@@ -295,8 +298,8 @@ def validate_topology(topo_tasks: Dict[TaskKey, TopoTask]):
295 )298 )
296 suffix = " ..." if len(dangling) > 10 else ""299 suffix = " ..." if len(dangling) > 10 else ""
297 raise ValueError(300 raise ValueError(
298- f"dyn_topo 存在 {len(dangling)} 条悬空后继边: {examples}{suffix}。"301+ f"dyn_topo has {len(dangling)} dangling successor edge(s): {examples}{suffix}."
299- "拓扑不完整时不能可靠判断任务先后关系。"302+ "Cannot reliably determine task ordering when topology is incomplete."
300 )303 )
301 304 
302 305 
@@ -308,7 +311,7 @@ def build_graph(topo_tasks: Dict[TaskKey, TopoTask]) -> Dict[int, Dict[int, Set[
308 311 
309 312 
310class ReachabilityIndex:313class ReachabilityIndex:
311- """仅为实际存在空间冲突候选的 task 惰性计算并缓存拓扑可达集。"""314+ """Lazily compute and cache topology reachability sets only for tasks with spatial conflict candidates."""
312 315 
313 def __init__(self, graph: Dict[int, Dict[int, Set[int]]]):316 def __init__(self, graph: Dict[int, Dict[int, Set[int]]]):
314 self._graph = graph317 self._graph = graph
@@ -341,7 +344,7 @@ class ReachabilityIndex:
341 344 
342 def is_ordered(self, lhs: TaskKey, rhs: TaskKey) -> bool:345 def is_ordered(self, lhs: TaskKey, rhs: TaskKey) -> bool:
343 if lhs.seq_no != rhs.seq_no:346 if lhs.seq_no != rhs.seq_no:
344- raise ValueError("只能查询同一 seqNo 内的任务依赖关系")347+ raise ValueError("Can only query task dependencies within the same seqNo")
345 pair = (lhs, rhs) if lhs < rhs else (rhs, lhs)348 pair = (lhs, rhs) if lhs < rhs else (rhs, lhs)
346 cached = self._ordered_pair_cache.get(pair)349 cached = self._ordered_pair_cache.get(pair)
347 if cached is not None:350 if cached is not None:
@@ -505,26 +508,26 @@ def _print_overlap_detail(conflict: Conflict):
505 508 
506def _print_conflict_kind_guide():509def _print_conflict_kind_guide():
507 print()510 print()
508- print("Overlap Kind 说明:")511+ print("Overlap Kind descriptions:")
509 print(512 print(
510- " ALL_DIMENSIONS_OVERLAP: 两个可能并发的任务访问同一完整物理分配,"513+ " ALL_DIMENSIONS_OVERLAP: Two possibly concurrent tasks access the same full physical allocation,"
511- "且所有维度的访问区间均重叠。"514+ "and all dimension access ranges overlap."
512 )515 )
513 print(516 print(
514- " INVALID_PARTIAL_ADDRESS_OVERLAP: 两个 RawTensor 物理区间发生部分交叉,"517+ " INVALID_PARTIAL_ADDRESS_OVERLAP: Two RawTensor physical ranges partially overlap,"
515- "但不是同一完整分配;需检查地址、大小和分配逻辑。"518+ "but not the same full allocation; check address, size and allocation logic."
516 )519 )
517 print(520 print(
518- " INVALID_RAW_SHAPE_MISMATCH: 两个 RawTensor 使用同一完整物理区间,"521+ " INVALID_RAW_SHAPE_MISMATCH: Two RawTensors use the same full physical range,"
519- "但 rawShape 不一致,无法在同一多维坐标系中可靠比较。"522+ "but rawShape differs, cannot reliably compare in the same coordinate system."
520 )523 )
521 print(524 print(
522- " INVALID_DIMENSION_MISMATCH: 两个 RawTensor 使用同一完整物理区间,"525+ " INVALID_DIMENSION_MISMATCH: Two RawTensors use the same full physical range,"
523- "但 offset/shape 维度数不一致,无法可靠比较各维交集。"526+ "but offset/shape dimension count differs, cannot reliably compare per-dimension intersection."
524 )527 )
525- print("Race Kind 说明:")528+ print("Race Kind descriptions:")
526- print(" RACE_READ_WRITE: 一个任务读取、另一个任务写入冲突内存。")529+ print(" RACE_READ_WRITE: One task reads, another writes to conflicting memory.")
527- print(" RACE_WRITE_WRITE: 两个任务都写入冲突内存。")530+ print(" RACE_WRITE_WRITE: Both tasks write to conflicting memory.")
528 531 
529 532 
530def print_report(533def print_report(
@@ -535,13 +538,13 @@ def print_report(
535 print("PyPTO Memory Overlap Check (dyn_topo based)")538 print("PyPTO Memory Overlap Check (dyn_topo based)")
536 print(SEPARATOR)539 print(SEPARATOR)
537 if conflicts:540 if conflicts:
538- print(f"RESULT: FAIL - 共发现 {len(conflicts)} 处内存重叠。")541+ print(f"RESULT: FAIL - Found {len(conflicts)} memory overlap(s).")
539 if unchecked_access_count:542 if unchecked_access_count:
540- print(f"WARNING: 另有 {unchecked_access_count} 条 access 数据无效,未参与检查。")543+ print(f"WARNING: {unchecked_access_count} access record(s) are invalid and were not checked.")
541 elif unchecked_access_count:544 elif unchecked_access_count:
542- print(f"RESULT: FAIL - 有 {unchecked_access_count} 条 access 数据无效,无法完成全部检查。")545+ print(f"RESULT: FAIL - {unchecked_access_count} access record(s) are invalid, cannot complete full check.")
543 else:546 else:
544- print("RESULT: PASS - 未发现无拓扑依赖任务之间的 Read-Write/Write-Write 内存重叠。")547+ print("RESULT: PASS - No Read-Write/Write-Write memory overlap found between topology-independent tasks.")
545 548 
546 if not conflicts:549 if not conflicts:
547 return550 return
@@ -556,7 +559,7 @@ def print_report(
556 if compact_conflicts:559 if compact_conflicts:
557 print()560 print()
558 print(SEPARATOR)561 print(SEPARATOR)
559- print("非全维度重叠异常(紧凑列表)")562+ print("Non-full-dimension overlap anomalies (compact list)")
560 print(SEPARATOR)563 print(SEPARATOR)
561 for conflict_index, conflict in compact_conflicts:564 for conflict_index, conflict in compact_conflicts:
562 print(565 print(
@@ -578,7 +581,7 @@ def print_report(
578 if all_dimension_conflicts:581 if all_dimension_conflicts:
579 print()582 print()
580 print(SEPARATOR)583 print(SEPARATOR)
581- print("ALL_DIMENSIONS_OVERLAP 详细信息")584+ print("ALL_DIMENSIONS_OVERLAP details")
582 print(SEPARATOR)585 print(SEPARATOR)
583 for group_index, (task_pair, indexed_group) in enumerate(586 for group_index, (task_pair, indexed_group) in enumerate(
584 sorted(all_dimension_conflicts.items(), key=lambda item: item[0]),587 sorted(all_dimension_conflicts.items(), key=lambda item: item[0]),
@@ -594,8 +597,8 @@ def print_report(
594 f"operandConflicts={len(group)}"597 f"operandConflicts={len(group)}"
595 )598 )
596 print(599 print(
597- "Dependency: 两个 Op 位于同一 DeviceTask,且在 dyn_topo 传递闭包中互相不可达,"600+ "Dependency: Two Ops are in the same DeviceTask and mutually unreachable "
598- "因此可能并发执行。"601+ "in dyn_topo transitive closure, thus may execute concurrently."
599 )602 )
600 _print_task("Source Task", representative.src, representative.src_topo)603 _print_task("Source Task", representative.src, representative.src_topo)
601 _print_task("Destination Task", representative.dst, representative.dst_topo)604 _print_task("Destination Task", representative.dst, representative.dst_topo)
@@ -633,21 +636,21 @@ def run(output_dir: str) -> int:
633def main():636def main():
634 parser = argparse.ArgumentParser(637 parser = argparse.ArgumentParser(
635 description=(638 description=(
636- "基于 output 目录中的 dyn_topo.txt 和 mem_rawtensor_access.csv "639+ "Check memory overlap between topology-independent Ops based on dyn_topo.txt and mem_rawtensor_access.csv "
637- "检查无拓扑依赖 Op 之间的内存重叠。"640+ "in the output directory."
638 )641 )
639 )642 )
640- parser.add_argument("output_dir", help="单次运行的 output 目录")643+ parser.add_argument("output_dir", help="Output directory of a single run")
641 args = parser.parse_args()644 args = parser.parse_args()
642 logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")645 logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
643 646 
644 if not os.path.isdir(args.output_dir):647 if not os.path.isdir(args.output_dir):
645- print(f"RESULT: FAIL - output 目录不存在: {args.output_dir}")648+ print(f"RESULT: FAIL - output directory does not exist: {args.output_dir}")
646 return 1649 return 1
647 try:650 try:
648 return run(os.path.abspath(args.output_dir))651 return run(os.path.abspath(args.output_dir))
649 except (OSError, ValueError) as error:652 except (OSError, ValueError) as error:
650- print(f"RESULT: FAIL - 内存重叠检查执行失败: {error}")653+ print(f"RESULT: FAIL - memory overlap check failed: {error}")
651 return 1654 return 1
652 655 
653 656 
@@ -15,7 +15,7 @@ from typing import Callable, Dict, Optional
15 15 
16 16 
17class Argument:17class Argument:
18- """存储单个参数的定义"""18+ """Store definition of a single argument"""
19 19 
20 def __init__(self, *args, **kwargs):20 def __init__(self, *args, **kwargs):
21 self.args = args21 self.args = args
@@ -56,12 +56,12 @@ class Command:
56 56 
57 57 
58def command(name: Optional[str] = None, help_info: Optional[str] = None):58def command(name: Optional[str] = None, help_info: Optional[str] = None):
59- """装饰器:标记一个函数为子命令"""59+ """Decorator: mark a function as a subcommand"""
60 60 
61 def decorator(func: Callable):61 def decorator(func: Callable):
62 cmd = Command.get_entry(func)62 cmd = Command.get_entry(func)
63 cmd_name = name or func.__name__63 cmd_name = name or func.__name__
64- cmd_help = help_info or func.__doc__ or f"执行 {cmd_name} 命令"64+ cmd_help = help_info or func.__doc__ or f"Execute {cmd_name} command"
65 cmd.set_name_help(cmd_name, cmd_help)65 cmd.set_name_help(cmd_name, cmd_help)
66 Command.cmd_dict[cmd_name] = cmd66 Command.cmd_dict[cmd_name] = cmd
67 return func67 return func
@@ -70,7 +70,7 @@ def command(name: Optional[str] = None, help_info: Optional[str] = None):
70 70 
71 71 
72def argument(*args, **kwargs):72def argument(*args, **kwargs):
73- """装饰器:为当前命令添加参数(必须在 @command 之后使用)"""73+ """Decorator: add arguments to the current command (must be used after @command)"""
74 74 
75 def decorator(func: Callable):75 def decorator(func: Callable):
76 cmd = Command.get_entry(func)76 cmd = Command.get_entry(func)
@@ -81,7 +81,7 @@ def argument(*args, **kwargs):
81 81 
82 82 
83def build_parser(prog: str = None, description: str = None) -> argparse.ArgumentParser:83def build_parser(prog: str = None, description: str = None) -> argparse.ArgumentParser:
84- """根据命令注册表构建 argparse 解析器"""84+ """Build argparse parser from command registry"""
85 parser = argparse.ArgumentParser(prog=prog, description=description)85 parser = argparse.ArgumentParser(prog=prog, description=description)
86 subparsers = parser.add_subparsers(dest='command', required=True, help='可用的子命令')86 subparsers = parser.add_subparsers(dest='command', required=True, help='可用的子命令')
87 87 
@@ -93,7 +93,7 @@ def build_parser(prog: str = None, description: str = None) -> argparse.Argument
93 93 
94 94 
95def dispatch(args: argparse.Namespace):95def dispatch(args: argparse.Namespace):
96- """执行对应的命令函数,传入解析后的参数"""96+ """Execute the corresponding command function with parsed arguments"""
97 cmd_name = args.command97 cmd_name = args.command
98 if cmd_name not in Command.cmd_dict:98 if cmd_name not in Command.cmd_dict:
99 raise ValueError(f"Unknown command: {cmd_name}")99 raise ValueError(f"Unknown command: {cmd_name}")
@@ -106,7 +106,7 @@ def dispatch(args: argparse.Namespace):
106 106 
107 107 
108def run(main_prog: str = None, description: str = None, commands_dir: str = "commands"):108def run(main_prog: str = None, description: str = None, commands_dir: str = "commands"):
109- """主入口:加载命令、构建解析器、执行"""109+ """Main entry: load commands, build parser, execute"""
110 parser = build_parser(prog=main_prog, description=description)110 parser = build_parser(prog=main_prog, description=description)
111 parsed_args = parser.parse_args()111 parsed_args = parser.parse_args()
112 return dispatch(parsed_args)112 return dispatch(parsed_args)
@@ -69,7 +69,7 @@ _data_type_full_mapping = {
69 69 
70 70 
71def _get_data_type(data_type: int):71def _get_data_type(data_type: int):
72- """数据类型数值转可读字符串"""72+ """Convert data type numeric value to readable string"""
73 return _data_type_full_mapping.get(data_type, f"UNKNOWN({data_type})")73 return _data_type_full_mapping.get(data_type, f"UNKNOWN({data_type})")
74 74 
75 75 
@@ -475,7 +475,7 @@ class CompactDumpTensorInfoParser:
475 475 
476 @staticmethod476 @staticmethod
477 def _calc_compact_size():477 def _calc_compact_size():
478- """计算无对齐的紧凑总字节数"""478+ """Calculate compact total byte count without alignment"""
479 total = 0479 total = 0
480 # 基础字段480 # 基础字段
481 total += FIELD_SIZES["uint8_t"] * 2 # version ~ rsrv_01481 total += FIELD_SIZES["uint8_t"] * 2 # version ~ rsrv_01
@@ -604,7 +604,7 @@ class CompactDumpTensorInfoParser:
604 return merge_tensor_info604 return merge_tensor_info
605 605 
606 def parse_single(self, bin_data: bytes, offset: int = 0) -> dict:606 def parse_single(self, bin_data: bytes, offset: int = 0) -> dict:
607- """解析单个紧凑存储的DumpTensorInfo结构体"""607+ """Parse a single compactly stored DumpTensorInfo struct"""
608 result = {"B>PHASE_NAME": "task_dump"}608 result = {"B>PHASE_NAME": "task_dump"}
609 current_offset = offset609 current_offset = offset
610 610 
@@ -652,7 +652,7 @@ class CompactDumpTensorInfoParser:
652 return result652 return result
653 653 
654 def parse_file(self, file_path: str) -> list[dict]:654 def parse_file(self, file_path: str) -> list[dict]:
655- """解析整个紧凑存储的bin文件"""655+ """Parse the entire compactly stored bin file"""
656 if not os.path.exists(file_path):656 if not os.path.exists(file_path):
657 raise FileNotFoundError(f"File not found: {file_path}")657 raise FileNotFoundError(f"File not found: {file_path}")
658 658 
@@ -688,7 +688,7 @@ class CompactDumpTensorInfoParser:
688 return tensor_info688 return tensor_info
689 689 
690 def get_exec_time(self, prof_data_file):690 def get_exec_time(self, prof_data_file):
691- """解析prof_data文件,获取每个任务的执行时间"""691+ """Parse prof_data file to get execution time per task"""
692 with open(prof_data_file, "rb") as f:692 with open(prof_data_file, "rb") as f:
693 data = json.load(f)693 data = json.load(f)
694 694 
@@ -849,7 +849,7 @@ class CompactDumpTensorInfoParser:
849 849 
850 850 
851def scan_pass_info_from_path(verify_path: str) -> Dict[str, int]:851def scan_pass_info_from_path(verify_path: str) -> Dict[str, int]:
852- """扫描 computation_graph 目录,返回 {pass_name: pass_num} 字典。"""852+ """Scan computation_graph directory, return {pass_name: pass_num} dict."""
853 pass_info: Dict[str, int] = {}853 pass_info: Dict[str, int] = {}
854 if not verify_path or not os.path.exists(verify_path):854 if not verify_path or not os.path.exists(verify_path):
855 return pass_info855 return pass_info
@@ -887,7 +887,7 @@ def get_pass_full_name(verify_path: str, pass_name: str = "CodegenPreproc") -> s
887 887 
888 888 
889def to_json_str(x):889def to_json_str(x):
890- """将 list/tuple 转为紧凑 JSON 字符串,其余原样返回。"""890+ """Convert list/tuple to compact JSON string, return others as-is."""
891 return json.dumps(x, separators=(',', ':')) if isinstance(x, (list, tuple)) else x891 return json.dumps(x, separators=(',', ':')) if isinstance(x, (list, tuple)) else x
892 892 
893 893 
@@ -912,11 +912,11 @@ def main():
912 global RESULT_FILE912 global RESULT_FILE
913 RESULT_FILE = csv_path913 RESULT_FILE = csv_path
914 if not os.path.exists(args.dump_tensor_path):914 if not os.path.exists(args.dump_tensor_path):
915- logging.error(f"目录不存在:{args.dump_tensor_path}")915+ logging.error(f"Directory does not exist: {args.dump_tensor_path}")
916 return916 return
917 # 初始化紧凑解析器917 # 初始化紧凑解析器
918 parser = CompactDumpTensorInfoParser(args.dump_tensor_path)918 parser = CompactDumpTensorInfoParser(args.dump_tensor_path)
919- logging.info(f"单个结构字节数:{parser.struct_compact_size}")919+ logging.info(f"Single struct byte count: {parser.struct_compact_size}")
920 920 
921 _verify_res.read_verify_result(args.verify_path)921 _verify_res.read_verify_result(args.verify_path)
922 922 
@@ -22,7 +22,7 @@ MAX_PRECISION = sys.float_info.dig + 1
22 22 
23 23 
24class IsCloseConfig(NamedTuple):24class IsCloseConfig(NamedTuple):
25- """check_isclose 函数的配置参数"""25+ """Configuration parameters for check_isclose function"""
26 26 
27 rtol: float = 1.0e-227 rtol: float = 1.0e-2
28 atol: float = 1.0e-228 atol: float = 1.0e-2
@@ -80,10 +80,10 @@ class TensorComparator:
80 df = pd.DataFrame(table_data, columns=headers)80 df = pd.DataFrame(table_data, columns=headers)
81 if file_exists:81 if file_exists:
82 df.to_csv(csv_path, mode='a', index=False, header=False, encoding='utf-8-sig')82 df.to_csv(csv_path, mode='a', index=False, header=False, encoding='utf-8-sig')
83- logging.info(f"数据已追加到: {csv_path}")83+ logging.info(f"Data appended to: {csv_path}")
84 else:84 else:
85 df.to_csv(csv_path, index=False, encoding='utf-8-sig')85 df.to_csv(csv_path, index=False, encoding='utf-8-sig')
86- logging.info(f"数据已保存到: {csv_path}")86+ logging.info(f"Data saved to: {csv_path}")
87 87 
88 @staticmethod88 @staticmethod
89 def check_isclose(a, b, config: IsCloseConfig = IsCloseConfig()):89 def check_isclose(a, b, config: IsCloseConfig = IsCloseConfig()):