Datasets:
Tasks:
Text Generation
Languages:
English
Size:
n<1K
Tags:
code
notebooks
training-scripts
dataset:Nanthasit/sakthai-kaggle-notebooks
license-mit
dataset-card
License:
NanGuard: zero grads BEFORE diagnostics; dump wrapped in try/except (first run confirmed rows have 6-77 unmasked labels at the poison step)
Browse files- job-0.5b-nanguard.py +34 -25
job-0.5b-nanguard.py
CHANGED
|
@@ -186,35 +186,44 @@ class NanGuard(SFTTrainer):
|
|
| 186 |
for p in model.parameters() if p.requires_grad)
|
| 187 |
if grads_bad or not torch.isfinite(loss):
|
| 188 |
NanGuard._dumped += 1
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
unmasked = (labels != -100).sum(-1)
|
| 193 |
-
print("micro-batch loss:", loss.item() if hasattr(loss, "item") else loss)
|
| 194 |
-
print("num_items_in_batch:", num_items_in_batch)
|
| 195 |
-
print("shape:", tuple(ids.shape), "id range:", ids.min().item(), ids.max().item())
|
| 196 |
-
print("unmasked label tokens per row:", unmasked.tolist())
|
| 197 |
-
was_training = model.training
|
| 198 |
-
model.eval()
|
| 199 |
-
with torch.no_grad():
|
| 200 |
-
outbf = model(input_ids=ids, attention_mask=inputs.get("attention_mask"),
|
| 201 |
-
labels=labels)
|
| 202 |
-
print("bf16 no-grad reforward loss:",
|
| 203 |
-
None if outbf.loss is None else outbf.loss.item(),
|
| 204 |
-
"logits nan:", torch.isnan(outbf.logits).any().item(),
|
| 205 |
-
"inf:", torch.isinf(outbf.logits).any().item())
|
| 206 |
-
if was_training:
|
| 207 |
-
model.train()
|
| 208 |
-
for k in range(ids.shape[0]):
|
| 209 |
-
txt = tokenizer.decode(ids[k], skip_special_tokens=False)
|
| 210 |
-
txt = txt.replace(tokenizer.pad_token, "")
|
| 211 |
-
print(f"--- row {k} unmasked={unmasked[k].item()} chars={len(txt)}")
|
| 212 |
-
print(" tail:", repr(txt[-300:]))
|
| 213 |
-
# neutralize: zero every gradient so the coming optimizer.step is a no-op
|
| 214 |
for p in model.parameters():
|
| 215 |
if p.grad is not None:
|
| 216 |
p.grad.zero_()
|
|
|
|
|
|
|
| 217 |
print(">>> gradients zeroed - this update is skipped, training continues")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
return torch.zeros_like(loss)
|
| 219 |
return loss
|
| 220 |
|
|
|
|
| 186 |
for p in model.parameters() if p.requires_grad)
|
| 187 |
if grads_bad or not torch.isfinite(loss):
|
| 188 |
NanGuard._dumped += 1
|
| 189 |
+
# SAFETY FIRST: neutralize before any diagnostic can crash. Zeroed
|
| 190 |
+
# grads make the coming optimizer.step a no-op; the poison never
|
| 191 |
+
# reaches the weights even if everything below throws.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
for p in model.parameters():
|
| 193 |
if p.grad is not None:
|
| 194 |
p.grad.zero_()
|
| 195 |
+
print(f"\n!!! non-finite {'grads' if grads_bad else 'loss'} #{NanGuard._dumped} "
|
| 196 |
+
f"at global_step {self.state.global_step} epoch {self.state.epoch}")
|
| 197 |
print(">>> gradients zeroed - this update is skipped, training continues")
|
| 198 |
+
if NanGuard._dumped <= 2: # full dump only for the first two events
|
| 199 |
+
try:
|
| 200 |
+
unmasked = (labels != -100).sum(-1)
|
| 201 |
+
print("micro-batch loss:", loss.item() if hasattr(loss, "item") else loss)
|
| 202 |
+
print("num_items_in_batch:", num_items_in_batch)
|
| 203 |
+
print("shape:", tuple(ids.shape), "id range:", ids.min().item(), ids.max().item())
|
| 204 |
+
print("unmasked label tokens per row:", unmasked.tolist())
|
| 205 |
+
bad_params = [n for n, p in model.named_parameters()
|
| 206 |
+
if p.grad is not None and not torch.isfinite(p.grad).all()]
|
| 207 |
+
print(f"non-finite grad params: 0 after zeroing; offenders were "
|
| 208 |
+
f"{len(bad_params)} (grads already cleared)")
|
| 209 |
+
with torch.no_grad():
|
| 210 |
+
outbf = model(input_ids=ids,
|
| 211 |
+
attention_mask=inputs.get("attention_mask"),
|
| 212 |
+
labels=labels)
|
| 213 |
+
print("bf16 no-grad reforward loss:",
|
| 214 |
+
None if outbf.loss is None else outbf.loss.item(),
|
| 215 |
+
"logits nan:", torch.isnan(outbf.logits).any().item(),
|
| 216 |
+
"inf:", torch.isinf(outbf.logits).any().item())
|
| 217 |
+
for k in range(ids.shape[0]):
|
| 218 |
+
txt = tokenizer.decode(ids[k], skip_special_tokens=False)
|
| 219 |
+
txt = txt.replace(tokenizer.pad_token, "")
|
| 220 |
+
print(f"--- row {k} unmasked={unmasked[k].item()} chars={len(txt)}")
|
| 221 |
+
print(" tail:", repr(txt[-300:]))
|
| 222 |
+
except Exception as e:
|
| 223 |
+
import traceback
|
| 224 |
+
print("diagnostic dump failed (training continues):",
|
| 225 |
+
type(e).__name__, e)
|
| 226 |
+
traceback.print_exc()
|
| 227 |
return torch.zeros_like(loss)
|
| 228 |
return loss
|
| 229 |
|