Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/en/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1547,6 +1547,8 @@
title: Perceiver
- local: model_doc/perception_lm
title: PerceptionLM
- local: model_doc/phi3_v
title: Phi-3-vision
- local: model_doc/phi4_multimodal
title: Phi4 Multimodal
- local: model_doc/pi0
Expand Down
78 changes: 78 additions & 0 deletions docs/source/en/model_doc/phi3_v.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<!--Copyright 2026 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->
*This model was published in HF papers on 2024-04-22 and contributed to Hugging Face Transformers on 2026-11-24.*

# Phi-3-vision

## Overview

Phi-3-vision is the multimodal member of the Phi-3 family by Microsoft, described in the
[Phi-3 Technical Report](https://huggingface.co/papers/2404.14219). It covers
[microsoft/Phi-3-vision-128k-instruct](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct) and
[microsoft/Phi-3.5-vision-instruct](https://huggingface.co/microsoft/Phi-3.5-vision-instruct). The
[TIGER-Lab/VLM2Vec-Full](https://huggingface.co/TIGER-Lab/VLM2Vec-Full) embedding model loads with the same classes.

## Architecture

Phi-3-vision combines a CLIP ViT-L/14 vision encoder at 336x336 pixels with a [Phi-3](./phi3) language model. An image
is resized to fit at most `num_crops` crops of 336x336, padded with white and split into crops, and a downscaled global
image is added. The features of the second to last vision layer are merged 2x2 into one token, a learned newline token
ends every row, and a learned separator sits between the crops and the global image. A two-layer MLP projects the
tokens into the language model.

## Usage

Put one `<|image|>` in the prompt per image, in the order of `images`, where the model cards use `<|image_1|>`, `<|image_2|>`, ...

```python
import torch
from transformers import AutoModelForImageTextToText, AutoProcessor
from transformers.image_utils import load_image

model_id = "microsoft/Phi-3.5-vision-instruct"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(model_id, dtype=torch.bfloat16, device_map="auto")

image = load_image("https://huggingface.co/datasets/hf-internal-testing/fixtures-coco/resolve/main/val2017/000000039769.jpg")
prompt = "<|user|>\n<|image|>\nWhat is shown in this image?<|end|>\n<|assistant|>\n"
inputs = processor(text=prompt, images=image, return_tensors="pt").to(model.device)

output = model.generate(**inputs, max_new_tokens=64, eos_token_id=processor.tokenizer.eos_token_id)
print(processor.decode(output[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))
```

## Phi3VConfig

[[autodoc]] Phi3VConfig

## Phi3VImageProcessor

[[autodoc]] Phi3VImageProcessor
- preprocess

## Phi3VProcessor

[[autodoc]] Phi3VProcessor

## Phi3VModel

[[autodoc]] Phi3VModel
- forward

## Phi3VForConditionalGeneration

[[autodoc]] Phi3VForConditionalGeneration
- forward
12 changes: 12 additions & 0 deletions src/transformers/conversion_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -1482,6 +1482,18 @@ def _build_checkpoint_conversion_mapping():
WeightRenaming(source_patterns=r"\.self_attn\.norm_q\.", target_patterns=".self_attn.q_norm."),
WeightRenaming(source_patterns=r"\.self_attn\.norm_k\.", target_patterns=".self_attn.k_norm."),
],
"phi3_v": [
WeightRenaming(r"^model\.vision_embed_tokens\.img_processor\.", "model.vision_tower."),
WeightRenaming(
r"^model\.vision_embed_tokens\.img_projection\.0\.", "model.multi_modal_projector.linear_1."
),
WeightRenaming(
r"^model\.vision_embed_tokens\.img_projection\.2\.", "model.multi_modal_projector.linear_2."
),
WeightRenaming(r"^model\.vision_embed_tokens\.sub_GN", "model.image_newline"),
WeightRenaming(r"^model\.vision_embed_tokens\.glb_GN", "model.image_separator"),
WeightRenaming(r"^model\.(embed_tokens|layers|norm)\.", r"model.language_model.\1."),
],
"phimoe": [
WeightRenaming(".block_sparse_moe.", ".mlp."),
WeightRenaming(".gate.weight", ".router.weight"),
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@
from .persimmon import *
from .phi import *
from .phi3 import *
from .phi3_v import *
from .phi4_multimodal import *
from .phimoe import *
from .phobert import *
Expand Down
3 changes: 3 additions & 0 deletions src/transformers/models/auto/auto_mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,7 @@
("persimmon", "PersimmonConfig"),
("phi", "PhiConfig"),
("phi3", "Phi3Config"),
("phi3_v", "Phi3VConfig"),
("phi4_multimodal", "Phi4MultimodalConfig"),
("phi4_multimodal_audio", "Phi4MultimodalAudioConfig"),
("phi4_multimodal_vision", "Phi4MultimodalVisionConfig"),
Expand Down Expand Up @@ -1348,6 +1349,7 @@
("pe_audio_video", "PeAudioVideoProcessor"),
("pe_video", "PeVideoProcessor"),
("perception_lm", "PerceptionLMProcessor"),
("phi3_v", "Phi3VProcessor"),
("phi4_multimodal", "Phi4MultimodalProcessor"),
("pi0", "PI0Processor"),
("pi05", "PI05Processor"),
Expand Down Expand Up @@ -1490,6 +1492,7 @@
("paddleocr_vl", {"pil": "PaddleOCRVLImageProcessorPil", "torchvision": "PaddleOCRVLImageProcessor"}),
("perceiver", {"pil": "PerceiverImageProcessorPil", "torchvision": "PerceiverImageProcessor"}),
("perception_lm", {"torchvision": "PerceptionLMImageProcessor"}),
("phi3_v", {"torchvision": "Phi3VImageProcessor"}),
("phi4_multimodal", {"torchvision": "Phi4MultimodalImageProcessor"}),
("pi0", {"torchvision": "PI0ImageProcessor"}),
("pix2struct", {"pil": "Pix2StructImageProcessorPil", "torchvision": "Pix2StructImageProcessor"}),
Expand Down
2 changes: 2 additions & 0 deletions src/transformers/models/auto/modeling_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin):
("persimmon", "PersimmonModel"),
("phi", "PhiModel"),
("phi3", "Phi3Model"),
("phi3_v", "Phi3VModel"),
("phi4_multimodal", "Phi4MultimodalModel"),
("phimoe", "PhimoeModel"),
("pi0", "PI0Model"),
Expand Down Expand Up @@ -1265,6 +1266,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin):
("paddleocr_vl", "PaddleOCRVLForConditionalGeneration"),
("paligemma", "PaliGemmaForConditionalGeneration"),
("perception_lm", "PerceptionLMForConditionalGeneration"),
("phi3_v", "Phi3VForConditionalGeneration"),
("pi0", "PI0ForConditionalGeneration"),
("pi05", "PI05ForConditionalGeneration"),
("pix2struct", "Pix2StructForConditionalGeneration"),
Expand Down
4 changes: 2 additions & 2 deletions src/transformers/models/phi3/configuration_phi3.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@ def convert_rope_params_to_dict(
# Standardize and validate the correctness of rotary position embeddings parameters
self.rope_parameters.setdefault("rope_theta", kwargs.pop("rope_theta", default_theta))
self.rope_parameters.setdefault("partial_rotary_factor", kwargs.get("partial_rotary_factor", 1.0))
self.standardize_rope_params()

# For backward compatibility if previous version used "su" or "yarn"
rope_parameters_type = self.rope_parameters.get("rope_type", None)
rope_parameters_type = self.rope_parameters.get("rope_type", self.rope_parameters.get("type"))
if rope_parameters_type is not None and rope_parameters_type in ["su", "yarn"]:
self.rope_parameters["rope_type"] = "longrope"
self.standardize_rope_params()
return kwargs

def validate_rope(self):
Expand Down
35 changes: 35 additions & 0 deletions src/transformers/models/phi3_v/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# This file was automatically generated from the modules in `src/transformers/models/phi3_v`.
# Do NOT edit this file manually as any edits will be overwritten by auto-generation of the file.
# A module is picked up once it exports a name through `__all__`.
# Regenerate the file with: `python utils/check_inits.py --fix_and_overwrite`
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 Microsoft and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import _LazyModule
from ...utils.import_utils import define_import_structure


if TYPE_CHECKING:
from .configuration_phi3_v import *
from .image_processing_phi3_v import *
from .modeling_phi3_v import *
from .processing_phi3_v import *
else:
import sys

_file = globals()["__file__"]
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
90 changes: 90 additions & 0 deletions src/transformers/models/phi3_v/configuration_phi3_v.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# This file was automatically generated from src/transformers/models/phi3_v/modular_phi3_v.py.
# Do NOT edit this file manually as any edits will be overwritten by the generation of
# the file from the modular. If any change should be done, please apply the change to the
# modular_phi3_v.py file directly. One of our CI enforces this.
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 Microsoft and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from dataclasses import fields
from typing import Literal

from huggingface_hub.dataclasses import strict

from ...configuration_utils import PreTrainedConfig, SubConfigSpec
from ...utils import auto_docstring
from ..auto import CONFIG_MAPPING, AutoConfig


@auto_docstring(checkpoint="microsoft/Phi-3.5-vision-instruct")
@strict
class Phi3VConfig(PreTrainedConfig):
r"""
Example:

```python
>>> from transformers import Phi3VForConditionalGeneration, Phi3VConfig

>>> # Initializing a Phi-3.5-vision style configuration
>>> configuration = Phi3VConfig()

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

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

model_type = "phi3_v"
attribute_map = {"image_token_id": "image_token_index"}
sub_configs_defaults = {
"text_config": SubConfigSpec(config_class=AutoConfig, model_type="phi3"),
"vision_config": SubConfigSpec(
config_class=AutoConfig,
model_type="clip_vision_model",
init_kwargs={
"intermediate_size": 4096,
"hidden_size": 1024,
"patch_size": 14,
"image_size": 336,
"num_hidden_layers": 24,
"num_attention_heads": 16,
"projection_dim": 768,
},
),
}

vision_config: dict | PreTrainedConfig | None = None
text_config: dict | PreTrainedConfig | None = None

image_token_index: int = 32044
projector_hidden_act: str = "gelu"
vision_feature_select_strategy: Literal["default", "full"] = "default"
vision_feature_layer: int | list[int] = -2
multimodal_projector_bias: bool = True
tie_word_embeddings: bool = False

def __post_init__(self, **kwargs):
# Hub configs are flat Phi-3 configs with the vision settings hardcoded in the remote code. They also force
# `flash_attention_2`, which would override `attn_implementation`
if self.text_config is None:
for key in ("_attn_implementation", "embd_layer", "img_processor"):
kwargs.pop(key, None)
text_keys = {field.name for field in fields(CONFIG_MAPPING["phi3"])} | {"rope_scaling", "rope_theta"}
self.text_config = {key: kwargs.pop(key) for key in list(kwargs) if key in text_keys}
super().__post_init__(**kwargs)


__all__ = ["Phi3VConfig"]
Loading
Loading