diff --git a/CLAUDE.md b/CLAUDE.md index edcf0ea..30d0b5b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -537,18 +537,32 @@ work. There are two such mechanisms. **Subgraphs** are the supported, modern split. The compiler partitions the model into independent compute graphs early, each in its own -folder under `vaiml_folder//vaiml_par_/`. The debugger debugs -one subgraph at a time. If the model has more than one subgraph the -user must name the one to debug in `vitisai_config.json` under -`passes[].vaiml_config.include_subgraphs`. +folder under `vaiml_folder//vaiml_par_/`. On XRT, with more +than one NPU partition and no `include_subgraphs`, the debugger reads +the halt plugin's performance counters before releasing the cores. +Counter 0 is the FNV-1a hash of the halted partition's kernel name. +Counter 1 is the halt count: 0 when the plugin halts only the first +run of the context (`halt_on_every_run` off), otherwise 1 for the first +halt and one higher for each later halt. A count of 1 or more is +followed until the hardware context goes away, and a partition may +run again later in the sequence. A count of 0, or a subgraph named in +`vitisai_config.json` under +`passes[].vaiml_config.include_subgraphs`, keeps the manual advance +described below. `--dump_layers` writes every partition; it does not +read the counters. `-s` and `--dump-aie-status` use one subgraph's +metadata when there is only one, and otherwise talk to the hardware +directly with the default overlay (or `-o`). **Failsafe partitions (FSP)** are an older mechanism, deprecated but still supported. They split a single subgraph into multiple program-memory partitions for very large models. Each FSP has its own work directory and `buffer_info.json`. Their execution order comes from -`partition-info.json`. The debugger runs `debug()` once per FSP, -prompting the user (or coordinating with FlexML) to advance between -partitions. +`partition-info.json`. On the manual path the debugger runs `debug()` +once per FSP. Between parts it arms a breakpoint on the lock-acquire +instruction. With `-l3` or `--automated_debug` it then closes the debug +server so FlexML can load the next part. Otherwise it asks the user to +press Enter in the VAIML process, wait for `waiting for user input`, +and press Enter in the debugger. ``` vaiml_folder//vaiml_par_0/ diff --git a/src/mldebug/batch_runner.py b/src/mldebug/batch_runner.py index cb20276..d8f79e2 100644 --- a/src/mldebug/batch_runner.py +++ b/src/mldebug/batch_runner.py @@ -19,6 +19,9 @@ from mldebug.utils import LOGGER, cleanup_and_exit, timeit, wait_until +# How long to wait for the driver to debug-halt every core at the next partition. +NEXT_PARTITION_HALT_TIMEOUT_S = 300 + class BatchRunner: """ @@ -62,6 +65,11 @@ def common_init(self): single-stamp collapse is handled up front by the Overlay. """ for sid in self.design_info.overlay.get_stampids(): + # A previous partition's breakpoints survive into this session: the + # cores are halted, not reset, between partitions. Those PCs mean + # something else in this partition's program. + self.aie_utls[sid].clear_pc_breakpoint(0) + self.aie_utls[sid].clear_pc_breakpoint(1) self.impls[sid].enable_pc_halt() if self.args.run_flags.skip_iter: self.aie_utls[sid].init_skip_iterations() @@ -496,29 +504,147 @@ def execute_and_dump(self): if layer.runs_replica(sid): self.state.pm_reload[sid] = self.check_pm_reload(sid) - for sid in overlay.get_stampids(): - self.aie_utls[sid].initialize_stamp() + # skip_iter2's last layer already cleared the PC breakpoints and continued + # once. initialize_stamp writes DEBUG_CONTROL0 again, and that second + # release lets cores run past the next partition's halt. The legacy FSP + # flow arms its own breakpoint afterwards, so it always releases here. + more = self.args.vaiml_folder_path and not getattr(self.args, "last_fsp", True) + legacy = getattr(self.args, "legacy_fsp", False) + if not (more and not legacy and self.args.run_flags.skip_iter2): + for sid in overlay.get_stampids(): + self.aie_utls[sid].initialize_stamp() LOGGER.log("\nFinished Execution") self._handle_fsp() self._write_run_summary("SUCCESS") - def _handle_fsp(self): - """Handle end-of-run logic for VAIML Failsafe Partition mode.""" - is_fsp = self.args.vaiml_folder_path and not self.args.last_fsp + def _partition_label(self): + """Name of the partition that just ran, as the driver prints it.""" + return ( + getattr(self.args, "partition_name", None) + or getattr(self.args, "subgraph_name", None) + or "unknown" + ) + + def _ref_core_pc(self): + """PC of the reference core, the first core tile of stamp 0.""" + if not self.aie_utls: + return "" + utl = self.aie_utls[0] + c, r = utl.pm_tracker_tile + pc = utl.read_core_pc_tile(c, r) + return f", PC: 0x{pc:x}" + + def _cores_all_halted(self): + """ + True when every core in every stamp is debug-halted. + + None means the register read failed. Between partitions that is the + hardware context going away after this partition has already finished. + """ + try: + return all(impl.poll_core_status() for impl in self.impls) + except Exception as err: # pylint: disable=broad-except + self._context_gone_error = err + return None - if is_fsp: - for utl in self.aie_utls: - utl.set_fsp_breakpoint() + def _session_done_context_gone(self): + """ + End the session successfully. + This partition's dumps are already written. The context disappeared + while waiting for the next one, which is how a later subgraph on its + own context looks from here. + """ + err = self._context_gone_error + name = self._partition_label() + LOGGER.log( + f"[INFO] Partition {name} finished. The hardware context is gone, " + f"so this session is complete. ({type(err).__name__}: {err})" + ) + self._write_run_summary("SUCCESS") + cleanup_and_exit(self.args, 0) + + def wait_for_next_partition(self): + """ + Wait until every core debug-halts at the next partition. + + The halt can land before the first poll, so an already-halted sample counts. + The L3 server is closed first so FlexML can load the next partition. + A failed read ends the session successfully: this partition is done and + the context is no longer here to halt. + """ + # Batch mode also closes in _handle_fsp. Closing again is a no-op, and + # interactive continue reaches this wait without that call. if self.dumper.debug_server: self.dumper.debug_server.close() - elif is_fsp: - input( - "First, please press Enter ONCE in the VAIML process " - "to load the next Failsafe Partition and wait for " - "`waiting for user input`. Then press Enter here." + if self.args.backend == "test": + return + name = self._partition_label() + LOGGER.log( + f"Partition {name} finished. " + "Waiting for all cores to debug-halt at the next partition." + ) + halted = self._cores_all_halted() + if halted is None: + self._session_done_context_gone() + return + if halted: + LOGGER.log( + f"All cores debug-halted after partition {name}{self._ref_core_pc()}." ) + return + deadline = time.monotonic() + NEXT_PARTITION_HALT_TIMEOUT_S + while True: + halted = self._cores_all_halted() + if halted is None: + self._session_done_context_gone() + return + if halted: + LOGGER.log( + f"All cores debug-halted after partition {name}{self._ref_core_pc()}." + ) + return + if time.monotonic() >= deadline: + minutes = NEXT_PARTITION_HALT_TIMEOUT_S // 60 + LOGGER.log( + f"[ERROR] Timed out after {minutes} minutes waiting for all cores " + f"to reach debug halt after partition {name}." + ) + # Dumps for this partition are already on disk. The context is still + # readable, so the next halt failing is a real error. Record it, or + # automated_debug keeps the previous partition's SUCCESS. + self._write_run_summary("FAIL") + cleanup_and_exit(self.args, 1) + time.sleep(0.1) + + def _handle_fsp(self): + """ + Close the L3 server, then wait for the next NPU partition's debug halt. + + The server is closed first so the runtime can load that partition. + A pinned subgraph (include_subgraphs) keeps the legacy flow instead: arm a + lock-acquire breakpoint and, without an L3 server, ask the user to load + the next partition. + """ + more = self.args.vaiml_folder_path and not getattr(self.args, "last_fsp", True) + if getattr(self.args, "legacy_fsp", False): + if more: + for utl in self.aie_utls: + utl.set_fsp_breakpoint() + if self.dumper.debug_server: + self.dumper.debug_server.close() + elif more: + input( + "First, please press Enter ONCE in the VAIML process " + "to load the next Failsafe Partition and wait for " + "`waiting for user input`. Then press Enter here." + ) + return + if self.dumper.debug_server: + self.dumper.debug_server.close() + if more: + self.wait_for_next_partition() def _write_run_summary(self, status): """ diff --git a/src/mldebug/client_debug.py b/src/mldebug/client_debug.py index 7b0f522..b4dc938 100644 --- a/src/mldebug/client_debug.py +++ b/src/mldebug/client_debug.py @@ -283,12 +283,22 @@ def print_kernel_functions(self, layer): def dump_layers(self, filename=None): """ Print a text report of every debuggable layer, or write it to filename. + + Later partitions append to an existing file so one path collects them all. """ report = format_layer_report(self.design_info) + name = getattr(self.args, "partition_name", None) + if name: + report = f"{name}\n{report}" if not filename: print(report) return - with open(filename, "w", encoding="utf-8") as fd: + # The first partition of this process truncates. Later ones append. + append = getattr(self.args, "layers_report_started", False) + self.args.layers_report_started = True + with open(filename, "a" if append else "w", encoding="utf-8") as fd: + if append: + fd.write("\n") fd.write(report + "\n") print(f"[INFO] Layer report written to {filename}") diff --git a/src/mldebug/input_parser.py b/src/mldebug/input_parser.py index cbaf530..af78f8b 100644 --- a/src/mldebug/input_parser.py +++ b/src/mldebug/input_parser.py @@ -6,7 +6,6 @@ """ from dataclasses import dataclass -from pathlib import Path import glob import json @@ -15,6 +14,7 @@ import subprocess import re +from mldebug.aie_overlay import Overlay from mldebug.arch import ( load_aie_arch, resolve_variant, @@ -100,6 +100,13 @@ def create_run_flags(args, subgraph_path: str, fsp: str, fsp_execution_order: li args.external_buffer_id = args.x2_folder_path + "/external_buffer_id.json" args.subgraph_name = None + # set_device writes the base device into args.device and treats a later + # non-empty value as an explicit -d. Put the original -d back (None when + # the user omitted it) so t20/t10 are not resolved as telluride. + if not hasattr(args, "device_arg"): + args.device_arg = args.device + args.device = args.device_arg + set_device(args) set_coredump_overlay(args) set_aie_scc(args, subgraph_path) @@ -623,49 +630,243 @@ def get_failsafe_partitions(subgraph_path: str) -> list[str]: return result -def get_subgraph(args) -> tuple[str, Subgraph]: +def _partition_index(name: str) -> int: + """Numeric suffix of a vaiml_par_ directory name.""" + match = re.search(r"(\d+)$", name) + if not match: + raise ValueError(f"Invalid partition name format: {name}") + return int(match.group(1)) + + +def _is_npu_subgraph(folder_path: str) -> bool: """ - Determines if the design is a single-subgraph design or finds the subgraph specified in vitisai_config.json. + True when the subgraph has AIE compiler output. - Args: - args: Argument object containing at least vaiml_folder_path. + CPU partitions have neither an AIE work directory nor an AIE call order. + """ + if os.path.isdir(os.path.join(folder_path, "0", "aiecompiler", "Work")): + return True + if os.path.isfile(os.path.join(folder_path, "0", "buffer_info.json")): + return True + info_path = os.path.join(folder_path, "partition-info.json") + if not os.path.isfile(info_path): + return False + with open(info_path, "r", encoding="utf-8") as f: + data = json.load(f) + return "aie_partition_call_order" in data - Returns: - Tuple[str, Subgraph]: Model folder name and the relevant Subgraph instance. - Raises: - RuntimeError: If multiple subgraphs are found and none is specified, or if none are found. +def fnv1a32(name: str) -> int: + """FNV-1a 32-bit hash of a kernel name. Matches the halt plugin.""" + digest = 2166136261 + for byte in name.encode("utf-8"): + digest ^= byte + digest = (digest * 16777619) & 0xFFFFFFFF + return digest + + +def partition_kernel_name(model_folder, subgraph_name, subgraph_path, fsp, fsp_order) -> str: """ - vaiml_folder_path = args.vaiml_folder_path - model_folder_name, subgraphs = return_all_subgraphs(vaiml_folder_path) - cfg_file = f"{vaiml_folder_path}/vitisai_config.json" + Name the halt plugin hashes into Performance_Counter0. - if Path(cfg_file).exists(): - with open(cfg_file, "r", encoding="utf-8") as f: - data = json.load(f) - vaiml_config = None - for pas in data["passes"]: - if "vaiml_config" in pas: - vaiml_config = pas["vaiml_config"] - vaiml_subgraphs = vaiml_config.get("include_subgraphs") - if vaiml_subgraphs: - # If the include_subgraphs option is present, make sure only one subgraph is present - if len(vaiml_subgraphs) != 1: - raise RuntimeError( - "Error: Multiple subgraphs found. " - "Please specify the partition by using include_subgraphs " - "flag in vaiml_config in vitisai_config.json" - ) - return model_folder_name, Subgraph( - folder_path=f"{vaiml_folder_path}/{model_folder_name}/{vaiml_subgraphs[0]}", - name=vaiml_subgraphs[0], + flexmlrt-hsi.json records it as aie_kernel_name. The folder name is not + always that string: hyphens in the model directory become underscores. + """ + hsi_path = os.path.join(subgraph_path, fsp, "flexmlrt-hsi.json") + if os.path.isfile(hsi_path): + with open(hsi_path, "r", encoding="utf-8") as f: + name = json.load(f).get("aie_kernel_name") + if name: + return name + name = f"{model_folder}_{subgraph_name}" + if list(fsp_order) != ["0"]: + name = f"{name}_part_{fsp}" + return name + + +def specified_subgraph(vaiml_folder_path: str) -> str | None: + """ + The single subgraph named by include_subgraphs, or None. + + None means the user did not pin a partition. More than one name is rejected. + """ + cfg_file = os.path.join(vaiml_folder_path, "vitisai_config.json") + if not os.path.isfile(cfg_file): + return None + with open(cfg_file, "r", encoding="utf-8") as f: + data = json.load(f) + for pas in data.get("passes", []): + vaiml_config = pas.get("vaiml_config") + if not vaiml_config: + continue + names = vaiml_config.get("include_subgraphs") + if not names: + return None + if len(names) != 1: + raise RuntimeError( + "Error: Multiple subgraphs found. " + "Please specify the partition by using include_subgraphs " + "flag in vaiml_config in vitisai_config.json" + ) + return names[0] + return None + + +def _buffer_layout(buffer_info_file: str): + """(batches, stamps, nrow, ncol) from buffer_info, matching LayerInfo.""" + with open(buffer_info_file, encoding="utf-8") as fd: + data = json.load(fd) + meta = data.get(".meta", {}) + overlay_stamps, nrow, ncol = meta.get("layout") or [1, 4, 4] + batches = meta.get("device_batch_size", 1) or 1 + stamps = meta.get("max_stamps_used") + group = meta.get("max_stamp_group_size", 1) or 1 + if not stamps: + layers = data.get("layers") or {} + if layers: + widest = max(lyr.get("no_of_stamps", 1) for lyr in layers.values()) + stamps = max(1, widest // batches) + else: + stamps = overlay_stamps + return batches, max(1, stamps // group), nrow, ncol + + +def _candidate_core_tiles(args, runs): + """Union of core tiles across the partitions that might be halted.""" + tiles = [] + seen = set() + for _name, folder, fsp, _order in runs: + info = os.path.join(folder, fsp, "buffer_info.json") + if not os.path.isfile(info): + continue + # multistamp keeps replicas that the runtime view collapses. + overlay = Overlay( + args.aie_iface, _buffer_layout(info), overlay=args.overlay, multistamp=True + ) + for tile in overlay.get_tiles(args.aie_iface.AIE_TILE_T, raw=True): + if tile not in seen: + seen.add(tile) + tiles.append(tile) + return tiles + + +def _uniform_counter(values, label, args): + """The one value every core holds, or exit if the tiles disagree.""" + distinct = set(values.values()) + if len(distinct) != 1: + for (col, row), value in values.items(): + LOGGER.log(f"[INFO] Core ({col},{row}) {label} 0x{value:08x}") + LOGGER.log(f"[ERROR] {label} differs across core tiles.") + cleanup_and_exit(args, 1) + return distinct.pop() + + +def select_halted_partition(args, runs, model_folder): + """ + Read the halt plugin's counters and return the matching partition. + + Performance_Counter0 is the FNV-1a hash of the halted partition's kernel + name. Performance_Counter1 is the halt count: 0 when the runtime halts only + once, otherwise 1 for the first halt and one higher for each later halt on + this context. Call this before anything unhalts the cores. Logs every hash + comparison. Exits when the tiles disagree or no name matches. + + Returns: + (run, halt_count). run is (name, folder, fsp, order). + """ + # Device and register map come from this partition. The counters live on + # the cores, so any candidate's arch is enough to address them. + sample = runs[0] + create_run_flags(args, sample[1], sample[2], sample[3]) + tiles = _candidate_core_tiles(args, runs) + if not tiles: + LOGGER.log("[ERROR] No core tiles found to read the halt counters.") + cleanup_and_exit(args, 1) + + ctx, pid = check_hw_context(args) + regs = args.aie_iface.Core_registers + offsets = { + "Performance_Counter0": regs["PERF_CNTR_0"], + "Performance_Counter1": regs["PERF_CNTR_1"], + } + read = {name: {} for name in offsets} + config = BackendConfig( + tiles=tiles, + ctx_id=ctx, + pid=pid, + device=args.device, + sub_device=getattr(args, "sub_device", None) or args.device, + args=args, + ) + backend = create_backend(args.backend, config) + try: + for col, row in tiles: + for name, offset in offsets.items(): + try: + read[name][(col, row)] = backend.read_register(col, row, offset) & 0xFFFFFFFF + except Exception as err: # pylint: disable=broad-except + LOGGER.log( + f"[ERROR] Failed to read {name} at ({col},{row}): " + f"{type(err).__name__}: {err}" ) - break + cleanup_and_exit(args, 1) + finally: + del backend + + observed = _uniform_counter(read["Performance_Counter0"], "Performance_Counter0", args) + halt_count = _uniform_counter(read["Performance_Counter1"], "Performance_Counter1", args) + LOGGER.log( + f"[INFO] Performance_Counter0 on {len(tiles)} core tiles is 0x{observed:08x}, " + f"halt count {halt_count}" + ) - if len(subgraphs) > 1: - raise RuntimeError( - "Error: Multi-partition design detected. Specify a partition in vitisai_config.json" + matched = None + for run in runs: + name, folder, fsp, order = run + kernel = partition_kernel_name(model_folder, name, folder, fsp, order) + digest = fnv1a32(kernel) + same = digest == observed + LOGGER.log( + f"[INFO] Compare {kernel} hash 0x{digest:08x} " + f"{'matches' if same else 'does not match'} register 0x{observed:08x}" ) - if len(subgraphs) == 0: + if same: + if matched is not None: + LOGGER.log("[ERROR] More than one partition matches Performance_Counter0.") + cleanup_and_exit(args, 1) + matched = run + if matched is None: + LOGGER.log( + f"[ERROR] No partition matches Performance_Counter0 0x{observed:08x}." + ) + cleanup_and_exit(args, 1) + kernel = partition_kernel_name( + model_folder, matched[0], matched[1], matched[2], matched[3] + ) + LOGGER.log(f"[INFO] Halted partition is {kernel}") + return matched, halt_count + + +def get_subgraphs(args) -> tuple[str, list[Subgraph]]: + """ + Return every NPU subgraph, sorted by numeric suffix. + + CPU partitions are left out. On hardware the caller selects which of these + is halted from Performance_Counter0 instead of walking the list in order. + + Args: + args: Argument object containing at least vaiml_folder_path. + + Returns: + Tuple[str, list[Subgraph]]: Model folder name and NPU subgraphs. + + Raises: + RuntimeError: If no NPU partition is found. + ValueError: If a subgraph name has no numeric suffix. + """ + model_folder_name, subgraphs = return_all_subgraphs(args.vaiml_folder_path) + npu = [s for s in subgraphs if _is_npu_subgraph(s.folder_path)] + if not npu: raise RuntimeError("Error: No partition found in the input model folder") - return model_folder_name, subgraphs[0] + npu.sort(key=lambda s: _partition_index(s.name)) + return model_folder_name, npu diff --git a/src/mldebug/interactive_controller.py b/src/mldebug/interactive_controller.py index 89d51df..3d87c6e 100644 --- a/src/mldebug/interactive_controller.py +++ b/src/mldebug/interactive_controller.py @@ -157,26 +157,39 @@ def continue_execution(self): """ Continue execution until the next manual breakpoint or to the end of design. - Handles Failsafe Partition (FSP) usage for VAIML compilation. + When another NPU partition follows, the final continue releases the cores + and waits for the driver's debug halt at the start of that partition. A + pinned subgraph (include_subgraphs) keeps the legacy flow: arm a + lock-acquire breakpoint and ask the user to load the next partition. """ if self.args.aie_only: print("This Functionality is disabled for aie-only debug.") return - is_fsp = self.args.vaiml_folder_path and not self.args.last_fsp + is_next = self.args.vaiml_folder_path and not getattr(self.args, "last_fsp", True) + legacy = getattr(self.args, "legacy_fsp", False) if self.state.continue_to_finish: print("Running AIE to end") - for sid, impl in enumerate(self.impls): - impl.continue_aie() - if is_fsp: + if is_next and legacy: + for sid, impl in enumerate(self.impls): + impl.continue_aie() self.aie_utls[sid].set_fsp_breakpoint() - if is_fsp: print( "First, please press Enter ONCE in the VAIML process" " to load the next Failsafe Partition, and wait for " "`waiting for user input`. Then press q here." ) return + if is_next: + # skip_iter2's last layer already released the cores once. + if not self.args.run_flags.skip_iter2: + for utl in self.aie_utls: + utl.initialize_stamp() + self.runner.wait_for_next_partition() + print("Next partition is debug-halted. Quit this session to debug it.") + return + for impl in self.impls: + impl.continue_aie() sys.exit(0) if not self.state.get_current_layer(): @@ -211,12 +224,14 @@ def continue_execution(self): return if self.state.continue_to_finish: - fsp_text = "" - if is_fsp: - fsp_text = " or to load the next Failsafe Partition" + next_text = "" + if is_next and legacy: + next_text = " or to load the next Failsafe Partition" + elif is_next: + next_text = ", then wait for the next partition" print( f"Reached Final iteration : {ta_itr} of layer : {ta_layer}. " - f"Press c/continue to Run AIE to end and exit{fsp_text}" + f"Press c/continue to Run AIE to end and exit{next_text}" ) else: print() diff --git a/src/mldebug/mldebug_cli.py b/src/mldebug/mldebug_cli.py index 6ebbcda..f5cc485 100644 --- a/src/mldebug/mldebug_cli.py +++ b/src/mldebug/mldebug_cli.py @@ -27,12 +27,22 @@ from mldebug.input_parser import ( check_hw_context, check_registry_keys, - get_subgraph, + get_subgraphs, get_failsafe_partitions, create_run_flags, + partition_kernel_name, + select_halted_partition, + specified_subgraph, ) from mldebug.interactive_prompt import InteractivePrompt -from mldebug.utils import LOGGER, setup_logger, close_logger, is_windows, version_string +from mldebug.utils import ( + LOGGER, + cleanup_and_exit, + close_logger, + is_windows, + setup_logger, + version_string, +) def _apply_unsupported_kernels_from_args(args): @@ -157,6 +167,18 @@ def debug(args, timestamp, subgraph_name=None, fsp="0", folder_name=None): output_dir = f"{folder_name}_{timestamp}/{subgraph_name}/{fsp}" args.subgraph_name = subgraph_name args.top_output_dir = f"{folder_name}_{timestamp}" + # The halt plugin and the driver logs use aie_kernel_name. That string + # is not always _: hyphens in the folder become + # underscores. Fall back to the folder form when the HSI file has no name. + hsi = getattr(args, "flexmlrt_hsi", None) + subgraph_path = os.path.dirname(os.path.dirname(hsi)) if hsi else "" + args.partition_name = partition_kernel_name( + folder_name, + subgraph_name, + subgraph_path, + fsp, + getattr(args, "fsp_execution_order", ["0"]), + ) else: output_dir = f"output_{time.strftime('%m%d%H%M%S')}" args.top_output_dir = output_dir @@ -456,26 +478,103 @@ def app(): print("Argument check failed") return - subgraph_name = None - subgraph_folder_path = "" - model_folder_name = None - fsp_execution_order = ["0"] + # create_run_flags restores this before every set_device. The resolved base + # device must not be fed back in as if the user had passed -d. + args.device_arg = args.device + model_folder_name = None + # One entry per NPU partition: (subgraph name, folder, fsp, that subgraph's order). + runs = [(None, "", "0", ["0"])] + pinned = None if args.vaiml_folder_path: - model_folder_name, subgraph = get_subgraph(args) - subgraph_name, subgraph_folder_path = subgraph.name, subgraph.folder_path - fsp_execution_order = get_failsafe_partitions(subgraph_folder_path) + model_folder_name, subgraphs = get_subgraphs(args) + pinned = specified_subgraph(args.vaiml_folder_path) + if pinned: + subgraphs = [s for s in subgraphs if s.name == pinned] + if not subgraphs: + raise RuntimeError(f"Error: Specified partition {pinned} was not found") + # -s and --dump-aie-status with one subgraph keep using its work dir, overlay + # and device. With several to choose from they are raw hardware access: no + # partition metadata and no halt counters. + if not (args.aie_only and len(subgraphs) > 1): + runs = [] + for subgraph in subgraphs: + order = get_failsafe_partitions(subgraph.folder_path) + for fsp in order: + runs.append((subgraph.name, subgraph.folder_path, fsp, order)) + + # The counters are only meaningful on live hardware with more than one + # partition to choose from. A pinned partition, a single partition, standalone + # mode, and offline backends keep a single session. + identify = ( + args.backend == "xrt" + and pinned is None + and len(runs) > 1 + and not args.aie_only + and not args.dump_aie_status + and not args.dump_layers + ) + # include_subgraphs pins one subgraph: its parts keep the legacy FSP flow + # (arm a breakpoint, prompt the user) instead of waiting for the plugin's halt. + args.legacy_fsp = pinned is not None + if len(runs) > 1 and not identify and not args.legacy_fsp: + LOGGER.log( + "Running NPU partitions in order: " + + ", ".join(name for name, _folder, _fsp, _order in runs) + ) timestamp = time.strftime("%m%d%H%M%S") registry_checked = False - for fsp in fsp_execution_order: + + def launch(run, last): + """Debug one partition. last means do not wait for another halt.""" + nonlocal registry_checked + subgraph_name, subgraph_folder_path, fsp, fsp_execution_order = run create_run_flags(args, subgraph_folder_path, fsp, fsp_execution_order) + args.last_fsp = last if not registry_checked and args.backend == "xrt" and is_windows(): check_registry_keys(args, args.device == AIE_DEV_NPU3) registry_checked = True debug(args, timestamp, subgraph_name, fsp, model_folder_name) - if args.dump_aie_status or args.dump_layers: - break + + if identify: + if is_windows(): + sample = runs[0] + create_run_flags(args, sample[1], sample[2], sample[3]) + check_registry_keys(args, args.device == AIE_DEV_NPU3) + registry_checked = True + # Cores are still halted. Read both counters before debug() releases them. + # Counter 1 is 0 when the plugin halts only the first run. That selects the + # manual advance, starting at the halted partition. Any higher count is one + # step of a sequence that may repeat a partition, so follow it until the + # context goes away rather than stopping after len(runs) halts. + chosen, halt_count = select_halted_partition(args, runs, model_folder_name) + if halt_count == 0: + LOGGER.log( + "[INFO] Halt count is 0. The runtime halts once; " + "later partitions use the manual advance." + ) + args.legacy_fsp = True + tail = runs[runs.index(chosen):] + for index, run in enumerate(tail): + launch(run, index == len(tail) - 1) + else: + while True: + launch(chosen, False) + previous = halt_count + chosen, halt_count = select_halted_partition(args, runs, model_folder_name) + expected = previous + 1 + if halt_count != expected: + LOGGER.log( + f"[ERROR] Performance_Counter1 is {halt_count}, expected {expected}. " + "A partition halt was missed." + ) + cleanup_and_exit(args, 1) + else: + for index, run in enumerate(runs): + launch(run, index == len(runs) - 1) + if args.dump_aie_status: + break # End Debug close_logger()