libtpu.sdk.debug 中的偵錯回呼

Python 偵錯回呼提供非同步機制,可在 TPU 執行期間直接從 libtpu 接收執行階段診斷。

當 TPU 發生硬體停滯、同步逾時、數值異常或裝置當機時,libtpu 會叫用已註冊的回呼,並提供結構化診斷資料。這樣一來,訓練或推論指令碼就能記錄事件、記錄程式狀態或觸發快訊,不必剖析控制台記錄或輪詢裝置暫存器。

修課條件

您需要 libtpu 0.0.46 以上版本,才能使用偵錯回呼。請安裝或升級,然後檢查版本:

pip install --upgrade libtpu
python3 -c "import importlib.metadata as m; print(m.version('libtpu'))"

註冊回呼不需要額外設定。不過,根據預設,系統只會回報停滯事件 (STALL_EVENT)。其他事件則必須啟用檢測功能才會回報;必要標記列在「支援的事件」的「觸發條件」下方。

使用指南

建立回呼函式

定義事件發生時要叫用的函式。回呼函式必須接受兩個對應引數:payload 和 metadata,並傳回 None。

事件會透過對應引數傳遞至回呼:

  • payload:包含大型執行階段構件,例如 NumPy ndarray (literal)、原始構件位元組 (serialized_artifact) 或剖析後的各核心狀態傾印 (core_states)。
  • metadata:包含輕量診斷屬性,例如布林事件標記 (is_sflag_timeout、is_sc_mismatch)、來源位置 (core_location) 和標記 (user_tag)。

這兩種對應都沒有事件類型欄位:本指南中的事件名稱 (例如 SFLAG_TIMEOUT) 只是標籤。根據現有的鍵來識別事件,例如中繼資料中的 is_sflag_timeout 或酬載中的 core_states,如範例工作流程所示。

註冊 (和取消註冊) 函式

您必須先使用 **libtpu.sdk.debug.register_debug_callback**(callback_fn) -> int 註冊回呼函式,才能執行工作負載:

  • 引數:callback_fn,可呼叫函式,接受 (payload: Mapping[str, Any], metadata: Mapping[str, Any]) 並傳回 None
  • 傳回:代表註冊控制代碼的整數 callback_id。如果註冊失敗,則會引發 RuntimeError。

執行完成或發生錯誤後,請務必使用 **libtpu.sdk.debug.unregister_debug_callback**(callback_id: int) -> None 取消註冊先前註冊的回呼:

  • callback_id:register_debug_callback 傳回的整數控制代碼
from typing import Any, Mapping
import libtpu.sdk.debug as tpu_debug

# Define your callback function
def callback_fn(
    payload: Mapping[str, Any], metadata: Mapping[str, Any]
) -> None:
  ...


def main():
  # Register the callback before starting the execution loop
  callback_id = tpu_debug.register_debug_callback(callback_fn)

  try:
    # Training or inference loop runs here
    pass
  finally:
    # Always unregister when finished or on error
    tpu_debug.unregister_debug_callback(callback_id)
if __name__ == "__main__":
  main()

  • 執行緒安全:回呼會在 libtpu 管理的背景執行緒上執行。在 Python 回呼中變更的任何狀態,都應受到適當的執行緒同步處理保護,或限制為執行緒安全資料結構。
  • 避免回呼造成封鎖:請勿在回呼中執行封鎖作業或長時間運算。如果需要大量處理,請將事件推送至佇列。佇列用於個別背景工作執行緒。回呼在執行時會保留 Python GIL,因此緩慢的回呼也會封鎖其他 Python 執行緒。
  • 例外狀況:回呼中引發的例外狀況會由 libtpu 擷取並記錄,不會傳播至程式。

支援的事件

偵錯回呼機制支援下列事件類型。

事件類型 觸發條件 metadata 欄位 payload 欄位
SFLAG_TIMEOUT TensorCore 等待同步旗標 (sflag) 的時間超過逾時限制,該旗標由 DMA (晶片內、晶片間或主機到晶片) 和屏障使用。--xla_tpu_debug_sflag_wait_timeout_ms 必須大於 0,且須提供 --xla_tpu_debug_sflag_wait_shalt_on_detection=false 和 --xla_tpu_enable_log_recorder=true。請參閱「TPU 停止運作:同步旗標等待逾時」。 is_sflag_timeout:True
user_tag:str
core_location:str
literal: np.ndarray
expected_sflag_value: int
latest_sflag_value_seen: int
progress_tracker_current_depth: int
progress_tracker_meta_id: int
progress_tracker_levels: list[tuple[int, int]]
unfinished_send_sflags_count: int
unfinished_send_sflags: list[int]
errors: list[str]
BOUNDS_CHECK_FAIL 保留;不會在 libtpu 0.0.46 中發出。邊界檢查失敗則會回報在程式記錄中。 is_bounds_check_fail:True
user_tag:str
core_location:str
常值:np.ndarray (違規索引/偏移)
STALL_EVENT TpuDiagnosticCoordinator 偵測到停滯 (例如看門狗或 sflag 逾時),或收到手動觸發條件,並擷取硬體狀態快照。預設為開啟。首次觸發後約 10 秒,每部主機會回報一次,之後最多每 15 分鐘回報一次。請參閱「TPU 停止回應診斷」。 source:int
host_id: int
description:str (選用)
timeout_ms:int (選用)
core_location:str (一律為「unknown」)
launch_id:int (選用)
core_states:dict (如果剖析失敗,則不會顯示)
serialized_artifact:位元組
core_states_parsing_error:True (僅限剖析失敗時)
SC_MISMATCH SparseCore 嵌入查詢或散佈/收集不相符。 is_sc_mismatch:True
user_tag:str
core_location:str
literal: np.ndarray (若已啟用)
SDC_NAN_INF 運算產生或收到非預期的 NaN 或 Inf 值。 contains_nan:bool
contains_inf:bool
is_input_nan_or_inf:bool
deduplicated_names:list[str] core_location:str is_collective_hlo:bool is_tpu_custom_call:bool
user_tag:str (選填)
literal: np.ndarray (若已啟用)
SDC_OUTPUT_MISMATCH 備援執行檢查發現輸出內容不符。 is_input_mismatch:bool
deduplicated_names:list[str]
core_location:str
is_collective_hlo:bool
is_tpu_custom_call:bool
user_tag:str (選填)
literal: np.ndarray (若已啟用)
HLO_LOGGER 已完成執行編譯指令,並啟用記錄功能。 instruction_name:str
user_tag:str
extra_args:list[str] (選用)
core_location:str
常值:np.ndarray (張量值)
FUSION_DEBUG 已執行使用偵錯檢測編譯的融合指令。 instruction_name:str
user_tag:str
core_location:str
duration_cycles:int
字面值:np.ndarray (如有擷取)
CORE_DUMP 裝置因嚴重錯誤而停止運作後,執行階段擷取了硬體狀態快照 (核心 dump)。請參閱「TPU 當機:分析核心 dump」。 instruction_name:str (選用)
core_dump_tc_values:list[dict]
core_dump_sc_values:list[dict]
core_location:str
(空白)

STALL_EVENT 涵蓋在 TPU 停止回應診斷中,包括如何觸發執行中工作的快照。每個 SFLAG_TIMEOUT 事件也會計為停滯觸發條件,因此大約 10 秒後,同一個主機會出現 STALL_EVENT 和 source=3 (SFLAG_TIMEOUT)。

如要進一步瞭解事件結構,請參閱「參考資料」一節。

工作流程範例

以下範例指令碼顯示完整的工作流程:如何在訓練指令碼中註冊回呼、處理常見事件,以及在完成後乾淨地取消註冊。

import sys
from typing import Any, Mapping
import libtpu.sdk.debug as tpu_debug


def on_tpu_debug_event(
    payload: Mapping[str, Any], metadata: Mapping[str, Any]
) -> None:
  """Called asynchronously by libtpu when an event occurs."""


  # 1. Sync Flag Timeouts
  if metadata.get("is_sflag_timeout"):
    tag = metadata.get("user_tag", "N/A")
    core = metadata.get("core_location", "unknown")
    print(
        f"[TPU TIMEOUT] Core {core} timed out waiting on sync flag (tag: {tag})",
        file=sys.stderr,
        flush=True,
    )


  # 2. Out-of-bounds memory access (reserved; not emitted in libtpu 0.0.46)
  elif metadata.get("is_bounds_check_fail"):
    tag = metadata.get("user_tag", "N/A")
    core = metadata.get("core_location", "unknown")
    bad_offset = payload.get("literal")
    print(
        f"[TPU BOUNDS ERROR] Bounds violation at {core} (offset: {bad_offset}, tag: {tag})",
        file=sys.stderr,
        flush=True,
    )


  # 3. Hardware Stalls
  elif metadata.get("source") is not None or "core_states" in payload:
    host_id = metadata.get("host_id", "N/A")
    desc = metadata.get("description", "")
    source = metadata.get("source")  # 0 (UNKNOWN) for a manual trigger
    print(
        f"[TPU STALL] Host {host_id}, source {source}: {desc}",
        file=sys.stderr,
        flush=True,
    )


    core_states = payload.get("core_states", {})
    for core_id, state in core_states.items():
      for seq in state.get("sequencer_info", []):
        pc = seq.get("pc", 0)
        hlo_op = seq.get("hlo_location", "N/A")
        print(
            f"  -> Core {core_id} at PC {hex(pc)} in {hlo_op}",
            file=sys.stderr,
            flush=True,
        )


  # 4. Numerical Anomalies (NaN / Inf)
  elif metadata.get("contains_nan") or metadata.get("contains_inf"):
    ops = ", ".join(metadata.get("deduplicated_names", []))
    core = metadata.get("core_location", "unknown")
    is_input = metadata.get("is_input_nan_or_inf", False)
    kind = "/".join(
        name
        for key, name in (("contains_nan", "NaN"), ("contains_inf", "Inf"))
        if metadata.get(key)
    )
    print(
        f"[TPU NUMERICS] {kind} detected at {core} in ops: {ops} (input already"
        f" {kind}: {is_input})",
        file=sys.stderr,
        flush=True,
    )


  # 5. Everything else (HLO logger, fusion, SDC mismatch, SparseCore, core dump)
  else:
    print(f"[TPU EVENT] {dict(metadata)}", file=sys.stderr, flush=True)




def main():
  # Register the callback before starting the execution loop
  callback_id = tpu_debug.register_debug_callback(on_tpu_debug_event)
  print(f"Registered debug callback ID {callback_id}", flush=True)


  try:
    # Training or inference loop runs here
    pass
  finally:
    # Always unregister when finished or on error
    tpu_debug.unregister_debug_callback(callback_id)
    print(f"Unregistered debug callback ID {callback_id}", flush=True)


if __name__ == "__main__":
  main()

參考資料:事件結構

同步旗標逾時 (SFLAG_TIMEOUT)

# metadata
{
    "is_sflag_timeout": True,
    "user_tag": "Wait timeout on sflag {...} after 180000 milliseconds, ...",  # Timeout message
    "core_location": "core 0",
}

# payload
{
    "literal": np.array([...], dtype=np.int32),  # Optional array if literal capture is enabled
    "expected_sflag_value": 16,  # Target sync flag value waited on
    "latest_sflag_value_seen": 15,  # Last sync flag value seen before timeout
    # Optional: present when --xla_tpu_enable_progress_tracker > 0
    "progress_tracker_current_depth": 1,
    "progress_tracker_meta_id": -1,  # LLO metadata ID (-1 if unset)
    "progress_tracker_levels": [  # (iteration, counter) per level; (-1, -1)  if unused
        (0, 2),
        (-1, -1),
    ],
    # Optional: present when --xla_tpu_enable_dma_send_sync_flag_tracker=true
    "unfinished_send_sflags_count": 1,
    "unfinished_send_sflags": [53, -1, -1, -1, -1],  # -1 for unused slots
    # "errors": ["..."],  # Only if decomposing literal fails; some fields above may then be absent
}

違反記憶體界限 (BOUNDS_CHECK_FAIL)

# Reserved: not emitted in libtpu 0.0.46.
# metadata
{
    "is_bounds_check_fail": True,
    "user_tag": "bounds_check",
    "core_location": "core 1",
}

# payload
{
    "literal": np.array(
        [1048576], dtype=np.int64
    ),  # Offending memory index or offset
}

TPU 停滯或停止運作 (STALL_EVENT)

# metadata
{
    # StallSource enum: UNKNOWN=0, PJRT_WATCHDOG=1, HAL_WATCHDOG=2,
    #                   SFLAG_TIMEOUT=3, CORE_STALL=4, HARDWARE_WEDGE=5
    "source": 1,
    "host_id": 0,  # -1 for a manual trigger in libtpu ≤ 0.0.50
    "description": "...",  # Optional: summary of the triggers
    "timeout_ms": 300000,  # Optional
    "core_location": "unknown",  # Not set for stall events
    "launch_id": 12345,  # Optional: runtime launch identifier
}

# payload
{
    "core_states": {
        0: {  # Keyed by integer core ID
            "core_id": {
                "global_core_id": 0,
                "chip_id": 0,
                "core_on_chip": {"type": "TPU_CORE_TYPE_TENSOR_CORE", "index": 0},
            },
            "sequencer_info": [{
                "sequencer_type": "SEQUENCER_TYPE_V",
                "sequencer_index": 0,
                "pc": 4260,  # Program counter (0x10a4)
                "tag": 12,
                "tracemark": 0,
                "program_id": 100,
                "run_id": 1,
                "hlo_location": "collective-permute.4",
                "hlo_detailed_info": "collective-permute",
            }],
            "xdb_server_running": True,
            "program_fingerprint": b"...",
            "launch_id": 12345,
            "queued_program_info": [
                {"run_id": 2, "launch_id": 12346, "program_fingerprint": b"..."}
            ],
            "error_message": "...",
        }
    },
    "serialized_artifact": b"...",  # Raw bytes of AllCoreStateSummaries
    # "core_states_parsing_error": True,  # Only if parsing fails; core_states is then absent
}

SparseCore 不相符 (SC_MISMATCH)

# metadata
{
    "is_sc_mismatch": True,
    "user_tag": "embedding_scatter",
    "core_location": "core 0",
}

# payload
{
    "literal": np.array([...]),  # Optional array if literal capture is enabled
}

偵測到 NaN 和 Inf (SDC_NAN_INF)

# metadata
{
    "contains_nan": True,
    "contains_inf": False,
    "is_input_nan_or_inf": False,  # True if input was already NaN; False if op produced it
    "deduplicated_names": ["layer1/matmul", "layer1/bias_add"],
    "is_collective_hlo": False,
    "is_tpu_custom_call": False,
    "user_tag": "forward_pass",  # Optional: instruction tag
    "core_location": "core 0",
}

# payload
{
    "literal": np.array([...]),  # Optional tensor literal if captured
}

SDC HLO 輸出不符 (SDC_OUTPUT_MISMATCH)

# metadata
{
    "core_location": "core 0",  # Core where mismatch was detected
    "deduplicated_names": ["conv.1"],  # Involved HLO instruction names
    "is_input_mismatch": False,  # True if input operands already mismatched
    "is_collective_hlo": False,  # True if operation was a collective op
    "is_tpu_custom_call": False,  # True if operation was a custom call
    "user_tag": "mismatch_tag",  # Optional: tag if specified
}
# payload
{
    "literal": np.array([...]),  # Optional array if literal capture is enabled
}

HLO 記錄器事件 (HLO_LOGGER)

# metadata
{
    "core_location": "core 0",  # Physical or logical core location
    "user_tag": "my_tag",  # User-defined tag on the HLO instruction
    "instruction_name": "custom-call.1",  # Name of the HLO instruction
    "tag": "hlo_logger",  # Compiler log record tag
    "extra_args": ["arg1", "arg2"],  # Optional: list of extra arguments
}

# payload
{
    "literal": np.array([...]),  # Logged tensor data as a NumPy ndarray
}

Fusion 偵錯事件 (FUSION_DEBUG)

# metadata
{
    "core_location": "core 0",
    "user_tag": "fusion_trace",
    "instruction_name": "fused_computation.3",  # Fused HLO instruction name
}

# payload
{
    "duration_cycles": 14250,  # Execution duration in hardware cycles
    "literal": np.array([...]),  # Optional tensor values if captured
}

硬體狀態快照 (CORE_DUMP)

# metadata
{
    "core_location": "core 0",
    "instruction_name": "dense_layer.1",  # Optional: associated HLO instruction
    "core_dump_tc_values": [
        {"title": "PC", "values": ["0x10a0", "0x10b4"]},
        {"title": "STATUS", "values": ["HALTED"]},
    ],
    "core_dump_sc_values": [
        {
            "scs_info": [{"title": "SCS_STATE", "values": ["IDLE"]}],
            "tile_info": [{"title": "TILE_ERR", "values": ["0x0"]}],
            "misc_info": [{"title": "INFO", "values": ["OK"]}],
        }
    ],
}

# payload
{}  # Empty: core dump values are in metadata