{"record":{"id":"f263a8e7f4237815","repo":"apache/beam","slug":"please-specify-either-torch-script-model-path-or-state-dict","errorCode":null,"errorMessage":"Please specify either torch_script_model_path or (state_dict_path, model_class) to successfully load the model.","messagePattern":"Please specify either torch_script_model_path or \\(state_dict_path, model_class\\) to successfully load the model\\.","errorType":"validation","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/ml/inference/pytorch_inference.py","lineNumber":91,"sourceCode":"def _validate_constructor_args(\n    state_dict_path, model_class, torch_script_model_path):\n  message = (\n      \"A {param1} has been supplied to the model \"\n      \"handler, but the required {param2} is missing. \"\n      \"Please provide the {param2} in order to \"\n      \"successfully load the {param1}.\")\n  # state_dict_path and model_class are coupled with each other\n  # raise RuntimeError if user forgets to pass any one of them.\n  if state_dict_path and not model_class:\n    raise RuntimeError(\n        message.format(param1=\"state_dict_path\", param2=\"model_class\"))\n\n  if not state_dict_path and model_class:\n    raise RuntimeError(\n        message.format(param1=\"model_class\", param2=\"state_dict_path\"))\n\n  if torch_script_model_path and state_dict_path:\n    raise RuntimeError(\n        \"Please specify either torch_script_model_path or \"\n        \"(state_dict_path, model_class) to successfully load the model.\")\n\n\ndef _load_model(\n    model_class: Optional[Callable[..., torch.nn.Module]],\n    state_dict_path: Optional[str],\n    device: torch.device,\n    model_params: Optional[dict[str, Any]],\n    torch_script_model_path: Optional[str],\n    load_model_args: Optional[dict[str, Any]]):\n  if device == torch.device('cuda') and not _cuda_device_is_usable():\n    logging.warning(\n        \"Model handler specified a 'GPU' device, but GPUs are not available. \"\n        \"Switching to CPU.\")\n    device = torch.device('cpu')\n\n  try:","sourceCodeStart":73,"sourceCodeEnd":109,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/ml/inference/pytorch_inference.py#L73-L109","documentation":"Raised by _validate_constructor_args in PytorchModelHandlerKeyedModel/PytorchModelHandler when the constructor arguments are inconsistent. Loading a PyTorch model requires either a TorchScript serialized model path alone, or a state_dict path paired with the model's class. Passing torch_script_model_path together with state_dict_path is ambiguous, so the handler refuses to construct.","triggerScenarios":"Constructing a ModelHandler (e.g. PytorchModelHandlerKeyedModel(...)) with both torch_script_model_path and state_dict_path set to non-None values.","commonSituations":"Migrating a handler from TorchScript loading to state_dict loading (or vice versa) and forgetting to remove the old path argument; building handler kwargs from a config that contains both keys; copy-pasting example code that mixes the two loading styles.","solutions":["Remove torch_script_model_path if you intend to load via (state_dict_path, model_class)","Remove state_dict_path and model_class if you intend to load a TorchScript model via torch_script_model_path","Ensure your config/kwargs builder emits exactly one of the two loading styles"],"exampleFix":"// before\nhandler = PytorchModelHandlerKeyedModel(\n    state_dict_path='gs://bucket/model.pt',\n    model_class=MyNet,\n    torch_script_path='gs://bucket/model_scripted.pt')\n// after\nhandler = PytorchModelHandlerKeyedModel(\n    state_dict_path='gs://bucket/model.pt',\n    model_class=MyNet)","handlingStrategy":"validation","validationCode":"def check_pytorch_handler_kwargs(kwargs):\n    has_ts = bool(kwargs.get('torch_script_model_path'))\n    has_sd = bool(kwargs.get('state_dict_path') and kwargs.get('model_class'))\n    if has_ts and has_sd:\n        raise ValueError('Pass either torch_script_model_path or (state_dict_path, model_class), not both.')\n    if not has_ts and not has_sd:\n        raise ValueError('Provide torch_script_model_path or (state_dict_path, model_class).')","typeGuard":"def is_valid_loading_style(kwargs: dict) -> bool:\n    has_ts = kwargs.get('torch_script_model_path') is not None\n    has_sd = kwargs.get('state_dict_path') is not None and kwargs.get('model_class') is not None\n    return has_ts ^ has_sd","tryCatchPattern":"try:\n    handler = PytorchModelHandlerKeyedModel(**kwargs)\nexcept RuntimeError as e:\n    if 'torch_script_model_path' in str(e):\n        kwargs.pop('torch_script_model_path')\n        handler = PytorchModelHandlerKeyedModel(**kwargs)\n    else:\n        raise","preventionTips":["Build handler kwargs from a single config source so only one loading style can be present","Assert before construction that exactly one of torch_script_model_path / state_dict_path is set","Keep TorchScript and state_dict examples separate; don't merge snippet kwargs"],"tags":["pytorch","apache-beam","ml-inference","constructor"],"backgroundTag":"mutually-exclusive-options","analyzedSha":"12126d8942aaf848030c478b4c6a28c6af861c66","analyzedAt":"2026-09-13T01:50:10.254Z","contentChangedAt":"2026-09-13T01:50:10.254Z","schemaVersion":2},"datasetVersion":"2026-09-20T03:17:13.778Z"}