{"record":{"id":"bdadc19c598f58e7","repo":"apache/beam","slug":"no-serializetostring-method-is-detected-on-loaded-model-type","errorCode":null,"errorMessage":"No SerializeToString method is detected on loaded model. Type of model: {type(model_proto)}","messagePattern":"No SerializeToString method is detected on loaded model\\. Type of model: (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/ml/inference/onnx_inference.py","lineNumber":134,"sourceCode":"        **kwargs)\n    self._model_uri = model_uri\n    self._session_options = session_options\n    self._providers = providers\n    self._provider_options = provider_options\n    self._model_inference_fn = inference_fn\n\n  def load_model(self) -> ort.InferenceSession:\n    \"\"\"Loads and initializes an onnx inference session for processing.\"\"\"\n    # when path is remote, we should first load into memory then deserialize\n    f = FileSystems.open(self._model_uri, \"rb\")\n    model_proto = onnx.load(f)\n    model_proto_bytes = model_proto\n    if not isinstance(model_proto, bytes):\n      if (hasattr(model_proto, \"SerializeToString\") and\n          callable(model_proto.SerializeToString)):\n        model_proto_bytes = model_proto.SerializeToString()\n      else:\n        raise TypeError(\n            \"No SerializeToString method is detected on loaded model. \" +\n            f\"Type of model: {type(model_proto)}\")\n    ort_session = ort.InferenceSession(\n        model_proto_bytes,\n        sess_options=self._session_options,\n        providers=self._providers,\n        provider_options=self._provider_options)\n    return ort_session\n\n  def run_inference(\n      self,\n      batch: Sequence[numpy.ndarray],\n      inference_session: ort.InferenceSession,\n      inference_args: Optional[dict[str, Any]] = None\n  ) -> Iterable[PredictionResult]:\n    \"\"\"Runs inferences on a batch of numpy arrays.\n\n    Args:","sourceCodeStart":116,"sourceCodeEnd":152,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/ml/inference/onnx_inference.py#L116-L152","documentation":"ONNXModelHandler.load_model expects the loaded model as bytes or an object exposing SerializeToString() (a protobuf message, e.g. onnx.ModelProto). If the object is neither bytes nor protobuf-like, a TypeError is raised because the handler cannot serialize it for onnxruntime's InferenceSession.","triggerScenarios":"onnx.load() returning a ModelProto is fine, but passing e.g. a session, a numpy object, or a str path into the handler's model slot leads to load_model hitting the else branch.","commonSituations":"Passing a file path string instead of loaded bytes; using tf/savedmodel exports without protobuf conversion; custom model wrappers lacking SerializeToString.","solutions":["Load with onnx.load(path) and pass the ModelProto (it has SerializeToString).","Or read the file yourself and pass bytes: open(path,'rb').read().","Ensure you pass onnxruntime-compatible ONNX protobuf, not a TorchScript/TF model."],"exampleFix":"// before\nhandler = ONNXModelHandler(model_url='model.onnx')\nsession_input = onnx.load('model.onnx').graph  # graph has no SerializeToString\n// after\nmodel_proto = onnx.load('model.onnx')  # ModelProto: has SerializeToString","handlingStrategy":"type-guard","validationCode":"if not isinstance(model, bytes) and not (hasattr(model, 'SerializeToString') and callable(getattr(model, 'SerializeToString'))):\n    raise TypeError('Pass bytes or an onnx.ModelProto to ONNXModelHandler')","typeGuard":"def is_protobuf_like(obj) -> bool:\n    return hasattr(obj, 'SerializeToString') and callable(obj.SerializeToString)","tryCatchPattern":"try:\n    handler.load_model()\nexcept TypeError as e:\n    if 'SerializeToString' in str(e):\n        model_bytes = open(model_path, 'rb').read()\n        # retry with bytes input\n    else:\n        raise","preventionTips":["Load models with onnx.load() (returns ModelProto) rather than passing paths or graphs","Never pass a string path where bytes/proto is expected","Verify the artifact is ONNX, not TorchScript or TF SavedModel"],"tags":["python","apache-beam","onnx","type-error","serialization"],"backgroundTag":"type-mismatch","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"}