# 多模态处理器

Processor 将 tokenizer 与一个或多个模态处理器（例如图像处理器、视频处理器或特征提取器）组合在一起。它暴露了一个 `__call__` 方法，该方法将每个输入路由到相应的组件，并将输出合并为一个字典。

某些多模态模型会将文本与图像、视频或音频交错排列。对于这些模型，[ProcessorMixin](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessorMixin) 可以将 `<image>`、`<video>` 和 `<audio>` 等占位符 token 替换为模型所期望的 token 模式。

## 添加新的处理器

通过创建 `src/transformers/models/<model>/processing_<my_model_name>.py` 并继承 `ProcessorMixin` 来定义一个处理器类。请确保定义一个带有默认值的 `TypedDict` 对象，并将其赋值给 `cls.valid_processor_kwargs`。

```python
from ...processing_utils import ProcessorMixin

class MyModelProcessor(ProcessorMixin):

    def __init__(self, image_processor, tokenizer, chat_template=None, **kwargs):
        self.image_token = tokenizer.image_token
        self.image_token_id = tokenizer.image_token_id
        super().__init__(
            image_processor=image_processor,
            tokenizer=tokenizer,
            chat_template=chat_template,
            **kwargs,
        )
```

如有需要，请实现 `replace_<modality>_token`。它接收来自子处理器的完整输出字典以及当前输入的索引，并返回针对该输入的展开替换字符串。替换字符串即模型在输入序列中所期望的内容。

如果模型完全不使用占位符重复（未定义 `image_token`），则无需重写此方法。保持 `self.image_token` 未设置，基类将完全跳过替换操作。

```python
def replace_image_token(self, image_inputs: dict, image_idx: int) -> str:
    num_crops = image_inputs["num_crops"][image_idx]
    return f"{self.boi_token}{self.image_token * self.num_image_tokens * num_crops}{self.eoi_token}"
```

可选择性地重写 `prepare_inputs_layout` 和 `validate_inputs` 方法。如果模型在处理开始前需要特定的输入结构，例如将图像重新排序为嵌套列表，或者在通用检查之上进行模型特定的验证。

```python
def prepare_inputs_layout(self, images=None, text=None, videos=None, audio=None, **kwargs):
    # Call `super()` to apply common preparation steps first 
    images, text, videos, audio = super().prepare_inputs_layout(images, text, videos, audio)
    if images is not None:
        images = make_nested_list_of_images(images)
    return images, text, videos, audio

def validate_inputs(self, images=None, text=None, videos=None, audio=None, **kwargs):
    super().validate_inputs(images=images, text=text, **kwargs)
    if text is not None and images is not None:
        n_tokens = [s.count(self.image_token) for s in text]
        n_images = [len(img_list) for img_list in images]
        if n_tokens != n_images:
            raise ValueError(
                f"Number of {self.image_token} tokens in text {n_tokens} does not match "
                f"number of images {n_images}."
            )
```

> [!TIP]
> 请参阅 [Gemma4Processor](/docs/transformers/main/zh/model_doc/gemma4#transformers.Gemma4Processor) 和 [Qwen2VLProcessor](/docs/transformers/main/zh/model_doc/qwen2_vl#transformers.Qwen2VLProcessor) 作为参考。

### 添加自定义参数

向处理器添加自定义参数有三种方式：

| 添加位置 | 用于 | 默认值 | 可在运行时配置 | 示例 |
|---|---|---|---|---|
| `__init__` | 保存在配置（模型属性）中的设置 | 通常具有默认值 | No | [Gemma3Processor](/docs/transformers/main/zh/model_doc/gemma3#transformers.Gemma3Processor) 中的 `image_seq_length` |
| `__call__` | 仅在运行时已知的输入 | 无默认值或 `None` | 是的 | `images`、`labels`、`suffix` 等。 |
| 自定义 `MyModelProcessingKwargs` 类 | 可在运行时配置的设置 | 设置为处理器类属性 | 是的 | [MiniCPMV4_7Processor](/docs/transformers/main/zh/model_doc/minicpmv4_7#transformers.MiniCPMV4_7Processor) 中的 `use_image_id` |

具有默认值的运行时参数必须添加到自定义的 `MyModelProcessingKwargs` 中，并作为 `**kwargs` 的一部分传递给 `__call__`。这些值的默认值可以设置为处理器类的属性。模态特定处理器（例如分词器或图像处理器）的默认值也可以以相同方式定义。通常不需要这样做，因为模态特定处理器已在各自的类中定义了默认值。仅当处理器必须覆盖模态特定处理器的设置时，才使用此选项。当然，在运行时传递给 `__call__` 的参数始终具有比任何默认值更高的优先级。

```python
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack

class MyModelProcessorKwargs(ProcessingKwargs, total=False):
    """
    use_image_id (`bool`, defaults to `False`):
        Whether to prepend an image-id tag (``<image_id>N</image_id>``) before
        each image placeholder.
    """
    use_image_id: bool

class MyModelProcessor(ProcessorMixin):
    valid_processor_kwargs = MyModelProcessorKwargs
    use_image_id = False

    text_kwargs = {"padding": True}   # default passed to tokenizer

    def __init__(self, image_processor=None, tokenizer=None, chat_template=None, image_seq_length: int = 256, **kwargs):
        super().__init__(image_processor, tokenizer, chat_template=chat_template, **kwargs)
        self.image_seq_length = image_seq_length

    @auto_docstring
    def __call__(
        self,
        images: ImageInput | None = None,
        text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
        suffix: str | None = None,
        **kwargs: Unpack[MyModelProcessorKwargs],
    ):
        images, text, videos, audio = self.prepare_inputs_layout(images=images, text=text, **kwargs)
        self.validate_inputs(images=images, text=text, **kwargs)

        merged_kwargs = self._merge_kwargs(tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs)

        merged_kwargs["use_image_id"] # is `False` as default from class attribute is added by _merge_kwargs
        merged_kwargs["text_kwargs"]["padding"] # is `True`
```

## 测试

所有多模态处理器都应包含一个继承自 `ProcessorTesterMixin` 的测试类。该混入类提供了一套标准测试，涵盖分词、图像处理、批处理以及往返编码。

```python
# tests/models/my_model_name/test_processor_<my_model_name>.py

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available
from ...test_processing_common import ProcessorTesterMixin

if is_vision_available():
    from transformers import MyModelProcessor

@require_vision
class MyModelProcessorTest(ProcessorTesterMixin, unittest.TestCase):
    processor_class = MyModelProcessor

    def get_processor(self):
        return MyModelProcessor.from_pretrained("hf-internal-testing/my-model-test")
```

