קריאה חוזרת (callback) לניפוי באגים ב-libtpu.sdk.debug

הקריאה החוזרת (callback) לניפוי באגים ב-Python מספקת מנגנון אסינכרוני לקבלת אבחון בזמן ריצה ישירות מ-libtpu במהלך הפעלת ה-TPU.

כשהחומרה נתקעת, כשנגמר הזמן הקצוב לסנכרון, כשיש חריגות מספריות או כשהמכשיר קורס ב-TPU,‏ libtpu מפעיל את פונקציית ה-callback הרשומה עם נתוני אבחון מובְנים. כך סקריפט האימון או ההסקה יכול לתעד אירועים, לתעד את מצב התוכנית או להפעיל התראות בלי לנתח את יומני המסוף או לדגום את אוגרי המכשיר.

דרישות מוקדמות

כדי להשתמש בקריאה חוזרת (callback) לניפוי באגים, צריך את גרסה 0.0.46 ומעלה של libtpu. מתקינים או משדרגים אותה, ואז בודקים את הגרסה:

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

לא צריך לבצע הגדרות נוספות כדי לרשום קריאה חוזרת. עם זאת, כברירת מחדל, המערכת מדווחת רק על אירועי עצירה (STALL_EVENT). כל אירוע אחר מדווח רק אחרי שמפעילים את המכשור שלו. הדגלים הנדרשים מפורטים בקטע תנאי טריגר במאמר אירועים נתמכים.

הנחיות לשימוש

יצירת פונקציית קריאה חוזרת (callback)

מגדירים את הפונקציה שרוצים להפעיל כשמתרחש אירוע. פונקציית הקריאה החוזרת צריכה לקבל שני ארגומנטים של מיפוי: payload ו-metadata, ולהחזיר את None.

האירועים מועברים לקריאה החוזרת (callback) דרך הארגומנטים של המיפוי:

  • ‫payload: מכיל פריטי מידע גדולים שנוצרו בזמן הריצה, כמו מערכים רב-ממדיים של NumPy‏ (literal), בייטים גולמיים של פריטי מידע (serialized_artifact) או קובצי dump מנותחים של מצב לכל ליבה (core_states).
  • ‫metadata: מכיל מאפייני אבחון קלים, כמו דגלי אירועים בוליאניים (is_sflag_timeout, is_sc_mismatch), מיקומי מקור (core_location) ותגים (user_tag).

לאף אחד מהמיפויים אין שדה של סוג אירוע: שמות האירועים במדריך הזה, כמו SFLAG_TIMEOUT, הם תוויות בלבד. מזהים אירוע לפי המפתחות שקיימים, לדוגמה is_sflag_timeout במטא-נתונים או core_states במטען הייעודי (payload), כמו שמוצג בתהליך העבודה לדוגמה.

רישום (וביטול הרישום) של הפונקציה

צריך לרשום את פונקציית הקריאה החוזרת לפני הרצת עומס העבודה באמצעות **libtpu.sdk.debug.register_debug_callback**(callback_fn) -> int:

  • ארגומנט: callback_fn, פונקציה שניתן להפעיל שמקבלת (payload: Mapping[str, Any], metadata: Mapping[str, Any]) ומחזירה None
  • החזרה: מספר שלם callback_id שמייצג את נקודת האחיזה של הרישום. אם הרישום נכשל, מופיעה השגיאה RuntimeError.

תמיד צריך לבטל את הרישום של קריאה חוזרת (callback) שנרשמה בעבר אחרי שהביצוע מסתיים או נכשל, באמצעות **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()

  • בטיחות השרשור: פונקציות ה-callback פועלות בשרשור ברקע שמנוהל על ידי libtpu. כל מצב שמשתנה בקריאה החוזרת (callback) של Python צריך להיות מוגן באמצעות סנכרון מתאים של ה-thread, או להיות מוגבל למבני נתונים מסוג thread-safe.
  • הימנעו מחסימת קריאות חוזרות (callbacks): אל תבצעו פעולות חסימה או חישובים ארוכים בתוך הקריאה החוזרת. אם נדרש עיבוד כבד, צריך להעביר את האירוע ל-queue.Queue ל-Thread עובד נפרד. הקריאה החוזרת (callback) מחזיקה את ה-GIL של Python בזמן שהיא פועלת, כך שקריאה חוזרת איטית חוסמת גם את השרשורים האחרים של Python.
  • חריגים: חריגים שמועלים בתוך ה-callback מזוהים ומתועדים ביומן על ידי libtpu, והם לא מועברים לתוכנית שלכם.

אירועים נתמכים

מנגנון הקריאה החוזרת (callback) לניפוי באגים תומך בסוגי האירועים הבאים.

סוג האירוע תנאי להפעלת הטריגר שדות של מטא-נתונים שדות המטען הייעודי (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 hang: Sync flag wait timeout ‫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
literal: np.ndarray (offending index/offset)
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
literal: 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 נספר גם כטריגר להשהיה, אז צפו לקבל STALL_EVENT עם source=3 (SFLAG_TIMEOUT) מאותו מארח כ-10 שניות לאחר מכן.

בקטע חומר עזר מוסבר בפירוט על מבנה האירועים.

תהליך עבודה לדוגמה

הסקריפט לדוגמה הבא מציג תהליך עבודה מלא: איך לרשום קריאה חוזרת בסקריפט אימון, לטפל באירועים נפוצים ולבטל את הרישום בצורה נקייה בסיום.

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