huggingface/transformers · error · ValueError

Invalid channel dimension format: {input_data_format}

Error message

Invalid channel dimension format: {input_data_format}

What it means

Raised by `transformers.image_utils.get_max_height_width` when `input_data_format` (default `ChannelDimension.FIRST`) is neither FIRST nor LAST. The function takes the elementwise max of image shapes across a batch and unpacks the result as (_, H, W) or (H, W, _) depending on layout; an unrecognized format makes the unpacking undefined, so it raises. Unlike sibling functions, the default is FIRST rather than None (no inference happens here).

Source

Thrown at src/transformers/image_utils.py:427

def max_across_indices(values: Iterable[Any]) -> list[Any]:
    """
    Return the maximum value across all indices of an iterable of values.
    """
    return [max(values_i) for values_i in zip(*values)]


def get_max_height_width(
    images: list[Union["torch.Tensor", np.ndarray]], input_data_format: str | ChannelDimension = ChannelDimension.FIRST
) -> list[int]:
    """
    Get the maximum height and width across all images in a batch.
    """
    if input_data_format == ChannelDimension.FIRST:
        _, max_height, max_width = max_across_indices([img.shape for img in images])
    elif input_data_format == ChannelDimension.LAST:
        max_height, max_width, _ = max_across_indices([img.shape for img in images])
    else:
        raise ValueError(f"Invalid channel dimension format: {input_data_format}")
    return (max_height, max_width)


def is_valid_annotation_coco_detection(annotation: dict[str, list | tuple]) -> bool:
    if (
        isinstance(annotation, dict)
        and "image_id" in annotation
        and "annotations" in annotation
        and isinstance(annotation["annotations"], (list, tuple))
        and (
            # an image can have no annotations
            len(annotation["annotations"]) == 0 or isinstance(annotation["annotations"][0], dict)
        )
    ):
        return True
    return False

View on GitHub (pinned to a597f97485)

Solutions

  1. Pass `ChannelDimension.FIRST` or `ChannelDimension.LAST` (or exact strings 'channels_first'/'channels_last').
  2. Remember the default assumes channels-first; channels-last batches must pass it explicitly.
  3. Validate config-supplied strings with `ChannelDimension(value)` before use.

Example fix

// before
mh, mw = get_max_height_width(imgs, input_data_format="channels-last")  # ValueError

// after
from transformers.image_utils import ChannelDimension
mh, mw = get_max_height_width(imgs, input_data_format=ChannelDimension.LAST)
Defensive patterns

Strategy: validation

Validate before calling

from transformers.image_utils import ChannelDimension

input_data_format = ChannelDimension(input_data_format)  # validate once
mh, mw = get_max_height_width(images, input_data_format=input_data_format)

Type guard

from transformers.image_utils import ChannelDimension

def is_valid_batch_layout(v) -> bool:
    return v in (ChannelDimension.FIRST, ChannelDimension.LAST, "channels_first", "channels_last")

Prevention

When it happens

Trigger: Calling `get_max_height_width(images, input_data_format='channels-last')` (hyphen typo), 'NCHW', 'HWC', or any non-enum string when padding a batch to the largest image.

Common situations: Custom batched-padding code; layouts hard-coded from other frameworks; a default that surprises users whose data is channels-last — they override the string and mistype it.

Related errors


AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14). Data as JSON: /api/errors/04d46d069d099bcb. Report an issue: GitHub.