Skip to content

Add Phi-3-vision - #51214

Open
lucamotz wants to merge 8 commits into
huggingface:mainfrom
lucamotz:add-phi3-v
Open

lucamotz wants to merge 8 commits into
huggingface:mainfrom
lucamotz:add-phi3-v

Conversation

@lucamotz

@lucamotz lucamotz commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

🤗 Transformers CI

What does this PR do?

Adds Phi-3-vision (phi3_v), so microsoft/Phi-3-vision-128k-instruct and microsoft/Phi-3.5-vision-instruct load without remote code; TIGER-Lab/VLM2Vec-Full loads with the same classes. It is LLaVA-NeXT with a Phi-3 text model: the new code is get_image_features (2x2 patch merge, learned row newline and global separator), the HD-crop image processor, and 6 WeightRenamings that load the Hub weights unchanged.

Fixes #36166

Earlier attempts: #41977 (no push since 2025-12-18, the 2025-11-24 review unanswered) and #36036; their authors are co-authors.

Design calls

  1. The image processor returns the crops of all images packed. image_sizes keeps its name and now holds the rows and columns of crops of each image, so both forwards stay inherited from LLaVA-NeXT; image_grid_hw, as in NeoMME and Nemotron-H-Omni, is the alternative and needs its own forwards.
  2. Each image's placeholder run ends with <s>, the layout of the remote processor (it tokenized the text after every image separately), so ids match it exactly (with <|image|> for its <|image_N|>). The LLaVA-style layout without <s> costs 2.2 ChartQA points (eval below).
  3. The Phi-3.5-vision remote code recomputes the cache when generation first crosses 4096 tokens, as Phi3ForCausalLM and Phi4MultimodalForCausalLM do. I ported it in Phi3's form, which needs a prepare_inputs_for_generation override that also passes the images again; without it, generation that starts below 4096 tokens degenerates once it passes them.
  4. Phi3VConfig drops the "_attn_implementation": "flash_attention_2" that the Microsoft configs force when it folds the flat Hub config; otherwise AutoModel* ignores attn_implementation and loading needs flash-attn.

processor.apply_chat_template and tokenizer.image_token need small Hub PRs, which are open: Phi-3.5-vision, Phi-3-vision-128k, VLM2Vec-Full.

Validation: input ids match the remote processor; against the remote code (transformers 4.48.3, same attention setting) the logits are bit-identical on CPU in bf16 (Phi-3.5-vision) and agree to 2e-4 at text positions in fp32 (TF32 off) on an NVIDIA GB10 (DGX Spark), with identical greedy text; RUN_SLOW tests pass on the GB10.

Parity with the remote code

Same weights and inputs and the remote code's attention setting (eager Phi-3, SDPA CLIP). Four prompts (one landscape image, one portrait image, two images, text only), plus one short prompt for the processor row.

Phi-3.5-vision Phi-3-vision-128k
Input ids (native processor vs remote processor) identical, 5/5 prompts identical, 5/5 prompts
Pixel values max abs 0.030 (PIL vs torch resize) max abs 0.034
CPU, bf16: logits, image features, greedy 40 tokens all identical (bit-exact), 4/4 prompts (run on the GB10 only)
GB10, fp32 (TF32 off): image features max abs 4.8e-6 (features up to ~160) 2.6e-6 (up to ~120)
GB10, fp32 (TF32 off): logits at text positions max abs ≤ 8.2e-5 ≤ 1.7e-4
GB10, fp32 (TF32 off): greedy 40 tokens identical, 4/4 identical, 4/4
GB10, bf16: logits at text positions max abs ≤ 0.50 (logits ~35), argmax 100% (95% on the two-image prompt) ≤ 0.50, argmax 100% (95% on the two-image prompt)
GB10, bf16: greedy 40 tokens identical on 4/4 end-to-end and 4/4 with the remote inputs identical on 4/4 end-to-end, 3/4 with the remote inputs (diverges after 16 tokens; identical in fp32)

TIGER-Lab/VLM2Vec-Full, last-token embeddings, bf16 on the GB10: cosine to the remote code 0.9995–1.0000.

Token layout eval (call 2)

Phi-3.5-vision, bf16, greedy, first 500 test items:

<s> after each image (this PR) no <s> (<|image|> with rstrip=False) no <s>, and no \n after the image (Hub tokenizer as is)
AI2D 80.2% 80.2% (McNemar p 1.0) 80.4% (p 1.0)
ChartQA (relaxed accuracy) 64.6% 62.4% (p 0.027) 61.6% (p 0.004)
4096-token cache reset (call 3)

Phi-3.5-vision, bf16 on the GB10, prompt of 4040 tokens (with an image, and text only), 200 greedy tokens. The reference is a restart of generate on the full sequence just past 4096 tokens, which is what the Phi-3.5-vision remote code's reset does. With the override, generation matches the reference token for token. Without it, 4.9% of the tokens past the boundary match, and the output turns into repeated newlines.

Teacher-forced, text only, four 4000-token windows, 300 following tokens: NLL past the boundary is 7.1–8.1 without the reset and 0.05–2.5 with it.

With the override, the Phi-3.5-vision remote code and this PR generate identical tokens across the boundary (fp32, TF32 off; a 3975-token prompt with an image, 200 tokens, crossing at token 122). A continuation from a passed-in cache that crosses 4096 tokens recomputes the prefix with only the images passed to that call, so earlier images are lost, and a continuation that adds an image raises.

I used Claude Code for parts of this implementation.

lucamotz and others added 3 commits November 24, 2026 22:18
Rename "su"/"yarn" to "longrope" before standardize_rope_params(), so
original_max_position_embeddings is added for "su" configs.
Native phi3_v for microsoft/Phi-3-vision-128k-instruct and microsoft/Phi-3.5-vision-instruct (TIGER-Lab/VLM2Vec-Full loads with the same classes), built on LLaVA-NeXT, with the Hub weights loaded through the conversion mapping.

Co-authored-by: Yaswanth Gali <[email protected]>
Co-authored-by: Dahlbomii <[email protected]>
Generation that starts at or below original_max_position_embeddings and continues past it recomputes the cache with the long factors, as Phi3ForCausalLM does, passing the images again.
@lucamotz
lucamotz marked this pull request as ready for review November 25, 2026 07:42
@lucamotz

Copy link
Copy Markdown
Contributor Author

fyi @hmellor

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dropped an early review - do you think we can do packed-images instead of padded? Otherwise no major comments

Comment on lines +177 to +186
packed_features = []
for features, (rows, cols) in zip(torch.split(image_features, num_crops), grids):
sub_image = (
features[1:].view(rows, cols, side, side, -1).transpose(1, 2).reshape(rows * side, cols * side, -1)
)
sub_image = torch.cat([sub_image, newline.expand(rows * side, -1, -1)], dim=1)
global_image = torch.cat([features[0], newline.expand(side, -1, -1)], dim=1)
image_tokens = torch.cat([sub_image.flatten(0, 1), separator, global_image.flatten(0, 1)])
packed_features.append(self.multi_modal_projector(image_tokens))
image_outputs.pooler_output = packed_features

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and then we can follow qwen-like models with image_grid_thw to do per-image projection in vectorized way

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, the projector now runs once over all crops and the loop only arranges the projected tokens.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can still remove tolist() and vectorize it all

Comment on lines +49 to +51
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

apply_chat_template doesn't work for model?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not with the Hub files as they are: the repos have no processor chat template and the tokenizer's template only takes string content, so I've opened Hub PRs that add one (Phi-3.5-vision, Phi-3-vision-128k), and the example can switch to apply_chat_template once they're merged.

The image processor groups images by size and returns the crops of all
images along one dimension, with the rows and columns of crops of each
image as `image_sizes`. The model projects all crops at once, and the
processor takes the crop size from the processed images.
Also drops the casts of the two separators, which go straight into the projector now.
@lucamotz

Copy link
Copy Markdown
Contributor Author

Yes, done: the image processor now returns the crops of all images packed along the first dimension.

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice, lgtm with minor nits. @hmellor i think we can get approve from someone core and merge, nice to see a good usage of modular

Comment on lines +169 to +171
newline = self.multi_modal_projector(self.image_newline[0])
separator = self.multi_modal_projector(self.image_separator[0])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

loool, why they didn't merge these into one final newline/sep weight

Comment on lines +177 to +186
packed_features = []
for features, (rows, cols) in zip(torch.split(image_features, num_crops), grids):
sub_image = (
features[1:].view(rows, cols, side, side, -1).transpose(1, 2).reshape(rows * side, cols * side, -1)
)
sub_image = torch.cat([sub_image, newline.expand(rows * side, -1, -1)], dim=1)
global_image = torch.cat([features[0], newline.expand(side, -1, -1)], dim=1)
image_tokens = torch.cat([sub_image.flatten(0, 1), separator, global_image.flatten(0, 1)])
packed_features.append(self.multi_modal_projector(image_tokens))
image_outputs.pooler_output = packed_features

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can still remove tolist() and vectorize it all

@hmellor
hmellor requested a review from vasqu November 26, 2026 12:09
@zucchini-nlp

Copy link
Copy Markdown
Member

run-slow: phi3_v

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

@github-actions

Copy link
Copy Markdown
Contributor

CI (Nvidia + AMD)

Nvidia · ✅ No new failures 🎉👏 · ⚙️ Workflow · 📊 Dashboard

AMD · ❌ 2 new failing tests 😭 · ⚙️ Workflow · 📊 Dashboard

Failures (2 new)

    New failures:

    - phi3_v:
        tests/models/phi3_v/test_modeling_phi3_v.py::Phi3VForConditionalGenerationModelTest::test_flash_attn_2_inference_equivalence (✅ ⟹ ❌)
        tests/models/phi3_v/test_modeling_phi3_v.py::Phi3VForConditionalGenerationModelTest::test_flash_attn_2_inference_equivalence_right_padding (✅ ⟹ ❌)

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: auto, phi3_v

@lucamotz

Copy link
Copy Markdown
Contributor Author

@zucchini-nlp Skipping the two AMD tests now. This was due to packing changes. Can you retry?

@zucchini-nlp

Copy link
Copy Markdown
Member

dw about AMD, we'll run slow ci once just before merging. For now waiting on core review

@vasqu

vasqu commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

I will come to this next week I promise, sprinting some other important core modeling stuff atm!

@lucamotz

lucamotz commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

I will come to this next week I promise, sprinting some other important core modeling stuff atm!

I’ll just remind you of your promise 😅 (really just a reminder, no need to hurry up on my end haha)

@vasqu

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add phi3 Vision

5 participants