Skip to content

mistral_common.tokens.tokenizers.image

ImageConfig(image_patch_size, max_image_size, spatial_merge_size=1) dataclass

Configuration for image tokenization.

Attributes:

Name Type Description
image_patch_size int

Size of a single image patch in pixels. The image grid is made of patches of this size; must be > 0.

max_image_size int

Maximum image dimension (width or height) in pixels before downsampling; must be > 0.

spatial_merge_size int

Number of adjacent patches merged into one image token along each dimension; must be > 0.

ImageEncoder(image_config, special_ids)

Encodes images into tokens and processed arrays.

An image is turned into a grid of patch tokens: each row is width_tokens img tokens terminated by an img_break token, and the last row ends with an img_end token. The image array is resized so its dimensions are multiples of the patch and merge sizes.

Parameters:

Name Type Description Default
image_config ImageConfig

Configuration controlling patch size, max image size, and spatial merging.

required
special_ids SpecialImageIDs

Token IDs used to mark image patches, row breaks, and the image end.

required
Source code in src/mistral_common/tokens/tokenizers/image.py
def __init__(self, image_config: ImageConfig, special_ids: SpecialImageIDs) -> None:
    r"""Initialize the image encoder.

    Args:
        image_config: Configuration controlling patch size, max image size,
            and spatial merging.
        special_ids: Token IDs used to mark image patches, row breaks, and
            the image end.
    """
    self.image_config = image_config
    self.special_ids = special_ids

image_token property

The token ID marking a single image patch.

Returns:

Type Description
int

The img special token ID.

mm_config property

Deprecated alias for image_config.

Returns:

Type Description
ImageConfig

The image config.

__call__(content)

Convert an image chunk into an image encoding.

The image is loaded, resized so its token grid covers the image, and encoded as img/img_break/img_end marker tokens plus the processed pixel array.

Parameters:

Name Type Description Default
content ImageChunk | ImageURLChunk

Image chunk to be converted.

required

Returns:

Type Description
ImageEncoding

An ImageEncoding with the marker tokens and the processed image

ImageEncoding

of shape (C, H, W).

Source code in src/mistral_common/tokens/tokenizers/image.py
def __call__(self, content: ImageChunk | ImageURLChunk) -> ImageEncoding:
    r"""Convert an image chunk into an image encoding.

    The image is loaded, resized so its token grid covers the image, and
    encoded as img/`img_break`/`img_end` marker tokens plus the processed
    pixel array.

    Args:
        content: Image chunk to be converted.

    Returns:
        An ImageEncoding with the marker tokens and the processed image
        of shape (C, H, W).
    """
    image = image_from_chunk(content)
    w, h = self._image_to_num_tokens(image)
    assert w > 0
    assert h > 0
    image_tokens = ([self.special_ids.img] * w + [self.special_ids.img_break]) * h
    image_tokens[-1] = self.special_ids.img_end
    new_image_size = (
        w * self.image_config.image_patch_size * self.image_config.spatial_merge_size,
        h * self.image_config.image_patch_size * self.image_config.spatial_merge_size,
    )
    processed_image = transform_image(image, new_image_size)
    return ImageEncoding(tokens=image_tokens, image=processed_image)

ImageEncoding(tokens, image) dataclass

A tokenized image.

Attributes:

Name Type Description
tokens list[int]

The token IDs representing the image (img/break/end markers).

image ndarray

The processed image as a numpy array of shape (C, H, W), normalized and resized for the model.

Examples:

>>> import numpy as np
>>> image_encoding = ImageEncoding(tokens=[1, 2, 3], image=np.array([[0., 0.5, 1.]]))

MultiModalVersion

Bases: str, Enum

Version of the image tokenizer.

Attributes:

Name Type Description
m1

The first multimodal version, patch size 16 and max image size 1024.

config property

The image config associated with this version.

Returns:

Type Description
ImageConfig

The ImageConfig for this multimodal version.

Raises:

Type Description
NotImplementedError

If the version has no config.

SpecialImageIDs(img, img_break, img_end) dataclass

Special image token IDs used to mark image regions in the token stream.

Attributes:

Name Type Description
img int

The token ID marking a single image patch.

img_break int

The token ID marking the end of an image row.

img_end int

The token ID marking the end of the whole image.

Examples:

>>> special_image_ids = SpecialImageIDs(img=1, img_break=2, img_end=3)

image_from_chunk(chunk)

Load a serializable image from a chunk.

Resolves the image from the chunk's data, accepting base64 data URLs, file URIs, and http(s) URLs.

Parameters:

Name Type Description Default
chunk ImageURLChunk | ImageChunk

The chunk to get the image from.

required

Returns:

Type Description
SerializableImage

The image as a PIL Image object.

Raises:

Type Description
ValueError

If a data URL does not contain a base64 payload or the URL scheme is unsupported.

Source code in src/mistral_common/tokens/tokenizers/image.py
def image_from_chunk(chunk: ImageURLChunk | ImageChunk) -> SerializableImage:
    r"""Load a serializable image from a chunk.

    Resolves the image from the chunk's data, accepting base64 data URLs,
    file URIs, and http(s) URLs.

    Args:
        chunk: The chunk to get the image from.

    Returns:
        The image as a PIL Image object.

    Raises:
        ValueError: If a data URL does not contain a base64 payload or the URL
            scheme is unsupported.
    """
    if isinstance(chunk, ImageChunk):
        return chunk.image
    url = chunk.get_url()
    if url.startswith("data:image"):
        _, _, data = url.partition(",")
        if not data:
            raise ValueError(f"Invalid image data URL {url[:64]}: expected a base64 payload after a comma.")
        image_data = base64.b64decode(data)
        return Image.open(BytesIO(image_data))
    if url.startswith("file://"):
        with open(url.removeprefix("file://"), "rb") as file:
            image = Image.open(file)
            image.load()
        return image
    if url.startswith("http"):
        return download_image(url=url, timeout=None)

    raise ValueError(f"Unsupported image url scheme {url}")

normalize(np_image, mean, std)

Normalize an image array with per-channel mean and standard deviation.

Parameters:

Name Type Description Default
np_image ndarray

Image to normalize, with shape (H, W, C) and values in [0, 255].

required
mean tuple[float, float, float]

Mean for each channel, values in [0, 1].

required
std tuple[float, float, float]

Standard deviation for each channel, values in [0, 1].

required

Returns:

Type Description
ndarray

Normalized image with shape (C, H, W), scaled to unit variance.

Raises:

Type Description
AssertionError

If np_image is not (H, W, C) or the channel count does not match mean and std.

Source code in src/mistral_common/tokens/tokenizers/image.py
def normalize(
    np_image: np.ndarray,
    mean: tuple[float, float, float],
    std: tuple[float, float, float],
) -> np.ndarray:
    r"""Normalize an image array with per-channel mean and standard deviation.

    Args:
        np_image: Image to normalize, with shape (H, W, C) and values in [0, 255].
        mean: Mean for each channel, values in [0, 1].
        std: Standard deviation for each channel, values in [0, 1].

    Returns:
        Normalized image with shape (C, H, W), scaled to unit variance.

    Raises:
        AssertionError: If `np_image` is not (H, W, C) or the channel count does
            not match mean and std.
    """
    np_image = np.divide(np_image, np.float32(255.0), dtype=np_image.dtype)

    assert len(np_image.shape) == 3, f"{np_image.shape=}"
    assert np_image.shape[2] == len(mean) == len(std), f"{np_image.shape=}, {mean=}, {std=}"

    mean_array = np.asarray(mean, dtype=np_image.dtype)
    std_array = np.asarray(std, dtype=np_image.dtype)

    np_image -= mean_array
    np_image /= std_array

    return np_image.transpose(2, 0, 1)

transform_image(image, new_size)

Resize and normalize an image for the model.

Converts to RGB (transparent backgrounds become white), resizes with cubic interpolation, then normalizes with the dataset statistics.

Parameters:

Name Type Description Default
image Image

PIL image to transform.

required
new_size tuple[int, int]

Target (width, height) in pixels.

required

Returns:

Type Description
ndarray

Transformed image with shape (C, H, W), normalized.

Raises:

Type Description
ImportError

If opencv is not installed.

Source code in src/mistral_common/tokens/tokenizers/image.py
def transform_image(image: Image.Image, new_size: tuple[int, int]) -> np.ndarray:
    r"""Resize and normalize an image for the model.

    Converts to RGB (transparent backgrounds become white), resizes with cubic
    interpolation, then normalizes with the dataset statistics.

    Args:
        image: PIL image to transform.
        new_size: Target (width, height) in pixels.

    Returns:
        Transformed image with shape (C, H, W), normalized.

    Raises:
        ImportError: If opencv is not installed.
    """
    assert_opencv_installed()

    np_image = cv2.resize(np.array(_convert_to_rgb(image), dtype=np.float32), new_size, interpolation=cv2.INTER_CUBIC)
    return normalize(np_image, DATASET_MEAN, DATASET_STD)