huggingface/transformers · error · ImportError

Unable to convert output to PyTorch tensors format, PyTorch

Error message

Unable to convert output to PyTorch tensors format, PyTorch is not installed.

What it means

BatchFeature.convert_to_tensors resolves the as_tensor function per TensorType. For TensorType.PYTORCH it first checks is_torch_available(); if transformers was installed without torch (CPU-only extras, minimal dep set, or broken torch install), conversion cannot proceed and ImportError is raised.

Source

Thrown at src/transformers/feature_extraction_utils.py:118

    def __getstate__(self):
        return {"data": self.data}

    def __setstate__(self, state):
        if "data" in state:
            self.data = state["data"]

    def _get_is_as_tensor_fns(self, tensor_type: str | TensorType | None = None):
        if tensor_type is None:
            return None, None

        # Convert to TensorType
        if not isinstance(tensor_type, TensorType):
            tensor_type = TensorType(tensor_type)

        if tensor_type == TensorType.PYTORCH:
            if not is_torch_available():
                raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.")
            import torch

            def as_tensor(value):
                if torch.is_tensor(value):
                    return value

                # stack list of tensors if tensor_type is PyTorch (# torch.tensor() does not support list of tensors)
                if isinstance(value, (list, tuple)) and len(value) > 0 and torch.is_tensor(value[0]):
                    return torch.stack(value)

                # convert list of numpy arrays to numpy array (stack) if tensor_type is Numpy
                if isinstance(value, (list, tuple)) and len(value) > 0:
                    if isinstance(value[0], np.ndarray):
                        value = np.array(value)
                    elif (
                        isinstance(value[0], (list, tuple))
                        and len(value[0]) > 0
                        and isinstance(value[0][0], np.ndarray)

View on GitHub (pinned to a597f97485)

Solutions

  1. Install torch in the environment (pip install torch) or use the appropriate transformers extra
  2. If torch is installed, verify 'import torch' works — a broken install can also trip is_torch_available()
  3. If you don't need tensors, call with return_tensors=None to keep numpy/python objects

Example fix

# before (env without torch)
fe(audio, return_tensors="pt")

# after
pip install torch   # then:
fe(audio, return_tensors="pt")
# or without torch:
fe(audio)  # numpy output
Defensive patterns

Strategy: validation

Validate before calling

from transformers.utils import is_torch_available

if not is_torch_available():
    raise ImportError("install torch before requesting return_tensors='pt'")

Type guard

def can_return_pt() -> bool:
    from transformers.utils import is_torch_available
    return is_torch_available()

Try / catch

try:
    batch = fe(audio, return_tensors="pt")
except ImportError as e:
    if "PyTorch is not installed" in str(e):
        batch = fe(audio, return_tensors="np")
    else:
        raise

Prevention

When it happens

Trigger: Calling a feature extractor (or BatchFeature(..., tensor_type='pt') / return_tensors='pt') in an environment where import torch fails or torch is not installed.

Common situations: Deploying in slim containers/docker images without the torch dependency; CI lint/type-check jobs with transformers but no torch; installing transformers via a meta-package that omits torch.

Related errors


AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14). Data as JSON: /api/errors/5cc4fad3f8f8a38d. Report an issue: GitHub.