opencompass / ops /phi_kkt_approx_gla_trace /illegal_input_dump.py
msj19's picture
Add files using upload-large-folder tool
e0fffc1 verified
Raw History Blame Contribute Delete
8.92 kB
"""Save phi-KKT inputs the first time a finite call produces a non-finite value.
Training calls ``phi_kkt_solve_trace_gla``. This guard watches that call:
- forward: every input is finite, and ``x`` / ``q_mix`` / ``o`` / state is not
- backward: gradients arriving at the outputs are finite, and a gradient
leaving into an input is not
The snapshot is written once per process. Set ``PHI_KKT_NAN_GUARD=0`` to skip
the checks. Set ``PHI_KKT_ILLEGAL_DUMP`` to change the file. Set
``PHI_KKT_ILLEGAL_RAISE=0`` to keep training after the snapshot.
"""
from __future__ import annotations
import os
import threading
from typing import Any, Dict, Mapping, Optional
import torch
from torch import Tensor
_DUMP_DIR = (
"/mnt/jfzn/msj/flash-linear-attention/legacy/training/fla4/debug_dumps"
)
_LOCK = threading.Lock()
_TLS = threading.local()
_SAVED = False
_ANNOUNCED = False
_INHERITED_NOTED = False
_CALL_INDEX = 0
def guard_enabled() -> bool:
return os.environ.get("PHI_KKT_NAN_GUARD", "1") != "0" and not _SAVED
def dump_path() -> str:
rank = os.environ.get("RANK", os.environ.get("LOCAL_RANK", "0"))
override = os.environ.get("PHI_KKT_ILLEGAL_DUMP")
if override:
root, ext = os.path.splitext(override)
if ext == "":
ext = ".pt"
return f"{root}_rank{rank}{ext}"
return os.path.join(_DUMP_DIR, f"phi_kkt_illegal_inputs_rank{rank}.pt")
def _illegal(tensor: Optional[Tensor]) -> bool:
"""True when a floating tensor contains NaN or Inf. One device sync."""
if tensor is None or not torch.is_tensor(tensor):
return False
if tensor.numel() == 0 or not tensor.is_floating_point():
return False
minimum, maximum = torch.aminmax(tensor.detach())
return not bool((torch.isfinite(minimum) & torch.isfinite(maximum)).item())
def _stats(tensor: Any) -> Dict[str, Any]:
if not torch.is_tensor(tensor):
return {"present": tensor is not None, "type": type(tensor).__name__}
data = tensor.detach()
info: Dict[str, Any] = {
"shape": list(data.shape),
"dtype": str(data.dtype).removeprefix("torch."),
"numel": int(data.numel()),
}
if data.numel() == 0 or not data.is_floating_point():
info["n_nonfinite"] = 0
return info
finite = torch.isfinite(data)
n_bad = int((~finite).sum().item())
info["n_nonfinite"] = n_bad
if n_bad < data.numel():
vals = data[finite]
info["finite_min"] = float(vals.min().item())
info["finite_max"] = float(vals.max().item())
return info
def _to_cpu(tensor: Any) -> Any:
if not torch.is_tensor(tensor):
return tensor
return tensor.detach().cpu().contiguous()
def _announce() -> None:
global _ANNOUNCED
if _ANNOUNCED:
return
_ANNOUNCED = True
print(
f"[phi_kkt] illegal-value guard on; first bad call dumps inputs to {dump_path()}",
flush=True,
)
def _note_inherited(layer_idx: Optional[int], bad_names) -> None:
global _INHERITED_NOTED
if _INHERITED_NOTED:
return
_INHERITED_NOTED = True
print(
f"[phi_kkt] layer {layer_idx} already received illegal inputs {bad_names}; "
"the transition happened before phi_kkt, inputs were not saved",
flush=True,
)
def dump_once(
state: Mapping[str, Any],
stage: str,
bad_name: str,
outputs: Optional[Mapping[str, Any]] = None,
grad: Optional[Tensor] = None,
) -> None:
"""Write the finite inputs that produced ``bad_name``. Runs at most once."""
global _SAVED
with _LOCK:
if _SAVED:
return
# Block nested hooks and later layers before the copy finishes.
_SAVED = True
payload: Dict[str, Any] = {
"stage": stage,
"bad_name": bad_name,
"layer_idx": state.get("layer_idx"),
"call_index": state.get("call_index"),
"fn": "phi_kkt_solve_trace_gla -> q_kkt_solve_trace_triton_safe_ver1 + chunk_gla",
"meta": dict(state.get("meta") or {}),
"input_stats": {},
"output_stats": {},
}
inputs = state.get("inputs") or {}
for name, tensor in inputs.items():
payload["input_stats"][name] = _stats(tensor)
payload[name] = _to_cpu(tensor)
if outputs is not None:
for name, tensor in outputs.items():
payload["output_stats"][name] = _stats(tensor)
if grad is not None:
payload["bad_grad_stats"] = _stats(grad)
path = dump_path()
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
temporary = path + ".tmp"
try:
torch.save(payload, temporary)
os.replace(temporary, path)
except Exception:
_SAVED = False
raise
message = (
f"[phi_kkt] layer {payload['layer_idx']} {stage} produced illegal `{bad_name}` "
f"from finite inputs (call {payload['call_index']}). saved {path}"
)
print(message, flush=True)
if os.environ.get("PHI_KKT_ILLEGAL_RAISE", "1") != "0":
raise RuntimeError(message)
class _InWatch(torch.autograd.Function):
"""Identity on an input. Backward sees the grad this call writes into it."""
@staticmethod
def forward(ctx, tensor: Tensor) -> Tensor:
ctx.state, ctx.name = _TLS.watch
return tensor
@staticmethod
def backward(ctx, grad: Tensor):
state = ctx.state
if state.get("out_finite") is True and _illegal(grad):
dump_once(state, stage="backward", bad_name=f"grad_{ctx.name}", grad=grad)
return grad
class _OutMark(torch.autograd.Function):
"""Identity on an output. Backward records whether the incoming grad is finite."""
@staticmethod
def forward(ctx, tensor: Tensor) -> Tensor:
ctx.state = _TLS.mark
return tensor
@staticmethod
def backward(ctx, grad: Tensor):
finite = grad is None or not _illegal(grad)
previous = ctx.state.get("out_finite")
ctx.state["out_finite"] = finite if previous is None else (previous and finite)
return grad
class PhiKktGuard:
"""Wrap one ``phi_kkt_solve_trace_gla`` call."""
def __init__(
self,
layer_idx: Optional[int],
inputs: Mapping[str, Any],
meta: Optional[Mapping[str, Any]] = None,
) -> None:
global _CALL_INDEX
self.inputs = dict(inputs)
self.meta = dict(meta or {})
self.active = guard_enabled()
self.input_finite = True
self._bad_inputs = []
self._seen: Dict[int, Tensor] = {}
self.state: Dict[str, Any] = {
"out_finite": None,
"layer_idx": layer_idx,
"inputs": self.inputs,
"meta": self.meta,
"call_index": None,
}
if not self.active:
return
_CALL_INDEX += 1
self.state["call_index"] = _CALL_INDEX
_announce()
shared: Dict[int, list] = {}
for name, tensor in self.inputs.items():
if torch.is_tensor(tensor):
shared.setdefault(id(tensor), []).append(name)
aliases = [names for names in shared.values() if len(names) > 1]
if aliases:
self.meta["aliases"] = aliases
self.state["meta"] = self.meta
self._bad_inputs = [name for name, tensor in self.inputs.items() if _illegal(tensor)]
self.input_finite = not self._bad_inputs
def wrap(self, name: str, tensor: Any) -> Any:
"""Return ``tensor`` with a backward probe. Same object is wrapped once."""
if not self.active or not self.input_finite:
return tensor
if tensor is None or not torch.is_tensor(tensor) or not tensor.requires_grad:
return tensor
key = id(tensor)
cached = self._seen.get(key)
if cached is not None:
return cached
_TLS.watch = (self.state, name)
wrapped = _InWatch.apply(tensor)
self._seen[key] = wrapped
return wrapped
def mark(self, tensor: Optional[Tensor]) -> Optional[Tensor]:
"""Return ``tensor`` with a probe on the gradient that enters this call."""
if not self.active or not self.input_finite:
return tensor
if tensor is None or not torch.is_tensor(tensor) or not tensor.requires_grad:
return tensor
_TLS.mark = self.state
return _OutMark.apply(tensor)
def check_forward(self, outputs: Mapping[str, Any]) -> None:
"""Dump when finite inputs just produced a non-finite forward tensor."""
if not self.active:
return
if not self.input_finite:
_note_inherited(self.state.get("layer_idx"), self._bad_inputs)
return
for name, tensor in outputs.items():
if _illegal(tensor):
dump_once(self.state, stage="forward", bad_name=name, outputs=outputs)
return