Transformers documentation

Pemroses multimodal

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Pemroses multimodal

Processor menggabungkan tokenizer dengan satu atau beberapa pemroses modalitas, seperti image processor, video processor, atau feature extractor. Ia mengekspos satu metode __call__ yang mengarahkan setiap input ke komponen yang tepat dan menggabungkan output menjadi satu dictionary.

Beberapa model multimodal menyisipkan teks dengan gambar, video, atau audio. Untuk model-model ini, ProcessorMixin dapat mengganti token placeholder seperti <image>, <video>, dan <audio> dengan pola token yang diharapkan oleh model.

Menambahkan prosesor baru

Definisikan kelas prosesor dengan membuat src/transformers/models/<model>/processing_<my_model_name>.py dan subclass ProcessorMixin. Pastikan untuk mendefinisikan objek TypedDict dengan nilai default dan menugaskannya sebagai cls.valid_processor_kwargs

from ...processing_utils import ProcessorMixin, ProcessingKwargs, Unpack

class MyModelProcessorKwargs(ProcessingKwargs, total=False):
    images_kwargs: MyModelImageProcessorKwargs
    _defaults = {
        "text_kwargs": {"padding": True},
        "images_kwargs": {"do_convert_rgb": True},
    }

class MyModelProcessor(ProcessorMixin):
    valid_processor_kwargs = MyModelProcessorKwargs

    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,
        )

Implementasikan replace_<modality>_token jika diperlukan. Fungsi ini menerima dict output lengkap dari subprocessor dan indeks dari input saat ini, lalu mengembalikan string penggantian yang telah diperluas untuk input tersebut. String penggantian adalah apa pun yang diharapkan oleh model dalam urutan input.

Jika model sama sekali tidak menggunakan pengulangan placeholder (tidak ada image_token yang didefinisikan), Anda tidak perlu menimpa metode ini. Biarkan self.image_token tidak disetel dan kelas dasar akan sepenuhnya melewati proses penggantian.

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

Secara opsional, timpa metode prepare_inputs_layout dan validate_inputs. Jika model memerlukan struktur input tertentu sebelum pemrosesan dimulai, seperti pengurutan ulang gambar sebagai daftar bersarang, atau validasi spesifik model di atas pemeriksaan umum.

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

Lihat Gemma4Processor dan Qwen2VLProcessor sebagai referensi.

Pengujian

Semua pemroses multimodal harus memiliki kelas uji yang mewarisi dari ProcessorTesterMixin. Mixin ini menyediakan serangkaian standar yang mencakup tokenisasi, pemrosesan gambar, batching, dan pengodean bolak-balik.

# 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