{"record":{"id":"685618a167675707","repo":"pola-rs/polars","slug":"pytorch-does-not-support-u16-u32-or-u64-dtypes","errorCode":null,"errorMessage":"PyTorch does not support u16, u32, or u64 dtypes; given {dtype}","messagePattern":"PyTorch does not support u16, u32, or u64 dtypes; given (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/dataframe/frame.py","lineNumber":2480,"sourceCode":"        ...     shuffle=True,\n        ...     batch_size=64,\n        ... )  # doctest: +SKIP\n        \"\"\"\n        if return_type not in (\"dataset\", \"dict\") and (\n            label is not None or features is not None\n        ):\n            msg = \"`label` and `features` only apply when `return_type` is 'dataset' or 'dict'\"\n            raise ValueError(msg)\n        elif return_type == \"dict\" and label is None and features is not None:\n            msg = \"`label` is required if setting `features` when `return_type='dict'\"\n            raise ValueError(msg)\n\n        torch = import_optional(\"torch\")\n\n        # Cast columns.\n        if dtype in (UInt16, UInt32, UInt64):\n            msg = f\"PyTorch does not support u16, u32, or u64 dtypes; given {dtype}\"\n            raise ValueError(msg)\n\n        to_dtype = dtype or {UInt16: Int32, UInt32: Int64, UInt64: Int64}\n\n        if label is not None:\n            label_frame = self.select(label)\n            # Avoid casting the label if it's an expression.\n            if not isinstance(label, pl.Expr):\n                label_frame = label_frame.cast(to_dtype)  # type: ignore[arg-type]\n            features_frame = (\n                self.select(features)\n                if features is not None\n                else self.drop(*label_frame.columns)\n            ).cast(to_dtype)  # type: ignore[arg-type]\n            frame = F.concat(\n                [label_frame, features_frame], how=\"horizontal\", strict=True\n            )\n        else:\n            label_frame = None","sourceCodeStart":2462,"sourceCodeEnd":2498,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/dataframe/frame.py#L2462-L2498","documentation":"Raised by DataFrame.to_torch when `dtype` is explicitly set to UInt16, UInt32, or UInt64. PyTorch tensors have no unsigned 16/32/64-bit dtypes, so those polars types cannot be represented faithfully. Note the asymmetry: if you do NOT pass dtype, polars auto-widens UInt16→Int32 and UInt32/UInt64→Int64; the error fires only when you explicitly request an unsigned dtype that torch cannot hold.","triggerScenarios":"`df.to_torch(dtype=pl.UInt32)`, `df.to_torch('dataset', label='y', dtype=pl.UInt64)` — any explicit unsigned (16/32/64) dtype argument. The check happens right after torch import and before casting.","commonSituations":"Schemas coming from parquet/arrow that use unsigned ints (IDs, counters, hashes) passed straight through as a cast target; porting numpy pipelines that used uint32; attempting to preserve exact bit-width when moving data into torch.","solutions":["Drop the dtype argument and let polars auto-cast: UInt16→Int32, UInt32/UInt64→Int64 happen automatically","Or cast to a supported signed dtype yourself: `df.to_torch(dtype=pl.Int32)`","Ensure values fit the widened signed range before relying on the automatic cast"],"exampleFix":"# before\nt = df.to_torch(dtype=pl.UInt32)\n\n# after\nt = df.to_torch(dtype=pl.Int32)\n# or simply let polars widen automatically:\nt = df.to_torch()","handlingStrategy":"validation","validationCode":"UNSUPPORTED = (pl.UInt16, pl.UInt32, pl.UInt64)\nif dtype in UNSUPPORTED:\n    raise ValueError(f'torch cannot represent {dtype}; widen to a signed dtype')\nt = df.to_torch(dtype=dtype)","typeGuard":"def torch_castable(dtype: pl.DataType) -> bool:\n    \"\"\"False for unsigned 16/32/64 dtypes torch cannot represent.\"\"\"\n    return dtype not in (pl.UInt16, pl.UInt32, pl.UInt64)","tryCatchPattern":"try:\n    t = df.to_torch(dtype=dtype)\nexcept ValueError as e:\n    if 'u16, u32, or u64' in str(e):\n        t = df.to_torch()  # let polars auto-widen UInt16->Int32, UInt32/64->Int64\n    else:\n        raise","preventionTips":["Omit dtype for unsigned frames; polars auto-widens to Int32/Int64","Validate schema dtypes against torch-supported sets before ML export","Check value ranges fit the widened signed dtype after automatic casting"],"tags":["torch","dtype","unsigned-integer","ml"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}