Buckets:
Phi4 Multimodal
Phi4 Multimodal is a multimodal model capable of text, image, and speech and audio inputs or any combination of these. It features a mixture of LoRA adapters for handling different inputs, and each input is routed to the appropriate encoder.
You can find all the original Phi4 Multimodal checkpoints under the Phi4 collection.
This model was contributed by cyrilvallez.
Click on the Phi-4 Multimodal in the right sidebar for more examples of how to apply Phi-4 Multimodal to different tasks.
The example below demonstrates how to generate text based on an image with Pipeline or the AutoModel class.
from transformers import pipeline
generator = pipeline("text-generation", model="microsoft/Phi-4-multimodal-instruct", dtype="auto", 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, GenerationConfig
from accelerate import Accelerator
model_path = "microsoft/Phi-4-multimodal-instruct"
device = Accelerator().device
processor = AutoProcessor.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device, dtype=torch.float16)
model.load_adapter(model_path, adapter_name="vision", device_map=device, adapter_kwargs={"subfolder": 'vision-lora'})
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
{"type": "text", "text": "What is shown in this image?"},
],
},
]
model.set_adapter("vision")
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}')
Notes
The example below demonstrates inference with an audio and text input.
import torch
from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
from accelerate import Accelerator
model_path = "microsoft/Phi-4-multimodal-instruct"
device = Accelerator().device
processor = AutoProcessor.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device, dtype=torch.float16)
model.load_adapter(model_path, adapter_name="speech", device_map=device, 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[[transformers.Phi4MultimodalFeatureExtractor]]
class transformers.Phi4MultimodalFeatureExtractortransformers.Phi4MultimodalFeatureExtractor
Phi4MultimodalImageProcessorFast[[transformers.Phi4MultimodalImageProcessorFast]]
class transformers.Phi4MultimodalImageProcessorFasttransformers.Phi4MultimodalImageProcessorFast
Constructs a fast Phi4 Multimodal image processor.
pad_to_max_num_cropstransformers.Phi4MultimodalImageProcessorFast.pad_to_max_num_crops
images: B x 3 x H x W, B<=max_crops
preprocesstransformers.Phi4MultimodalImageProcessorFast.preprocessUnion[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]) --
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set do_rescale=False.
- do_convert_rgb (
bool, optional) -- Whether to convert the image to RGB. - do_resize (
bool, optional) -- Whether to resize the image. - size (
Annotated[Union[int, list[int], tuple[int, ...], dict[str, int], NoneType], None]) -- Describes the maximum input dimensions to the model. - crop_size (
Annotated[Union[int, list[int], tuple[int, ...], dict[str, int], NoneType], None]) -- Size of the output image after applyingcenter_crop. - resample (
Annotated[Union[PILImageResampling, int, NoneType], None]) -- Resampling filter to use if resizing the image. This can be one of the enumPILImageResampling. Only has an effect ifdo_resizeis set toTrue. - do_rescale (
bool, optional) -- Whether to rescale the image. - rescale_factor (
float, optional) -- Rescale factor to rescale the image by ifdo_rescaleis set toTrue. - do_normalize (
bool, optional) -- Whether to normalize the image. - image_mean (
Union[float, list[float], tuple[float, ...], NoneType]) -- Image mean to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - image_std (
Union[float, list[float], tuple[float, ...], NoneType]) -- Image standard deviation to use for normalization. Only has an effect ifdo_normalizeis set toTrue. - do_pad (
bool, optional) -- Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model. - pad_size (
Annotated[Union[int, list[int], tuple[int, ...], dict[str, int], NoneType], None]) -- The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_pad=True. - do_center_crop (
bool, optional) -- Whether to center crop the image. - data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]) -- OnlyChannelDimension.FIRSTis supported. Added for compatibility with slow processors. - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]) -- The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:"channels_first"orChannelDimension.FIRST: image in (num_channels, height, width) format."channels_last"orChannelDimension.LAST: image in (height, width, num_channels) format."none"orChannelDimension.NONE: image in (height, width) format.
- device (
Annotated[str, None], optional) -- The device to process the images on. If unset, the device is inferred from the input images. - return_tensors (
Annotated[Union[str, ~utils.generic.TensorType, NoneType], None]) -- Returns stacked tensors if set to `pt, otherwise returns a list of tensors. - disable_grouping (
bool, optional) -- Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 - patch_size (
int, optional) -- The size of the patch. - dynamic_hd (
int, optional) -- The maximum number of crops per image.0<class 'transformers.image_processing_base.BatchFeature'>- data (dict) -- Dictionary of lists/arrays/tensors returned by the call method ('pixel_values', etc.). - tensor_type (
Union[None, str, TensorType], optional) -- You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
Phi4MultimodalProcessor[[transformers.Phi4MultimodalProcessor]]
class transformers.Phi4MultimodalProcessortransformers.Phi4MultimodalProcessorPhi4MultimodalImageProcessorFast) --
The image processor to use for images.
- audio_processor (
Phi4MultimodalFeatureExtractor) -- The audio processor to use for audio inputs. - tokenizer (
GPT2TokenizerFast) -- The tokenizer to use for text. - fake_image_token_pattern (
str, optional, defaults tor"<\|image_\d+\|>") -- The fake image token pattern. - fake_audio_token_pattern (
str, optional, defaults tor"<\|audio_\d+\|>") -- The fake audio token pattern.0
Constructs a Phi4Multimodal processor which raps an image processor, a audio processor, and a GPT tokenizer into a single processor.
Phi4MultimodalProcessor offers all the functionalities of Phi4MultimodalImageProcessorFast and GPT2Tokenizer. See the
__call__() and decode() for more information.
Phi4MultimodalAudioConfig[[transformers.Phi4MultimodalAudioConfig]]
class transformers.Phi4MultimodalAudioConfigtransformers.Phi4MultimodalAudioConfigint, optional, defaults to 1024) --
Dimensionality of the encoder layers.
- intermediate_size (
int, optional, defaults to 1536) -- Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. - num_blocks (
int, optional, defaults to 24) -- Number of hidden layers in the Transformer encoder. - num_attention_heads (
int, optional, defaults to 16) -- Number of attention heads for each attention layer in the Transformer encoder. - activation (
str, optional, defaults to"swish") -- The non-linear activation function in the MLPs. - chunk_size (
int, optional, defaults to -1) -- The chunk size to create the masks. - left_chunk (
int, optional, defaults to 18) -- The left chunk to create the masks. - dropout_rate (
float, optional, defaults to 0.0) -- The dropout ratio. - ext_pw_out_channel (
int, optional, defaults to 1024) -- Number of out channels in the point-wise conv modules. - depthwise_separable_out_channel (
int, optional, defaults to 1024) -- Number of out channels in the depth-wise separable conv modules. - depthwise_multiplier (
int, optional, defaults to 1) -- Input size multiplier for the depth-wise separable conv modules. - kernel_size (
int, optional, defaults to 3) -- Kernel size for the depth-wise separable conv modules. - conv_activation (
str, optional, defaults to"swish") -- The non-linear activation function in the conv modules. - input_size (
int, optional, defaults to 80) -- Input size for the audio model. - conv_glu_type (
str, optional, defaults to"swish") -- The non-linear activation function in the point-wise conv modules. - time_reduction (
int, optional, defaults to 8) -- Time reduction (subsampling factor). - bias_max_distance (
int, optional, defaults to 1000) -- Max distance for the relative attention bias module. - bias_symmetric (
bool, optional, defaults toFalse) -- Whether the relative attention bias should be symmetric or not. - nemo_activation (
str, optional, defaults to"relu") -- The non-linear activation function in the nemo conv modules. - nemo_conv_channels (
int, optional, defaults to 1024) -- Number of channels in the nemo conv modules. - downsample_rate (
int, optional, defaults to 1) -- Downsample rate for the audio feature extractor. - initializer_range (
float, optional, defaults to 0.02) -- The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - audio_token_id (
int, optional, defaults to 200011) -- The audio token id. - feature_layer (
int, optional, defaults to -2) -- The index of the layer of the encoder from which to extract audio features.0
This is the configuration class to store the configuration of a Phi4MultimodalAudioModel. It is used to instantiate a Phi4Multimodal audio encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the audio encoder of microsoft/Phi-4-multimodal-instruct architecture.
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> from transformers import Phi4MultimodalAudioConfig
>>> # Initializing a Phi4MultimodalAudioConfig with microsoft/Phi-4-multimodal-instruct style configuration
>>> configuration = Phi4MultimodalAudioConfig()
Phi4MultimodalVisionConfig[[transformers.Phi4MultimodalVisionConfig]]
class transformers.Phi4MultimodalVisionConfigtransformers.Phi4MultimodalVisionConfigint, optional, defaults to 1152) --
Dimensionality of the encoder layers and the pooler layer.
- intermediate_size (
int, optional, defaults to 4304) -- Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. - num_hidden_layers (
int, optional, defaults to 27) -- Number of hidden layers in the Transformer encoder. - num_attention_heads (
int, optional, defaults to 16) -- Number of attention heads for each attention layer in the Transformer encoder. - num_channels (
int, optional, defaults to 3) -- Number of channels in the input images. - image_size (
int, optional, defaults to 448) -- The size (resolution) of each image. - patch_size (
int, optional, defaults to 14) -- The size (resolution) of each patch. - hidden_act (
strorfunction, optional, defaults to"gelu_pytorch_tanh") -- The non-linear activation function (function or string) in the encoder and pooler. If string,"gelu","relu","selu"and"gelu_new""quick_gelu"are supported. - layer_norm_eps (
float, optional, defaults to 1e-06) -- The epsilon used by the layer normalization layers. - attention_dropout (
float, optional, defaults to 0.0) -- The dropout ratio for the attention probabilities. - crop_size (
int, optional, defaults to 448) -- Crop size for the input images. - image_token_id (
int, optional, defaults to 200010) -- The image token id. - feature_layer (
int, optional, defaults to -2) -- The index of the layer of the encoder from which to extract image features.0
This is the configuration class to store the configuration of a Phi4MultimodalVisionModel. It is used to instantiate a Phi4Multimodal vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the vision encoder of microsoft/Phi-4-multimodal-instruct architecture.
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> from transformers import Phi4MultimodalVisionConfig
>>> # Initializing a Phi4MultimodalVisionConfig with microsoft/Phi-4-multimodal-instruct style configuration
>>> configuration = Phi4MultimodalVisionConfig()
Phi4MultimodalConfig[[transformers.Phi4MultimodalConfig]]
class transformers.Phi4MultimodalConfigtransformers.Phi4MultimodalConfigint, optional, defaults to 200064) --
Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
inputs_ids passed when calling Phi3Model.
- hidden_size (
int, optional, defaults to 3072) -- Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to 8192) -- Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to 32) -- Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to 32) -- Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to 8) -- This is the number of key_value heads that should be used to implement Grouped Query Attention. Ifnum_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), ifnum_key_value_heads=1the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default tonum_attention_heads. - resid_pdrop (
float, optional, defaults to 0.0) -- Dropout probability for mlp outputs. - embd_pdrop (
int, optional, defaults to 0.0) -- The dropout ratio for the embeddings. - attention_dropout (
float, optional, defaults to 0.0) -- The dropout ratio after computing the attention scores. - hidden_act (
strorfunction, optional, defaults to"silu") -- The non-linear activation function (function or string) in the decoder. - max_position_embeddings (
int, optional, defaults to 131072) -- The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to 0.02) -- The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (
float, optional, defaults to 1e-05) -- The epsilon value used for the RMSNorm. - use_cache (
bool, optional, defaults toTrue) -- Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=True. Whether to tie weight embeddings or not. - tie_word_embeddings (
bool, optional, defaults toFalse) -- Whether to tie weight embeddings - rope_theta (
float, optional, defaults to 10000.0) -- The base period of the RoPE embeddings. - rope_scaling (
dict, optional) -- The scaling strategy for the RoPE embeddings. IfNone, no scaling is applied. If a dictionary, it must contain the following keys:type,short_factorandlong_factor. Thetypemust belongropeand theshort_factorandlong_factormust be lists of numbers with the same length as the hidden size divided by the number of attention heads divided by 2. - partial_rotary_factor (
float, optional, defaults to1.0) -- Percentage of the query and keys which will have rotary embedding. Must be between 0.0 and 1.0. - bos_token_id (
int, optional, defaults to 199999) -- The id of the "beginning-of-sequence" token. - eos_token_id (
intorlist[int], optional, defaults to[199999, 200020]) -- The id of the "end-of-sequence" token. - pad_token_id (
int, optional, defaults to 199999) -- The id of the padding token. - original_max_position_embeddings (
int, optional, defaults to 4096) -- The maximum sequence length that this model was trained with. This is used to determine the size of the original RoPE embeddings when using long scaling. - sliding_window (
int, optional) -- Sliding window attention window size. IfNone, no sliding window is applied. - vision_config (
Phi4MultimodalVisionConfigordict, optional) -- The vision config for the underlying image embedding model. If not provided, will default to the configuration used to instantiate a model similar in architecture as microsoft/Phi-4-multimodal-instruct. - audio_config (
Phi4MultimodalAudioConfigordict, optional) -- The audio config for the underlying audio embedding model. If not provided, will default to the configuration used to instantiate a model similar in architecture as microsoft/Phi-4-multimodal-instruct.0
This is the configuration class to store the configuration of a Phi4MultimodalModel. It is used to instantiate a Phi4Multimodal model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the microsoft/Phi-4-multimodal-instruct architecture.
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> 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
Phi4MultimodalAudioModel[[transformers.Phi4MultimodalAudioModel]]
class transformers.Phi4MultimodalAudioModeltransformers.Phi4MultimodalAudioModel
forward_embeddingstransformers.Phi4MultimodalAudioModel.forward_embeddings
Phi4MultimodalVisionModel[[transformers.Phi4MultimodalVisionModel]]
class transformers.Phi4MultimodalVisionModeltransformers.Phi4MultimodalVisionModel
Phi4MultimodalModel[[transformers.Phi4MultimodalModel]]
class transformers.Phi4MultimodalModeltransformers.Phi4MultimodalModel
The bare Phi4 Multimodal Model outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.Phi4MultimodalModel.forward
image_pixel_values (torch.FloatTensor, optional):
If the input contains images, these correspond to the pixel values after transformations (as returned by
the Processor)
image_sizes (torch.LongTensor, optional):
If the input contains images, these correspond to size of each image.
image_attention_mask (torch.LongTensor, optional):
Attention mask for the images.
audio_input_features (torch.FloatTensor, optional):
If the input contains audio samples, these correspond to the values after transformation (as returned by
the Processor).
audio_embed_sizes (torch.Tensor, optional):
Size of the audio inputs.
audio_attention_mask (`torch.Tensor, optional):
Attention mask for the audio inputs.
Phi4MultimodalForCausalLM[[transformers.Phi4MultimodalForCausalLM]]
class transformers.Phi4MultimodalForCausalLMtransformers.Phi4MultimodalForCausalLM
The Phi4 Multimodal Model for causal language modeling.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forwardtransformers.Phi4MultimodalForCausalLM.forwardtorch.LongTensor of shape (batch_size, sequence_length), optional) --
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) -- Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].past_key_values (
~cache_utils.Cache, optional) -- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don't have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length).inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) -- Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model's internal embedding lookup matrix.image_pixel_values (
torch.FloatTensor, optional) -- If the input contains images, these correspond to the pixel values after transformations (as returned by the Processor)image_sizes (
torch.LongTensor, optional) -- If the input contains images, these correspond to size of each image.image_attention_mask (
torch.LongTensor, optional) -- Attention mask for the images.audio_input_features (
torch.FloatTensor, optional) -- If the input contains audio samples, these correspond to the values after transformation (as returned by the Processor).audio_embed_sizes (
torch.Tensor, optional) -- Size of the audio inputs.audio_attention_mask (`torch.Tensor, optional) -- Attention mask for the audio inputs.
labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) -- Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size].use_cache (
bool, optional) -- If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values).output_attentions (
bool, optional) -- Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) -- Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.cache_position (
torch.LongTensorof shape(sequence_length), optional) -- Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.logits_to_keep (
Union[int, torch.Tensor], defaults to0) -- If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_ids(special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).0transformers.modeling_outputs.CausalLMOutputWithPast ortuple(torch.FloatTensor)A transformers.modeling_outputs.CausalLMOutputWithPast or a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (Phi4MultimodalConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) -- Language modeling loss (for next-token prediction).logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.vocab_size)) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).past_key_values (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) -- It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
past_key_valuesinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The Phi4MultimodalForCausalLM forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example:
>>> 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'
Xet Storage Details
- Size:
- 49.3 kB
- Xet hash:
- 5da7ccfba054eaee91425fd1b6c2bb7298625e384d338530c0f1a57a21f8cd63
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.