{
  "id": "pytorch/nan-loss-step",
  "signature": "RuntimeError: Loss is NaN or Inf at step 500. Consider reducing learning rate, adding gradient clipping, or checking input data for outliers.",
  "signature_zh": "RuntimeError: 在第 500 步损失为 NaN 或 Inf。考虑降低学习率、添加梯度裁剪或检查输入数据中的异常值。",
  "regex": "RuntimeError: Loss is NaN or Inf at step \\d+",
  "domain": "pytorch",
  "category": "assertion_error",
  "subcategory": null,
  "root_cause": "Training loss becomes NaN or Inf due to exploding gradients, numerical instability (e.g., log of zero), or corrupted input data with extreme values.",
  "root_cause_type": "generic",
  "root_cause_zh": "训练损失变为 NaN 或 Inf，原因包括梯度爆炸、数值不稳定（例如，对零取对数）或输入数据中存在极端异常值。",
  "versions": [
    {
      "version": "torch>=1.8",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "torch>=2.0",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "Setting torch.set_default_dtype(torch.float64) to increase precision",
      "why_fails": "Float64 may delay but not prevent NaN if the root cause is exploding gradients or log(0); also slows training significantly.",
      "fail_rate": 0.65,
      "condition": "",
      "sources": []
    },
    {
      "action": "Restarting training from scratch without changes",
      "why_fails": "The same hyperparameters and data will produce the same NaN at the same step; the issue is deterministic.",
      "fail_rate": 0.95,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "Add gradient clipping: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) after loss.backward() and before optimizer.step()",
      "success_rate": 0.85,
      "how": "Add gradient clipping: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) after loss.backward() and before optimizer.step()",
      "condition": "",
      "sources": []
    },
    {
      "action": "Reduce learning rate by factor of 10: optimizer = torch.optim.Adam(model.parameters(), lr=1e-4) instead of 1e-3",
      "success_rate": 0.75,
      "how": "Reduce learning rate by factor of 10: optimizer = torch.optim.Adam(model.parameters(), lr=1e-4) instead of 1e-3",
      "condition": "",
      "sources": []
    },
    {
      "action": "Add a small epsilon to log inputs: loss = F.cross_entropy(logits, targets) inside a try block with torch.clamp(logits, min=-100, max=100)",
      "success_rate": 0.8,
      "how": "Add a small epsilon to log inputs: loss = F.cross_entropy(logits, targets) inside a try block with torch.clamp(logits, min=-100, max=100)",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [
    "Add gradient clipping: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) after loss.backward() and before optimizer.step()",
    "Reduce learning rate by factor of 10: optimizer = torch.optim.Adam(model.parameters(), lr=1e-4) instead of 1e-3",
    "Add a small epsilon to log inputs: loss = F.cross_entropy(logits, targets) inside a try block with torch.clamp(logits, min=-100, max=100)"
  ],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": "https://pytorch.org/docs/stable/notes/numerical_stability.html",
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.9,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2023-02-10",
  "last_confirmed": "2024-06-01",
  "last_updated": "2024-06-01",
  "evidence_count": 1,
  "tags": [],
  "locale": "en",
  "aliases": []
}