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 콜백에서 변경된 모든 상태는 적절한 스레드 동기화로 보호되거나 스레드 안전 데이터 구조로 제한되어야 합니다. - 콜백을 비차단 상태로 유지: 콜백 내에서 차단 작업이나 장기 실행 계산을 실행하지 마세요. 과도한 처리가 필요한 경우 이벤트를 별도의 작업자 스레드를 위해 queue.Queue로 푸시합니다. 콜백은 실행되는 동안 Python GIL을 보유하므로 느린 콜백은 다른 Python 스레드도 차단합니다.
- 예외: 콜백 내에서 발생한 예외는
libtpu에 의해 포착되고 로깅되며 프로그램에 전파되지 않습니다.
지원되는 이벤트
디버그 콜백 메커니즘에서 지원하는 이벤트 유형은 다음과 같습니다.
| 이벤트 유형 | 트리거 조건 | 메타데이터 필드 | 페이로드 필드 |
|---|---|---|---|
| SFLAG_TIMEOUT | DMA(칩 내, 칩 간 또는 호스트-칩) 및 배리어에서 사용하는 동기화 플래그(sflag)에 대한 TensorCore 대기가 제한 시간을 초과했습니다. --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 |
리터럴: 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(항상 '알 수 없음') 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 | 기기가 치명적인 오류로 인해 중지된 후 런타임에서 하드웨어 상태 스냅샷(코어 덤프)을 캡처했습니다. TPU 비정상 종료: 코어 덤프 분석을 참조하세요. | instruction_name: str(선택사항) core_dump_tc_values: list[dict] core_dump_sc_values: list[dict] core_location: str |
(비어 있음) |
STALL_EVENT은 실행 중인 작업에서 스냅샷을 트리거하는 방법을 포함하여 TPU 중단 진단에서 다룹니다. 각 SFLAG_TIMEOUT 이벤트는 중단 트리거로도 계산되므로 약 10초 후에 동일한 호스트에서 source=3(SFLAG_TIMEOUT)가 있는 STALL_EVENT가 발생할 것으로 예상됩니다.
이벤트 구조에 대한 자세한 내용은 참조 섹션을 확인하세요.
워크플로 예
다음 예시 스크립트는 전체 워크플로를 보여줍니다. 학습 스크립트에서 콜백을 등록하고, 일반적인 이벤트를 처리하고, 완료 시 완전히 등록 취소하는 방법을 보여줍니다.
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_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