Lightning-AI/pytorch-lightning · error · ValueError

Expected {n} items but only found {len(v)} for {k}

Error message

Expected {n} items but only found {len(v)} for {k}

What it means

In WandbLogger.log_image, every kwarg (e.g. caption, masks) must be a list whose length equals len(images), because items are zipped positionally to build wandb.Image objects. A length mismatch raises this ValueError naming the offending kwarg.

Source

Thrown at src/lightning/pytorch/loggers/wandb.py:496

        Can be defined either with `columns` and `data` or with `dataframe`.

        """

        self.log_table(key, columns, data, dataframe, step)

    @rank_zero_only
    def log_image(self, key: str, images: list[Any], step: Optional[int] = None, **kwargs: Any) -> None:
        """Log images (tensors, numpy arrays, PIL Images or file paths).

        Optional kwargs are lists passed to each image (ex: caption, masks, boxes).

        """
        if not isinstance(images, list):
            raise TypeError(f'Expected a list as "images", found {type(images)}')
        n = len(images)
        for k, v in kwargs.items():
            if len(v) != n:
                raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
        kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]

        import wandb

        metrics = {key: [wandb.Image(img, **kwarg) for img, kwarg in zip(images, kwarg_list)]}
        self.log_metrics(metrics, step)  # type: ignore[arg-type]

    @rank_zero_only
    def log_audio(self, key: str, audios: list[Any], step: Optional[int] = None, **kwargs: Any) -> None:
        r"""Log audios (numpy arrays, or file paths).

        Args:
            key: The key to be used for logging the audio files
            audios: The list of audio file paths, or numpy arrays to be logged
            step: The step number to be used for logging the audio files
            \**kwargs: Optional kwargs are lists passed to each ``Wandb.Audio`` instance (ex: caption, sample_rate).

        Optional kwargs are lists passed to each audio (ex: caption, sample_rate).

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. Make each kwarg list length equal len(images)
  2. For a shared caption, replicate it: caption=[c] * len(images)
  3. Compute captions per image from the batch before calling

Example fix

# before
logger.log_image([im1, im2], caption=["generated"])
# after
logger.log_image([im1, im2], caption=["generated"] * 2)
Defensive patterns

Strategy: validation

Validate before calling

n = len(images)
kwargs = {k: (v * n if isinstance(v, str) else v) for k, v in kwargs.items()}
assert all(len(v) == n for v in kwargs.values())

Prevention

When it happens

Trigger: logger.log_image([img1, img2, img3], caption=["only one caption"]) — 3 images but a 1-element caption list; same for masks/boxes lists of any differing length.

Common situations: Passing a single string caption for multiple images, or reusing a captions list computed for a previous batch size.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/26895a22e81412e6. Report an issue: GitHub.