{"record":{"id":"5c1cabdb0907d031","repo":"huggingface/transformers","slug":"attempting-to-cast-a-batchfeature-to-type-str-arg","errorCode":null,"errorMessage":"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.","messagePattern":"Attempting to cast a BatchFeature to type (.+?)\\. This is not supported\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/transformers/feature_extraction_utils.py","lineNumber":246,"sourceCode":"            [`BatchFeature`]: The same instance after modification.\n        \"\"\"\n        requires_backends(self, [\"torch\"])\n        import torch\n\n        device = kwargs.get(\"device\")\n        non_blocking = kwargs.get(\"non_blocking\", False)\n        # Check if the args are a device or a dtype\n        if device is None and len(args) > 0:\n            # device should be always the first argument\n            arg = args[0]\n            if is_torch_dtype(arg):\n                # The first argument is a dtype\n                pass\n            elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):\n                device = arg\n            else:\n                # it's something else\n                raise ValueError(f\"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.\")\n\n        # We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`\n        def maybe_to(v):\n            # check if v is a floating point tensor\n            if isinstance(v, torch.Tensor) and torch.is_floating_point(v):\n                # cast and send to device\n                return v.to(*args, **kwargs)\n            elif isinstance(v, torch.Tensor) and device is not None:\n                return v.to(device=device, non_blocking=non_blocking)\n            # recursively handle lists and tuples\n            elif isinstance(v, (list, tuple)):\n                return type(v)(maybe_to(item) for item in v)\n            else:\n                return v\n\n        self.data = {k: maybe_to(v) for k, v in self.items()}\n        return self\n","sourceCodeStart":228,"sourceCodeEnd":264,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/feature_extraction_utils.py#L228-L264","documentation":"BatchFeature.to() parses its first positional argument as either a torch dtype, a device (string, torch.device, or int index), or unknown. If the first arg matches none of those (e.g. a numpy dtype, a module, a list), the code refuses with this ValueError rather than guessing a conversion.","triggerScenarios":"Calling batch.to(np.float32), batch.to(some_object), or chaining .to() with an argument shape modeled on another library where the first parameter is not a device/dtype.","commonSituations":"Passing numpy dtypes when porting numpy-heavy code; passing a tensor as the first arg; utilities that forward arbitrary kwargs into .to().","solutions":["Use a torch dtype or device: batch.to(torch.float32) or batch.to('cuda:0')","Convert numpy dtypes first: batch.to(torch.from_numpy(np.zeros(1, np.float32)).dtype) or simply torch.float32","Keep only floating-point tensors castable — note ints are moved to device but not dtype-cast by design"],"exampleFix":"# before\nbatch.to(np.float32)\n\n# after\nimport torch\nbatch.to(torch.float32)","handlingStrategy":"type-guard","validationCode":"import torch\n\ndef to_batch(batch, target):\n    if not (torch.is_tensor(target) or isinstance(target, (str, int)) or str(target).startswith(\"cuda\")):\n        target = torch.float32  # or raise\n    return batch.to(target)","typeGuard":"def is_valid_to_arg(arg) -> bool:\n    import torch\n    if isinstance(arg, torch.dtype):\n        return True\n    return isinstance(arg, (str, int, torch.device))","tryCatchPattern":"try:\n    batch.to(np_dtype)\nexcept ValueError as e:\n    if \"not supported\" in str(e):\n        import torch\n        batch.to({np.float32: torch.float32, np.float16: torch.float16}[np_dtype])\n    else:\n        raise","preventionTips":["Use torch dtypes and device strings in .to() calls","Map numpy dtypes to torch dtypes at the boundary","Do not forward arbitrary kwargs into BatchFeature.to()"],"tags":["feature-extractor","batchfeature","dtype","device","transformers"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}