hpcaitech/Open-Sora · error · TypeError

type {type(data)} cannot be converted to ndarray.

Error message

type {type(data)} cannot be converted to ndarray.

What it means

This TypeError is raised by to_ndarray in opensora/utils/misc.py when the input is not an np.ndarray, torch.Tensor, int, float, or a value np.array/np.ndarray can construct from. It is the numpy counterpart of to_tensor and exists to reject data types the conversion matrix does not cover. Hitting it means the caller passed an unsupported object such as a string, dict, or None.

Source

Thrown at opensora/utils/misc.py:221

    Args:
        data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to
            be converted.

    Returns:
        numpy.ndarray: The converted ndarray.
    """
    if isinstance(data, torch.Tensor):
        return data.numpy()
    elif isinstance(data, np.ndarray):
        return data
    elif isinstance(data, Sequence):
        return np.array(data)
    elif isinstance(data, int):
        return np.ndarray([data], dtype=int)
    elif isinstance(data, float):
        return np.array([data], dtype=float)
    else:
        raise TypeError(f"type {type(data)} cannot be converted to ndarray.")


def to_torch_dtype(dtype: str | torch.dtype) -> torch.dtype:
    """
    Convert a string or a torch.dtype to a torch.dtype.

    Args:
        dtype (str | torch.dtype): The input dtype.

    Returns:
        torch.dtype: The converted dtype.
    """
    if isinstance(dtype, torch.dtype):
        return dtype
    elif isinstance(dtype, str):
        dtype_mapping = {
            "float64": torch.float64,
            "float32": torch.float32,

View on GitHub (pinned to 7ad6a96a13)

Solutions

  1. Convert the input to an array-like numeric structure first (e.g. list of floats, np.array) before calling to_ndarray
  2. For string data, parse/encode it (float(x) for numeric strings, label encoding for classes) then convert
  3. Pre-validate with isinstance checks for np.ndarray, torch.Tensor, int, float, or Sequence
  4. Handle None explicitly with a default or an early return

Example fix

# before
arr = to_ndarray(meta["fps"])

# after
arr = to_ndarray(float(meta["fps"]))
Defensive patterns

Strategy: type-guard

Validate before calling

import numbers
from collections.abc import Sequence
ok = isinstance(data, (np.ndarray, torch.Tensor, numbers.Integral, numbers.Real, Sequence)) and not isinstance(data, (str, bytes, dict))
if not ok:
    raise TypeError(f"Unsupported input for to_ndarray: {type(data)!r}")

Type guard

def is_ndarray_convertible(data) -> bool:
    return isinstance(data, (np.ndarray, torch.Tensor, int, float, Sequence)) and not isinstance(data, (str, bytes, dict))

Try / catch

try:
    arr = to_ndarray(data)
except TypeError:
    arr = np.asarray(data, dtype=float)

Prevention

When it happens

Trigger: Calling to_ndarray("1.5"), to_ndarray({"x": [1,2]}), to_ndarray(None), or to_ndarray(some_object) where the object is not array-like. Note the int branch uses np.ndarray([data], dtype=int), which itself errors for unusual ints, but the explicit raise fires for anything outside the isinstance chain.

Common situations: Processing dataset fields that are strings (file paths, captions) or dicts of lists; passing optional fields that resolved to None; migrating code from to_tensor to to_ndarray with data that was never numeric.

Related errors


AI-assisted analysis of hpcaitech/Open-Sora@7ad6a96a13 (2026-08-28). Data as JSON: /api/errors/781e257ab8f0bb68. Report an issue: GitHub.