lllyasviel/Fooocus · error · ValueError

input has {x.ndim} dims but target_dims is {target_dims}, wh

Error message

input has {x.ndim} dims but target_dims is {target_dims}, which is less

What it means

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.

Source

Thrown at ldm_patched/k_diffusion/utils.py:25

import warnings

from PIL import Image
import torch
from torch import nn, optim
from torch.utils import data


def hf_datasets_augs_helper(examples, transform, image_key, mode='RGB'):
    """Apply passed in transforms for HuggingFace Datasets."""
    images = [transform(image.convert(mode)) for image in examples[image_key]]
    return {image_key: images}


def append_dims(x, target_dims):
    """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
    dims_to_append = target_dims - x.ndim
    if dims_to_append < 0:
        raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')
    expanded = x[(...,) + (None,) * dims_to_append]
    # MPS will get inf values if it tries to index into the new axes, but detaching fixes this.
    # https://github.com/pytorch/pytorch/issues/84364
    return expanded.detach().clone() if expanded.device.type == 'mps' else expanded


def n_params(module):
    """Returns the number of trainable parameters in a module."""
    return sum(p.numel() for p in module.parameters())


def download_file(path, url, digest=None):
    """Downloads a file if it does not exist, optionally checking its SHA-256 hash."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    if not path.exists():
        with urllib.request.urlopen(url) as response, open(path, 'wb') as f:
            shutil.copyfileobj(response, f)

View on GitHub (pinned to ae05379cc9)

Solutions

  1. Pass the lower-rank operand: append_dims(sigma, x.ndim) with sigma of shape (B,) — this is the canonical use.
  2. If x has excess dims, flatten/squeeze them first: x = x.reshape(x.shape[0], *ones) or index the needed slice.
  3. 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.
  4. For genuinely mismatched ranks, broadcast manually with slicing instead of append_dims.

Example fix

# before
sigmas = torch.rand(4, 4, 8, 8)          # accidentally latent-shaped
out = append_dims(sigmas, 2)              # ValueError

# after
sigmas = torch.rand(4)                    # batch vector
out = append_dims(sigmas, 4)              # 4x1x1x1, broadcasts with 4x4x8x8
Defensive patterns

Strategy: type-guard

Validate before calling

if x.ndim > target_dims:
    raise ValueError(f'cannot append dims: x has {x.ndim} dims, target is {target_dims}')
# canonical usage: append_dims(batch_vector, latent.ndim)

Type guard

def can_append_dims(x: torch.Tensor, target_dims: int) -> bool:
    return x.ndim <= target_dims

Try / catch

try:
    out = append_dims(x, target_dims)
except ValueError as e:
    if 'target_dims' in str(e):
        raise ValueError(f'append_dims misuse: pass the lower-rank operand; x.ndim={x.ndim}, target={target_dims}') from e
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of lllyasviel/Fooocus@ae05379cc9 (2026-08-15). Data as JSON: /api/errors/71778f5c43491c7e. Report an issue: GitHub.