optimum-rbln 0.8.2a4__py3-none-any.whl → 0.9.3rc0__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.
- optimum/rbln/__init__.py +96 -9
- optimum/rbln/__version__.py +16 -3
- optimum/rbln/cli.py +660 -0
- optimum/rbln/configuration_utils.py +153 -42
- optimum/rbln/diffusers/__init__.py +7 -0
- optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl.py +3 -3
- optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl_cosmos.py +1 -1
- optimum/rbln/diffusers/configurations/models/configuration_controlnet.py +3 -3
- optimum/rbln/diffusers/configurations/models/configuration_prior_transformer.py +4 -4
- optimum/rbln/diffusers/configurations/models/configuration_transformer_cosmos.py +9 -4
- optimum/rbln/diffusers/configurations/models/configuration_transformer_sd3.py +9 -4
- optimum/rbln/diffusers/configurations/models/configuration_unet_2d_condition.py +3 -3
- optimum/rbln/diffusers/configurations/models/configuration_vq_model.py +3 -3
- optimum/rbln/diffusers/configurations/pipelines/configuration_controlnet.py +35 -19
- optimum/rbln/diffusers/configurations/pipelines/configuration_cosmos.py +14 -11
- optimum/rbln/diffusers/configurations/pipelines/configuration_kandinsky2_2.py +30 -20
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion.py +13 -9
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_3.py +17 -13
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_xl.py +17 -10
- optimum/rbln/diffusers/modeling_diffusers.py +30 -14
- optimum/rbln/diffusers/models/__init__.py +3 -13
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl.py +31 -3
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_cosmos.py +28 -3
- optimum/rbln/diffusers/models/autoencoders/vq_model.py +31 -3
- optimum/rbln/diffusers/models/transformers/prior_transformer.py +1 -1
- optimum/rbln/diffusers/models/transformers/transformer_cosmos.py +9 -1
- optimum/rbln/diffusers/models/transformers/transformer_sd3.py +9 -1
- optimum/rbln/diffusers/models/unets/unet_2d_condition.py +6 -3
- optimum/rbln/diffusers/pipelines/__init__.py +11 -5
- optimum/rbln/diffusers/pipelines/auto_pipeline.py +307 -0
- optimum/rbln/diffusers/pipelines/cosmos/configuration_cosmos_guardrail.py +19 -16
- optimum/rbln/diffusers/pipelines/cosmos/cosmos_guardrail.py +14 -18
- optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +31 -1
- optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +31 -1
- optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +1 -6
- optimum/rbln/modeling.py +71 -19
- optimum/rbln/modeling_base.py +99 -21
- optimum/rbln/ops/attn.py +158 -0
- optimum/rbln/ops/flash_attn.py +166 -0
- optimum/rbln/ops/kv_cache_update.py +5 -0
- optimum/rbln/ops/linear.py +7 -0
- optimum/rbln/transformers/__init__.py +92 -0
- optimum/rbln/transformers/configuration_generic.py +9 -7
- optimum/rbln/transformers/modeling_attention_utils.py +252 -0
- optimum/rbln/transformers/modeling_generic.py +51 -9
- optimum/rbln/transformers/modeling_outputs.py +37 -0
- optimum/rbln/transformers/models/__init__.py +91 -30
- optimum/rbln/transformers/models/auto/__init__.py +2 -0
- optimum/rbln/transformers/models/auto/auto_factory.py +92 -17
- optimum/rbln/transformers/models/auto/modeling_auto.py +45 -0
- optimum/rbln/transformers/models/bart/bart_architecture.py +1 -3
- optimum/rbln/transformers/models/bart/configuration_bart.py +2 -0
- optimum/rbln/transformers/models/bert/bert_architecture.py +16 -0
- optimum/rbln/transformers/models/bert/modeling_bert.py +8 -4
- optimum/rbln/transformers/models/blip_2/configuration_blip_2.py +42 -11
- optimum/rbln/transformers/models/blip_2/modeling_blip_2.py +94 -30
- optimum/rbln/transformers/models/clip/configuration_clip.py +10 -7
- optimum/rbln/transformers/models/clip/modeling_clip.py +27 -4
- optimum/rbln/transformers/models/colpali/colpali_architecture.py +3 -6
- optimum/rbln/transformers/models/colpali/configuration_colpali.py +37 -21
- optimum/rbln/transformers/models/colpali/modeling_colpali.py +113 -96
- optimum/rbln/transformers/models/colqwen2/__init__.py +2 -0
- optimum/rbln/transformers/models/colqwen2/colqwen2_architecture.py +233 -0
- optimum/rbln/transformers/models/colqwen2/configuration_colqwen2.py +74 -0
- optimum/rbln/transformers/models/colqwen2/modeling_colqwen2.py +446 -0
- optimum/rbln/transformers/models/decoderonly/__init__.py +3 -2
- optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py +109 -37
- optimum/rbln/transformers/models/decoderonly/configuration_lora.py +411 -0
- optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +318 -309
- optimum/rbln/transformers/models/decoderonly/decoderonly_runtime_utils.py +504 -0
- optimum/rbln/transformers/models/decoderonly/generation_decoderonly.py +111 -0
- optimum/rbln/transformers/models/decoderonly/lora_architecture.py +204 -0
- optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +453 -897
- optimum/rbln/transformers/models/depth_anything/__init__.py +16 -0
- optimum/rbln/transformers/models/depth_anything/configuration_depth_anything.py +24 -0
- optimum/rbln/transformers/models/depth_anything/modeling_depth_anything.py +25 -0
- optimum/rbln/transformers/models/exaone/modeling_exaone.py +42 -4
- optimum/rbln/transformers/models/gemma/__init__.py +2 -2
- optimum/rbln/transformers/models/gemma/configuration_gemma.py +9 -1
- optimum/rbln/transformers/models/gemma/gemma_architecture.py +1 -4
- optimum/rbln/transformers/models/gemma/modeling_gemma.py +22 -1
- optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +49 -13
- optimum/rbln/transformers/models/gemma3/gemma3_architecture.py +12 -2
- optimum/rbln/transformers/models/gemma3/gemma3_runtime_utils.py +245 -0
- optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +201 -349
- optimum/rbln/transformers/models/gpt2/__init__.py +2 -2
- optimum/rbln/transformers/models/gpt2/configuration_gpt2.py +31 -3
- optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +10 -8
- optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +18 -1
- optimum/rbln/transformers/models/grounding_dino/__init__.py +10 -0
- optimum/rbln/transformers/models/grounding_dino/configuration_grounding_dino.py +92 -0
- optimum/rbln/transformers/models/grounding_dino/grounding_dino_architecture.py +599 -0
- optimum/rbln/transformers/models/grounding_dino/modeling_grounding_dino.py +1032 -0
- optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +35 -7
- optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +26 -27
- optimum/rbln/transformers/models/llama/__init__.py +2 -2
- optimum/rbln/transformers/models/llama/configuration_llama.py +9 -1
- optimum/rbln/transformers/models/llama/modeling_llama.py +22 -1
- optimum/rbln/transformers/models/llava/__init__.py +16 -0
- optimum/rbln/transformers/models/llava/configuration_llava.py +72 -0
- optimum/rbln/transformers/models/llava/modeling_llava.py +478 -0
- optimum/rbln/transformers/models/llava_next/configuration_llava_next.py +15 -17
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +235 -375
- optimum/rbln/transformers/models/midm/midm_architecture.py +4 -1
- optimum/rbln/transformers/models/midm/modeling_midm.py +42 -4
- optimum/rbln/transformers/models/mistral/__init__.py +2 -2
- optimum/rbln/transformers/models/mistral/configuration_mistral.py +9 -1
- optimum/rbln/transformers/models/mistral/mistral_architecture.py +1 -1
- optimum/rbln/transformers/models/mistral/modeling_mistral.py +26 -3
- optimum/rbln/transformers/models/opt/__init__.py +2 -2
- optimum/rbln/transformers/models/opt/configuration_opt.py +8 -1
- optimum/rbln/transformers/models/opt/modeling_opt.py +28 -16
- optimum/rbln/transformers/models/opt/opt_architecture.py +4 -4
- optimum/rbln/transformers/models/pegasus/__init__.py +17 -0
- optimum/rbln/transformers/models/pegasus/configuration_pegasus.py +38 -0
- optimum/rbln/transformers/models/pegasus/modeling_pegasus.py +71 -0
- optimum/rbln/transformers/models/pegasus/pegasus_architecture.py +161 -0
- optimum/rbln/transformers/models/phi/__init__.py +2 -2
- optimum/rbln/transformers/models/phi/configuration_phi.py +9 -1
- optimum/rbln/transformers/models/phi/modeling_phi.py +10 -1
- optimum/rbln/transformers/models/phi/phi_architecture.py +11 -7
- optimum/rbln/transformers/models/pixtral/__init__.py +16 -0
- optimum/rbln/transformers/models/pixtral/configuration_pixtral.py +43 -0
- optimum/rbln/transformers/models/pixtral/modeling_pixtral.py +310 -0
- optimum/rbln/transformers/models/pixtral/pixtral_architecture.py +73 -0
- optimum/rbln/transformers/models/qwen2/__init__.py +2 -2
- optimum/rbln/transformers/models/qwen2/configuration_qwen2.py +9 -1
- optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +27 -1
- optimum/rbln/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py +21 -6
- optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +15 -21
- optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py +28 -7
- optimum/rbln/transformers/models/qwen2_vl/__init__.py +19 -0
- optimum/rbln/transformers/models/qwen2_vl/configuration_qwen2_vl.py +88 -0
- optimum/rbln/transformers/models/qwen2_vl/modeling_qwen2_vl.py +514 -0
- optimum/rbln/transformers/models/qwen2_vl/qwen2_vl_architecture.py +165 -0
- optimum/rbln/transformers/models/qwen3/configuration_qwen3.py +2 -2
- optimum/rbln/transformers/models/qwen3/modeling_qwen3.py +86 -330
- optimum/rbln/transformers/models/qwen3/qwen3_architecture.py +1 -245
- optimum/rbln/transformers/models/seq2seq/configuration_seq2seq.py +20 -13
- optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +24 -3
- optimum/rbln/transformers/models/seq2seq/seq2seq_architecture.py +2 -2
- optimum/rbln/transformers/models/siglip/__init__.py +2 -6
- optimum/rbln/transformers/models/siglip/configuration_siglip.py +1 -1
- optimum/rbln/transformers/models/siglip/modeling_siglip.py +5 -16
- optimum/rbln/transformers/models/swin/__init__.py +16 -0
- optimum/rbln/transformers/models/swin/configuration_swin.py +42 -0
- optimum/rbln/transformers/models/swin/modeling_swin.py +341 -0
- optimum/rbln/transformers/models/t5/configuration_t5.py +2 -0
- optimum/rbln/transformers/models/t5/t5_architecture.py +8 -1
- optimum/rbln/transformers/models/time_series_transformer/configuration_time_series_transformer.py +3 -3
- optimum/rbln/transformers/models/time_series_transformer/modeling_time_series_transformer.py +4 -14
- optimum/rbln/transformers/models/time_series_transformer/time_series_transformers_architecture.py +7 -1
- optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +1 -0
- optimum/rbln/transformers/models/whisper/configuration_whisper.py +12 -13
- optimum/rbln/transformers/models/whisper/generation_whisper.py +28 -6
- optimum/rbln/transformers/models/whisper/modeling_whisper.py +28 -3
- optimum/rbln/transformers/models/xlm_roberta/__init__.py +2 -8
- optimum/rbln/transformers/utils/rbln_quantization.py +391 -75
- optimum/rbln/transformers/utils/rbln_runtime_wrapper.py +79 -0
- optimum/rbln/utils/depreacate_utils.py +16 -0
- optimum/rbln/utils/runtime_utils.py +28 -18
- optimum/rbln/utils/submodule.py +31 -9
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/METADATA +8 -7
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/RECORD +167 -125
- optimum_rbln-0.9.3rc0.dist-info/entry_points.txt +2 -0
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/WHEEL +0 -0
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/licenses/LICENSE +0 -0
|
@@ -12,64 +12,57 @@
|
|
|
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
|
-
from transformers import
|
|
22
|
-
AutoModelForVision2Seq,
|
|
23
|
-
LlavaNextForConditionalGeneration,
|
|
24
|
-
PretrainedConfig,
|
|
25
|
-
PreTrainedModel,
|
|
26
|
-
)
|
|
22
|
+
from transformers import AutoModelForVision2Seq, LlavaNextForConditionalGeneration, PretrainedConfig, PreTrainedModel
|
|
27
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
|
+
)
|
|
28
30
|
|
|
29
31
|
from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
|
|
30
32
|
from ....modeling import RBLNModel
|
|
31
33
|
from ....utils.logging import get_logger
|
|
34
|
+
from ...utils.rbln_runtime_wrapper import LoopProcessor
|
|
35
|
+
from ..decoderonly.generation_decoderonly import RBLNDecoderOnlyGenerationMixin
|
|
32
36
|
from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyOutput
|
|
33
37
|
|
|
34
38
|
|
|
35
39
|
logger = get_logger(__name__)
|
|
36
40
|
|
|
37
41
|
if TYPE_CHECKING:
|
|
38
|
-
from transformers import
|
|
39
|
-
AutoFeatureExtractor,
|
|
40
|
-
AutoProcessor,
|
|
41
|
-
AutoTokenizer,
|
|
42
|
-
PretrainedConfig,
|
|
43
|
-
)
|
|
44
|
-
|
|
42
|
+
from transformers import AutoFeatureExtractor, AutoProcessor, AutoTokenizer, PretrainedConfig
|
|
45
43
|
|
|
46
|
-
class LoopVisionTower:
|
|
47
|
-
def __init__(self, vision_tower: RBLNModel) -> None:
|
|
48
|
-
self.vision_tower = vision_tower
|
|
49
44
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
pixel_values = args[0]
|
|
45
|
+
class LoopVisionTower(LoopProcessor):
|
|
46
|
+
def __init__(self, vision_tower: "RBLNModel"):
|
|
47
|
+
super().__init__(model=vision_tower.model[0])
|
|
54
48
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
for i in range(batch_size):
|
|
58
|
-
outputs.append(self.vision_tower.model[0](pixel_values[i : i + 1]))
|
|
49
|
+
def _get_batch_size(self, pixel_values, **kwargs):
|
|
50
|
+
return pixel_values.shape[0]
|
|
59
51
|
|
|
60
|
-
|
|
61
|
-
|
|
52
|
+
def _prepare_inputs_for_iteration(self, index, common_inputs, pixel_values, **kwargs):
|
|
53
|
+
pixel_values_item = pixel_values[index : index + 1]
|
|
54
|
+
out_buffer = [tensor[index : index + 1] for tensor in kwargs["out"]]
|
|
55
|
+
return ([pixel_values_item], {"out": out_buffer})
|
|
62
56
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
57
|
+
def _process_outputs(self, outputs: list, **kwargs) -> "BaseModelOutputWithPooling":
|
|
58
|
+
output = kwargs["out"]
|
|
59
|
+
last_hidden_states = output[0]
|
|
60
|
+
pooler_output = output[1]
|
|
66
61
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
for i in range(len(hidden_states[0]))
|
|
72
|
-
) # hidden x (batch,)
|
|
62
|
+
if not output[2:]:
|
|
63
|
+
hidden_states = None
|
|
64
|
+
else:
|
|
65
|
+
hidden_states = tuple(output[2:])
|
|
73
66
|
|
|
74
67
|
return BaseModelOutputWithPooling(
|
|
75
68
|
last_hidden_state=last_hidden_states,
|
|
@@ -77,38 +70,25 @@ class LoopVisionTower:
|
|
|
77
70
|
hidden_states=hidden_states,
|
|
78
71
|
)
|
|
79
72
|
|
|
80
|
-
def __call__(self, *args: Any, **kwds: Any) -> Any:
|
|
81
|
-
return self.forward(*args, **kwds)
|
|
82
|
-
|
|
83
|
-
def __repr__(self) -> str:
|
|
84
|
-
return repr(self.vision_tower)
|
|
85
73
|
|
|
74
|
+
class LoopProjector(LoopProcessor):
|
|
75
|
+
def __init__(self, multi_modal_projector: "RBLNModel"):
|
|
76
|
+
super().__init__(model=multi_modal_projector)
|
|
86
77
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
self.multi_modal_projector = multi_modal_projector
|
|
78
|
+
def _get_batch_size(self, image_feature, **kwargs):
|
|
79
|
+
return image_feature.shape[0]
|
|
90
80
|
|
|
91
|
-
def
|
|
92
|
-
|
|
93
|
-
|
|
81
|
+
def _prepare_inputs_for_iteration(self, index, common_inputs, image_feature, **kwargs):
|
|
82
|
+
image_feature_item = image_feature[index : index + 1]
|
|
83
|
+
out_buffer = [tensor[index : index + 1] for tensor in kwargs["out"]]
|
|
84
|
+
return ([image_feature_item], {"out": out_buffer})
|
|
94
85
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
outputs.append(self.multi_modal_projector(image_feature[i : i + 1]))
|
|
86
|
+
def _process_outputs(self, outputs: list, **kwargs):
|
|
87
|
+
output = kwargs["out"]
|
|
88
|
+
return output[0]
|
|
99
89
|
|
|
100
|
-
# FIXME:: This can be optimized using out= API of rbln runtime.
|
|
101
|
-
outputs = torch.cat(outputs, dim=0)
|
|
102
|
-
return outputs
|
|
103
90
|
|
|
104
|
-
|
|
105
|
-
return self.forward(*args, **kwds)
|
|
106
|
-
|
|
107
|
-
def __repr__(self) -> str:
|
|
108
|
-
return repr(self.multi_modal_projector)
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
91
|
+
class RBLNLlavaNextForConditionalGeneration(RBLNModel, RBLNDecoderOnlyGenerationMixin):
|
|
112
92
|
"""
|
|
113
93
|
RBLNLlavaNextForConditionalGeneration is a multi-modal model that combines vision and language processing capabilities,
|
|
114
94
|
optimized for RBLN NPUs. It is designed for conditional generation tasks that involve both image and text inputs.
|
|
@@ -158,6 +138,23 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
158
138
|
def can_generate(self):
|
|
159
139
|
return True
|
|
160
140
|
|
|
141
|
+
@classmethod
|
|
142
|
+
def get_pytorch_model(cls, *args, **kwargs):
|
|
143
|
+
model = super().get_pytorch_model(*args, **kwargs)
|
|
144
|
+
|
|
145
|
+
with no_init_weights():
|
|
146
|
+
model_cls_name = model.model.language_model.__class__.__name__
|
|
147
|
+
causal_model_cls_name = model_cls_name.replace("Model", "ForCausalLM")
|
|
148
|
+
causal_model_cls = getattr(importlib.import_module("transformers"), causal_model_cls_name)
|
|
149
|
+
new_language_model = causal_model_cls(model.model.language_model.config)
|
|
150
|
+
|
|
151
|
+
new_language_model.lm_head = model.lm_head
|
|
152
|
+
new_language_model.model = model.model.language_model
|
|
153
|
+
model.model.language_model = new_language_model
|
|
154
|
+
model.lm_head = None
|
|
155
|
+
del model.lm_head
|
|
156
|
+
return model
|
|
157
|
+
|
|
161
158
|
@classmethod
|
|
162
159
|
def save_torch_artifacts(
|
|
163
160
|
cls,
|
|
@@ -169,7 +166,7 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
169
166
|
# If you are unavoidably running on a CPU rather than an RBLN device,
|
|
170
167
|
# store the torch tensor, weight, etc. in this function.
|
|
171
168
|
save_dict = {}
|
|
172
|
-
save_dict["image_newline"] = model.image_newline
|
|
169
|
+
save_dict["image_newline"] = model.model.image_newline
|
|
173
170
|
torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
|
|
174
171
|
|
|
175
172
|
def __post_init__(self, **kwargs):
|
|
@@ -216,7 +213,11 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
216
213
|
selected_image_feature_dim = num_positions
|
|
217
214
|
|
|
218
215
|
input_info = [
|
|
219
|
-
(
|
|
216
|
+
(
|
|
217
|
+
"image_features",
|
|
218
|
+
[rbln_config.vision_tower.batch_size, selected_image_feature_dim, feature_size],
|
|
219
|
+
"float32",
|
|
220
|
+
)
|
|
220
221
|
]
|
|
221
222
|
rbln_compile_config = RBLNCompileConfig(input_info=input_info)
|
|
222
223
|
rbln_config.set_compile_cfgs([rbln_compile_config])
|
|
@@ -227,89 +228,62 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
227
228
|
input_ids,
|
|
228
229
|
inputs_embeds=None,
|
|
229
230
|
pixel_values=None,
|
|
230
|
-
image_sizes=None,
|
|
231
231
|
attention_mask=None,
|
|
232
|
+
cache_position=None,
|
|
233
|
+
image_sizes=None,
|
|
232
234
|
generate_idx=None,
|
|
233
235
|
**kwargs,
|
|
234
236
|
):
|
|
235
|
-
# Prepare HF generation
|
|
236
237
|
is_prefill_phase = generate_idx is None
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
model_inputs = self.language_model.prepare_inputs_for_generation(
|
|
240
|
-
input_ids=input_ids,
|
|
241
|
-
inputs_embeds=inputs_embeds,
|
|
242
|
-
generate_idx=generate_idx, # Not affect
|
|
243
|
-
attention_mask=attention_mask,
|
|
244
|
-
**kwargs,
|
|
245
|
-
)
|
|
238
|
+
model_inputs = {}
|
|
246
239
|
|
|
247
240
|
if is_prefill_phase:
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
241
|
+
generate_idx = attention_mask.sum(dim=-1, keepdim=True).int()
|
|
242
|
+
cache_position = None
|
|
243
|
+
pixel_values = pixel_values
|
|
244
|
+
model_inputs.update({"image_sizes": image_sizes})
|
|
245
|
+
else:
|
|
246
|
+
if inputs_embeds is not None:
|
|
247
|
+
raise NotImplementedError("Specifying inputs_embeds in decoder phase is not supported.")
|
|
255
248
|
|
|
256
|
-
|
|
249
|
+
pixel_values = None
|
|
250
|
+
input_ids = input_ids[:, -1:]
|
|
251
|
+
cache_position = generate_idx
|
|
252
|
+
generate_idx = generate_idx + 1
|
|
253
|
+
model_inputs.update({"input_ids": input_ids})
|
|
254
|
+
|
|
255
|
+
if inputs_embeds is not None:
|
|
256
|
+
if self.rbln_config.use_inputs_embeds:
|
|
257
|
+
model_inputs.update({"inputs_embeds": inputs_embeds})
|
|
258
|
+
else:
|
|
259
|
+
raise ValueError(
|
|
260
|
+
"The specifying inputs_embeds is only supported when using a compiled RBLN model with 'rbln_use_inputs_embeds' set to True."
|
|
261
|
+
)
|
|
262
|
+
else:
|
|
263
|
+
model_inputs.update({"input_ids": input_ids})
|
|
264
|
+
|
|
265
|
+
model_inputs.update(
|
|
266
|
+
{
|
|
267
|
+
"attention_mask": attention_mask,
|
|
268
|
+
"pixel_values": pixel_values,
|
|
269
|
+
"cache_position": cache_position,
|
|
270
|
+
"generate_idx": generate_idx,
|
|
271
|
+
}
|
|
272
|
+
)
|
|
257
273
|
return model_inputs
|
|
258
274
|
|
|
259
|
-
def _update_model_kwargs_for_generation(
|
|
260
|
-
self,
|
|
261
|
-
outputs: RBLNDecoderOnlyOutput,
|
|
262
|
-
model_kwargs: Dict[str, Any],
|
|
263
|
-
**kwargs,
|
|
264
|
-
) -> Dict[str, Any]:
|
|
275
|
+
def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
|
|
265
276
|
# update generate_idx
|
|
266
277
|
model_kwargs["generate_idx"] = outputs.generate_idx
|
|
267
|
-
|
|
268
278
|
return model_kwargs
|
|
269
279
|
|
|
270
|
-
def
|
|
280
|
+
def get_image_features(
|
|
271
281
|
self,
|
|
272
|
-
input_ids: torch.LongTensor,
|
|
273
|
-
) -> torch.Tensor:
|
|
274
|
-
for_inputs_embeds_ids = input_ids.clone()
|
|
275
|
-
for_inputs_embeds_ids[(input_ids == self.config.image_token_index)] = 0
|
|
276
|
-
inputs_embeds = self.get_input_embeddings()(for_inputs_embeds_ids)
|
|
277
|
-
|
|
278
|
-
return inputs_embeds
|
|
279
|
-
|
|
280
|
-
def image_embedding(
|
|
281
|
-
self,
|
|
282
|
-
image_sizes: torch.Tensor,
|
|
283
282
|
pixel_values: torch.FloatTensor,
|
|
284
|
-
|
|
283
|
+
image_sizes: torch.Tensor,
|
|
284
|
+
vision_feature_layer: Union[int, List[int]],
|
|
285
285
|
vision_feature_select_strategy: str,
|
|
286
286
|
):
|
|
287
|
-
vision_feature_layer = (
|
|
288
|
-
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
289
|
-
)
|
|
290
|
-
vision_feature_select_strategy = (
|
|
291
|
-
vision_feature_select_strategy
|
|
292
|
-
if vision_feature_select_strategy is not None
|
|
293
|
-
else self.config.vision_feature_select_strategy
|
|
294
|
-
)
|
|
295
|
-
|
|
296
|
-
"""
|
|
297
|
-
Obtains image last hidden states from the vision tower and apply multimodal projection.
|
|
298
|
-
|
|
299
|
-
Args:
|
|
300
|
-
pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
|
|
301
|
-
The tensors corresponding to the input images.
|
|
302
|
-
image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
|
|
303
|
-
Actual image size of each images (H, W).
|
|
304
|
-
vision_feature_layer (`int`):
|
|
305
|
-
The index of the layer to select the vision feature.
|
|
306
|
-
vision_feature_select_strategy (`str`):
|
|
307
|
-
The feature selection strategy used to select the vision feature from the vision backbone.
|
|
308
|
-
Can be one of `"default"` or `"full"`
|
|
309
|
-
Returns:
|
|
310
|
-
image_features (List[`torch.Tensor`]): List of image feature tensor, each contains all the visual feature of all patches
|
|
311
|
-
and are of shape `(num_patches, image_length, embed_dim)`).
|
|
312
|
-
"""
|
|
313
287
|
# ! infer image_num_patches from image_sizes
|
|
314
288
|
image_num_patches = [
|
|
315
289
|
image_size_to_num_patches(
|
|
@@ -319,6 +293,26 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
319
293
|
)
|
|
320
294
|
for imsize in image_sizes
|
|
321
295
|
]
|
|
296
|
+
|
|
297
|
+
# prepare out buffer for pre-allocation
|
|
298
|
+
vision_out_size = [
|
|
299
|
+
pixel_values.shape[0] * pixel_values.shape[1],
|
|
300
|
+
(self.config.vision_config.image_size // self.config.vision_config.patch_size) ** 2 + 1,
|
|
301
|
+
self.config.vision_config.hidden_size,
|
|
302
|
+
]
|
|
303
|
+
pooler_out_size = [pixel_values.shape[0] * pixel_values.shape[1], self.config.vision_config.hidden_size]
|
|
304
|
+
vision_out_buffer = []
|
|
305
|
+
for i in range(self.config.vision_config.num_hidden_layers + 2):
|
|
306
|
+
vision_out_buffer.append(torch.empty(size=vision_out_size, dtype=torch.float32, device="cpu"))
|
|
307
|
+
vision_out_buffer.insert(1, torch.empty(size=pooler_out_size, dtype=torch.float32, device="cpu"))
|
|
308
|
+
|
|
309
|
+
projector_out_size = [
|
|
310
|
+
pixel_values.shape[0] * pixel_values.shape[1],
|
|
311
|
+
(self.config.vision_config.image_size // self.config.vision_config.patch_size) ** 2,
|
|
312
|
+
self.config.text_config.hidden_size,
|
|
313
|
+
]
|
|
314
|
+
projector_out_buffer = [torch.empty(size=projector_out_size, dtype=torch.float32, device="cpu")]
|
|
315
|
+
|
|
322
316
|
if pixel_values.dim() == 5:
|
|
323
317
|
# stacked if input is (batch_size, num_patches, num_channels, height, width)
|
|
324
318
|
_pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
|
|
@@ -327,118 +321,25 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
327
321
|
# otherwise has to be stacked from list of (num_patches, num_channels, height, width)
|
|
328
322
|
raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
|
|
329
323
|
|
|
330
|
-
image_features = self.vision_tower(pixel_values, output_hidden_states=True)
|
|
331
|
-
|
|
324
|
+
image_features = self.vision_tower(pixel_values, output_hidden_states=True, out=vision_out_buffer)
|
|
325
|
+
# If we have one vision feature layer, return the corresponding hidden states,
|
|
326
|
+
# otherwise, select the hidden states of each feature layer and concatenate them
|
|
327
|
+
if isinstance(vision_feature_layer, int):
|
|
328
|
+
selected_image_feature = image_features.hidden_states[vision_feature_layer]
|
|
329
|
+
else:
|
|
330
|
+
hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
|
|
331
|
+
selected_image_feature = torch.cat(hs_pool, dim=-1)
|
|
332
|
+
|
|
332
333
|
if vision_feature_select_strategy == "default":
|
|
333
334
|
selected_image_feature = selected_image_feature[:, 1:]
|
|
334
335
|
elif vision_feature_select_strategy == "full":
|
|
335
336
|
selected_image_feature = selected_image_feature
|
|
336
|
-
image_features = self.multi_modal_projector(selected_image_feature)
|
|
337
|
-
image_features = torch.split(image_features, image_num_patches, dim=0)
|
|
338
|
-
|
|
339
|
-
# NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
|
|
340
|
-
image_features, feature_lens = self.pack_image_features(
|
|
341
|
-
image_features,
|
|
342
|
-
image_sizes,
|
|
343
|
-
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
344
|
-
image_newline=self.image_newline,
|
|
345
|
-
)
|
|
346
|
-
|
|
347
|
-
return image_features, feature_lens
|
|
348
|
-
|
|
349
|
-
def forward(
|
|
350
|
-
self,
|
|
351
|
-
input_ids: torch.LongTensor = None,
|
|
352
|
-
attention_mask: torch.LongTensor = None,
|
|
353
|
-
pixel_values: torch.FloatTensor = None,
|
|
354
|
-
image_sizes: Optional[torch.LongTensor] = None,
|
|
355
|
-
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
356
|
-
vision_feature_layer: Optional[int] = None,
|
|
357
|
-
vision_feature_select_strategy: Optional[str] = None,
|
|
358
|
-
cache_position: torch.Tensor = None,
|
|
359
|
-
generate_idx: Optional[torch.Tensor] = None,
|
|
360
|
-
batch_idx: Optional[int] = None,
|
|
361
|
-
**kwargs,
|
|
362
|
-
) -> Union[Tuple, RBLNDecoderOnlyOutput]:
|
|
363
|
-
vision_feature_layer = (
|
|
364
|
-
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
365
|
-
)
|
|
366
|
-
vision_feature_select_strategy = (
|
|
367
|
-
vision_feature_select_strategy
|
|
368
|
-
if vision_feature_select_strategy is not None
|
|
369
|
-
else self.config.vision_feature_select_strategy
|
|
370
|
-
)
|
|
371
|
-
|
|
372
|
-
if inputs_embeds is not None:
|
|
373
|
-
raise NotImplementedError("Specifying inputs_embeds is not supported.")
|
|
374
|
-
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
375
|
-
|
|
376
|
-
if pixel_values is not None and pixel_values.size(0) > 0:
|
|
377
|
-
image_features, _ = self.image_embedding(
|
|
378
|
-
pixel_values=pixel_values,
|
|
379
|
-
image_sizes=image_sizes,
|
|
380
|
-
vision_feature_layer=vision_feature_layer,
|
|
381
|
-
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
382
|
-
)
|
|
383
|
-
|
|
384
|
-
n_image_tokens = (input_ids == self.config.image_token_index).sum().item()
|
|
385
|
-
n_image_features = image_features.shape[0]
|
|
386
|
-
if n_image_tokens != n_image_features:
|
|
387
|
-
raise ValueError(
|
|
388
|
-
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
|
389
|
-
)
|
|
390
|
-
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
|
391
|
-
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
392
|
-
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
393
|
-
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
394
337
|
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
logits = []
|
|
399
|
-
batch_size = input_ids.shape[0]
|
|
400
|
-
inputs_embeds = [inputs_embeds[i : i + 1, attention_mask[i].bool()] for i in range(batch_size)]
|
|
401
|
-
for batch_idx in range(batch_size):
|
|
402
|
-
generate_idx[batch_idx] = inputs_embeds[batch_idx].shape[-2]
|
|
403
|
-
output = self.language_model.prefill_decoder(
|
|
404
|
-
inputs_embeds=inputs_embeds[batch_idx],
|
|
405
|
-
batch_idx=batch_idx,
|
|
406
|
-
cache_position=torch.arange(
|
|
407
|
-
0,
|
|
408
|
-
generate_idx[batch_idx].item(),
|
|
409
|
-
dtype=torch.int32,
|
|
410
|
-
).unsqueeze(0),
|
|
411
|
-
)
|
|
412
|
-
|
|
413
|
-
logits.append(output.logits)
|
|
414
|
-
logits = torch.cat(logits, dim=0)
|
|
415
|
-
else:
|
|
416
|
-
output = self.language_model.decoder(
|
|
417
|
-
inputs_embeds=inputs_embeds,
|
|
418
|
-
cache_position=cache_position,
|
|
419
|
-
)
|
|
420
|
-
logits = output.logits
|
|
421
|
-
return RBLNDecoderOnlyOutput(logits=logits, generate_idx=generate_idx)
|
|
338
|
+
image_features = self.multi_modal_projector(selected_image_feature, out=projector_out_buffer)
|
|
339
|
+
image_features = torch.split(image_features, image_num_patches, dim=0)
|
|
340
|
+
return image_features
|
|
422
341
|
|
|
423
|
-
# Almost copied from : https://github.com/huggingface/transformers/blob/6b550462139655d488d4c663086a63e98713c6b9/src/transformers/models/llava_next/modeling_llava_next.py
|
|
424
342
|
def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
|
|
425
|
-
"""
|
|
426
|
-
Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
|
|
427
|
-
|
|
428
|
-
Args:
|
|
429
|
-
image_features (`List[torch.Tensor]` of length num_images, each of shape `(num_patches, image_length, embed_dim)`)
|
|
430
|
-
List of image feature tensor, each contains all the visual feature of all patches.
|
|
431
|
-
image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
|
|
432
|
-
Actual image size of each images (H, W).
|
|
433
|
-
vision_feature_select_strategy (`str`)
|
|
434
|
-
The feature selection strategy used to select the vision feature from the vision backbone.
|
|
435
|
-
image_newline (`torch.Tensor` of shape `(embed_dim)`)
|
|
436
|
-
New line embedding vector.
|
|
437
|
-
Returns:
|
|
438
|
-
image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
|
|
439
|
-
feature_lens (`List[int]`)
|
|
440
|
-
token length of each image in image_features
|
|
441
|
-
"""
|
|
442
343
|
new_image_features = []
|
|
443
344
|
feature_lens = []
|
|
444
345
|
for image_idx, image_feature in enumerate(image_features):
|
|
@@ -447,18 +348,22 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
447
348
|
image_feature = image_feature[1:]
|
|
448
349
|
height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
|
|
449
350
|
|
|
450
|
-
if vision_feature_select_strategy == "default":
|
|
451
|
-
expected_num_patches = height * width
|
|
452
|
-
elif vision_feature_select_strategy == "full":
|
|
453
|
-
expected_num_patches = height * width + 1
|
|
454
|
-
if expected_num_patches != base_image_feature.shape[0]:
|
|
455
|
-
raise ValueError("The number of patches is not consistent with the image size.")
|
|
456
|
-
|
|
457
351
|
num_patch_height, num_patch_width = get_anyres_image_grid_shape(
|
|
458
352
|
image_sizes[image_idx],
|
|
459
353
|
self.config.image_grid_pinpoints,
|
|
460
354
|
self.config.vision_config.image_size,
|
|
461
355
|
)
|
|
356
|
+
|
|
357
|
+
if (
|
|
358
|
+
np.prod(image_feature.shape) % (num_patch_height * num_patch_width * height * width) != 0
|
|
359
|
+
and vision_feature_select_strategy == "default"
|
|
360
|
+
):
|
|
361
|
+
logger.warning_once(
|
|
362
|
+
"Image feature shape does not line up with the provided patch size. "
|
|
363
|
+
"You may be using the `default` vision_feature_select_strategy with a"
|
|
364
|
+
" visual encoder that does not have CLS."
|
|
365
|
+
)
|
|
366
|
+
|
|
462
367
|
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
|
463
368
|
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
|
464
369
|
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
|
@@ -485,151 +390,106 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
485
390
|
feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
|
|
486
391
|
return image_features, feature_lens
|
|
487
392
|
|
|
393
|
+
def _preprocess_prefill(
|
|
394
|
+
self,
|
|
395
|
+
input_ids: torch.LongTensor = None,
|
|
396
|
+
pixel_values: torch.FloatTensor = None,
|
|
397
|
+
image_sizes: Optional[torch.LongTensor] = None,
|
|
398
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
399
|
+
vision_feature_layer: Optional[int] = None,
|
|
400
|
+
vision_feature_select_strategy: Optional[str] = None,
|
|
401
|
+
**kwargs,
|
|
402
|
+
):
|
|
403
|
+
vision_feature_layer = (
|
|
404
|
+
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
405
|
+
)
|
|
488
406
|
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
Args:
|
|
495
|
-
image_size (`tuple`):
|
|
496
|
-
The size of the input image in the format (width, height).
|
|
497
|
-
grid_pinpoints (`List`):
|
|
498
|
-
A list containing possible resolutions. Each item in the list should be a tuple or list
|
|
499
|
-
of the form `(height, width)`.
|
|
500
|
-
patch_size (`int`):
|
|
501
|
-
The size of each image patch.
|
|
502
|
-
|
|
503
|
-
Returns:
|
|
504
|
-
tuple: The shape of the image patch grid in the format (width, height).
|
|
505
|
-
"""
|
|
506
|
-
if not isinstance(grid_pinpoints, list):
|
|
507
|
-
raise TypeError("grid_pinpoints should be a list of tuples or lists")
|
|
508
|
-
|
|
509
|
-
# ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
|
|
510
|
-
if not isinstance(image_size, (list, tuple)):
|
|
511
|
-
if not isinstance(image_size, (torch.Tensor, np.ndarray)):
|
|
512
|
-
raise TypeError(
|
|
513
|
-
f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
|
|
514
|
-
)
|
|
515
|
-
image_size = image_size.tolist()
|
|
516
|
-
|
|
517
|
-
height, width = select_best_resolution(image_size, grid_pinpoints)
|
|
518
|
-
return height // patch_size, width // patch_size
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
# Almost copied from : https://github.com/huggingface/transformers/blob/1feebb5b4150882deabddd190a541f336f3be817/src/transformers/models/llava_next/modeling_llava_next.py#L115C1-L152C1
|
|
522
|
-
def unpad_image(tensor, original_size):
|
|
523
|
-
"""
|
|
524
|
-
Unpads a PyTorch tensor of a padded and resized image.
|
|
407
|
+
vision_feature_select_strategy = (
|
|
408
|
+
vision_feature_select_strategy
|
|
409
|
+
if vision_feature_select_strategy is not None
|
|
410
|
+
else self.config.vision_feature_select_strategy
|
|
411
|
+
)
|
|
525
412
|
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
The image tensor, assumed to be of shape (num_channels, height, width).
|
|
529
|
-
original_size (`tuple`):
|
|
530
|
-
The original size of the image (height, width).
|
|
413
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
414
|
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
531
415
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
if not isinstance(original_size, (list, tuple)):
|
|
536
|
-
if not isinstance(original_size, (torch.Tensor, np.ndarray)):
|
|
537
|
-
raise TypeError(
|
|
538
|
-
f"image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor"
|
|
416
|
+
if pixel_values is not None and inputs_embeds is not None:
|
|
417
|
+
raise ValueError(
|
|
418
|
+
"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
|
|
539
419
|
)
|
|
540
|
-
original_size = original_size.tolist()
|
|
541
|
-
original_height, original_width = original_size
|
|
542
|
-
current_height, current_width = tensor.shape[1:]
|
|
543
|
-
|
|
544
|
-
original_aspect_ratio = original_width / original_height
|
|
545
|
-
current_aspect_ratio = current_width / current_height
|
|
546
420
|
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
new_height = int(round(original_height * scale_factor, 7))
|
|
550
|
-
padding = (current_height - new_height) // 2
|
|
551
|
-
unpadded_tensor = tensor[:, padding : current_height - padding, :]
|
|
552
|
-
else:
|
|
553
|
-
scale_factor = current_height / original_height
|
|
554
|
-
new_width = int(round(original_width * scale_factor, 7))
|
|
555
|
-
padding = (current_width - new_width) // 2
|
|
556
|
-
unpadded_tensor = tensor[:, :, padding : current_width - padding]
|
|
421
|
+
if inputs_embeds is None:
|
|
422
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
557
423
|
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
This is done by calculating the effective and wasted resolution for each possible resolution.
|
|
424
|
+
if pixel_values is not None and pixel_values.size(0) > 0:
|
|
425
|
+
image_features = self.get_image_features(
|
|
426
|
+
pixel_values,
|
|
427
|
+
image_sizes,
|
|
428
|
+
vision_feature_layer=vision_feature_layer,
|
|
429
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
430
|
+
)
|
|
567
431
|
|
|
568
|
-
|
|
432
|
+
# NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
|
|
433
|
+
image_features, feature_lens = self.pack_image_features(
|
|
434
|
+
image_features,
|
|
435
|
+
image_sizes,
|
|
436
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
437
|
+
image_newline=self.image_newline,
|
|
438
|
+
)
|
|
569
439
|
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
A list of possible resolutions in the format [(height1, width1), (height2, width2), ...].
|
|
440
|
+
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
|
441
|
+
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
442
|
+
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
443
|
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
575
444
|
|
|
576
|
-
|
|
577
|
-
tuple: The best fit resolution in the format (height, width).
|
|
578
|
-
"""
|
|
579
|
-
original_height, original_width = original_size
|
|
580
|
-
best_fit = None
|
|
581
|
-
max_effective_resolution = 0
|
|
582
|
-
min_wasted_resolution = float("inf")
|
|
445
|
+
return inputs_embeds
|
|
583
446
|
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
447
|
+
def forward(
|
|
448
|
+
self,
|
|
449
|
+
input_ids: torch.LongTensor = None,
|
|
450
|
+
attention_mask: torch.LongTensor = None,
|
|
451
|
+
pixel_values: torch.FloatTensor = None,
|
|
452
|
+
image_sizes: Optional[torch.LongTensor] = None,
|
|
453
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
454
|
+
cache_position: torch.Tensor = None,
|
|
455
|
+
generate_idx: Optional[torch.Tensor] = None,
|
|
456
|
+
return_dict: Optional[bool] = None,
|
|
457
|
+
**kwargs,
|
|
458
|
+
) -> Union[Tuple, RBLNDecoderOnlyOutput]:
|
|
459
|
+
# Prefill
|
|
460
|
+
if cache_position is None:
|
|
461
|
+
inputs_embeds = self._preprocess_prefill(
|
|
462
|
+
input_ids=input_ids, inputs_embeds=inputs_embeds, pixel_values=pixel_values, image_sizes=image_sizes
|
|
463
|
+
)
|
|
464
|
+
logits = []
|
|
465
|
+
inputs = inputs_embeds if inputs_embeds is not None else input_ids
|
|
466
|
+
batch_size = inputs.shape[0]
|
|
589
467
|
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
468
|
+
for b_idx in range(batch_size):
|
|
469
|
+
cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
|
|
470
|
+
output = self.language_model.prefill_decoder(
|
|
471
|
+
input_ids=inputs[b_idx : b_idx + 1] if inputs_embeds is None else None,
|
|
472
|
+
inputs_embeds=inputs[b_idx : b_idx + 1] if inputs_embeds is not None else None,
|
|
473
|
+
attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
|
|
474
|
+
cache_position=cache_position,
|
|
475
|
+
batch_idx=b_idx,
|
|
476
|
+
)
|
|
477
|
+
logits.append(output.logits)
|
|
596
478
|
|
|
597
|
-
|
|
479
|
+
logits = torch.cat(logits, dim=0)
|
|
598
480
|
|
|
481
|
+
# Decoder
|
|
482
|
+
else:
|
|
483
|
+
logits = self.language_model.decoder(
|
|
484
|
+
input_ids=input_ids,
|
|
485
|
+
inputs_embeds=inputs_embeds,
|
|
486
|
+
cache_position=cache_position,
|
|
487
|
+
).logits
|
|
599
488
|
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
The size of the input image in the format (height, width). ?
|
|
608
|
-
grid_pinpoints (`List`):
|
|
609
|
-
A list containing possible resolutions. Each item in the list should be a tuple or list
|
|
610
|
-
of the form `(height, width)`.
|
|
611
|
-
patch_size (`int`):
|
|
612
|
-
The size of each image patch.
|
|
613
|
-
|
|
614
|
-
Returns:
|
|
615
|
-
int: the number of patches
|
|
616
|
-
"""
|
|
617
|
-
if not isinstance(grid_pinpoints, list):
|
|
618
|
-
raise TypeError("grid_pinpoints should be a list of tuples or lists")
|
|
619
|
-
|
|
620
|
-
# ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
|
|
621
|
-
if not isinstance(image_size, (list, tuple)):
|
|
622
|
-
if not isinstance(image_size, (torch.Tensor, np.ndarray)):
|
|
623
|
-
raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
|
|
624
|
-
image_size = image_size.tolist()
|
|
625
|
-
|
|
626
|
-
best_resolution = select_best_resolution(image_size, grid_pinpoints)
|
|
627
|
-
height, width = best_resolution
|
|
628
|
-
num_patches = 0
|
|
629
|
-
# consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
|
|
630
|
-
for i in range(0, height, patch_size):
|
|
631
|
-
for j in range(0, width, patch_size):
|
|
632
|
-
num_patches += 1
|
|
633
|
-
# add the base patch
|
|
634
|
-
num_patches += 1
|
|
635
|
-
return num_patches
|
|
489
|
+
if not return_dict:
|
|
490
|
+
return logits, generate_idx
|
|
491
|
+
else:
|
|
492
|
+
return RBLNDecoderOnlyOutput(
|
|
493
|
+
logits=logits,
|
|
494
|
+
generate_idx=generate_idx,
|
|
495
|
+
)
|