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,104 @@
|
|
|
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 ....utils import logging
|
|
16
|
+
from ...models.decoderonly import RBLNDecoderOnlyModel, RBLNDecoderOnlyModelForCausalLM
|
|
17
|
+
from .gemma_architecture import GemmaWrapper
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
logger = logging.get_logger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RBLNGemmaForCausalLM(RBLNDecoderOnlyModelForCausalLM):
|
|
24
|
+
"""
|
|
25
|
+
The Gemma Model transformer with a language modeling head (linear layer) on top.
|
|
26
|
+
This model inherits from [`RBLNDecoderOnlyModelForCausalLM`]. Check the superclass documentation for the generic methods the library implements for all its models.
|
|
27
|
+
|
|
28
|
+
A class to convert and run pre-trained transformers based GemmaForCausalLM model on RBLN devices.
|
|
29
|
+
It implements the methods to convert a pre-trained transformers GemmaForCausalLM model into a RBLN transformer model by:
|
|
30
|
+
|
|
31
|
+
- transferring the checkpoint weights of the original into an optimized RBLN graph,
|
|
32
|
+
- compiling the resulting graph using the RBLN compiler.
|
|
33
|
+
|
|
34
|
+
**Configuration:**
|
|
35
|
+
This model uses [`RBLNGemmaForCausalLMConfig`] for configuration. When calling methods like `from_pretrained` or `from_model`,
|
|
36
|
+
the `rbln_config` parameter should be an instance of [`RBLNGemmaForCausalLMConfig`] or a dictionary conforming to its structure.
|
|
37
|
+
|
|
38
|
+
See the [`RBLNGemmaForCausalLMConfig`] class for all available configuration options.
|
|
39
|
+
|
|
40
|
+
Examples:
|
|
41
|
+
```python
|
|
42
|
+
from optimum.rbln import RBLNGemmaForCausalLM
|
|
43
|
+
|
|
44
|
+
# Simple usage using rbln_* arguments
|
|
45
|
+
# `max_seq_len` is automatically inferred from the model config
|
|
46
|
+
model = RBLNGemmaForCausalLM.from_pretrained(
|
|
47
|
+
"google/gemma-7b",
|
|
48
|
+
export=True,
|
|
49
|
+
rbln_batch_size=1,
|
|
50
|
+
rbln_tensor_parallel_size=4,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# Using a config dictionary
|
|
55
|
+
rbln_config = {
|
|
56
|
+
"batch_size": 1,
|
|
57
|
+
"max_seq_len": 4096,
|
|
58
|
+
"tensor_parallel_size": 4,
|
|
59
|
+
}
|
|
60
|
+
model = RBLNGemmaForCausalLM.from_pretrained(
|
|
61
|
+
"google/gemma-7b",
|
|
62
|
+
export=True,
|
|
63
|
+
rbln_config=rbln_config
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# Using a RBLNGemmaForCausalLMConfig instance (recommended for type checking)
|
|
68
|
+
from optimum.rbln import RBLNGemmaForCausalLMConfig
|
|
69
|
+
|
|
70
|
+
config = RBLNGemmaForCausalLMConfig(
|
|
71
|
+
batch_size=1,
|
|
72
|
+
max_seq_len=4096,
|
|
73
|
+
tensor_parallel_size=4
|
|
74
|
+
)
|
|
75
|
+
model = RBLNGemmaForCausalLM.from_pretrained(
|
|
76
|
+
"google/gemma-7b",
|
|
77
|
+
export=True,
|
|
78
|
+
rbln_config=config
|
|
79
|
+
)
|
|
80
|
+
```
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
_decoder_wrapper_cls = GemmaWrapper
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class RBLNGemmaModel(RBLNDecoderOnlyModel):
|
|
87
|
+
"""
|
|
88
|
+
The Gemma Model transformer without a language modeling head.
|
|
89
|
+
This model inherits from [`RBLNDecoderOnlyModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
|
|
90
|
+
|
|
91
|
+
A class to convert and run pre-trained transformers based GemmaModel model on RBLN devices.
|
|
92
|
+
It implements the methods to convert a pre-trained transformers GemmaModel model into a RBLN transformer model by:
|
|
93
|
+
|
|
94
|
+
- transferring the checkpoint weights of the original into an optimized RBLN graph,
|
|
95
|
+
- compiling the resulting graph using the RBLN compiler.
|
|
96
|
+
|
|
97
|
+
**Configuration:**
|
|
98
|
+
This model uses [`RBLNGemmaModelConfig`] for configuration. When calling methods like `from_pretrained` or `from_model`,
|
|
99
|
+
the `rbln_config` parameter should be an instance of [`RBLNGemmaModelConfig`] or a dictionary conforming to its structure.
|
|
100
|
+
|
|
101
|
+
See the [`RBLNGemmaModelConfig`] class for all available configuration options.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
_decoder_wrapper_cls = GemmaWrapper
|
|
@@ -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_gemma3 import RBLNGemma3ForCausalLMConfig, RBLNGemma3ForConditionalGenerationConfig
|
|
16
|
+
from .modeling_gemma3 import RBLNGemma3ForCausalLM, RBLNGemma3ForConditionalGeneration
|
|
@@ -0,0 +1,109 @@
|
|
|
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
|
+
from typing import Any, Optional
|
|
15
|
+
|
|
16
|
+
from ....configuration_utils import RBLNModelConfig
|
|
17
|
+
from ....utils.logging import get_logger
|
|
18
|
+
from ..decoderonly.configuration_decoderonly import RBLNDecoderOnlyModelForCausalLMConfig
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
logger = get_logger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RBLNGemma3ForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
use_position_ids: Optional[bool] = None,
|
|
28
|
+
use_attention_mask: Optional[bool] = None,
|
|
29
|
+
prefill_chunk_size: Optional[int] = None,
|
|
30
|
+
image_prefill_chunk_size: Optional[int] = None,
|
|
31
|
+
**kwargs: Any,
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Args:
|
|
35
|
+
use_position_ids (Optional[bool]): Whether or not to use `position_ids`, which is indices of positions of each input sequence tokens in the position embeddings.
|
|
36
|
+
use_attention_mask (Optional[bool]): Whether or not to use `attention_mask` to to avoid performing attention on padding token indices.
|
|
37
|
+
prefill_chunk_size (Optional[int]): The chunk size used during the prefill phase for
|
|
38
|
+
processing input sequences. Defaults to 256. Must be a positive integer
|
|
39
|
+
divisible by 64. Affects prefill performance and memory usage.
|
|
40
|
+
image_prefill_chunk_size (Optional[int]): The chunk size used during the prefill phase for
|
|
41
|
+
processing images. This config is used when `use_image_prefill` is True.
|
|
42
|
+
Currently, the `prefill_chunk_size` and `image_prefill_chunk_size` should be the same value.
|
|
43
|
+
kwargs: Additional arguments passed to the parent `RBLNDecoderOnlyModelForCausalLMConfig`.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
ValueError: If `use_attention_mask` or `use_position_ids` are False.
|
|
47
|
+
"""
|
|
48
|
+
# use_attention_mask and use_position_ids are always True for Gemma3
|
|
49
|
+
use_attention_mask = use_attention_mask or True
|
|
50
|
+
use_position_ids = use_position_ids or True
|
|
51
|
+
prefill_chunk_size = prefill_chunk_size or 256
|
|
52
|
+
|
|
53
|
+
super().__init__(
|
|
54
|
+
prefill_chunk_size=prefill_chunk_size,
|
|
55
|
+
use_attention_mask=use_attention_mask,
|
|
56
|
+
use_position_ids=use_position_ids,
|
|
57
|
+
**kwargs,
|
|
58
|
+
)
|
|
59
|
+
self.image_prefill_chunk_size = image_prefill_chunk_size
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def use_image_prefill(self):
|
|
63
|
+
return self.image_prefill_chunk_size is not None
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def decoder_runtime_idx(self):
|
|
67
|
+
return 2 if self.use_image_prefill else 1
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class RBLNGemma3ForConditionalGenerationConfig(RBLNModelConfig):
|
|
71
|
+
submodules = ["vision_tower", "language_model"]
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
batch_size: Optional[int] = None,
|
|
76
|
+
vision_tower: Optional[RBLNModelConfig] = None,
|
|
77
|
+
language_model: Optional[RBLNModelConfig] = None,
|
|
78
|
+
**kwargs: Any,
|
|
79
|
+
):
|
|
80
|
+
"""
|
|
81
|
+
Args:
|
|
82
|
+
batch_size (Optional[int]): The batch size for inference. Defaults to 1.
|
|
83
|
+
vision_tower (Optional[RBLNModelConfig]): Configuration for the vision encoder component.
|
|
84
|
+
language_model (Optional[RBLNModelConfig]): Configuration for the language model component.
|
|
85
|
+
kwargs: Additional arguments passed to the parent RBLNModelConfig.
|
|
86
|
+
|
|
87
|
+
Raises:
|
|
88
|
+
ValueError: If `batch_size` is not a positive integer.
|
|
89
|
+
"""
|
|
90
|
+
super().__init__(**kwargs)
|
|
91
|
+
self.batch_size = batch_size or 1
|
|
92
|
+
if not isinstance(self.batch_size, int) or self.batch_size < 0:
|
|
93
|
+
raise ValueError(f"batch_size must be a positive integer, got {self.batch_size}")
|
|
94
|
+
|
|
95
|
+
if self.batch_size != 1:
|
|
96
|
+
logger.warning("Ignore batch_size for Gemma3 vision tower. It will be set to 1.")
|
|
97
|
+
|
|
98
|
+
self.vision_tower = self.initialize_submodule_config(
|
|
99
|
+
submodule_config=vision_tower, batch_size=1, force_kwargs=True
|
|
100
|
+
)
|
|
101
|
+
self.language_model = self.initialize_submodule_config(submodule_config=language_model)
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def image_prefill_chunk_size(self):
|
|
105
|
+
return self.language_model.image_prefill_chunk_size
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def prefill_chunk_size(self):
|
|
109
|
+
return self.language_model.prefill_chunk_size
|
|
@@ -0,0 +1,170 @@
|
|
|
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 copy
|
|
16
|
+
from typing import Optional, Tuple, Union
|
|
17
|
+
|
|
18
|
+
import torch
|
|
19
|
+
from transformers.models.gemma3.modeling_gemma3 import Gemma3RMSNorm
|
|
20
|
+
|
|
21
|
+
from ..decoderonly.decoderonly_architecture import (
|
|
22
|
+
DecoderOnlyAttention,
|
|
23
|
+
DecoderOnlyLayer,
|
|
24
|
+
DecoderOnlyModel,
|
|
25
|
+
DecoderOnlyWrapper,
|
|
26
|
+
RotaryEmbedding,
|
|
27
|
+
slice_and_unsqueeze_cos_sin,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Gemma3ForCausalLMWrapper(DecoderOnlyWrapper):
|
|
32
|
+
def get_rotary_emb(self, max_seq_len):
|
|
33
|
+
rotary_emb_global = RotaryEmbedding(config=self.config, max_seq_len_cached=max_seq_len)
|
|
34
|
+
|
|
35
|
+
config = copy.deepcopy(self.config)
|
|
36
|
+
config.rope_theta = config.rope_local_base_freq
|
|
37
|
+
config.rope_scaling = {"rope_type": "default"}
|
|
38
|
+
rotary_emb_local = RotaryEmbedding(config=config, max_seq_len_cached=max_seq_len)
|
|
39
|
+
|
|
40
|
+
return (rotary_emb_global, rotary_emb_local)
|
|
41
|
+
|
|
42
|
+
def get_rbln_attn_class(self):
|
|
43
|
+
return Gemma3Attention
|
|
44
|
+
|
|
45
|
+
def get_rbln_layer_class(self):
|
|
46
|
+
return Gemma3DecoderLayer
|
|
47
|
+
|
|
48
|
+
def get_rbln_model_class(self):
|
|
49
|
+
return Gemma3TextModel
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Gemma3TextModel(DecoderOnlyModel):
|
|
53
|
+
# Different from DecoderOnlyModel, this model has global and local rotary embeddings.
|
|
54
|
+
def forward(
|
|
55
|
+
self,
|
|
56
|
+
input_ids: torch.Tensor = None,
|
|
57
|
+
inputs_embeds: torch.Tensor = None,
|
|
58
|
+
attention_mask: torch.Tensor = None,
|
|
59
|
+
cache_position: torch.Tensor = None,
|
|
60
|
+
position_ids: torch.Tensor = None,
|
|
61
|
+
query_position: torch.Tensor = None,
|
|
62
|
+
past_key_values: Tuple[Tuple[torch.Tensor]] = None,
|
|
63
|
+
rotary_emb: torch.nn.Module = None,
|
|
64
|
+
global_block_tables: Optional[torch.Tensor] = None,
|
|
65
|
+
local_block_tables: Optional[torch.Tensor] = None,
|
|
66
|
+
lora_int_id: Optional[torch.Tensor] = None,
|
|
67
|
+
):
|
|
68
|
+
# retrieve input_ids and inputs_embeds
|
|
69
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
70
|
+
raise ValueError(
|
|
71
|
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# embed positions
|
|
75
|
+
if inputs_embeds is None:
|
|
76
|
+
inputs_embeds = self.get_embedding()(input_ids)
|
|
77
|
+
|
|
78
|
+
hidden_states = inputs_embeds
|
|
79
|
+
|
|
80
|
+
# Global Position Embeddings
|
|
81
|
+
cos_global, sin_global = rotary_emb[0](hidden_states, self.max_seq_len)
|
|
82
|
+
cos_global, sin_global = slice_and_unsqueeze_cos_sin(cos_global, sin_global, position_ids)
|
|
83
|
+
|
|
84
|
+
# Local Position Embeddings
|
|
85
|
+
cos_local, sin_local = rotary_emb[1](hidden_states, self.max_seq_len)
|
|
86
|
+
cos_local, sin_local = slice_and_unsqueeze_cos_sin(cos_local, sin_local, position_ids)
|
|
87
|
+
|
|
88
|
+
# (batch, seq_len) -> (batch,)
|
|
89
|
+
if self.attn_impl == "flash_attn":
|
|
90
|
+
seq_positions = cache_position[:, 0]
|
|
91
|
+
seq_positions = self.convert_sequence_positions_for_flash_attn(
|
|
92
|
+
seq_positions=seq_positions, max_seq_len=self.max_seq_len
|
|
93
|
+
)
|
|
94
|
+
else:
|
|
95
|
+
seq_positions = cache_position[:, :1]
|
|
96
|
+
|
|
97
|
+
sliding_cache_pos = self.get_local_cache_positions(position_ids, query_position)
|
|
98
|
+
|
|
99
|
+
for layer_idx, layer in enumerate(self.layers):
|
|
100
|
+
is_sliding = True if layer_idx in self.sliding_window_layers else False
|
|
101
|
+
hidden_states = layer(
|
|
102
|
+
hidden_states=hidden_states,
|
|
103
|
+
attention_mask=attention_mask,
|
|
104
|
+
seq_positions=sliding_cache_pos if is_sliding else seq_positions,
|
|
105
|
+
past_key_values=past_key_values,
|
|
106
|
+
cos=cos_local if is_sliding else cos_global,
|
|
107
|
+
sin=sin_local if is_sliding else sin_global,
|
|
108
|
+
block_tables=local_block_tables if is_sliding else global_block_tables,
|
|
109
|
+
lora_int_id=lora_int_id,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
hidden_states = self.get_last_layernorm()(hidden_states)
|
|
113
|
+
return hidden_states
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class Gemma3DecoderLayer(DecoderOnlyLayer):
|
|
117
|
+
def get_pre_feedforward_layernorm(self) -> Gemma3RMSNorm:
|
|
118
|
+
return self._original_mod.pre_feedforward_layernorm
|
|
119
|
+
|
|
120
|
+
def get_post_feedforward_layernorm(self) -> Gemma3RMSNorm:
|
|
121
|
+
return self._original_mod.post_feedforward_layernorm
|
|
122
|
+
|
|
123
|
+
def forward(
|
|
124
|
+
self,
|
|
125
|
+
hidden_states: torch.Tensor,
|
|
126
|
+
attention_mask: torch.Tensor,
|
|
127
|
+
seq_positions: Union[torch.LongTensor, Tuple[torch.LongTensor]],
|
|
128
|
+
past_key_values: Tuple[Tuple[torch.Tensor]],
|
|
129
|
+
cos: Optional[torch.Tensor] = None,
|
|
130
|
+
sin: Optional[torch.Tensor] = None,
|
|
131
|
+
block_tables: Optional[torch.Tensor] = None,
|
|
132
|
+
lora_int_id: Optional[torch.Tensor] = None,
|
|
133
|
+
):
|
|
134
|
+
residual = hidden_states
|
|
135
|
+
hidden_states = self.get_pre_attention_layernorm()(hidden_states)
|
|
136
|
+
|
|
137
|
+
hidden_states = self.self_attn(
|
|
138
|
+
hidden_states=hidden_states,
|
|
139
|
+
attention_mask=attention_mask,
|
|
140
|
+
seq_positions=seq_positions,
|
|
141
|
+
past_key_values=past_key_values,
|
|
142
|
+
cos=cos,
|
|
143
|
+
sin=sin,
|
|
144
|
+
block_tables=block_tables,
|
|
145
|
+
lora_int_id=lora_int_id,
|
|
146
|
+
)
|
|
147
|
+
hidden_states = self.get_post_attention_layernorm()(hidden_states)
|
|
148
|
+
hidden_states = residual + hidden_states
|
|
149
|
+
|
|
150
|
+
# Fully Connected
|
|
151
|
+
residual = hidden_states
|
|
152
|
+
hidden_states = self.get_pre_feedforward_layernorm()(hidden_states)
|
|
153
|
+
hidden_states = self.forward_mlp(hidden_states, lora_int_id)
|
|
154
|
+
hidden_states = self.get_post_feedforward_layernorm()(hidden_states)
|
|
155
|
+
hidden_states = residual + hidden_states
|
|
156
|
+
|
|
157
|
+
return hidden_states
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Gemma3Attention(DecoderOnlyAttention):
|
|
161
|
+
def __post_init__(self):
|
|
162
|
+
self.q_proj = self._original_mod.q_proj
|
|
163
|
+
self.k_proj = self._original_mod.k_proj
|
|
164
|
+
self.v_proj = self._original_mod.v_proj
|
|
165
|
+
self.o_proj = self._original_mod.o_proj
|
|
166
|
+
self.q_norm = self._original_mod.q_norm
|
|
167
|
+
self.k_norm = self._original_mod.k_norm
|
|
168
|
+
|
|
169
|
+
def get_attn_scale(self):
|
|
170
|
+
return self._original_mod.config.query_pre_attn_scalar**-0.5
|
|
@@ -0,0 +1,245 @@
|
|
|
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
|
+
from typing import Optional
|
|
15
|
+
|
|
16
|
+
import rebel
|
|
17
|
+
import torch
|
|
18
|
+
|
|
19
|
+
from ...modeling_outputs import RBLNDecoderOnlyOutput, RBLNGemma3ForCausalLMOutput
|
|
20
|
+
from ..decoderonly.decoderonly_runtime_utils import RBLNPytorchRuntime
|
|
21
|
+
from ..decoderonly.modeling_decoderonly import RBLNRuntimeModel
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RBLNGemma3RuntimeModel(RBLNRuntimeModel):
|
|
25
|
+
def __init__(self, *args, image_prefill: Optional[rebel.Runtime] = None, **kwargs):
|
|
26
|
+
super().__init__(*args, **kwargs)
|
|
27
|
+
self.image_prefill = RBLNPytorchRuntime(image_prefill) # FIXME(taehoon)
|
|
28
|
+
self.prefill = RBLNPytorchRuntime(self.runtime) if self.phase == "prefill" else None # FIXME
|
|
29
|
+
self.decode = RBLNPytorchRuntime(self.runtime) if self.phase == "decode" else None
|
|
30
|
+
|
|
31
|
+
def _prepare_prefill_inputs(self, *args, **kwargs):
|
|
32
|
+
(
|
|
33
|
+
inputs,
|
|
34
|
+
cache_position,
|
|
35
|
+
chunked_attention_mask,
|
|
36
|
+
position_ids,
|
|
37
|
+
position_embed,
|
|
38
|
+
padded_cache_lengths,
|
|
39
|
+
query_length,
|
|
40
|
+
token_type_ids,
|
|
41
|
+
) = super()._prepare_prefill_inputs(*args, **kwargs)
|
|
42
|
+
|
|
43
|
+
# chunked_attention_mask shape
|
|
44
|
+
chunked_attention_mask = torch.zeros(1, chunked_attention_mask.shape[-1], dtype=torch.float32)
|
|
45
|
+
|
|
46
|
+
# In case of Gemma3ForConditionalGeneration, the loop counter may not be a prefill_chunk_size,
|
|
47
|
+
# so we cannot guarantee that the last chunk starts at a position that is a multiple of prefill_chunk_size.
|
|
48
|
+
if self.rbln_config.use_image_prefill:
|
|
49
|
+
padding_size = self.rbln_config.image_prefill_chunk_size
|
|
50
|
+
inputs = torch.nn.functional.pad(inputs, (0, 0, 0, padding_size))
|
|
51
|
+
cache_position = torch.nn.functional.pad(cache_position, (0, padding_size))
|
|
52
|
+
position_ids = torch.nn.functional.pad(position_ids, (0, padding_size))
|
|
53
|
+
token_type_ids = torch.nn.functional.pad(token_type_ids, (0, padding_size), value=-1)
|
|
54
|
+
|
|
55
|
+
return (
|
|
56
|
+
inputs,
|
|
57
|
+
cache_position,
|
|
58
|
+
chunked_attention_mask,
|
|
59
|
+
position_ids,
|
|
60
|
+
position_embed,
|
|
61
|
+
padded_cache_lengths,
|
|
62
|
+
query_length,
|
|
63
|
+
token_type_ids,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def prefill_forward(
|
|
67
|
+
self,
|
|
68
|
+
inputs: torch.Tensor,
|
|
69
|
+
cache_position: torch.Tensor = None,
|
|
70
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
71
|
+
batch_idx: int = None,
|
|
72
|
+
block_tables: torch.Tensor = None,
|
|
73
|
+
is_external_block_tables: bool = None,
|
|
74
|
+
position_embed: Optional[torch.Tensor] = None,
|
|
75
|
+
token_type_ids: Optional[torch.Tensor] = None,
|
|
76
|
+
local_block_tables: Optional[torch.Tensor] = None,
|
|
77
|
+
lora_int_ids: Optional[torch.Tensor] = None,
|
|
78
|
+
) -> torch.FloatTensor:
|
|
79
|
+
"""
|
|
80
|
+
Performs chunked prefill for efficient KV-cache updates and memory optimization.
|
|
81
|
+
Instead of processing the entire sequence at once, the input is divided into chunks of size `prefill_chunk_size`,
|
|
82
|
+
and each chunk is processed sequentially. This allows for better memory utilization and compatibility with continuous batching.
|
|
83
|
+
"""
|
|
84
|
+
if self.rbln_config.use_lora and lora_int_ids is None:
|
|
85
|
+
if self.lora_int_ids is None:
|
|
86
|
+
raise ValueError(
|
|
87
|
+
"lora_int_id is required when using LoRA. "
|
|
88
|
+
"You should call set_lora_int_ids() before forward() or pass lora_int_id to forward()."
|
|
89
|
+
)
|
|
90
|
+
if batch_idx is not None:
|
|
91
|
+
lora_int_ids = self.lora_int_ids[batch_idx : batch_idx + 1].clone()
|
|
92
|
+
else:
|
|
93
|
+
lora_int_ids = self.lora_int_ids.clone()
|
|
94
|
+
|
|
95
|
+
(
|
|
96
|
+
inputs,
|
|
97
|
+
cache_position,
|
|
98
|
+
chunked_attention_mask,
|
|
99
|
+
position_ids,
|
|
100
|
+
position_embed,
|
|
101
|
+
padded_cache_lengths,
|
|
102
|
+
query_length,
|
|
103
|
+
token_type_ids,
|
|
104
|
+
) = self._prepare_prefill_inputs(
|
|
105
|
+
inputs, cache_position, attention_mask, position_embed, token_type_ids=token_type_ids
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
step = 0
|
|
109
|
+
while step < query_length:
|
|
110
|
+
if self.rbln_config.use_image_prefill:
|
|
111
|
+
# Check if the prefill chunk is an image prefill
|
|
112
|
+
is_image_prefill = torch.all(
|
|
113
|
+
token_type_ids[:, step : step + self.rbln_config.image_prefill_chunk_size] == 1
|
|
114
|
+
)
|
|
115
|
+
# Check if the prefill chunk is a text prefill which have image_tokens in it.
|
|
116
|
+
is_text_prefill_with_image_tokens = not is_image_prefill and torch.any(
|
|
117
|
+
token_type_ids[:, step : step + self.rbln_config.prefill_chunk_size] == 1
|
|
118
|
+
)
|
|
119
|
+
else:
|
|
120
|
+
is_image_prefill, is_text_prefill_with_image_tokens = False, False
|
|
121
|
+
|
|
122
|
+
# Check if the prefill chunk is the last chunk
|
|
123
|
+
is_last_chunk = step + self.rbln_config.prefill_chunk_size >= query_length
|
|
124
|
+
|
|
125
|
+
input_chunk = inputs[:, step : step + self.rbln_config.prefill_chunk_size]
|
|
126
|
+
cache_pos_chunk = (
|
|
127
|
+
cache_position[:, step : step + self.rbln_config.prefill_chunk_size] + padded_cache_lengths
|
|
128
|
+
)
|
|
129
|
+
position_ids_chunk = position_ids[:, step : step + self.rbln_config.prefill_chunk_size]
|
|
130
|
+
|
|
131
|
+
# if text_prefill end with image_tokens, we only treat the text part.
|
|
132
|
+
num_processed_tokens = self.rbln_config.prefill_chunk_size
|
|
133
|
+
current_padded_cache_lengths = 0
|
|
134
|
+
if is_text_prefill_with_image_tokens:
|
|
135
|
+
first_image_token_idx = torch.where(
|
|
136
|
+
token_type_ids[:, step : step + self.rbln_config.prefill_chunk_size] == 1
|
|
137
|
+
)[1][0]
|
|
138
|
+
num_processed_tokens = first_image_token_idx.item()
|
|
139
|
+
current_padded_cache_lengths = self.rbln_config.prefill_chunk_size - num_processed_tokens
|
|
140
|
+
if is_last_chunk:
|
|
141
|
+
num_processed_tokens = query_length - step
|
|
142
|
+
|
|
143
|
+
chunked_attention_mask[
|
|
144
|
+
:, step + padded_cache_lengths : step + num_processed_tokens + padded_cache_lengths
|
|
145
|
+
] = 1
|
|
146
|
+
query_position = torch.tensor(num_processed_tokens - 1, dtype=torch.int16)
|
|
147
|
+
|
|
148
|
+
if is_image_prefill:
|
|
149
|
+
logits = self.image_prefill(
|
|
150
|
+
input_chunk,
|
|
151
|
+
cache_pos_chunk,
|
|
152
|
+
block_tables,
|
|
153
|
+
local_block_tables,
|
|
154
|
+
query_position,
|
|
155
|
+
chunked_attention_mask,
|
|
156
|
+
position_ids_chunk,
|
|
157
|
+
lora_int_ids if self.rbln_config.use_lora else None,
|
|
158
|
+
)
|
|
159
|
+
else:
|
|
160
|
+
logits = self.prefill(
|
|
161
|
+
input_chunk,
|
|
162
|
+
cache_pos_chunk,
|
|
163
|
+
block_tables,
|
|
164
|
+
local_block_tables,
|
|
165
|
+
query_position,
|
|
166
|
+
chunked_attention_mask,
|
|
167
|
+
position_ids_chunk,
|
|
168
|
+
lora_int_ids if self.rbln_config.use_lora else None,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
padded_cache_lengths += current_padded_cache_lengths
|
|
172
|
+
step += num_processed_tokens
|
|
173
|
+
|
|
174
|
+
if not is_external_block_tables:
|
|
175
|
+
self.dec_attn_mask[batch_idx : batch_idx + 1] = chunked_attention_mask
|
|
176
|
+
|
|
177
|
+
return RBLNGemma3ForCausalLMOutput(
|
|
178
|
+
logits=logits, padded_cache_lengths=padded_cache_lengths, attention_mask=chunked_attention_mask
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def decode_forward(
|
|
182
|
+
self,
|
|
183
|
+
inputs: torch.Tensor,
|
|
184
|
+
cache_position: torch.Tensor = None,
|
|
185
|
+
block_tables: torch.Tensor = None,
|
|
186
|
+
is_external_block_tables: bool = None,
|
|
187
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
188
|
+
position_embed: Optional[torch.Tensor] = None,
|
|
189
|
+
position_ids: Optional[torch.Tensor] = None,
|
|
190
|
+
local_block_tables: Optional[torch.Tensor] = None,
|
|
191
|
+
lora_int_ids: Optional[torch.Tensor] = None,
|
|
192
|
+
) -> torch.FloatTensor:
|
|
193
|
+
if self.rbln_config.use_lora and lora_int_ids is None:
|
|
194
|
+
if self.lora_int_ids is None:
|
|
195
|
+
raise ValueError(
|
|
196
|
+
"lora_int_id is required when using LoRA. "
|
|
197
|
+
"You should call set_lora_int_ids() before forward() or pass lora_int_id to forward()."
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
lora_int_ids = self.lora_int_ids
|
|
201
|
+
|
|
202
|
+
if lora_int_ids is not None and lora_int_ids.shape[0] != self.batch_size:
|
|
203
|
+
raise ValueError(f"lora_int_ids size mismatch: got {lora_int_ids.shape[0]}, expected {self.batch_size}.")
|
|
204
|
+
|
|
205
|
+
batch_size = inputs.shape[0]
|
|
206
|
+
if batch_size != self.batch_size:
|
|
207
|
+
raise RuntimeError(
|
|
208
|
+
f"Batch size mismatch: got {batch_size}, expected {self.batch_size} (compiled batch size)."
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
if batch_size != cache_position.shape[0]:
|
|
212
|
+
raise RuntimeError(f"Cache position size mismatch: got {cache_position.shape[0]}, expected {batch_size}.")
|
|
213
|
+
|
|
214
|
+
# FIXME(taehoon): how to handle pos_attn_mask with external block tables
|
|
215
|
+
if is_external_block_tables:
|
|
216
|
+
if attention_mask is None:
|
|
217
|
+
raise ValueError("attention_mask should be provided with external block tables.")
|
|
218
|
+
if local_block_tables is None:
|
|
219
|
+
raise ValueError("local_block_tables should be provided with external block tables.")
|
|
220
|
+
else:
|
|
221
|
+
local_block_tables = (
|
|
222
|
+
local_block_tables
|
|
223
|
+
if local_block_tables is not None
|
|
224
|
+
else torch.arange(0, self.batch_size, dtype=torch.int16).view(self.batch_size, -1)
|
|
225
|
+
)
|
|
226
|
+
if self.rbln_config.use_attention_mask and attention_mask is None:
|
|
227
|
+
for b_idx in range(batch_size):
|
|
228
|
+
decoding_step = cache_position[b_idx].item()
|
|
229
|
+
if not (0 <= decoding_step < self.dec_attn_mask.shape[-1]):
|
|
230
|
+
raise ValueError(
|
|
231
|
+
f"Decoding step {decoding_step} out of bounds for attention mask with shape {self.dec_attn_mask.shape}."
|
|
232
|
+
)
|
|
233
|
+
self.dec_attn_mask[b_idx, decoding_step] = 1
|
|
234
|
+
|
|
235
|
+
attention_mask = self.dec_attn_mask
|
|
236
|
+
|
|
237
|
+
if self.batch_size < block_tables.shape[0]:
|
|
238
|
+
block_tables = block_tables[: self.batch_size]
|
|
239
|
+
|
|
240
|
+
if attention_mask is not None and self.batch_size < attention_mask.shape[0]:
|
|
241
|
+
attention_mask = attention_mask[: self.batch_size]
|
|
242
|
+
|
|
243
|
+
logits = self.decode(inputs, cache_position, block_tables, local_block_tables, attention_mask, position_ids)
|
|
244
|
+
|
|
245
|
+
return RBLNDecoderOnlyOutput(logits=logits)
|