{"record":{"id":"5fbb70826e938ae3","repo":"huggingface/transformers","slug":"return-tensors-set-to-pt-but-pytorch-can-t-be-im","errorCode":null,"errorMessage":"return_tensors set to 'pt' but PyTorch can't be imported","messagePattern":"return_tensors set to 'pt' but PyTorch can't be imported","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/transformers/data/processors/utils.py","lineNumber":316,"sourceCode":"            elif self.mode == \"regression\":\n                label = float(example.label)\n            else:\n                raise ValueError(self.mode)\n\n            if ex_index < 5 and self.verbose:\n                logger.info(\"*** Example ***\")\n                logger.info(f\"guid: {example.guid}\")\n                logger.info(f\"input_ids: {' '.join([str(x) for x in input_ids])}\")\n                logger.info(f\"attention_mask: {' '.join([str(x) for x in attention_mask])}\")\n                logger.info(f\"label: {example.label} (id = {label})\")\n\n            features.append(InputFeatures(input_ids=input_ids, attention_mask=attention_mask, label=label))\n\n        if return_tensors is None:\n            return features\n        elif return_tensors == \"pt\":\n            if not is_torch_available():\n                raise RuntimeError(\"return_tensors set to 'pt' but PyTorch can't be imported\")\n            import torch\n            from torch.utils.data import TensorDataset\n\n            all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)\n            all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)\n            if self.mode == \"classification\":\n                all_labels = torch.tensor([f.label for f in features], dtype=torch.long)\n            elif self.mode == \"regression\":\n                all_labels = torch.tensor([f.label for f in features], dtype=torch.float)\n\n            dataset = TensorDataset(all_input_ids, all_attention_mask, all_labels)\n            return dataset\n        else:\n            raise ValueError(\"return_tensors should be `'pt'` or `None`\")\n","sourceCodeStart":298,"sourceCodeEnd":331,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/data/processors/utils.py#L298-L331","documentation":"The featurizer can package examples as a torch TensorDataset when return_tensors='pt', but transformers is installed without PyTorch in the current environment (is_torch_available() is False). The library raises RuntimeError instead of attempting the import so you get a clear message rather than a ModuleNotFoundError for torch.","triggerScenarios":"Calling get_features(..., return_tensors='pt') in an environment where torch is not installed; running on a CPU-only slim install of transformers (pip install transformers without torch); a venv/container where torch was uninstalled or never installed.","commonSituations":"Using transformers only for tokenizers/ONNX/JAX and then trying the PyTorch tensor path; CI images that omit torch to save space; switching conda envs mid-project.","solutions":["Install PyTorch in the active environment (pip install torch), then retry.","If you deliberately run without torch, call the featurizer with return_tensors=None and consume the list of InputFeatures.","Verify the environment with python -c \"import torch\" and check you are in the interpreter/venv you think you are."],"exampleFix":"# before\nfeatures = featurizer.get_features(texts, return_tensors=\"pt\")  # no torch installed\n\n# after (option A): install torch\n# pip install torch\n# after (option B): stay framework-free\nfeatures = featurizer.get_features(texts, return_tensors=None)","handlingStrategy":"validation","validationCode":"from transformers.utils import is_torch_available\nif return_tensors == \"pt\" and not is_torch_available():\n    raise RuntimeError(\"torch required for return_tensors='pt'; pip install torch or use return_tensors=None\")","typeGuard":null,"tryCatchPattern":"try:\n    ds = featurizer.get_features(texts, return_tensors=\"pt\")\nexcept RuntimeError as e:\n    if \"PyTorch\" in str(e):\n        features = featurizer.get_features(texts, return_tensors=None)  # graceful degrade\n    else:\n        raise","preventionTips":["Verify the active interpreter has torch before requesting tensor output.","Pin torch in requirements to avoid slim-env surprises in CI.","Design pipelines to accept the list-of-features return as a fallback."],"tags":["pytorch","environment","dependencies","runtime"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}