Skip to content

llmcompressor.modeling.kimi_k3.kimi_k3_vision_processing

Image processor class for Kimi-K3.

Classes:

KimiK3VisionProcessor

KimiK3VisionProcessor(media_proc_cfg: dict, **kwargs)

Bases: BaseImageProcessor

Methods:

  • make_image_prompt –

    Build the K3 image placeholder with resolution info.

  • preprocess –

    Preprocess a atom vision input (images) into model-ready tensors.

Source code in src/llmcompressor/modeling/kimi_k3/kimi_k3_vision_processing.py
def __init__(
    self,
    media_proc_cfg: dict,
    **kwargs,
):
    super().__init__(**kwargs)
    self.media_proc_cfg = media_proc_cfg

make_image_prompt classmethod

make_image_prompt(width: int, height: int) -> str

Build the K3 image placeholder with resolution info.

Source code in src/llmcompressor/modeling/kimi_k3/kimi_k3_vision_processing.py
@classmethod
def make_image_prompt(cls, width: int, height: int) -> str:
    """Build the K3 image placeholder with resolution info."""
    return (
        f"<|media_begin|>image {width}x{height}"
        f"<|media_content|><|media_pad|><|media_end|>"
    )

preprocess

preprocess(
    medias: list[MediaInput],
    return_tensors: Optional[Union[str, TensorType]] = None,
) -> BatchFeature

Preprocess a atom vision input (images) into model-ready tensors.

Args: medias: List of MediaInput. return_tensors: Desired output format ('pt', 'np', 'tf', or None).

Returns: BatchFeature containing 'pixel_values' and 'grid_thws' tensors.

Source code in src/llmcompressor/modeling/kimi_k3/kimi_k3_vision_processing.py
def preprocess(
    self,
    medias: list[MediaInput],
    return_tensors: Optional[Union[str, TensorType]] = None,
) -> BatchFeature:
    """
    Preprocess a atom vision input (images) into model-ready tensors.

    Args:
        medias: List of MediaInput.
        return_tensors: Desired output format ('pt', 'np', 'tf', or None).

    Returns:
        BatchFeature containing 'pixel_values' and 'grid_thws' tensors.
    """
    if not isinstance(medias, list):
        medias = [medias]
    if medias:
        pixel_values = []
        for item in medias:
            item = ensure_media_type(
                item,
                transparent_bg_config=self._transparent_bg_config,
                transparent_bg_fill_stage=self._transparent_bg_fill_stage,
            )
            resize_config = self.get_resize_config(item)
            new_width, new_height, pad_width, pad_height = (
                resize_config["new_width"],
                resize_config["new_height"],
                resize_config["pad_width"],
                resize_config["pad_height"],
            )
            if item["type"] == "image":
                image = item["image"]
                image_np = self.resize_image(
                    image, new_width, new_height, pad_width, pad_height
                )
                pixel_values.append(np.expand_dims(image_np, axis=0))
            else:
                raise ValueError("Unsupported type: {}".format(item["type"]))
        normalized_pixel_values = []
        image_std_inv = 1.0 / np.array(self.media_proc_cfg["image_std"])
        image_mean = np.array(self.media_proc_cfg["image_mean"])
        for pixels in pixel_values:
            pixels = normalize(pixels, image_mean, image_std_inv)
            pixels_and_thw = navit_patchify(
                pixels,
                self.media_proc_cfg["patch_size"],
            )
            normalized_pixel_values.append(pixels_and_thw)

        pixel_values = torch.cat(
            [
                _to_tensor(pixel_value["pixel_values"])
                for pixel_value in normalized_pixel_values
            ]
        )
        grid_thws = torch.cat(
            [
                _to_tensor(pixel_value["grid_thw"], dtype=torch.int64).unsqueeze(0)
                for pixel_value in normalized_pixel_values
            ]
        )

        data = {
            "pixel_values": pixel_values,
            "grid_thws": grid_thws,
        }

    else:
        data = {}

    return BatchFeature(data=data, tensor_type=return_tensors)