optimum-rbln 0.8.2a4__py3-none-any.whl → 0.9.3__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 +108 -9
- optimum/rbln/__version__.py +16 -3
- optimum/rbln/cli.py +660 -0
- optimum/rbln/configuration_utils.py +156 -43
- optimum/rbln/diffusers/__init__.py +19 -0
- optimum/rbln/diffusers/configurations/__init__.py +3 -0
- optimum/rbln/diffusers/configurations/models/__init__.py +2 -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_autoencoder_kl_temporal_decoder.py +67 -0
- 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_unet_spatio_temporal_condition.py +59 -0
- optimum/rbln/diffusers/configurations/models/configuration_vq_model.py +3 -3
- optimum/rbln/diffusers/configurations/pipelines/__init__.py +3 -0
- 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/configurations/pipelines/configuration_stable_video_diffusion.py +114 -0
- optimum/rbln/diffusers/modeling_diffusers.py +30 -14
- optimum/rbln/diffusers/models/__init__.py +4 -0
- optimum/rbln/diffusers/models/autoencoders/__init__.py +1 -0
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl.py +31 -3
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_cosmos.py +31 -6
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +275 -0
- optimum/rbln/diffusers/models/autoencoders/vae.py +27 -8
- optimum/rbln/diffusers/models/autoencoders/vq_model.py +31 -3
- optimum/rbln/diffusers/models/controlnet.py +16 -1
- optimum/rbln/diffusers/models/transformers/prior_transformer.py +17 -3
- optimum/rbln/diffusers/models/transformers/transformer_cosmos.py +25 -2
- optimum/rbln/diffusers/models/transformers/transformer_sd3.py +23 -2
- optimum/rbln/diffusers/models/unets/__init__.py +1 -0
- optimum/rbln/diffusers/models/unets/unet_2d_condition.py +23 -4
- optimum/rbln/diffusers/models/unets/unet_spatio_temporal_condition.py +201 -0
- optimum/rbln/diffusers/pipelines/__init__.py +15 -5
- optimum/rbln/diffusers/pipelines/auto_pipeline.py +307 -0
- optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +20 -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/diffusers/pipelines/stable_video_diffusion/__init__.py +15 -0
- optimum/rbln/diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +46 -0
- optimum/rbln/modeling.py +48 -21
- optimum/rbln/modeling_base.py +99 -22
- 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 +7 -32
- optimum/rbln/transformers/modeling_attention_utils.py +385 -0
- optimum/rbln/transformers/modeling_generic.py +48 -65
- optimum/rbln/transformers/modeling_outputs.py +37 -0
- optimum/rbln/transformers/models/__init__.py +91 -30
- optimum/rbln/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py +28 -2
- optimum/rbln/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py +68 -5
- 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/bart/modeling_bart.py +23 -2
- optimum/rbln/transformers/models/bert/bert_architecture.py +16 -0
- optimum/rbln/transformers/models/bert/modeling_bert.py +93 -4
- optimum/rbln/transformers/models/blip_2/configuration_blip_2.py +42 -11
- optimum/rbln/transformers/models/blip_2/modeling_blip_2.py +135 -44
- optimum/rbln/transformers/models/clip/configuration_clip.py +10 -7
- optimum/rbln/transformers/models/clip/modeling_clip.py +67 -6
- 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 +82 -104
- 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 +114 -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 +508 -0
- optimum/rbln/transformers/models/decoderonly/generation_decoderonly.py +119 -0
- optimum/rbln/transformers/models/decoderonly/lora_architecture.py +204 -0
- optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +485 -905
- 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 +42 -0
- optimum/rbln/transformers/models/distilbert/modeling_distilbert.py +24 -0
- optimum/rbln/transformers/models/dpt/modeling_dpt.py +17 -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 -351
- 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 +1048 -0
- optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +35 -7
- optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +29 -32
- 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 +490 -0
- optimum/rbln/transformers/models/llava_next/configuration_llava_next.py +15 -17
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +234 -376
- 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 +29 -17
- 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 +322 -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 -22
- 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 +513 -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/resnet/configuration_resnet.py +17 -0
- optimum/rbln/transformers/models/resnet/modeling_resnet.py +73 -0
- optimum/rbln/transformers/models/roberta/modeling_roberta.py +33 -0
- optimum/rbln/transformers/models/seq2seq/configuration_seq2seq.py +21 -16
- optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +58 -13
- 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 +21 -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 +354 -0
- optimum/rbln/transformers/models/t5/configuration_t5.py +2 -0
- optimum/rbln/transformers/models/t5/modeling_t5.py +2 -2
- 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 +20 -16
- optimum/rbln/transformers/models/time_series_transformer/time_series_transformers_architecture.py +7 -1
- optimum/rbln/transformers/models/vit/modeling_vit.py +19 -0
- optimum/rbln/transformers/models/wav2vec2/configuration_wav2vec2.py +15 -3
- optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +61 -8
- optimum/rbln/transformers/models/whisper/configuration_whisper.py +12 -13
- optimum/rbln/transformers/models/whisper/generation_whisper.py +62 -6
- optimum/rbln/transformers/models/whisper/modeling_whisper.py +30 -5
- optimum/rbln/transformers/models/xlm_roberta/__init__.py +2 -8
- optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +43 -0
- optimum/rbln/transformers/utils/rbln_quantization.py +400 -75
- optimum/rbln/transformers/utils/rbln_runtime_wrapper.py +79 -0
- optimum/rbln/utils/deprecation.py +213 -0
- optimum/rbln/utils/hub.py +14 -3
- optimum/rbln/utils/runtime_utils.py +60 -18
- optimum/rbln/utils/submodule.py +31 -9
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3.dist-info}/METADATA +8 -7
- optimum_rbln-0.9.3.dist-info/RECORD +264 -0
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3.dist-info}/WHEEL +1 -1
- optimum_rbln-0.9.3.dist-info/entry_points.txt +2 -0
- optimum_rbln-0.8.2a4.dist-info/RECORD +0 -215
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3.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,21 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
158
138
|
def can_generate(self):
|
|
159
139
|
return True
|
|
160
140
|
|
|
141
|
+
@classmethod
|
|
142
|
+
def _reconstruct_model_if_needed(cls, model: "PreTrainedModel"):
|
|
143
|
+
with no_init_weights():
|
|
144
|
+
model_cls_name = model.model.language_model.__class__.__name__
|
|
145
|
+
causal_model_cls_name = model_cls_name.replace("Model", "ForCausalLM")
|
|
146
|
+
causal_model_cls = getattr(importlib.import_module("transformers"), causal_model_cls_name)
|
|
147
|
+
new_language_model = causal_model_cls(model.model.language_model.config)
|
|
148
|
+
|
|
149
|
+
new_language_model.lm_head = model.lm_head
|
|
150
|
+
new_language_model.model = model.model.language_model
|
|
151
|
+
model.model.language_model = new_language_model
|
|
152
|
+
model.lm_head = None
|
|
153
|
+
del model.lm_head
|
|
154
|
+
return model
|
|
155
|
+
|
|
161
156
|
@classmethod
|
|
162
157
|
def save_torch_artifacts(
|
|
163
158
|
cls,
|
|
@@ -169,7 +164,7 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
169
164
|
# If you are unavoidably running on a CPU rather than an RBLN device,
|
|
170
165
|
# store the torch tensor, weight, etc. in this function.
|
|
171
166
|
save_dict = {}
|
|
172
|
-
save_dict["image_newline"] = model.image_newline
|
|
167
|
+
save_dict["image_newline"] = model.model.image_newline
|
|
173
168
|
torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
|
|
174
169
|
|
|
175
170
|
def __post_init__(self, **kwargs):
|
|
@@ -195,7 +190,7 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
195
190
|
return self.language_model.get_input_embeddings()
|
|
196
191
|
|
|
197
192
|
@classmethod
|
|
198
|
-
def
|
|
193
|
+
def _wrap_model_if_needed(cls, model: "PreTrainedModel", rbln_config: RBLNModelConfig):
|
|
199
194
|
return model.multi_modal_projector
|
|
200
195
|
|
|
201
196
|
@classmethod
|
|
@@ -216,7 +211,11 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
216
211
|
selected_image_feature_dim = num_positions
|
|
217
212
|
|
|
218
213
|
input_info = [
|
|
219
|
-
(
|
|
214
|
+
(
|
|
215
|
+
"image_features",
|
|
216
|
+
[rbln_config.vision_tower.batch_size, selected_image_feature_dim, feature_size],
|
|
217
|
+
"float32",
|
|
218
|
+
)
|
|
220
219
|
]
|
|
221
220
|
rbln_compile_config = RBLNCompileConfig(input_info=input_info)
|
|
222
221
|
rbln_config.set_compile_cfgs([rbln_compile_config])
|
|
@@ -227,89 +226,62 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
227
226
|
input_ids,
|
|
228
227
|
inputs_embeds=None,
|
|
229
228
|
pixel_values=None,
|
|
230
|
-
image_sizes=None,
|
|
231
229
|
attention_mask=None,
|
|
230
|
+
cache_position=None,
|
|
231
|
+
image_sizes=None,
|
|
232
232
|
generate_idx=None,
|
|
233
233
|
**kwargs,
|
|
234
234
|
):
|
|
235
|
-
# Prepare HF generation
|
|
236
235
|
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
|
-
)
|
|
236
|
+
model_inputs = {}
|
|
246
237
|
|
|
247
238
|
if is_prefill_phase:
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
239
|
+
generate_idx = attention_mask.sum(dim=-1, keepdim=True).int()
|
|
240
|
+
cache_position = None
|
|
241
|
+
pixel_values = pixel_values
|
|
242
|
+
model_inputs.update({"image_sizes": image_sizes})
|
|
243
|
+
else:
|
|
244
|
+
if inputs_embeds is not None:
|
|
245
|
+
raise NotImplementedError("Specifying inputs_embeds in decoder phase is not supported.")
|
|
255
246
|
|
|
256
|
-
|
|
247
|
+
pixel_values = None
|
|
248
|
+
input_ids = input_ids[:, -1:]
|
|
249
|
+
cache_position = generate_idx
|
|
250
|
+
generate_idx = generate_idx + 1
|
|
251
|
+
model_inputs.update({"input_ids": input_ids})
|
|
252
|
+
|
|
253
|
+
if inputs_embeds is not None:
|
|
254
|
+
if self.rbln_config.use_inputs_embeds:
|
|
255
|
+
model_inputs.update({"inputs_embeds": inputs_embeds})
|
|
256
|
+
else:
|
|
257
|
+
raise ValueError(
|
|
258
|
+
"The specifying inputs_embeds is only supported when using a compiled RBLN model with 'rbln_use_inputs_embeds' set to True."
|
|
259
|
+
)
|
|
260
|
+
else:
|
|
261
|
+
model_inputs.update({"input_ids": input_ids})
|
|
262
|
+
|
|
263
|
+
model_inputs.update(
|
|
264
|
+
{
|
|
265
|
+
"attention_mask": attention_mask,
|
|
266
|
+
"pixel_values": pixel_values,
|
|
267
|
+
"cache_position": cache_position,
|
|
268
|
+
"generate_idx": generate_idx,
|
|
269
|
+
}
|
|
270
|
+
)
|
|
257
271
|
return model_inputs
|
|
258
272
|
|
|
259
|
-
def _update_model_kwargs_for_generation(
|
|
260
|
-
self,
|
|
261
|
-
outputs: RBLNDecoderOnlyOutput,
|
|
262
|
-
model_kwargs: Dict[str, Any],
|
|
263
|
-
**kwargs,
|
|
264
|
-
) -> Dict[str, Any]:
|
|
273
|
+
def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
|
|
265
274
|
# update generate_idx
|
|
266
275
|
model_kwargs["generate_idx"] = outputs.generate_idx
|
|
267
|
-
|
|
268
276
|
return model_kwargs
|
|
269
277
|
|
|
270
|
-
def
|
|
278
|
+
def get_image_features(
|
|
271
279
|
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
280
|
pixel_values: torch.FloatTensor,
|
|
284
|
-
|
|
281
|
+
image_sizes: torch.Tensor,
|
|
282
|
+
vision_feature_layer: Union[int, List[int]],
|
|
285
283
|
vision_feature_select_strategy: str,
|
|
286
284
|
):
|
|
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
285
|
# ! infer image_num_patches from image_sizes
|
|
314
286
|
image_num_patches = [
|
|
315
287
|
image_size_to_num_patches(
|
|
@@ -319,6 +291,26 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
319
291
|
)
|
|
320
292
|
for imsize in image_sizes
|
|
321
293
|
]
|
|
294
|
+
|
|
295
|
+
# prepare out buffer for pre-allocation
|
|
296
|
+
vision_out_size = [
|
|
297
|
+
pixel_values.shape[0] * pixel_values.shape[1],
|
|
298
|
+
(self.config.vision_config.image_size // self.config.vision_config.patch_size) ** 2 + 1,
|
|
299
|
+
self.config.vision_config.hidden_size,
|
|
300
|
+
]
|
|
301
|
+
pooler_out_size = [pixel_values.shape[0] * pixel_values.shape[1], self.config.vision_config.hidden_size]
|
|
302
|
+
vision_out_buffer = []
|
|
303
|
+
for i in range(self.config.vision_config.num_hidden_layers + 2):
|
|
304
|
+
vision_out_buffer.append(torch.empty(size=vision_out_size, dtype=torch.float32, device="cpu"))
|
|
305
|
+
vision_out_buffer.insert(1, torch.empty(size=pooler_out_size, dtype=torch.float32, device="cpu"))
|
|
306
|
+
|
|
307
|
+
projector_out_size = [
|
|
308
|
+
pixel_values.shape[0] * pixel_values.shape[1],
|
|
309
|
+
(self.config.vision_config.image_size // self.config.vision_config.patch_size) ** 2,
|
|
310
|
+
self.config.text_config.hidden_size,
|
|
311
|
+
]
|
|
312
|
+
projector_out_buffer = [torch.empty(size=projector_out_size, dtype=torch.float32, device="cpu")]
|
|
313
|
+
|
|
322
314
|
if pixel_values.dim() == 5:
|
|
323
315
|
# stacked if input is (batch_size, num_patches, num_channels, height, width)
|
|
324
316
|
_pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
|
|
@@ -327,118 +319,25 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
327
319
|
# otherwise has to be stacked from list of (num_patches, num_channels, height, width)
|
|
328
320
|
raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
|
|
329
321
|
|
|
330
|
-
image_features = self.vision_tower(pixel_values, output_hidden_states=True)
|
|
331
|
-
|
|
322
|
+
image_features = self.vision_tower(pixel_values, output_hidden_states=True, out=vision_out_buffer)
|
|
323
|
+
# If we have one vision feature layer, return the corresponding hidden states,
|
|
324
|
+
# otherwise, select the hidden states of each feature layer and concatenate them
|
|
325
|
+
if isinstance(vision_feature_layer, int):
|
|
326
|
+
selected_image_feature = image_features.hidden_states[vision_feature_layer]
|
|
327
|
+
else:
|
|
328
|
+
hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
|
|
329
|
+
selected_image_feature = torch.cat(hs_pool, dim=-1)
|
|
330
|
+
|
|
332
331
|
if vision_feature_select_strategy == "default":
|
|
333
332
|
selected_image_feature = selected_image_feature[:, 1:]
|
|
334
333
|
elif vision_feature_select_strategy == "full":
|
|
335
334
|
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
335
|
|
|
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)
|
|
336
|
+
image_features = self.multi_modal_projector(selected_image_feature, out=projector_out_buffer)
|
|
337
|
+
image_features = torch.split(image_features, image_num_patches, dim=0)
|
|
338
|
+
return image_features
|
|
422
339
|
|
|
423
|
-
# Almost copied from : https://github.com/huggingface/transformers/blob/6b550462139655d488d4c663086a63e98713c6b9/src/transformers/models/llava_next/modeling_llava_next.py
|
|
424
340
|
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
341
|
new_image_features = []
|
|
443
342
|
feature_lens = []
|
|
444
343
|
for image_idx, image_feature in enumerate(image_features):
|
|
@@ -447,18 +346,22 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
447
346
|
image_feature = image_feature[1:]
|
|
448
347
|
height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
|
|
449
348
|
|
|
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
349
|
num_patch_height, num_patch_width = get_anyres_image_grid_shape(
|
|
458
350
|
image_sizes[image_idx],
|
|
459
351
|
self.config.image_grid_pinpoints,
|
|
460
352
|
self.config.vision_config.image_size,
|
|
461
353
|
)
|
|
354
|
+
|
|
355
|
+
if (
|
|
356
|
+
np.prod(image_feature.shape) % (num_patch_height * num_patch_width * height * width) != 0
|
|
357
|
+
and vision_feature_select_strategy == "default"
|
|
358
|
+
):
|
|
359
|
+
logger.warning_once(
|
|
360
|
+
"Image feature shape does not line up with the provided patch size. "
|
|
361
|
+
"You may be using the `default` vision_feature_select_strategy with a"
|
|
362
|
+
" visual encoder that does not have CLS."
|
|
363
|
+
)
|
|
364
|
+
|
|
462
365
|
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
|
463
366
|
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
|
464
367
|
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
|
@@ -485,151 +388,106 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
|
485
388
|
feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
|
|
486
389
|
return image_features, feature_lens
|
|
487
390
|
|
|
391
|
+
def _preprocess_prefill(
|
|
392
|
+
self,
|
|
393
|
+
input_ids: torch.LongTensor = None,
|
|
394
|
+
pixel_values: torch.FloatTensor = None,
|
|
395
|
+
image_sizes: Optional[torch.LongTensor] = None,
|
|
396
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
397
|
+
vision_feature_layer: Optional[int] = None,
|
|
398
|
+
vision_feature_select_strategy: Optional[str] = None,
|
|
399
|
+
**kwargs,
|
|
400
|
+
):
|
|
401
|
+
vision_feature_layer = (
|
|
402
|
+
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
|
403
|
+
)
|
|
488
404
|
|
|
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.
|
|
405
|
+
vision_feature_select_strategy = (
|
|
406
|
+
vision_feature_select_strategy
|
|
407
|
+
if vision_feature_select_strategy is not None
|
|
408
|
+
else self.config.vision_feature_select_strategy
|
|
409
|
+
)
|
|
525
410
|
|
|
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).
|
|
411
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
412
|
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
531
413
|
|
|
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"
|
|
414
|
+
if pixel_values is not None and inputs_embeds is not None:
|
|
415
|
+
raise ValueError(
|
|
416
|
+
"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
|
|
539
417
|
)
|
|
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
418
|
|
|
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]
|
|
419
|
+
if inputs_embeds is None:
|
|
420
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
557
421
|
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
This is done by calculating the effective and wasted resolution for each possible resolution.
|
|
422
|
+
if pixel_values is not None and pixel_values.size(0) > 0:
|
|
423
|
+
image_features = self.get_image_features(
|
|
424
|
+
pixel_values,
|
|
425
|
+
image_sizes,
|
|
426
|
+
vision_feature_layer=vision_feature_layer,
|
|
427
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
428
|
+
)
|
|
567
429
|
|
|
568
|
-
|
|
430
|
+
# NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
|
|
431
|
+
image_features, feature_lens = self.pack_image_features(
|
|
432
|
+
image_features,
|
|
433
|
+
image_sizes,
|
|
434
|
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
|
435
|
+
image_newline=self.image_newline,
|
|
436
|
+
)
|
|
569
437
|
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
A list of possible resolutions in the format [(height1, width1), (height2, width2), ...].
|
|
438
|
+
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
|
439
|
+
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
440
|
+
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
441
|
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
|
575
442
|
|
|
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")
|
|
443
|
+
return inputs_embeds
|
|
583
444
|
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
445
|
+
def forward(
|
|
446
|
+
self,
|
|
447
|
+
input_ids: torch.LongTensor = None,
|
|
448
|
+
attention_mask: torch.LongTensor = None,
|
|
449
|
+
pixel_values: torch.FloatTensor = None,
|
|
450
|
+
image_sizes: Optional[torch.LongTensor] = None,
|
|
451
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
452
|
+
cache_position: torch.Tensor = None,
|
|
453
|
+
generate_idx: Optional[torch.Tensor] = None,
|
|
454
|
+
return_dict: Optional[bool] = None,
|
|
455
|
+
**kwargs,
|
|
456
|
+
) -> Union[Tuple, RBLNDecoderOnlyOutput]:
|
|
457
|
+
# Prefill
|
|
458
|
+
if cache_position is None:
|
|
459
|
+
inputs_embeds = self._preprocess_prefill(
|
|
460
|
+
input_ids=input_ids, inputs_embeds=inputs_embeds, pixel_values=pixel_values, image_sizes=image_sizes
|
|
461
|
+
)
|
|
462
|
+
logits = []
|
|
463
|
+
inputs = inputs_embeds if inputs_embeds is not None else input_ids
|
|
464
|
+
batch_size = inputs.shape[0]
|
|
589
465
|
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
466
|
+
for b_idx in range(batch_size):
|
|
467
|
+
cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
|
|
468
|
+
output = self.language_model.prefill_decoder(
|
|
469
|
+
input_ids=inputs[b_idx : b_idx + 1] if inputs_embeds is None else None,
|
|
470
|
+
inputs_embeds=inputs[b_idx : b_idx + 1] if inputs_embeds is not None else None,
|
|
471
|
+
attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
|
|
472
|
+
cache_position=cache_position,
|
|
473
|
+
batch_idx=b_idx,
|
|
474
|
+
)
|
|
475
|
+
logits.append(output.logits)
|
|
596
476
|
|
|
597
|
-
|
|
477
|
+
logits = torch.cat(logits, dim=0)
|
|
598
478
|
|
|
479
|
+
# Decoder
|
|
480
|
+
else:
|
|
481
|
+
logits = self.language_model.decoder(
|
|
482
|
+
input_ids=input_ids,
|
|
483
|
+
inputs_embeds=inputs_embeds,
|
|
484
|
+
cache_position=cache_position,
|
|
485
|
+
).logits
|
|
599
486
|
|
|
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
|
|
487
|
+
if not return_dict:
|
|
488
|
+
return logits, generate_idx
|
|
489
|
+
else:
|
|
490
|
+
return RBLNDecoderOnlyOutput(
|
|
491
|
+
logits=logits,
|
|
492
|
+
generate_idx=generate_idx,
|
|
493
|
+
)
|