-
Notifications
You must be signed in to change notification settings - Fork 239
Support VLM calibration with image-text data #755
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
Edwardf0t1
wants to merge
16
commits into
main
Choose a base branch
from
zhiyu/vlm-calib
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
Changes from 15 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b9acc43
Add support for VLM calibration with image-text pair data
Edwardf0t1 528b51d
Add support for VLM calibration with image-text pair data
Edwardf0t1 3ef4b9d
add support for sampling from Nemotron-VLM-Dataset-v2
Edwardf0t1 2d60f98
update readme
Edwardf0t1 42a8406
fix issues when calibrate with image data for Nemotron Nano VL
Edwardf0t1 7489a36
fix issues when calibrate with image data for Nemotron Nano VL
Edwardf0t1 bd87154
fix issues when calibrate with image data for Nemotron Nano VL
Edwardf0t1 3200a63
fix issues when calibrate with image data for Nemotron Nano VL
Edwardf0t1 8964aa5
simplify
Edwardf0t1 3b7373d
refactor to make hf_ptq cleaner, create a separate vlm dataset utils …
Edwardf0t1 5c774f9
refactor to make hf_ptq cleaner, create a separate vlm dataset utils …
Edwardf0t1 f2774fc
update readme
Edwardf0t1 59d97a6
update readme
Edwardf0t1 e2e59f6
update readme
Edwardf0t1 2a3868a
minor refactor
Edwardf0t1 2611b0e
address reviews
Edwardf0t1 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
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,98 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # 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. | ||
|
|
||
| """Nemotron VL calibration helpers. | ||
|
|
||
| Nemotron Nano VL v2 remote-code wrapper `forward()` is not ideal to call during PTQ calibration because it may: | ||
| - Call `torch.distributed.get_rank()` unconditionally | ||
| - Assume `past_key_values` exists in the language model output | ||
|
|
||
| Instead, we run a "safe multimodal forward" that exercises: | ||
| - Vision encoder feature extraction (C-RADIOv2-H) | ||
| - Insertion of vision embeddings into token embeddings at `img_context_token_id` | ||
| - Language model forward pass (to trigger quantizer calibration) | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import contextlib | ||
| from typing import Any | ||
|
|
||
| import torch | ||
|
|
||
|
|
||
| def safe_nemotron_vl_forward(full_model: torch.nn.Module, batch: dict[str, Any]) -> None: | ||
| """Run a minimal multimodal forward for Nemotron VL that avoids wrapper output packaging.""" | ||
| pixel_values = batch.get("pixel_values") | ||
| input_ids = batch.get("input_ids") | ||
| attention_mask = batch.get("attention_mask") | ||
| position_ids = batch.get("position_ids") | ||
| image_flags = batch.get("image_flags") | ||
|
|
||
| if pixel_values is None or input_ids is None: | ||
| return | ||
|
|
||
| # Nemotron Nano VL v2 expects `image_flags` in forward(), but the processor doesn't always emit it. | ||
| # `pixel_values` is flattened across batch*images, so `image_flags` should align with pixel_values.shape[0]. | ||
| if image_flags is None and torch.is_tensor(pixel_values): | ||
| image_flags = torch.ones( | ||
| (pixel_values.shape[0], 1), device=pixel_values.device, dtype=torch.long | ||
| ) | ||
| if image_flags is None: | ||
| return | ||
|
|
||
| # Match the model's preferred vision dtype (usually bf16). | ||
| vision_dtype = None | ||
| with contextlib.suppress(Exception): | ||
| vision_dtype = getattr(full_model.vision_model.config, "torch_dtype", None) | ||
| if vision_dtype is None: | ||
| with contextlib.suppress(Exception): | ||
| vision_dtype = getattr(full_model.language_model.config, "torch_dtype", None) | ||
| if ( | ||
| vision_dtype is not None | ||
| and torch.is_tensor(pixel_values) | ||
| and pixel_values.dtype != vision_dtype | ||
| ): | ||
| pixel_values = pixel_values.to(dtype=vision_dtype) | ||
|
|
||
| # Token embeddings | ||
| inputs_embeds = full_model.language_model.get_input_embeddings()(input_ids) | ||
| image_flags_s = image_flags.squeeze(-1) | ||
|
|
||
| b, n, c = inputs_embeds.shape | ||
| flat_embeds = inputs_embeds.reshape(b * n, c) | ||
| flat_ids = input_ids.reshape(b * n) | ||
| selected = flat_ids == full_model.img_context_token_id | ||
|
|
||
| # Vision embeddings | ||
| vit_embeds = full_model.extract_feature(pixel_values) | ||
| vit_embeds = vit_embeds[image_flags_s == 1] | ||
| try: | ||
| flat_embeds[selected] = flat_embeds[selected] * 0.0 + vit_embeds.reshape(-1, c) | ||
| except Exception: | ||
| vit_embeds = vit_embeds.reshape(-1, c) | ||
| n_token = selected.sum() | ||
| flat_embeds[selected] = flat_embeds[selected] * 0.0 + vit_embeds[:n_token] | ||
|
|
||
| inputs_embeds = flat_embeds.reshape(b, n, c) | ||
|
|
||
| # LLM forward (drives activation stats) | ||
| full_model.language_model( | ||
| inputs_embeds=inputs_embeds, | ||
| attention_mask=attention_mask, | ||
| position_ids=position_ids, | ||
| use_cache=False, | ||
| return_dict=False, | ||
| ) |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.