{"record":{"id":"71778f5c43491c7e","repo":"lllyasviel/Fooocus","slug":"input-has-x-ndim-dims-but-target-dims-is-target","errorCode":null,"errorMessage":"input has {x.ndim} dims but target_dims is {target_dims}, which is less","messagePattern":"input has (.+?) dims but target_dims is (.+?), which is less","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"ldm_patched/k_diffusion/utils.py","lineNumber":25,"sourceCode":"import warnings\n\nfrom PIL import Image\nimport torch\nfrom torch import nn, optim\nfrom torch.utils import data\n\n\ndef hf_datasets_augs_helper(examples, transform, image_key, mode='RGB'):\n    \"\"\"Apply passed in transforms for HuggingFace Datasets.\"\"\"\n    images = [transform(image.convert(mode)) for image in examples[image_key]]\n    return {image_key: images}\n\n\ndef append_dims(x, target_dims):\n    \"\"\"Appends dimensions to the end of a tensor until it has target_dims dimensions.\"\"\"\n    dims_to_append = target_dims - x.ndim\n    if dims_to_append < 0:\n        raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')\n    expanded = x[(...,) + (None,) * dims_to_append]\n    # MPS will get inf values if it tries to index into the new axes, but detaching fixes this.\n    # https://github.com/pytorch/pytorch/issues/84364\n    return expanded.detach().clone() if expanded.device.type == 'mps' else expanded\n\n\ndef n_params(module):\n    \"\"\"Returns the number of trainable parameters in a module.\"\"\"\n    return sum(p.numel() for p in module.parameters())\n\n\ndef download_file(path, url, digest=None):\n    \"\"\"Downloads a file if it does not exist, optionally checking its SHA-256 hash.\"\"\"\n    path = Path(path)\n    path.parent.mkdir(parents=True, exist_ok=True)\n    if not path.exists():\n        with urllib.request.urlopen(url) as response, open(path, 'wb') as f:\n            shutil.copyfileobj(response, f)","sourceCodeStart":7,"sourceCodeEnd":43,"githubUrl":"https://github.com/lllyasviel/Fooocus/blob/ae05379cc97bc4361ec8b4ec90193dab21be763f/ldm_patched/k_diffusion/utils.py#L7-L43","documentation":"append_dims(x, target_dims) right-pads a tensor with trailing singleton dimensions so broadcasting against latents works (e.g. turning a B-dimensional sigma into Bx1x1x1). It can only add dimensions, never remove or reorder; if x already has more dims than target_dims the required broadcast would be ill-formed and it raises ValueError.","triggerScenarios":"append_dims(sigma_tensor /*4 dims*/, 4) where x is BxCxHxW but target is 4 from a scalar context; appending a C=4 tensor to target_dims=2; passing a full-rank tensor where the code expects a batch-vector. Typical when model wrappers return richer-shaped conditioning/sigma tensors than the sampler expects.","commonSituations":"Custom samplers or hooks calling append_dims on tensors that are already latent-shaped; conditioning tensors (B,4,H,W) routed into a sigma-like append_dims call; refactors that change x from vector to image-shaped.","solutions":["Pass the lower-rank operand: append_dims(sigma, x.ndim) with sigma of shape (B,) — this is the canonical use.","If x has excess dims, flatten/squeeze them first: x = x.reshape(x.shape[0], *ones) or index the needed slice.","Check what target_dims you computed — it should be x.ndim (e.g. 4 for latents), applied to the *vector* operand, not to the latent itself.","For genuinely mismatched ranks, broadcast manually with slicing instead of append_dims."],"exampleFix":"# before\nsigmas = torch.rand(4, 4, 8, 8)          # accidentally latent-shaped\nout = append_dims(sigmas, 2)              # ValueError\n\n# after\nsigmas = torch.rand(4)                    # batch vector\nout = append_dims(sigmas, 4)              # 4x1x1x1, broadcasts with 4x4x8x8","handlingStrategy":"type-guard","validationCode":"if x.ndim > target_dims:\n    raise ValueError(f'cannot append dims: x has {x.ndim} dims, target is {target_dims}')\n# canonical usage: append_dims(batch_vector, latent.ndim)","typeGuard":"def can_append_dims(x: torch.Tensor, target_dims: int) -> bool:\n    return x.ndim <= target_dims","tryCatchPattern":"try:\n    out = append_dims(x, target_dims)\nexcept ValueError as e:\n    if 'target_dims' in str(e):\n        raise ValueError(f'append_dims misuse: pass the lower-rank operand; x.ndim={x.ndim}, target={target_dims}') from e\n    raise","preventionTips":["Use the idiom append_dims(vector, latent.ndim) — never append a latent-shaped tensor.","Assert operand ranks before broadcasting-heavy sampler code.","Remember append_dims only adds trailing singleton dims; it never removes or reorders."],"tags":["k-diffusion","broadcasting","tensor-shape","utility"],"backgroundTag":null,"analyzedSha":"ae05379cc97bc4361ec8b4ec90193dab21be763f","analyzedAt":"2026-08-15T04:23:59.533Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}