optimum-rbln 0.9.1__py3-none-any.whl → 0.9.2a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of optimum-rbln might be problematic. Click here for more details.
- optimum/rbln/__version__.py +2 -2
- optimum/rbln/configuration_utils.py +54 -7
- optimum/rbln/diffusers/configurations/pipelines/configuration_controlnet.py +30 -14
- optimum/rbln/diffusers/configurations/pipelines/configuration_cosmos.py +11 -8
- optimum/rbln/diffusers/configurations/pipelines/configuration_kandinsky2_2.py +23 -13
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion.py +10 -6
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_3.py +14 -10
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_xl.py +14 -7
- optimum/rbln/diffusers/pipelines/cosmos/configuration_cosmos_guardrail.py +9 -11
- optimum/rbln/transformers/models/blip_2/configuration_blip_2.py +35 -3
- optimum/rbln/transformers/models/blip_2/modeling_blip_2.py +21 -22
- optimum/rbln/transformers/models/clip/modeling_clip.py +4 -0
- optimum/rbln/transformers/models/colpali/colpali_architecture.py +2 -2
- optimum/rbln/transformers/models/colpali/configuration_colpali.py +17 -1
- optimum/rbln/transformers/models/colpali/modeling_colpali.py +72 -79
- optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +2 -2
- optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +11 -3
- optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +58 -43
- optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +27 -3
- optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +22 -15
- optimum/rbln/transformers/models/llava/configuration_llava.py +16 -2
- optimum/rbln/transformers/models/llava/modeling_llava.py +106 -49
- optimum/rbln/transformers/models/llava_next/configuration_llava_next.py +11 -13
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +232 -342
- optimum/rbln/transformers/models/pixtral/modeling_pixtral.py +6 -11
- optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +11 -1
- optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py +22 -0
- optimum/rbln/transformers/models/qwen2_vl/modeling_qwen2_vl.py +11 -1
- optimum/rbln/transformers/models/qwen2_vl/qwen2_vl_architecture.py +22 -0
- optimum/rbln/transformers/models/siglip/modeling_siglip.py +3 -14
- optimum/rbln/transformers/utils/rbln_runtime_wrapper.py +79 -0
- optimum/rbln/utils/submodule.py +21 -5
- {optimum_rbln-0.9.1.dist-info → optimum_rbln-0.9.2a1.dist-info}/METADATA +2 -2
- {optimum_rbln-0.9.1.dist-info → optimum_rbln-0.9.2a1.dist-info}/RECORD +36 -35
- {optimum_rbln-0.9.1.dist-info → optimum_rbln-0.9.2a1.dist-info}/WHEEL +0 -0
- {optimum_rbln-0.9.1.dist-info → optimum_rbln-0.9.2a1.dist-info}/licenses/LICENSE +0 -0
|
@@ -12,18 +12,26 @@
|
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
|
|
15
|
+
import importlib
|
|
15
16
|
import inspect
|
|
16
17
|
from pathlib import Path
|
|
17
|
-
from typing import TYPE_CHECKING, Any, Callable,
|
|
18
|
+
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union
|
|
18
19
|
|
|
19
20
|
import numpy as np
|
|
20
21
|
import torch
|
|
21
22
|
from transformers import AutoModelForVision2Seq, LlavaNextForConditionalGeneration, PretrainedConfig, PreTrainedModel
|
|
22
23
|
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
|
24
|
+
from transformers.modeling_utils import no_init_weights
|
|
25
|
+
from transformers.models.llava_next.modeling_llava_next import (
|
|
26
|
+
get_anyres_image_grid_shape,
|
|
27
|
+
image_size_to_num_patches,
|
|
28
|
+
unpad_image,
|
|
29
|
+
)
|
|
23
30
|
|
|
24
31
|
from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
|
|
25
32
|
from ....modeling import RBLNModel
|
|
26
33
|
from ....utils.logging import get_logger
|
|
34
|
+
from ...utils.rbln_runtime_wrapper import LoopProcessor
|
|
27
35
|
from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyOutput
|
|
28
36
|
|
|
29
37
|
|
|
@@ -33,33 +41,27 @@ if TYPE_CHECKING:
|
|
|
33
41
|
from transformers import AutoFeatureExtractor, AutoProcessor, AutoTokenizer, PretrainedConfig
|
|
34
42
|
|
|
35
43
|
|
|
36
|
-
class LoopVisionTower:
|
|
37
|
-
def __init__(self, vision_tower: RBLNModel)
|
|
38
|
-
|
|
44
|
+
class LoopVisionTower(LoopProcessor):
|
|
45
|
+
def __init__(self, vision_tower: "RBLNModel"):
|
|
46
|
+
super().__init__(model=vision_tower.model[0])
|
|
39
47
|
|
|
40
|
-
def
|
|
41
|
-
|
|
42
|
-
# shape of pixel_values : [batch, num_patches, num_channel, height, width]
|
|
43
|
-
pixel_values = args[0]
|
|
48
|
+
def _get_batch_size(self, pixel_values, **kwargs):
|
|
49
|
+
return pixel_values.shape[0]
|
|
44
50
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
for
|
|
48
|
-
|
|
51
|
+
def _prepare_inputs_for_iteration(self, index, common_inputs, pixel_values, **kwargs):
|
|
52
|
+
pixel_values_item = pixel_values[index : index + 1]
|
|
53
|
+
out_buffer = [tensor[index : index + 1] for tensor in kwargs["out"]]
|
|
54
|
+
return ([pixel_values_item], {"out": out_buffer})
|
|
49
55
|
|
|
50
|
-
|
|
51
|
-
|
|
56
|
+
def _process_outputs(self, outputs: list, **kwargs) -> "BaseModelOutputWithPooling":
|
|
57
|
+
output = kwargs["out"]
|
|
58
|
+
last_hidden_states = output[0]
|
|
59
|
+
pooler_output = output[1]
|
|
52
60
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
hidden_states = [output[2:] for output in outputs] # batch x (hidden x 1)
|
|
58
|
-
|
|
59
|
-
hidden_states = tuple(
|
|
60
|
-
torch.cat(tuple((hidden_states[n][i] for n in range(batch_size))), dim=0)
|
|
61
|
-
for i in range(len(hidden_states[0]))
|
|
62
|
-
) # hidden x (batch,)
|
|
61
|
+
if not output[2:]:
|
|
62
|
+
hidden_states = None
|
|
63
|
+
else:
|
|
64
|
+
hidden_states = tuple(output[2:])
|
|
63
65
|
|
|
64
66
|
return BaseModelOutputWithPooling(
|
|
65
67
|
last_hidden_state=last_hidden_states,
|
|
@@ -67,35 +69,22 @@ class LoopVisionTower:
|
|
|
67
69
|
hidden_states=hidden_states,
|
|
68
70
|
)
|
|
69
71
|
|
|
70
|
-
def __call__(self, *args: Any, **kwds: Any) -> Any:
|
|
71
|
-
return self.forward(*args, **kwds)
|
|
72
|
-
|
|
73
|
-
def __repr__(self) -> str:
|
|
74
|
-
return repr(self.vision_tower)
|
|
75
|
-
|
|
76
72
|
|
|
77
|
-
class LoopProjector:
|
|
78
|
-
def __init__(self, multi_modal_projector)
|
|
79
|
-
|
|
73
|
+
class LoopProjector(LoopProcessor):
|
|
74
|
+
def __init__(self, multi_modal_projector: "RBLNModel"):
|
|
75
|
+
super().__init__(model=multi_modal_projector)
|
|
80
76
|
|
|
81
|
-
def
|
|
82
|
-
|
|
83
|
-
image_feature = args[0]
|
|
77
|
+
def _get_batch_size(self, image_feature, **kwargs):
|
|
78
|
+
return image_feature.shape[0]
|
|
84
79
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
for
|
|
88
|
-
|
|
80
|
+
def _prepare_inputs_for_iteration(self, index, common_inputs, image_feature, **kwargs):
|
|
81
|
+
image_feature_item = image_feature[index : index + 1]
|
|
82
|
+
out_buffer = [tensor[index : index + 1] for tensor in kwargs["out"]]
|
|
83
|
+
return ([image_feature_item], {"out": out_buffer})
|
|
89
84
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
return
|
|
93
|
-
|
|
94
|
-
def __call__(self, *args: Any, **kwds: Any) -> Any:
|
|
95
|
-
return self.forward(*args, **kwds)
|
|
96
|
-
|
|
97
|
-
def __repr__(self) -> str:
|
|
98
|
-
return repr(self.multi_modal_projector)
|
|
85
|
+
def _process_outputs(self, outputs: list, **kwargs):
|
|
86
|
+
output = kwargs["out"]
|
|
87
|
+
return output[0]
|
|
99
88
|
|
|
100
89
|
|
|
101
90
|
class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
@@ -148,6 +137,23 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
148
137
|
def can_generate(self):
|
|
149
138
|
return True
|
|
150
139
|
|
|
140
|
+
@classmethod
|
|
141
|
+
def get_pytorch_model(cls, *args, **kwargs):
|
|
142
|
+
model = super().get_pytorch_model(*args, **kwargs)
|
|
143
|
+
|
|
144
|
+
with no_init_weights():
|
|
145
|
+
model_cls_name = model.model.language_model.__class__.__name__
|
|
146
|
+
causal_model_cls_name = model_cls_name.replace("Model", "ForCausalLM")
|
|
147
|
+
causal_model_cls = getattr(importlib.import_module("transformers"), causal_model_cls_name)
|
|
148
|
+
new_language_model = causal_model_cls(model.model.language_model.config)
|
|
149
|
+
|
|
150
|
+
new_language_model.lm_head = model.lm_head
|
|
151
|
+
new_language_model.model = model.model.language_model
|
|
152
|
+
model.model.language_model = new_language_model
|
|
153
|
+
model.lm_head = None
|
|
154
|
+
del model.lm_head
|
|
155
|
+
return model
|
|
156
|
+
|
|
151
157
|
@classmethod
|
|
152
158
|
def save_torch_artifacts(
|
|
153
159
|
cls,
|
|
@@ -159,7 +165,7 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
159
165
|
# If you are unavoidably running on a CPU rather than an RBLN device,
|
|
160
166
|
# store the torch tensor, weight, etc. in this function.
|
|
161
167
|
save_dict = {}
|
|
162
|
-
save_dict["image_newline"] = model.image_newline
|
|
168
|
+
save_dict["image_newline"] = model.model.image_newline
|
|
163
169
|
torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
|
|
164
170
|
|
|
165
171
|
def __post_init__(self, **kwargs):
|
|
@@ -206,7 +212,11 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
206
212
|
selected_image_feature_dim = num_positions
|
|
207
213
|
|
|
208
214
|
input_info = [
|
|
209
|
-
(
|
|
215
|
+
(
|
|
216
|
+
"image_features",
|
|
217
|
+
[rbln_config.vision_tower.batch_size, selected_image_feature_dim, feature_size],
|
|
218
|
+
"float32",
|
|
219
|
+
)
|
|
210
220
|
]
|
|
211
221
|
rbln_compile_config = RBLNCompileConfig(input_info=input_info)
|
|
212
222
|
rbln_config.set_compile_cfgs([rbln_compile_config])
|
|
@@ -217,86 +227,62 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
217
227
|
input_ids,
|
|
218
228
|
inputs_embeds=None,
|
|
219
229
|
pixel_values=None,
|
|
220
|
-
image_sizes=None,
|
|
221
230
|
attention_mask=None,
|
|
231
|
+
cache_position=None,
|
|
232
|
+
image_sizes=None,
|
|
222
233
|
generate_idx=None,
|
|
223
234
|
**kwargs,
|
|
224
235
|
):
|
|
225
|
-
# Prepare HF generation
|
|
226
236
|
is_prefill_phase = generate_idx is None
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
model_inputs = self.language_model.prepare_inputs_for_generation(
|
|
230
|
-
input_ids=input_ids,
|
|
231
|
-
inputs_embeds=inputs_embeds,
|
|
232
|
-
generate_idx=generate_idx, # Not affect
|
|
233
|
-
attention_mask=attention_mask,
|
|
234
|
-
**kwargs,
|
|
235
|
-
)
|
|
237
|
+
model_inputs = {}
|
|
236
238
|
|
|
237
239
|
if is_prefill_phase:
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
240
|
+
generate_idx = attention_mask.sum(dim=-1, keepdim=True).int()
|
|
241
|
+
cache_position = None
|
|
242
|
+
pixel_values = pixel_values
|
|
243
|
+
model_inputs.update({"image_sizes": image_sizes})
|
|
244
|
+
else:
|
|
245
|
+
if inputs_embeds is not None:
|
|
246
|
+
raise NotImplementedError("Specifying inputs_embeds in decoder phase is not supported.")
|
|
245
247
|
|
|
246
|
-
|
|
248
|
+
pixel_values = None
|
|
249
|
+
input_ids = input_ids[:, -1:]
|
|
250
|
+
cache_position = generate_idx
|
|
251
|
+
generate_idx = generate_idx + 1
|
|
252
|
+
model_inputs.update({"input_ids": input_ids})
|
|
253
|
+
|
|
254
|
+
if inputs_embeds is not None:
|
|
255
|
+
if self.rbln_config.use_inputs_embeds:
|
|
256
|
+
model_inputs.update({"inputs_embeds": inputs_embeds})
|
|
257
|
+
else:
|
|
258
|
+
raise ValueError(
|
|
259
|
+
"The specifying inputs_embeds is only supported when using a compiled RBLN model with 'rbln_use_inputs_embeds' set to True."
|
|
260
|
+
)
|
|
261
|
+
else:
|
|
262
|
+
model_inputs.update({"input_ids": input_ids})
|
|
263
|
+
|
|
264
|
+
model_inputs.update(
|
|
265
|
+
{
|
|
266
|
+
"attention_mask": attention_mask,
|
|
267
|
+
"pixel_values": pixel_values,
|
|
268
|
+
"cache_position": cache_position,
|
|
269
|
+
"generate_idx": generate_idx,
|
|
270
|
+
}
|
|
271
|
+
)
|
|
247
272
|
return model_inputs
|
|
248
273
|
|
|
249
|
-
def _update_model_kwargs_for_generation(
|
|
250
|
-
self,
|
|
251
|
-
outputs: RBLNDecoderOnlyOutput,
|
|
252
|
-
model_kwargs: Dict[str, Any],
|
|
253
|
-
**kwargs,
|
|
254
|
-
) -> Dict[str, Any]:
|
|
274
|
+
def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
|
|
255
275
|
# update generate_idx
|
|
256
276
|
model_kwargs["generate_idx"] = outputs.generate_idx
|
|
257
|
-
|
|
258
277
|
return model_kwargs
|
|
259
278
|
|
|
260
|
-
def
|
|
279
|
+
def get_image_features(
|
|
261
280
|
self,
|
|
262
|
-
input_ids: torch.LongTensor,
|
|
263
|
-
) -> torch.Tensor:
|
|
264
|
-
for_inputs_embeds_ids = input_ids.clone()
|
|
265
|
-
for_inputs_embeds_ids[(input_ids == self.config.image_token_index)] = 0
|
|
266
|
-
inputs_embeds = self.get_input_embeddings()(for_inputs_embeds_ids)
|
|
267
|
-
|
|
268
|
-
return inputs_embeds
|
|
269
|
-
|
|
270
|
-
def image_embedding(
|
|
271
|
-
self,
|
|
272
|
-
image_sizes: torch.Tensor,
|
|
273
281
|
pixel_values: torch.FloatTensor,
|
|
274
|
-
|
|
282
|
+
image_sizes: torch.Tensor,
|
|
283
|
+
vision_feature_layer: Union[int, List[int]],
|
|
275
284
|
vision_feature_select_strategy: str,
|
|
276
285
|
):
|
|
277
|
-
vision_feature_layer = (
|
|
278
|
-
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
279
|
-
)
|
|
280
|
-
vision_feature_select_strategy = (
|
|
281
|
-
vision_feature_select_strategy
|
|
282
|
-
if vision_feature_select_strategy is not None
|
|
283
|
-
else self.config.vision_feature_select_strategy
|
|
284
|
-
)
|
|
285
|
-
|
|
286
|
-
"""
|
|
287
|
-
Obtains image last hidden states from the vision tower and apply multimodal projection.
|
|
288
|
-
|
|
289
|
-
Args:
|
|
290
|
-
pixel_values (torch.FloatTensor): The tensors corresponding to the input images
|
|
291
|
-
whose shape is `(batch_size, num_patches, channels, height, width)`.
|
|
292
|
-
image_sizes (torch.Tensor): Actual image size of each images (H, W).
|
|
293
|
-
vision_feature_layer (int): The index of the layer to select the vision feature.
|
|
294
|
-
vision_feature_select_strategy (str): The feature selection strategy used to select the vision feature from the vision backbone.
|
|
295
|
-
Can be one of `"default"` or `"full"`
|
|
296
|
-
Returns:
|
|
297
|
-
image_features (List[torch.Tensor]): List of image feature tensor, each contains all the visual feature of all patches
|
|
298
|
-
and are of shape `(num_patches, image_length, embed_dim)`).
|
|
299
|
-
"""
|
|
300
286
|
# ! infer image_num_patches from image_sizes
|
|
301
287
|
image_num_patches = [
|
|
302
288
|
image_size_to_num_patches(
|
|
@@ -306,6 +292,26 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
306
292
|
)
|
|
307
293
|
for imsize in image_sizes
|
|
308
294
|
]
|
|
295
|
+
|
|
296
|
+
# prepare out buffer for pre-allocation
|
|
297
|
+
vision_out_size = [
|
|
298
|
+
pixel_values.shape[0] * pixel_values.shape[1],
|
|
299
|
+
(self.config.vision_config.image_size // self.config.vision_config.patch_size) ** 2 + 1,
|
|
300
|
+
self.config.vision_config.hidden_size,
|
|
301
|
+
]
|
|
302
|
+
pooler_out_size = [pixel_values.shape[0] * pixel_values.shape[1], self.config.vision_config.hidden_size]
|
|
303
|
+
vision_out_buffer = []
|
|
304
|
+
for i in range(self.config.vision_config.num_hidden_layers + 2):
|
|
305
|
+
vision_out_buffer.append(torch.empty(size=vision_out_size, dtype=torch.float32, device="cpu"))
|
|
306
|
+
vision_out_buffer.insert(1, torch.empty(size=pooler_out_size, dtype=torch.float32, device="cpu"))
|
|
307
|
+
|
|
308
|
+
projector_out_size = [
|
|
309
|
+
pixel_values.shape[0] * pixel_values.shape[1],
|
|
310
|
+
(self.config.vision_config.image_size // self.config.vision_config.patch_size) ** 2,
|
|
311
|
+
self.config.text_config.hidden_size,
|
|
312
|
+
]
|
|
313
|
+
projector_out_buffer = [torch.empty(size=projector_out_size, dtype=torch.float32, device="cpu")]
|
|
314
|
+
|
|
309
315
|
if pixel_values.dim() == 5:
|
|
310
316
|
# stacked if input is (batch_size, num_patches, num_channels, height, width)
|
|
311
317
|
_pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
|
|
@@ -314,114 +320,25 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
314
320
|
# otherwise has to be stacked from list of (num_patches, num_channels, height, width)
|
|
315
321
|
raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
|
|
316
322
|
|
|
317
|
-
image_features = self.vision_tower(pixel_values, output_hidden_states=True)
|
|
318
|
-
|
|
323
|
+
image_features = self.vision_tower(pixel_values, output_hidden_states=True, out=vision_out_buffer)
|
|
324
|
+
# If we have one vision feature layer, return the corresponding hidden states,
|
|
325
|
+
# otherwise, select the hidden states of each feature layer and concatenate them
|
|
326
|
+
if isinstance(vision_feature_layer, int):
|
|
327
|
+
selected_image_feature = image_features.hidden_states[vision_feature_layer]
|
|
328
|
+
else:
|
|
329
|
+
hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
|
|
330
|
+
selected_image_feature = torch.cat(hs_pool, dim=-1)
|
|
331
|
+
|
|
319
332
|
if vision_feature_select_strategy == "default":
|
|
320
333
|
selected_image_feature = selected_image_feature[:, 1:]
|
|
321
334
|
elif vision_feature_select_strategy == "full":
|
|
322
335
|
selected_image_feature = selected_image_feature
|
|
323
|
-
image_features = self.multi_modal_projector(selected_image_feature)
|
|
324
|
-
image_features = torch.split(image_features, image_num_patches, dim=0)
|
|
325
|
-
|
|
326
|
-
# NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
|
|
327
|
-
image_features, feature_lens = self.pack_image_features(
|
|
328
|
-
image_features,
|
|
329
|
-
image_sizes,
|
|
330
|
-
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
331
|
-
image_newline=self.image_newline,
|
|
332
|
-
)
|
|
333
|
-
|
|
334
|
-
return image_features, feature_lens
|
|
335
|
-
|
|
336
|
-
def forward(
|
|
337
|
-
self,
|
|
338
|
-
input_ids: torch.LongTensor = None,
|
|
339
|
-
attention_mask: torch.LongTensor = None,
|
|
340
|
-
pixel_values: torch.FloatTensor = None,
|
|
341
|
-
image_sizes: Optional[torch.LongTensor] = None,
|
|
342
|
-
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
343
|
-
vision_feature_layer: Optional[int] = None,
|
|
344
|
-
vision_feature_select_strategy: Optional[str] = None,
|
|
345
|
-
cache_position: torch.Tensor = None,
|
|
346
|
-
generate_idx: Optional[torch.Tensor] = None,
|
|
347
|
-
batch_idx: Optional[int] = None,
|
|
348
|
-
**kwargs,
|
|
349
|
-
) -> Union[Tuple, RBLNDecoderOnlyOutput]:
|
|
350
|
-
vision_feature_layer = (
|
|
351
|
-
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
352
|
-
)
|
|
353
|
-
vision_feature_select_strategy = (
|
|
354
|
-
vision_feature_select_strategy
|
|
355
|
-
if vision_feature_select_strategy is not None
|
|
356
|
-
else self.config.vision_feature_select_strategy
|
|
357
|
-
)
|
|
358
|
-
|
|
359
|
-
if inputs_embeds is not None:
|
|
360
|
-
raise NotImplementedError("Specifying inputs_embeds is not supported.")
|
|
361
|
-
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
362
|
-
|
|
363
|
-
if pixel_values is not None and pixel_values.size(0) > 0:
|
|
364
|
-
image_features, _ = self.image_embedding(
|
|
365
|
-
pixel_values=pixel_values,
|
|
366
|
-
image_sizes=image_sizes,
|
|
367
|
-
vision_feature_layer=vision_feature_layer,
|
|
368
|
-
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
369
|
-
)
|
|
370
|
-
|
|
371
|
-
n_image_tokens = (input_ids == self.config.image_token_index).sum().item()
|
|
372
|
-
n_image_features = image_features.shape[0]
|
|
373
|
-
if n_image_tokens != n_image_features:
|
|
374
|
-
raise ValueError(
|
|
375
|
-
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
|
376
|
-
)
|
|
377
|
-
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
|
378
|
-
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
379
|
-
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
380
|
-
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
381
|
-
|
|
382
|
-
is_prefill_phase = not generate_idx.bool().all()
|
|
383
|
-
|
|
384
|
-
if is_prefill_phase:
|
|
385
|
-
logits = []
|
|
386
|
-
batch_size = input_ids.shape[0]
|
|
387
|
-
inputs_embeds = [inputs_embeds[i : i + 1, attention_mask[i].bool()] for i in range(batch_size)]
|
|
388
|
-
for batch_idx in range(batch_size):
|
|
389
|
-
generate_idx[batch_idx] = inputs_embeds[batch_idx].shape[-2]
|
|
390
|
-
output = self.language_model.prefill_decoder(
|
|
391
|
-
inputs_embeds=inputs_embeds[batch_idx],
|
|
392
|
-
batch_idx=batch_idx,
|
|
393
|
-
cache_position=torch.arange(
|
|
394
|
-
0,
|
|
395
|
-
generate_idx[batch_idx].item(),
|
|
396
|
-
dtype=torch.int32,
|
|
397
|
-
).unsqueeze(0),
|
|
398
|
-
)
|
|
399
336
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
output = self.language_model.decoder(
|
|
404
|
-
inputs_embeds=inputs_embeds,
|
|
405
|
-
cache_position=cache_position,
|
|
406
|
-
)
|
|
407
|
-
logits = output.logits
|
|
408
|
-
return RBLNDecoderOnlyOutput(logits=logits, generate_idx=generate_idx)
|
|
337
|
+
image_features = self.multi_modal_projector(selected_image_feature, out=projector_out_buffer)
|
|
338
|
+
image_features = torch.split(image_features, image_num_patches, dim=0)
|
|
339
|
+
return image_features
|
|
409
340
|
|
|
410
|
-
# Almost copied from : https://github.com/huggingface/transformers/blob/6b550462139655d488d4c663086a63e98713c6b9/src/transformers/models/llava_next/modeling_llava_next.py
|
|
411
341
|
def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
|
|
412
|
-
# Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
|
|
413
|
-
|
|
414
|
-
# Args:
|
|
415
|
-
# image_features (List[torch.Tensor]): List of image feature tensor, each contains all the visual feature of all patches.
|
|
416
|
-
# Its length is num_images, and each of shape is `(num_patches, image_length, embed_dim)`
|
|
417
|
-
# image_sizes (torch.Tensor): Actual image size of each images (H, W).
|
|
418
|
-
# vision_feature_select_strategy (str): The feature selection strategy used to select the vision feature from the vision backbone.
|
|
419
|
-
# image_newline (torch.Tensor): New line embedding vector whose shape is `embed_dim`.
|
|
420
|
-
|
|
421
|
-
# Returns:
|
|
422
|
-
# image_features (torch.Tensor): A torch.Tensor of shape `(all_feat_len, embed_dim)`)
|
|
423
|
-
# feature_lens (List[int]): A token length of each image in image_features
|
|
424
|
-
|
|
425
342
|
new_image_features = []
|
|
426
343
|
feature_lens = []
|
|
427
344
|
for image_idx, image_feature in enumerate(image_features):
|
|
@@ -430,18 +347,22 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
430
347
|
image_feature = image_feature[1:]
|
|
431
348
|
height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
|
|
432
349
|
|
|
433
|
-
if vision_feature_select_strategy == "default":
|
|
434
|
-
expected_num_patches = height * width
|
|
435
|
-
elif vision_feature_select_strategy == "full":
|
|
436
|
-
expected_num_patches = height * width + 1
|
|
437
|
-
if expected_num_patches != base_image_feature.shape[0]:
|
|
438
|
-
raise ValueError("The number of patches is not consistent with the image size.")
|
|
439
|
-
|
|
440
350
|
num_patch_height, num_patch_width = get_anyres_image_grid_shape(
|
|
441
351
|
image_sizes[image_idx],
|
|
442
352
|
self.config.image_grid_pinpoints,
|
|
443
353
|
self.config.vision_config.image_size,
|
|
444
354
|
)
|
|
355
|
+
|
|
356
|
+
if (
|
|
357
|
+
np.prod(image_feature.shape) % (num_patch_height * num_patch_width * height * width) != 0
|
|
358
|
+
and vision_feature_select_strategy == "default"
|
|
359
|
+
):
|
|
360
|
+
logger.warning_once(
|
|
361
|
+
"Image feature shape does not line up with the provided patch size. "
|
|
362
|
+
"You may be using the `default` vision_feature_select_strategy with a"
|
|
363
|
+
" visual encoder that does not have CLS."
|
|
364
|
+
)
|
|
365
|
+
|
|
445
366
|
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
|
446
367
|
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
|
447
368
|
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
|
@@ -468,137 +389,106 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
468
389
|
feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
|
|
469
390
|
return image_features, feature_lens
|
|
470
391
|
|
|
392
|
+
def _preprocess_prefill(
|
|
393
|
+
self,
|
|
394
|
+
input_ids: torch.LongTensor = None,
|
|
395
|
+
pixel_values: torch.FloatTensor = None,
|
|
396
|
+
image_sizes: Optional[torch.LongTensor] = None,
|
|
397
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
398
|
+
vision_feature_layer: Optional[int] = None,
|
|
399
|
+
vision_feature_select_strategy: Optional[str] = None,
|
|
400
|
+
**kwargs,
|
|
401
|
+
):
|
|
402
|
+
vision_feature_layer = (
|
|
403
|
+
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
404
|
+
)
|
|
471
405
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
406
|
+
vision_feature_select_strategy = (
|
|
407
|
+
vision_feature_select_strategy
|
|
408
|
+
if vision_feature_select_strategy is not None
|
|
409
|
+
else self.config.vision_feature_select_strategy
|
|
410
|
+
)
|
|
475
411
|
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
# grid_pinpoints (list): A list containing possible resolutions.
|
|
479
|
-
# Each item in the list should be a tuple or list of the form `(height, width)`.
|
|
480
|
-
# patch_size (int): The size of each image patch.
|
|
412
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
413
|
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
481
414
|
|
|
482
|
-
|
|
483
|
-
|
|
415
|
+
if pixel_values is not None and inputs_embeds is not None:
|
|
416
|
+
raise ValueError(
|
|
417
|
+
"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
|
|
418
|
+
)
|
|
484
419
|
|
|
485
|
-
|
|
486
|
-
|
|
420
|
+
if inputs_embeds is None:
|
|
421
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
487
422
|
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
423
|
+
if pixel_values is not None and pixel_values.size(0) > 0:
|
|
424
|
+
image_features = self.get_image_features(
|
|
425
|
+
pixel_values,
|
|
426
|
+
image_sizes,
|
|
427
|
+
vision_feature_layer=vision_feature_layer,
|
|
428
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
493
429
|
)
|
|
494
|
-
image_size = image_size.tolist()
|
|
495
430
|
|
|
496
|
-
|
|
497
|
-
|
|
431
|
+
# NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
|
|
432
|
+
image_features, feature_lens = self.pack_image_features(
|
|
433
|
+
image_features,
|
|
434
|
+
image_sizes,
|
|
435
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
436
|
+
image_newline=self.image_newline,
|
|
437
|
+
)
|
|
498
438
|
|
|
439
|
+
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
|
440
|
+
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
441
|
+
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
442
|
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
499
443
|
|
|
500
|
-
|
|
501
|
-
def unpad_image(tensor, original_size):
|
|
502
|
-
# Unpads a PyTorch tensor of a padded and resized image.
|
|
444
|
+
return inputs_embeds
|
|
503
445
|
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
446
|
+
def forward(
|
|
447
|
+
self,
|
|
448
|
+
input_ids: torch.LongTensor = None,
|
|
449
|
+
attention_mask: torch.LongTensor = None,
|
|
450
|
+
pixel_values: torch.FloatTensor = None,
|
|
451
|
+
image_sizes: Optional[torch.LongTensor] = None,
|
|
452
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
453
|
+
cache_position: torch.Tensor = None,
|
|
454
|
+
generate_idx: Optional[torch.Tensor] = None,
|
|
455
|
+
return_dict: Optional[bool] = None,
|
|
456
|
+
**kwargs,
|
|
457
|
+
) -> Union[Tuple, RBLNDecoderOnlyOutput]:
|
|
458
|
+
# Prefill
|
|
459
|
+
if cache_position is None:
|
|
460
|
+
inputs_embeds = self._preprocess_prefill(
|
|
461
|
+
input_ids=input_ids, inputs_embeds=inputs_embeds, pixel_values=pixel_values, image_sizes=image_sizes
|
|
462
|
+
)
|
|
463
|
+
logits = []
|
|
464
|
+
inputs = inputs_embeds if inputs_embeds is not None else input_ids
|
|
465
|
+
batch_size = inputs.shape[0]
|
|
507
466
|
|
|
508
|
-
|
|
509
|
-
|
|
467
|
+
for b_idx in range(batch_size):
|
|
468
|
+
cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
|
|
469
|
+
output = self.language_model.prefill_decoder(
|
|
470
|
+
input_ids=inputs[b_idx : b_idx + 1] if inputs_embeds is None else None,
|
|
471
|
+
inputs_embeds=inputs[b_idx : b_idx + 1] if inputs_embeds is not None else None,
|
|
472
|
+
attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
|
|
473
|
+
cache_position=cache_position,
|
|
474
|
+
batch_idx=b_idx,
|
|
475
|
+
)
|
|
476
|
+
logits.append(output.logits)
|
|
510
477
|
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
478
|
+
logits = torch.cat(logits, dim=0)
|
|
479
|
+
|
|
480
|
+
# Decoder
|
|
481
|
+
else:
|
|
482
|
+
logits = self.language_model.decoder(
|
|
483
|
+
input_ids=input_ids,
|
|
484
|
+
inputs_embeds=inputs_embeds,
|
|
485
|
+
cache_position=cache_position,
|
|
486
|
+
).logits
|
|
487
|
+
|
|
488
|
+
if not return_dict:
|
|
489
|
+
return logits, generate_idx
|
|
490
|
+
else:
|
|
491
|
+
return RBLNDecoderOnlyOutput(
|
|
492
|
+
logits=logits,
|
|
493
|
+
generate_idx=generate_idx,
|
|
515
494
|
)
|
|
516
|
-
original_size = original_size.tolist()
|
|
517
|
-
original_height, original_width = original_size
|
|
518
|
-
current_height, current_width = tensor.shape[1:]
|
|
519
|
-
|
|
520
|
-
original_aspect_ratio = original_width / original_height
|
|
521
|
-
current_aspect_ratio = current_width / current_height
|
|
522
|
-
|
|
523
|
-
if original_aspect_ratio > current_aspect_ratio:
|
|
524
|
-
scale_factor = current_width / original_width
|
|
525
|
-
new_height = int(round(original_height * scale_factor, 7))
|
|
526
|
-
padding = (current_height - new_height) // 2
|
|
527
|
-
unpadded_tensor = tensor[:, padding : current_height - padding, :]
|
|
528
|
-
else:
|
|
529
|
-
scale_factor = current_height / original_height
|
|
530
|
-
new_width = int(round(original_width * scale_factor, 7))
|
|
531
|
-
padding = (current_width - new_width) // 2
|
|
532
|
-
unpadded_tensor = tensor[:, :, padding : current_width - padding]
|
|
533
|
-
|
|
534
|
-
return unpadded_tensor
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
# Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
|
|
538
|
-
def select_best_resolution(original_size: tuple, possible_resolutions: list) -> tuple:
|
|
539
|
-
# Selects the best resolution from a list of possible resolutions based on the original size.
|
|
540
|
-
|
|
541
|
-
# This is done by calculating the effective and wasted resolution for each possible resolution.
|
|
542
|
-
|
|
543
|
-
# The best fit resolution is the one that maximizes the effective resolution and minimizes the wasted resolution.
|
|
544
|
-
|
|
545
|
-
# Args:
|
|
546
|
-
# original_size (tuple): The original size of the image in the format (height, width).
|
|
547
|
-
# possible_resolutions (List(tuple)): A list of possible resolutions in the format [(height1, width1), (height2, width2), ...].
|
|
548
|
-
|
|
549
|
-
# Returns:
|
|
550
|
-
# (tuple): The best fit resolution in the format (height, width).
|
|
551
|
-
|
|
552
|
-
original_height, original_width = original_size
|
|
553
|
-
best_fit = None
|
|
554
|
-
max_effective_resolution = 0
|
|
555
|
-
min_wasted_resolution = float("inf")
|
|
556
|
-
|
|
557
|
-
for height, width in possible_resolutions:
|
|
558
|
-
scale = min(width / original_width, height / original_height)
|
|
559
|
-
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
|
560
|
-
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
|
561
|
-
wasted_resolution = (width * height) - effective_resolution
|
|
562
|
-
|
|
563
|
-
if effective_resolution > max_effective_resolution or (
|
|
564
|
-
effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution
|
|
565
|
-
):
|
|
566
|
-
max_effective_resolution = effective_resolution
|
|
567
|
-
min_wasted_resolution = wasted_resolution
|
|
568
|
-
best_fit = (height, width)
|
|
569
|
-
|
|
570
|
-
return best_fit
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
# Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
|
|
574
|
-
def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
|
|
575
|
-
# Calculate the number of patches after the preprocessing for images of any resolution.
|
|
576
|
-
|
|
577
|
-
# Args:
|
|
578
|
-
# image_size (Union[torch.LongTensor, np.ndarray, Tuple[int, int]): The size of the input image in the format (height, width).
|
|
579
|
-
# grid_pinpoints (list): A list containing possible resolutions.
|
|
580
|
-
# Each item in the list should be a tuple or list of the form `(height, width)`.
|
|
581
|
-
# patch_size (int): The size of each image patch.
|
|
582
|
-
|
|
583
|
-
# Returns:
|
|
584
|
-
# (int): the number of patches.
|
|
585
|
-
|
|
586
|
-
if not isinstance(grid_pinpoints, list):
|
|
587
|
-
raise TypeError("grid_pinpoints should be a list of tuples or lists")
|
|
588
|
-
|
|
589
|
-
# ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
|
|
590
|
-
if not isinstance(image_size, (list, tuple)):
|
|
591
|
-
if not isinstance(image_size, (torch.Tensor, np.ndarray)):
|
|
592
|
-
raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
|
|
593
|
-
image_size = image_size.tolist()
|
|
594
|
-
|
|
595
|
-
best_resolution = select_best_resolution(image_size, grid_pinpoints)
|
|
596
|
-
height, width = best_resolution
|
|
597
|
-
num_patches = 0
|
|
598
|
-
# consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
|
|
599
|
-
for i in range(0, height, patch_size):
|
|
600
|
-
for j in range(0, width, patch_size):
|
|
601
|
-
num_patches += 1
|
|
602
|
-
# add the base patch
|
|
603
|
-
num_patches += 1
|
|
604
|
-
return num_patches
|