Transformers documentation

Phi4 多模态

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2025-03-03 在 HF papers 上发布,并于 2025-03-25 贡献至 Hugging Face Transformers。

PyTorch

Phi4 多模态

Phi4 Multimodal 是一个多模态模型,支持文本、图像以及语音和音频输入,或这些输入类型的任意组合。它采用 LoRA 适配器混合架构来处理不同的输入,并将每种输入路由至相应的编码器。

您可以在 Phi4 集合中找到所有原始的 Phi4 Multimodal 检查点。

该模型由 cyrilvallez 贡献。

点击右侧边栏中的 Phi-4 Multimodal,以查看更多将 Phi-4 Multimodal 应用于不同任务的示例。

以下示例演示了如何使用 Pipeline 或 AutoModel 类基于图像生成文本。

Pipeline
AutoModel
from transformers import pipeline


generator = pipeline("text-generation", model="microsoft/Phi-4-multimodal-instruct", device=0)

prompt = "Explain the concept of multimodal AI in simple terms."

result = generator(prompt, max_length=50)
print(result[0]['generated_text'])

备注

下面的示例演示了使用音频和文本输入进行推理。

import torch

from transformers import AutoModelForCausalLM, AutoProcessor


model_path = "microsoft/Phi-4-multimodal-instruct"

processor = AutoProcessor.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto")

model.load_adapter(model_path, adapter_name="speech", device_map="auto", adapter_kwargs={"subfolder": 'speech-lora'})
model.set_adapter("speech")
audio_url = "https://upload.wikimedia.org/wikipedia/commons/b/b0/Barbara_Sahakian_BBC_Radio4_The_Life_Scientific_29_May_2012_b01j5j24.flac"
messages = [
    {
        "role": "user",
        "content": [
            {"type": "audio", "url": audio_url},
            {"type": "text", "text": "Transcribe the audio to text, and then translate the audio to French. Use <sep> as a separator between the origina transcript and the translation."},
        ],
    },
]

inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)

generate_ids = model.generate(
    **inputs,
    max_new_tokens=1000,
    do_sample=False,
)
generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
response = processor.batch_decode(
    generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
)[0]
print(f'Response\n{response}')

Phi4MultimodalFeatureExtractor

class transformers.Phi4MultimodalFeatureExtractor

< >

( feature_size: int = 80sampling_rate: int = 16000hop_length: int = 160n_fft: int = 512win_length: int = 400preemphasis: float = 0.97padding_value: float = 0.0audio_compression_rate: int = 8audio_downsample_rate: int = 1audio_feat_stride: int = 1mel_min_frequency: float = 0mel_max_frequency: float = 7690**kwargs )

Phi4MultimodalImageProcessor

class transformers.Phi4MultimodalImageProcessor

< >

( **kwargs: *<class 'transformers.models.phi4_multimodal.image_processing_phi4_multimodal.Phi4MultimodalImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 448, 'width': 448}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (int, kwargs, 可选) — 补丁的大小。
  • dynamic_hd (int, kwargs, 可选) — 每张图片的最大裁剪数量。

构建一个 Phi4MultimodalImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.phi4_multimodal.image_processing_phi4_multimodal.Phi4MultimodalImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (int, kwargs, 可选) — 补丁的大小。
  • dynamic_hd (int, kwargs, 可选) — 每张图片的最大裁剪数量。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

Phi4MultimodalProcessor

class transformers.Phi4MultimodalProcessor

< >

( image_processoraudio_processortokenizer**kwargs )

参数

  • image_processor (Phi4MultimodalImageProcessor) — 图像处理器是必需的输入。
  • audio_processor({audio_processor_class})— 音频处理器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。

构造一个 Phi4MultimodalProcessor,它将图像处理器、音频处理器和分词器封装为单一处理器。

Phi4MultimodalProcessor 提供了 Phi4MultimodalImageProcessor、{audio_processor_class} 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~Phi4MultimodalImageProcessor、~{audio_processor_class} 和 ~tokenizer_class。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • videos (Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置 do_rescale=False。
  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 可选) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。
  • return_mm_token_type_ids (bool, kwargs) — 是否返回多模态 token 类型 id,用于指示多模态占位符 token 的位置。
  • return_text_replacement_offsets (bool, kwargs) — 是否返回每个多模态占位符及其替换内容的字符偏移量。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

Phi4MultimodalAudioConfig

class transformers.Phi4MultimodalAudioConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1024intermediate_size: int = 1536num_blocks: int = 24num_attention_heads: int = 16activation: str = 'swish'chunk_size: int = -1left_chunk: int = 18dropout_rate: float | int = 0.0ext_pw_out_channel: int = 1024depthwise_separable_out_channel: int = 1024depthwise_multiplier: int = 1kernel_size: int = 3conv_activation: str = 'swish'input_size: int = 80conv_glu_type: str = 'swish'time_reduction: int = 8bias_max_distance: int = 1000bias_symmetric: bool = Falsenemo_activation: str = 'relu'nemo_conv_channels: int = 1024downsample_rate: int = 1initializer_range: float = 0.02audio_token_id: int = 200011feature_layer: int = -2 )

参数

  • hidden_size (int,可选,默认为 1024) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 1536) — MLP 表示的维度。
  • num_blocks (int,可选,默认为 24) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • activation (str,可选,默认为 "swish") — MLP 中使用的非线性激活函数。
  • chunk_size (int,可选,默认值为 -1) — 用于创建掩码的块大小。
  • left_chunk (int,可选,默认为 18) — 用于创建掩码的左侧块。
  • dropout_rate (float,可选,默认为 0.0) — Dropout 比率。
  • ext_pw_out_channel (int,可选,默认为 1024) — 逐点卷积模块中的输出通道数。
  • depthwise_separable_out_channel (int,可选,默认为 1024) — 深度可分离卷积模块中的输出通道数。
  • depthwise_multiplier (int,可选,默认为 1) — 深度可分离卷积模块的输入尺寸乘数。
  • kernel_size (int,可选,默认为 3) — 深度可分离卷积模块的卷积核大小。
  • conv_activation (str,可选,默认为 "swish") — 卷积模块中使用的非线性激活函数。
  • input_size (int,可选,默认为 80) — 音频模型的输入大小。
  • conv_glu_type (str,可选,默认为 "swish") — 逐点卷积模块中的非线性激活函数。
  • time_reduction (int,可选,默认为 8) — 时间缩减(子采样因子)。
  • bias_max_distance(int,可选,默认为 1000)— 相对注意力偏置模块的最大距离。
  • bias_symmetric (bool,可选,默认为 False) — 相对注意力偏置是否应对称。
  • nemo_activation (str,可选,默认为 "relu") — nemo 卷积模块中使用的非线性激活函数。
  • nemo_conv_channels (int,可选,默认为 1024) — nemo conv 模块中的通道数。
  • downsample_rate (int,可选,默认为 1) — 音频特征提取器的下采样率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • audio_token_id (int,可选,默认为 200011) — 用作输入音频占位符的音频 token 索引。
  • feature_layer (int, 可选,默认为 -2) — 用于提取音频特征的编码器层索引。

这是用于存储 Phi4MultimodalModel 配置的类。它根据指定的参数实例化 Phi4 多模态模型,并定义模型架构。使用默认值实例化配置,将得到与 microsoft/Phi-4-multimodal-instruct 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import Phi4MultimodalAudioConfig

>>> # Initializing a Phi4MultimodalAudioConfig with microsoft/Phi-4-multimodal-instruct style configuration
>>> configuration = Phi4MultimodalAudioConfig()

Phi4MultimodalVisionConfig

class transformers.Phi4MultimodalVisionConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1152intermediate_size: int = 4304num_hidden_layers: int = 27num_attention_heads: int = 16num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 448patch_size: int | list[int] | tuple[int, int] = 14hidden_act: str = 'gelu_pytorch_tanh'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0crop_size: int = 448image_token_id: int = 200010feature_layer: int = -2 )

参数

  • hidden_size (int,可选,默认为 1152) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 4304) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 27) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 448) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 14) — 每个 patch 的大小(分辨率)。
  • hidden_act (str,可选,默认为 gelu_pytorch_tanh) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • crop_size (int,可选,默认为 448) — 输入图像的裁剪尺寸。
  • image_token_id (int,可选,默认为 200010) — 用作输入图像占位符的图像 token 索引。
  • feature_layer (int, 可选,默认为 -2) — 用于提取图像特征的编码器层索引。

这是用于存储 Phi4MultimodalModel 配置的类。它根据指定的参数实例化 Phi4 多模态模型,并定义模型架构。使用默认值实例化配置,将得到与 microsoft/Phi-4-multimodal-instruct 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import Phi4MultimodalVisionConfig

>>> # Initializing a Phi4MultimodalVisionConfig with microsoft/Phi-4-multimodal-instruct style configuration
>>> configuration = Phi4MultimodalVisionConfig()

Phi4MultimodalConfig

类 transformers.Phi4MultimodalConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 200064hidden_size: int = 3072intermediate_size: int = 8192num_hidden_layers: int = 32num_attention_heads: int = 32num_key_value_heads: int | None = 8resid_pdrop: float | int = 0.0embd_pdrop: float | int = 0.0attention_dropout: float | int = 0.0hidden_act: str = 'silu'max_position_embeddings: int = 131072original_max_position_embeddings: int | None = 4096initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Truetie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Nonebos_token_id: int | None = 199999eos_token_id: int | list[int] | None = Nonepad_token_id: int | None = 199999sliding_window: int | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None )

参数

  • vocab_size (int,可选,默认为 200064) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 3072) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 8192) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 32) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 32) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选,默认为 8) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果 num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 num_attention_heads。
  • resid_pdrop (Union[float, int],可选,默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • embd_pdrop (Union[float, int],可选,默认为 0.0) — 嵌入层的 dropout 比率。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • hidden_act (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 131072) — 该模型可能使用的最大序列长度。
  • original_max_position_embeddings (int,可选,默认为 4096) — 该模型训练时使用的最大序列长度。在使用长序列缩放时,此参数用于确定原始 RoPE 嵌入的大小。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rms_norm_eps (float,可选,默认为 1e-05) — RMS 归一化层使用的 epsilon 值。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • bos_token_id (int,可选,默认为 199999) — 词表中用于表示流起始的 token id。
  • eos_token_id (Union[int, list[int]], 可选) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • pad_token_id (int,可选,默认为 199999) — 词表中用于填充的 token id。
  • sliding_window (int, 可选) — 滑动窗口注意力的窗口大小。如果为 None,则不应用滑动窗口。
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • audio_config (Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 音频骨干网络的配置对象或字典。

这是用于存储 Phi4MultimodalModel 配置的类。它根据指定的参数实例化 Phi4 多模态模型,并定义模型架构。使用默认值实例化配置,将得到与 microsoft/Phi-4-multimodal-instruct 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import Phi4MultimodalModel, Phi4MultimodalConfig

>>> # Initializing a Phi4Multimodal style configuration
>>> configuration = Phi4MultimodalConfig.from_pretrained("microsoft/Phi-4-multimodal-instruct")

>>> # Initializing a model from the configuration
>>> model = Phi4MultimodalModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

validate_rope

< >

( )

验证 rope_parameters 配置。

Phi4MultimodalAudioModel

class transformers.Phi4MultimodalAudioModel

< >

( config: Phi4MultimodalAudioConfig )

forward_embeddings

< >

( hidden_statesmasks )

将输入通过顶层嵌入层进行前向传播

Phi4MultimodalVisionModel

class transformers.Phi4MultimodalVisionModel

< >

( config: Phi4MultimodalVisionConfig )

Phi4MultimodalModel

class transformers.Phi4MultimodalModel

< >

( config: Phi4MultimodalConfig )

参数

  • config (Phi4MultimodalConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

未添加任何特定头部的裸 Phi4 多模态模型,直接输出原始隐藏状态。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneimage_pixel_values: typing.Optional[torch.Tensor] = Noneimage_sizes: typing.Optional[torch.LongTensor] = Noneimage_attention_mask = Noneaudio_input_features: typing.Optional[torch.Tensor] = Noneaudio_embed_sizes = Noneaudio_attention_mask = Noneuse_cache: bool | None = None**kwargs )

image_pixel_values (torch.Tensor, 可选): 如果输入包含图像,则对应于转换后的像素值(由 Processor 返回) image_sizes (torch.LongTensor, 可选): 如果输入包含图像,则对应于每张图像的尺寸。 image_attention_mask (torch.LongTensor, 可选): 图像的注意力掩码。 audio_input_features (torch.Tensor, 可选): 如果输入包含音频样本,则对应于转换后的值(由 Processor 返回)。 audio_embed_sizes (torch.Tensor, 可选): 音频输入的尺寸。 audio_attention_mask (`torch.Tensor, 可选): 音频输入的注意力掩码。

Phi4MultimodalForCausalLM

class transformers.Phi4MultimodalForCausalLM

< >

( config: Phi4MultimodalConfig )

参数

  • config (Phi4MultimodalConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

用于因果语言建模的 Phi4 多模态模型。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneimage_pixel_values: typing.Optional[torch.Tensor] = Noneimage_sizes: typing.Optional[torch.LongTensor] = Noneimage_attention_mask = Noneaudio_input_features: typing.Optional[torch.Tensor] = Noneaudio_embed_sizes = Noneaudio_attention_mask = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs ) → CausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • image_pixel_values (torch.Tensor, 可选) — 如果输入包含图像,则这些值对应于经过变换后的像素值(由 Processor 返回)
  • image_sizes (torch.LongTensor, 可选) — 如果输入包含图像,则对应每张图像的尺寸。
  • image_attention_mask (torch.LongTensor, 可选) — 图像的注意力掩码。
  • audio_input_features (torch.Tensor, 可选) — 如果输入包含音频样本,这些值对应于变换后的结果(由 Processor 返回)。
  • audio_embed_sizes (torch.Tensor,可选) — 音频输入的维度。
  • audio_attention_mask (`torch.Tensor, 可选) — 音频输入的注意力掩码。
  • labels (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 用于计算因果语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] (参见 input_ids 文档字符串)。索引设置为 -100 的 token 将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size].

    标签在内部会进行移位,因此使用labels[..., 1:]来预测logits[..., :-1, :]。 请传入与input_ids匹配的未移位标签(即labels = input_ids)。在传入之前,请勿自行对标签进行移位。

    如果标签已经移位(例如在使用序列并行时),请将其作为 shift_labels 关键字参数传入,系统将直接使用该值。为了计算损失,仍然必须传入 labels。

  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。

返回值

CausalLMOutputWithPast 或 tuple(torch.Tensor)

一个 CausalLMOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Phi4MultimodalConfig)和输入。

Phi4MultimodalForCausalLM 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import AutoTokenizer, Phi4MultimodalForCausalLM
>>> model = Phi4MultimodalForCausalLM.from_pretrained("TBA")
>>> tokenizer = AutoTokenizer.from_pretrained("TBA")
>>> prompt = "This is an example script ."
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
Update on GitHub