transformers 5.0.0rc1__py3-none-any.whl → 5.0.0rc2__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.
- transformers/__init__.py +20 -1
- transformers/activations.py +1 -1
- transformers/audio_utils.py +0 -1
- transformers/cache_utils.py +17 -15
- transformers/configuration_utils.py +114 -70
- transformers/conversion_mapping.py +68 -5
- transformers/core_model_loading.py +201 -35
- transformers/dependency_versions_table.py +1 -1
- transformers/feature_extraction_utils.py +54 -22
- transformers/generation/candidate_generator.py +79 -31
- transformers/generation/configuration_utils.py +162 -122
- transformers/generation/continuous_batching/cache.py +47 -18
- transformers/generation/continuous_batching/cache_manager.py +131 -34
- transformers/generation/continuous_batching/continuous_api.py +101 -64
- transformers/generation/continuous_batching/requests.py +28 -1
- transformers/generation/continuous_batching/scheduler.py +11 -4
- transformers/generation/stopping_criteria.py +1 -1
- transformers/generation/utils.py +108 -110
- transformers/generation/watermarking.py +8 -5
- transformers/image_processing_base.py +2 -12
- transformers/image_processing_utils_fast.py +15 -4
- transformers/initialization.py +37 -0
- transformers/integrations/__init__.py +12 -0
- transformers/integrations/accelerate.py +44 -111
- transformers/integrations/aqlm.py +3 -5
- transformers/integrations/awq.py +2 -5
- transformers/integrations/bitnet.py +5 -8
- transformers/integrations/bitsandbytes.py +16 -15
- transformers/integrations/deepspeed.py +18 -3
- transformers/integrations/eetq.py +3 -5
- transformers/integrations/fbgemm_fp8.py +1 -1
- transformers/integrations/finegrained_fp8.py +6 -16
- transformers/integrations/flash_attention.py +2 -2
- transformers/integrations/higgs.py +2 -5
- transformers/integrations/hub_kernels.py +23 -5
- transformers/integrations/integration_utils.py +35 -0
- transformers/integrations/mistral.py +12 -0
- transformers/integrations/moe.py +240 -0
- transformers/integrations/mxfp4.py +4 -10
- transformers/integrations/peft.py +5 -0
- transformers/integrations/quanto.py +5 -2
- transformers/integrations/spqr.py +3 -5
- transformers/integrations/tensor_parallel.py +167 -221
- transformers/integrations/vptq.py +3 -5
- transformers/modeling_gguf_pytorch_utils.py +66 -19
- transformers/modeling_rope_utils.py +78 -81
- transformers/modeling_utils.py +583 -503
- transformers/models/__init__.py +19 -0
- transformers/models/afmoe/modeling_afmoe.py +7 -16
- transformers/models/afmoe/modular_afmoe.py +5 -13
- transformers/models/aimv2/modeling_aimv2.py +4 -0
- transformers/models/aimv2/modular_aimv2.py +4 -0
- transformers/models/albert/modeling_albert.py +3 -0
- transformers/models/align/modeling_align.py +12 -6
- transformers/models/altclip/modeling_altclip.py +7 -3
- transformers/models/apertus/modeling_apertus.py +4 -2
- transformers/models/apertus/modular_apertus.py +4 -1
- transformers/models/arcee/modeling_arcee.py +1 -1
- transformers/models/aria/modeling_aria.py +8 -4
- transformers/models/aria/modular_aria.py +7 -3
- transformers/models/audioflamingo3/processing_audioflamingo3.py +27 -22
- transformers/models/auto/auto_factory.py +1 -1
- transformers/models/auto/configuration_auto.py +27 -0
- transformers/models/auto/feature_extraction_auto.py +7 -3
- transformers/models/auto/image_processing_auto.py +4 -2
- transformers/models/auto/modeling_auto.py +31 -0
- transformers/models/auto/processing_auto.py +4 -0
- transformers/models/auto/tokenization_auto.py +132 -153
- transformers/models/auto/video_processing_auto.py +5 -2
- transformers/models/aya_vision/modeling_aya_vision.py +7 -3
- transformers/models/bamba/modeling_bamba.py +18 -19
- transformers/models/bamba/modular_bamba.py +17 -16
- transformers/models/bark/modeling_bark.py +9 -0
- transformers/models/bart/configuration_bart.py +0 -1
- transformers/models/bart/modeling_bart.py +7 -0
- transformers/models/beit/image_processing_beit_fast.py +0 -1
- transformers/models/bert/modeling_bert.py +3 -0
- transformers/models/bert_generation/modeling_bert_generation.py +2 -0
- transformers/models/big_bird/modeling_big_bird.py +3 -0
- transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py +7 -0
- transformers/models/bit/modeling_bit.py +5 -1
- transformers/models/bitnet/modeling_bitnet.py +1 -1
- transformers/models/blenderbot/modeling_blenderbot.py +7 -0
- transformers/models/blenderbot/tokenization_blenderbot.py +6 -7
- transformers/models/blenderbot_small/modeling_blenderbot_small.py +7 -0
- transformers/models/blip/modeling_blip.py +2 -0
- transformers/models/blip/modeling_blip_text.py +8 -0
- transformers/models/blip_2/modeling_blip_2.py +2 -0
- transformers/models/bloom/modeling_bloom.py +13 -44
- transformers/models/blt/modeling_blt.py +162 -2
- transformers/models/blt/modular_blt.py +168 -3
- transformers/models/bridgetower/image_processing_bridgetower_fast.py +0 -2
- transformers/models/bridgetower/modeling_bridgetower.py +6 -0
- transformers/models/bros/modeling_bros.py +8 -0
- transformers/models/camembert/modeling_camembert.py +109 -106
- transformers/models/canine/modeling_canine.py +6 -0
- transformers/models/canine/tokenization_canine.py +2 -0
- transformers/models/chameleon/modeling_chameleon.py +9 -4
- transformers/models/chinese_clip/modeling_chinese_clip.py +6 -3
- transformers/models/clap/feature_extraction_clap.py +2 -2
- transformers/models/clap/modeling_clap.py +25 -15
- transformers/models/clip/modeling_clip.py +2 -0
- transformers/models/clipseg/modeling_clipseg.py +4 -0
- transformers/models/clvp/modeling_clvp.py +14 -3
- transformers/models/code_llama/tokenization_code_llama.py +1 -1
- transformers/models/codegen/modeling_codegen.py +13 -4
- transformers/models/cohere/modeling_cohere.py +1 -1
- transformers/models/cohere2/modeling_cohere2.py +1 -1
- transformers/models/cohere2_vision/image_processing_cohere2_vision_fast.py +0 -1
- transformers/models/cohere2_vision/modeling_cohere2_vision.py +7 -3
- transformers/models/conditional_detr/configuration_conditional_detr.py +1 -1
- transformers/models/conditional_detr/modeling_conditional_detr.py +4 -1
- transformers/models/convbert/modeling_convbert.py +3 -0
- transformers/models/convnext/image_processing_convnext.py +2 -2
- transformers/models/convnext/image_processing_convnext_fast.py +9 -13
- transformers/models/csm/generation_csm.py +19 -22
- transformers/models/csm/modeling_csm.py +3 -1
- transformers/models/csm/modular_csm.py +2 -0
- transformers/models/ctrl/modeling_ctrl.py +14 -2
- transformers/models/cvt/modeling_cvt.py +5 -1
- transformers/models/cwm/modeling_cwm.py +1 -1
- transformers/models/d_fine/configuration_d_fine.py +3 -4
- transformers/models/d_fine/modeling_d_fine.py +46 -39
- transformers/models/d_fine/modular_d_fine.py +15 -4
- transformers/models/dab_detr/configuration_dab_detr.py +2 -2
- transformers/models/dab_detr/modeling_dab_detr.py +1 -1
- transformers/models/dac/modeling_dac.py +4 -4
- transformers/models/data2vec/modeling_data2vec_text.py +7 -0
- transformers/models/data2vec/modular_data2vec_text.py +7 -0
- transformers/models/dbrx/configuration_dbrx.py +9 -1
- transformers/models/dbrx/modeling_dbrx.py +1 -1
- transformers/models/deberta/modeling_deberta.py +2 -0
- transformers/models/deberta_v2/modeling_deberta_v2.py +2 -0
- transformers/models/decision_transformer/modeling_decision_transformer.py +8 -5
- transformers/models/deepseek_v2/modeling_deepseek_v2.py +7 -4
- transformers/models/deepseek_v2/modular_deepseek_v2.py +4 -2
- transformers/models/deepseek_v3/modeling_deepseek_v3.py +9 -5
- transformers/models/deepseek_v3/modular_deepseek_v3.py +6 -2
- transformers/models/deepseek_vl/image_processing_deepseek_vl_fast.py +0 -1
- transformers/models/deepseek_vl/modeling_deepseek_vl.py +9 -5
- transformers/models/deepseek_vl/modular_deepseek_vl.py +3 -0
- transformers/models/deepseek_vl_hybrid/image_processing_deepseek_vl_hybrid_fast.py +0 -4
- transformers/models/deepseek_vl_hybrid/modeling_deepseek_vl_hybrid.py +9 -5
- transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py +9 -9
- transformers/models/deformable_detr/configuration_deformable_detr.py +2 -2
- transformers/models/deformable_detr/modeling_deformable_detr.py +1 -1
- transformers/models/depth_anything/configuration_depth_anything.py +2 -3
- transformers/models/depth_pro/image_processing_depth_pro_fast.py +0 -1
- transformers/models/detr/configuration_detr.py +1 -1
- transformers/models/detr/modeling_detr.py +8 -1
- transformers/models/dia/generation_dia.py +3 -10
- transformers/models/dia/modeling_dia.py +12 -1
- transformers/models/dia/modular_dia.py +11 -0
- transformers/models/dia/processing_dia.py +1 -1
- transformers/models/diffllama/modeling_diffllama.py +3 -3
- transformers/models/diffllama/modular_diffllama.py +2 -2
- transformers/models/dinov3_vit/image_processing_dinov3_vit_fast.py +0 -1
- transformers/models/dinov3_vit/modeling_dinov3_vit.py +3 -0
- transformers/models/dinov3_vit/modular_dinov3_vit.py +3 -0
- transformers/models/distilbert/modeling_distilbert.py +11 -9
- transformers/models/doge/modeling_doge.py +1 -1
- transformers/models/donut/image_processing_donut_fast.py +0 -1
- transformers/models/donut/modeling_donut_swin.py +16 -12
- transformers/models/dots1/modeling_dots1.py +14 -5
- transformers/models/dpt/configuration_dpt.py +1 -1
- transformers/models/dpt/image_processing_dpt_fast.py +1 -2
- transformers/models/dpt/modular_dpt.py +1 -2
- transformers/models/edgetam/configuration_edgetam.py +1 -1
- transformers/models/edgetam/modeling_edgetam.py +5 -2
- transformers/models/edgetam/modular_edgetam.py +15 -14
- transformers/models/edgetam_video/modeling_edgetam_video.py +55 -43
- transformers/models/edgetam_video/modular_edgetam_video.py +13 -19
- transformers/models/efficientloftr/image_processing_efficientloftr_fast.py +1 -2
- transformers/models/efficientloftr/modeling_efficientloftr.py +14 -1
- transformers/models/efficientnet/image_processing_efficientnet.py +5 -6
- transformers/models/efficientnet/image_processing_efficientnet_fast.py +1 -2
- transformers/models/efficientnet/modeling_efficientnet.py +5 -1
- transformers/models/electra/modeling_electra.py +7 -0
- transformers/models/emu3/modeling_emu3.py +8 -2
- transformers/models/emu3/modular_emu3.py +7 -1
- transformers/models/encodec/modeling_encodec.py +14 -0
- transformers/models/eomt/image_processing_eomt_fast.py +46 -14
- transformers/models/eomt/modeling_eomt.py +7 -0
- transformers/models/eomt/modular_eomt.py +7 -0
- transformers/models/ernie/modeling_ernie.py +6 -0
- transformers/models/ernie/modular_ernie.py +6 -0
- transformers/models/ernie4_5/modeling_ernie4_5.py +1 -1
- transformers/models/ernie4_5_moe/modeling_ernie4_5_moe.py +16 -13
- transformers/models/ernie4_5_moe/modular_ernie4_5_moe.py +9 -35
- transformers/models/ernie4_5_vl_moe/__init__.py +31 -0
- transformers/models/ernie4_5_vl_moe/configuration_ernie4_5_vl_moe.py +330 -0
- transformers/models/ernie4_5_vl_moe/image_processing_ernie4_5_vl_moe.py +456 -0
- transformers/models/ernie4_5_vl_moe/image_processing_ernie4_5_vl_moe_fast.py +232 -0
- transformers/models/ernie4_5_vl_moe/modeling_ernie4_5_vl_moe.py +1898 -0
- transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py +1904 -0
- transformers/models/ernie4_5_vl_moe/processing_ernie4_5_vl_moe.py +251 -0
- transformers/models/ernie4_5_vl_moe/video_processing_ernie4_5_vl_moe.py +594 -0
- transformers/models/esm/modeling_esm.py +6 -0
- transformers/models/esm/modeling_esmfold.py +6 -1
- transformers/models/evolla/modeling_evolla.py +9 -1
- transformers/models/evolla/modular_evolla.py +8 -0
- transformers/models/exaone4/modeling_exaone4.py +1 -1
- transformers/models/falcon/modeling_falcon.py +3 -3
- transformers/models/falcon_h1/modeling_falcon_h1.py +28 -23
- transformers/models/falcon_h1/modular_falcon_h1.py +7 -2
- transformers/models/falcon_mamba/modeling_falcon_mamba.py +6 -2
- transformers/models/falcon_mamba/modular_falcon_mamba.py +7 -2
- transformers/models/fast_vlm/modeling_fast_vlm.py +7 -3
- transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py +23 -10
- transformers/models/fastspeech2_conformer/tokenization_fastspeech2_conformer.py +1 -0
- transformers/models/flaubert/modeling_flaubert.py +14 -15
- transformers/models/flava/image_processing_flava_fast.py +0 -2
- transformers/models/flava/modeling_flava.py +4 -1
- transformers/models/flex_olmo/modeling_flex_olmo.py +7 -4
- transformers/models/florence2/modeling_florence2.py +20 -3
- transformers/models/florence2/modular_florence2.py +13 -0
- transformers/models/fnet/modeling_fnet.py +7 -0
- transformers/models/fuyu/image_processing_fuyu.py +1 -1
- transformers/models/fuyu/modeling_fuyu.py +3 -1
- transformers/models/fuyu/processing_fuyu.py +16 -0
- transformers/models/gemma/modeling_gemma.py +10 -12
- transformers/models/gemma/modular_gemma.py +9 -11
- transformers/models/gemma2/modeling_gemma2.py +1 -1
- transformers/models/gemma2/modular_gemma2.py +1 -1
- transformers/models/gemma3/image_processing_gemma3_fast.py +0 -1
- transformers/models/gemma3/modeling_gemma3.py +28 -7
- transformers/models/gemma3/modular_gemma3.py +26 -6
- transformers/models/gemma3n/configuration_gemma3n.py +3 -0
- transformers/models/gemma3n/modeling_gemma3n.py +47 -9
- transformers/models/gemma3n/modular_gemma3n.py +51 -9
- transformers/models/git/modeling_git.py +181 -126
- transformers/models/glm/modeling_glm.py +1 -1
- transformers/models/glm4/modeling_glm4.py +1 -1
- transformers/models/glm46v/image_processing_glm46v.py +0 -4
- transformers/models/glm46v/modeling_glm46v.py +3 -1
- transformers/models/glm46v/modular_glm46v.py +3 -0
- transformers/models/glm4_moe/modeling_glm4_moe.py +9 -5
- transformers/models/glm4_moe/modular_glm4_moe.py +1 -1
- transformers/models/glm4v/image_processing_glm4v.py +0 -4
- transformers/models/glm4v/modeling_glm4v.py +15 -5
- transformers/models/glm4v/modular_glm4v.py +11 -3
- transformers/models/glm4v_moe/modeling_glm4v_moe.py +39 -23
- transformers/models/glm4v_moe/modular_glm4v_moe.py +12 -0
- transformers/models/glmasr/__init__.py +30 -0
- transformers/models/glmasr/configuration_glmasr.py +197 -0
- transformers/models/glmasr/modeling_glmasr.py +512 -0
- transformers/models/glmasr/modular_glmasr.py +433 -0
- transformers/models/glmasr/processing_glmasr.py +332 -0
- transformers/models/glpn/image_processing_glpn_fast.py +0 -1
- transformers/models/got_ocr2/image_processing_got_ocr2_fast.py +0 -1
- transformers/models/got_ocr2/modeling_got_ocr2.py +8 -3
- transformers/models/gpt2/modeling_gpt2.py +8 -5
- transformers/models/gpt_bigcode/modeling_gpt_bigcode.py +3 -8
- transformers/models/gpt_neo/modeling_gpt_neo.py +15 -3
- transformers/models/gpt_neox/modeling_gpt_neox.py +1 -1
- transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py +1 -1
- transformers/models/gpt_oss/configuration_gpt_oss.py +17 -0
- transformers/models/gpt_oss/modeling_gpt_oss.py +6 -9
- transformers/models/gpt_oss/modular_gpt_oss.py +5 -7
- transformers/models/gptj/modeling_gptj.py +15 -6
- transformers/models/granite/modeling_granite.py +1 -1
- transformers/models/granite_speech/modeling_granite_speech.py +15 -1
- transformers/models/granitemoe/modeling_granitemoe.py +2 -3
- transformers/models/granitemoe/modular_granitemoe.py +1 -2
- transformers/models/granitemoehybrid/configuration_granitemoehybrid.py +4 -0
- transformers/models/granitemoehybrid/modeling_granitemoehybrid.py +33 -23
- transformers/models/granitemoehybrid/modular_granitemoehybrid.py +12 -2
- transformers/models/granitemoeshared/modeling_granitemoeshared.py +2 -3
- transformers/models/grounding_dino/configuration_grounding_dino.py +2 -3
- transformers/models/grounding_dino/modeling_grounding_dino.py +4 -4
- transformers/models/groupvit/modeling_groupvit.py +6 -1
- transformers/models/helium/modeling_helium.py +1 -1
- transformers/models/hgnet_v2/modeling_hgnet_v2.py +10 -0
- transformers/models/hgnet_v2/modular_hgnet_v2.py +10 -0
- transformers/models/hubert/modeling_hubert.py +4 -0
- transformers/models/hubert/modular_hubert.py +4 -0
- transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py +1 -1
- transformers/models/hunyuan_v1_dense/modular_hunyuan_v1_dense.py +1 -1
- transformers/models/hunyuan_v1_moe/__init__.py +1 -1
- transformers/models/hunyuan_v1_moe/modeling_hunyuan_v1_moe.py +12 -4
- transformers/models/hunyuan_v1_moe/modular_hunyuan_v1_moe.py +4 -2
- transformers/models/ibert/modeling_ibert.py +16 -0
- transformers/models/idefics/modeling_idefics.py +10 -0
- transformers/models/idefics2/modeling_idefics2.py +7 -1
- transformers/models/idefics3/modeling_idefics3.py +5 -1
- transformers/models/imagegpt/image_processing_imagegpt_fast.py +1 -5
- transformers/models/imagegpt/modeling_imagegpt.py +9 -2
- transformers/models/instructblip/modeling_instructblip.py +2 -0
- transformers/models/instructblipvideo/modeling_instructblipvideo.py +52 -50
- transformers/models/instructblipvideo/video_processing_instructblipvideo.py +0 -1
- transformers/models/internvl/modeling_internvl.py +11 -8
- transformers/models/internvl/modular_internvl.py +5 -9
- transformers/models/internvl/video_processing_internvl.py +0 -1
- transformers/models/jais2/__init__.py +27 -0
- transformers/models/jais2/configuration_jais2.py +152 -0
- transformers/models/jais2/modeling_jais2.py +486 -0
- transformers/models/jais2/modular_jais2.py +196 -0
- transformers/models/jamba/modeling_jamba.py +24 -19
- transformers/models/jamba/modular_jamba.py +17 -17
- transformers/models/janus/image_processing_janus_fast.py +0 -1
- transformers/models/janus/modeling_janus.py +15 -7
- transformers/models/janus/modular_janus.py +16 -7
- transformers/models/jetmoe/modeling_jetmoe.py +2 -2
- transformers/models/jetmoe/modular_jetmoe.py +1 -0
- transformers/models/kosmos2/modeling_kosmos2.py +14 -2
- transformers/models/kosmos2_5/image_processing_kosmos2_5_fast.py +2 -2
- transformers/models/kosmos2_5/modeling_kosmos2_5.py +10 -1
- transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py +9 -3
- transformers/models/kyutai_speech_to_text/modular_kyutai_speech_to_text.py +9 -1
- transformers/models/lasr/configuration_lasr.py +4 -0
- transformers/models/lasr/modeling_lasr.py +3 -2
- transformers/models/lasr/modular_lasr.py +8 -1
- transformers/models/lasr/processing_lasr.py +0 -2
- transformers/models/layoutlm/modeling_layoutlm.py +5 -3
- transformers/models/layoutlmv2/image_processing_layoutlmv2_fast.py +0 -1
- transformers/models/layoutlmv2/modeling_layoutlmv2.py +12 -0
- transformers/models/layoutlmv2/tokenization_layoutlmv2.py +1 -0
- transformers/models/layoutlmv3/image_processing_layoutlmv3_fast.py +0 -1
- transformers/models/layoutlmv3/modeling_layoutlmv3.py +29 -5
- transformers/models/led/modeling_led.py +6 -0
- transformers/models/levit/modeling_levit.py +18 -0
- transformers/models/lfm2/modeling_lfm2.py +1 -1
- transformers/models/lfm2_moe/modeling_lfm2_moe.py +14 -4
- transformers/models/lfm2_moe/modular_lfm2_moe.py +5 -28
- transformers/models/lfm2_vl/configuration_lfm2_vl.py +4 -0
- transformers/models/lfm2_vl/modeling_lfm2_vl.py +11 -5
- transformers/models/lfm2_vl/modular_lfm2_vl.py +4 -2
- transformers/models/lfm2_vl/processing_lfm2_vl.py +82 -42
- transformers/models/lightglue/image_processing_lightglue_fast.py +1 -2
- transformers/models/lilt/modeling_lilt.py +19 -15
- transformers/models/llama/modeling_llama.py +1 -1
- transformers/models/llama4/image_processing_llama4_fast.py +1 -2
- transformers/models/llama4/modeling_llama4.py +8 -4
- transformers/models/llava/image_processing_llava_fast.py +0 -1
- transformers/models/llava/modeling_llava.py +12 -7
- transformers/models/llava_next/image_processing_llava_next_fast.py +0 -1
- transformers/models/llava_next/modeling_llava_next.py +7 -3
- transformers/models/llava_next_video/modeling_llava_next_video.py +7 -3
- transformers/models/llava_next_video/modular_llava_next_video.py +7 -3
- transformers/models/llava_onevision/image_processing_llava_onevision_fast.py +0 -1
- transformers/models/llava_onevision/modeling_llava_onevision.py +7 -3
- transformers/models/llava_onevision/modular_llava_onevision.py +7 -4
- transformers/models/longcat_flash/modeling_longcat_flash.py +2 -1
- transformers/models/longcat_flash/modular_longcat_flash.py +1 -0
- transformers/models/longt5/modeling_longt5.py +0 -4
- transformers/models/m2m_100/modeling_m2m_100.py +10 -0
- transformers/models/mamba/modeling_mamba.py +2 -1
- transformers/models/mamba2/modeling_mamba2.py +24 -23
- transformers/models/marian/configuration_marian.py +1 -1
- transformers/models/marian/modeling_marian.py +3 -0
- transformers/models/markuplm/modeling_markuplm.py +5 -8
- transformers/models/mask2former/configuration_mask2former.py +3 -3
- transformers/models/mask2former/image_processing_mask2former_fast.py +1 -4
- transformers/models/mask2former/modeling_mask2former.py +9 -0
- transformers/models/maskformer/configuration_maskformer.py +3 -3
- transformers/models/maskformer/image_processing_maskformer_fast.py +1 -4
- transformers/models/maskformer/modeling_maskformer.py +9 -1
- transformers/models/maskformer/modeling_maskformer_swin.py +19 -15
- transformers/models/mbart/configuration_mbart.py +1 -0
- transformers/models/mbart/modeling_mbart.py +7 -0
- transformers/models/megatron_bert/modeling_megatron_bert.py +2 -0
- transformers/models/metaclip_2/modeling_metaclip_2.py +2 -0
- transformers/models/metaclip_2/modular_metaclip_2.py +2 -0
- transformers/models/mimi/modeling_mimi.py +25 -4
- transformers/models/minimax/modeling_minimax.py +16 -3
- transformers/models/minimax/modular_minimax.py +12 -1
- transformers/models/ministral/modeling_ministral.py +1 -1
- transformers/models/ministral3/modeling_ministral3.py +1 -1
- transformers/models/mistral/modeling_mistral.py +1 -1
- transformers/models/mistral3/modeling_mistral3.py +10 -4
- transformers/models/mistral3/modular_mistral3.py +3 -1
- transformers/models/mixtral/modeling_mixtral.py +12 -4
- transformers/models/mixtral/modular_mixtral.py +6 -2
- transformers/models/mlcd/modeling_mlcd.py +6 -0
- transformers/models/mlcd/modular_mlcd.py +4 -0
- transformers/models/mllama/modeling_mllama.py +13 -2
- transformers/models/mm_grounding_dino/configuration_mm_grounding_dino.py +1 -2
- transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py +4 -4
- transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py +1 -2
- transformers/models/mobilebert/modeling_mobilebert.py +2 -0
- transformers/models/mobilenet_v2/image_processing_mobilenet_v2_fast.py +0 -1
- transformers/models/mobilevit/image_processing_mobilevit.py +5 -5
- transformers/models/mobilevit/image_processing_mobilevit_fast.py +1 -2
- transformers/models/mobilevit/modeling_mobilevit.py +4 -0
- transformers/models/mobilevitv2/modeling_mobilevitv2.py +4 -0
- transformers/models/modernbert/modeling_modernbert.py +12 -1
- transformers/models/modernbert/modular_modernbert.py +12 -1
- transformers/models/modernbert_decoder/modeling_modernbert_decoder.py +9 -1
- transformers/models/modernbert_decoder/modular_modernbert_decoder.py +9 -1
- transformers/models/moonshine/modeling_moonshine.py +1 -1
- transformers/models/moshi/modeling_moshi.py +21 -51
- transformers/models/mpnet/modeling_mpnet.py +2 -0
- transformers/models/mra/modeling_mra.py +4 -1
- transformers/models/mt5/configuration_mt5.py +2 -3
- transformers/models/mt5/modeling_mt5.py +0 -10
- transformers/models/musicgen/modeling_musicgen.py +5 -9
- transformers/models/musicgen_melody/modeling_musicgen_melody.py +4 -0
- transformers/models/mvp/modeling_mvp.py +7 -0
- transformers/models/nanochat/modeling_nanochat.py +1 -1
- transformers/models/nemotron/modeling_nemotron.py +3 -3
- transformers/models/nllb_moe/configuration_nllb_moe.py +1 -0
- transformers/models/nllb_moe/modeling_nllb_moe.py +10 -0
- transformers/models/nougat/image_processing_nougat_fast.py +0 -1
- transformers/models/nougat/tokenization_nougat.py +11 -16
- transformers/models/nystromformer/modeling_nystromformer.py +7 -0
- transformers/models/olmo/modeling_olmo.py +1 -1
- transformers/models/olmo2/modeling_olmo2.py +1 -1
- transformers/models/olmo3/modeling_olmo3.py +1 -1
- transformers/models/olmoe/modeling_olmoe.py +12 -4
- transformers/models/olmoe/modular_olmoe.py +4 -2
- transformers/models/omdet_turbo/configuration_omdet_turbo.py +2 -2
- transformers/models/omdet_turbo/modeling_omdet_turbo.py +4 -0
- transformers/models/oneformer/configuration_oneformer.py +3 -3
- transformers/models/oneformer/modeling_oneformer.py +7 -38
- transformers/models/openai/modeling_openai.py +12 -0
- transformers/models/ovis2/image_processing_ovis2_fast.py +0 -1
- transformers/models/ovis2/modeling_ovis2.py +15 -3
- transformers/models/ovis2/modular_ovis2.py +8 -0
- transformers/models/owlv2/image_processing_owlv2_fast.py +0 -2
- transformers/models/owlv2/modeling_owlv2.py +7 -3
- transformers/models/owlv2/modular_owlv2.py +0 -2
- transformers/models/owlvit/modeling_owlvit.py +7 -3
- transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py +3 -2
- transformers/models/paddleocr_vl/modeling_paddleocr_vl.py +28 -14
- transformers/models/paddleocr_vl/modular_paddleocr_vl.py +22 -12
- transformers/models/paligemma/modeling_paligemma.py +25 -17
- transformers/models/parakeet/modeling_parakeet.py +5 -0
- transformers/models/parakeet/modular_parakeet.py +5 -0
- transformers/models/parakeet/{tokenization_parakeet_fast.py → tokenization_parakeet.py} +3 -3
- transformers/models/patchtsmixer/modeling_patchtsmixer.py +4 -0
- transformers/models/patchtst/modeling_patchtst.py +5 -4
- transformers/models/pe_audio/__init__.py +30 -0
- transformers/models/pe_audio/configuration_pe_audio.py +206 -0
- transformers/models/pe_audio/feature_extraction_pe_audio.py +162 -0
- transformers/models/pe_audio/modeling_pe_audio.py +820 -0
- transformers/models/pe_audio/modular_pe_audio.py +299 -0
- transformers/models/pe_audio/processing_pe_audio.py +24 -0
- transformers/models/pe_audio_video/__init__.py +29 -0
- transformers/models/pe_audio_video/configuration_pe_audio_video.py +225 -0
- transformers/models/pe_audio_video/modeling_pe_audio_video.py +972 -0
- transformers/models/pe_audio_video/modular_pe_audio_video.py +764 -0
- transformers/models/pe_audio_video/processing_pe_audio_video.py +25 -0
- transformers/models/pe_video/__init__.py +30 -0
- transformers/models/pe_video/configuration_pe_video.py +211 -0
- transformers/models/pe_video/modeling_pe_video.py +636 -0
- transformers/models/pe_video/modular_pe_video.py +219 -0
- transformers/models/pe_video/processing_pe_video.py +10 -0
- transformers/models/pe_video/video_processing_pe_video.py +66 -0
- transformers/models/pegasus/configuration_pegasus.py +1 -0
- transformers/models/pegasus/modeling_pegasus.py +3 -0
- transformers/models/pegasus_x/modeling_pegasus_x.py +1 -0
- transformers/models/perceiver/image_processing_perceiver_fast.py +0 -1
- transformers/models/perceiver/modeling_perceiver.py +5 -1
- transformers/models/perception_lm/image_processing_perception_lm_fast.py +0 -1
- transformers/models/perception_lm/modeling_perception_lm.py +7 -3
- transformers/models/perception_lm/modular_perception_lm.py +7 -3
- transformers/models/persimmon/modeling_persimmon.py +1 -1
- transformers/models/phi/modeling_phi.py +1 -1
- transformers/models/phi3/modeling_phi3.py +1 -1
- transformers/models/phi4_multimodal/modeling_phi4_multimodal.py +4 -1
- transformers/models/phi4_multimodal/modular_phi4_multimodal.py +3 -0
- transformers/models/phi4_multimodal/processing_phi4_multimodal.py +0 -2
- transformers/models/phimoe/modeling_phimoe.py +12 -4
- transformers/models/phimoe/modular_phimoe.py +1 -1
- transformers/models/pix2struct/processing_pix2struct.py +0 -4
- transformers/models/pixio/__init__.py +30 -0
- transformers/models/pixio/configuration_pixio.py +151 -0
- transformers/models/pixio/modeling_pixio.py +507 -0
- transformers/models/pixio/modular_pixio.py +404 -0
- transformers/models/pixtral/modeling_pixtral.py +1 -1
- transformers/models/pixtral/processing_pixtral.py +3 -1
- transformers/models/plbart/configuration_plbart.py +1 -0
- transformers/models/plbart/modeling_plbart.py +7 -0
- transformers/models/plbart/modular_plbart.py +6 -0
- transformers/models/poolformer/image_processing_poolformer_fast.py +0 -1
- transformers/models/poolformer/modeling_poolformer.py +11 -1
- transformers/models/pop2piano/configuration_pop2piano.py +0 -1
- transformers/models/prompt_depth_anything/configuration_prompt_depth_anything.py +2 -3
- transformers/models/prophetnet/modeling_prophetnet.py +2 -1
- transformers/models/qwen2/modeling_qwen2.py +1 -1
- transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py +104 -64
- transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py +58 -18
- transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +18 -5
- transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py +26 -22
- transformers/models/qwen2_audio/modeling_qwen2_audio.py +2 -2
- transformers/models/qwen2_moe/modeling_qwen2_moe.py +12 -4
- transformers/models/qwen2_vl/image_processing_qwen2_vl.py +3 -2
- transformers/models/qwen2_vl/modeling_qwen2_vl.py +17 -4
- transformers/models/qwen3/modeling_qwen3.py +1 -1
- transformers/models/qwen3_moe/modeling_qwen3_moe.py +12 -4
- transformers/models/qwen3_next/modeling_qwen3_next.py +4 -6
- transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py +4 -0
- transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py +92 -46
- transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py +48 -4
- transformers/models/qwen3_vl/configuration_qwen3_vl.py +5 -5
- transformers/models/qwen3_vl/modeling_qwen3_vl.py +17 -4
- transformers/models/qwen3_vl/modular_qwen3_vl.py +21 -10
- transformers/models/qwen3_vl/processing_qwen3_vl.py +3 -3
- transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py +94 -112
- transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py +32 -81
- transformers/models/rag/configuration_rag.py +0 -8
- transformers/models/rag/modeling_rag.py +7 -9
- transformers/models/recurrent_gemma/modeling_recurrent_gemma.py +3 -2
- transformers/models/reformer/modeling_reformer.py +9 -1
- transformers/models/regnet/modeling_regnet.py +4 -0
- transformers/models/rembert/modeling_rembert.py +7 -1
- transformers/models/resnet/modeling_resnet.py +8 -3
- transformers/models/roberta/modeling_roberta.py +3 -0
- transformers/models/roberta/modular_roberta.py +3 -0
- transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py +3 -0
- transformers/models/roc_bert/modeling_roc_bert.py +3 -0
- transformers/models/rt_detr/configuration_rt_detr.py +1 -1
- transformers/models/rt_detr/modeling_rt_detr.py +4 -0
- transformers/models/rt_detr/modeling_rt_detr_resnet.py +8 -3
- transformers/models/rt_detr_v2/configuration_rt_detr_v2.py +2 -3
- transformers/models/rt_detr_v2/modeling_rt_detr_v2.py +7 -0
- transformers/models/rt_detr_v2/modular_rt_detr_v2.py +8 -3
- transformers/models/rwkv/modeling_rwkv.py +1 -1
- transformers/models/sam/configuration_sam.py +1 -0
- transformers/models/sam/image_processing_sam_fast.py +0 -1
- transformers/models/sam/modeling_sam.py +4 -1
- transformers/models/sam2/configuration_sam2.py +1 -1
- transformers/models/sam2/modeling_sam2.py +5 -1
- transformers/models/sam2/modular_sam2.py +5 -1
- transformers/models/sam2_video/modeling_sam2_video.py +51 -43
- transformers/models/sam2_video/modular_sam2_video.py +31 -18
- transformers/models/sam3/configuration_sam3.py +21 -1
- transformers/models/sam3/modeling_sam3.py +23 -0
- transformers/models/sam3_tracker/modeling_sam3_tracker.py +2 -0
- transformers/models/sam3_tracker/modular_sam3_tracker.py +2 -0
- transformers/models/sam3_tracker_video/configuration_sam3_tracker_video.py +25 -0
- transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py +26 -15
- transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py +25 -2
- transformers/models/sam3_video/configuration_sam3_video.py +14 -0
- transformers/models/sam3_video/modeling_sam3_video.py +3 -3
- transformers/models/sam3_video/processing_sam3_video.py +1 -1
- transformers/models/sam_hq/configuration_sam_hq.py +1 -0
- transformers/models/sam_hq/modeling_sam_hq.py +26 -23
- transformers/models/seamless_m4t/modeling_seamless_m4t.py +27 -11
- transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py +6 -0
- transformers/models/seed_oss/modeling_seed_oss.py +1 -1
- transformers/models/segformer/image_processing_segformer_fast.py +0 -1
- transformers/models/segformer/modeling_segformer.py +2 -2
- transformers/models/segformer/modular_segformer.py +0 -1
- transformers/models/shieldgemma2/modeling_shieldgemma2.py +1 -0
- transformers/models/siglip/modeling_siglip.py +24 -2
- transformers/models/siglip2/modeling_siglip2.py +63 -41
- transformers/models/smollm3/modeling_smollm3.py +1 -1
- transformers/models/smolvlm/modeling_smolvlm.py +5 -1
- transformers/models/smolvlm/video_processing_smolvlm.py +0 -1
- transformers/models/speech_to_text/modeling_speech_to_text.py +10 -0
- transformers/models/speecht5/modeling_speecht5.py +28 -0
- transformers/models/splinter/modeling_splinter.py +9 -3
- transformers/models/squeezebert/modeling_squeezebert.py +2 -0
- transformers/models/stablelm/modeling_stablelm.py +1 -1
- transformers/models/starcoder2/modeling_starcoder2.py +1 -1
- transformers/models/superglue/image_processing_superglue_fast.py +1 -2
- transformers/models/superpoint/image_processing_superpoint_fast.py +1 -2
- transformers/models/swiftformer/modeling_swiftformer.py +4 -0
- transformers/models/swin/modeling_swin.py +16 -12
- transformers/models/swin2sr/image_processing_swin2sr_fast.py +0 -1
- transformers/models/swin2sr/modeling_swin2sr.py +49 -33
- transformers/models/swinv2/modeling_swinv2.py +41 -33
- transformers/models/switch_transformers/modeling_switch_transformers.py +2 -8
- transformers/models/switch_transformers/modular_switch_transformers.py +2 -8
- transformers/models/t5/configuration_t5.py +7 -1
- transformers/models/t5/modeling_t5.py +1 -7
- transformers/models/t5gemma/modeling_t5gemma.py +1 -1
- transformers/models/t5gemma2/configuration_t5gemma2.py +6 -42
- transformers/models/t5gemma2/modeling_t5gemma2.py +13 -4
- transformers/models/t5gemma2/modular_t5gemma2.py +289 -4
- transformers/models/table_transformer/configuration_table_transformer.py +1 -1
- transformers/models/table_transformer/modeling_table_transformer.py +1 -1
- transformers/models/textnet/image_processing_textnet_fast.py +0 -1
- transformers/models/timesfm/modeling_timesfm.py +12 -0
- transformers/models/timesfm/modular_timesfm.py +12 -0
- transformers/models/timm_backbone/modeling_timm_backbone.py +13 -9
- transformers/models/timm_wrapper/configuration_timm_wrapper.py +3 -0
- transformers/models/timm_wrapper/modeling_timm_wrapper.py +19 -13
- transformers/models/trocr/modeling_trocr.py +1 -2
- transformers/models/tvp/configuration_tvp.py +5 -1
- transformers/models/tvp/modeling_tvp.py +4 -4
- transformers/models/udop/configuration_udop.py +1 -0
- transformers/models/udop/modeling_udop.py +3 -7
- transformers/models/umt5/configuration_umt5.py +2 -2
- transformers/models/umt5/modeling_umt5.py +0 -6
- transformers/models/vaultgemma/modeling_vaultgemma.py +1 -1
- transformers/models/video_llama_3/image_processing_video_llama_3.py +3 -2
- transformers/models/video_llama_3/modeling_video_llama_3.py +12 -1
- transformers/models/video_llama_3/modular_video_llama_3.py +10 -1
- transformers/models/video_llava/modeling_video_llava.py +7 -3
- transformers/models/vilt/configuration_vilt.py +2 -2
- transformers/models/vilt/modeling_vilt.py +7 -0
- transformers/models/vipllava/modeling_vipllava.py +7 -3
- transformers/models/visual_bert/modeling_visual_bert.py +2 -0
- transformers/models/vitmatte/configuration_vitmatte.py +1 -1
- transformers/models/vitmatte/image_processing_vitmatte_fast.py +0 -1
- transformers/models/vitmatte/modeling_vitmatte.py +4 -0
- transformers/models/vitpose/configuration_vitpose.py +1 -1
- transformers/models/vitpose/image_processing_vitpose_fast.py +0 -1
- transformers/models/voxtral/modeling_voxtral.py +2 -2
- transformers/models/voxtral/modular_voxtral.py +2 -2
- transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py +16 -10
- transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py +7 -0
- transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py +21 -11
- transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py +21 -11
- transformers/models/whisper/generation_whisper.py +1 -0
- transformers/models/whisper/modeling_whisper.py +5 -3
- transformers/models/x_clip/modeling_x_clip.py +2 -0
- transformers/models/xcodec/modeling_xcodec.py +5 -0
- transformers/models/xglm/modeling_xglm.py +10 -0
- transformers/models/xlm/modeling_xlm.py +13 -14
- transformers/models/xlm_roberta/modeling_xlm_roberta.py +109 -106
- transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py +3 -0
- transformers/models/xlnet/modeling_xlnet.py +3 -1
- transformers/models/xmod/modeling_xmod.py +3 -0
- transformers/models/yoso/modeling_yoso.py +4 -1
- transformers/models/zamba/modeling_zamba.py +2 -1
- transformers/models/zamba2/modeling_zamba2.py +3 -2
- transformers/models/zoedepth/configuration_zoedepth.py +1 -1
- transformers/models/zoedepth/image_processing_zoedepth_fast.py +1 -3
- transformers/models/zoedepth/modeling_zoedepth.py +7 -0
- transformers/pipelines/__init__.py +9 -6
- transformers/pipelines/automatic_speech_recognition.py +20 -12
- transformers/pipelines/base.py +1 -1
- transformers/pipelines/document_question_answering.py +1 -1
- transformers/pipelines/question_answering.py +1 -1
- transformers/pipelines/text_to_audio.py +2 -2
- transformers/processing_utils.py +127 -56
- transformers/quantizers/auto.py +2 -4
- transformers/quantizers/base.py +9 -64
- transformers/quantizers/quantizer_aqlm.py +1 -18
- transformers/quantizers/quantizer_auto_round.py +1 -10
- transformers/quantizers/quantizer_awq.py +3 -8
- transformers/quantizers/quantizer_bitnet.py +1 -6
- transformers/quantizers/quantizer_bnb_4bit.py +9 -49
- transformers/quantizers/quantizer_bnb_8bit.py +9 -19
- transformers/quantizers/quantizer_compressed_tensors.py +1 -4
- transformers/quantizers/quantizer_eetq.py +2 -12
- transformers/quantizers/quantizer_fbgemm_fp8.py +5 -14
- transformers/quantizers/quantizer_finegrained_fp8.py +15 -10
- transformers/quantizers/quantizer_fp_quant.py +4 -4
- transformers/quantizers/quantizer_gptq.py +1 -4
- transformers/quantizers/quantizer_higgs.py +2 -6
- transformers/quantizers/quantizer_mxfp4.py +2 -28
- transformers/quantizers/quantizer_quanto.py +14 -14
- transformers/quantizers/quantizer_spqr.py +3 -8
- transformers/quantizers/quantizer_torchao.py +28 -124
- transformers/quantizers/quantizer_vptq.py +1 -10
- transformers/testing_utils.py +28 -12
- transformers/tokenization_mistral_common.py +3 -2
- transformers/tokenization_utils_base.py +3 -2
- transformers/tokenization_utils_tokenizers.py +25 -2
- transformers/trainer.py +24 -2
- transformers/trainer_callback.py +8 -0
- transformers/trainer_seq2seq.py +4 -0
- transformers/training_args.py +8 -10
- transformers/utils/__init__.py +4 -0
- transformers/utils/attention_visualizer.py +4 -4
- transformers/utils/auto_docstring.py +34 -25
- transformers/utils/generic.py +20 -0
- transformers/utils/import_utils.py +51 -9
- transformers/utils/kernel_config.py +71 -18
- transformers/utils/quantization_config.py +8 -8
- transformers/video_processing_utils.py +16 -12
- {transformers-5.0.0rc1.dist-info → transformers-5.0.0rc2.dist-info}/METADATA +5 -6
- {transformers-5.0.0rc1.dist-info → transformers-5.0.0rc2.dist-info}/RECORD +671 -632
- {transformers-5.0.0rc1.dist-info → transformers-5.0.0rc2.dist-info}/WHEEL +0 -0
- {transformers-5.0.0rc1.dist-info → transformers-5.0.0rc2.dist-info}/entry_points.txt +0 -0
- {transformers-5.0.0rc1.dist-info → transformers-5.0.0rc2.dist-info}/licenses/LICENSE +0 -0
- {transformers-5.0.0rc1.dist-info → transformers-5.0.0rc2.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,1898 @@
|
|
|
1
|
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
|
2
|
+
# This file was automatically generated from src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py.
|
|
3
|
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
|
4
|
+
# the file from the modular. If any change should be done, please apply the change to the
|
|
5
|
+
# modular_ernie4_5_vl_moe.py file directly. One of our CI enforces this.
|
|
6
|
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
|
7
|
+
# coding=utf-8
|
|
8
|
+
# Copyright 2025 Baidu and HuggingFace Inc. team. All rights reserved.
|
|
9
|
+
#
|
|
10
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
11
|
+
# you may not use this file except in compliance with the License.
|
|
12
|
+
# You may obtain a copy of the License at
|
|
13
|
+
#
|
|
14
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
15
|
+
#
|
|
16
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
17
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
18
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
19
|
+
# See the License for the specific language governing permissions and
|
|
20
|
+
# limitations under the License.
|
|
21
|
+
|
|
22
|
+
import itertools
|
|
23
|
+
from collections.abc import Callable
|
|
24
|
+
from typing import Any, Optional, Union
|
|
25
|
+
|
|
26
|
+
import torch
|
|
27
|
+
import torch.nn as nn
|
|
28
|
+
import torch.nn.functional as F
|
|
29
|
+
|
|
30
|
+
from ... import initialization as init
|
|
31
|
+
from ...activations import ACT2FN
|
|
32
|
+
from ...cache_utils import Cache, DynamicCache
|
|
33
|
+
from ...generation import GenerationMixin
|
|
34
|
+
from ...integrations import use_experts_implementation, use_kernel_forward_from_hub, use_kernelized_func
|
|
35
|
+
from ...masking_utils import create_causal_mask
|
|
36
|
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
|
37
|
+
from ...modeling_layers import GradientCheckpointingLayer
|
|
38
|
+
from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
|
39
|
+
from ...modeling_rope_utils import dynamic_rope_update
|
|
40
|
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
|
41
|
+
from ...processing_utils import Unpack
|
|
42
|
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling
|
|
43
|
+
from ...utils.generic import OutputRecorder, check_model_inputs, maybe_autocast
|
|
44
|
+
from .configuration_ernie4_5_vl_moe import (
|
|
45
|
+
Ernie4_5_VL_MoeConfig,
|
|
46
|
+
Ernie4_5_VL_MoeTextConfig,
|
|
47
|
+
Ernie4_5_VL_MoeVisionConfig,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Ernie4_5_VL_MoeTextRotaryEmbedding(nn.Module):
|
|
52
|
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
|
53
|
+
|
|
54
|
+
def __init__(self, config, device=None):
|
|
55
|
+
super().__init__()
|
|
56
|
+
self.max_seq_len_cached = config.max_position_embeddings
|
|
57
|
+
self.original_max_seq_len = config.max_position_embeddings
|
|
58
|
+
|
|
59
|
+
self.config = config
|
|
60
|
+
|
|
61
|
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
|
62
|
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
|
63
|
+
if self.rope_type != "default":
|
|
64
|
+
raise ValueError(f"Ernie 4.5 VL requires the `default` rope type, but found {self.rope_type} instead.")
|
|
65
|
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
|
66
|
+
|
|
67
|
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
|
68
|
+
self.original_inv_freq = inv_freq
|
|
69
|
+
|
|
70
|
+
self.mrope_section = config.rope_parameters.get("mrope_section", [22, 22, 20])
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def compute_default_rope_parameters(
|
|
74
|
+
config: Optional[Ernie4_5_VL_MoeTextConfig] = None,
|
|
75
|
+
device: Optional["torch.device"] = None,
|
|
76
|
+
seq_len: Optional[int] = None,
|
|
77
|
+
) -> tuple["torch.Tensor", float]:
|
|
78
|
+
"""
|
|
79
|
+
Computes the inverse frequencies according to the original RoPE implementation
|
|
80
|
+
Args:
|
|
81
|
+
config ([`~transformers.PreTrainedConfig`]):
|
|
82
|
+
The model configuration.
|
|
83
|
+
device (`torch.device`):
|
|
84
|
+
The device to use for initialization of the inverse frequencies.
|
|
85
|
+
seq_len (`int`, *optional*):
|
|
86
|
+
The current sequence length. Unused for this type of RoPE.
|
|
87
|
+
Returns:
|
|
88
|
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
|
89
|
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
|
90
|
+
"""
|
|
91
|
+
base = config.rope_parameters["rope_theta"]
|
|
92
|
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
|
93
|
+
|
|
94
|
+
attention_factor = 1.0 # Unused in this type of RoPE
|
|
95
|
+
|
|
96
|
+
# Compute the inverse frequencies
|
|
97
|
+
inv_freq = 1.0 / (
|
|
98
|
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
# Special to ernie, we prerotate on the hw dim
|
|
102
|
+
mrope_section = config.rope_parameters.get("mrope_section", [22, 22, 20])
|
|
103
|
+
hw_dim = mrope_section[0] + mrope_section[1]
|
|
104
|
+
t_dim = mrope_section[2]
|
|
105
|
+
|
|
106
|
+
inv_freq_3d = torch.empty_like(inv_freq)
|
|
107
|
+
# (Pre-)Rotate to avoid another rotation during the forward
|
|
108
|
+
inv_freq_3d[:hw_dim] = torch.cat([inv_freq[:-t_dim][0::2], inv_freq[:-t_dim][1::2]])
|
|
109
|
+
inv_freq_3d[-t_dim:] = inv_freq[-t_dim:]
|
|
110
|
+
|
|
111
|
+
return inv_freq_3d, attention_factor
|
|
112
|
+
|
|
113
|
+
@torch.no_grad()
|
|
114
|
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
|
115
|
+
def forward(self, x, position_ids):
|
|
116
|
+
inv_freq_expanded = (
|
|
117
|
+
self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device)
|
|
118
|
+
)
|
|
119
|
+
position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
|
|
120
|
+
|
|
121
|
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
|
122
|
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
|
123
|
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
|
|
124
|
+
cos = freqs.cos() * self.attention_scaling
|
|
125
|
+
sin = freqs.sin() * self.attention_scaling
|
|
126
|
+
|
|
127
|
+
sin = self.recomposition_to_3d(sin)
|
|
128
|
+
cos = self.recomposition_to_3d(cos)
|
|
129
|
+
|
|
130
|
+
return cos, sin
|
|
131
|
+
|
|
132
|
+
def recomposition_to_3d(self, freq):
|
|
133
|
+
freq_h, freq_w, freq_t = (m[(i + 1) % 3] for i, m in enumerate(freq.split([*self.mrope_section], dim=-1)))
|
|
134
|
+
freq_hw = torch.stack([freq_h, freq_w], dim=-1).flatten(-2)
|
|
135
|
+
freq_hwt = torch.cat([freq_hw, freq_t], dim=-1)
|
|
136
|
+
return freq_hwt.repeat_interleave(2, dim=-1)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
|
140
|
+
"""
|
|
141
|
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
|
142
|
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
|
143
|
+
"""
|
|
144
|
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
|
145
|
+
if n_rep == 1:
|
|
146
|
+
return hidden_states
|
|
147
|
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
|
148
|
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def eager_attention_forward(
|
|
152
|
+
module: nn.Module,
|
|
153
|
+
query: torch.Tensor,
|
|
154
|
+
key: torch.Tensor,
|
|
155
|
+
value: torch.Tensor,
|
|
156
|
+
attention_mask: Optional[torch.Tensor],
|
|
157
|
+
scaling: float,
|
|
158
|
+
dropout: float = 0.0,
|
|
159
|
+
**kwargs: Unpack[TransformersKwargs],
|
|
160
|
+
):
|
|
161
|
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
|
162
|
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
|
163
|
+
|
|
164
|
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
|
165
|
+
if attention_mask is not None:
|
|
166
|
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
|
167
|
+
attn_weights = attn_weights + causal_mask
|
|
168
|
+
|
|
169
|
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
|
170
|
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
|
171
|
+
attn_output = torch.matmul(attn_weights, value_states)
|
|
172
|
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
|
173
|
+
|
|
174
|
+
return attn_output, attn_weights
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def rotate_half_text(x):
|
|
178
|
+
"""Rotates half the hidden dims of the input."""
|
|
179
|
+
x1 = x[..., 0::2]
|
|
180
|
+
x2 = x[..., 1::2]
|
|
181
|
+
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
|
185
|
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
q (`torch.Tensor`): The query tensor.
|
|
189
|
+
k (`torch.Tensor`): The key tensor.
|
|
190
|
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
|
191
|
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
|
192
|
+
position_ids (`torch.Tensor`, *optional*):
|
|
193
|
+
Deprecated and unused.
|
|
194
|
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
|
195
|
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
|
196
|
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
|
197
|
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
|
198
|
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
|
199
|
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
|
200
|
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
|
201
|
+
Returns:
|
|
202
|
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
|
203
|
+
"""
|
|
204
|
+
original_dtype = q.dtype
|
|
205
|
+
|
|
206
|
+
cos = cos.unsqueeze(unsqueeze_dim)
|
|
207
|
+
sin = sin.unsqueeze(unsqueeze_dim)
|
|
208
|
+
|
|
209
|
+
q_embed = (q.float() * cos) + (rotate_half_text(q).float() * sin)
|
|
210
|
+
k_embed = (k.float() * cos) + (rotate_half_text(k).float() * sin)
|
|
211
|
+
|
|
212
|
+
return q_embed.to(original_dtype), k_embed.to(original_dtype)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@use_kernelized_func(apply_rotary_pos_emb)
|
|
216
|
+
class Ernie4_5_VL_MoeTextAttention(nn.Module):
|
|
217
|
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
|
218
|
+
|
|
219
|
+
def __init__(self, config: Ernie4_5_VL_MoeConfig, layer_idx: int):
|
|
220
|
+
super().__init__()
|
|
221
|
+
self.config = config
|
|
222
|
+
self.layer_idx = layer_idx
|
|
223
|
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
|
224
|
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
|
225
|
+
self.scaling = self.head_dim**-0.5
|
|
226
|
+
|
|
227
|
+
self.attention_dropout = 0.0
|
|
228
|
+
self.is_causal = True
|
|
229
|
+
|
|
230
|
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.use_bias)
|
|
231
|
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.use_bias)
|
|
232
|
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.use_bias)
|
|
233
|
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.use_bias)
|
|
234
|
+
|
|
235
|
+
def forward(
|
|
236
|
+
self,
|
|
237
|
+
hidden_states: torch.Tensor,
|
|
238
|
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
|
239
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
240
|
+
past_key_values: Optional[Cache] = None,
|
|
241
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
242
|
+
**kwargs: Unpack[TransformersKwargs],
|
|
243
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
244
|
+
input_shape = hidden_states.shape[:-1]
|
|
245
|
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
|
246
|
+
|
|
247
|
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
|
248
|
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
|
249
|
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
|
250
|
+
|
|
251
|
+
cos, sin = position_embeddings
|
|
252
|
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
|
253
|
+
|
|
254
|
+
if past_key_values is not None:
|
|
255
|
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
|
256
|
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
|
257
|
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
|
258
|
+
|
|
259
|
+
attention_interface: Callable = eager_attention_forward
|
|
260
|
+
if self.config._attn_implementation != "eager":
|
|
261
|
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
|
262
|
+
|
|
263
|
+
attn_output, attn_weights = attention_interface(
|
|
264
|
+
self,
|
|
265
|
+
query_states,
|
|
266
|
+
key_states,
|
|
267
|
+
value_states,
|
|
268
|
+
attention_mask,
|
|
269
|
+
dropout=0.0 if not self.training else self.attention_dropout,
|
|
270
|
+
scaling=self.scaling,
|
|
271
|
+
**kwargs,
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
|
275
|
+
attn_output = self.o_proj(attn_output)
|
|
276
|
+
return attn_output, attn_weights
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
@use_kernel_forward_from_hub("RMSNorm")
|
|
280
|
+
class Ernie4_5_VL_MoeRMSNorm(nn.Module):
|
|
281
|
+
def __init__(self, hidden_size, eps=1e-6):
|
|
282
|
+
"""
|
|
283
|
+
Ernie4_5_VL_MoeRMSNorm is equivalent to T5LayerNorm
|
|
284
|
+
"""
|
|
285
|
+
super().__init__()
|
|
286
|
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
|
287
|
+
self.variance_epsilon = eps
|
|
288
|
+
|
|
289
|
+
def forward(self, hidden_states):
|
|
290
|
+
input_dtype = hidden_states.dtype
|
|
291
|
+
hidden_states = hidden_states.to(torch.float32)
|
|
292
|
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
|
293
|
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
|
294
|
+
return self.weight * hidden_states.to(input_dtype)
|
|
295
|
+
|
|
296
|
+
def extra_repr(self):
|
|
297
|
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class Ernie4_5_VL_MoeMLP(nn.Module):
|
|
301
|
+
def __init__(self, config, intermediate_size=None):
|
|
302
|
+
super().__init__()
|
|
303
|
+
self.config = config
|
|
304
|
+
self.hidden_size = config.hidden_size
|
|
305
|
+
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
|
|
306
|
+
|
|
307
|
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
|
|
308
|
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
|
|
309
|
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
|
|
310
|
+
self.act_fn = ACT2FN[config.hidden_act]
|
|
311
|
+
|
|
312
|
+
def forward(self, x):
|
|
313
|
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
|
314
|
+
return down_proj
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class Ernie4_5_VL_MoeMoeStatics(nn.Module):
|
|
318
|
+
"""
|
|
319
|
+
Stores MoE (Mixture of Experts) statistics
|
|
320
|
+
- Bias for the gating
|
|
321
|
+
- Additionally, usage per expert in the original codebase
|
|
322
|
+
"""
|
|
323
|
+
|
|
324
|
+
def __init__(self, config):
|
|
325
|
+
super().__init__()
|
|
326
|
+
|
|
327
|
+
num_experts_groups = 1
|
|
328
|
+
num_experts = config.moe_num_experts
|
|
329
|
+
|
|
330
|
+
self.e_score_correction_bias = nn.Parameter(
|
|
331
|
+
torch.zeros(num_experts_groups, num_experts, dtype=torch.float32),
|
|
332
|
+
requires_grad=False,
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
def forward(self, hidden_states):
|
|
336
|
+
# NOTE: This is a workaround to enable TP with a module that only has parameters
|
|
337
|
+
#
|
|
338
|
+
# Otherwise, it stays as `DTensor` when called in the "super" forward
|
|
339
|
+
# 1. All other tensors are local (`torch.Tensor`)
|
|
340
|
+
# 2. Isolate does not work on `nn.Module` which only has parameters
|
|
341
|
+
return hidden_states + self.e_score_correction_bias.squeeze()
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
class Ernie4_5_VL_MoeMoeTopKRouter(nn.Module):
|
|
345
|
+
def __init__(self, config):
|
|
346
|
+
super().__init__()
|
|
347
|
+
self.weight = nn.Parameter(torch.zeros(config.moe_num_experts, config.hidden_size, dtype=torch.float32))
|
|
348
|
+
self.moe_statics = Ernie4_5_VL_MoeMoeStatics(config)
|
|
349
|
+
self.top_k = config.moe_k
|
|
350
|
+
self.norm_min = config.moe_norm_min
|
|
351
|
+
|
|
352
|
+
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
|
353
|
+
device_type = (
|
|
354
|
+
hidden_states.device.type
|
|
355
|
+
if isinstance(hidden_states.device.type, str) and hidden_states.device.type != "mps"
|
|
356
|
+
else "cpu"
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
|
360
|
+
router_logits = F.linear(hidden_states.float(), self.weight.float())
|
|
361
|
+
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
|
|
362
|
+
_, selected_experts = torch.topk(self.moe_statics(routing_weights), self.top_k, dim=-1)
|
|
363
|
+
routing_weights = torch.gather(routing_weights, dim=-1, index=selected_experts)
|
|
364
|
+
routing_weights = routing_weights / torch.clamp(
|
|
365
|
+
routing_weights.sum(dim=-1, keepdim=True), min=self.norm_min
|
|
366
|
+
)
|
|
367
|
+
routing_weights = routing_weights.to(hidden_states.dtype)
|
|
368
|
+
return router_logits, selected_experts, routing_weights
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
@use_experts_implementation
|
|
372
|
+
class Ernie4_5_VL_MoeMoeExperts(nn.Module):
|
|
373
|
+
"""Collection of expert weights stored as 3D tensors."""
|
|
374
|
+
|
|
375
|
+
def __init__(self, config, intermediate_size=None):
|
|
376
|
+
super().__init__()
|
|
377
|
+
self.num_experts = config.moe_num_experts
|
|
378
|
+
self.hidden_dim = config.hidden_size
|
|
379
|
+
self.intermediate_dim = config.moe_intermediate_size if intermediate_size is None else intermediate_size
|
|
380
|
+
self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
|
|
381
|
+
self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
|
|
382
|
+
self.act_fn = ACT2FN[config.hidden_act]
|
|
383
|
+
|
|
384
|
+
def forward(
|
|
385
|
+
self,
|
|
386
|
+
hidden_states: torch.Tensor,
|
|
387
|
+
top_k_index: torch.Tensor,
|
|
388
|
+
top_k_weights: torch.Tensor,
|
|
389
|
+
) -> torch.Tensor:
|
|
390
|
+
final_hidden_states = torch.zeros_like(hidden_states)
|
|
391
|
+
with torch.no_grad():
|
|
392
|
+
expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
|
|
393
|
+
expert_mask = expert_mask.permute(2, 1, 0)
|
|
394
|
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
|
395
|
+
|
|
396
|
+
for expert_idx in expert_hit:
|
|
397
|
+
expert_idx = expert_idx[0]
|
|
398
|
+
if expert_idx == self.num_experts:
|
|
399
|
+
continue
|
|
400
|
+
top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
|
|
401
|
+
current_state = hidden_states[token_idx]
|
|
402
|
+
gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
|
|
403
|
+
current_hidden_states = self.act_fn(gate) * up
|
|
404
|
+
current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
|
|
405
|
+
current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
|
|
406
|
+
final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
|
|
407
|
+
|
|
408
|
+
return final_hidden_states
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
class Ernie4_5_VL_MoeSparseMoeBlock(nn.Module):
|
|
412
|
+
def __init__(self, config, intermediate_size):
|
|
413
|
+
super().__init__()
|
|
414
|
+
self.hidden_dim = config.hidden_size
|
|
415
|
+
self.num_experts = config.moe_num_experts
|
|
416
|
+
self.top_k = config.moe_k
|
|
417
|
+
self.gate = Ernie4_5_VL_MoeMoeTopKRouter(config)
|
|
418
|
+
self.experts = Ernie4_5_VL_MoeMoeExperts(config, intermediate_size)
|
|
419
|
+
|
|
420
|
+
def forward(
|
|
421
|
+
self,
|
|
422
|
+
hidden_states: torch.Tensor,
|
|
423
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
424
|
+
hidden_states = hidden_states.view(-1, self.hidden_dim)
|
|
425
|
+
|
|
426
|
+
router_logits, top_k_index, top_k_weights = self.gate(hidden_states)
|
|
427
|
+
final_hidden_states = self.experts(hidden_states, top_k_index, top_k_weights)
|
|
428
|
+
|
|
429
|
+
# moe results are changed to a flattened shape to ease the modality isolated assigning of results
|
|
430
|
+
return final_hidden_states.flatten(), router_logits.flatten()
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
class Ernie4_5_VL_MoeMoeBlock(nn.Module):
|
|
434
|
+
"""
|
|
435
|
+
Similar to `Ernie4_5_Moe` where we have modality isolated experts:
|
|
436
|
+
- A set of text experts that are only run on text tokens
|
|
437
|
+
- A set of vision experts that are only run on vision (image/video) tokens
|
|
438
|
+
|
|
439
|
+
This modality isolation is unique to the Ernie 4.5 VL Moe models.
|
|
440
|
+
"""
|
|
441
|
+
|
|
442
|
+
def __init__(self, config):
|
|
443
|
+
super().__init__()
|
|
444
|
+
self.num_experts = config.moe_num_experts
|
|
445
|
+
|
|
446
|
+
self.text_moe = Ernie4_5_VL_MoeSparseMoeBlock(config, intermediate_size=config.moe_intermediate_size[0])
|
|
447
|
+
self.vision_moe = Ernie4_5_VL_MoeSparseMoeBlock(config, intermediate_size=config.moe_intermediate_size[1])
|
|
448
|
+
|
|
449
|
+
self.shared_experts = None
|
|
450
|
+
if config.moe_num_shared_experts > 0:
|
|
451
|
+
self.shared_experts = Ernie4_5_VL_MoeMLP(
|
|
452
|
+
config, config.moe_intermediate_size[0] * config.moe_num_shared_experts
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
def forward(
|
|
456
|
+
self,
|
|
457
|
+
hidden_states: torch.Tensor,
|
|
458
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
459
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
460
|
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
|
461
|
+
|
|
462
|
+
# (Optional) shared experts
|
|
463
|
+
if self.shared_experts is not None:
|
|
464
|
+
shared_output = self.shared_experts(hidden_states)
|
|
465
|
+
|
|
466
|
+
if moe_mm_token_type_ids is not None and moe_mm_token_type_ids.any():
|
|
467
|
+
final_hidden_states = torch.zeros_like(hidden_states)
|
|
468
|
+
router_logits = torch.zeros(
|
|
469
|
+
size=(batch_size * sequence_length, self.num_experts),
|
|
470
|
+
device=final_hidden_states.device,
|
|
471
|
+
dtype=torch.float,
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
# True (1 or 2) == vision, False (0) == text tokens
|
|
475
|
+
moe_mm_token_type_ids = moe_mm_token_type_ids.bool()
|
|
476
|
+
token_type_ids_router = moe_mm_token_type_ids.reshape(-1)[:, None].expand(-1, self.num_experts)
|
|
477
|
+
token_type_ids_states = moe_mm_token_type_ids[..., None].expand(-1, -1, hidden_dim)
|
|
478
|
+
|
|
479
|
+
# Run moe on each modality and assign their results to the original token positions
|
|
480
|
+
final_hidden_states[~token_type_ids_states], router_logits[~token_type_ids_router] = self.text_moe(
|
|
481
|
+
hidden_states[~token_type_ids_states]
|
|
482
|
+
)
|
|
483
|
+
final_hidden_states[token_type_ids_states], router_logits[token_type_ids_router] = self.vision_moe(
|
|
484
|
+
hidden_states[token_type_ids_states]
|
|
485
|
+
)
|
|
486
|
+
else:
|
|
487
|
+
final_hidden_states, router_logits = self.text_moe(hidden_states)
|
|
488
|
+
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
|
489
|
+
router_logits = router_logits.reshape(-1, self.num_experts)
|
|
490
|
+
|
|
491
|
+
# Add (optional) shared experts to the result
|
|
492
|
+
if self.shared_experts is not None:
|
|
493
|
+
final_hidden_states = final_hidden_states + shared_output
|
|
494
|
+
|
|
495
|
+
return final_hidden_states, router_logits
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
class Ernie4_5_VL_MoeDecoderLayer(GradientCheckpointingLayer):
|
|
499
|
+
def __init__(self, config, layer_idx):
|
|
500
|
+
super().__init__()
|
|
501
|
+
self.hidden_size = config.hidden_size
|
|
502
|
+
|
|
503
|
+
self.self_attn = Ernie4_5_VL_MoeTextAttention(config, layer_idx)
|
|
504
|
+
|
|
505
|
+
if config.mlp_layer_types[layer_idx] == "sparse":
|
|
506
|
+
self.mlp = Ernie4_5_VL_MoeMoeBlock(config)
|
|
507
|
+
else:
|
|
508
|
+
self.mlp = Ernie4_5_VL_MoeMLP(config)
|
|
509
|
+
|
|
510
|
+
self.input_layernorm = Ernie4_5_VL_MoeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
|
511
|
+
self.post_attention_layernorm = Ernie4_5_VL_MoeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
|
512
|
+
|
|
513
|
+
def forward(
|
|
514
|
+
self,
|
|
515
|
+
hidden_states: torch.Tensor,
|
|
516
|
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
|
517
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
518
|
+
position_ids: Optional[torch.Tensor] = None,
|
|
519
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
520
|
+
past_key_values: Optional[Cache] = None,
|
|
521
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
522
|
+
**kwargs: Unpack[FlashAttentionKwargs],
|
|
523
|
+
) -> tuple[torch.Tensor, Optional[tuple[torch.Tensor, torch.Tensor]]]:
|
|
524
|
+
residual = hidden_states
|
|
525
|
+
|
|
526
|
+
hidden_states = self.input_layernorm(hidden_states)
|
|
527
|
+
|
|
528
|
+
# Self Attention
|
|
529
|
+
hidden_states, _ = self.self_attn(
|
|
530
|
+
hidden_states=hidden_states,
|
|
531
|
+
position_embeddings=position_embeddings,
|
|
532
|
+
attention_mask=attention_mask,
|
|
533
|
+
position_ids=position_ids,
|
|
534
|
+
past_key_values=past_key_values,
|
|
535
|
+
cache_position=cache_position,
|
|
536
|
+
**kwargs,
|
|
537
|
+
)
|
|
538
|
+
hidden_states = hidden_states + residual
|
|
539
|
+
|
|
540
|
+
# Fully Connected
|
|
541
|
+
residual = hidden_states
|
|
542
|
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
|
543
|
+
if isinstance(self.mlp, Ernie4_5_VL_MoeMoeBlock):
|
|
544
|
+
hidden_states, _ = self.mlp(hidden_states, moe_mm_token_type_ids)
|
|
545
|
+
else:
|
|
546
|
+
hidden_states = self.mlp(hidden_states)
|
|
547
|
+
hidden_states = hidden_states + residual
|
|
548
|
+
|
|
549
|
+
return hidden_states
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
@auto_docstring
|
|
553
|
+
class Ernie4_5_VL_MoePreTrainedModel(PreTrainedModel):
|
|
554
|
+
config: Ernie4_5_VL_MoeConfig
|
|
555
|
+
base_model_prefix = "model"
|
|
556
|
+
input_modalities = ("image", "video", "text")
|
|
557
|
+
supports_gradient_checkpointing = True
|
|
558
|
+
_no_split_modules = ["Ernie4_5_VL_MoeDecoderLayer", "Ernie4_5_VL_MoeVisionBlock"]
|
|
559
|
+
_skip_keys_device_placement = "past_key_values"
|
|
560
|
+
_supports_flash_attn = True
|
|
561
|
+
_supports_sdpa = True
|
|
562
|
+
_can_compile_fullgraph = False
|
|
563
|
+
_supports_attention_backend = True
|
|
564
|
+
|
|
565
|
+
_can_record_outputs = {
|
|
566
|
+
"router_logits": OutputRecorder(Ernie4_5_VL_MoeMoeBlock, index=1),
|
|
567
|
+
"hidden_states": Ernie4_5_VL_MoeDecoderLayer,
|
|
568
|
+
"attentions": Ernie4_5_VL_MoeTextAttention,
|
|
569
|
+
}
|
|
570
|
+
_keep_in_fp32_modules_strict = ["gate.weight", "moe_statics"]
|
|
571
|
+
|
|
572
|
+
def _init_weights(self, module):
|
|
573
|
+
super()._init_weights(module)
|
|
574
|
+
if isinstance(module, Ernie4_5_VL_MoeMoeTopKRouter):
|
|
575
|
+
init.zeros_(module.moe_statics.e_score_correction_bias)
|
|
576
|
+
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
|
577
|
+
elif isinstance(module, Ernie4_5_VL_MoeMoeExperts):
|
|
578
|
+
init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
|
|
579
|
+
init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
|
|
580
|
+
elif isinstance(module, Ernie4_5_VL_MoeVisionRotaryEmbedding):
|
|
581
|
+
inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim))
|
|
582
|
+
init.copy_(module.inv_freq, inv_freq)
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
@auto_docstring
|
|
586
|
+
class Ernie4_5_VL_MoeTextModel(Ernie4_5_VL_MoePreTrainedModel):
|
|
587
|
+
config: Ernie4_5_VL_MoeTextConfig
|
|
588
|
+
|
|
589
|
+
def __init__(self, config: Ernie4_5_VL_MoeTextConfig):
|
|
590
|
+
super().__init__(config)
|
|
591
|
+
self.padding_idx = config.pad_token_id
|
|
592
|
+
self.vocab_size = config.vocab_size
|
|
593
|
+
|
|
594
|
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
|
595
|
+
self.layers = nn.ModuleList(
|
|
596
|
+
[Ernie4_5_VL_MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
|
597
|
+
)
|
|
598
|
+
self.norm = Ernie4_5_VL_MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
|
599
|
+
self.rotary_emb = Ernie4_5_VL_MoeTextRotaryEmbedding(config=config)
|
|
600
|
+
self.gradient_checkpointing = False
|
|
601
|
+
|
|
602
|
+
# Initialize weights and apply final processing
|
|
603
|
+
self.post_init()
|
|
604
|
+
|
|
605
|
+
@check_model_inputs
|
|
606
|
+
@auto_docstring
|
|
607
|
+
def forward(
|
|
608
|
+
self,
|
|
609
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
610
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
611
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
612
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
613
|
+
past_key_values: Optional[Cache] = None,
|
|
614
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
615
|
+
use_cache: Optional[bool] = None,
|
|
616
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
617
|
+
**kwargs: Unpack[FlashAttentionKwargs],
|
|
618
|
+
) -> MoeModelOutputWithPast:
|
|
619
|
+
r"""
|
|
620
|
+
moe_mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
621
|
+
The same as `mm_token_type_ids` while additionally considering start/end image/video tokens as respective vision tokens.
|
|
622
|
+
"""
|
|
623
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
624
|
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
625
|
+
|
|
626
|
+
if use_cache and past_key_values is None:
|
|
627
|
+
past_key_values = DynamicCache(config=self.config)
|
|
628
|
+
|
|
629
|
+
if inputs_embeds is None:
|
|
630
|
+
inputs_embeds = self.embed_tokens(input_ids)
|
|
631
|
+
|
|
632
|
+
if cache_position is None:
|
|
633
|
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
|
634
|
+
cache_position = torch.arange(
|
|
635
|
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
|
636
|
+
)
|
|
637
|
+
|
|
638
|
+
# the hard coded `3` is for temporal, height and width.
|
|
639
|
+
if position_ids is None:
|
|
640
|
+
position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
|
|
641
|
+
elif position_ids.ndim == 2:
|
|
642
|
+
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
|
|
643
|
+
|
|
644
|
+
# NOTE: we need to pass text position ids for packing. Ernie 4.5 VL uses 3D positions
|
|
645
|
+
# where each dim indicates visual spatial positions for temporal/height/width grids.
|
|
646
|
+
# There are is only one scenario when FA2-like packed masking might be activated.
|
|
647
|
+
# 1. User specifically passed packed `position_ids` and no attention mask.
|
|
648
|
+
# In this case we expect the useer to create correct position ids for all 3 grids
|
|
649
|
+
# and prepend text-only position ids to it. The final tensor will be [4, bs, seq-len]
|
|
650
|
+
if position_ids.ndim == 3 and position_ids.shape[0] == 4:
|
|
651
|
+
text_position_ids = position_ids[0]
|
|
652
|
+
position_ids = position_ids[1:]
|
|
653
|
+
else:
|
|
654
|
+
# If inputs are not packed (usual 3D positions), do not prepare mask from position_ids
|
|
655
|
+
text_position_ids = None
|
|
656
|
+
|
|
657
|
+
attention_mask = create_causal_mask(
|
|
658
|
+
config=self.config,
|
|
659
|
+
input_embeds=inputs_embeds,
|
|
660
|
+
attention_mask=attention_mask,
|
|
661
|
+
cache_position=cache_position,
|
|
662
|
+
past_key_values=past_key_values,
|
|
663
|
+
position_ids=text_position_ids,
|
|
664
|
+
)
|
|
665
|
+
|
|
666
|
+
hidden_states = inputs_embeds
|
|
667
|
+
|
|
668
|
+
# create position embeddings to be shared across the decoder layers
|
|
669
|
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
|
670
|
+
|
|
671
|
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
|
672
|
+
hidden_states = decoder_layer(
|
|
673
|
+
hidden_states,
|
|
674
|
+
position_embeddings=position_embeddings,
|
|
675
|
+
attention_mask=attention_mask,
|
|
676
|
+
position_ids=position_ids,
|
|
677
|
+
moe_mm_token_type_ids=moe_mm_token_type_ids,
|
|
678
|
+
past_key_values=past_key_values,
|
|
679
|
+
cache_position=cache_position,
|
|
680
|
+
**kwargs,
|
|
681
|
+
)
|
|
682
|
+
|
|
683
|
+
hidden_states = self.norm(hidden_states)
|
|
684
|
+
|
|
685
|
+
return MoeModelOutputWithPast(
|
|
686
|
+
last_hidden_state=hidden_states,
|
|
687
|
+
past_key_values=past_key_values,
|
|
688
|
+
)
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
class Ernie4_5VLVisionMLP(nn.Module):
|
|
692
|
+
def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None:
|
|
693
|
+
super().__init__()
|
|
694
|
+
self.fc1 = nn.Linear(dim, hidden_dim)
|
|
695
|
+
self.act = ACT2FN[hidden_act]
|
|
696
|
+
self.fc2 = nn.Linear(hidden_dim, dim)
|
|
697
|
+
|
|
698
|
+
def forward(self, x) -> torch.Tensor:
|
|
699
|
+
return self.fc2(self.act(self.fc1(x)))
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
class Ernie4_5_VL_MoePatchEmbed(nn.Module):
|
|
703
|
+
def __init__(
|
|
704
|
+
self,
|
|
705
|
+
patch_size: int = 14,
|
|
706
|
+
in_channels: int = 3,
|
|
707
|
+
embed_dim: int = 1152,
|
|
708
|
+
) -> None:
|
|
709
|
+
super().__init__()
|
|
710
|
+
self.patch_size = patch_size
|
|
711
|
+
self.in_channels = in_channels
|
|
712
|
+
self.embed_dim = embed_dim
|
|
713
|
+
self.proj = nn.Linear(in_channels * patch_size * patch_size, embed_dim, bias=False)
|
|
714
|
+
|
|
715
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
|
716
|
+
target_dtype = self.proj.weight.dtype
|
|
717
|
+
return self.proj(hidden_states.to(target_dtype))
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
class Ernie4_5_VL_MoeVisionRotaryEmbedding(nn.Module):
|
|
721
|
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
|
722
|
+
|
|
723
|
+
def __init__(self, dim: int, theta: float = 10000.0) -> None:
|
|
724
|
+
super().__init__()
|
|
725
|
+
self.dim = dim
|
|
726
|
+
self.theta = theta
|
|
727
|
+
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
|
|
728
|
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
|
729
|
+
|
|
730
|
+
def forward(self, seqlen: int) -> torch.Tensor:
|
|
731
|
+
seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
|
732
|
+
freqs = torch.outer(seq, self.inv_freq)
|
|
733
|
+
return freqs
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def rotate_half(x):
|
|
737
|
+
"""Rotates half the hidden dims of the input."""
|
|
738
|
+
x1 = x[..., : x.shape[-1] // 2]
|
|
739
|
+
x2 = x[..., x.shape[-1] // 2 :]
|
|
740
|
+
return torch.cat((-x2, x1), dim=-1)
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def apply_rotary_pos_emb_vision(
|
|
744
|
+
q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
|
|
745
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
746
|
+
orig_q_dtype = q.dtype
|
|
747
|
+
orig_k_dtype = k.dtype
|
|
748
|
+
q, k = q.float(), k.float()
|
|
749
|
+
cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
|
|
750
|
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
|
751
|
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
|
752
|
+
q_embed = q_embed.to(orig_q_dtype)
|
|
753
|
+
k_embed = k_embed.to(orig_k_dtype)
|
|
754
|
+
return q_embed, k_embed
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
class Ernie4_5_VL_MoeVisionAttention(nn.Module):
|
|
758
|
+
def __init__(self, config: Ernie4_5_VL_MoeVisionConfig) -> None:
|
|
759
|
+
super().__init__()
|
|
760
|
+
self.dim = config.hidden_size
|
|
761
|
+
self.num_heads = config.num_heads
|
|
762
|
+
self.head_dim = self.dim // self.num_heads
|
|
763
|
+
self.num_key_value_groups = 1 # needed for eager attention
|
|
764
|
+
self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True)
|
|
765
|
+
self.proj = nn.Linear(self.dim, self.dim)
|
|
766
|
+
self.scaling = self.head_dim**-0.5
|
|
767
|
+
self.config = config
|
|
768
|
+
self.attention_dropout = 0.0
|
|
769
|
+
self.is_causal = False
|
|
770
|
+
|
|
771
|
+
def forward(
|
|
772
|
+
self,
|
|
773
|
+
hidden_states: torch.Tensor,
|
|
774
|
+
cu_seqlens: torch.Tensor,
|
|
775
|
+
rotary_pos_emb: Optional[torch.Tensor] = None,
|
|
776
|
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
|
777
|
+
**kwargs,
|
|
778
|
+
) -> torch.Tensor:
|
|
779
|
+
seq_length = hidden_states.shape[0]
|
|
780
|
+
query_states, key_states, value_states = (
|
|
781
|
+
self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
|
782
|
+
)
|
|
783
|
+
cos, sin = position_embeddings
|
|
784
|
+
query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
|
|
785
|
+
|
|
786
|
+
query_states = query_states.transpose(0, 1).unsqueeze(0)
|
|
787
|
+
key_states = key_states.transpose(0, 1).unsqueeze(0)
|
|
788
|
+
value_states = value_states.transpose(0, 1).unsqueeze(0)
|
|
789
|
+
|
|
790
|
+
attention_interface: Callable = eager_attention_forward
|
|
791
|
+
if self.config._attn_implementation != "eager":
|
|
792
|
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
|
793
|
+
|
|
794
|
+
if "flash" in self.config._attn_implementation:
|
|
795
|
+
# Flash Attention: Use cu_seqlens for variable length attention
|
|
796
|
+
max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
|
|
797
|
+
attn_output, _ = attention_interface(
|
|
798
|
+
self,
|
|
799
|
+
query_states,
|
|
800
|
+
key_states,
|
|
801
|
+
value_states,
|
|
802
|
+
attention_mask=None,
|
|
803
|
+
scaling=self.scaling,
|
|
804
|
+
dropout=0.0 if not self.training else self.attention_dropout,
|
|
805
|
+
cu_seq_lens_q=cu_seqlens,
|
|
806
|
+
cu_seq_lens_k=cu_seqlens,
|
|
807
|
+
max_length_q=max_seqlen,
|
|
808
|
+
max_length_k=max_seqlen,
|
|
809
|
+
is_causal=False,
|
|
810
|
+
**kwargs,
|
|
811
|
+
)
|
|
812
|
+
else:
|
|
813
|
+
# Other implementations: Process each chunk separately
|
|
814
|
+
lengths = cu_seqlens[1:] - cu_seqlens[:-1]
|
|
815
|
+
splits = [
|
|
816
|
+
torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
|
|
817
|
+
]
|
|
818
|
+
|
|
819
|
+
attn_outputs = [
|
|
820
|
+
attention_interface(
|
|
821
|
+
self,
|
|
822
|
+
q,
|
|
823
|
+
k,
|
|
824
|
+
v,
|
|
825
|
+
attention_mask=None,
|
|
826
|
+
scaling=self.scaling,
|
|
827
|
+
dropout=0.0 if not self.training else self.attention_dropout,
|
|
828
|
+
is_causal=False,
|
|
829
|
+
**kwargs,
|
|
830
|
+
)[0]
|
|
831
|
+
for q, k, v in zip(*splits)
|
|
832
|
+
]
|
|
833
|
+
attn_output = torch.cat(attn_outputs, dim=1)
|
|
834
|
+
|
|
835
|
+
attn_output = attn_output.reshape(seq_length, -1).contiguous()
|
|
836
|
+
attn_output = self.proj(attn_output)
|
|
837
|
+
return attn_output
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
class Ernie4_5_VL_MoeVisionBlock(GradientCheckpointingLayer):
|
|
841
|
+
def __init__(self, config) -> None:
|
|
842
|
+
super().__init__()
|
|
843
|
+
|
|
844
|
+
self.norm1 = nn.LayerNorm(config.hidden_size, config.rms_norm_eps)
|
|
845
|
+
self.norm2 = nn.LayerNorm(config.hidden_size, config.rms_norm_eps)
|
|
846
|
+
self.attn = Ernie4_5_VL_MoeVisionAttention(config=config)
|
|
847
|
+
self.mlp = Ernie4_5VLVisionMLP(
|
|
848
|
+
dim=config.hidden_size,
|
|
849
|
+
hidden_dim=config.intermediate_size,
|
|
850
|
+
hidden_act=config.hidden_act,
|
|
851
|
+
)
|
|
852
|
+
|
|
853
|
+
def forward(
|
|
854
|
+
self,
|
|
855
|
+
hidden_states: torch.Tensor,
|
|
856
|
+
cu_seqlens: torch.Tensor,
|
|
857
|
+
rotary_pos_emb: Optional[torch.Tensor] = None,
|
|
858
|
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
|
859
|
+
**kwargs,
|
|
860
|
+
) -> torch.Tensor:
|
|
861
|
+
hidden_states = hidden_states + self.attn(
|
|
862
|
+
self.norm1(hidden_states),
|
|
863
|
+
cu_seqlens=cu_seqlens,
|
|
864
|
+
rotary_pos_emb=rotary_pos_emb,
|
|
865
|
+
position_embeddings=position_embeddings,
|
|
866
|
+
**kwargs,
|
|
867
|
+
)
|
|
868
|
+
hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
|
|
869
|
+
return hidden_states
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
@auto_docstring
|
|
873
|
+
class Ernie4_5_VL_MoeVisionTransformerPretrainedModel(Ernie4_5_VL_MoePreTrainedModel):
|
|
874
|
+
config: Ernie4_5_VL_MoeVisionConfig
|
|
875
|
+
input_modalities = ("image", "video")
|
|
876
|
+
_no_split_modules = ["Ernie4_5_VL_MoeVisionBlock"]
|
|
877
|
+
_input_embed_layer = "patch_embed"
|
|
878
|
+
|
|
879
|
+
def __init__(self, config) -> None:
|
|
880
|
+
super().__init__(config)
|
|
881
|
+
self.spatial_merge_size = config.spatial_merge_size
|
|
882
|
+
|
|
883
|
+
self.patch_embed = Ernie4_5_VL_MoePatchEmbed(
|
|
884
|
+
patch_size=config.patch_size,
|
|
885
|
+
in_channels=config.in_channels,
|
|
886
|
+
embed_dim=config.hidden_size,
|
|
887
|
+
)
|
|
888
|
+
|
|
889
|
+
head_dim = config.hidden_size // config.num_heads
|
|
890
|
+
self.rotary_pos_emb = Ernie4_5_VL_MoeVisionRotaryEmbedding(head_dim // 2)
|
|
891
|
+
|
|
892
|
+
self.blocks = nn.ModuleList([Ernie4_5_VL_MoeVisionBlock(config) for _ in range(config.depth)])
|
|
893
|
+
self.gradient_checkpointing = False
|
|
894
|
+
|
|
895
|
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
|
|
896
|
+
|
|
897
|
+
self.post_init()
|
|
898
|
+
|
|
899
|
+
def rot_pos_emb(self, grid_thw):
|
|
900
|
+
pos_ids = []
|
|
901
|
+
for t, h, w in grid_thw:
|
|
902
|
+
hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
|
|
903
|
+
hpos_ids = hpos_ids.reshape(
|
|
904
|
+
h // self.spatial_merge_size,
|
|
905
|
+
self.spatial_merge_size,
|
|
906
|
+
w // self.spatial_merge_size,
|
|
907
|
+
self.spatial_merge_size,
|
|
908
|
+
)
|
|
909
|
+
hpos_ids = hpos_ids.permute(0, 2, 1, 3)
|
|
910
|
+
hpos_ids = hpos_ids.flatten()
|
|
911
|
+
|
|
912
|
+
wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
|
|
913
|
+
wpos_ids = wpos_ids.reshape(
|
|
914
|
+
h // self.spatial_merge_size,
|
|
915
|
+
self.spatial_merge_size,
|
|
916
|
+
w // self.spatial_merge_size,
|
|
917
|
+
self.spatial_merge_size,
|
|
918
|
+
)
|
|
919
|
+
wpos_ids = wpos_ids.permute(0, 2, 1, 3)
|
|
920
|
+
wpos_ids = wpos_ids.flatten()
|
|
921
|
+
pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
|
|
922
|
+
pos_ids = torch.cat(pos_ids, dim=0)
|
|
923
|
+
max_grid_size = grid_thw[:, 1:].max()
|
|
924
|
+
rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
|
|
925
|
+
rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
|
|
926
|
+
return rotary_pos_emb
|
|
927
|
+
|
|
928
|
+
@auto_docstring
|
|
929
|
+
def forward(
|
|
930
|
+
self,
|
|
931
|
+
hidden_states: torch.Tensor,
|
|
932
|
+
grid_thw: torch.Tensor,
|
|
933
|
+
**kwargs,
|
|
934
|
+
) -> torch.Tensor:
|
|
935
|
+
r"""
|
|
936
|
+
grid_thw (`torch.LongTensor` of shape `(num_images, 3)`):
|
|
937
|
+
The temporal, height and width dimensions of feature shape for each image. Each row contains [t, h, w] values.
|
|
938
|
+
"""
|
|
939
|
+
hidden_states = self.patch_embed(hidden_states)
|
|
940
|
+
rotary_pos_emb = self.rot_pos_emb(grid_thw)
|
|
941
|
+
emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
|
|
942
|
+
position_embeddings = (emb.cos(), emb.sin())
|
|
943
|
+
|
|
944
|
+
cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
|
|
945
|
+
dim=0,
|
|
946
|
+
# Select dtype based on the following factors:
|
|
947
|
+
# - FA2 requires that cu_seqlens_q must have dtype int32
|
|
948
|
+
# - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
|
|
949
|
+
# See https://github.com/huggingface/transformers/pull/34852 for more information
|
|
950
|
+
dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
|
|
951
|
+
)
|
|
952
|
+
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
|
|
953
|
+
|
|
954
|
+
for block in self.blocks:
|
|
955
|
+
hidden_states = block(
|
|
956
|
+
hidden_states,
|
|
957
|
+
cu_seqlens=cu_seqlens,
|
|
958
|
+
position_embeddings=position_embeddings,
|
|
959
|
+
**kwargs,
|
|
960
|
+
)
|
|
961
|
+
hidden_states = self.ln(hidden_states)
|
|
962
|
+
return hidden_states
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
class Ernie4_5_VL_MoeVisionMLP(nn.Module):
|
|
966
|
+
def __init__(self, config, in_dim, out_dim):
|
|
967
|
+
super().__init__()
|
|
968
|
+
|
|
969
|
+
self.fc1 = nn.Linear(in_dim, out_dim)
|
|
970
|
+
self.act_fn = nn.GELU()
|
|
971
|
+
self.fc2 = nn.Linear(out_dim, out_dim)
|
|
972
|
+
self.ln = nn.LayerNorm(out_dim, eps=config.vision_config.rms_norm_eps)
|
|
973
|
+
|
|
974
|
+
def forward(self, hidden_states):
|
|
975
|
+
hidden_states = self.fc1(hidden_states)
|
|
976
|
+
hidden_states = self.act_fn(hidden_states)
|
|
977
|
+
hidden_states = self.fc2(hidden_states)
|
|
978
|
+
hidden_states = self.ln(hidden_states)
|
|
979
|
+
return hidden_states
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
class Ernie4_5_VL_MoeVariableResolutionResamplerModel(nn.Module):
|
|
983
|
+
def __init__(self, config: Ernie4_5_VL_MoeConfig):
|
|
984
|
+
super().__init__()
|
|
985
|
+
self.config = config
|
|
986
|
+
|
|
987
|
+
self.in_dim = config.vision_config.hidden_size
|
|
988
|
+
self.out_dim = config.text_config.hidden_size
|
|
989
|
+
self.spatial_merge_size = config.vision_config.spatial_merge_size
|
|
990
|
+
self.temporal_merge_size = config.vision_config.temporal_merge_size
|
|
991
|
+
|
|
992
|
+
# compress 2d conv(picture) to 1d
|
|
993
|
+
self.spatial_dim = self.in_dim * self.spatial_merge_size**2
|
|
994
|
+
# compress 3d conv(video) to 1d
|
|
995
|
+
self.temporal_dim = self.in_dim * self.spatial_merge_size**2 * self.temporal_merge_size
|
|
996
|
+
|
|
997
|
+
self.spatial_linear = Ernie4_5_VL_MoeVisionMLP(config, self.spatial_dim, self.spatial_dim)
|
|
998
|
+
self.temporal_linear = Ernie4_5_VL_MoeVisionMLP(config, self.temporal_dim, self.spatial_dim)
|
|
999
|
+
|
|
1000
|
+
self.mlp = nn.Linear(self.spatial_dim, self.out_dim)
|
|
1001
|
+
self.after_norm = Ernie4_5_VL_MoeRMSNorm(self.out_dim, config.text_config.rms_norm_eps)
|
|
1002
|
+
|
|
1003
|
+
def _temporal_slicing(self, hidden_states, grid_thw):
|
|
1004
|
+
"""
|
|
1005
|
+
Slices along the temporal dimension in even/odd patterns (usually if we have a video input)
|
|
1006
|
+
or duplicates along temporal dimension (usually if we have an image input).
|
|
1007
|
+
|
|
1008
|
+
Example:
|
|
1009
|
+
Video input with temporal pattern of [1, -1, 2, -2, 3, -3]
|
|
1010
|
+
> Even input [1, 2, 3], odd input [-1, -2, -3]
|
|
1011
|
+
> Reorderd via slices to [1, 2, 3, -1, -2, -3]
|
|
1012
|
+
Image input with temporal pattern [1]
|
|
1013
|
+
> Duplicate input [1], [1]
|
|
1014
|
+
> Reordered to [1, 1]
|
|
1015
|
+
|
|
1016
|
+
NOTE: This is hard-coded for `temporal_merge_size == 2` and won't work otherwise.
|
|
1017
|
+
"""
|
|
1018
|
+
# Calculating offsets on spatial dim (based on flattened tensors)
|
|
1019
|
+
grid_t, grid_hw = grid_thw[:, 0], grid_thw[:, 1:]
|
|
1020
|
+
grid_hw_after_conv = grid_hw.prod(-1) // (self.spatial_merge_size**2)
|
|
1021
|
+
|
|
1022
|
+
# Calculating offsets on batch dim (based on flattened tensors)
|
|
1023
|
+
tokens_per_img_or_vid = (grid_thw.prod(-1) // (self.spatial_merge_size**2)).flatten()
|
|
1024
|
+
batch_offsets = torch.empty(tokens_per_img_or_vid.size(), dtype=tokens_per_img_or_vid.dtype)
|
|
1025
|
+
batch_offsets[0] = 0
|
|
1026
|
+
batch_offsets[1:] = tokens_per_img_or_vid.cumsum(dim=0)[:-1]
|
|
1027
|
+
|
|
1028
|
+
first_slice_offsets = []
|
|
1029
|
+
second_slice_offsets = []
|
|
1030
|
+
for temporal_size, spatial_size, batch_offset in zip(grid_t, grid_hw_after_conv, batch_offsets):
|
|
1031
|
+
# Depending on temporal, we may interleave:
|
|
1032
|
+
# - Images have temporal == 1 --> same offsets (duplicate "frame" image)
|
|
1033
|
+
# - Videos have temporal > 1 --> different offsets (even, odd)
|
|
1034
|
+
first_offset_range = range(0, temporal_size, 2)
|
|
1035
|
+
second_offset_range = range(1 if temporal_size > 1 else 0, temporal_size, 2)
|
|
1036
|
+
|
|
1037
|
+
for temporal_offset_even, temporal_offset_odd in zip(first_offset_range, second_offset_range):
|
|
1038
|
+
first_slice_offsets.append(
|
|
1039
|
+
torch.arange(
|
|
1040
|
+
batch_offset + (temporal_offset_even) * spatial_size,
|
|
1041
|
+
batch_offset + (temporal_offset_even + 1) * spatial_size,
|
|
1042
|
+
)
|
|
1043
|
+
)
|
|
1044
|
+
second_slice_offsets.append(
|
|
1045
|
+
torch.arange(
|
|
1046
|
+
batch_offset + (temporal_offset_odd) * spatial_size,
|
|
1047
|
+
batch_offset + (temporal_offset_odd + 1) * spatial_size,
|
|
1048
|
+
)
|
|
1049
|
+
)
|
|
1050
|
+
|
|
1051
|
+
# Input: [1, -1, 2, -2, 3, -3] or [1]
|
|
1052
|
+
# Indices: [0, 2, 4] (even) or [0] (duplicate)
|
|
1053
|
+
first_slice_offsets = torch.cat(first_slice_offsets, dim=-1).to(hidden_states.device)
|
|
1054
|
+
# Indices: [1, 3, 5] (odd) or [0] (duplicate)
|
|
1055
|
+
second_slice_offsets = torch.cat(second_slice_offsets, dim=-1).to(hidden_states.device)
|
|
1056
|
+
|
|
1057
|
+
# Output: [1, 2, 3, -1, -2, -3] or [1, 1]
|
|
1058
|
+
return torch.concat(
|
|
1059
|
+
[
|
|
1060
|
+
torch.index_select(hidden_states, dim=0, index=first_slice_offsets),
|
|
1061
|
+
torch.index_select(hidden_states, dim=0, index=second_slice_offsets),
|
|
1062
|
+
],
|
|
1063
|
+
dim=-1,
|
|
1064
|
+
)
|
|
1065
|
+
|
|
1066
|
+
def forward(self, hidden_states, grid_thw):
|
|
1067
|
+
# image spatial
|
|
1068
|
+
# reshape imitates convolution via linear projection
|
|
1069
|
+
hidden_states = hidden_states.reshape([-1, hidden_states.shape[-1] * (self.spatial_merge_size**2)])
|
|
1070
|
+
hidden_states = self.spatial_linear(hidden_states)
|
|
1071
|
+
|
|
1072
|
+
# video temporal
|
|
1073
|
+
hidden_states = self._temporal_slicing(hidden_states, grid_thw)
|
|
1074
|
+
hidden_states = self.temporal_linear(hidden_states)
|
|
1075
|
+
|
|
1076
|
+
# final mlp
|
|
1077
|
+
hidden_states = self.mlp(hidden_states)
|
|
1078
|
+
hidden_states = self.after_norm(hidden_states)
|
|
1079
|
+
|
|
1080
|
+
return hidden_states
|
|
1081
|
+
|
|
1082
|
+
|
|
1083
|
+
@auto_docstring
|
|
1084
|
+
class Ernie4_5_VL_MoeModel(Ernie4_5_VL_MoePreTrainedModel):
|
|
1085
|
+
base_model_prefix = "model"
|
|
1086
|
+
_checkpoint_conversion_mapping = {"^norm": "language_model.norm"}
|
|
1087
|
+
# Reference: fix gemma3 grad acc #37208
|
|
1088
|
+
accepts_loss_kwargs = False
|
|
1089
|
+
config: Ernie4_5_VL_MoeConfig
|
|
1090
|
+
_no_split_modules = ["Ernie4_5_VL_MoeDecoderLayer", "Ernie4_5_VL_MoeVisionBlock"]
|
|
1091
|
+
|
|
1092
|
+
def __init__(self, config: Ernie4_5_VL_MoeConfig):
|
|
1093
|
+
super().__init__(config)
|
|
1094
|
+
self.language_model = Ernie4_5_VL_MoeTextModel._from_config(config.text_config)
|
|
1095
|
+
self.rope_deltas = None # cache rope_deltas here
|
|
1096
|
+
self.vision_tower = Ernie4_5_VL_MoeVisionTransformerPretrainedModel._from_config(config.vision_config)
|
|
1097
|
+
self.resampler_model = Ernie4_5_VL_MoeVariableResolutionResamplerModel(config)
|
|
1098
|
+
|
|
1099
|
+
# Initialize weights and apply final processing
|
|
1100
|
+
self.post_init()
|
|
1101
|
+
|
|
1102
|
+
def get_input_embeddings(self):
|
|
1103
|
+
return self.language_model.get_input_embeddings()
|
|
1104
|
+
|
|
1105
|
+
def set_input_embeddings(self, value):
|
|
1106
|
+
self.language_model.set_input_embeddings(value)
|
|
1107
|
+
|
|
1108
|
+
def get_rope_index(
|
|
1109
|
+
self,
|
|
1110
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
1111
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
1112
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
1113
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1114
|
+
mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1115
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
1116
|
+
"""
|
|
1117
|
+
Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
|
|
1118
|
+
|
|
1119
|
+
Explanation:
|
|
1120
|
+
Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
|
|
1121
|
+
|
|
1122
|
+
For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
|
|
1123
|
+
Examples:
|
|
1124
|
+
input_ids: [T T T T T], here T is for text.
|
|
1125
|
+
temporal position_ids: [0, 1, 2, 3, 4]
|
|
1126
|
+
height position_ids: [0, 1, 2, 3, 4]
|
|
1127
|
+
width position_ids: [0, 1, 2, 3, 4]
|
|
1128
|
+
|
|
1129
|
+
For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
|
|
1130
|
+
and 1D rotary position embedding for text part.
|
|
1131
|
+
Examples:
|
|
1132
|
+
Temporal (Time): 3 patches, representing different segments of the video in time.
|
|
1133
|
+
Height: 2 patches, dividing each frame vertically.
|
|
1134
|
+
Width: 2 patches, dividing each frame horizontally.
|
|
1135
|
+
We also have some important parameters:
|
|
1136
|
+
fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
|
|
1137
|
+
tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity.
|
|
1138
|
+
temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
|
|
1139
|
+
interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs.
|
|
1140
|
+
input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
|
|
1141
|
+
vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
|
|
1142
|
+
vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
|
|
1143
|
+
vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
|
|
1144
|
+
text temporal position_ids: [101, 102, 103, 104, 105]
|
|
1145
|
+
text height position_ids: [101, 102, 103, 104, 105]
|
|
1146
|
+
text width position_ids: [101, 102, 103, 104, 105]
|
|
1147
|
+
Here we calculate the text start position_ids as the max vision position_ids plus 1.
|
|
1148
|
+
|
|
1149
|
+
Args:
|
|
1150
|
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
|
1151
|
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
|
1152
|
+
it.
|
|
1153
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
1154
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
1155
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
1156
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
1157
|
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1158
|
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
|
1159
|
+
|
|
1160
|
+
- 1 for tokens that are **not masked**,
|
|
1161
|
+
- 0 for tokens that are **masked**.
|
|
1162
|
+
mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1163
|
+
Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
|
|
1164
|
+
|
|
1165
|
+
Returns:
|
|
1166
|
+
position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
|
|
1167
|
+
mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
|
|
1168
|
+
"""
|
|
1169
|
+
|
|
1170
|
+
temporal_merge_size = self.config.vision_config.temporal_merge_size
|
|
1171
|
+
spatial_merge_size = self.config.vision_config.spatial_merge_size
|
|
1172
|
+
|
|
1173
|
+
mrope_position_deltas = []
|
|
1174
|
+
if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
|
|
1175
|
+
total_input_ids = input_ids
|
|
1176
|
+
if attention_mask is None:
|
|
1177
|
+
attention_mask = torch.ones_like(total_input_ids)
|
|
1178
|
+
position_ids = torch.ones(
|
|
1179
|
+
3,
|
|
1180
|
+
input_ids.shape[0],
|
|
1181
|
+
input_ids.shape[1],
|
|
1182
|
+
dtype=input_ids.dtype,
|
|
1183
|
+
device=input_ids.device,
|
|
1184
|
+
)
|
|
1185
|
+
image_index, video_index = 0, 0
|
|
1186
|
+
attention_mask = attention_mask.to(total_input_ids.device)
|
|
1187
|
+
for i, input_ids in enumerate(total_input_ids):
|
|
1188
|
+
# If we don't have `mm_token_type_ids`, then we have text tokens only (== 0)
|
|
1189
|
+
if mm_token_type_ids is None:
|
|
1190
|
+
input_token_type = torch.zeros_like(input_ids)[attention_mask[i] == 1].tolist()
|
|
1191
|
+
else:
|
|
1192
|
+
input_token_type = mm_token_type_ids[i, attention_mask[i] == 1].tolist()
|
|
1193
|
+
|
|
1194
|
+
input_type_group = []
|
|
1195
|
+
for key, group in itertools.groupby(enumerate(input_token_type), lambda x: x[1]):
|
|
1196
|
+
group = list(group)
|
|
1197
|
+
start_index = group[0][0]
|
|
1198
|
+
end_index = group[-1][0] + 1
|
|
1199
|
+
input_type_group.append((key, start_index, end_index))
|
|
1200
|
+
|
|
1201
|
+
llm_pos_ids_list = []
|
|
1202
|
+
for modality_type, start_idx, end_idx in input_type_group:
|
|
1203
|
+
st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
|
|
1204
|
+
|
|
1205
|
+
# text == 0
|
|
1206
|
+
if modality_type == 0:
|
|
1207
|
+
text_len = end_idx - start_idx
|
|
1208
|
+
llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
|
|
1209
|
+
|
|
1210
|
+
# image == 1, video == 2
|
|
1211
|
+
else:
|
|
1212
|
+
grid_thw = image_grid_thw if modality_type == 1 else video_grid_thw
|
|
1213
|
+
mm_index = image_index if modality_type == 1 else video_index
|
|
1214
|
+
t_merge_size = 1 if modality_type == 1 else temporal_merge_size
|
|
1215
|
+
|
|
1216
|
+
t, h, w = (
|
|
1217
|
+
grid_thw[mm_index][0],
|
|
1218
|
+
grid_thw[mm_index][1],
|
|
1219
|
+
grid_thw[mm_index][2],
|
|
1220
|
+
)
|
|
1221
|
+
llm_grid_t, llm_grid_h, llm_grid_w = (
|
|
1222
|
+
t.item() // t_merge_size,
|
|
1223
|
+
h.item() // spatial_merge_size,
|
|
1224
|
+
w.item() // spatial_merge_size,
|
|
1225
|
+
)
|
|
1226
|
+
|
|
1227
|
+
for t_idx in range(llm_grid_t):
|
|
1228
|
+
t_index = torch.tensor(t_idx).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
|
|
1229
|
+
h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(1, -1, llm_grid_w).flatten()
|
|
1230
|
+
w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(1, llm_grid_h, -1).flatten()
|
|
1231
|
+
llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx)
|
|
1232
|
+
|
|
1233
|
+
if modality_type == 1:
|
|
1234
|
+
image_index += 1
|
|
1235
|
+
else:
|
|
1236
|
+
video_index += 1
|
|
1237
|
+
|
|
1238
|
+
llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
|
|
1239
|
+
position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
|
|
1240
|
+
mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
|
|
1241
|
+
mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
|
|
1242
|
+
return position_ids, mrope_position_deltas
|
|
1243
|
+
else:
|
|
1244
|
+
if attention_mask is not None:
|
|
1245
|
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
|
1246
|
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
|
1247
|
+
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
|
|
1248
|
+
max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
|
|
1249
|
+
mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
|
|
1250
|
+
else:
|
|
1251
|
+
position_ids = (
|
|
1252
|
+
torch.arange(input_ids.shape[1], device=input_ids.device)
|
|
1253
|
+
.view(1, 1, -1)
|
|
1254
|
+
.expand(3, input_ids.shape[0], -1)
|
|
1255
|
+
)
|
|
1256
|
+
mrope_position_deltas = torch.zeros(
|
|
1257
|
+
[input_ids.shape[0], 1],
|
|
1258
|
+
device=input_ids.device,
|
|
1259
|
+
dtype=input_ids.dtype,
|
|
1260
|
+
)
|
|
1261
|
+
|
|
1262
|
+
return position_ids, mrope_position_deltas
|
|
1263
|
+
|
|
1264
|
+
def get_video_features(
|
|
1265
|
+
self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
|
|
1266
|
+
):
|
|
1267
|
+
"""
|
|
1268
|
+
Encodes videos into continuous embeddings that can be forwarded to the language model.
|
|
1269
|
+
|
|
1270
|
+
Args:
|
|
1271
|
+
pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
|
1272
|
+
The tensors corresponding to the input videos.
|
|
1273
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
1274
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
1275
|
+
"""
|
|
1276
|
+
video_embeds = self.vision_tower(pixel_values_videos, video_grid_thw)
|
|
1277
|
+
video_embeds = self.resampler_model(video_embeds, video_grid_thw)
|
|
1278
|
+
split_sizes = (
|
|
1279
|
+
video_grid_thw.prod(-1)
|
|
1280
|
+
// self.vision_tower.spatial_merge_size**2
|
|
1281
|
+
// self.resampler_model.temporal_merge_size
|
|
1282
|
+
).tolist()
|
|
1283
|
+
video_embeds = torch.split(video_embeds, split_sizes)
|
|
1284
|
+
return video_embeds
|
|
1285
|
+
|
|
1286
|
+
def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
|
|
1287
|
+
"""
|
|
1288
|
+
Encodes images into continuous embeddings that can be forwarded to the language model.
|
|
1289
|
+
|
|
1290
|
+
Args:
|
|
1291
|
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
|
1292
|
+
The tensors corresponding to the input images.
|
|
1293
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
1294
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
1295
|
+
"""
|
|
1296
|
+
image_embeds = self.vision_tower(pixel_values, image_grid_thw)
|
|
1297
|
+
image_embeds = self.resampler_model(image_embeds, image_grid_thw)
|
|
1298
|
+
split_sizes = (image_grid_thw.prod(-1) // self.vision_tower.spatial_merge_size**2).tolist()
|
|
1299
|
+
image_embeds = torch.split(image_embeds, split_sizes)
|
|
1300
|
+
return image_embeds
|
|
1301
|
+
|
|
1302
|
+
def get_placeholder_mask(
|
|
1303
|
+
self,
|
|
1304
|
+
input_ids: torch.LongTensor,
|
|
1305
|
+
inputs_embeds: torch.FloatTensor,
|
|
1306
|
+
image_features: Optional[torch.FloatTensor] = None,
|
|
1307
|
+
video_features: Optional[torch.FloatTensor] = None,
|
|
1308
|
+
):
|
|
1309
|
+
"""
|
|
1310
|
+
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
|
|
1311
|
+
equal to the length of multimodal features. If the lengths are different, an error is raised.
|
|
1312
|
+
"""
|
|
1313
|
+
if input_ids is None:
|
|
1314
|
+
special_image_mask = inputs_embeds == self.get_input_embeddings()(
|
|
1315
|
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
|
1316
|
+
)
|
|
1317
|
+
special_image_mask = special_image_mask.all(-1)
|
|
1318
|
+
special_video_mask = inputs_embeds == self.get_input_embeddings()(
|
|
1319
|
+
torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
|
|
1320
|
+
)
|
|
1321
|
+
special_video_mask = special_video_mask.all(-1)
|
|
1322
|
+
else:
|
|
1323
|
+
special_image_mask = input_ids == self.config.image_token_id
|
|
1324
|
+
special_video_mask = input_ids == self.config.video_token_id
|
|
1325
|
+
|
|
1326
|
+
n_image_tokens = special_image_mask.sum()
|
|
1327
|
+
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
1328
|
+
if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel():
|
|
1329
|
+
raise ValueError(
|
|
1330
|
+
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
|
|
1331
|
+
)
|
|
1332
|
+
|
|
1333
|
+
n_video_tokens = special_video_mask.sum()
|
|
1334
|
+
special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
|
1335
|
+
if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
|
|
1336
|
+
raise ValueError(
|
|
1337
|
+
f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}"
|
|
1338
|
+
)
|
|
1339
|
+
|
|
1340
|
+
return special_image_mask, special_video_mask
|
|
1341
|
+
|
|
1342
|
+
@auto_docstring
|
|
1343
|
+
@can_return_tuple
|
|
1344
|
+
def forward(
|
|
1345
|
+
self,
|
|
1346
|
+
input_ids: torch.LongTensor = None,
|
|
1347
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1348
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
1349
|
+
mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1350
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1351
|
+
past_key_values: Optional[Cache] = None,
|
|
1352
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
1353
|
+
use_cache: Optional[bool] = None,
|
|
1354
|
+
pixel_values: Optional[torch.Tensor] = None,
|
|
1355
|
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
|
1356
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
1357
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
1358
|
+
rope_deltas: Optional[torch.LongTensor] = None,
|
|
1359
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
1360
|
+
**kwargs: Unpack[TransformersKwargs],
|
|
1361
|
+
) -> Union[tuple, MoeModelOutputWithPast]:
|
|
1362
|
+
r"""
|
|
1363
|
+
mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1364
|
+
Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
|
|
1365
|
+
moe_mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1366
|
+
The same as `mm_token_type_ids` while additionally considering start/end image/video tokens as respective vision tokens.
|
|
1367
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
1368
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
1369
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
1370
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
1371
|
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
|
1372
|
+
The rope index difference between sequence length and multimodal rope.
|
|
1373
|
+
"""
|
|
1374
|
+
if inputs_embeds is None:
|
|
1375
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
1376
|
+
|
|
1377
|
+
if pixel_values is not None:
|
|
1378
|
+
image_embeds = self.get_image_features(pixel_values, image_grid_thw)
|
|
1379
|
+
image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
|
|
1380
|
+
image_mask, _ = self.get_placeholder_mask(
|
|
1381
|
+
input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
|
|
1382
|
+
)
|
|
1383
|
+
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
|
|
1384
|
+
|
|
1385
|
+
if pixel_values_videos is not None:
|
|
1386
|
+
video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
|
|
1387
|
+
video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
|
|
1388
|
+
_, video_mask = self.get_placeholder_mask(
|
|
1389
|
+
input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds
|
|
1390
|
+
)
|
|
1391
|
+
inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
|
|
1392
|
+
|
|
1393
|
+
if position_ids is None:
|
|
1394
|
+
position_ids = self.get_position_ids(
|
|
1395
|
+
input_ids=input_ids,
|
|
1396
|
+
attention_mask=attention_mask,
|
|
1397
|
+
past_key_values=past_key_values,
|
|
1398
|
+
inputs_embeds=inputs_embeds,
|
|
1399
|
+
image_grid_thw=image_grid_thw,
|
|
1400
|
+
video_grid_thw=video_grid_thw,
|
|
1401
|
+
cache_position=cache_position,
|
|
1402
|
+
mm_token_type_ids=mm_token_type_ids,
|
|
1403
|
+
)
|
|
1404
|
+
|
|
1405
|
+
outputs = self.language_model(
|
|
1406
|
+
input_ids=None,
|
|
1407
|
+
position_ids=position_ids,
|
|
1408
|
+
moe_mm_token_type_ids=moe_mm_token_type_ids,
|
|
1409
|
+
attention_mask=attention_mask,
|
|
1410
|
+
use_cache=use_cache,
|
|
1411
|
+
past_key_values=past_key_values,
|
|
1412
|
+
inputs_embeds=inputs_embeds,
|
|
1413
|
+
return_dict=True,
|
|
1414
|
+
cache_position=cache_position,
|
|
1415
|
+
**kwargs,
|
|
1416
|
+
)
|
|
1417
|
+
|
|
1418
|
+
return MoeModelOutputWithPast(
|
|
1419
|
+
last_hidden_state=outputs.last_hidden_state,
|
|
1420
|
+
past_key_values=outputs.past_key_values,
|
|
1421
|
+
hidden_states=outputs.hidden_states,
|
|
1422
|
+
attentions=outputs.attentions,
|
|
1423
|
+
router_logits=outputs.router_logits,
|
|
1424
|
+
)
|
|
1425
|
+
|
|
1426
|
+
# TODO: Should be moved to generation loop instead in the future
|
|
1427
|
+
# Relevant PR(s): https://github.com/huggingface/transformers/pull/42088
|
|
1428
|
+
def get_position_ids(
|
|
1429
|
+
self,
|
|
1430
|
+
input_ids: torch.LongTensor = None,
|
|
1431
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1432
|
+
past_key_values: Optional[Cache] = None,
|
|
1433
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
1434
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
1435
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
1436
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
1437
|
+
mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1438
|
+
):
|
|
1439
|
+
"""
|
|
1440
|
+
Calculating the 3D position ids with a custom mechanism / caching
|
|
1441
|
+
- First forward calculates the initial positions and the respective
|
|
1442
|
+
deltas (offset) for subsequent positions. See `get_rope_index` for
|
|
1443
|
+
more details.
|
|
1444
|
+
- Second and on (generation), uses the cache position combined with the
|
|
1445
|
+
cached deltas to determine the current position.
|
|
1446
|
+
|
|
1447
|
+
NOTE: We assume that the position ids are `None` and recalculate them here in any case.
|
|
1448
|
+
"""
|
|
1449
|
+
# Calculate RoPE index once per generation in the pre-fill stage only.
|
|
1450
|
+
# When compiling, we can't check tensor values thus we check only input length
|
|
1451
|
+
# It is safe to assume that `length!=1` means we're in pre-fill because compiled
|
|
1452
|
+
# models currently cannot do asssisted decoding
|
|
1453
|
+
prefill_compiled_stage = is_torchdynamo_compiling() and (
|
|
1454
|
+
(input_ids is not None and input_ids.shape[1] != 1)
|
|
1455
|
+
or (inputs_embeds is not None and inputs_embeds.shape[1] != 1)
|
|
1456
|
+
)
|
|
1457
|
+
prefill_noncompiled_stage = not is_torchdynamo_compiling() and (
|
|
1458
|
+
(cache_position is not None and cache_position[0] == 0)
|
|
1459
|
+
or (past_key_values is None or past_key_values.get_seq_length() == 0)
|
|
1460
|
+
)
|
|
1461
|
+
if (prefill_compiled_stage or prefill_noncompiled_stage) or self.rope_deltas is None:
|
|
1462
|
+
position_ids, rope_deltas = self.get_rope_index(
|
|
1463
|
+
input_ids,
|
|
1464
|
+
image_grid_thw,
|
|
1465
|
+
video_grid_thw,
|
|
1466
|
+
attention_mask=attention_mask,
|
|
1467
|
+
mm_token_type_ids=mm_token_type_ids,
|
|
1468
|
+
)
|
|
1469
|
+
self.rope_deltas = rope_deltas
|
|
1470
|
+
# then use the prev pre-calculated rope-deltas to get the correct position ids
|
|
1471
|
+
else:
|
|
1472
|
+
if input_ids is not None:
|
|
1473
|
+
batch_size, seq_length, device = input_ids.shape[0], 1, input_ids.device
|
|
1474
|
+
elif inputs_embeds is not None:
|
|
1475
|
+
batch_size, seq_length, device = inputs_embeds.shape[0], 1, inputs_embeds.device
|
|
1476
|
+
else:
|
|
1477
|
+
raise ValueError(
|
|
1478
|
+
"Cannot calculate position ids without any input to the model. "
|
|
1479
|
+
"Need either `input_ids` or `inputs_embeds`!"
|
|
1480
|
+
)
|
|
1481
|
+
|
|
1482
|
+
delta = (cache_position[0] + self.rope_deltas).to(device) if cache_position is not None else 0
|
|
1483
|
+
position_ids = torch.arange(seq_length, device=device)
|
|
1484
|
+
position_ids = position_ids.view(1, -1).expand(batch_size, -1)
|
|
1485
|
+
if cache_position is not None: # otherwise `deltas` is an int `0`
|
|
1486
|
+
delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0)
|
|
1487
|
+
position_ids = position_ids.add(delta)
|
|
1488
|
+
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
|
|
1489
|
+
|
|
1490
|
+
return position_ids
|
|
1491
|
+
|
|
1492
|
+
|
|
1493
|
+
def load_balancing_loss_func(
|
|
1494
|
+
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
|
|
1495
|
+
num_experts: Optional[int] = None,
|
|
1496
|
+
top_k=2,
|
|
1497
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1498
|
+
) -> Union[torch.Tensor, int]:
|
|
1499
|
+
r"""
|
|
1500
|
+
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
|
1501
|
+
|
|
1502
|
+
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
|
|
1503
|
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
|
1504
|
+
experts is too unbalanced.
|
|
1505
|
+
|
|
1506
|
+
Args:
|
|
1507
|
+
gate_logits:
|
|
1508
|
+
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
|
1509
|
+
shape [batch_size X sequence_length, num_experts].
|
|
1510
|
+
num_experts:
|
|
1511
|
+
Number of experts
|
|
1512
|
+
top_k:
|
|
1513
|
+
The number of experts to route per-token, can be also interpreted as the `top-k` routing
|
|
1514
|
+
parameter.
|
|
1515
|
+
attention_mask (`torch.Tensor`, *optional*):
|
|
1516
|
+
The attention_mask used in forward function
|
|
1517
|
+
shape [batch_size X sequence_length] if not None.
|
|
1518
|
+
|
|
1519
|
+
Returns:
|
|
1520
|
+
The auxiliary loss.
|
|
1521
|
+
"""
|
|
1522
|
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
|
1523
|
+
return 0
|
|
1524
|
+
|
|
1525
|
+
if isinstance(gate_logits, tuple):
|
|
1526
|
+
compute_device = gate_logits[0].device
|
|
1527
|
+
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
|
|
1528
|
+
|
|
1529
|
+
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
|
|
1530
|
+
|
|
1531
|
+
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
|
|
1532
|
+
|
|
1533
|
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
|
|
1534
|
+
|
|
1535
|
+
if attention_mask is None:
|
|
1536
|
+
# Compute the percentage of tokens routed to each experts
|
|
1537
|
+
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
|
|
1538
|
+
|
|
1539
|
+
# Compute the average probability of routing to these experts
|
|
1540
|
+
router_prob_per_expert = torch.mean(routing_weights, dim=0)
|
|
1541
|
+
else:
|
|
1542
|
+
batch_size, sequence_length = attention_mask.shape
|
|
1543
|
+
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
|
|
1544
|
+
|
|
1545
|
+
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
|
1546
|
+
expert_attention_mask = (
|
|
1547
|
+
attention_mask[None, :, :, None, None]
|
|
1548
|
+
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
|
|
1549
|
+
.reshape(-1, top_k, num_experts)
|
|
1550
|
+
.to(compute_device)
|
|
1551
|
+
)
|
|
1552
|
+
|
|
1553
|
+
# Compute the percentage of tokens routed to each experts
|
|
1554
|
+
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
|
|
1555
|
+
expert_attention_mask, dim=0
|
|
1556
|
+
)
|
|
1557
|
+
|
|
1558
|
+
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
|
1559
|
+
router_per_expert_attention_mask = (
|
|
1560
|
+
attention_mask[None, :, :, None]
|
|
1561
|
+
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
|
|
1562
|
+
.reshape(-1, num_experts)
|
|
1563
|
+
.to(compute_device)
|
|
1564
|
+
)
|
|
1565
|
+
|
|
1566
|
+
# Compute the average probability of routing to these experts
|
|
1567
|
+
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
|
|
1568
|
+
router_per_expert_attention_mask, dim=0
|
|
1569
|
+
)
|
|
1570
|
+
|
|
1571
|
+
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
|
|
1572
|
+
return overall_loss * num_experts
|
|
1573
|
+
|
|
1574
|
+
|
|
1575
|
+
class Ernie4_5_VL_MoeForConditionalGeneration(Ernie4_5_VL_MoePreTrainedModel, GenerationMixin):
|
|
1576
|
+
_checkpoint_conversion_mapping = {"^model.norm": "model.language_model.norm"}
|
|
1577
|
+
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
|
|
1578
|
+
# Reference: fix gemma3 grad acc #37208
|
|
1579
|
+
accepts_loss_kwargs = False
|
|
1580
|
+
|
|
1581
|
+
def __init__(self, config):
|
|
1582
|
+
super().__init__(config)
|
|
1583
|
+
self.model = Ernie4_5_VL_MoeModel(config)
|
|
1584
|
+
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
|
|
1585
|
+
|
|
1586
|
+
self.router_aux_loss_coef = config.text_config.router_aux_loss_coef
|
|
1587
|
+
self.num_experts = config.text_config.moe_num_experts
|
|
1588
|
+
self.num_experts_per_tok = config.text_config.moe_k
|
|
1589
|
+
|
|
1590
|
+
self.post_init()
|
|
1591
|
+
|
|
1592
|
+
def get_input_embeddings(self):
|
|
1593
|
+
return self.model.get_input_embeddings()
|
|
1594
|
+
|
|
1595
|
+
def set_input_embeddings(self, value):
|
|
1596
|
+
self.model.set_input_embeddings(value)
|
|
1597
|
+
|
|
1598
|
+
def get_video_features(
|
|
1599
|
+
self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
|
|
1600
|
+
):
|
|
1601
|
+
return self.model.get_video_features(pixel_values_videos, video_grid_thw)
|
|
1602
|
+
|
|
1603
|
+
def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
|
|
1604
|
+
return self.model.get_image_features(pixel_values, image_grid_thw)
|
|
1605
|
+
|
|
1606
|
+
@auto_docstring
|
|
1607
|
+
@can_return_tuple
|
|
1608
|
+
def forward(
|
|
1609
|
+
self,
|
|
1610
|
+
input_ids: torch.LongTensor = None,
|
|
1611
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1612
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
1613
|
+
mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1614
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1615
|
+
past_key_values: Optional[Cache] = None,
|
|
1616
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
1617
|
+
labels: Optional[torch.LongTensor] = None,
|
|
1618
|
+
use_cache: Optional[bool] = None,
|
|
1619
|
+
output_router_logits: Optional[bool] = None,
|
|
1620
|
+
pixel_values: Optional[torch.Tensor] = None,
|
|
1621
|
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
|
1622
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
1623
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
1624
|
+
rope_deltas: Optional[torch.LongTensor] = None,
|
|
1625
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
1626
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
1627
|
+
**kwargs: Unpack[TransformersKwargs],
|
|
1628
|
+
) -> Union[tuple, MoeCausalLMOutputWithPast]:
|
|
1629
|
+
r"""
|
|
1630
|
+
mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1631
|
+
Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
|
|
1632
|
+
moe_mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1633
|
+
The same as `mm_token_type_ids` while additionally considering start/end image/video tokens as respective vision tokens.
|
|
1634
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1635
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
1636
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
1637
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
1638
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
1639
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
1640
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
1641
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
1642
|
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
|
1643
|
+
The rope index difference between sequence length and multimodal rope.
|
|
1644
|
+
"""
|
|
1645
|
+
output_router_logits = (
|
|
1646
|
+
output_router_logits if output_router_logits is not None else self.config.text_config.output_router_logits
|
|
1647
|
+
)
|
|
1648
|
+
|
|
1649
|
+
outputs = self.model(
|
|
1650
|
+
input_ids=input_ids,
|
|
1651
|
+
attention_mask=attention_mask,
|
|
1652
|
+
position_ids=position_ids,
|
|
1653
|
+
mm_token_type_ids=mm_token_type_ids,
|
|
1654
|
+
moe_mm_token_type_ids=moe_mm_token_type_ids,
|
|
1655
|
+
past_key_values=past_key_values,
|
|
1656
|
+
inputs_embeds=inputs_embeds,
|
|
1657
|
+
use_cache=use_cache,
|
|
1658
|
+
output_router_logits=output_router_logits,
|
|
1659
|
+
return_dict=True,
|
|
1660
|
+
pixel_values=pixel_values,
|
|
1661
|
+
pixel_values_videos=pixel_values_videos,
|
|
1662
|
+
image_grid_thw=image_grid_thw,
|
|
1663
|
+
video_grid_thw=video_grid_thw,
|
|
1664
|
+
rope_deltas=rope_deltas,
|
|
1665
|
+
cache_position=cache_position,
|
|
1666
|
+
**kwargs,
|
|
1667
|
+
)
|
|
1668
|
+
|
|
1669
|
+
hidden_states = outputs.last_hidden_state
|
|
1670
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
1671
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
1672
|
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
|
1673
|
+
|
|
1674
|
+
loss = None
|
|
1675
|
+
if labels is not None:
|
|
1676
|
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
|
|
1677
|
+
|
|
1678
|
+
aux_loss = None
|
|
1679
|
+
if output_router_logits:
|
|
1680
|
+
aux_loss = load_balancing_loss_func(
|
|
1681
|
+
outputs.router_logits,
|
|
1682
|
+
self.num_experts,
|
|
1683
|
+
self.num_experts_per_tok,
|
|
1684
|
+
attention_mask,
|
|
1685
|
+
)
|
|
1686
|
+
if labels is not None:
|
|
1687
|
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
|
1688
|
+
|
|
1689
|
+
return MoeCausalLMOutputWithPast(
|
|
1690
|
+
loss=loss,
|
|
1691
|
+
aux_loss=aux_loss,
|
|
1692
|
+
logits=logits,
|
|
1693
|
+
past_key_values=outputs.past_key_values,
|
|
1694
|
+
hidden_states=outputs.hidden_states,
|
|
1695
|
+
attentions=outputs.attentions,
|
|
1696
|
+
router_logits=outputs.router_logits,
|
|
1697
|
+
)
|
|
1698
|
+
|
|
1699
|
+
def prepare_inputs_for_generation(
|
|
1700
|
+
self,
|
|
1701
|
+
input_ids,
|
|
1702
|
+
inputs_embeds=None,
|
|
1703
|
+
attention_mask=None,
|
|
1704
|
+
cache_position=None,
|
|
1705
|
+
past_key_values=None,
|
|
1706
|
+
image_grid_thw=None,
|
|
1707
|
+
video_grid_thw=None,
|
|
1708
|
+
use_cache=True,
|
|
1709
|
+
is_first_iteration=False,
|
|
1710
|
+
# Intentionally ignore position ids to force custom cache logic
|
|
1711
|
+
position_ids=None,
|
|
1712
|
+
**kwargs,
|
|
1713
|
+
):
|
|
1714
|
+
model_inputs = super().prepare_inputs_for_generation(
|
|
1715
|
+
input_ids,
|
|
1716
|
+
inputs_embeds=inputs_embeds,
|
|
1717
|
+
attention_mask=attention_mask,
|
|
1718
|
+
cache_position=cache_position,
|
|
1719
|
+
past_key_values=past_key_values,
|
|
1720
|
+
image_grid_thw=image_grid_thw,
|
|
1721
|
+
video_grid_thw=video_grid_thw,
|
|
1722
|
+
use_cache=use_cache,
|
|
1723
|
+
is_first_iteration=is_first_iteration,
|
|
1724
|
+
**kwargs,
|
|
1725
|
+
)
|
|
1726
|
+
|
|
1727
|
+
# Using our own caching with rope delta
|
|
1728
|
+
model_inputs["position_ids"] = self.model.get_position_ids(
|
|
1729
|
+
input_ids=model_inputs.get("input_ids"),
|
|
1730
|
+
attention_mask=model_inputs.get("attention_mask"),
|
|
1731
|
+
past_key_values=model_inputs.get("past_key_values"),
|
|
1732
|
+
inputs_embeds=model_inputs.get("inputs_embeds"),
|
|
1733
|
+
image_grid_thw=model_inputs.get("image_grid_thw"),
|
|
1734
|
+
video_grid_thw=model_inputs.get("video_grid_thw"),
|
|
1735
|
+
cache_position=model_inputs.get("cache_position"),
|
|
1736
|
+
mm_token_type_ids=model_inputs.get("mm_token_type_ids"),
|
|
1737
|
+
)
|
|
1738
|
+
|
|
1739
|
+
if not is_first_iteration and use_cache:
|
|
1740
|
+
model_inputs["pixel_values"] = None
|
|
1741
|
+
model_inputs["pixel_values_videos"] = None
|
|
1742
|
+
model_inputs["mm_token_type_ids"] = None
|
|
1743
|
+
model_inputs["moe_mm_token_type_ids"] = None
|
|
1744
|
+
|
|
1745
|
+
return model_inputs
|
|
1746
|
+
|
|
1747
|
+
def _get_image_nums_and_video_nums(
|
|
1748
|
+
self,
|
|
1749
|
+
input_ids: Optional[torch.LongTensor],
|
|
1750
|
+
inputs_embeds: Optional[torch.Tensor] = None,
|
|
1751
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
1752
|
+
"""
|
|
1753
|
+
Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
|
|
1754
|
+
These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
|
|
1755
|
+
|
|
1756
|
+
Args:
|
|
1757
|
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
|
1758
|
+
Indices of input sequence tokens in the vocabulary.
|
|
1759
|
+
|
|
1760
|
+
Returns:
|
|
1761
|
+
image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
|
|
1762
|
+
video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
|
|
1763
|
+
"""
|
|
1764
|
+
|
|
1765
|
+
if inputs_embeds is not None:
|
|
1766
|
+
is_image = (
|
|
1767
|
+
inputs_embeds
|
|
1768
|
+
== self.get_input_embeddings()(
|
|
1769
|
+
torch.tensor(self.config.image_start_token_id, dtype=torch.long, device=inputs_embeds.device)
|
|
1770
|
+
)
|
|
1771
|
+
)[..., 0]
|
|
1772
|
+
is_video_start = (
|
|
1773
|
+
inputs_embeds
|
|
1774
|
+
== self.get_input_embeddings()(
|
|
1775
|
+
torch.tensor(self.config.video_start_token_id, dtype=torch.long, device=inputs_embeds.device)
|
|
1776
|
+
)
|
|
1777
|
+
)[..., 0]
|
|
1778
|
+
is_video_end = (
|
|
1779
|
+
inputs_embeds
|
|
1780
|
+
== self.get_input_embeddings()(
|
|
1781
|
+
torch.tensor(self.config.video_end_token_id, dtype=torch.long, device=inputs_embeds.device)
|
|
1782
|
+
)
|
|
1783
|
+
)[..., 0]
|
|
1784
|
+
else:
|
|
1785
|
+
is_image = input_ids == self.config.image_start_token_id
|
|
1786
|
+
is_video_start = input_ids == self.config.video_start_token_id
|
|
1787
|
+
is_video_end = input_ids == self.config.video_end_token_id
|
|
1788
|
+
|
|
1789
|
+
# Cumulative sum to track if we're inside a video span
|
|
1790
|
+
# We'll assume well-formed video tags (i.e. matching starts and ends)
|
|
1791
|
+
video_level = torch.cumsum(is_video_start.int() - is_video_end.int(), dim=1)
|
|
1792
|
+
inside_video = video_level > 0 # shape (batch_size, seq_length)
|
|
1793
|
+
|
|
1794
|
+
# Mask out image tokens that are inside video spans
|
|
1795
|
+
standalone_images = is_image & (~inside_video)
|
|
1796
|
+
|
|
1797
|
+
# Count per batch
|
|
1798
|
+
image_counts = standalone_images.sum(dim=1)
|
|
1799
|
+
video_counts = is_video_start.sum(dim=1)
|
|
1800
|
+
|
|
1801
|
+
return image_counts, video_counts
|
|
1802
|
+
|
|
1803
|
+
def _expand_inputs_for_generation(
|
|
1804
|
+
self,
|
|
1805
|
+
expand_size: int = 1,
|
|
1806
|
+
is_encoder_decoder: bool = False,
|
|
1807
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
1808
|
+
**model_kwargs,
|
|
1809
|
+
) -> tuple[torch.LongTensor, dict[str, Any]]:
|
|
1810
|
+
# Overwritten -- Support for expanding tensors without a batch size dimension
|
|
1811
|
+
# e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
|
|
1812
|
+
# pixel_values.shape[0] is sum(seqlen_images for samples)
|
|
1813
|
+
# image_grid_thw.shape[0] is sum(num_images for samples)
|
|
1814
|
+
|
|
1815
|
+
if expand_size == 1:
|
|
1816
|
+
return input_ids, model_kwargs
|
|
1817
|
+
|
|
1818
|
+
visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
|
|
1819
|
+
|
|
1820
|
+
def _expand_dict_for_generation_visual(dict_to_expand):
|
|
1821
|
+
image_grid_thw = model_kwargs.get("image_grid_thw", None)
|
|
1822
|
+
video_grid_thw = model_kwargs.get("video_grid_thw", None)
|
|
1823
|
+
image_nums, video_nums = self._get_image_nums_and_video_nums(
|
|
1824
|
+
input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
|
|
1825
|
+
)
|
|
1826
|
+
|
|
1827
|
+
def _repeat_interleave_samples(x, lengths, repeat_times):
|
|
1828
|
+
samples = torch.split(x, lengths)
|
|
1829
|
+
repeat_args = [repeat_times] + [1] * (x.dim() - 1)
|
|
1830
|
+
result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
|
|
1831
|
+
return result
|
|
1832
|
+
|
|
1833
|
+
for key in dict_to_expand:
|
|
1834
|
+
if key == "pixel_values":
|
|
1835
|
+
# split images into samples
|
|
1836
|
+
samples = torch.split(image_grid_thw, list(image_nums))
|
|
1837
|
+
# compute the sequence length of images for each sample
|
|
1838
|
+
lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
|
|
1839
|
+
dict_to_expand[key] = _repeat_interleave_samples(
|
|
1840
|
+
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
|
|
1841
|
+
)
|
|
1842
|
+
elif key == "image_grid_thw":
|
|
1843
|
+
# get the num of images for each sample
|
|
1844
|
+
lengths = list(image_nums)
|
|
1845
|
+
dict_to_expand[key] = _repeat_interleave_samples(
|
|
1846
|
+
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
|
|
1847
|
+
)
|
|
1848
|
+
elif key == "pixel_values_videos":
|
|
1849
|
+
samples = torch.split(video_grid_thw, list(video_nums))
|
|
1850
|
+
lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
|
|
1851
|
+
dict_to_expand[key] = _repeat_interleave_samples(
|
|
1852
|
+
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
|
|
1853
|
+
)
|
|
1854
|
+
elif key == "video_grid_thw":
|
|
1855
|
+
lengths = list(video_nums)
|
|
1856
|
+
dict_to_expand[key] = _repeat_interleave_samples(
|
|
1857
|
+
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
|
|
1858
|
+
)
|
|
1859
|
+
elif key == "second_per_grid_ts":
|
|
1860
|
+
dict_to_expand[key] = _repeat_interleave_samples(
|
|
1861
|
+
dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
|
|
1862
|
+
)
|
|
1863
|
+
return dict_to_expand
|
|
1864
|
+
|
|
1865
|
+
def _expand_dict_for_generation(dict_to_expand):
|
|
1866
|
+
for key in dict_to_expand:
|
|
1867
|
+
if (
|
|
1868
|
+
key != "cache_position"
|
|
1869
|
+
and dict_to_expand[key] is not None
|
|
1870
|
+
and isinstance(dict_to_expand[key], torch.Tensor)
|
|
1871
|
+
and key not in visual_keys
|
|
1872
|
+
):
|
|
1873
|
+
dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
|
|
1874
|
+
return dict_to_expand
|
|
1875
|
+
|
|
1876
|
+
model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
|
|
1877
|
+
|
|
1878
|
+
if input_ids is not None:
|
|
1879
|
+
input_ids = input_ids.repeat_interleave(expand_size, dim=0)
|
|
1880
|
+
|
|
1881
|
+
model_kwargs = _expand_dict_for_generation(model_kwargs)
|
|
1882
|
+
|
|
1883
|
+
if is_encoder_decoder:
|
|
1884
|
+
if model_kwargs.get("encoder_outputs") is None:
|
|
1885
|
+
raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
|
|
1886
|
+
model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
|
|
1887
|
+
|
|
1888
|
+
return input_ids, model_kwargs
|
|
1889
|
+
|
|
1890
|
+
|
|
1891
|
+
__all__ = [
|
|
1892
|
+
"Ernie4_5_VL_MoePreTrainedModel",
|
|
1893
|
+
"Ernie4_5_VL_MoeForConditionalGeneration",
|
|
1894
|
+
"Ernie4_5_VL_MoeModel",
|
|
1895
|
+
"Ernie4_5_VL_MoeTextModel",
|
|
1896
|
+
"Ernie4_5_VL_MoeVisionTransformerPretrainedModel",
|
|
1897
|
+
"Ernie4_5_VL_MoeVariableResolutionResamplerModel",
|
|
1898
|
+
]
|