File size: 8,921 Bytes
e0fffc1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | """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
|