Merged
fix(machine): Fix the runtime memory overlap check tool #6460
duanhaotianAdd on Sep 17
fix(machine): Fix the runtime memory overlap check tool #6460
Merged
duanhaotianAdd on Sep 17
Total: 1 files changed+102-168
@@ -8,11 +8,7 @@
8# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.8# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9# See LICENSE in the root of the software repository for the full text of the LICENSE.9# See LICENSE in the root of the software repository for the full text of the LICENSE.
10# -----------------------------------------------------------------------------------------------------------10# -----------------------------------------------------------------------------------------------------------
11-"""基于 controlflow 内存 dump 和 dyn_topo 的离线内存重叠检查。11+"""基于 controlflow 内存 dump 和 dyn_topo 的离线 GM 写出重叠检查。
12- 
13-只需要传入一次运行的 output 目录。脚本不依赖 profiling/swimlane 时间:
14-同一 DeviceTask 内,dyn_topo 上互相不可达的两个 Op 视为可能并发,然后检查
15-Read-Write 和 Write-Write Operand 的物理地址及各维访问范围。
16"""12"""
17 13 
18import argparse14import argparse
@@ -28,6 +24,8 @@ DYN_TOPO_NAME = "dyn_topo.txt"
28ACCESS_CSV_NAME = "mem_rawtensor_access.csv"24ACCESS_CSV_NAME = "mem_rawtensor_access.csv"
29TASK_OP_BITS = 1625TASK_OP_BITS = 16
30SEPARATOR = "=" * 10026SEPARATOR = "=" * 100
27+GM_OUTCAST_LOCATION = "OUTCAST"
28+REPORT_LOG_NAME = "memory_overlap_check.log"
31 29 
32 30 
33@dataclass(frozen=True, order=True)31@dataclass(frozen=True, order=True)
@@ -377,6 +375,10 @@ def _access_overlap_kind(src: Access, dst: Access) -> Optional[str]:
377 return "ALL_DIMENSIONS_OVERLAP"375 return "ALL_DIMENSIONS_OVERLAP"
378 376 
379 377 
378+def _is_gm_outcast_write(access: Access) -> bool:
379+ return access.is_write and access.location == GM_OUTCAST_LOCATION and access.raw_magic is not None
380+ 
381+ 
380def check_overlaps(382def check_overlaps(
381 topo_tasks: Dict[TaskKey, TopoTask],383 topo_tasks: Dict[TaskKey, TopoTask],
382 accesses: Dict[TaskKey, List[Access]],384 accesses: Dict[TaskKey, List[Access]],
@@ -386,12 +388,13 @@ def check_overlaps(
386 by_seq: Dict[int, List[Access]] = defaultdict(list)388 by_seq: Dict[int, List[Access]] = defaultdict(list)
387 for task_accesses in accesses.values():389 for task_accesses in accesses.values():
388 for access in task_accesses:390 for access in task_accesses:
389- by_seq[access.seq_no].append(access)391+ if _is_gm_outcast_write(access):
392+ by_seq[access.seq_no].append(access)
390 393 
391 conflicts: List[Conflict] = []394 conflicts: List[Conflict] = []
392 counters: Counter = Counter()395 counters: Counter = Counter()
393 for seq_no, seq_accesses in sorted(by_seq.items()):396 for seq_no, seq_accesses in sorted(by_seq.items()):
394- seq_accesses.sort(key=lambda access: (access.base, access.end, access.row_number))397+ seq_accesses.sort(key=lambda access: (access.base, access.end, access.raw_magic, access.row_number))
395 counters["deviceTasks"] += 1398 counters["deviceTasks"] += 1
396 counters["sweepAccesses"] += len(seq_accesses)399 counters["sweepAccesses"] += len(seq_accesses)
397 active: List[Access] = []400 active: List[Access] = []
@@ -403,32 +406,24 @@ def check_overlaps(
403 if candidate.key == current.key:406 if candidate.key == current.key:
404 counters["skippedSameTaskPairs"] += 1407 counters["skippedSameTaskPairs"] += 1
405 continue408 continue
409+ if candidate.raw_magic != current.raw_magic:
410+ counters["skippedDifferentTensor"] += 1
411+ continue
406 src, dst = (412 src, dst = (
407 (candidate, current)413 (candidate, current)
408 if candidate.key < current.key414 if candidate.key < current.key
409 else (current, candidate)415 else (current, candidate)
410 )416 )
411- if not src.is_write and not dst.is_write:
412- counters["skippedReadReadPairs"] += 1
413- continue
414- counters["spatialRuleChecks"] += 1
415 overlap_kind = _access_overlap_kind(src, dst)417 overlap_kind = _access_overlap_kind(src, dst)
416- if overlap_kind is None:418+ if overlap_kind != "ALL_DIMENSIONS_OVERLAP":
417- counters["dimensionDisjointPairs"] += 1419+ counters["skippedNotSameWindow"] += 1
418 continue420 continue
419- counters["spatialConflictCandidates"] += 1
420 if reachability.is_ordered(src.key, dst.key):421 if reachability.is_ordered(src.key, dst.key):
421 counters["orderedSpatialCandidates"] += 1422 counters["orderedSpatialCandidates"] += 1
422 continue423 continue
423- counters["possiblyConcurrentCandidates"] += 1
424- race_kind = (
425- "RACE_WRITE_WRITE"
426- if src.is_write and dst.is_write
427- else "RACE_READ_WRITE"
428- )
429 conflicts.append(424 conflicts.append(
430 Conflict(425 Conflict(
431- race_kind=race_kind,426+ race_kind="RACE_WRITE_WRITE",
432 overlap_kind=overlap_kind,427 overlap_kind=overlap_kind,
433 src=src,428 src=src,
434 dst=dst,429 dst=dst,
@@ -436,7 +431,7 @@ def check_overlaps(
436 dst_topo=topo_tasks[dst.key],431 dst_topo=topo_tasks[dst.key],
437 )432 )
438 )433 )
439- counters[race_kind] += 1434+ counters["RACE_WRITE_WRITE"] += 1
440 counters[overlap_kind] += 1435 counters[overlap_kind] += 1
441 active.append(current)436 active.append(current)
442 counters["topologyTaskPairQueries"] = reachability.queried_pair_count437 counters["topologyTaskPairQueries"] = reachability.queried_pair_count
@@ -445,175 +440,86 @@ def check_overlaps(
445 return conflicts, counters440 return conflicts, counters
446 441 
447 442 
448-def _format_interval(begin: int, end: int) -> str:
449- return f"[{begin}, {end})"
450- 
451- 
452def _format_hex_interval(begin: int, end: int) -> str:443def _format_hex_interval(begin: int, end: int) -> str:
453 return f"[0x{begin:x}, 0x{end:x})"444 return f"[0x{begin:x}, 0x{end:x})"
454 445 
455 446 
456-def _print_task(role: str, access: Access, topo: TopoTask):447+def _leaf_pair_key(conflict: Conflict) -> Tuple[str, str]:
457- print(f"{role}:")448+ lhs = conflict.src_topo.leaf_hash
458- print(449+ rhs = conflict.dst_topo.leaf_hash
459- f" DeviceTask: seqNo={access.seq_no}; "450+ return (lhs, rhs) if lhs <= rhs else (rhs, lhs)
460- f"RootFunction: funcIdx={access.func_idx}, rootIndex={access.root_index}, "
461- f"topoRootIndex={topo.root_index}, rootHash={topo.root_hash}"
462- )
463- print(
464- f" Op: taskId={access.task_id}, opIdx={access.op_idx}, opmagic={topo.opmagic}, "
465- f"leafIndex={topo.leaf_index}, leafHash={topo.leaf_hash}, "
466- f"coreType={topo.core_type}, psgId={topo.psg_id}, wrapId={topo.wrap_id}"
467- )
468 451 
469 452 
470-def _print_operand(role: str, access: Access):453+def _format_op_line(role: str, access: Access, topo: TopoTask) -> str:
471- access_mode = "WRITE" if access.is_write else "READ"454+ return (
472- print(455+ f"{role}: leafHash={topo.leaf_hash} funcIdx={access.func_idx} rootHash={topo.root_hash} "
473- f" {role}: {access.operand_name}, access={access_mode}, csvRow={access.row_number}, "456+ f"coreType={topo.core_type} opIdx={access.op_idx} opmagic={topo.opmagic} taskId={access.task_id}"
474- f"location={access.location}, rawMagic={access.raw_magic}"
475 )457 )
476- print(
477- f" RawTensor: address={_format_hex_interval(access.base, access.end)}, "
478- f"size={access.end - access.base} bytes"
479- )
480- print(f" Shape: offset={access.offset}, shape={access.shape}, rawShape={access.raw_shape}")
481- 
482- 
483-def _print_overlap_detail(conflict: Conflict):
484- src, dst = conflict.src, conflict.dst
485- address_begin = max(src.base, dst.base)
486- address_end = min(src.end, dst.end)
487- print("Overlap:")
488- print(
489- f" Physical intersection: {_format_hex_interval(address_begin, address_end)}, "
490- f"size={address_end - address_begin} bytes"
491- )
492- if conflict.overlap_kind != "ALL_DIMENSIONS_OVERLAP":
493- print(" Dimension intersection: unavailable because allocation ranges/dimensions are inconsistent")
494- return
495- for dim in range(len(src.offset)):
496- src_begin = src.offset[dim]
497- src_end = src_begin + src.shape[dim]
498- dst_begin = dst.offset[dim]
499- dst_end = dst_begin + dst.shape[dim]
500- overlap_begin = max(src_begin, dst_begin)
501- overlap_end = min(src_end, dst_end)
502- print(
503- f" dim[{dim}]: src={_format_interval(src_begin, src_end)}, "
504- f"dst={_format_interval(dst_begin, dst_end)}, "
505- f"intersection={_format_interval(overlap_begin, overlap_end)}"
506- )
507- 
508- 
509-def _print_conflict_kind_guide():
510- print()
511- print("Overlap Kind descriptions:")
512- print(
513- " ALL_DIMENSIONS_OVERLAP: Two possibly concurrent tasks access the same full physical allocation,"
514- "and all dimension access ranges overlap."
515- )
516- print(
517- " INVALID_PARTIAL_ADDRESS_OVERLAP: Two RawTensor physical ranges partially overlap,"
518- "but not the same full allocation; check address, size and allocation logic."
519- )
520- print(
521- " INVALID_RAW_SHAPE_MISMATCH: Two RawTensors use the same full physical range,"
522- "but rawShape differs, cannot reliably compare in the same coordinate system."
523- )
524- print(
525- " INVALID_DIMENSION_MISMATCH: Two RawTensors use the same full physical range,"
526- "but offset/shape dimension count differs, cannot reliably compare per-dimension intersection."
527- )
528- print("Race Kind descriptions:")
529- print(" RACE_READ_WRITE: One task reads, another writes to conflicting memory.")
530- print(" RACE_WRITE_WRITE: Both tasks write to conflicting memory.")
531 458 
532 459 
533def print_report(460def print_report(
534 conflicts: List[Conflict],461 conflicts: List[Conflict],
535 unchecked_access_count: int,462 unchecked_access_count: int,
463+ check_counters: Optional[Counter] = None,
536):464):
465+ unique_pairs: Dict[Tuple[str, str], Conflict] = {}
466+ tensors_by_pair: Dict[Tuple[str, str], List[Conflict]] = defaultdict(list)
467+ for conflict in conflicts:
468+ key = _leaf_pair_key(conflict)
469+ if key not in unique_pairs:
470+ unique_pairs[key] = conflict
471+ if conflict.src.raw_magic not in {item.src.raw_magic for item in tensors_by_pair[key]}:
472+ tensors_by_pair[key].append(conflict)
473+ 
537 print(SEPARATOR)474 print(SEPARATOR)
538- print("PyPTO Memory Overlap Check (dyn_topo based)")475+ print("PyPTO Memory Overlap Check (GM outcast write-write, dyn_topo based)")
539 print(SEPARATOR)476 print(SEPARATOR)
540- if conflicts:477+ if check_counters:
541- print(f"RESULT: FAIL - Found {len(conflicts)} memory overlap(s).")478+ print(
479+ f"Checked GM outcast writes={check_counters.get('sweepAccesses', 0)}, "
480+ f"same-tensor address pairs={check_counters.get('addressCandidatePairs', 0)}, "
481+ f"ordered skipped={check_counters.get('orderedSpatialCandidates', 0)}"
482+ )
483+ unique_count = len(unique_pairs)
484+ if unique_count:
485+ print(f"RESULT: FAIL - Found {unique_count} unique leafHash pair(s) with concurrent GM write-write overlap.")
542 if unchecked_access_count:486 if unchecked_access_count:
543 print(f"WARNING: {unchecked_access_count} access record(s) are invalid and were not checked.")487 print(f"WARNING: {unchecked_access_count} access record(s) are invalid and were not checked.")
544 elif unchecked_access_count:488 elif unchecked_access_count:
545 print(f"RESULT: FAIL - {unchecked_access_count} access record(s) are invalid, cannot complete full check.")489 print(f"RESULT: FAIL - {unchecked_access_count} access record(s) are invalid, cannot complete full check.")
546 else:490 else:
547- print("RESULT: PASS - No Read-Write/Write-Write memory overlap found between topology-independent tasks.")491+ print("RESULT: PASS - No unordered GM write-write overlap on the same tensor.")
548 492 
549- if not conflicts:493+ if not unique_pairs:
550 return494 return
551 495 
552- _print_conflict_kind_guide()496+ print()
553- indexed_conflicts = list(enumerate(conflicts, start=1))497+ print("Rule: two WRITEs to the same GM outcast (same rawMagic and address range), overlapping offset/shape,")
554- compact_conflicts = [498+ print("and neither task can reach the other in dyn_topo.")
555- (index, conflict)499+ print()
556- for index, conflict in indexed_conflicts500+ print(SEPARATOR)
557- if conflict.overlap_kind != "ALL_DIMENSIONS_OVERLAP"501+ print("Unique leafHash pairs")
558- ]502+ print(SEPARATOR)
559- if compact_conflicts:503+ for pair_index, key in enumerate(sorted(unique_pairs), start=1):
504+ representative = unique_pairs[key]
505+ src, dst = representative.src, representative.dst
506+ src_topo, dst_topo = representative.src_topo, representative.dst_topo
507+ if src_topo.leaf_hash > dst_topo.leaf_hash:
508+ src, dst = dst, src
509+ src_topo, dst_topo = dst_topo, src_topo
560 print()510 print()
561- print(SEPARATOR)511+ print(f"[Pair #{pair_index}]")
562- print("Non-full-dimension overlap anomalies (compact list)")512+ print(f" {_format_op_line('src', src, src_topo)}")
563- print(SEPARATOR)513+ print(f" {_format_op_line('dst', dst, dst_topo)}")
564- for conflict_index, conflict in compact_conflicts:514+ for tensor_conflict in tensors_by_pair[key]:
565 print(515 print(
566- f"[Conflict #{conflict_index}] overlapKind={conflict.overlap_kind}, "516+ f" tensor rawMagic={tensor_conflict.src.raw_magic} "
567- f"raceKind={conflict.race_kind}, "517+ f"address={_format_hex_interval(tensor_conflict.src.base, tensor_conflict.src.end)} "
568- f"src=(funcIdx={conflict.src.func_idx}, opIdx={conflict.src.op_idx}), "518+ f"offset={tensor_conflict.src.offset} shape={tensor_conflict.src.shape}"
569- f"dst=(funcIdx={conflict.dst.func_idx}, opIdx={conflict.dst.op_idx})"
570 )519 )
571 520 
572- all_dimension_conflicts: Dict[
573- Tuple[TaskKey, TaskKey], List[Tuple[int, Conflict]]
574- ] = defaultdict(list)
575- for conflict_index, conflict in indexed_conflicts:
576- if conflict.overlap_kind == "ALL_DIMENSIONS_OVERLAP":
577- all_dimension_conflicts[(conflict.src.key, conflict.dst.key)].append(
578- (conflict_index, conflict)
579- )
580 521 
581- if all_dimension_conflicts:522+def run(output_dir: str, log_path: Optional[str] = None) -> int:
582- print()
583- print(SEPARATOR)
584- print("ALL_DIMENSIONS_OVERLAP details")
585- print(SEPARATOR)
586- for group_index, (task_pair, indexed_group) in enumerate(
587- sorted(all_dimension_conflicts.items(), key=lambda item: item[0]),
588- start=1,
589- ):
590- group = [conflict for _, conflict in indexed_group]
591- representative = group[0]
592- print()
593- print(SEPARATOR)
594- print(
595- f"[Task Pair #{group_index}] seqNo={task_pair[0].seq_no}, "
596- f"srcTaskId={task_pair[0].task_id}, dstTaskId={task_pair[1].task_id}, "
597- f"operandConflicts={len(group)}"
598- )
599- print(
600- "Dependency: Two Ops are in the same DeviceTask and mutually unreachable "
601- "in dyn_topo transitive closure, thus may execute concurrently."
602- )
603- _print_task("Source Task", representative.src, representative.src_topo)
604- _print_task("Destination Task", representative.dst, representative.dst_topo)
605- for conflict_index, conflict in indexed_group:
606- print()
607- print(
608- f" [Operand Conflict #{conflict_index}] raceKind={conflict.race_kind}, "
609- f"overlapKind={conflict.overlap_kind}"
610- )
611- _print_operand("Source Operand", conflict.src)
612- _print_operand("Destination Operand", conflict.dst)
613- _print_overlap_detail(conflict)
614- 
615- 
616-def run(output_dir: str) -> int:
617 dyn_topo_path, access_csv_path = resolve_inputs(output_dir)523 dyn_topo_path, access_csv_path = resolve_inputs(output_dir)
618 logging.info("dyn_topo: %s", dyn_topo_path)524 logging.info("dyn_topo: %s", dyn_topo_path)
619 logging.info("memory access dump: %s", access_csv_path)525 logging.info("memory access dump: %s", access_csv_path)
@@ -624,23 +530,51 @@ def run(output_dir: str) -> int:
624 validate_task_sets(topo_tasks, accesses)530 validate_task_sets(topo_tasks, accesses)
625 logging.info("loaded topo tasks=%d, access tasks=%d", len(topo_tasks), len(accesses))531 logging.info("loaded topo tasks=%d, access tasks=%d", len(topo_tasks), len(accesses))
626 532 
627- conflicts, _ = check_overlaps(topo_tasks, accesses)533+ conflicts, check_counters = check_overlaps(topo_tasks, accesses)
628 unchecked_access_count = sum(534 unchecked_access_count = sum(
629 access_stats[name]535 access_stats[name]
630 for name in ("skippedNonConcrete", "skippedInvalidRange", "skippedInvalidShape")536 for name in ("skippedNonConcrete", "skippedInvalidRange", "skippedInvalidShape")
631 )537 )
632- print_report(conflicts, unchecked_access_count)538+ if log_path is None:
539+ log_path = os.path.join(output_dir, REPORT_LOG_NAME)
540+ os.makedirs(os.path.dirname(os.path.abspath(log_path)) or ".", exist_ok=True)
541+ with open(log_path, "w", encoding="utf-8") as log_file:
542+ original_stdout = sys.stdout
543+ sys.stdout = _TeeWriter(original_stdout, log_file)
544+ try:
545+ print_report(conflicts, unchecked_access_count, check_counters)
546+ finally:
547+ sys.stdout = original_stdout
548+ logging.info("report log: %s", log_path)
633 return 1 if conflicts or unchecked_access_count else 0549 return 1 if conflicts or unchecked_access_count else 0
634 550 
635 551 
552+class _TeeWriter:
553+ def __init__(self, *streams):
554+ self._streams = streams
555+ 
556+ def write(self, data):
557+ for stream in self._streams:
558+ stream.write(data)
559+ 
560+ def flush(self):
561+ for stream in self._streams:
562+ stream.flush()
563+ 
564+ 
636def main():565def main():
637 parser = argparse.ArgumentParser(566 parser = argparse.ArgumentParser(
638 description=(567 description=(
639- "Check memory overlap between topology-independent Ops based on dyn_topo.txt and mem_rawtensor_access.csv "568+ "Check unordered GM outcast write-write overlap (same tensor, overlapping offset/shape) "
640- "in the output directory."569+ "using dyn_topo.txt and mem_rawtensor_access.csv."
641 )570 )
642 )571 )
643 parser.add_argument("output_dir", help="Output directory of a single run")572 parser.add_argument("output_dir", help="Output directory of a single run")
573+ parser.add_argument(
574+ "--log-file",
575+ default=None,
576+ help=f"Report path (default: <output_dir>/{REPORT_LOG_NAME})",
577+ )
644 args = parser.parse_args()578 args = parser.parse_args()
645 logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")579 logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
646 580 
@@ -648,7 +582,7 @@ def main():
648 print(f"RESULT: FAIL - output directory does not exist: {args.output_dir}")582 print(f"RESULT: FAIL - output directory does not exist: {args.output_dir}")
649 return 1583 return 1
650 try:584 try:
651- return run(os.path.abspath(args.output_dir))585+ return run(os.path.abspath(args.output_dir), args.log_file)
652 except (OSError, ValueError) as error:586 except (OSError, ValueError) as error:
653 print(f"RESULT: FAIL - memory overlap check failed: {error}")587 print(f"RESULT: FAIL - memory overlap check failed: {error}")
654 return 1588 return 1