Transformers documentation

マルチモーダルプロセッサ

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

マルチモーダルプロセッサ

プロセッサーは、トークナイザーと、画像プロセッサー、動画プロセッサー、特徴量抽出器などの1つ以上のモダリティプロセッサーを組み合わせます。単一の__call__メソッドを公開し、各入力を適切なコンポーネントにルーティングして、出力を1つの辞書にマージします。

一部のマルチモーダルモデルでは、テキストと画像、動画、またはオーディオが交互に配置されます。これらのモデルでは、ProcessorMixinを使用して、<image>、<video>、<audio>などのプレースホルダトークンを、モデルが期待するトークンパターンに置き換えることができます。

新しいプロセッサの追加

src/transformers/models/<model>/processing_<my_model_name>.py を作成し、ProcessorMixin をサブクラス化することで、プロセッサークラスを定義します。デフォルト値を持つ TypedDict オブジェクトを定義し、それを cls.valid_processor_kwargs に割り当てることを忘れないでください。

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 を設定せずにしておくと、ベースクラスは置換を完全にスキップします。

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 メソッドをオーバーライドできます。これは、処理を開始する前に特定の入力構造が必要となる場合(画像をネストされたリストとして並べ替えるなど)、または共通のチェックに加えてモデル固有の検証を行う場合に使用します。

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}."
            )

参考として、Gemma4Processor と Qwen2VLProcessor をご覧ください。

カスタム引数の追加

プロセッサーにカスタム引数を追加するには、3つの方法があります。

追加する場所用途デフォルト値実行時に設定可能例
__init__設定(モデルのプロパティ)として config に保存されるもの通常、デフォルト値がありますいいえGemma3Processor の image_seq_length
__call__実行時にのみ判明する入力デフォルト値なしまたはNoneはいimages、labels、suffix など
カスタム MyModelProcessingKwargs クラス実行時に設定できる設定プロセッサクラスの属性として設定はいMiniCPMV4_7Processor の use_image_id

デフォルト値を持つことのできるランタイム引数は、カスタムのMyModelProcessingKwargsに追加する必要があり、__call__に**kwargsの一部として渡されます。これらの値のデフォルトは、プロセッサクラスの属性として設定できます。モダリティ固有のプロセッサ(トークナイザや画像プロセッサなど)のデフォルトも、同様に定義できます。ただし、モダリティ固有のプロセッサは通常、それぞれのクラス内でデフォルトが定義済みのため、この設定は必要ありません。プロセッサがモダリティ固有のプロセッサの設定を上書きする必要がある場合のみ、このオプションを使用してください。もちろん、__call__にランタイムで渡された引数は、常にすべてのデフォルトよりも優先されます。

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を継承するテストクラスが必要です。このミックスインは、トークナイズ、画像処理、バッチ処理、およびラウンドトリップエンコーディングをカバーする標準的なテストスイートを提供します。

# 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")
Update on GitHub