Model

ankit/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4

Blame for image_processing_nemotron_h_omni.py at 951ba44

Line blame for image_processing_nemotron_h_omni.py
LineCommitAuthorDateCode
1Add files using upload-large-folder toolbf6c919ankit# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Fast image processor for the NemotronH Omni model."""
15
16import math
17
18import numpy as np
19from transformers.image_processing_backends import TorchvisionBackend
20from transformers.image_processing_base import BatchFeature
21from transformers.image_utils import ImageInput, ImageType, get_image_type, make_list_of_images
22from transformers.utils import is_torch_available
23
24
25if is_torch_available():
26 import torch
27
28
29class NemotronH_Omni_Reasoning_V3ImageProcessor(TorchvisionBackend):
30 """
31 Dynamic-resolution image processor for the NemotronH Omni model.
32
33 Each image is resized to a single tile whose patch-grid `(h_patches, w_patches)` is chosen to
34 land between `min_num_patches` and `max_num_patches` (on a `patch_size` grid), respecting the
35 aspect ratio, then normalized with `norm_mean` / `norm_std`. Video frames use a separate fixed
36 target-patch budget with aspect ratio preserved (toggled via `_is_video_mode`).
37 """
38
39 model_input_names = ["pixel_values"]
40
41 def __init__(
42 self,
43 norm_mean=None,
44 norm_std=None,
45 patch_size=16,
46 downsample_ratio=0.5,
47 min_num_patches=1024,
48 max_num_patches=13312,
49 max_model_len=16384,
50 video_target_num_patches=1024,
51 video_maintain_aspect_ratio=True,
52 **kwargs,
53 ):
54 super().__init__(**kwargs)
55 self.norm_mean = norm_mean
56 self.norm_std = norm_std
57 self.patch_size = patch_size
58 self.downsample_ratio = downsample_ratio
59 # Integer reduction factor for pixel_shuffle (downsample_ratio = 0.5 -> factor 2).
60 self._downsample_factor = int(round(1.0 / downsample_ratio))
61 # Per-image patch-grid bounds (on the pre-pixel-shuffle `patch_size` grid).
62 self.min_num_patches = min_num_patches
63 self.max_num_patches = max_num_patches
64 self.max_model_len = max_model_len
65 # Video frames use a separate (fixed) target-patch budget with aspect-ratio preserved.
66 self.video_target_num_patches = video_target_num_patches
67 self.video_maintain_aspect_ratio = video_maintain_aspect_ratio
68
69 # Keep the PIL image through to `_preprocess`: we need PIL.resize semantics to match the
70 # reference tiling algorithm exactly; resizing a tensor via `torchvision.transforms.Resize`
71 # uses different kernels and breaks bit-exact agreement.
72 def _process_image(self, image: ImageInput, **kwargs):
73 if get_image_type(image) == ImageType.PIL:
74 if image.mode != "RGB":
75 image = image.convert("RGB")
76 return image
77
78 # transformers 5.6 renamed this hook from `_process_image` to `process_image`; alias both.
79 process_image = _process_image
80
81 # Toggled by the processor around video calls (the strict `ImagesKwargs` validator won't let us
82 # thread a new kwarg down, so we use a flag on the instance instead).
83 _is_video_mode: bool = False
84
85 def _preprocess(self, images, return_tensors=None, **kwargs) -> BatchFeature:
86 """Resize each image to its dynamic-resolution tile, normalize, and return pixel values.
87
88 When `self._is_video_mode=True` (flipped by the processor before the video call), each
89 input is resized using the **video** target-size rule (`video_target_num_patches`,
90 aspect-ratio preserved) instead of the image dynamic-res rule.
91 """
92 is_video = self._is_video_mode
93 images = make_list_of_images(images)
94
95 target_sizes = []
96 if is_video:
97 for img in images:
98 target_w_patches, target_h_patches = self._compute_target_patches_video(img)
99 target_sizes.append((target_w_patches, target_h_patches))
100 else:
101 # Image path: per-image budget bounded by [min_num_patches, max_num_patches], with a
102 # global cap derived from `max_model_len` x pixel-shuffle factor^2.
103 num_tokens_available = self.max_model_len - 4
104 budget = num_tokens_available * (self._downsample_factor**2)
105 budget = max(budget, self.min_num_patches * len(images))
106 max_budget = self.max_num_patches if (self.max_num_patches and self.max_num_patches > 0) else float("inf")
107 per_image_budget = [max(min(budget, max_budget), self.min_num_patches) for _ in images]
108 for img, tokens_for_media in zip(images, per_image_budget):
109 target_w_patches, target_h_patches = self._compute_target_patches(img, tokens_for_media)
110 target_sizes.append((target_w_patches, target_h_patches))
111
112 norm_mean = torch.tensor(self.norm_mean).view(1, 3, 1, 1)
113 norm_std = torch.tensor(self.norm_std).view(1, 3, 1, 1)
114
115 pixel_values_list = []
116 num_tokens_per_image = []
117 imgs_sizes = []
118 for img, (wp, hp) in zip(images, target_sizes):
119 target_w = wp * self.patch_size
120 target_h = hp * self.patch_size
121 # Antialiased bicubic interpolation via `torch.nn.functional.interpolate`. PIL's bicubic
122 # uses a different kernel (and no antialiasing), producing pixel values that amplify
123 # through the ViT / mamba stack and cause outputs to diverge past the first few tokens.
124 arr = np.asarray(img, dtype=np.uint8) # (H, W, 3)
125 t = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).to(dtype=torch.float32) # (1, 3, H, W)
126 if t.shape[-2] != target_h or t.shape[-1] != target_w:
127 t = torch.nn.functional.interpolate(
128 t, size=(target_h, target_w), mode="bicubic", align_corners=False, antialias=True
129 )
130 t = (t / 255.0 - norm_mean) / norm_std
131 pixel_values_list.append(t.squeeze(0)) # (3, H, W)
132 num_tokens_per_image.append((wp * hp) // (self._downsample_factor**2))
133 imgs_sizes.append((target_h, target_w))
134
135 # Stack if all images have the same target size; otherwise keep as a list of
136 # (3, H_i, W_i) tensors (the model's `extract_feature` handles both).
137 all_same_shape = all(t.shape == pixel_values_list[0].shape for t in pixel_values_list)
138 pixel_values = torch.stack(pixel_values_list, dim=0) if all_same_shape else pixel_values_list
139
140 return BatchFeature(
141 data={
142 "pixel_values": pixel_values,
143 "num_patches": [1] * len(images),
144 "num_tokens": num_tokens_per_image,
145 "imgs_sizes": imgs_sizes,
146 },
147 tensor_type=(return_tensors if all_same_shape else None),
148 )
149
150 def _compute_target_patches(self, img, tokens_available: int):
151 """Choose the `(w_patches, h_patches)` tile that best fits `tokens_available` (image path)."""
152 orig_w, orig_h = img.width, img.height
153 # Ceil-ish: `round(x + 0.5)` == `floor(x) + 1` for non-integer x, `x` for integer.
154 closest_patch_h = round(orig_h / self.patch_size + 0.5)
155 closest_patch_w = round(orig_w / self.patch_size + 0.5)
156 patches = closest_patch_h * closest_patch_w
157
158 # Downscale to fit the token budget.
159 factor = min(math.sqrt(tokens_available / patches), 1.0)
160 target_h = math.floor(factor * closest_patch_h)
161 target_w = math.floor(factor * closest_patch_w)
162
163 # Scale up if below the per-image minimum.
164 if tokens_available > self.min_num_patches and target_h * target_w < self.min_num_patches:
165 up = math.sqrt(self.min_num_patches / (target_h * target_w))
166 target_h = math.ceil(up * target_h)
167 target_w = math.ceil(up * target_w)
168
169 # Round each dim to a multiple of the pixel_shuffle factor so tokens divide evenly.
170 divisor = self._downsample_factor
171 rem_h = target_h % divisor
172 if rem_h:
173 inc_h = divisor - rem_h
174 if (target_h + inc_h) * target_w <= tokens_available:
175 target_h += inc_h
176 else:
177 target_h = max(divisor, target_h - rem_h)
178 rem_w = target_w % divisor
179 if rem_w:
180 inc_w = divisor - rem_w
181 if target_h * (target_w + inc_w) <= tokens_available:
182 target_w += inc_w
183 else:
184 target_w = max(divisor, target_w - rem_w)
185
186 return target_w, target_h
187
188 def _compute_target_patches_video(self, img):
189 """Choose an aspect-preserving `(w_patches, h_patches)` tile near `video_target_num_patches`."""
190 orig_w, orig_h = img.width, img.height
191 target = self.video_target_num_patches
192 divisor = self._downsample_factor
193 if self.video_maintain_aspect_ratio:
194 aspect_wh = orig_w / max(orig_h, 1)
195 ph = max(round(math.sqrt(target / aspect_wh)), 1)
196 pw = max(round(math.sqrt(target * aspect_wh)), 1)
197 if divisor > 1:
198 rem_h = ph % divisor
199 rem_w = pw % divisor
200 ph_up = ph + (divisor - rem_h if rem_h else 0)
201 ph_down = ph - rem_h
202 pw_up = pw + (divisor - rem_w if rem_w else 0)
203 pw_down = pw - rem_w
204 if ph_up * pw_up <= target:
205 ph, pw = ph_up, pw_up
206 else:
207 ph = max(divisor, ph_down)
208 pw = max(divisor, pw_down)
209 else:
210 side = int(math.sqrt(target))
211 side = max(divisor, (side // divisor) * divisor)
212 ph = pw = side
213 return pw, ph
214
215
216__all__ = ["NemotronH_Omni_Reasoning_V3ImageProcessor"]