{"record":{"id":"53ce2d7d8b1ef531","repo":"Comfy-Org/ComfyUI","slug":"expected-4d-image-tensor-got-type-item-name","errorCode":null,"errorMessage":"Expected 4D image tensor, got {type(item).__name__} shape {getattr(item, 'shape', None)}","messagePattern":"Expected 4D image tensor, got (.+?) shape (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"comfy_extras/nodes_dataset.py","lineNumber":660,"sourceCode":"        if not has_process and not has_group:\n            raise ValueError(\n                f\"{cls.__name__}: Must override either _process or _group_process\"\n            )\n\n        return has_group\n\n    @classmethod\n    def _ensure_image_list(cls, images):\n        \"\"\"Normalize to a flat list of [1, H, W, C] tensors.\"\"\"\n        if isinstance(images, torch.Tensor):\n            if images.ndim != 4:\n                raise ValueError(f\"Expected 4D image tensor, got shape {tuple(images.shape)}\")\n            return [images[i:i+1] for i in range(images.shape[0])]\n\n        flat = []\n        for item in images:\n            if not isinstance(item, torch.Tensor) or item.ndim != 4:\n                raise ValueError(f\"Expected 4D image tensor, got {type(item).__name__} shape {getattr(item, 'shape', None)}\")\n            flat.extend([item[i:i+1] for i in range(item.shape[0])])\n        return flat\n\n    @classmethod\n    def define_schema(cls):\n        if cls.node_id is None:\n            raise NotImplementedError(f\"{cls.__name__} must set node_id class variable\")\n\n        is_group = cls._detect_processing_mode()\n\n        # Auto-detect is_output_list if not explicitly set\n        # Single processing: False (backend collects results into list)\n        # Group processing: True by default (can be False for single-output nodes)\n        output_is_list = (\n            cls.is_output_list if cls.is_output_list is not None else is_group\n        )\n\n        inputs = [","sourceCodeStart":642,"sourceCodeEnd":678,"githubUrl":"https://github.com/Comfy-Org/ComfyUI/blob/1c6d8d45b3693bfbb32385b410d813a7fd6be216/comfy_extras/nodes_dataset.py#L642-L678","documentation":"The second branch of _ensure_image_list handles iterables of tensors: each item must itself be a 4D torch.Tensor. This raise covers both failure modes at once — a non-tensor item (type name shown) and a wrong-dimensionality tensor (shape shown via getattr) — producing one message that names the offending item's type and shape.","triggerScenarios":"Passing a list like [np.ndarray, ...], [tensor_3d, ...], [None], or mixed tensor/PIL lists to a dataset processing node. Any single bad item aborts the whole flatten.","commonSituations":"Heterogeneous lists built from multiple sources (some numpy, some tensors); per-item slicing that dropped batch dims on only some entries; empty non-tensor sentinels mixed into results.","solutions":["Normalize every list item to a 4D tensor: convert numpy via torch.from_numpy(...).permute(2,0,1).unsqueeze(0).","Ensure per-item slices keep 4D: use images[i:i+1], not images[i].","Drop or convert non-tensor entries before calling the node."],"exampleFix":"# before\nimgs = [images[i] for i in range(images.shape[0])]     # each (H, W, C)\n# after\nimgs = [images[i:i + 1] for i in range(images.shape[0])]  # each (1, H, W, C)","handlingStrategy":"type-guard","validationCode":"import torch\ndef flatten_batches(items):\n    flat = []\n    for it in items:\n        if not isinstance(it, torch.Tensor) or it.ndim != 4:\n            raise TypeError(f\"bad item {type(it).__name__}\")\n        flat.extend([it[i:i+1] for i in range(it.shape[0])])\n    return flat","typeGuard":"def all_4d_tensors(items) -> bool:\n    return all(isinstance(it, torch.Tensor) and it.ndim == 4 for it in items)","tryCatchPattern":null,"preventionTips":["Slice batches with [i:i+1] to keep 4D per-item tensors.","Convert numpy items with torch.from_numpy(...).permute(2,0,1).unsqueeze(0).","Don't mix PIL, numpy, and tensor items in one list."],"tags":["dataset","tensor-shape","type-guard","comfyui"],"backgroundTag":null,"analyzedSha":"1c6d8d45b3693bfbb32385b410d813a7fd6be216","analyzedAt":"2026-08-14T19:37:18.893Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}