{"record":{"id":"7e0f16b10d477439","repo":"hpcaitech/Open-Sora","slug":"type-type-data-cannot-be-converted-to-tensor","errorCode":null,"errorMessage":"type {type(data)} cannot be converted to tensor.","messagePattern":"type (.+?) cannot be converted to tensor\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"opensora/utils/misc.py","lineNumber":194,"sourceCode":"        data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to\n            be converted.\n\n    Returns:\n        torch.Tensor: The converted tensor.\n    \"\"\"\n\n    if isinstance(data, torch.Tensor):\n        return data\n    elif isinstance(data, np.ndarray):\n        return torch.from_numpy(data)\n    elif isinstance(data, Sequence) and not isinstance(data, str):\n        return torch.tensor(data)\n    elif isinstance(data, int):\n        return torch.LongTensor([data])\n    elif isinstance(data, float):\n        return torch.FloatTensor([data])\n    else:\n        raise TypeError(f\"type {type(data)} cannot be converted to tensor.\")\n\n\ndef to_ndarray(data: torch.Tensor | np.ndarray | Sequence | int | float) -> np.ndarray:\n    \"\"\"Convert objects of various python types to :obj:`numpy.ndarray`.\n\n    Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,\n    :class:`Sequence`, :class:`int` and :class:`float`.\n\n    Args:\n        data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to\n            be converted.\n\n    Returns:\n        numpy.ndarray: The converted ndarray.\n    \"\"\"\n    if isinstance(data, torch.Tensor):\n        return data.numpy()\n    elif isinstance(data, np.ndarray):","sourceCodeStart":176,"sourceCodeEnd":212,"githubUrl":"https://github.com/hpcaitech/Open-Sora/blob/7ad6a96a135feb81f755c84fb391818718f6beb2/opensora/utils/misc.py#L176-L212","documentation":"This TypeError is raised by to_tensor in opensora/utils/misc.py when the input data is not one of the supported types: torch.Tensor, numpy.ndarray, int, float, or a sequence convertible by torch.tensor. The function branches on isinstance checks, and anything else (str, dict, None, arbitrary objects) reaches the else branch. It signals that the caller passed data the conversion utility cannot map to a torch.Tensor.","triggerScenarios":"Calling to_tensor(\"hello\"), to_tensor({\"a\": 1}), to_tensor(None), or to_tensor(some_custom_object). Lists/sequences attempt torch.tensor(data), so non-numeric nested sequences (e.g. [\"a\", \"b\"]) also raise, though from torch itself.","commonSituations":"Feeding string labels or metadata from a dataset/dataloader directly into to_tensor; passing a dict of arrays instead of the arrays themselves; passing None from an optional field that was never populated in a data preprocessing pipeline.","solutions":["Convert the value to a supported type first: np.array(data) or a numeric Python list before calling to_tensor","If the value is text (labels/classes), map it to indices via a vocabulary/label encoder, then convert","Guard with isinstance checks for torch.Tensor, np.ndarray, int, float, or Sequence before calling to_tensor","If None is possible, add an explicit None check and a sensible default"],"exampleFix":"# before\nt = to_tensor(sample[\"caption\"])\n\n# after\nt = to_tensor(label_to_id[sample[\"label\"]])","handlingStrategy":"type-guard","validationCode":"import numbers\nfrom collections.abc import Sequence\nok = isinstance(data, (torch.Tensor, np.ndarray, numbers.Integral, numbers.Real, Sequence)) and not isinstance(data, (str, bytes, dict))\nif not ok:\n    raise TypeError(f\"Unsupported input for to_tensor: {type(data)!r}\")","typeGuard":"def is_tensor_convertible(data) -> bool:\n    return isinstance(data, (torch.Tensor, np.ndarray, int, float, Sequence)) and not isinstance(data, (str, bytes, dict))","tryCatchPattern":"try:\n    t = to_tensor(data)\nexcept TypeError:\n    t = torch.tensor(as_numeric(data))  # caller-specific numeric coercion","preventionTips":["Never pass raw strings, dicts, or optional-None fields to to_tensor","Encode categorical/text fields to numeric ids before conversion"],"tags":["pytorch","typeerror","type-conversion","opensora"],"backgroundTag":"tensor-conversion-type-error","analyzedSha":"7ad6a96a135feb81f755c84fb391818718f6beb2","analyzedAt":"2026-08-28T16:58:37.171Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}