Repository navigation
Add Phi-3-vision - #51214
Add Phi-3-vision#51214lucamotz wants to merge 8 commits into
Conversation
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.
|
fyi @hmellor |
zucchini-nlp
left a comment
There was a problem hiding this comment.
dropped an early review - do you think we can do packed-images instead of padded? Otherwise no major comments
| 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 |
There was a problem hiding this comment.
and then we can follow qwen-like models with image_grid_thw to do per-image projection in vectorized way
There was a problem hiding this comment.
Done, the projector now runs once over all crops and the loop only arranges the projected tokens.
There was a problem hiding this comment.
can still remove tolist() and vectorize it all
| 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) |
There was a problem hiding this comment.
apply_chat_template doesn't work for model?
There was a problem hiding this comment.
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.
|
Yes, done: the image processor now returns the crops of all images packed along the first dimension. |
zucchini-nlp
left a comment
There was a problem hiding this comment.
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
| newline = self.multi_modal_projector(self.image_newline[0]) | ||
| separator = self.multi_modal_projector(self.image_separator[0]) | ||
|
|
There was a problem hiding this comment.
loool, why they didn't merge these into one final newline/sep weight
| 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 |
There was a problem hiding this comment.
can still remove tolist() and vectorize it all
|
run-slow: phi3_v |
|
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: |
CI (Nvidia + AMD)Nvidia · ✅ No new failures 🎉👏 · ⚙️ Workflow · 📊 Dashboard AMD · ❌ 2 new failing tests 😭 · ⚙️ Workflow · 📊 Dashboard Failures (2 new)New failures: - phi3_v: |
… as the first sample
|
[For maintainers] Suggested jobs to run (before merge) run-slow: auto, phi3_v |
|
@zucchini-nlp Skipping the two AMD tests now. This was due to packing changes. Can you retry? |
|
dw about AMD, we'll run slow ci once just before merging. For now waiting on core review |
|
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) |
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 isget_image_features(2x2 patch merge, learned row newline and global separator), the HD-crop image processor, and 6WeightRenamings 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
image_sizeskeeps 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.<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).Phi3ForCausalLMandPhi4MultimodalForCausalLMdo. I ported it in Phi3's form, which needs aprepare_inputs_for_generationoverride that also passes the images again; without it, generation that starts below 4096 tokens degenerates once it passes them.Phi3VConfigdrops the"_attn_implementation": "flash_attention_2"that the Microsoft configs force when it folds the flat Hub config; otherwiseAutoModel*ignoresattn_implementationand loading needs flash-attn.processor.apply_chat_templateandtokenizer.image_tokenneed 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_SLOWtests 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.
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)<s>(<|image|>withrstrip=False)<s>, and no\nafter the image (Hub tokenizer as is)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
generateon 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.