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,1904 @@
|
|
|
1
|
+
# coding=utf-8
|
|
2
|
+
# Copyright 2025 Baidu and HuggingFace Inc. team. All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
"""PyTorch Ernie4.5-VL model."""
|
|
16
|
+
|
|
17
|
+
import itertools
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from typing import Optional, Union
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import torch
|
|
23
|
+
import torch.nn as nn
|
|
24
|
+
import torch.nn.functional as F
|
|
25
|
+
|
|
26
|
+
from ... import initialization as init
|
|
27
|
+
from ...cache_utils import Cache, DynamicCache
|
|
28
|
+
from ...configuration_utils import PreTrainedConfig, layer_type_validation
|
|
29
|
+
from ...generation import GenerationMixin
|
|
30
|
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature
|
|
31
|
+
from ...image_processing_utils_fast import (
|
|
32
|
+
group_images_by_shape,
|
|
33
|
+
reorder_images,
|
|
34
|
+
)
|
|
35
|
+
from ...image_transforms import convert_to_rgb, resize, to_channel_dimension_format
|
|
36
|
+
from ...image_utils import (
|
|
37
|
+
OPENAI_CLIP_MEAN,
|
|
38
|
+
OPENAI_CLIP_STD,
|
|
39
|
+
ChannelDimension,
|
|
40
|
+
ImageInput,
|
|
41
|
+
PILImageResampling,
|
|
42
|
+
SizeDict,
|
|
43
|
+
get_image_size,
|
|
44
|
+
infer_channel_dimension_format,
|
|
45
|
+
is_scaled_image,
|
|
46
|
+
make_list_of_images,
|
|
47
|
+
to_numpy_array,
|
|
48
|
+
)
|
|
49
|
+
from ...masking_utils import create_causal_mask
|
|
50
|
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
|
51
|
+
from ...modeling_layers import GradientCheckpointingLayer
|
|
52
|
+
from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
|
53
|
+
from ...modeling_rope_utils import dynamic_rope_update
|
|
54
|
+
from ...modeling_utils import PreTrainedModel
|
|
55
|
+
from ...processing_utils import Unpack
|
|
56
|
+
from ...utils import (
|
|
57
|
+
TensorType,
|
|
58
|
+
TransformersKwargs,
|
|
59
|
+
auto_docstring,
|
|
60
|
+
can_return_tuple,
|
|
61
|
+
is_torchdynamo_compiling,
|
|
62
|
+
logging,
|
|
63
|
+
)
|
|
64
|
+
from ...utils.generic import OutputRecorder, check_model_inputs, maybe_autocast
|
|
65
|
+
from ..ernie4_5_moe.configuration_ernie4_5_moe import Ernie4_5_MoeConfig
|
|
66
|
+
from ..ernie4_5_moe.modeling_ernie4_5_moe import (
|
|
67
|
+
Ernie4_5_MoeAttention,
|
|
68
|
+
Ernie4_5_MoeExperts,
|
|
69
|
+
Ernie4_5_MoeMLP,
|
|
70
|
+
Ernie4_5_MoeModel,
|
|
71
|
+
Ernie4_5_MoeRMSNorm,
|
|
72
|
+
Ernie4_5_MoeStatics,
|
|
73
|
+
Ernie4_5_MoeTopKRouter,
|
|
74
|
+
)
|
|
75
|
+
from ..glm4v.image_processing_glm4v import Glm4vImageProcessor, Glm4vImageProcessorKwargs
|
|
76
|
+
from ..glm4v.image_processing_glm4v_fast import Glm4vImageProcessorFast
|
|
77
|
+
from ..glm4v.modeling_glm4v import Glm4vForConditionalGeneration
|
|
78
|
+
from ..mixtral.modeling_mixtral import load_balancing_loss_func
|
|
79
|
+
from ..qwen2_5_vl.modeling_qwen2_5_vl import (
|
|
80
|
+
Qwen2_5_VisionPatchEmbed,
|
|
81
|
+
Qwen2_5_VisionRotaryEmbedding,
|
|
82
|
+
Qwen2_5_VLModel,
|
|
83
|
+
Qwen2_5_VLPreTrainedModel,
|
|
84
|
+
Qwen2_5_VLVisionBlock,
|
|
85
|
+
)
|
|
86
|
+
from ..qwen2_vl.configuration_qwen2_vl import Qwen2VLVisionConfig
|
|
87
|
+
from ..qwen2_vl.image_processing_qwen2_vl import smart_resize
|
|
88
|
+
from ..qwen2_vl.modeling_qwen2_vl import Qwen2VisionTransformerPretrainedModel, VisionMlp
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
logger = logging.get_logger(__name__)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class Ernie4_5_VL_MoeVisionConfig(Qwen2VLVisionConfig):
|
|
95
|
+
r"""
|
|
96
|
+
This is the configuration class to store the configuration of the [`Ernie4_5_VL_MoeVisionTransformerPretrainedModel`].
|
|
97
|
+
It is used to instantiate the vision models portion of the complete Ernie4.5-VL Moe model according to the specified
|
|
98
|
+
arguments, defining the model architecture.
|
|
99
|
+
|
|
100
|
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
|
101
|
+
documentation from [`PretrainedConfig`] for more information.
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
depth (`int`, *optional*, defaults to 32):
|
|
105
|
+
Number of layers (depth) in the model.
|
|
106
|
+
hidden_size (`int`, *optional*, defaults to 1280):
|
|
107
|
+
Dimensionality of the encoder layers and the pooler layer.
|
|
108
|
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
|
109
|
+
The non-linear activation function (function or string) in the encoder and pooler.
|
|
110
|
+
intermediate_size (`int`, *optional*, defaults to 5120):
|
|
111
|
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
|
112
|
+
num_heads (`int`, *optional*, defaults to 16):
|
|
113
|
+
Number of attention heads for each attention layer in the Transformer encoder.
|
|
114
|
+
in_channels (`int`, *optional*, defaults to 3):
|
|
115
|
+
The number of input channels.
|
|
116
|
+
patch_size (`int`, *optional*, defaults to 14):
|
|
117
|
+
The size (resolution) of each patch.
|
|
118
|
+
spatial_merge_size (`int`, *optional*, defaults to 2):
|
|
119
|
+
The size used for merging spatial dimensions.
|
|
120
|
+
temporal_merge_size (`int`, *optional*, defaults to 2):
|
|
121
|
+
The size used for merge along the temporal dimension.
|
|
122
|
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
|
123
|
+
The epsilon used by the rms normalization layers.
|
|
124
|
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
|
125
|
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
model_type = "ernie4_5_vl_moe_vision"
|
|
129
|
+
|
|
130
|
+
base_model_tp_plan = {
|
|
131
|
+
"blocks.*.attn.qkv": "colwise",
|
|
132
|
+
"blocks.*.attn.proj": "rowwise",
|
|
133
|
+
"blocks.*.mlp.fc1": "colwise",
|
|
134
|
+
"blocks.*.mlp.fc2": "rowwise",
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
def __init__(
|
|
138
|
+
self,
|
|
139
|
+
depth=32,
|
|
140
|
+
hidden_size=1280,
|
|
141
|
+
hidden_act="quick_gelu",
|
|
142
|
+
intermediate_size=4 * 1280,
|
|
143
|
+
num_heads=16,
|
|
144
|
+
in_channels=3,
|
|
145
|
+
patch_size=14,
|
|
146
|
+
spatial_merge_size=2,
|
|
147
|
+
temporal_merge_size=2,
|
|
148
|
+
rms_norm_eps=1e-6,
|
|
149
|
+
initializer_range=0.02,
|
|
150
|
+
**kwargs,
|
|
151
|
+
):
|
|
152
|
+
super().__init__(
|
|
153
|
+
depth=depth,
|
|
154
|
+
hidden_size=hidden_size,
|
|
155
|
+
hidden_act=hidden_act,
|
|
156
|
+
intermediate_size=intermediate_size,
|
|
157
|
+
num_heads=num_heads,
|
|
158
|
+
in_channels=in_channels,
|
|
159
|
+
patch_size=patch_size,
|
|
160
|
+
spatial_merge_size=spatial_merge_size,
|
|
161
|
+
temporal_merge_size=temporal_merge_size,
|
|
162
|
+
rms_norm_eps=rms_norm_eps,
|
|
163
|
+
initializer_range=initializer_range,
|
|
164
|
+
**kwargs,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
del self.embed_dim # noqa: F821
|
|
168
|
+
del self.mlp_ratio # noqa: F821
|
|
169
|
+
del self.temporal_patch_size # noqa: F821
|
|
170
|
+
|
|
171
|
+
self.intermediate_size = intermediate_size
|
|
172
|
+
self.temporal_merge_size = temporal_merge_size
|
|
173
|
+
self.rms_norm_eps = rms_norm_eps
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class Ernie4_5_VL_MoeTextConfig(Ernie4_5_MoeConfig, PreTrainedConfig):
|
|
177
|
+
r"""
|
|
178
|
+
This is the configuration class to store the configuration of a [`Ernie4_5_VL_MoeTextModel`]. It is used to instantiate a
|
|
179
|
+
the text model portion of the complete Ernie4.5-VL Moe model according to the specified arguments, defining the model architecture.
|
|
180
|
+
|
|
181
|
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
|
182
|
+
documentation from [`PretrainedConfig`] for more information.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
vocab_size (`int`, *optional*, defaults to 103424):
|
|
186
|
+
Vocabulary size of the Ernie 4.5 VL model. Defines the number of different tokens that can be represented by the
|
|
187
|
+
`inputs_ids` passed when calling [`Ernie4_5_VL_MoeTextModel`]
|
|
188
|
+
hidden_size (`int`, *optional*, defaults to 2560):
|
|
189
|
+
Dimension of the hidden representations.
|
|
190
|
+
intermediate_size (`int`, *optional*, defaults to 12288):
|
|
191
|
+
Dimension of the MLP representations.
|
|
192
|
+
num_hidden_layers (`int`, *optional*, defaults to 28):
|
|
193
|
+
Number of hidden layers in the Transformer encoder.
|
|
194
|
+
num_attention_heads (`int`, *optional*, defaults to 20):
|
|
195
|
+
Number of attention heads for each attention layer in the Transformer encoder.
|
|
196
|
+
num_key_value_heads (`int`, *optional*, defaults to 4):
|
|
197
|
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
|
198
|
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
|
199
|
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
|
200
|
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
|
201
|
+
by meanpooling all the original heads within that group. For more details, check out [this
|
|
202
|
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `4`.
|
|
203
|
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
|
204
|
+
The non-linear activation function (function or string) in the decoder.
|
|
205
|
+
max_position_embeddings (`int`, *optional*, defaults to 131072):
|
|
206
|
+
The maximum sequence length that this model might ever be used with.
|
|
207
|
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
|
208
|
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
|
209
|
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
|
210
|
+
The epsilon used by the rms normalization layers.
|
|
211
|
+
use_cache (`bool`, *optional*, defaults to `True`):
|
|
212
|
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
|
213
|
+
relevant if `config.is_decoder=True`.
|
|
214
|
+
use_bias (`bool`, *optional*, defaults to `False`):
|
|
215
|
+
Whether to use a bias in any of the projections including mlp and attention for example.
|
|
216
|
+
tie_word_embeddings (`bool`, *optional*, defaults to `True`):
|
|
217
|
+
Whether the model's input and output word embeddings should be tied.
|
|
218
|
+
rope_parameters (`RopeParameters`, *optional*):
|
|
219
|
+
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionaty should contain
|
|
220
|
+
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
|
|
221
|
+
with longer `max_position_embeddings`.
|
|
222
|
+
mlp_layer_types (`list`, *optional*):
|
|
223
|
+
MLP (Moe vs Dense) pattern for each layer.
|
|
224
|
+
moe_intermediate_size (`list[int]`, *optional*, defaults to `[1536, 512]`):
|
|
225
|
+
Intermediate size of the routed experts; differs between text (first) and image (second) experts.
|
|
226
|
+
moe_k (`int`, *optional*, defaults to 6):
|
|
227
|
+
Number of selected experts.
|
|
228
|
+
moe_num_experts (`int`, *optional*, defaults to 64):
|
|
229
|
+
Number of routed experts.
|
|
230
|
+
moe_num_shared_experts (`int`, *optional*, defaults to 2):
|
|
231
|
+
The number of experts that are shared for all MoE forwards.
|
|
232
|
+
moe_norm_min (`float`, *optional*, defaults to 1e-12):
|
|
233
|
+
Minimum division value during routing normalization.
|
|
234
|
+
output_router_logits (`bool`, *optional*, defaults to `False`):
|
|
235
|
+
Whether or not the router logits should be returned by the model. Enabling this will also
|
|
236
|
+
allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
|
|
237
|
+
router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
|
|
238
|
+
The aux loss factor for the total loss.
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
model_type = "ernie4_5_vl_moe_text"
|
|
242
|
+
base_config_key = "text_config"
|
|
243
|
+
|
|
244
|
+
base_model_tp_plan = {
|
|
245
|
+
"layers.*.self_attn.q_proj": "colwise",
|
|
246
|
+
"layers.*.self_attn.k_proj": "colwise",
|
|
247
|
+
"layers.*.self_attn.v_proj": "colwise",
|
|
248
|
+
"layers.*.self_attn.o_proj": "rowwise",
|
|
249
|
+
"layers.*.mlp.shared_experts.gate_proj": "colwise",
|
|
250
|
+
"layers.*.mlp.shared_experts.up_proj": "colwise",
|
|
251
|
+
"layers.*.mlp.shared_experts.down_proj": "rowwise",
|
|
252
|
+
"layers.*.mlp.gate_proj": "colwise",
|
|
253
|
+
"layers.*.mlp.up_proj": "colwise",
|
|
254
|
+
"layers.*.mlp.down_proj": "rowwise",
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
def __init__(
|
|
258
|
+
self,
|
|
259
|
+
vocab_size=103424,
|
|
260
|
+
hidden_size=2560,
|
|
261
|
+
intermediate_size=12288,
|
|
262
|
+
num_hidden_layers=28,
|
|
263
|
+
num_attention_heads=20,
|
|
264
|
+
num_key_value_heads=4,
|
|
265
|
+
hidden_act="silu",
|
|
266
|
+
max_position_embeddings=131072,
|
|
267
|
+
initializer_range=0.02,
|
|
268
|
+
rms_norm_eps=1e-5,
|
|
269
|
+
use_cache=True,
|
|
270
|
+
use_bias=False,
|
|
271
|
+
tie_word_embeddings=True,
|
|
272
|
+
rope_parameters=None,
|
|
273
|
+
mlp_layer_types=None,
|
|
274
|
+
moe_intermediate_size=None,
|
|
275
|
+
moe_k=6,
|
|
276
|
+
moe_num_experts=64,
|
|
277
|
+
moe_num_shared_experts=2,
|
|
278
|
+
moe_norm_min=1e-12,
|
|
279
|
+
output_router_logits=False,
|
|
280
|
+
router_aux_loss_coef=0.001,
|
|
281
|
+
**kwargs,
|
|
282
|
+
):
|
|
283
|
+
self.vocab_size = vocab_size
|
|
284
|
+
self.hidden_size = hidden_size
|
|
285
|
+
self.intermediate_size = intermediate_size
|
|
286
|
+
self.num_hidden_layers = num_hidden_layers
|
|
287
|
+
self.num_attention_heads = num_attention_heads
|
|
288
|
+
self.num_key_value_heads = num_key_value_heads
|
|
289
|
+
self.hidden_act = hidden_act
|
|
290
|
+
self.max_position_embeddings = max_position_embeddings
|
|
291
|
+
self.initializer_range = initializer_range
|
|
292
|
+
self.rms_norm_eps = rms_norm_eps
|
|
293
|
+
self.use_cache = use_cache
|
|
294
|
+
self.use_bias = use_bias
|
|
295
|
+
self.rope_parameters = rope_parameters
|
|
296
|
+
|
|
297
|
+
# Default to MoE from the second layer and on
|
|
298
|
+
self.mlp_layer_types = mlp_layer_types
|
|
299
|
+
if self.mlp_layer_types is None:
|
|
300
|
+
self.mlp_layer_types = ["dense"] + ["sparse"] * (self.num_hidden_layers - 1)
|
|
301
|
+
layer_type_validation(self.mlp_layer_types, self.num_hidden_layers, attention=False)
|
|
302
|
+
|
|
303
|
+
self.moe_intermediate_size = moe_intermediate_size
|
|
304
|
+
if self.moe_intermediate_size is None:
|
|
305
|
+
self.moe_intermediate_size = [1536, 512]
|
|
306
|
+
self.moe_k = moe_k
|
|
307
|
+
self.moe_num_experts = moe_num_experts
|
|
308
|
+
self.moe_num_shared_experts = moe_num_shared_experts
|
|
309
|
+
self.moe_norm_min = moe_norm_min
|
|
310
|
+
self.output_router_logits = output_router_logits
|
|
311
|
+
self.router_aux_loss_coef = router_aux_loss_coef
|
|
312
|
+
|
|
313
|
+
PreTrainedConfig.__init__(
|
|
314
|
+
tie_word_embeddings=tie_word_embeddings, ignore_keys_at_rope_validation={"mrope_section"}, **kwargs
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
class Ernie4_5_VL_MoeConfig(PreTrainedConfig):
|
|
319
|
+
r"""
|
|
320
|
+
This is the configuration class to store the configuration of a [`Ernie4_5_VL_MoeModel`]. It is used to instantiate a
|
|
321
|
+
Ernie4.5-VL MoE model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
|
322
|
+
with the defaults will yield a similar configuration to that of
|
|
323
|
+
Ernie 4.5 VL 28B A3B [baidu/ERNIE-4.5-VL-28B-A3B-PT](https://huggingface.co/baidu/ERNIE-4.5-VL-28B-A3B-PT).
|
|
324
|
+
|
|
325
|
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
|
326
|
+
documentation from [`PretrainedConfig`] for more information.
|
|
327
|
+
|
|
328
|
+
Args:
|
|
329
|
+
text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Ernie4_5_VL_MoeTextConfig`):
|
|
330
|
+
The config object or dictionary of the text backbone.
|
|
331
|
+
vision_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Ernie4_5_VL_MoeVisionConfig`):
|
|
332
|
+
The config object or dictionary of the vision backbone.
|
|
333
|
+
image_start_token_id (`int`, *optional*, defaults to 101304):
|
|
334
|
+
The image token index to encode the start of image.
|
|
335
|
+
image_end_token_id (`int`, *optional*, defaults to 101305):
|
|
336
|
+
The image token index to encode the end of image.
|
|
337
|
+
image_token_id (`int`, *optional*, defaults to 100295):
|
|
338
|
+
The image token index to encode the image prompt.
|
|
339
|
+
video_start_token_id (`int`, *optional*, defaults to 101306):
|
|
340
|
+
The video token index to encode the start of video.
|
|
341
|
+
video_end_token_id (`int`, *optional*, defaults to 101307):
|
|
342
|
+
The video token index to encode the end of video.
|
|
343
|
+
video_token_id (`int`, *optional*, defaults to 103367):
|
|
344
|
+
The video token index to encode the video prompt.
|
|
345
|
+
|
|
346
|
+
```python
|
|
347
|
+
>>> from transformers import Ernie4_5_VL_MoeForConditionalGeneration, Ernie4_5_VL_MoeConfig
|
|
348
|
+
|
|
349
|
+
>>> # Initializing a Ernie4_5_VL_Moe style configuration
|
|
350
|
+
>>> configuration = Ernie4_5_VL_MoeConfig()
|
|
351
|
+
|
|
352
|
+
>>> # Initializing a model from the Ernie 4.5 VL 28B A3B configuration
|
|
353
|
+
>>> model = Ernie4_5_VL_MoeForConditionalGeneration(configuration)
|
|
354
|
+
|
|
355
|
+
>>> # Accessing the model configuration
|
|
356
|
+
>>> configuration = model.config
|
|
357
|
+
```"""
|
|
358
|
+
|
|
359
|
+
model_type = "ernie4_5_vl_moe"
|
|
360
|
+
sub_configs = {"vision_config": Ernie4_5_VL_MoeVisionConfig, "text_config": Ernie4_5_VL_MoeTextConfig}
|
|
361
|
+
keys_to_ignore_at_inference = ["past_key_values"]
|
|
362
|
+
|
|
363
|
+
def __init__(
|
|
364
|
+
self,
|
|
365
|
+
text_config=None,
|
|
366
|
+
vision_config=None,
|
|
367
|
+
image_start_token_id=101304,
|
|
368
|
+
image_end_token_id=101305,
|
|
369
|
+
image_token_id=100295,
|
|
370
|
+
video_start_token_id=101306,
|
|
371
|
+
video_end_token_id=101307,
|
|
372
|
+
video_token_id=103367,
|
|
373
|
+
**kwargs,
|
|
374
|
+
):
|
|
375
|
+
if isinstance(vision_config, dict):
|
|
376
|
+
self.vision_config = self.sub_configs["vision_config"](**vision_config)
|
|
377
|
+
elif isinstance(vision_config, Ernie4_5_VL_MoeVisionConfig):
|
|
378
|
+
self.vision_config = vision_config
|
|
379
|
+
elif vision_config is None:
|
|
380
|
+
self.vision_config = self.sub_configs["vision_config"]()
|
|
381
|
+
|
|
382
|
+
if isinstance(text_config, dict):
|
|
383
|
+
self.text_config = self.sub_configs["text_config"](**text_config)
|
|
384
|
+
elif isinstance(text_config, Ernie4_5_VL_MoeTextConfig):
|
|
385
|
+
self.text_config = text_config
|
|
386
|
+
elif text_config is None:
|
|
387
|
+
self.text_config = self.sub_configs["text_config"](**kwargs)
|
|
388
|
+
|
|
389
|
+
self.image_start_token_id = image_start_token_id
|
|
390
|
+
self.image_end_token_id = image_end_token_id
|
|
391
|
+
self.image_token_id = image_token_id
|
|
392
|
+
self.video_start_token_id = video_start_token_id
|
|
393
|
+
self.video_end_token_id = video_end_token_id
|
|
394
|
+
self.video_token_id = video_token_id
|
|
395
|
+
|
|
396
|
+
super().__init__(**kwargs)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
class Ernie4_5_VL_MoeTextRotaryEmbedding(nn.Module):
|
|
400
|
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
|
401
|
+
|
|
402
|
+
def __init__(self, config, device=None):
|
|
403
|
+
super().__init__()
|
|
404
|
+
self.max_seq_len_cached = config.max_position_embeddings
|
|
405
|
+
self.original_max_seq_len = config.max_position_embeddings
|
|
406
|
+
|
|
407
|
+
self.config = config
|
|
408
|
+
|
|
409
|
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
|
410
|
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
|
411
|
+
if self.rope_type != "default":
|
|
412
|
+
raise ValueError(f"Ernie 4.5 VL requires the `default` rope type, but found {self.rope_type} instead.")
|
|
413
|
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
|
414
|
+
|
|
415
|
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
|
416
|
+
self.original_inv_freq = inv_freq
|
|
417
|
+
|
|
418
|
+
self.mrope_section = config.rope_parameters.get("mrope_section", [22, 22, 20])
|
|
419
|
+
|
|
420
|
+
@staticmethod
|
|
421
|
+
def compute_default_rope_parameters(
|
|
422
|
+
config: Optional[Ernie4_5_VL_MoeTextConfig] = None,
|
|
423
|
+
device: Optional["torch.device"] = None,
|
|
424
|
+
seq_len: Optional[int] = None,
|
|
425
|
+
) -> tuple["torch.Tensor", float]:
|
|
426
|
+
"""
|
|
427
|
+
Computes the inverse frequencies according to the original RoPE implementation
|
|
428
|
+
Args:
|
|
429
|
+
config ([`~transformers.PreTrainedConfig`]):
|
|
430
|
+
The model configuration.
|
|
431
|
+
device (`torch.device`):
|
|
432
|
+
The device to use for initialization of the inverse frequencies.
|
|
433
|
+
seq_len (`int`, *optional*):
|
|
434
|
+
The current sequence length. Unused for this type of RoPE.
|
|
435
|
+
Returns:
|
|
436
|
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
|
437
|
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
|
438
|
+
"""
|
|
439
|
+
base = config.rope_parameters["rope_theta"]
|
|
440
|
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
|
441
|
+
|
|
442
|
+
attention_factor = 1.0 # Unused in this type of RoPE
|
|
443
|
+
|
|
444
|
+
# Compute the inverse frequencies
|
|
445
|
+
inv_freq = 1.0 / (
|
|
446
|
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
# Special to ernie, we prerotate on the hw dim
|
|
450
|
+
mrope_section = config.rope_parameters.get("mrope_section", [22, 22, 20])
|
|
451
|
+
hw_dim = mrope_section[0] + mrope_section[1]
|
|
452
|
+
t_dim = mrope_section[2]
|
|
453
|
+
|
|
454
|
+
inv_freq_3d = torch.empty_like(inv_freq)
|
|
455
|
+
# (Pre-)Rotate to avoid another rotation during the forward
|
|
456
|
+
inv_freq_3d[:hw_dim] = torch.cat([inv_freq[:-t_dim][0::2], inv_freq[:-t_dim][1::2]])
|
|
457
|
+
inv_freq_3d[-t_dim:] = inv_freq[-t_dim:]
|
|
458
|
+
|
|
459
|
+
return inv_freq_3d, attention_factor
|
|
460
|
+
|
|
461
|
+
@torch.no_grad()
|
|
462
|
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
|
463
|
+
def forward(self, x, position_ids):
|
|
464
|
+
inv_freq_expanded = (
|
|
465
|
+
self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device)
|
|
466
|
+
)
|
|
467
|
+
position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
|
|
468
|
+
|
|
469
|
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
|
470
|
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
|
471
|
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
|
|
472
|
+
cos = freqs.cos() * self.attention_scaling
|
|
473
|
+
sin = freqs.sin() * self.attention_scaling
|
|
474
|
+
|
|
475
|
+
sin = self.recomposition_to_3d(sin)
|
|
476
|
+
cos = self.recomposition_to_3d(cos)
|
|
477
|
+
|
|
478
|
+
return cos, sin
|
|
479
|
+
|
|
480
|
+
def recomposition_to_3d(self, freq):
|
|
481
|
+
freq_h, freq_w, freq_t = (m[(i + 1) % 3] for i, m in enumerate(freq.split([*self.mrope_section], dim=-1)))
|
|
482
|
+
freq_hw = torch.stack([freq_h, freq_w], dim=-1).flatten(-2)
|
|
483
|
+
freq_hwt = torch.cat([freq_hw, freq_t], dim=-1)
|
|
484
|
+
return freq_hwt.repeat_interleave(2, dim=-1)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def rotate_half_text(x):
|
|
488
|
+
"""Rotates half the hidden dims of the input."""
|
|
489
|
+
x1 = x[..., 0::2]
|
|
490
|
+
x2 = x[..., 1::2]
|
|
491
|
+
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
|
495
|
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
|
496
|
+
|
|
497
|
+
Args:
|
|
498
|
+
q (`torch.Tensor`): The query tensor.
|
|
499
|
+
k (`torch.Tensor`): The key tensor.
|
|
500
|
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
|
501
|
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
|
502
|
+
position_ids (`torch.Tensor`, *optional*):
|
|
503
|
+
Deprecated and unused.
|
|
504
|
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
|
505
|
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
|
506
|
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
|
507
|
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
|
508
|
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
|
509
|
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
|
510
|
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
|
511
|
+
Returns:
|
|
512
|
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
|
513
|
+
"""
|
|
514
|
+
original_dtype = q.dtype
|
|
515
|
+
|
|
516
|
+
cos = cos.unsqueeze(unsqueeze_dim)
|
|
517
|
+
sin = sin.unsqueeze(unsqueeze_dim)
|
|
518
|
+
|
|
519
|
+
q_embed = (q.float() * cos) + (rotate_half_text(q).float() * sin)
|
|
520
|
+
k_embed = (k.float() * cos) + (rotate_half_text(k).float() * sin)
|
|
521
|
+
|
|
522
|
+
return q_embed.to(original_dtype), k_embed.to(original_dtype)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
class Ernie4_5_VL_MoeTextAttention(Ernie4_5_MoeAttention):
|
|
526
|
+
pass
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
class Ernie4_5_VL_MoeRMSNorm(Ernie4_5_MoeRMSNorm):
|
|
530
|
+
pass
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
class Ernie4_5_VL_MoeMLP(Ernie4_5_MoeMLP):
|
|
534
|
+
pass
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
class Ernie4_5_VL_MoeMoeStatics(Ernie4_5_MoeStatics):
|
|
538
|
+
pass
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
class Ernie4_5_VL_MoeMoeTopKRouter(Ernie4_5_MoeTopKRouter):
|
|
542
|
+
def __init__(self, config):
|
|
543
|
+
super().__init__(config)
|
|
544
|
+
self.moe_statics = Ernie4_5_VL_MoeMoeStatics(config)
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
class Ernie4_5_VL_MoeMoeExperts(Ernie4_5_MoeExperts):
|
|
548
|
+
def __init__(self, config, intermediate_size=None):
|
|
549
|
+
super().__init__(config)
|
|
550
|
+
self.intermediate_dim = config.moe_intermediate_size if intermediate_size is None else intermediate_size
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
class Ernie4_5_VL_MoeSparseMoeBlock(nn.Module):
|
|
554
|
+
def __init__(self, config, intermediate_size):
|
|
555
|
+
super().__init__()
|
|
556
|
+
self.hidden_dim = config.hidden_size
|
|
557
|
+
self.num_experts = config.moe_num_experts
|
|
558
|
+
self.top_k = config.moe_k
|
|
559
|
+
self.gate = Ernie4_5_VL_MoeMoeTopKRouter(config)
|
|
560
|
+
self.experts = Ernie4_5_VL_MoeMoeExperts(config, intermediate_size)
|
|
561
|
+
|
|
562
|
+
def forward(
|
|
563
|
+
self,
|
|
564
|
+
hidden_states: torch.Tensor,
|
|
565
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
566
|
+
hidden_states = hidden_states.view(-1, self.hidden_dim)
|
|
567
|
+
|
|
568
|
+
router_logits, top_k_index, top_k_weights = self.gate(hidden_states)
|
|
569
|
+
final_hidden_states = self.experts(hidden_states, top_k_index, top_k_weights)
|
|
570
|
+
|
|
571
|
+
# moe results are changed to a flattened shape to ease the modality isolated assigning of results
|
|
572
|
+
return final_hidden_states.flatten(), router_logits.flatten()
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
class Ernie4_5_VL_MoeMoeBlock(nn.Module):
|
|
576
|
+
"""
|
|
577
|
+
Similar to `Ernie4_5_Moe` where we have modality isolated experts:
|
|
578
|
+
- A set of text experts that are only run on text tokens
|
|
579
|
+
- A set of vision experts that are only run on vision (image/video) tokens
|
|
580
|
+
|
|
581
|
+
This modality isolation is unique to the Ernie 4.5 VL Moe models.
|
|
582
|
+
"""
|
|
583
|
+
|
|
584
|
+
def __init__(self, config):
|
|
585
|
+
super().__init__()
|
|
586
|
+
self.num_experts = config.moe_num_experts
|
|
587
|
+
|
|
588
|
+
self.text_moe = Ernie4_5_VL_MoeSparseMoeBlock(config, intermediate_size=config.moe_intermediate_size[0])
|
|
589
|
+
self.vision_moe = Ernie4_5_VL_MoeSparseMoeBlock(config, intermediate_size=config.moe_intermediate_size[1])
|
|
590
|
+
|
|
591
|
+
self.shared_experts = None
|
|
592
|
+
if config.moe_num_shared_experts > 0:
|
|
593
|
+
self.shared_experts = Ernie4_5_VL_MoeMLP(
|
|
594
|
+
config, config.moe_intermediate_size[0] * config.moe_num_shared_experts
|
|
595
|
+
)
|
|
596
|
+
|
|
597
|
+
def forward(
|
|
598
|
+
self,
|
|
599
|
+
hidden_states: torch.Tensor,
|
|
600
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
601
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
602
|
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
|
603
|
+
|
|
604
|
+
# (Optional) shared experts
|
|
605
|
+
if self.shared_experts is not None:
|
|
606
|
+
shared_output = self.shared_experts(hidden_states)
|
|
607
|
+
|
|
608
|
+
if moe_mm_token_type_ids is not None and moe_mm_token_type_ids.any():
|
|
609
|
+
final_hidden_states = torch.zeros_like(hidden_states)
|
|
610
|
+
router_logits = torch.zeros(
|
|
611
|
+
size=(batch_size * sequence_length, self.num_experts),
|
|
612
|
+
device=final_hidden_states.device,
|
|
613
|
+
dtype=torch.float,
|
|
614
|
+
)
|
|
615
|
+
|
|
616
|
+
# True (1 or 2) == vision, False (0) == text tokens
|
|
617
|
+
moe_mm_token_type_ids = moe_mm_token_type_ids.bool()
|
|
618
|
+
token_type_ids_router = moe_mm_token_type_ids.reshape(-1)[:, None].expand(-1, self.num_experts)
|
|
619
|
+
token_type_ids_states = moe_mm_token_type_ids[..., None].expand(-1, -1, hidden_dim)
|
|
620
|
+
|
|
621
|
+
# Run moe on each modality and assign their results to the original token positions
|
|
622
|
+
final_hidden_states[~token_type_ids_states], router_logits[~token_type_ids_router] = self.text_moe(
|
|
623
|
+
hidden_states[~token_type_ids_states]
|
|
624
|
+
)
|
|
625
|
+
final_hidden_states[token_type_ids_states], router_logits[token_type_ids_router] = self.vision_moe(
|
|
626
|
+
hidden_states[token_type_ids_states]
|
|
627
|
+
)
|
|
628
|
+
else:
|
|
629
|
+
final_hidden_states, router_logits = self.text_moe(hidden_states)
|
|
630
|
+
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
|
631
|
+
router_logits = router_logits.reshape(-1, self.num_experts)
|
|
632
|
+
|
|
633
|
+
# Add (optional) shared experts to the result
|
|
634
|
+
if self.shared_experts is not None:
|
|
635
|
+
final_hidden_states = final_hidden_states + shared_output
|
|
636
|
+
|
|
637
|
+
return final_hidden_states, router_logits
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
class Ernie4_5_VL_MoeDecoderLayer(GradientCheckpointingLayer):
|
|
641
|
+
def __init__(self, config, layer_idx):
|
|
642
|
+
super().__init__()
|
|
643
|
+
self.hidden_size = config.hidden_size
|
|
644
|
+
|
|
645
|
+
self.self_attn = Ernie4_5_VL_MoeTextAttention(config, layer_idx)
|
|
646
|
+
|
|
647
|
+
if config.mlp_layer_types[layer_idx] == "sparse":
|
|
648
|
+
self.mlp = Ernie4_5_VL_MoeMoeBlock(config)
|
|
649
|
+
else:
|
|
650
|
+
self.mlp = Ernie4_5_VL_MoeMLP(config)
|
|
651
|
+
|
|
652
|
+
self.input_layernorm = Ernie4_5_VL_MoeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
|
653
|
+
self.post_attention_layernorm = Ernie4_5_VL_MoeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
|
654
|
+
|
|
655
|
+
def forward(
|
|
656
|
+
self,
|
|
657
|
+
hidden_states: torch.Tensor,
|
|
658
|
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
|
659
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
660
|
+
position_ids: Optional[torch.Tensor] = None,
|
|
661
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
662
|
+
past_key_values: Optional[Cache] = None,
|
|
663
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
664
|
+
**kwargs: Unpack[FlashAttentionKwargs],
|
|
665
|
+
) -> tuple[torch.Tensor, Optional[tuple[torch.Tensor, torch.Tensor]]]:
|
|
666
|
+
residual = hidden_states
|
|
667
|
+
|
|
668
|
+
hidden_states = self.input_layernorm(hidden_states)
|
|
669
|
+
|
|
670
|
+
# Self Attention
|
|
671
|
+
hidden_states, _ = self.self_attn(
|
|
672
|
+
hidden_states=hidden_states,
|
|
673
|
+
position_embeddings=position_embeddings,
|
|
674
|
+
attention_mask=attention_mask,
|
|
675
|
+
position_ids=position_ids,
|
|
676
|
+
past_key_values=past_key_values,
|
|
677
|
+
cache_position=cache_position,
|
|
678
|
+
**kwargs,
|
|
679
|
+
)
|
|
680
|
+
hidden_states = hidden_states + residual
|
|
681
|
+
|
|
682
|
+
# Fully Connected
|
|
683
|
+
residual = hidden_states
|
|
684
|
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
|
685
|
+
if isinstance(self.mlp, Ernie4_5_VL_MoeMoeBlock):
|
|
686
|
+
hidden_states, _ = self.mlp(hidden_states, moe_mm_token_type_ids)
|
|
687
|
+
else:
|
|
688
|
+
hidden_states = self.mlp(hidden_states)
|
|
689
|
+
hidden_states = hidden_states + residual
|
|
690
|
+
|
|
691
|
+
return hidden_states
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
class Ernie4_5_VL_MoePreTrainedModel(Qwen2_5_VLPreTrainedModel):
|
|
695
|
+
_can_compile_fullgraph = False
|
|
696
|
+
|
|
697
|
+
_can_record_outputs = {
|
|
698
|
+
"router_logits": OutputRecorder(Ernie4_5_VL_MoeMoeBlock, index=1),
|
|
699
|
+
"hidden_states": Ernie4_5_VL_MoeDecoderLayer,
|
|
700
|
+
"attentions": Ernie4_5_VL_MoeTextAttention,
|
|
701
|
+
}
|
|
702
|
+
_keep_in_fp32_modules_strict = ["gate.weight", "moe_statics"]
|
|
703
|
+
|
|
704
|
+
def _init_weights(self, module):
|
|
705
|
+
PreTrainedModel._init_weights(self, module)
|
|
706
|
+
if isinstance(module, Ernie4_5_VL_MoeMoeTopKRouter):
|
|
707
|
+
init.zeros_(module.moe_statics.e_score_correction_bias)
|
|
708
|
+
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
|
709
|
+
elif isinstance(module, Ernie4_5_VL_MoeMoeExperts):
|
|
710
|
+
init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
|
|
711
|
+
init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
|
|
712
|
+
elif isinstance(module, Ernie4_5_VL_MoeVisionRotaryEmbedding):
|
|
713
|
+
inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim))
|
|
714
|
+
init.copy_(module.inv_freq, inv_freq)
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
class Ernie4_5_VL_MoeTextModel(Ernie4_5_MoeModel):
|
|
718
|
+
config: Ernie4_5_VL_MoeTextConfig
|
|
719
|
+
|
|
720
|
+
def __init__(self, config: Ernie4_5_VL_MoeTextConfig):
|
|
721
|
+
super().__init__(config)
|
|
722
|
+
self.rotary_emb = Ernie4_5_VL_MoeTextRotaryEmbedding(config=config)
|
|
723
|
+
|
|
724
|
+
@check_model_inputs
|
|
725
|
+
@auto_docstring
|
|
726
|
+
def forward(
|
|
727
|
+
self,
|
|
728
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
729
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
730
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
731
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
732
|
+
past_key_values: Optional[Cache] = None,
|
|
733
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
734
|
+
use_cache: Optional[bool] = None,
|
|
735
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
736
|
+
**kwargs: Unpack[FlashAttentionKwargs],
|
|
737
|
+
) -> MoeModelOutputWithPast:
|
|
738
|
+
r"""
|
|
739
|
+
moe_mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
740
|
+
The same as `mm_token_type_ids` while additionally considering start/end image/video tokens as respective vision tokens.
|
|
741
|
+
"""
|
|
742
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
|
743
|
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
|
744
|
+
|
|
745
|
+
if use_cache and past_key_values is None:
|
|
746
|
+
past_key_values = DynamicCache(config=self.config)
|
|
747
|
+
|
|
748
|
+
if inputs_embeds is None:
|
|
749
|
+
inputs_embeds = self.embed_tokens(input_ids)
|
|
750
|
+
|
|
751
|
+
if cache_position is None:
|
|
752
|
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
|
753
|
+
cache_position = torch.arange(
|
|
754
|
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
|
755
|
+
)
|
|
756
|
+
|
|
757
|
+
# the hard coded `3` is for temporal, height and width.
|
|
758
|
+
if position_ids is None:
|
|
759
|
+
position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
|
|
760
|
+
elif position_ids.ndim == 2:
|
|
761
|
+
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
|
|
762
|
+
|
|
763
|
+
# NOTE: we need to pass text position ids for packing. Ernie 4.5 VL uses 3D positions
|
|
764
|
+
# where each dim indicates visual spatial positions for temporal/height/width grids.
|
|
765
|
+
# There are is only one scenario when FA2-like packed masking might be activated.
|
|
766
|
+
# 1. User specifically passed packed `position_ids` and no attention mask.
|
|
767
|
+
# In this case we expect the useer to create correct position ids for all 3 grids
|
|
768
|
+
# and prepend text-only position ids to it. The final tensor will be [4, bs, seq-len]
|
|
769
|
+
if position_ids.ndim == 3 and position_ids.shape[0] == 4:
|
|
770
|
+
text_position_ids = position_ids[0]
|
|
771
|
+
position_ids = position_ids[1:]
|
|
772
|
+
else:
|
|
773
|
+
# If inputs are not packed (usual 3D positions), do not prepare mask from position_ids
|
|
774
|
+
text_position_ids = None
|
|
775
|
+
|
|
776
|
+
attention_mask = create_causal_mask(
|
|
777
|
+
config=self.config,
|
|
778
|
+
input_embeds=inputs_embeds,
|
|
779
|
+
attention_mask=attention_mask,
|
|
780
|
+
cache_position=cache_position,
|
|
781
|
+
past_key_values=past_key_values,
|
|
782
|
+
position_ids=text_position_ids,
|
|
783
|
+
)
|
|
784
|
+
|
|
785
|
+
hidden_states = inputs_embeds
|
|
786
|
+
|
|
787
|
+
# create position embeddings to be shared across the decoder layers
|
|
788
|
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
|
789
|
+
|
|
790
|
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
|
791
|
+
hidden_states = decoder_layer(
|
|
792
|
+
hidden_states,
|
|
793
|
+
position_embeddings=position_embeddings,
|
|
794
|
+
attention_mask=attention_mask,
|
|
795
|
+
position_ids=position_ids,
|
|
796
|
+
moe_mm_token_type_ids=moe_mm_token_type_ids,
|
|
797
|
+
past_key_values=past_key_values,
|
|
798
|
+
cache_position=cache_position,
|
|
799
|
+
**kwargs,
|
|
800
|
+
)
|
|
801
|
+
|
|
802
|
+
hidden_states = self.norm(hidden_states)
|
|
803
|
+
|
|
804
|
+
return MoeModelOutputWithPast(
|
|
805
|
+
last_hidden_state=hidden_states,
|
|
806
|
+
past_key_values=past_key_values,
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
class Ernie4_5VLVisionMLP(VisionMlp):
|
|
811
|
+
pass
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
class Ernie4_5_VL_MoePatchEmbed(Qwen2_5_VisionPatchEmbed):
|
|
815
|
+
def __init__(
|
|
816
|
+
self,
|
|
817
|
+
patch_size: int = 14,
|
|
818
|
+
in_channels: int = 3,
|
|
819
|
+
embed_dim: int = 1152,
|
|
820
|
+
) -> None:
|
|
821
|
+
super().__init__(patch_size, in_channels, embed_dim)
|
|
822
|
+
|
|
823
|
+
del self.temporal_patch_size
|
|
824
|
+
del kernel_size # noqa: F821
|
|
825
|
+
self.proj = nn.Linear(in_channels * patch_size * patch_size, embed_dim, bias=False)
|
|
826
|
+
|
|
827
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
|
828
|
+
target_dtype = self.proj.weight.dtype
|
|
829
|
+
return self.proj(hidden_states.to(target_dtype))
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
class Ernie4_5_VL_MoeVisionRotaryEmbedding(Qwen2_5_VisionRotaryEmbedding):
|
|
833
|
+
pass
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
class Ernie4_5_VL_MoeVisionBlock(Qwen2_5_VLVisionBlock):
|
|
837
|
+
def __init__(self, config) -> None:
|
|
838
|
+
super().__init__(config, None)
|
|
839
|
+
|
|
840
|
+
self.norm1 = nn.LayerNorm(config.hidden_size, config.rms_norm_eps)
|
|
841
|
+
self.norm2 = nn.LayerNorm(config.hidden_size, config.rms_norm_eps)
|
|
842
|
+
self.mlp = Ernie4_5VLVisionMLP(
|
|
843
|
+
dim=config.hidden_size,
|
|
844
|
+
hidden_dim=config.intermediate_size,
|
|
845
|
+
hidden_act=config.hidden_act,
|
|
846
|
+
)
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
class Ernie4_5_VL_MoeVisionTransformerPretrainedModel(Qwen2VisionTransformerPretrainedModel):
|
|
850
|
+
def __init__(self, config) -> None:
|
|
851
|
+
super().__init__(config)
|
|
852
|
+
|
|
853
|
+
del self.merger
|
|
854
|
+
|
|
855
|
+
self.patch_embed = Ernie4_5_VL_MoePatchEmbed(
|
|
856
|
+
patch_size=config.patch_size,
|
|
857
|
+
in_channels=config.in_channels,
|
|
858
|
+
embed_dim=config.hidden_size,
|
|
859
|
+
)
|
|
860
|
+
|
|
861
|
+
head_dim = config.hidden_size // config.num_heads
|
|
862
|
+
self.rotary_pos_emb = Ernie4_5_VL_MoeVisionRotaryEmbedding(head_dim // 2)
|
|
863
|
+
|
|
864
|
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
|
|
865
|
+
|
|
866
|
+
def get_dtype(self):
|
|
867
|
+
raise AttributeError("Ernie 4.5 VL Moe does not need this!")
|
|
868
|
+
|
|
869
|
+
def get_device(self):
|
|
870
|
+
raise AttributeError("Ernie 4.5 VL Moe does not need this!")
|
|
871
|
+
|
|
872
|
+
def forward(
|
|
873
|
+
self,
|
|
874
|
+
hidden_states: torch.Tensor,
|
|
875
|
+
grid_thw: torch.Tensor,
|
|
876
|
+
**kwargs,
|
|
877
|
+
) -> torch.Tensor:
|
|
878
|
+
hidden_states = self.patch_embed(hidden_states)
|
|
879
|
+
rotary_pos_emb = self.rot_pos_emb(grid_thw)
|
|
880
|
+
emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
|
|
881
|
+
position_embeddings = (emb.cos(), emb.sin())
|
|
882
|
+
|
|
883
|
+
cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
|
|
884
|
+
dim=0,
|
|
885
|
+
# Select dtype based on the following factors:
|
|
886
|
+
# - FA2 requires that cu_seqlens_q must have dtype int32
|
|
887
|
+
# - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
|
|
888
|
+
# See https://github.com/huggingface/transformers/pull/34852 for more information
|
|
889
|
+
dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
|
|
890
|
+
)
|
|
891
|
+
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
|
|
892
|
+
|
|
893
|
+
for block in self.blocks:
|
|
894
|
+
hidden_states = block(
|
|
895
|
+
hidden_states,
|
|
896
|
+
cu_seqlens=cu_seqlens,
|
|
897
|
+
position_embeddings=position_embeddings,
|
|
898
|
+
**kwargs,
|
|
899
|
+
)
|
|
900
|
+
hidden_states = self.ln(hidden_states)
|
|
901
|
+
return hidden_states
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
class Ernie4_5_VL_MoeVisionMLP(nn.Module):
|
|
905
|
+
def __init__(self, config, in_dim, out_dim):
|
|
906
|
+
super().__init__()
|
|
907
|
+
|
|
908
|
+
self.fc1 = nn.Linear(in_dim, out_dim)
|
|
909
|
+
self.act_fn = nn.GELU()
|
|
910
|
+
self.fc2 = nn.Linear(out_dim, out_dim)
|
|
911
|
+
self.ln = nn.LayerNorm(out_dim, eps=config.vision_config.rms_norm_eps)
|
|
912
|
+
|
|
913
|
+
def forward(self, hidden_states):
|
|
914
|
+
hidden_states = self.fc1(hidden_states)
|
|
915
|
+
hidden_states = self.act_fn(hidden_states)
|
|
916
|
+
hidden_states = self.fc2(hidden_states)
|
|
917
|
+
hidden_states = self.ln(hidden_states)
|
|
918
|
+
return hidden_states
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
class Ernie4_5_VL_MoeVariableResolutionResamplerModel(nn.Module):
|
|
922
|
+
def __init__(self, config: Ernie4_5_VL_MoeConfig):
|
|
923
|
+
super().__init__()
|
|
924
|
+
self.config = config
|
|
925
|
+
|
|
926
|
+
self.in_dim = config.vision_config.hidden_size
|
|
927
|
+
self.out_dim = config.text_config.hidden_size
|
|
928
|
+
self.spatial_merge_size = config.vision_config.spatial_merge_size
|
|
929
|
+
self.temporal_merge_size = config.vision_config.temporal_merge_size
|
|
930
|
+
|
|
931
|
+
# compress 2d conv(picture) to 1d
|
|
932
|
+
self.spatial_dim = self.in_dim * self.spatial_merge_size**2
|
|
933
|
+
# compress 3d conv(video) to 1d
|
|
934
|
+
self.temporal_dim = self.in_dim * self.spatial_merge_size**2 * self.temporal_merge_size
|
|
935
|
+
|
|
936
|
+
self.spatial_linear = Ernie4_5_VL_MoeVisionMLP(config, self.spatial_dim, self.spatial_dim)
|
|
937
|
+
self.temporal_linear = Ernie4_5_VL_MoeVisionMLP(config, self.temporal_dim, self.spatial_dim)
|
|
938
|
+
|
|
939
|
+
self.mlp = nn.Linear(self.spatial_dim, self.out_dim)
|
|
940
|
+
self.after_norm = Ernie4_5_VL_MoeRMSNorm(self.out_dim, config.text_config.rms_norm_eps)
|
|
941
|
+
|
|
942
|
+
def _temporal_slicing(self, hidden_states, grid_thw):
|
|
943
|
+
"""
|
|
944
|
+
Slices along the temporal dimension in even/odd patterns (usually if we have a video input)
|
|
945
|
+
or duplicates along temporal dimension (usually if we have an image input).
|
|
946
|
+
|
|
947
|
+
Example:
|
|
948
|
+
Video input with temporal pattern of [1, -1, 2, -2, 3, -3]
|
|
949
|
+
> Even input [1, 2, 3], odd input [-1, -2, -3]
|
|
950
|
+
> Reorderd via slices to [1, 2, 3, -1, -2, -3]
|
|
951
|
+
Image input with temporal pattern [1]
|
|
952
|
+
> Duplicate input [1], [1]
|
|
953
|
+
> Reordered to [1, 1]
|
|
954
|
+
|
|
955
|
+
NOTE: This is hard-coded for `temporal_merge_size == 2` and won't work otherwise.
|
|
956
|
+
"""
|
|
957
|
+
# Calculating offsets on spatial dim (based on flattened tensors)
|
|
958
|
+
grid_t, grid_hw = grid_thw[:, 0], grid_thw[:, 1:]
|
|
959
|
+
grid_hw_after_conv = grid_hw.prod(-1) // (self.spatial_merge_size**2)
|
|
960
|
+
|
|
961
|
+
# Calculating offsets on batch dim (based on flattened tensors)
|
|
962
|
+
tokens_per_img_or_vid = (grid_thw.prod(-1) // (self.spatial_merge_size**2)).flatten()
|
|
963
|
+
batch_offsets = torch.empty(tokens_per_img_or_vid.size(), dtype=tokens_per_img_or_vid.dtype)
|
|
964
|
+
batch_offsets[0] = 0
|
|
965
|
+
batch_offsets[1:] = tokens_per_img_or_vid.cumsum(dim=0)[:-1]
|
|
966
|
+
|
|
967
|
+
first_slice_offsets = []
|
|
968
|
+
second_slice_offsets = []
|
|
969
|
+
for temporal_size, spatial_size, batch_offset in zip(grid_t, grid_hw_after_conv, batch_offsets):
|
|
970
|
+
# Depending on temporal, we may interleave:
|
|
971
|
+
# - Images have temporal == 1 --> same offsets (duplicate "frame" image)
|
|
972
|
+
# - Videos have temporal > 1 --> different offsets (even, odd)
|
|
973
|
+
first_offset_range = range(0, temporal_size, 2)
|
|
974
|
+
second_offset_range = range(1 if temporal_size > 1 else 0, temporal_size, 2)
|
|
975
|
+
|
|
976
|
+
for temporal_offset_even, temporal_offset_odd in zip(first_offset_range, second_offset_range):
|
|
977
|
+
first_slice_offsets.append(
|
|
978
|
+
torch.arange(
|
|
979
|
+
batch_offset + (temporal_offset_even) * spatial_size,
|
|
980
|
+
batch_offset + (temporal_offset_even + 1) * spatial_size,
|
|
981
|
+
)
|
|
982
|
+
)
|
|
983
|
+
second_slice_offsets.append(
|
|
984
|
+
torch.arange(
|
|
985
|
+
batch_offset + (temporal_offset_odd) * spatial_size,
|
|
986
|
+
batch_offset + (temporal_offset_odd + 1) * spatial_size,
|
|
987
|
+
)
|
|
988
|
+
)
|
|
989
|
+
|
|
990
|
+
# Input: [1, -1, 2, -2, 3, -3] or [1]
|
|
991
|
+
# Indices: [0, 2, 4] (even) or [0] (duplicate)
|
|
992
|
+
first_slice_offsets = torch.cat(first_slice_offsets, dim=-1).to(hidden_states.device)
|
|
993
|
+
# Indices: [1, 3, 5] (odd) or [0] (duplicate)
|
|
994
|
+
second_slice_offsets = torch.cat(second_slice_offsets, dim=-1).to(hidden_states.device)
|
|
995
|
+
|
|
996
|
+
# Output: [1, 2, 3, -1, -2, -3] or [1, 1]
|
|
997
|
+
return torch.concat(
|
|
998
|
+
[
|
|
999
|
+
torch.index_select(hidden_states, dim=0, index=first_slice_offsets),
|
|
1000
|
+
torch.index_select(hidden_states, dim=0, index=second_slice_offsets),
|
|
1001
|
+
],
|
|
1002
|
+
dim=-1,
|
|
1003
|
+
)
|
|
1004
|
+
|
|
1005
|
+
def forward(self, hidden_states, grid_thw):
|
|
1006
|
+
# image spatial
|
|
1007
|
+
# reshape imitates convolution via linear projection
|
|
1008
|
+
hidden_states = hidden_states.reshape([-1, hidden_states.shape[-1] * (self.spatial_merge_size**2)])
|
|
1009
|
+
hidden_states = self.spatial_linear(hidden_states)
|
|
1010
|
+
|
|
1011
|
+
# video temporal
|
|
1012
|
+
hidden_states = self._temporal_slicing(hidden_states, grid_thw)
|
|
1013
|
+
hidden_states = self.temporal_linear(hidden_states)
|
|
1014
|
+
|
|
1015
|
+
# final mlp
|
|
1016
|
+
hidden_states = self.mlp(hidden_states)
|
|
1017
|
+
hidden_states = self.after_norm(hidden_states)
|
|
1018
|
+
|
|
1019
|
+
return hidden_states
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
class Ernie4_5_VL_MoeModel(Qwen2_5_VLModel):
|
|
1023
|
+
_checkpoint_conversion_mapping = {"^norm": "language_model.norm"}
|
|
1024
|
+
|
|
1025
|
+
def __init__(self, config: Ernie4_5_VL_MoeConfig):
|
|
1026
|
+
super().__init__(config)
|
|
1027
|
+
|
|
1028
|
+
del self.visual
|
|
1029
|
+
self.vision_tower = Ernie4_5_VL_MoeVisionTransformerPretrainedModel._from_config(config.vision_config)
|
|
1030
|
+
self.resampler_model = Ernie4_5_VL_MoeVariableResolutionResamplerModel(config)
|
|
1031
|
+
|
|
1032
|
+
# TODO: Should be moved to generation loop instead in the future
|
|
1033
|
+
# Relevant PR(s): https://github.com/huggingface/transformers/pull/42088
|
|
1034
|
+
def get_position_ids(
|
|
1035
|
+
self,
|
|
1036
|
+
input_ids: torch.LongTensor = None,
|
|
1037
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1038
|
+
past_key_values: Optional[Cache] = None,
|
|
1039
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
1040
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
1041
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
1042
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
1043
|
+
mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1044
|
+
):
|
|
1045
|
+
"""
|
|
1046
|
+
Calculating the 3D position ids with a custom mechanism / caching
|
|
1047
|
+
- First forward calculates the initial positions and the respective
|
|
1048
|
+
deltas (offset) for subsequent positions. See `get_rope_index` for
|
|
1049
|
+
more details.
|
|
1050
|
+
- Second and on (generation), uses the cache position combined with the
|
|
1051
|
+
cached deltas to determine the current position.
|
|
1052
|
+
|
|
1053
|
+
NOTE: We assume that the position ids are `None` and recalculate them here in any case.
|
|
1054
|
+
"""
|
|
1055
|
+
# Calculate RoPE index once per generation in the pre-fill stage only.
|
|
1056
|
+
# When compiling, we can't check tensor values thus we check only input length
|
|
1057
|
+
# It is safe to assume that `length!=1` means we're in pre-fill because compiled
|
|
1058
|
+
# models currently cannot do asssisted decoding
|
|
1059
|
+
prefill_compiled_stage = is_torchdynamo_compiling() and (
|
|
1060
|
+
(input_ids is not None and input_ids.shape[1] != 1)
|
|
1061
|
+
or (inputs_embeds is not None and inputs_embeds.shape[1] != 1)
|
|
1062
|
+
)
|
|
1063
|
+
prefill_noncompiled_stage = not is_torchdynamo_compiling() and (
|
|
1064
|
+
(cache_position is not None and cache_position[0] == 0)
|
|
1065
|
+
or (past_key_values is None or past_key_values.get_seq_length() == 0)
|
|
1066
|
+
)
|
|
1067
|
+
if (prefill_compiled_stage or prefill_noncompiled_stage) or self.rope_deltas is None:
|
|
1068
|
+
position_ids, rope_deltas = self.get_rope_index(
|
|
1069
|
+
input_ids,
|
|
1070
|
+
image_grid_thw,
|
|
1071
|
+
video_grid_thw,
|
|
1072
|
+
attention_mask=attention_mask,
|
|
1073
|
+
mm_token_type_ids=mm_token_type_ids,
|
|
1074
|
+
)
|
|
1075
|
+
self.rope_deltas = rope_deltas
|
|
1076
|
+
# then use the prev pre-calculated rope-deltas to get the correct position ids
|
|
1077
|
+
else:
|
|
1078
|
+
if input_ids is not None:
|
|
1079
|
+
batch_size, seq_length, device = input_ids.shape[0], 1, input_ids.device
|
|
1080
|
+
elif inputs_embeds is not None:
|
|
1081
|
+
batch_size, seq_length, device = inputs_embeds.shape[0], 1, inputs_embeds.device
|
|
1082
|
+
else:
|
|
1083
|
+
raise ValueError(
|
|
1084
|
+
"Cannot calculate position ids without any input to the model. "
|
|
1085
|
+
"Need either `input_ids` or `inputs_embeds`!"
|
|
1086
|
+
)
|
|
1087
|
+
|
|
1088
|
+
delta = (cache_position[0] + self.rope_deltas).to(device) if cache_position is not None else 0
|
|
1089
|
+
position_ids = torch.arange(seq_length, device=device)
|
|
1090
|
+
position_ids = position_ids.view(1, -1).expand(batch_size, -1)
|
|
1091
|
+
if cache_position is not None: # otherwise `deltas` is an int `0`
|
|
1092
|
+
delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0)
|
|
1093
|
+
position_ids = position_ids.add(delta)
|
|
1094
|
+
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
|
|
1095
|
+
|
|
1096
|
+
return position_ids
|
|
1097
|
+
|
|
1098
|
+
def get_rope_index(
|
|
1099
|
+
self,
|
|
1100
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
1101
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
1102
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
1103
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1104
|
+
mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1105
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
1106
|
+
"""
|
|
1107
|
+
Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
|
|
1108
|
+
|
|
1109
|
+
Explanation:
|
|
1110
|
+
Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
|
|
1111
|
+
|
|
1112
|
+
For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
|
|
1113
|
+
Examples:
|
|
1114
|
+
input_ids: [T T T T T], here T is for text.
|
|
1115
|
+
temporal position_ids: [0, 1, 2, 3, 4]
|
|
1116
|
+
height position_ids: [0, 1, 2, 3, 4]
|
|
1117
|
+
width position_ids: [0, 1, 2, 3, 4]
|
|
1118
|
+
|
|
1119
|
+
For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
|
|
1120
|
+
and 1D rotary position embedding for text part.
|
|
1121
|
+
Examples:
|
|
1122
|
+
Temporal (Time): 3 patches, representing different segments of the video in time.
|
|
1123
|
+
Height: 2 patches, dividing each frame vertically.
|
|
1124
|
+
Width: 2 patches, dividing each frame horizontally.
|
|
1125
|
+
We also have some important parameters:
|
|
1126
|
+
fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
|
|
1127
|
+
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.
|
|
1128
|
+
temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
|
|
1129
|
+
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.
|
|
1130
|
+
input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
|
|
1131
|
+
vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
|
|
1132
|
+
vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
|
|
1133
|
+
vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
|
|
1134
|
+
text temporal position_ids: [101, 102, 103, 104, 105]
|
|
1135
|
+
text height position_ids: [101, 102, 103, 104, 105]
|
|
1136
|
+
text width position_ids: [101, 102, 103, 104, 105]
|
|
1137
|
+
Here we calculate the text start position_ids as the max vision position_ids plus 1.
|
|
1138
|
+
|
|
1139
|
+
Args:
|
|
1140
|
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
|
1141
|
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
|
1142
|
+
it.
|
|
1143
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
1144
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
1145
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
1146
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
1147
|
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1148
|
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
|
1149
|
+
|
|
1150
|
+
- 1 for tokens that are **not masked**,
|
|
1151
|
+
- 0 for tokens that are **masked**.
|
|
1152
|
+
mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1153
|
+
Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
|
|
1154
|
+
|
|
1155
|
+
Returns:
|
|
1156
|
+
position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
|
|
1157
|
+
mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
|
|
1158
|
+
"""
|
|
1159
|
+
|
|
1160
|
+
temporal_merge_size = self.config.vision_config.temporal_merge_size
|
|
1161
|
+
spatial_merge_size = self.config.vision_config.spatial_merge_size
|
|
1162
|
+
|
|
1163
|
+
mrope_position_deltas = []
|
|
1164
|
+
if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
|
|
1165
|
+
total_input_ids = input_ids
|
|
1166
|
+
if attention_mask is None:
|
|
1167
|
+
attention_mask = torch.ones_like(total_input_ids)
|
|
1168
|
+
position_ids = torch.ones(
|
|
1169
|
+
3,
|
|
1170
|
+
input_ids.shape[0],
|
|
1171
|
+
input_ids.shape[1],
|
|
1172
|
+
dtype=input_ids.dtype,
|
|
1173
|
+
device=input_ids.device,
|
|
1174
|
+
)
|
|
1175
|
+
image_index, video_index = 0, 0
|
|
1176
|
+
attention_mask = attention_mask.to(total_input_ids.device)
|
|
1177
|
+
for i, input_ids in enumerate(total_input_ids):
|
|
1178
|
+
# If we don't have `mm_token_type_ids`, then we have text tokens only (== 0)
|
|
1179
|
+
if mm_token_type_ids is None:
|
|
1180
|
+
input_token_type = torch.zeros_like(input_ids)[attention_mask[i] == 1].tolist()
|
|
1181
|
+
else:
|
|
1182
|
+
input_token_type = mm_token_type_ids[i, attention_mask[i] == 1].tolist()
|
|
1183
|
+
|
|
1184
|
+
input_type_group = []
|
|
1185
|
+
for key, group in itertools.groupby(enumerate(input_token_type), lambda x: x[1]):
|
|
1186
|
+
group = list(group)
|
|
1187
|
+
start_index = group[0][0]
|
|
1188
|
+
end_index = group[-1][0] + 1
|
|
1189
|
+
input_type_group.append((key, start_index, end_index))
|
|
1190
|
+
|
|
1191
|
+
llm_pos_ids_list = []
|
|
1192
|
+
for modality_type, start_idx, end_idx in input_type_group:
|
|
1193
|
+
st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
|
|
1194
|
+
|
|
1195
|
+
# text == 0
|
|
1196
|
+
if modality_type == 0:
|
|
1197
|
+
text_len = end_idx - start_idx
|
|
1198
|
+
llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
|
|
1199
|
+
|
|
1200
|
+
# image == 1, video == 2
|
|
1201
|
+
else:
|
|
1202
|
+
grid_thw = image_grid_thw if modality_type == 1 else video_grid_thw
|
|
1203
|
+
mm_index = image_index if modality_type == 1 else video_index
|
|
1204
|
+
t_merge_size = 1 if modality_type == 1 else temporal_merge_size
|
|
1205
|
+
|
|
1206
|
+
t, h, w = (
|
|
1207
|
+
grid_thw[mm_index][0],
|
|
1208
|
+
grid_thw[mm_index][1],
|
|
1209
|
+
grid_thw[mm_index][2],
|
|
1210
|
+
)
|
|
1211
|
+
llm_grid_t, llm_grid_h, llm_grid_w = (
|
|
1212
|
+
t.item() // t_merge_size,
|
|
1213
|
+
h.item() // spatial_merge_size,
|
|
1214
|
+
w.item() // spatial_merge_size,
|
|
1215
|
+
)
|
|
1216
|
+
|
|
1217
|
+
for t_idx in range(llm_grid_t):
|
|
1218
|
+
t_index = torch.tensor(t_idx).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
|
|
1219
|
+
h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(1, -1, llm_grid_w).flatten()
|
|
1220
|
+
w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(1, llm_grid_h, -1).flatten()
|
|
1221
|
+
llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx)
|
|
1222
|
+
|
|
1223
|
+
if modality_type == 1:
|
|
1224
|
+
image_index += 1
|
|
1225
|
+
else:
|
|
1226
|
+
video_index += 1
|
|
1227
|
+
|
|
1228
|
+
llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
|
|
1229
|
+
position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
|
|
1230
|
+
mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
|
|
1231
|
+
mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
|
|
1232
|
+
return position_ids, mrope_position_deltas
|
|
1233
|
+
else:
|
|
1234
|
+
if attention_mask is not None:
|
|
1235
|
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
|
1236
|
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
|
1237
|
+
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
|
|
1238
|
+
max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
|
|
1239
|
+
mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
|
|
1240
|
+
else:
|
|
1241
|
+
position_ids = (
|
|
1242
|
+
torch.arange(input_ids.shape[1], device=input_ids.device)
|
|
1243
|
+
.view(1, 1, -1)
|
|
1244
|
+
.expand(3, input_ids.shape[0], -1)
|
|
1245
|
+
)
|
|
1246
|
+
mrope_position_deltas = torch.zeros(
|
|
1247
|
+
[input_ids.shape[0], 1],
|
|
1248
|
+
device=input_ids.device,
|
|
1249
|
+
dtype=input_ids.dtype,
|
|
1250
|
+
)
|
|
1251
|
+
|
|
1252
|
+
return position_ids, mrope_position_deltas
|
|
1253
|
+
|
|
1254
|
+
def get_video_features(
|
|
1255
|
+
self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
|
|
1256
|
+
):
|
|
1257
|
+
"""
|
|
1258
|
+
Encodes videos into continuous embeddings that can be forwarded to the language model.
|
|
1259
|
+
|
|
1260
|
+
Args:
|
|
1261
|
+
pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
|
1262
|
+
The tensors corresponding to the input videos.
|
|
1263
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
1264
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
1265
|
+
"""
|
|
1266
|
+
video_embeds = self.vision_tower(pixel_values_videos, video_grid_thw)
|
|
1267
|
+
video_embeds = self.resampler_model(video_embeds, video_grid_thw)
|
|
1268
|
+
split_sizes = (
|
|
1269
|
+
video_grid_thw.prod(-1)
|
|
1270
|
+
// self.vision_tower.spatial_merge_size**2
|
|
1271
|
+
// self.resampler_model.temporal_merge_size
|
|
1272
|
+
).tolist()
|
|
1273
|
+
video_embeds = torch.split(video_embeds, split_sizes)
|
|
1274
|
+
return video_embeds
|
|
1275
|
+
|
|
1276
|
+
def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
|
|
1277
|
+
"""
|
|
1278
|
+
Encodes images into continuous embeddings that can be forwarded to the language model.
|
|
1279
|
+
|
|
1280
|
+
Args:
|
|
1281
|
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
|
1282
|
+
The tensors corresponding to the input images.
|
|
1283
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
1284
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
1285
|
+
"""
|
|
1286
|
+
image_embeds = self.vision_tower(pixel_values, image_grid_thw)
|
|
1287
|
+
image_embeds = self.resampler_model(image_embeds, image_grid_thw)
|
|
1288
|
+
split_sizes = (image_grid_thw.prod(-1) // self.vision_tower.spatial_merge_size**2).tolist()
|
|
1289
|
+
image_embeds = torch.split(image_embeds, split_sizes)
|
|
1290
|
+
return image_embeds
|
|
1291
|
+
|
|
1292
|
+
@auto_docstring
|
|
1293
|
+
@can_return_tuple
|
|
1294
|
+
def forward(
|
|
1295
|
+
self,
|
|
1296
|
+
input_ids: torch.LongTensor = None,
|
|
1297
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1298
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
1299
|
+
mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1300
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1301
|
+
past_key_values: Optional[Cache] = None,
|
|
1302
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
1303
|
+
use_cache: Optional[bool] = None,
|
|
1304
|
+
pixel_values: Optional[torch.Tensor] = None,
|
|
1305
|
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
|
1306
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
1307
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
1308
|
+
rope_deltas: Optional[torch.LongTensor] = None,
|
|
1309
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
1310
|
+
**kwargs: Unpack[TransformersKwargs],
|
|
1311
|
+
) -> Union[tuple, MoeModelOutputWithPast]:
|
|
1312
|
+
r"""
|
|
1313
|
+
mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1314
|
+
Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
|
|
1315
|
+
moe_mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1316
|
+
The same as `mm_token_type_ids` while additionally considering start/end image/video tokens as respective vision tokens.
|
|
1317
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
1318
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
1319
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
1320
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
1321
|
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
|
1322
|
+
The rope index difference between sequence length and multimodal rope.
|
|
1323
|
+
"""
|
|
1324
|
+
if inputs_embeds is None:
|
|
1325
|
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
|
1326
|
+
|
|
1327
|
+
if pixel_values is not None:
|
|
1328
|
+
image_embeds = self.get_image_features(pixel_values, image_grid_thw)
|
|
1329
|
+
image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
|
|
1330
|
+
image_mask, _ = self.get_placeholder_mask(
|
|
1331
|
+
input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
|
|
1332
|
+
)
|
|
1333
|
+
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
|
|
1334
|
+
|
|
1335
|
+
if pixel_values_videos is not None:
|
|
1336
|
+
video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
|
|
1337
|
+
video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
|
|
1338
|
+
_, video_mask = self.get_placeholder_mask(
|
|
1339
|
+
input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds
|
|
1340
|
+
)
|
|
1341
|
+
inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
|
|
1342
|
+
|
|
1343
|
+
if position_ids is None:
|
|
1344
|
+
position_ids = self.get_position_ids(
|
|
1345
|
+
input_ids=input_ids,
|
|
1346
|
+
attention_mask=attention_mask,
|
|
1347
|
+
past_key_values=past_key_values,
|
|
1348
|
+
inputs_embeds=inputs_embeds,
|
|
1349
|
+
image_grid_thw=image_grid_thw,
|
|
1350
|
+
video_grid_thw=video_grid_thw,
|
|
1351
|
+
cache_position=cache_position,
|
|
1352
|
+
mm_token_type_ids=mm_token_type_ids,
|
|
1353
|
+
)
|
|
1354
|
+
|
|
1355
|
+
outputs = self.language_model(
|
|
1356
|
+
input_ids=None,
|
|
1357
|
+
position_ids=position_ids,
|
|
1358
|
+
moe_mm_token_type_ids=moe_mm_token_type_ids,
|
|
1359
|
+
attention_mask=attention_mask,
|
|
1360
|
+
use_cache=use_cache,
|
|
1361
|
+
past_key_values=past_key_values,
|
|
1362
|
+
inputs_embeds=inputs_embeds,
|
|
1363
|
+
return_dict=True,
|
|
1364
|
+
cache_position=cache_position,
|
|
1365
|
+
**kwargs,
|
|
1366
|
+
)
|
|
1367
|
+
|
|
1368
|
+
return MoeModelOutputWithPast(
|
|
1369
|
+
last_hidden_state=outputs.last_hidden_state,
|
|
1370
|
+
past_key_values=outputs.past_key_values,
|
|
1371
|
+
hidden_states=outputs.hidden_states,
|
|
1372
|
+
attentions=outputs.attentions,
|
|
1373
|
+
router_logits=outputs.router_logits,
|
|
1374
|
+
)
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
class Ernie4_5_VL_MoeForConditionalGeneration(Glm4vForConditionalGeneration, GenerationMixin):
|
|
1378
|
+
_checkpoint_conversion_mapping = {"^model.norm": "model.language_model.norm"}
|
|
1379
|
+
|
|
1380
|
+
def __init__(self, config):
|
|
1381
|
+
super().__init__(config)
|
|
1382
|
+
|
|
1383
|
+
self.router_aux_loss_coef = config.text_config.router_aux_loss_coef
|
|
1384
|
+
self.num_experts = config.text_config.moe_num_experts
|
|
1385
|
+
self.num_experts_per_tok = config.text_config.moe_k
|
|
1386
|
+
|
|
1387
|
+
def prepare_inputs_for_generation(
|
|
1388
|
+
self,
|
|
1389
|
+
input_ids,
|
|
1390
|
+
inputs_embeds=None,
|
|
1391
|
+
attention_mask=None,
|
|
1392
|
+
cache_position=None,
|
|
1393
|
+
past_key_values=None,
|
|
1394
|
+
image_grid_thw=None,
|
|
1395
|
+
video_grid_thw=None,
|
|
1396
|
+
use_cache=True,
|
|
1397
|
+
is_first_iteration=False,
|
|
1398
|
+
# Intentionally ignore position ids to force custom cache logic
|
|
1399
|
+
position_ids=None,
|
|
1400
|
+
**kwargs,
|
|
1401
|
+
):
|
|
1402
|
+
model_inputs = super().prepare_inputs_for_generation(
|
|
1403
|
+
input_ids,
|
|
1404
|
+
inputs_embeds=inputs_embeds,
|
|
1405
|
+
attention_mask=attention_mask,
|
|
1406
|
+
cache_position=cache_position,
|
|
1407
|
+
past_key_values=past_key_values,
|
|
1408
|
+
image_grid_thw=image_grid_thw,
|
|
1409
|
+
video_grid_thw=video_grid_thw,
|
|
1410
|
+
use_cache=use_cache,
|
|
1411
|
+
is_first_iteration=is_first_iteration,
|
|
1412
|
+
**kwargs,
|
|
1413
|
+
)
|
|
1414
|
+
|
|
1415
|
+
# Using our own caching with rope delta
|
|
1416
|
+
model_inputs["position_ids"] = self.model.get_position_ids(
|
|
1417
|
+
input_ids=model_inputs.get("input_ids"),
|
|
1418
|
+
attention_mask=model_inputs.get("attention_mask"),
|
|
1419
|
+
past_key_values=model_inputs.get("past_key_values"),
|
|
1420
|
+
inputs_embeds=model_inputs.get("inputs_embeds"),
|
|
1421
|
+
image_grid_thw=model_inputs.get("image_grid_thw"),
|
|
1422
|
+
video_grid_thw=model_inputs.get("video_grid_thw"),
|
|
1423
|
+
cache_position=model_inputs.get("cache_position"),
|
|
1424
|
+
mm_token_type_ids=model_inputs.get("mm_token_type_ids"),
|
|
1425
|
+
)
|
|
1426
|
+
|
|
1427
|
+
if not is_first_iteration and use_cache:
|
|
1428
|
+
model_inputs["pixel_values"] = None
|
|
1429
|
+
model_inputs["pixel_values_videos"] = None
|
|
1430
|
+
model_inputs["mm_token_type_ids"] = None
|
|
1431
|
+
model_inputs["moe_mm_token_type_ids"] = None
|
|
1432
|
+
|
|
1433
|
+
return model_inputs
|
|
1434
|
+
|
|
1435
|
+
@auto_docstring
|
|
1436
|
+
@can_return_tuple
|
|
1437
|
+
def forward(
|
|
1438
|
+
self,
|
|
1439
|
+
input_ids: torch.LongTensor = None,
|
|
1440
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
1441
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
1442
|
+
mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1443
|
+
moe_mm_token_type_ids: Optional[torch.IntTensor] = None,
|
|
1444
|
+
past_key_values: Optional[Cache] = None,
|
|
1445
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
1446
|
+
labels: Optional[torch.LongTensor] = None,
|
|
1447
|
+
use_cache: Optional[bool] = None,
|
|
1448
|
+
output_router_logits: Optional[bool] = None,
|
|
1449
|
+
pixel_values: Optional[torch.Tensor] = None,
|
|
1450
|
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
|
1451
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
1452
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
1453
|
+
rope_deltas: Optional[torch.LongTensor] = None,
|
|
1454
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
1455
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
1456
|
+
**kwargs: Unpack[TransformersKwargs],
|
|
1457
|
+
) -> Union[tuple, MoeCausalLMOutputWithPast]:
|
|
1458
|
+
r"""
|
|
1459
|
+
mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1460
|
+
Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
|
|
1461
|
+
moe_mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1462
|
+
The same as `mm_token_type_ids` while additionally considering start/end image/video tokens as respective vision tokens.
|
|
1463
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
1464
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
1465
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
1466
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
1467
|
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
|
1468
|
+
The temporal, height and width of feature shape of each image in LLM.
|
|
1469
|
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
|
1470
|
+
The temporal, height and width of feature shape of each video in LLM.
|
|
1471
|
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
|
1472
|
+
The rope index difference between sequence length and multimodal rope.
|
|
1473
|
+
"""
|
|
1474
|
+
output_router_logits = (
|
|
1475
|
+
output_router_logits if output_router_logits is not None else self.config.text_config.output_router_logits
|
|
1476
|
+
)
|
|
1477
|
+
|
|
1478
|
+
outputs = self.model(
|
|
1479
|
+
input_ids=input_ids,
|
|
1480
|
+
attention_mask=attention_mask,
|
|
1481
|
+
position_ids=position_ids,
|
|
1482
|
+
mm_token_type_ids=mm_token_type_ids,
|
|
1483
|
+
moe_mm_token_type_ids=moe_mm_token_type_ids,
|
|
1484
|
+
past_key_values=past_key_values,
|
|
1485
|
+
inputs_embeds=inputs_embeds,
|
|
1486
|
+
use_cache=use_cache,
|
|
1487
|
+
output_router_logits=output_router_logits,
|
|
1488
|
+
return_dict=True,
|
|
1489
|
+
pixel_values=pixel_values,
|
|
1490
|
+
pixel_values_videos=pixel_values_videos,
|
|
1491
|
+
image_grid_thw=image_grid_thw,
|
|
1492
|
+
video_grid_thw=video_grid_thw,
|
|
1493
|
+
rope_deltas=rope_deltas,
|
|
1494
|
+
cache_position=cache_position,
|
|
1495
|
+
**kwargs,
|
|
1496
|
+
)
|
|
1497
|
+
|
|
1498
|
+
hidden_states = outputs.last_hidden_state
|
|
1499
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
1500
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
1501
|
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
|
1502
|
+
|
|
1503
|
+
loss = None
|
|
1504
|
+
if labels is not None:
|
|
1505
|
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
|
|
1506
|
+
|
|
1507
|
+
aux_loss = None
|
|
1508
|
+
if output_router_logits:
|
|
1509
|
+
aux_loss = load_balancing_loss_func(
|
|
1510
|
+
outputs.router_logits,
|
|
1511
|
+
self.num_experts,
|
|
1512
|
+
self.num_experts_per_tok,
|
|
1513
|
+
attention_mask,
|
|
1514
|
+
)
|
|
1515
|
+
if labels is not None:
|
|
1516
|
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
|
1517
|
+
|
|
1518
|
+
return MoeCausalLMOutputWithPast(
|
|
1519
|
+
loss=loss,
|
|
1520
|
+
aux_loss=aux_loss,
|
|
1521
|
+
logits=logits,
|
|
1522
|
+
past_key_values=outputs.past_key_values,
|
|
1523
|
+
hidden_states=outputs.hidden_states,
|
|
1524
|
+
attentions=outputs.attentions,
|
|
1525
|
+
router_logits=outputs.router_logits,
|
|
1526
|
+
)
|
|
1527
|
+
|
|
1528
|
+
|
|
1529
|
+
class Ernie4_5_VL_MoeImageProcessorKwargs(Glm4vImageProcessorKwargs):
|
|
1530
|
+
r"""
|
|
1531
|
+
patch_size (`int`, *optional*, defaults to 14):
|
|
1532
|
+
The spatial patch size of the vision encoder.
|
|
1533
|
+
temporal_patch_size (`int`, *optional*):
|
|
1534
|
+
The temporal patch size of the vision encoder. Unused in the image processor, only used for videos.
|
|
1535
|
+
merge_size (`int`, *optional*, defaults to 2):
|
|
1536
|
+
The merge size of the vision encoder to llm encoder.
|
|
1537
|
+
"""
|
|
1538
|
+
|
|
1539
|
+
|
|
1540
|
+
class Ernie4_5_VL_MoeImageProcessor(Glm4vImageProcessor):
|
|
1541
|
+
r"""
|
|
1542
|
+
Constructs a Ernie 4.5 VL image processor that dynamically resizes images based on the original images.
|
|
1543
|
+
|
|
1544
|
+
Args:
|
|
1545
|
+
do_resize (`bool`, *optional*, defaults to `True`):
|
|
1546
|
+
Whether to resize the image's (height, width) dimensions.
|
|
1547
|
+
size (`dict[str, int]`, *optional*, defaults to `{"shortest_edge": 56 * 56, "longest_edge": 28 * 28 * 6177}`):
|
|
1548
|
+
Size of the image after resizing. `shortest_edge` and `longest_edge` keys must be present.
|
|
1549
|
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
|
1550
|
+
Resampling filter to use when resizing the image.
|
|
1551
|
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
|
1552
|
+
Whether to rescale the image by the specified scale `rescale_factor`.
|
|
1553
|
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
|
1554
|
+
Scale factor to use if rescaling the image.
|
|
1555
|
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
|
1556
|
+
Whether to normalize the image.
|
|
1557
|
+
image_mean (`float` or `list[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
|
|
1558
|
+
Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
|
|
1559
|
+
image_std (`float` or `list[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
|
|
1560
|
+
Standard deviation to use if normalizing the image. This is a float or list of floats for each channel
|
|
1561
|
+
in the image.
|
|
1562
|
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
|
1563
|
+
Whether to convert the image to RGB.
|
|
1564
|
+
patch_size (`int`, *optional*, defaults to 14):
|
|
1565
|
+
The spatial patch size of the vision encoder.
|
|
1566
|
+
temporal_patch_size (`int`, *optional*):
|
|
1567
|
+
The temporal patch size of the vision encoder. Unused in the image processor, only used for videos.
|
|
1568
|
+
merge_size (`int`, *optional*, defaults to 2):
|
|
1569
|
+
The merge size of the vision encoder to llm encoder.
|
|
1570
|
+
"""
|
|
1571
|
+
|
|
1572
|
+
def __init__(
|
|
1573
|
+
self,
|
|
1574
|
+
do_resize: bool = True,
|
|
1575
|
+
size: Optional[dict[str, int]] = None,
|
|
1576
|
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
|
1577
|
+
do_rescale: bool = True,
|
|
1578
|
+
rescale_factor: Union[int, float] = 1 / 255,
|
|
1579
|
+
do_normalize: bool = True,
|
|
1580
|
+
image_mean: Optional[Union[float, list[float]]] = None,
|
|
1581
|
+
image_std: Optional[Union[float, list[float]]] = None,
|
|
1582
|
+
do_convert_rgb: bool = True,
|
|
1583
|
+
patch_size: int = 14,
|
|
1584
|
+
temporal_patch_size: Optional[int] = None,
|
|
1585
|
+
merge_size: int = 2,
|
|
1586
|
+
**kwargs,
|
|
1587
|
+
) -> None:
|
|
1588
|
+
BaseImageProcessor.__init__(**kwargs)
|
|
1589
|
+
if size is not None:
|
|
1590
|
+
if "shortest_edge" not in size or "longest_edge" not in size:
|
|
1591
|
+
raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
|
|
1592
|
+
size = {"shortest_edge": size["shortest_edge"], "longest_edge": size["longest_edge"]}
|
|
1593
|
+
else:
|
|
1594
|
+
size = {"shortest_edge": 56 * 56, "longest_edge": 6177 * 28 * 28}
|
|
1595
|
+
self.size = size
|
|
1596
|
+
|
|
1597
|
+
self.do_resize = do_resize
|
|
1598
|
+
self.resample = resample
|
|
1599
|
+
self.do_rescale = do_rescale
|
|
1600
|
+
self.rescale_factor = rescale_factor
|
|
1601
|
+
self.do_normalize = do_normalize
|
|
1602
|
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
|
1603
|
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
|
1604
|
+
|
|
1605
|
+
self.patch_size = patch_size
|
|
1606
|
+
self.temporal_patch_size = temporal_patch_size
|
|
1607
|
+
self.merge_size = merge_size
|
|
1608
|
+
self.do_convert_rgb = do_convert_rgb
|
|
1609
|
+
|
|
1610
|
+
def _preprocess(
|
|
1611
|
+
self,
|
|
1612
|
+
images: ImageInput,
|
|
1613
|
+
do_resize: Optional[bool] = None,
|
|
1614
|
+
size: Optional[dict[str, int]] = None,
|
|
1615
|
+
resample: PILImageResampling = None,
|
|
1616
|
+
do_rescale: Optional[bool] = None,
|
|
1617
|
+
rescale_factor: Optional[float] = None,
|
|
1618
|
+
do_normalize: Optional[bool] = None,
|
|
1619
|
+
image_mean: Optional[Union[float, list[float]]] = None,
|
|
1620
|
+
image_std: Optional[Union[float, list[float]]] = None,
|
|
1621
|
+
patch_size: Optional[int] = None,
|
|
1622
|
+
temporal_patch_size: Optional[int] = None,
|
|
1623
|
+
merge_size: Optional[int] = None,
|
|
1624
|
+
do_convert_rgb: Optional[bool] = None,
|
|
1625
|
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
|
1626
|
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
|
1627
|
+
):
|
|
1628
|
+
"""
|
|
1629
|
+
Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
|
|
1630
|
+
|
|
1631
|
+
Args:
|
|
1632
|
+
images (`ImageInput`):
|
|
1633
|
+
Image or batch of images to preprocess. Expects pixel values ranging from 0 to 255. If pixel values range from 0 to 1, set `do_rescale=False`.
|
|
1634
|
+
vision_info (`list[Dict]`, *optional*):
|
|
1635
|
+
Optional list of dictionaries containing additional information about vision inputs.
|
|
1636
|
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
|
1637
|
+
Whether to resize the image.
|
|
1638
|
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
|
1639
|
+
Size of the image after resizing. `shortest_edge` and `longest_edge` keys must be present.
|
|
1640
|
+
resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
|
|
1641
|
+
Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
|
|
1642
|
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
|
1643
|
+
Whether to rescale the image.
|
|
1644
|
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
|
1645
|
+
Scale factor to use if rescaling the image.
|
|
1646
|
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
|
1647
|
+
Whether to normalize the image.
|
|
1648
|
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
|
1649
|
+
Mean to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
|
|
1650
|
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
|
1651
|
+
Standard deviation to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
|
|
1652
|
+
patch_size (`int`, *optional*, defaults to `self.patch_size`):
|
|
1653
|
+
The spatial patch size of the vision encoder.
|
|
1654
|
+
temporal_patch_size (`int`, *optional*):
|
|
1655
|
+
The temporal patch size of the vision encoder. Unused in the image processor, only used for videos.
|
|
1656
|
+
merge_size (`int`, *optional*, defaults to `self.merge_size`):
|
|
1657
|
+
The merge size of the vision encoder to llm encoder.
|
|
1658
|
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
|
1659
|
+
Whether to convert the image to RGB.
|
|
1660
|
+
data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
|
|
1661
|
+
The channel dimension format for the output image. Can be one of:
|
|
1662
|
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
|
1663
|
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
|
1664
|
+
- Unset: Use the channel dimension format of the input image.
|
|
1665
|
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
|
1666
|
+
The channel dimension format for the input image. Can be one of:
|
|
1667
|
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
|
1668
|
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
|
1669
|
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
|
1670
|
+
"""
|
|
1671
|
+
images = make_list_of_images(images)
|
|
1672
|
+
|
|
1673
|
+
if do_convert_rgb:
|
|
1674
|
+
images = [convert_to_rgb(image) for image in images]
|
|
1675
|
+
|
|
1676
|
+
# All transformations expect numpy arrays.
|
|
1677
|
+
images = [to_numpy_array(image) for image in images]
|
|
1678
|
+
|
|
1679
|
+
if do_rescale and is_scaled_image(images[0]):
|
|
1680
|
+
logger.warning_once(
|
|
1681
|
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
|
1682
|
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
|
1683
|
+
)
|
|
1684
|
+
if input_data_format is None:
|
|
1685
|
+
# We assume that all images have the same channel dimension format.
|
|
1686
|
+
input_data_format = infer_channel_dimension_format(images[0])
|
|
1687
|
+
|
|
1688
|
+
height, width = get_image_size(images[0], channel_dim=input_data_format)
|
|
1689
|
+
resized_height, resized_width = height, width
|
|
1690
|
+
processed_images = []
|
|
1691
|
+
for image in images:
|
|
1692
|
+
if do_resize:
|
|
1693
|
+
resized_height, resized_width = smart_resize(
|
|
1694
|
+
height,
|
|
1695
|
+
width,
|
|
1696
|
+
factor=patch_size * merge_size,
|
|
1697
|
+
min_pixels=size["shortest_edge"],
|
|
1698
|
+
max_pixels=size["longest_edge"],
|
|
1699
|
+
)
|
|
1700
|
+
image = resize(
|
|
1701
|
+
image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format
|
|
1702
|
+
)
|
|
1703
|
+
|
|
1704
|
+
if do_rescale:
|
|
1705
|
+
image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
|
|
1706
|
+
|
|
1707
|
+
if do_normalize:
|
|
1708
|
+
image = self.normalize(
|
|
1709
|
+
image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
|
|
1710
|
+
)
|
|
1711
|
+
|
|
1712
|
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
|
1713
|
+
processed_images.append(image)
|
|
1714
|
+
|
|
1715
|
+
patches = np.array(processed_images)
|
|
1716
|
+
if data_format == ChannelDimension.LAST:
|
|
1717
|
+
patches = patches.transpose([0, 3, 1, 2])
|
|
1718
|
+
|
|
1719
|
+
# Main difference to Qwen2 VL - no temporal patches
|
|
1720
|
+
channel = patches.shape[1]
|
|
1721
|
+
grid_t = patches.shape[0]
|
|
1722
|
+
grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
|
|
1723
|
+
patches = patches.reshape(
|
|
1724
|
+
[
|
|
1725
|
+
grid_t,
|
|
1726
|
+
channel,
|
|
1727
|
+
grid_h // merge_size,
|
|
1728
|
+
merge_size,
|
|
1729
|
+
patch_size,
|
|
1730
|
+
grid_w // merge_size,
|
|
1731
|
+
merge_size,
|
|
1732
|
+
patch_size,
|
|
1733
|
+
]
|
|
1734
|
+
)
|
|
1735
|
+
# [grid_t, grid_h/merge, grid_w/merge, merge, merge, channel, patch, patch]
|
|
1736
|
+
patches = patches.transpose([0, 2, 5, 3, 6, 1, 4, 7])
|
|
1737
|
+
flatten_patches = patches.reshape(grid_t * grid_h * grid_w, channel * patch_size * patch_size)
|
|
1738
|
+
|
|
1739
|
+
return flatten_patches, (grid_t, grid_h, grid_w)
|
|
1740
|
+
|
|
1741
|
+
def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
|
|
1742
|
+
"""
|
|
1743
|
+
A utility that returns number of image patches for a given image size.
|
|
1744
|
+
|
|
1745
|
+
Args:
|
|
1746
|
+
height (`int`):
|
|
1747
|
+
Height of the input image.
|
|
1748
|
+
width (`int`):
|
|
1749
|
+
Width of the input image.
|
|
1750
|
+
images_kwargs (`dict`, *optional*)
|
|
1751
|
+
Any kwargs to override defaults of the image processor.
|
|
1752
|
+
Returns:
|
|
1753
|
+
`int`: Number of image patches per image.
|
|
1754
|
+
"""
|
|
1755
|
+
min_pixels = self.size["shortest_edge"]
|
|
1756
|
+
max_pixels = self.size["longest_edge"]
|
|
1757
|
+
patch_size = images_kwargs.get("patch_size", self.patch_size)
|
|
1758
|
+
merge_size = images_kwargs.get("merge_size", self.merge_size)
|
|
1759
|
+
|
|
1760
|
+
factor = patch_size * merge_size
|
|
1761
|
+
resized_height, resized_width = smart_resize(
|
|
1762
|
+
height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels
|
|
1763
|
+
)
|
|
1764
|
+
grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
|
|
1765
|
+
return grid_h * grid_w
|
|
1766
|
+
|
|
1767
|
+
|
|
1768
|
+
class Ernie4_5_VL_MoeImageProcessorFast(Glm4vImageProcessorFast):
|
|
1769
|
+
size = {"shortest_edge": 56 * 56, "longest_edge": 28 * 28 * 6177}
|
|
1770
|
+
temporal_patch_size = None # Unused
|
|
1771
|
+
|
|
1772
|
+
def _preprocess(
|
|
1773
|
+
self,
|
|
1774
|
+
images: list["torch.Tensor"],
|
|
1775
|
+
do_resize: bool,
|
|
1776
|
+
size: SizeDict,
|
|
1777
|
+
interpolation: Optional["F.InterpolationMode"],
|
|
1778
|
+
do_rescale: bool,
|
|
1779
|
+
rescale_factor: float,
|
|
1780
|
+
do_normalize: bool,
|
|
1781
|
+
image_mean: Optional[Union[float, list[float]]],
|
|
1782
|
+
image_std: Optional[Union[float, list[float]]],
|
|
1783
|
+
patch_size: int,
|
|
1784
|
+
merge_size: int,
|
|
1785
|
+
disable_grouping: Optional[bool],
|
|
1786
|
+
return_tensors: Optional[Union[str, TensorType]],
|
|
1787
|
+
**kwargs,
|
|
1788
|
+
):
|
|
1789
|
+
# Group images by size for batched resizing
|
|
1790
|
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
|
1791
|
+
resized_images_grouped = {}
|
|
1792
|
+
for shape, stacked_images in grouped_images.items():
|
|
1793
|
+
height, width = stacked_images.shape[-2:]
|
|
1794
|
+
if do_resize:
|
|
1795
|
+
resized_height, resized_width = smart_resize(
|
|
1796
|
+
height,
|
|
1797
|
+
width,
|
|
1798
|
+
factor=patch_size * merge_size,
|
|
1799
|
+
min_pixels=size["shortest_edge"],
|
|
1800
|
+
max_pixels=size["longest_edge"],
|
|
1801
|
+
)
|
|
1802
|
+
stacked_images = self.resize(
|
|
1803
|
+
image=stacked_images,
|
|
1804
|
+
size=SizeDict(height=resized_height, width=resized_width),
|
|
1805
|
+
interpolation=interpolation,
|
|
1806
|
+
)
|
|
1807
|
+
resized_images_grouped[shape] = stacked_images
|
|
1808
|
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
|
1809
|
+
|
|
1810
|
+
# Group images by size for further processing
|
|
1811
|
+
# Needed in case do_resize is False, or resize returns images with different sizes
|
|
1812
|
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
|
1813
|
+
processed_images_grouped = {}
|
|
1814
|
+
processed_grids = {}
|
|
1815
|
+
for shape, stacked_images in grouped_images.items():
|
|
1816
|
+
resized_height, resized_width = stacked_images.shape[-2:]
|
|
1817
|
+
# Fused rescale and normalize
|
|
1818
|
+
patches = self.rescale_and_normalize(
|
|
1819
|
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
|
1820
|
+
)
|
|
1821
|
+
if patches.ndim == 4:
|
|
1822
|
+
# add a temporal dimension if we have images
|
|
1823
|
+
patches = patches.unsqueeze(1)
|
|
1824
|
+
|
|
1825
|
+
# Main difference to Qwen2 VL - no temporal patches
|
|
1826
|
+
batch_size, grid_t, channel = patches.shape[:3]
|
|
1827
|
+
grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
|
|
1828
|
+
|
|
1829
|
+
patches = patches.view(
|
|
1830
|
+
batch_size,
|
|
1831
|
+
grid_t,
|
|
1832
|
+
channel,
|
|
1833
|
+
grid_h // merge_size,
|
|
1834
|
+
merge_size,
|
|
1835
|
+
patch_size,
|
|
1836
|
+
grid_w // merge_size,
|
|
1837
|
+
merge_size,
|
|
1838
|
+
patch_size,
|
|
1839
|
+
)
|
|
1840
|
+
# Reorder dimensions to group grid and patch information for subsequent flattening.
|
|
1841
|
+
# [batch, grid_t, grid_h/merge, grid_w/merge, merge, merge, channel, patch, patch]
|
|
1842
|
+
patches = patches.permute(0, 1, 3, 6, 4, 7, 2, 5, 8)
|
|
1843
|
+
|
|
1844
|
+
flatten_patches = patches.reshape(
|
|
1845
|
+
batch_size,
|
|
1846
|
+
grid_t * grid_h * grid_w,
|
|
1847
|
+
channel * patch_size * patch_size,
|
|
1848
|
+
)
|
|
1849
|
+
|
|
1850
|
+
processed_images_grouped[shape] = flatten_patches
|
|
1851
|
+
processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
|
|
1852
|
+
|
|
1853
|
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
|
1854
|
+
processed_grids = reorder_images(processed_grids, grouped_images_index)
|
|
1855
|
+
pixel_values = torch.cat(processed_images, dim=0)
|
|
1856
|
+
image_grid_thw = torch.tensor(processed_grids)
|
|
1857
|
+
|
|
1858
|
+
return BatchFeature(
|
|
1859
|
+
data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors
|
|
1860
|
+
)
|
|
1861
|
+
|
|
1862
|
+
def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
|
|
1863
|
+
"""
|
|
1864
|
+
A utility that returns number of image patches for a given image size.
|
|
1865
|
+
|
|
1866
|
+
Note: Do not remove this method! It is used by vLLM to infer the number of patches and placeholders
|
|
1867
|
+
without an image input.
|
|
1868
|
+
|
|
1869
|
+
Args:
|
|
1870
|
+
height (`int`):
|
|
1871
|
+
Height of the input image.
|
|
1872
|
+
width (`int`):
|
|
1873
|
+
Width of the input image.
|
|
1874
|
+
images_kwargs (`dict`, *optional*)
|
|
1875
|
+
Any kwargs to override defaults of the image processor.
|
|
1876
|
+
Returns:
|
|
1877
|
+
`int`: Number of image patches per image.
|
|
1878
|
+
"""
|
|
1879
|
+
min_pixels = self.size["shortest_edge"]
|
|
1880
|
+
max_pixels = self.size["longest_edge"]
|
|
1881
|
+
patch_size = images_kwargs.get("patch_size", self.patch_size)
|
|
1882
|
+
merge_size = images_kwargs.get("merge_size", self.merge_size)
|
|
1883
|
+
|
|
1884
|
+
factor = patch_size * merge_size
|
|
1885
|
+
resized_height, resized_width = smart_resize(
|
|
1886
|
+
height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels
|
|
1887
|
+
)
|
|
1888
|
+
grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
|
|
1889
|
+
return grid_h * grid_w
|
|
1890
|
+
|
|
1891
|
+
|
|
1892
|
+
__all__ = [
|
|
1893
|
+
"Ernie4_5_VL_MoeConfig",
|
|
1894
|
+
"Ernie4_5_VL_MoeTextConfig",
|
|
1895
|
+
"Ernie4_5_VL_MoeVisionConfig",
|
|
1896
|
+
"Ernie4_5_VL_MoePreTrainedModel",
|
|
1897
|
+
"Ernie4_5_VL_MoeForConditionalGeneration",
|
|
1898
|
+
"Ernie4_5_VL_MoeModel",
|
|
1899
|
+
"Ernie4_5_VL_MoeTextModel",
|
|
1900
|
+
"Ernie4_5_VL_MoeVisionTransformerPretrainedModel",
|
|
1901
|
+
"Ernie4_5_VL_MoeVariableResolutionResamplerModel",
|
|
1902
|
+
"Ernie4_5_VL_MoeImageProcessor",
|
|
1903
|
+
"Ernie4_5_VL_MoeImageProcessorFast",
|
|
1904
|
+
]
|