Source code for mllm_shap.backends.transformers.processor
"""Model inputs for audio and image language models through a Hugging Face processor.
@domain backends
@see [[knowledge/architecture/backends]]
@tested-by [[tests/backends/test_transformers_audio.py]]
@tested-by [[tests/backends/test_transformers_image.py]]
"""
from collections.abc import Mapping
from typing import Any
import numpy as np
from numpy.typing import NDArray
from ...domain.config import ContentOrder
from ...domain.conversation import (
AudioPart,
ConversationSnapshot,
ImagePart,
Message,
TextPart,
)
from .._chat import chat_role, message_parts, snapshot_has_audio, snapshot_has_image
from .audio import audio_template_part, sampling_rate, template_has_audio, waveform
from .chat import render_prompt
from .image import image_template_part, template_has_image
Item = str | NDArray[np.float32] | ImagePart
"""One part a processor receives (text, a waveform or an image)."""
[docs]
def processor_inputs(
processor: Any,
snapshot: ConversationSnapshot,
order: ContentOrder = "legacy",
processor_kwargs: Mapping[str, Any] | None = None,
) -> Any:
"""Encode ``snapshot`` with its audio and images for ``processor``.
Images, and audio for a processor whose chat template mentions audio, go in as
structured chat-template parts (a mistral-common tokenizer, as in Voxtral, has
an implicit template and takes each clip as base64 WAV); otherwise each audio
part becomes ``processor.audio_token`` in the rendered prompt and the waveforms
go to ``processor(text=..., audio=...)``. Parts follow ``order``
(``message_parts``, media first under ``legacy``); an audio part left empty by
masking is dropped.
``processor_kwargs`` (``max_pixels``, say) go to the processor call.
Raises:
ValueError: If ``snapshot`` has an image and the processor's chat template
takes none.
"""
has_image = snapshot_has_image(snapshot)
if has_image and not template_has_image(processor):
msg = "the processor has no image chat template for image snapshots"
raise ValueError(msg)
rate = sampling_rate(processor) if snapshot_has_audio(snapshot) else 0
items = {id(m): _items(m, rate, order) for m in snapshot.messages()}
kwargs = dict(processor_kwargs or {})
if has_image or template_has_audio(processor):
conversation = [
{
"role": chat_role(m.role),
"content": [_template_part(i, rate, processor) for i in items[id(m)]],
}
for m in snapshot.messages()
]
return processor.apply_chat_template(
conversation,
tokenize=True,
return_dict=True,
add_generation_prompt=True,
return_tensors="pt",
**kwargs,
)
messages = [
{
"role": chat_role(m.role),
"content": "".join(
i if isinstance(i, str) else processor.audio_token for i in items[id(m)]
),
}
for m in snapshot.messages()
]
waveforms = [
i for m in snapshot.messages() for i in items[id(m)] if not isinstance(i, str)
]
return processor(
text=render_prompt(processor.tokenizer, messages),
audio=waveforms or None,
return_tensors="pt",
**kwargs,
)
def _items(message: Message, rate: int, order: ContentOrder) -> list[Item]:
"""Return the message's texts, non-empty waveforms and images in send order."""
items: list[Item] = []
for part in message_parts(message, order, media_first=True):
if isinstance(part, TextPart):
items.append(part.text)
elif isinstance(part, AudioPart):
samples = waveform(part, rate)
if samples.size:
items.append(samples)
else:
items.append(part)
return items
def _template_part(item: Item, rate: int, processor: Any) -> dict[str, Any]:
if isinstance(item, str):
return {"type": "text", "text": item}
if isinstance(item, ImagePart):
return image_template_part(item)
return audio_template_part(item, rate, processor)