optimum-rbln 0.9.3.post1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of optimum-rbln might be problematic. Click here for more details.
- optimum/rbln/__init__.py +505 -0
- optimum/rbln/__version__.py +34 -0
- optimum/rbln/cli.py +660 -0
- optimum/rbln/configuration_utils.py +968 -0
- optimum/rbln/diffusers/__init__.py +198 -0
- optimum/rbln/diffusers/configurations/__init__.py +37 -0
- optimum/rbln/diffusers/configurations/models/__init__.py +10 -0
- optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl.py +73 -0
- optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl_cosmos.py +84 -0
- optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl_temporal_decoder.py +67 -0
- optimum/rbln/diffusers/configurations/models/configuration_controlnet.py +64 -0
- optimum/rbln/diffusers/configurations/models/configuration_prior_transformer.py +59 -0
- optimum/rbln/diffusers/configurations/models/configuration_transformer_cosmos.py +78 -0
- optimum/rbln/diffusers/configurations/models/configuration_transformer_sd3.py +63 -0
- optimum/rbln/diffusers/configurations/models/configuration_unet_2d_condition.py +81 -0
- optimum/rbln/diffusers/configurations/models/configuration_unet_spatio_temporal_condition.py +59 -0
- optimum/rbln/diffusers/configurations/models/configuration_vq_model.py +74 -0
- optimum/rbln/diffusers/configurations/pipelines/__init__.py +34 -0
- optimum/rbln/diffusers/configurations/pipelines/configuration_controlnet.py +316 -0
- optimum/rbln/diffusers/configurations/pipelines/configuration_cosmos.py +117 -0
- optimum/rbln/diffusers/configurations/pipelines/configuration_kandinsky2_2.py +363 -0
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion.py +156 -0
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_3.py +176 -0
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_xl.py +159 -0
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_video_diffusion.py +114 -0
- optimum/rbln/diffusers/modeling_diffusers.py +451 -0
- optimum/rbln/diffusers/models/__init__.py +64 -0
- optimum/rbln/diffusers/models/autoencoders/__init__.py +18 -0
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl.py +255 -0
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_cosmos.py +245 -0
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +275 -0
- optimum/rbln/diffusers/models/autoencoders/vae.py +178 -0
- optimum/rbln/diffusers/models/autoencoders/vq_model.py +211 -0
- optimum/rbln/diffusers/models/controlnet.py +281 -0
- optimum/rbln/diffusers/models/transformers/__init__.py +17 -0
- optimum/rbln/diffusers/models/transformers/prior_transformer.py +160 -0
- optimum/rbln/diffusers/models/transformers/transformer_cosmos.py +344 -0
- optimum/rbln/diffusers/models/transformers/transformer_sd3.py +191 -0
- optimum/rbln/diffusers/models/unets/__init__.py +16 -0
- optimum/rbln/diffusers/models/unets/unet_2d_condition.py +408 -0
- optimum/rbln/diffusers/models/unets/unet_spatio_temporal_condition.py +201 -0
- optimum/rbln/diffusers/pipelines/__init__.py +113 -0
- optimum/rbln/diffusers/pipelines/auto_pipeline.py +307 -0
- optimum/rbln/diffusers/pipelines/controlnet/__init__.py +19 -0
- optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +139 -0
- optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +669 -0
- optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +640 -0
- optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +825 -0
- optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +837 -0
- optimum/rbln/diffusers/pipelines/cosmos/__init__.py +17 -0
- optimum/rbln/diffusers/pipelines/cosmos/configuration_cosmos_guardrail.py +113 -0
- optimum/rbln/diffusers/pipelines/cosmos/cosmos_guardrail.py +425 -0
- optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +128 -0
- optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +128 -0
- optimum/rbln/diffusers/pipelines/kandinsky2_2/__init__.py +23 -0
- optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +34 -0
- optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +207 -0
- optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +34 -0
- optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpaint.py +34 -0
- optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +31 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/__init__.py +17 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +32 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +31 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +31 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_3/__init__.py +17 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +31 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +31 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +31 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/__init__.py +17 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +31 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +31 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +31 -0
- 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 +364 -0
- optimum/rbln/modeling_base.py +637 -0
- optimum/rbln/ops/__init__.py +19 -0
- optimum/rbln/ops/attn.py +455 -0
- optimum/rbln/ops/flash_attn.py +350 -0
- optimum/rbln/ops/kv_cache_update.py +29 -0
- optimum/rbln/ops/linear.py +32 -0
- optimum/rbln/ops/sliding_window_attn.py +111 -0
- optimum/rbln/transformers/__init__.py +340 -0
- optimum/rbln/transformers/configuration_generic.py +120 -0
- optimum/rbln/transformers/modeling_attention_utils.py +385 -0
- optimum/rbln/transformers/modeling_generic.py +280 -0
- optimum/rbln/transformers/modeling_outputs.py +37 -0
- optimum/rbln/transformers/modeling_rope_utils.py +314 -0
- optimum/rbln/transformers/models/__init__.py +343 -0
- optimum/rbln/transformers/models/audio_spectrogram_transformer/__init__.py +17 -0
- optimum/rbln/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py +47 -0
- optimum/rbln/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py +91 -0
- optimum/rbln/transformers/models/auto/__init__.py +31 -0
- optimum/rbln/transformers/models/auto/auto_factory.py +267 -0
- optimum/rbln/transformers/models/auto/modeling_auto.py +162 -0
- optimum/rbln/transformers/models/bart/__init__.py +17 -0
- optimum/rbln/transformers/models/bart/bart_architecture.py +163 -0
- optimum/rbln/transformers/models/bart/configuration_bart.py +36 -0
- optimum/rbln/transformers/models/bart/modeling_bart.py +86 -0
- optimum/rbln/transformers/models/bert/__init__.py +16 -0
- optimum/rbln/transformers/models/bert/bert_architecture.py +16 -0
- optimum/rbln/transformers/models/bert/configuration_bert.py +46 -0
- optimum/rbln/transformers/models/bert/modeling_bert.py +148 -0
- optimum/rbln/transformers/models/blip_2/__init__.py +20 -0
- optimum/rbln/transformers/models/blip_2/configuration_blip_2.py +115 -0
- optimum/rbln/transformers/models/blip_2/modeling_blip_2.py +526 -0
- optimum/rbln/transformers/models/clip/__init__.py +26 -0
- optimum/rbln/transformers/models/clip/configuration_clip.py +103 -0
- optimum/rbln/transformers/models/clip/modeling_clip.py +384 -0
- optimum/rbln/transformers/models/colpali/__init__.py +2 -0
- optimum/rbln/transformers/models/colpali/colpali_architecture.py +218 -0
- optimum/rbln/transformers/models/colpali/configuration_colpali.py +84 -0
- optimum/rbln/transformers/models/colpali/modeling_colpali.py +361 -0
- 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 +27 -0
- optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py +300 -0
- optimum/rbln/transformers/models/decoderonly/configuration_lora.py +411 -0
- optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +1224 -0
- 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 +823 -0
- 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/__init__.py +19 -0
- optimum/rbln/transformers/models/distilbert/configuration_distilbert.py +24 -0
- optimum/rbln/transformers/models/distilbert/modeling_distilbert.py +51 -0
- optimum/rbln/transformers/models/dpt/__init__.py +16 -0
- optimum/rbln/transformers/models/dpt/configuration_dpt.py +24 -0
- optimum/rbln/transformers/models/dpt/modeling_dpt.py +42 -0
- optimum/rbln/transformers/models/exaone/__init__.py +24 -0
- optimum/rbln/transformers/models/exaone/configuration_exaone.py +42 -0
- optimum/rbln/transformers/models/exaone/exaone_architecture.py +77 -0
- optimum/rbln/transformers/models/exaone/modeling_exaone.py +145 -0
- optimum/rbln/transformers/models/gemma/__init__.py +16 -0
- optimum/rbln/transformers/models/gemma/configuration_gemma.py +50 -0
- optimum/rbln/transformers/models/gemma/gemma_architecture.py +27 -0
- optimum/rbln/transformers/models/gemma/modeling_gemma.py +104 -0
- optimum/rbln/transformers/models/gemma3/__init__.py +16 -0
- optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +109 -0
- optimum/rbln/transformers/models/gemma3/gemma3_architecture.py +170 -0
- optimum/rbln/transformers/models/gemma3/gemma3_runtime_utils.py +245 -0
- optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +611 -0
- optimum/rbln/transformers/models/gpt2/__init__.py +16 -0
- optimum/rbln/transformers/models/gpt2/configuration_gpt2.py +50 -0
- optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +93 -0
- optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +55 -0
- 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/__init__.py +16 -0
- optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +89 -0
- optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +497 -0
- optimum/rbln/transformers/models/llama/__init__.py +16 -0
- optimum/rbln/transformers/models/llama/configuration_llama.py +50 -0
- optimum/rbln/transformers/models/llama/llama_architecture.py +19 -0
- optimum/rbln/transformers/models/llama/modeling_llama.py +104 -0
- 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/__init__.py +16 -0
- optimum/rbln/transformers/models/llava_next/configuration_llava_next.py +69 -0
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +493 -0
- optimum/rbln/transformers/models/midm/__init__.py +24 -0
- optimum/rbln/transformers/models/midm/configuration_midm.py +42 -0
- optimum/rbln/transformers/models/midm/midm_architecture.py +144 -0
- optimum/rbln/transformers/models/midm/modeling_midm.py +144 -0
- optimum/rbln/transformers/models/mistral/__init__.py +16 -0
- optimum/rbln/transformers/models/mistral/configuration_mistral.py +50 -0
- optimum/rbln/transformers/models/mistral/mistral_architecture.py +19 -0
- optimum/rbln/transformers/models/mistral/modeling_mistral.py +115 -0
- optimum/rbln/transformers/models/opt/__init__.py +16 -0
- optimum/rbln/transformers/models/opt/configuration_opt.py +29 -0
- optimum/rbln/transformers/models/opt/modeling_opt.py +102 -0
- optimum/rbln/transformers/models/opt/opt_architecture.py +74 -0
- 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 +16 -0
- optimum/rbln/transformers/models/phi/configuration_phi.py +50 -0
- optimum/rbln/transformers/models/phi/modeling_phi.py +92 -0
- optimum/rbln/transformers/models/phi/phi_architecture.py +115 -0
- 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 +16 -0
- optimum/rbln/transformers/models/qwen2/configuration_qwen2.py +50 -0
- optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +123 -0
- optimum/rbln/transformers/models/qwen2/qwen2_architecture.py +19 -0
- optimum/rbln/transformers/models/qwen2_5_vl/__init__.py +19 -0
- optimum/rbln/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py +111 -0
- optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +636 -0
- optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py +220 -0
- 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/__init__.py +16 -0
- optimum/rbln/transformers/models/qwen3/configuration_qwen3.py +71 -0
- optimum/rbln/transformers/models/qwen3/modeling_qwen3.py +133 -0
- optimum/rbln/transformers/models/qwen3/qwen3_architecture.py +31 -0
- optimum/rbln/transformers/models/resnet/__init__.py +23 -0
- optimum/rbln/transformers/models/resnet/configuration_resnet.py +42 -0
- optimum/rbln/transformers/models/resnet/modeling_resnet.py +99 -0
- optimum/rbln/transformers/models/roberta/__init__.py +24 -0
- optimum/rbln/transformers/models/roberta/configuration_roberta.py +33 -0
- optimum/rbln/transformers/models/roberta/modeling_roberta.py +72 -0
- optimum/rbln/transformers/models/seq2seq/__init__.py +16 -0
- optimum/rbln/transformers/models/seq2seq/configuration_seq2seq.py +71 -0
- optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +477 -0
- optimum/rbln/transformers/models/seq2seq/seq2seq_architecture.py +527 -0
- optimum/rbln/transformers/models/siglip/__init__.py +16 -0
- optimum/rbln/transformers/models/siglip/configuration_siglip.py +76 -0
- optimum/rbln/transformers/models/siglip/modeling_siglip.py +199 -0
- 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/__init__.py +17 -0
- optimum/rbln/transformers/models/t5/configuration_t5.py +36 -0
- optimum/rbln/transformers/models/t5/modeling_t5.py +130 -0
- optimum/rbln/transformers/models/t5/t5_architecture.py +264 -0
- optimum/rbln/transformers/models/time_series_transformer/__init__.py +26 -0
- optimum/rbln/transformers/models/time_series_transformer/configuration_time_series_transformer.py +41 -0
- optimum/rbln/transformers/models/time_series_transformer/modeling_time_series_transformer.py +435 -0
- optimum/rbln/transformers/models/time_series_transformer/time_series_transformers_architecture.py +337 -0
- optimum/rbln/transformers/models/vit/__init__.py +19 -0
- optimum/rbln/transformers/models/vit/configuration_vit.py +24 -0
- optimum/rbln/transformers/models/vit/modeling_vit.py +44 -0
- optimum/rbln/transformers/models/wav2vec2/__init__.py +16 -0
- optimum/rbln/transformers/models/wav2vec2/configuration_wav2vec2.py +38 -0
- optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +104 -0
- optimum/rbln/transformers/models/whisper/__init__.py +17 -0
- optimum/rbln/transformers/models/whisper/configuration_whisper.py +72 -0
- optimum/rbln/transformers/models/whisper/generation_whisper.py +159 -0
- optimum/rbln/transformers/models/whisper/modeling_whisper.py +475 -0
- optimum/rbln/transformers/models/whisper/whisper_architecture.py +349 -0
- optimum/rbln/transformers/models/xlm_roberta/__init__.py +24 -0
- optimum/rbln/transformers/models/xlm_roberta/configuration_xlm_roberta.py +32 -0
- optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +82 -0
- optimum/rbln/transformers/utils/__init__.py +0 -0
- optimum/rbln/transformers/utils/rbln_quantization.py +589 -0
- optimum/rbln/transformers/utils/rbln_runtime_wrapper.py +79 -0
- optimum/rbln/utils/__init__.py +16 -0
- optimum/rbln/utils/decorator_utils.py +86 -0
- optimum/rbln/utils/deprecation.py +213 -0
- optimum/rbln/utils/hub.py +94 -0
- optimum/rbln/utils/import_utils.py +170 -0
- optimum/rbln/utils/logging.py +110 -0
- optimum/rbln/utils/model_utils.py +63 -0
- optimum/rbln/utils/runtime_utils.py +249 -0
- optimum/rbln/utils/save_utils.py +102 -0
- optimum/rbln/utils/submodule.py +152 -0
- optimum_rbln-0.9.3.post1.dist-info/METADATA +124 -0
- optimum_rbln-0.9.3.post1.dist-info/RECORD +264 -0
- optimum_rbln-0.9.3.post1.dist-info/WHEEL +4 -0
- optimum_rbln-0.9.3.post1.dist-info/entry_points.txt +2 -0
- optimum_rbln-0.9.3.post1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from .configuration_llava_next import RBLNLlavaNextForConditionalGenerationConfig
|
|
16
|
+
from .modeling_llava_next import RBLNLlavaNextForConditionalGeneration
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from typing import Any, Optional
|
|
16
|
+
|
|
17
|
+
from ....configuration_utils import RBLNModelConfig
|
|
18
|
+
from ....utils.logging import get_logger
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
logger = get_logger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RBLNLlavaNextForConditionalGenerationConfig(RBLNModelConfig):
|
|
25
|
+
"""
|
|
26
|
+
Configuration class for RBLNLlavaNextForConditionalGeneration.
|
|
27
|
+
|
|
28
|
+
This configuration class stores the configuration parameters specific to
|
|
29
|
+
RBLN-optimized LLaVA-Next models for multimodal conditional generation tasks
|
|
30
|
+
that combine vision and language processing capabilities.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
submodules = ["vision_tower", "language_model"]
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
batch_size: Optional[int] = None,
|
|
38
|
+
vision_tower: Optional[RBLNModelConfig] = None,
|
|
39
|
+
language_model: Optional[RBLNModelConfig] = None,
|
|
40
|
+
**kwargs: Any,
|
|
41
|
+
):
|
|
42
|
+
"""
|
|
43
|
+
Args:
|
|
44
|
+
batch_size (Optional[int]): The batch size for inference. Defaults to 1.
|
|
45
|
+
vision_tower (Optional[RBLNModelConfig]): Configuration for the vision encoder component.
|
|
46
|
+
language_model (Optional[RBLNModelConfig]): Configuration for the language model component.
|
|
47
|
+
kwargs: Additional arguments passed to the parent RBLNModelConfig.
|
|
48
|
+
|
|
49
|
+
Raises:
|
|
50
|
+
ValueError: If `batch_size` is not a positive integer.
|
|
51
|
+
"""
|
|
52
|
+
super().__init__(**kwargs)
|
|
53
|
+
self.batch_size = batch_size or 1
|
|
54
|
+
if not isinstance(self.batch_size, int) or self.batch_size < 0:
|
|
55
|
+
raise ValueError(f"batch_size must be a positive integer, got {self.batch_size}")
|
|
56
|
+
|
|
57
|
+
if self.batch_size != 1:
|
|
58
|
+
logger.warning("Ignore batch_size for LlavaNext vision tower. It will be set to 1.")
|
|
59
|
+
|
|
60
|
+
self.vision_tower = self.initialize_submodule_config(
|
|
61
|
+
submodule_config=vision_tower,
|
|
62
|
+
batch_size=1, # vision_tower batch_size is always 1 in LlavaNext
|
|
63
|
+
output_hidden_states=True, # LlavaNext requires output_hidden_states to be True
|
|
64
|
+
force_kwargs=True,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
self.language_model = self.initialize_submodule_config(
|
|
68
|
+
submodule_config=language_model,
|
|
69
|
+
)
|
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
import importlib
|
|
16
|
+
import inspect
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import torch
|
|
22
|
+
from transformers import AutoModelForVision2Seq, LlavaNextForConditionalGeneration, PretrainedConfig, PreTrainedModel
|
|
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
|
+
)
|
|
30
|
+
|
|
31
|
+
from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
|
|
32
|
+
from ....modeling import RBLNModel
|
|
33
|
+
from ....utils.logging import get_logger
|
|
34
|
+
from ...utils.rbln_runtime_wrapper import LoopProcessor
|
|
35
|
+
from ..decoderonly.generation_decoderonly import RBLNDecoderOnlyGenerationMixin
|
|
36
|
+
from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyOutput
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
logger = get_logger(__name__)
|
|
40
|
+
|
|
41
|
+
if TYPE_CHECKING:
|
|
42
|
+
from transformers import AutoFeatureExtractor, AutoProcessor, AutoTokenizer, PretrainedConfig
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class LoopVisionTower(LoopProcessor):
|
|
46
|
+
def __init__(self, vision_tower: "RBLNModel"):
|
|
47
|
+
super().__init__(model=vision_tower.model[0])
|
|
48
|
+
|
|
49
|
+
def _get_batch_size(self, pixel_values, **kwargs):
|
|
50
|
+
return pixel_values.shape[0]
|
|
51
|
+
|
|
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})
|
|
56
|
+
|
|
57
|
+
def _process_outputs(self, outputs: list, **kwargs) -> "BaseModelOutputWithPooling":
|
|
58
|
+
output = kwargs["out"]
|
|
59
|
+
last_hidden_states = output[0]
|
|
60
|
+
pooler_output = output[1]
|
|
61
|
+
|
|
62
|
+
if not output[2:]:
|
|
63
|
+
hidden_states = None
|
|
64
|
+
else:
|
|
65
|
+
hidden_states = tuple(output[2:])
|
|
66
|
+
|
|
67
|
+
return BaseModelOutputWithPooling(
|
|
68
|
+
last_hidden_state=last_hidden_states,
|
|
69
|
+
pooler_output=pooler_output,
|
|
70
|
+
hidden_states=hidden_states,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class LoopProjector(LoopProcessor):
|
|
75
|
+
def __init__(self, multi_modal_projector: "RBLNModel"):
|
|
76
|
+
super().__init__(model=multi_modal_projector)
|
|
77
|
+
|
|
78
|
+
def _get_batch_size(self, image_feature, **kwargs):
|
|
79
|
+
return image_feature.shape[0]
|
|
80
|
+
|
|
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})
|
|
85
|
+
|
|
86
|
+
def _process_outputs(self, outputs: list, **kwargs):
|
|
87
|
+
output = kwargs["out"]
|
|
88
|
+
return output[0]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class RBLNLlavaNextForConditionalGeneration(RBLNModel, RBLNDecoderOnlyGenerationMixin):
|
|
92
|
+
"""
|
|
93
|
+
RBLNLlavaNextForConditionalGeneration is a multi-modal model that combines vision and language processing capabilities,
|
|
94
|
+
optimized for RBLN NPUs. It is designed for conditional generation tasks that involve both image and text inputs.
|
|
95
|
+
|
|
96
|
+
This model inherits from [`RBLNModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
|
|
97
|
+
|
|
98
|
+
Important Note:
|
|
99
|
+
This model includes a Large Language Model (LLM) as a submodule. For optimal performance, it is highly recommended to use
|
|
100
|
+
tensor parallelism for the language model. This can be achieved by using the `rbln_config` parameter in the
|
|
101
|
+
`from_pretrained` method. Refer to the `from_pretrained` documentation and the RBLNLlavaNextForConditionalGenerationConfig class for details.
|
|
102
|
+
|
|
103
|
+
Examples:
|
|
104
|
+
```python
|
|
105
|
+
from optimum.rbln import RBLNLlavaNextForConditionalGeneration
|
|
106
|
+
|
|
107
|
+
model = RBLNLlavaNextForConditionalGeneration.from_pretrained(
|
|
108
|
+
"llava-hf/llava-v1.6-mistral-7b-hf",
|
|
109
|
+
export=True,
|
|
110
|
+
rbln_config={
|
|
111
|
+
"language_model": {
|
|
112
|
+
"tensor_parallel_size": 4,
|
|
113
|
+
"use_inputs_embeds": True, # In Llava-Next, language model must use inputs_embeds as input.
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
model.save_pretrained("compiled-llava-next-mistral-7b-hf")
|
|
119
|
+
```
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
auto_model_class = AutoModelForVision2Seq
|
|
123
|
+
_rbln_submodules = [
|
|
124
|
+
{"name": "vision_tower"},
|
|
125
|
+
{"name": "language_model"},
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
def __getattr__(self, __name: str) -> Any:
|
|
129
|
+
def redirect(func):
|
|
130
|
+
return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
|
|
131
|
+
|
|
132
|
+
val = getattr(LlavaNextForConditionalGeneration, __name)
|
|
133
|
+
|
|
134
|
+
if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
|
|
135
|
+
return redirect(val)
|
|
136
|
+
return val
|
|
137
|
+
|
|
138
|
+
def can_generate(self):
|
|
139
|
+
return True
|
|
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
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def save_torch_artifacts(
|
|
158
|
+
cls,
|
|
159
|
+
model: "LlavaNextForConditionalGeneration",
|
|
160
|
+
save_dir_path: Path,
|
|
161
|
+
subfolder: str,
|
|
162
|
+
rbln_config: RBLNModelConfig,
|
|
163
|
+
):
|
|
164
|
+
# If you are unavoidably running on a CPU rather than an RBLN device,
|
|
165
|
+
# store the torch tensor, weight, etc. in this function.
|
|
166
|
+
save_dict = {}
|
|
167
|
+
save_dict["image_newline"] = model.model.image_newline
|
|
168
|
+
torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
|
|
169
|
+
|
|
170
|
+
def __post_init__(self, **kwargs):
|
|
171
|
+
self.vision_tower = LoopVisionTower(self.rbln_submodules[0])
|
|
172
|
+
self.language_model = self.rbln_submodules[1]
|
|
173
|
+
self.multi_modal_projector = LoopProjector(self.model[0])
|
|
174
|
+
|
|
175
|
+
artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
|
|
176
|
+
self.image_newline = artifacts["image_newline"]
|
|
177
|
+
|
|
178
|
+
# Copied from the original class
|
|
179
|
+
self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
|
|
180
|
+
self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
|
|
181
|
+
return super().__post_init__(**kwargs)
|
|
182
|
+
|
|
183
|
+
def get_attn_impl(self) -> str:
|
|
184
|
+
return self.rbln_config.language_model.attn_impl
|
|
185
|
+
|
|
186
|
+
def get_kvcache_num_blocks(self) -> int:
|
|
187
|
+
return self.rbln_config.language_model.kvcache_num_blocks
|
|
188
|
+
|
|
189
|
+
def get_input_embeddings(self):
|
|
190
|
+
return self.language_model.get_input_embeddings()
|
|
191
|
+
|
|
192
|
+
@classmethod
|
|
193
|
+
def _wrap_model_if_needed(cls, model: "PreTrainedModel", rbln_config: RBLNModelConfig):
|
|
194
|
+
return model.multi_modal_projector
|
|
195
|
+
|
|
196
|
+
@classmethod
|
|
197
|
+
def _update_rbln_config(
|
|
198
|
+
cls,
|
|
199
|
+
preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
|
|
200
|
+
model: Optional["PreTrainedModel"] = None,
|
|
201
|
+
model_config: Optional["PretrainedConfig"] = None,
|
|
202
|
+
rbln_config: Optional[RBLNModelConfig] = None,
|
|
203
|
+
) -> RBLNModelConfig:
|
|
204
|
+
feature_size = model_config.vision_config.hidden_size
|
|
205
|
+
|
|
206
|
+
# Calculating `num_positions` : See CLIPVisionEmbeddings of transformers for more details.
|
|
207
|
+
num_positions = (model_config.vision_config.image_size // model_config.vision_config.patch_size) ** 2 + 1
|
|
208
|
+
if model_config.vision_feature_select_strategy == "default":
|
|
209
|
+
selected_image_feature_dim = num_positions - 1
|
|
210
|
+
else:
|
|
211
|
+
selected_image_feature_dim = num_positions
|
|
212
|
+
|
|
213
|
+
input_info = [
|
|
214
|
+
(
|
|
215
|
+
"image_features",
|
|
216
|
+
[rbln_config.vision_tower.batch_size, selected_image_feature_dim, feature_size],
|
|
217
|
+
"float32",
|
|
218
|
+
)
|
|
219
|
+
]
|
|
220
|
+
rbln_compile_config = RBLNCompileConfig(input_info=input_info)
|
|
221
|
+
rbln_config.set_compile_cfgs([rbln_compile_config])
|
|
222
|
+
return rbln_config
|
|
223
|
+
|
|
224
|
+
def prepare_inputs_for_generation(
|
|
225
|
+
self,
|
|
226
|
+
input_ids,
|
|
227
|
+
inputs_embeds=None,
|
|
228
|
+
pixel_values=None,
|
|
229
|
+
attention_mask=None,
|
|
230
|
+
cache_position=None,
|
|
231
|
+
image_sizes=None,
|
|
232
|
+
generate_idx=None,
|
|
233
|
+
**kwargs,
|
|
234
|
+
):
|
|
235
|
+
is_prefill_phase = generate_idx is None
|
|
236
|
+
model_inputs = {}
|
|
237
|
+
|
|
238
|
+
if is_prefill_phase:
|
|
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.")
|
|
246
|
+
|
|
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
|
+
)
|
|
271
|
+
return model_inputs
|
|
272
|
+
|
|
273
|
+
def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
|
|
274
|
+
# update generate_idx
|
|
275
|
+
model_kwargs["generate_idx"] = outputs.generate_idx
|
|
276
|
+
return model_kwargs
|
|
277
|
+
|
|
278
|
+
def get_image_features(
|
|
279
|
+
self,
|
|
280
|
+
pixel_values: torch.FloatTensor,
|
|
281
|
+
image_sizes: torch.Tensor,
|
|
282
|
+
vision_feature_layer: Union[int, List[int]],
|
|
283
|
+
vision_feature_select_strategy: str,
|
|
284
|
+
):
|
|
285
|
+
# ! infer image_num_patches from image_sizes
|
|
286
|
+
image_num_patches = [
|
|
287
|
+
image_size_to_num_patches(
|
|
288
|
+
image_size=imsize,
|
|
289
|
+
grid_pinpoints=self.config.image_grid_pinpoints,
|
|
290
|
+
patch_size=self.config.vision_config.image_size,
|
|
291
|
+
)
|
|
292
|
+
for imsize in image_sizes
|
|
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
|
+
|
|
314
|
+
if pixel_values.dim() == 5:
|
|
315
|
+
# stacked if input is (batch_size, num_patches, num_channels, height, width)
|
|
316
|
+
_pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
|
|
317
|
+
pixel_values = torch.cat(_pixel_values_list, dim=0)
|
|
318
|
+
elif pixel_values.dim() != 4:
|
|
319
|
+
# otherwise has to be stacked from list of (num_patches, num_channels, height, width)
|
|
320
|
+
raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
|
|
321
|
+
|
|
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
|
+
|
|
331
|
+
if vision_feature_select_strategy == "default":
|
|
332
|
+
selected_image_feature = selected_image_feature[:, 1:]
|
|
333
|
+
elif vision_feature_select_strategy == "full":
|
|
334
|
+
selected_image_feature = selected_image_feature
|
|
335
|
+
|
|
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
|
|
339
|
+
|
|
340
|
+
def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
|
|
341
|
+
new_image_features = []
|
|
342
|
+
feature_lens = []
|
|
343
|
+
for image_idx, image_feature in enumerate(image_features):
|
|
344
|
+
if image_feature.shape[0] > 1:
|
|
345
|
+
base_image_feature = image_feature[0]
|
|
346
|
+
image_feature = image_feature[1:]
|
|
347
|
+
height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
|
|
348
|
+
|
|
349
|
+
num_patch_height, num_patch_width = get_anyres_image_grid_shape(
|
|
350
|
+
image_sizes[image_idx],
|
|
351
|
+
self.config.image_grid_pinpoints,
|
|
352
|
+
self.config.vision_config.image_size,
|
|
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
|
+
|
|
365
|
+
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
|
366
|
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
|
367
|
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
|
368
|
+
image_feature = unpad_image(image_feature, image_sizes[image_idx])
|
|
369
|
+
if image_newline is not None:
|
|
370
|
+
image_feature = torch.cat(
|
|
371
|
+
(
|
|
372
|
+
image_feature,
|
|
373
|
+
image_newline[:, None, None]
|
|
374
|
+
.expand(*image_feature.shape[:-1], 1)
|
|
375
|
+
.to(image_feature.device, image_feature.dtype),
|
|
376
|
+
),
|
|
377
|
+
dim=-1,
|
|
378
|
+
)
|
|
379
|
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
|
380
|
+
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
|
|
381
|
+
else:
|
|
382
|
+
image_feature = image_feature[0]
|
|
383
|
+
if image_newline is not None:
|
|
384
|
+
image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
|
|
385
|
+
new_image_features.append(image_feature)
|
|
386
|
+
feature_lens.append(image_feature.size(0))
|
|
387
|
+
image_features = torch.cat(new_image_features, dim=0)
|
|
388
|
+
feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
|
|
389
|
+
return image_features, feature_lens
|
|
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
|
+
)
|
|
404
|
+
|
|
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
|
+
)
|
|
410
|
+
|
|
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")
|
|
413
|
+
|
|
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"
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
if inputs_embeds is None:
|
|
420
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
421
|
+
|
|
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
|
+
)
|
|
429
|
+
|
|
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
|
+
)
|
|
437
|
+
|
|
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)
|
|
442
|
+
|
|
443
|
+
return inputs_embeds
|
|
444
|
+
|
|
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]
|
|
465
|
+
|
|
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)
|
|
476
|
+
|
|
477
|
+
logits = torch.cat(logits, dim=0)
|
|
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
|
|
486
|
+
|
|
487
|
+
if not return_dict:
|
|
488
|
+
return logits, generate_idx
|
|
489
|
+
else:
|
|
490
|
+
return RBLNDecoderOnlyOutput(
|
|
491
|
+
logits=logits,
|
|
492
|
+
generate_idx=generate_idx,
|
|
493
|
+
)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
from os import environ
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
this_path = os.path.abspath(__file__)
|
|
20
|
+
local_dir = "/" + os.path.join(*this_path.split("/")[:-1]) + "/hf_hub_cached"
|
|
21
|
+
environ["LOCAL_CACHE_ROOT_CUSTOM_CODE_MIDM"] = local_dir
|
|
22
|
+
|
|
23
|
+
from .configuration_midm import RBLNMidmLMHeadModelConfig
|
|
24
|
+
from .modeling_midm import RBLNMidmLMHeadModel
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from ..decoderonly.configuration_decoderonly import RBLNDecoderOnlyModelForCausalLMConfig
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RBLNMidmLMHeadModelConfig(RBLNDecoderOnlyModelForCausalLMConfig):
|
|
19
|
+
"""
|
|
20
|
+
Configuration class for MIDM models.
|
|
21
|
+
|
|
22
|
+
This class is an alias of RBLNDecoderOnlyModelForCausalLMConfig.
|
|
23
|
+
|
|
24
|
+
Example usage:
|
|
25
|
+
```python
|
|
26
|
+
from optimum.rbln import RBLNMidmLMHeadModel, RBLNMidmLMHeadModelConfig
|
|
27
|
+
|
|
28
|
+
# Create a configuration object
|
|
29
|
+
config = RBLNMidmLMHeadModelConfig(
|
|
30
|
+
batch_size=1,
|
|
31
|
+
max_seq_len=4096,
|
|
32
|
+
tensor_parallel_size=4
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
# Use the configuration with from_pretrained
|
|
36
|
+
model = RBLNMidmLMHeadModel.from_pretrained(
|
|
37
|
+
"KT-AI/midm-bitext-S-7B-inst-v1",
|
|
38
|
+
export=True,
|
|
39
|
+
rbln_config=config
|
|
40
|
+
)
|
|
41
|
+
```
|
|
42
|
+
"""
|