Repository navigation
Add Phi3.5 Vision Model #41977
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yaswanth19
wants to merge
40
commits into
huggingface:main
Choose a base branch
from
yaswanth19:add-phi3-vision
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add Phi3.5 Vision Model #41977
Changes from all commits
Commits
Show all changes
40 commits
Select commit
Hold shift + click to select a range
f280e53
Add model
yaswanth19 c6d9b89
Add model in auto
yaswanth19 865bf5e
processor tests passing
yaswanth19 e95d6d0
Model is almost done
yaswanth19 fa0f1ba
Tests and cleanup
yaswanth19 26c6d0b
commit for now
yaswanth19 89510c4
Merge branch 'main' into add-phi3-vision
yaswanth19 711ac88
small fixes
yaswanth19 e5bdab4
Add model tests
yaswanth19 24918f2
Rename key
yaswanth19 e27a37f
make style
yaswanth19 d9a5892
More tests
yaswanth19 a63903c
Merge branch 'main' into add-phi3-vision
yaswanth19 55865ac
processor tests passing
yaswanth19 3f2c293
make fixup
yaswanth19 144e200
Add docs
yaswanth19 51a3f5f
Merge branch 'main' into add-phi3-vision
yaswanth19 03f1885
fix docstring
yaswanth19 ee5ab9f
up
yaswanth19 2b3e5dc
Finally fix check_docstring
yaswanth19 594901b
Add integrations tests
yaswanth19 fd6a5d3
Update expectation in tests
yaswanth19 79ba322
up
yaswanth19 1192d96
nit
yaswanth19 13fe7ee
Merge branch 'main' into add-phi3-vision
yaswanth19 b731693
Remove prints
yaswanth19 23131a4
Fix failing text
yaswanth19 4485c3f
Merge branch 'main' into add-phi3-vision
yaswanth19 9a5dbb8
doc update
yaswanth19 f9ab6f0
up
yaswanth19 b2ed0d2
Changes per review
yaswanth19 197ac13
update and run tests
yaswanth19 f48018e
uncomment slow
yaswanth19 edbea31
Merge branch 'main' into add-phi3-vision
yaswanth19 4374c99
Fix failing tests
yaswanth19 6ebdce5
image_sizes is set directly
yaswanth19 6a8a772
Merge branch 'main' into add-phi3-vision
yaswanth19 0827a84
Merge branch 'main' into add-phi3-vision
yaswanth19 c7bb9c7
Tokenize in a single call
yaswanth19 796319c
Merge branch 'main' into add-phi3-vision
yaswanth19 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| <!--Copyright 2025 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 contain specific syntax for our doc-builder (similar to MDX) that may not be | ||
| rendered properly in your Markdown viewer. | ||
|
|
||
| --> | ||
| *This model was released on 2024-06-18 and added to Hugging Face Transformers on 2025-11-15.* | ||
|
|
||
| <div style="float: right;"> | ||
| <div class="flex flex-wrap space-x-1"> | ||
| <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> | ||
| <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> | ||
| <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"> | ||
| </div> | ||
| </div> | ||
|
|
||
| # Phi-3.5 Vision | ||
|
|
||
| *Phi-3.5 vision is a lightweight, state-of-the-art open multimodal model built upon datasets which include - synthetic data and filtered publicly available websites - with a focus on very high-quality, reasoning dense data both on text and vision. The model belongs to the Phi-3 model family, and the multimodal version comes with 128K context length (in tokens) it can support. The model underwent a rigorous enhancement process, incorporating both supervised fine-tuning and direct preference optimization to ensure precise instruction adherence and robust safety measures.* | ||
|
|
||
|
|
||
| ## Usage Example | ||
|
|
||
| The example below demonstrates how to generate text with `Phi3VForConditionalGeneration`. | ||
|
|
||
|
|
||
| ```py | ||
| import torch | ||
| from transformers import Phi3VForConditionalGeneration, Phi3VProcessor | ||
|
|
||
| model_id = "yaswanthgali/Phi-3.5-vision-instruct" | ||
|
|
||
| # Prepare inputsfor generation. | ||
| messages = [ | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| {'type':'image', 'url': 'http://images.cocodataset.org/val2017/000000039769.jpg'}, | ||
| {'type':"text", "text":"What do you see in this image?."} | ||
| ] | ||
| }, | ||
| ] | ||
|
|
||
| processor = Phi3VProcessor.from_pretrained(model_id) | ||
| model = Phi3VForConditionalGeneration.from_pretrained(model_id, | ||
| dtype=torch.bfloat16, | ||
| device_map="auto") | ||
|
|
||
| inputs = processor.apply_chat_template( | ||
| messages, | ||
| add_generation_prompt=True, | ||
| generation_mode="text", | ||
| tokenize=True, | ||
| return_dict=True, | ||
| return_tensors="pt", | ||
| ).to(model.device, dtype=torch.bfloat16) | ||
|
|
||
| output = model.generate(**inputs, max_new_tokens=20,do_sample=True) | ||
| text = processor.decode(output[0], skip_special_tokens=True) | ||
| print(text) | ||
| ``` | ||
|
|
||
| ## Phi3VConfig | ||
|
|
||
| [[autodoc]] Phi3VConfig | ||
|
|
||
| ## Phi3VImageProcessorFast | ||
|
|
||
| [[autodoc]] Phi3VImageProcessorFast | ||
|
|
||
| ## Phi3VProcessor | ||
|
|
||
| [[autodoc]] Phi3VProcessor | ||
|
|
||
| ## Phi3VModel | ||
|
|
||
| [[autodoc]] Phi3VModel | ||
| - forward | ||
|
|
||
| ## Phi3VForConditionalGeneration | ||
|
|
||
| [[autodoc]] Phi3VForConditionalGeneration | ||
| - forward | ||
| - generate | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| # Copyright 2025 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_fast 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__) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 | ||
| # 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. | ||
| # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 | ||
| # coding=utf-8 | ||
| # Copyright 2025 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 ...configuration_utils import PretrainedConfig | ||
| from ...utils import logging | ||
| from ..auto import CONFIG_MAPPING, AutoConfig | ||
|
|
||
|
|
||
| logger = logging.get_logger(__name__) | ||
|
|
||
|
|
||
| class Phi3VConfig(PretrainedConfig): | ||
| r""" | ||
| This is the configuration class to store the configuration of a [`Phi3VModel`]. It is used to instantiate an | ||
| Phi3 Vision 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 Phi-3.5 vision model. | ||
|
|
||
| e.g. [microsoft/Phi-3.5-vision-instruct](https://huggingface.co/microsoft/Phi-3.5-vision-instruct) | ||
|
|
||
| Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the | ||
| documentation from [`PreTrainedConfig`] for more information. | ||
|
|
||
| Args: | ||
| vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`): | ||
| The config object or dictionary of the vision backbone. | ||
| text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `Phi3Config`): | ||
| The config object or dictionary of the text backbone. | ||
| image_token_id (`int`, *optional*, defaults to 32044): | ||
| Token index of a placeholder image token. | ||
|
|
||
| Example: | ||
|
|
||
| ```python | ||
| >>> from transformers import Phi3VForConditionalGeneration, Phi3VConfig, Phi3Config, CLIPVisionConfig | ||
|
|
||
| >>> # Initializing vision config | ||
| >>> vision_config = CLIPVisionConfig() | ||
|
|
||
| >>> # Initializing text config | ||
| >>> text_config = Phi3Config() | ||
|
|
||
| >>> # Initializing config | ||
| >>> configuration = Phi3VConfig(vision_config=vision_config, text_config=text_config) | ||
|
|
||
| >>> # Initializing a model from the Phi-3 style configuration | ||
| >>> model = Phi3VForConditionalGeneration(configuration) | ||
|
|
||
| >>> # Accessing the model configuration | ||
| >>> configuration = model.config | ||
| ```""" | ||
|
|
||
| model_type = "phi3_v" | ||
|
|
||
| sub_configs = {"vision_config": AutoConfig, "text_config": AutoConfig} | ||
|
|
||
| def __init__(self, vision_config=None, text_config=None, image_token_id=32044, **kwargs): | ||
| if text_config is None: | ||
| logger.info("`text_config` is None. Initializing with default values") | ||
| self.text_config = CONFIG_MAPPING["phi3"]() | ||
| elif isinstance(text_config, dict): | ||
| text_config["model_type"] = text_config.get("model_type", "phi3") | ||
| self.text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config) | ||
| elif isinstance(text_config, PretrainedConfig): | ||
| self.text_config = text_config | ||
| else: | ||
| raise ValueError( | ||
| f"Invalid type for `text_config`. Must be either `dict` or `LlamaConfig`." | ||
| f" Type found: {type(text_config)}" | ||
| ) | ||
|
|
||
| if vision_config is None: | ||
| logger.info("`vision_config` is None. Initializing with default CLIPVisionConfig values") | ||
| self.vision_config = CONFIG_MAPPING["clip_vision_model"]() | ||
| elif isinstance(vision_config, dict): | ||
| vision_config["model_type"] = vision_config.get("model_type", "clip_vision_model") | ||
| self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config) | ||
| elif isinstance(vision_config, PretrainedConfig): | ||
| self.vision_config = vision_config | ||
| else: | ||
| raise ValueError( | ||
| f"Invalid type for `vision_config`. Must be either `dict` or `CLIPVisionConfig`." | ||
| f" Type found: {type(vision_config)}" | ||
| ) | ||
|
|
||
| self.image_token_id = image_token_id | ||
| super().__init__(**kwargs) | ||
|
|
||
|
|
||
| __all__ = ["Phi3VConfig"] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: can we add a small intro for the model here before the abstract?