{"record":{"id":"5c5765413c4f39a7","repo":"Comfy-Org/ComfyUI","slug":"expected-torch-tensor-got-type-img-tensor","errorCode":null,"errorMessage":"Expected torch.Tensor, got {type(img_tensor)}","messagePattern":"Expected torch\\.Tensor, got (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"comfy_extras/nodes_dataset.py","lineNumber":432,"sourceCode":"                img_tensor = img_tensor.squeeze(0)\n\n            # If tensor is [C, H, W], permute to [H, W, C]\n            if img_tensor.dim() == 3 and img_tensor.shape[0] in [1, 3, 4]:\n                if (\n                    img_tensor.shape[0] <= 4\n                    and img_tensor.shape[1] > 4\n                    and img_tensor.shape[2] > 4\n                ):\n                    img_tensor = img_tensor.permute(1, 2, 0)\n\n            # Convert to numpy and scale to 0-255\n            img_array = img_tensor.cpu().numpy()\n            img_array = np.clip(img_array * 255.0, 0, 255).astype(np.uint8)\n\n            # Convert to PIL Image\n            img = Image.fromarray(img_array)\n        else:\n            raise ValueError(f\"Expected torch.Tensor, got {type(img_tensor)}\")\n\n        # Save image\n        if overwrite:\n            filename = f\"{prefix}_{idx:05d}.png\"\n        else:\n            _, _, counter, _, resolved_prefix = folder_paths.get_save_image_path(prefix, output_dir)\n            filename = f\"{resolved_prefix}_{counter:05}_{idx:05d}.png\"\n        filepath = os.path.join(output_dir, filename)\n        img.save(filepath)\n        saved_files.append(filename)\n\n    return saved_files\n\n\nclass SaveImageDataSetToFolderNode(io.ComfyNode):\n    @classmethod\n    def define_schema(cls):\n        return io.Schema(","sourceCodeStart":414,"sourceCodeEnd":450,"githubUrl":"https://github.com/Comfy-Org/ComfyUI/blob/1c6d8d45b3693bfbb32385b410d813a7fd6be216/comfy_extras/nodes_dataset.py#L414-L450","documentation":"The dataset-save helper accepts either PIL Images or torch tensors per item; when an item is neither, the else branch raises naming the actual type. The preceding code already handles tensors including CHW->HWC permute, so this error specifically means the iterable passed as images contains a foreign object (str path, numpy array, list, None).","triggerScenarios":"Passing a list containing numpy arrays, file-path strings, or None instead of torch.Tensor / PIL.Image entries — e.g. feeding raw generator output lists or JSON-derived structures straight into the save-dataset node.","commonSituations":"Version drift where an upstream node changed output from tensors to numpy or to a dict payload; user scripts assembling the list manually and forgetting conversions; None placeholders for skipped items.","solutions":["Convert every item to a torch tensor before saving: torch.from_numpy(arr) for numpy, PILToTensor for images.","Filter out None/str entries before passing the list.","Check the upstream node's declared output type and insert the appropriate conversion node."],"exampleFix":"# before\nimages = [np.array(pil_img)]\n# after\nimages = [torch.from_numpy(np.array(pil_img)).permute(2, 0, 1)]","handlingStrategy":"type-guard","validationCode":"import torch, numpy as np\ndef coerce_item(x):\n    if isinstance(x, torch.Tensor):\n        return x\n    if isinstance(x, np.ndarray):\n        return torch.from_numpy(x)\n    if hasattr(x, \"convert\"):  # PIL\n        return PILToTensor()(x)\n    raise TypeError(f\"cannot coerce {type(x)!r}\")","typeGuard":"def is_savable(x) -> bool:\n    return hasattr(x, \"save\") or isinstance(x, torch.Tensor)","tryCatchPattern":"try:\n    save_dataset(images)\nexcept ValueError as e:\n    if \"Expected torch.Tensor\" in str(e):\n        images = [coerce_item(x) for x in images]\n        save_dataset(images)\n    else:\n        raise","preventionTips":["Convert numpy/PIL to tensors at the boundary, not at save time.","Filter None and str entries out of image lists before saving.","Re-check upstream node output types after upgrading custom nodes."],"tags":["dataset","type-error","tensor","comfyui"],"backgroundTag":null,"analyzedSha":"1c6d8d45b3693bfbb32385b410d813a7fd6be216","analyzedAt":"2026-08-14T19:37:18.893Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}