Le rappel de débogage Python fournit un mécanisme asynchrone permettant de recevoir des diagnostics d'exécution directement depuis libtpu pendant l'exécution de la TPU.
Lorsque des blocages matériels, des délais avant expiration de la synchronisation, des anomalies numériques ou des plantages d'appareil se produisent sur le TPU, libtpu appelle votre rappel enregistré avec des données de diagnostic structurées. Cela permet à votre script d'entraînement ou d'inférence de consigner des événements, d'enregistrer l'état du programme ou de déclencher des alertes sans analyser les journaux de la console ni interroger les registres de l'appareil.
Conditions préalables
Vous devez disposer de libtpu 0.0.46 ou d'une version ultérieure pour le rappel de débogage. Installez-le ou mettez-le à niveau, puis vérifiez la version :
pip install --upgrade libtpu
python3 -c "import importlib.metadata as m; print(m.version('libtpu'))"
L'enregistrement d'un rappel ne nécessite aucune configuration supplémentaire. Toutefois, seuls les événements de blocage (STALL_EVENT) sont signalés par défaut. Tous les autres événements ne sont signalés qu'après l'activation de leur instrumentation. Les options requises sont listées sous Condition de déclenchement dans Événements compatibles.
Consignes d'utilisation
Créer votre fonction de rappel
Définissez la fonction à appeler lorsqu'un événement se produit. Votre fonction de rappel doit accepter deux arguments de mappage : payload et metadata, et renvoyer None.
Les événements sont transmis au rappel via les arguments de mappage :
- payload : contient des artefacts d'exécution volumineux, tels que des ndarrays NumPy (
literal), des octets d'artefact bruts (serialized_artifact) ou des vidages d'état analysés par cœur (core_states). - metadata : contient des attributs de diagnostic légers, tels que des indicateurs d'événement booléens (
is_sflag_timeout,is_sc_mismatch), des emplacements sources (core_location) et des tags (user_tag).
Aucun mappage ne comporte de champ de type d'événement : les noms d'événements de ce guide, tels que SFLAG_TIMEOUT, ne sont que des libellés. Identifiez un événement par les clés présentes, par exemple is_sflag_timeout dans les métadonnées ou core_states dans la charge utile, comme indiqué dans l'exemple de workflow.
Enregistrer (et annuler l'enregistrement de) votre fonction
Vous devez enregistrer la fonction de rappel avant l'exécution de la charge de travail à l'aide de **libtpu.sdk.debug.register_debug_callback**(callback_fn) -> int :
- Argument :
callback_fn, un appelable prenant (payload: Mapping[str, Any], metadata: Mapping[str, Any]) et renvoyantNone - Renvoie : un entier
callback_idreprésentant le handle d'enregistrement. GénèreRuntimeErrorsi l'enregistrement échoue.
Annulez toujours l'enregistrement d'un rappel précédemment enregistré une fois l'exécution terminée ou en cas d'erreur à l'aide de **libtpu.sdk.debug.unregister_debug_callback**(callback_id: int)
-> None :
callback_id: handle entier renvoyé parregister_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()
- Thread safety : les rappels s'exécutent sur un thread d'arrière-plan géré par
libtpu. Tout état modifié dans votre rappel Python doit être protégé par une synchronisation de thread appropriée ou limité aux structures de données thread-safe. - Évitez de bloquer les rappels : n'effectuez pas d'opérations bloquantes ni de calculs de longue durée dans le rappel. Si un traitement lourd est nécessaire, transmettez l'événement à une file d'attente pour un thread de travail distinct. Le rappel contient le GIL Python pendant son exécution. Un rappel lent bloque donc également vos autres threads Python.
- Exceptions : les exceptions générées dans le rappel sont interceptées et consignées par
libtpu. Elles ne sont pas propagées à votre programme.
Événements compatibles
Les types d'événements suivants sont compatibles avec le mécanisme de rappel de débogage.
| Type d'événement | Condition de déclenchement | Champs de métadonnées | Champs de charge utile |
|---|---|---|---|
| SFLAG_TIMEOUT | Un TensorCore en attente d'un flag de synchronisation (sflag), utilisé par les DMA (intra-puce, inter-puce ou hôte-puce) et les barrières, a dépassé le délai avant expiration. Nécessite --xla_tpu_debug_sflag_wait_timeout_ms > 0, --xla_tpu_debug_sflag_wait_shalt_on_detection=false et --xla_tpu_enable_log_recorder=true. Consultez Blocage du TPU : délai d'attente de l'indicateur de synchronisation dépassé. |
is_sflag_timeout : True user_tag : str core_location : str |
littéral : 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 | Réservé ; non émis dans libtpu 0.0.46. Les échecs de vérification des limites sont signalés dans le journal du programme. |
is_bounds_check_fail : True user_tag : str core_location : str |
literal: np.ndarray (index/décalage incriminé) |
| STALL_EVENT | Le TpuDiagnosticCoordinator a détecté un blocage (par exemple, un délai avant expiration du watchdog ou du sflag) ou a reçu un déclencheur manuel, et a capturé des instantanés de l'état du matériel. Activé par défaut. Signalé une fois par hôte environ 10 secondes après le premier déclencheur, puis au maximum une fois toutes les 15 minutes. Consultez Diagnostics de blocage des TPU. | source : int host_id: int description : str (facultatif) timeout_ms : int (facultatif) core_location : str (toujours "unknown") launch_id : int (facultatif) |
core_states : dict (absent en cas d'échec de l'analyse) serialized_artifact : octets core_states_parsing_error : True (uniquement en cas d'échec de l'analyse) |
| SC_MISMATCH | Incompatibilité entre la recherche d'embedding SparseCore et la dispersion/le regroupement. | is_sc_mismatch : True user_tag : str core_location : str |
littéral : np.ndarray (si activé) |
| SDC_NAN_INF | L'opération a généré ou reçu des valeurs NaN ou Inf inattendues. | 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 (facultatif) |
littéral : np.ndarray (si activé) |
| SDC_OUTPUT_MISMATCH | La vérification de l'exécution redondante a détecté des sorties non concordantes. | is_input_mismatch : bool deduplicated_names : list[str] core_location : str is_collective_hlo : bool is_tpu_custom_call : bool user_tag : str (facultatif) |
littéral : np.ndarray (si activé) |
| HLO_LOGGER | L'instruction compilée avec la journalisation activée a terminé son exécution. | instruction_name : str user_tag : str extra_args : list[str] (facultatif) core_location : str |
littéral : np.ndarray (valeurs de Tensor) |
| FUSION_DEBUG | L'instruction fusionnée compilée avec l'instrumentation de débogage a été exécutée. | instruction_name : str user_tag : str core_location : str |
duration_cycles : littéral int : np.ndarray (si capturé) |
| CORE_DUMP | L'environnement d'exécution a capturé un instantané de l'état du matériel (vidage de mémoire) après l'arrêt de l'appareil en raison d'une erreur fatale. Consultez Plantage du TPU : analyser le vidage de mémoire. | instruction_name : str (facultatif) core_dump_tc_values : list[dict] core_dump_sc_values : list[dict] core_location : str |
(vide) |
STALL_EVENT est abordé dans Diagnostics de blocage des TPU, y compris comment déclencher un instantané sur un job en cours d'exécution. Chaque événement SFLAG_TIMEOUT est également comptabilisé comme un déclencheur de blocage. Attendez-vous donc à un STALL_EVENT avec source=3 (SFLAG_TIMEOUT) du même hôte environ 10 secondes plus tard.
Pour en savoir plus sur la structure des événements, consultez la section Documentation de référence.
Exemple de workflow
L'exemple de script suivant illustre un workflow complet : comment enregistrer un rappel dans un script d'entraînement, gérer les événements courants et annuler l'enregistrement proprement une fois l'opération terminée.
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()
Référence : Structure des événements
Délai avant expiration de l'indicateur de synchronisation (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
}
Violation des limites de mémoire (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
}
Blocage ou suspension du 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
}
Incompatibilité 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 et Inf détectés (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
}
Incohérence de la sortie HLO SDC (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
}
Événement de l'enregistreur 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
}
Événement de débogage 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
}
Instantané de l'état du matériel (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