{
  "id": "pytorch/torchscript-dynamic-control-flow",
  "signature": "RuntimeError: TorchScript supports tracing only for tensors. This function cannot be traced because it uses dynamic control flow (e.g., if/else or loops).",
  "signature_zh": "运行时错误：TorchScript 仅支持张量的跟踪。此函数无法跟踪，因为它使用了动态控制流（例如，if/else 或循环）。",
  "regex": "RuntimeError: TorchScript supports tracing only for tensors",
  "domain": "pytorch",
  "category": "runtime_error",
  "subcategory": null,
  "root_cause": "TorchScript tracing (torch.jit.trace) cannot handle Python control flow that depends on tensor values; it records operations on specific inputs and fails when the path changes.",
  "root_cause_type": "generic",
  "root_cause_zh": "TorchScript 跟踪（torch.jit.trace）无法处理依赖于张量值的 Python 控制流；它记录特定输入上的操作，并在路径更改时失败。",
  "versions": [
    {
      "version": "torch 1.9.0",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "torch 2.0.0",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "python 3.9",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Using torch.jit.trace with a large set of example inputs may still fail if control flow depends on runtime values not present in examples.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Adding more concrete inputs to trace may cover some paths but not all, leading to incomplete traces.",
      "fail_rate": 0.7,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "Use torch.jit.script instead of trace for models with dynamic control flow:\n@torch.jit.script\ndef forward(self, x):\n    if x.sum() > 0:\n        return x * 2\n    else:\n        return x / 2\n# Then script the model: scripted_model = torch.jit.script(model)",
      "success_rate": 0.9,
      "how": "Use torch.jit.script instead of trace for models with dynamic control flow:\n@torch.jit.script\ndef forward(self, x):\n    if x.sum() > 0:\n        return x * 2\n    else:\n        return x / 2\n# Then script the model: scripted_model = torch.jit.script(model)",
      "condition": "",
      "sources": []
    },
    {
      "action": "Refactor the model to avoid dynamic control flow in the traced function, e.g., use torch.where or masked operations:\ndef forward(self, x):\n    mask = (x.sum(dim=1, keepdim=True) > 0).float()\n    return x * (1 + mask)  # equivalent to if-else",
      "success_rate": 0.85,
      "how": "Refactor the model to avoid dynamic control flow in the traced function, e.g., use torch.where or masked operations:\ndef forward(self, x):\n    mask = (x.sum(dim=1, keepdim=True) > 0).float()\n    return x * (1 + mask)  # equivalent to if-else",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [
    "Use torch.jit.script instead of trace for models with dynamic control flow:\n@torch.jit.script\ndef forward(self, x):\n    if x.sum() > 0:\n        return x * 2\n    else:\n        return x / 2\n# Then script the model: scripted_model = torch.jit.script(model)",
    "Refactor the model to avoid dynamic control flow in the traced function, e.g., use torch.where or masked operations:\ndef forward(self, x):\n    mask = (x.sum(dim=1, keepdim=True) > 0).float()\n    return x * (1 + mask)  # equivalent to if-else"
  ],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": "https://pytorch.org/docs/stable/jit.html#mixing-tracing-and-scripting",
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.88,
  "fix_success_rate": 0.9,
  "resolvable": "true",
  "first_seen": "2023-02-10",
  "last_confirmed": "2024-06-01",
  "last_updated": "2024-06-01",
  "evidence_count": 1,
  "tags": [],
  "locale": "en",
  "aliases": []
}