paddlex 2.0.0rc4__py3-none-any.whl → 3.0.0__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.
- paddlex/.version +1 -0
- paddlex/__init__.py +35 -18
- paddlex/__main__.py +39 -0
- paddlex/configs/modules/3d_bev_detection/BEVFusion.yaml +38 -0
- paddlex/configs/modules/chart_parsing/PP-Chart2Table.yaml +13 -0
- paddlex/configs/modules/doc_text_orientation/PP-LCNet_x1_0_doc_ori.yaml +41 -0
- paddlex/configs/modules/doc_vlm/PP-DocBee-2B.yaml +14 -0
- paddlex/configs/modules/doc_vlm/PP-DocBee-7B.yaml +14 -0
- paddlex/configs/modules/doc_vlm/PP-DocBee2-3B.yaml +14 -0
- paddlex/configs/modules/face_detection/BlazeFace-FPN-SSH.yaml +40 -0
- paddlex/configs/modules/face_detection/BlazeFace.yaml +40 -0
- paddlex/configs/modules/face_detection/PP-YOLOE_plus-S_face.yaml +40 -0
- paddlex/configs/modules/face_detection/PicoDet_LCNet_x2_5_face.yaml +40 -0
- paddlex/configs/modules/face_feature/MobileFaceNet.yaml +41 -0
- paddlex/configs/modules/face_feature/ResNet50_face.yaml +41 -0
- paddlex/configs/modules/formula_recognition/LaTeX_OCR_rec.yaml +40 -0
- paddlex/configs/modules/formula_recognition/PP-FormulaNet-L.yaml +40 -0
- paddlex/configs/modules/formula_recognition/PP-FormulaNet-S.yaml +40 -0
- paddlex/configs/modules/formula_recognition/PP-FormulaNet_plus-L.yaml +40 -0
- paddlex/configs/modules/formula_recognition/PP-FormulaNet_plus-M.yaml +40 -0
- paddlex/configs/modules/formula_recognition/PP-FormulaNet_plus-S.yaml +40 -0
- paddlex/configs/modules/formula_recognition/UniMERNet.yaml +40 -0
- paddlex/configs/modules/human_detection/PP-YOLOE-L_human.yaml +42 -0
- paddlex/configs/modules/human_detection/PP-YOLOE-S_human.yaml +42 -0
- paddlex/configs/modules/image_anomaly_detection/STFPM.yaml +41 -0
- paddlex/configs/modules/image_classification/CLIP_vit_base_patch16_224.yaml +41 -0
- paddlex/configs/modules/image_classification/CLIP_vit_large_patch14_224.yaml +41 -0
- paddlex/configs/modules/image_classification/ConvNeXt_base_224.yaml +41 -0
- paddlex/configs/modules/image_classification/ConvNeXt_base_384.yaml +41 -0
- paddlex/configs/modules/image_classification/ConvNeXt_large_224.yaml +41 -0
- paddlex/configs/modules/image_classification/ConvNeXt_large_384.yaml +41 -0
- paddlex/configs/modules/image_classification/ConvNeXt_small.yaml +41 -0
- paddlex/configs/modules/image_classification/ConvNeXt_tiny.yaml +41 -0
- paddlex/configs/modules/image_classification/FasterNet-L.yaml +40 -0
- paddlex/configs/modules/image_classification/FasterNet-M.yaml +40 -0
- paddlex/configs/modules/image_classification/FasterNet-S.yaml +40 -0
- paddlex/configs/modules/image_classification/FasterNet-T0.yaml +40 -0
- paddlex/configs/modules/image_classification/FasterNet-T1.yaml +40 -0
- paddlex/configs/modules/image_classification/FasterNet-T2.yaml +40 -0
- paddlex/configs/modules/image_classification/MobileNetV1_x0_25.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV1_x0_5.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV1_x0_75.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV1_x1_0.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV2_x0_25.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV2_x0_5.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV2_x1_0.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV2_x1_5.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV2_x2_0.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_large_x0_35.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_large_x0_5.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_large_x0_75.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_large_x1_0.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_large_x1_25.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_small_x0_35.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_small_x0_5.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_small_x0_75.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_small_x1_0.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV3_small_x1_25.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV4_conv_large.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV4_conv_medium.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV4_conv_small.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV4_hybrid_large.yaml +41 -0
- paddlex/configs/modules/image_classification/MobileNetV4_hybrid_medium.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNetV2-B0.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNetV2-B1.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNetV2-B2.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNetV2-B3.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNetV2-B4.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNetV2-B5.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNetV2-B6.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNet_base.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNet_small.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-HGNet_tiny.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNetV2_base.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNetV2_large.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNetV2_small.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNet_x0_25.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNet_x0_35.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNet_x0_5.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNet_x0_75.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNet_x1_0.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNet_x1_5.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNet_x2_0.yaml +41 -0
- paddlex/configs/modules/image_classification/PP-LCNet_x2_5.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet101.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet101_vd.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet152.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet152_vd.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet18.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet18_vd.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet200_vd.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet34.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet34_vd.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet50.yaml +41 -0
- paddlex/configs/modules/image_classification/ResNet50_vd.yaml +41 -0
- paddlex/configs/modules/image_classification/StarNet-S1.yaml +41 -0
- paddlex/configs/modules/image_classification/StarNet-S2.yaml +41 -0
- paddlex/configs/modules/image_classification/StarNet-S3.yaml +41 -0
- paddlex/configs/modules/image_classification/StarNet-S4.yaml +41 -0
- paddlex/configs/modules/image_classification/SwinTransformer_base_patch4_window12_384.yaml +41 -0
- paddlex/configs/modules/image_classification/SwinTransformer_base_patch4_window7_224.yaml +41 -0
- paddlex/configs/modules/image_classification/SwinTransformer_large_patch4_window12_384.yaml +41 -0
- paddlex/configs/modules/image_classification/SwinTransformer_large_patch4_window7_224.yaml +41 -0
- paddlex/configs/modules/image_classification/SwinTransformer_small_patch4_window7_224.yaml +41 -0
- paddlex/configs/modules/image_classification/SwinTransformer_tiny_patch4_window7_224.yaml +41 -0
- paddlex/configs/modules/image_feature/PP-ShiTuV2_rec.yaml +42 -0
- paddlex/configs/modules/image_feature/PP-ShiTuV2_rec_CLIP_vit_base.yaml +42 -0
- paddlex/configs/modules/image_feature/PP-ShiTuV2_rec_CLIP_vit_large.yaml +41 -0
- paddlex/configs/modules/image_multilabel_classification/CLIP_vit_base_patch16_448_ML.yaml +41 -0
- paddlex/configs/modules/image_multilabel_classification/PP-HGNetV2-B0_ML.yaml +41 -0
- paddlex/configs/modules/image_multilabel_classification/PP-HGNetV2-B4_ML.yaml +41 -0
- paddlex/configs/modules/image_multilabel_classification/PP-HGNetV2-B6_ML.yaml +41 -0
- paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml +41 -0
- paddlex/configs/modules/image_multilabel_classification/ResNet50_ML.yaml +41 -0
- paddlex/configs/modules/image_unwarping/UVDoc.yaml +12 -0
- paddlex/configs/modules/instance_segmentation/Cascade-MaskRCNN-ResNet50-FPN.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/Cascade-MaskRCNN-ResNet50-vd-SSLDv2-FPN.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/Mask-RT-DETR-H.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/Mask-RT-DETR-L.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/Mask-RT-DETR-M.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/Mask-RT-DETR-S.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/Mask-RT-DETR-X.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/MaskRCNN-ResNeXt101-vd-FPN.yaml +39 -0
- paddlex/configs/modules/instance_segmentation/MaskRCNN-ResNet101-FPN.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/MaskRCNN-ResNet101-vd-FPN.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/MaskRCNN-ResNet50-FPN.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/MaskRCNN-ResNet50-vd-FPN.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/MaskRCNN-ResNet50.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/PP-YOLOE_seg-S.yaml +40 -0
- paddlex/configs/modules/instance_segmentation/SOLOv2.yaml +40 -0
- paddlex/configs/modules/keypoint_detection/PP-TinyPose_128x96.yaml +40 -0
- paddlex/configs/modules/keypoint_detection/PP-TinyPose_256x192.yaml +40 -0
- paddlex/configs/modules/layout_detection/PP-DocBlockLayout.yaml +40 -0
- paddlex/configs/modules/layout_detection/PP-DocLayout-L.yaml +40 -0
- paddlex/configs/modules/layout_detection/PP-DocLayout-M.yaml +40 -0
- paddlex/configs/modules/layout_detection/PP-DocLayout-S.yaml +40 -0
- paddlex/configs/modules/layout_detection/PP-DocLayout_plus-L.yaml +40 -0
- paddlex/configs/modules/layout_detection/PicoDet-L_layout_17cls.yaml +40 -0
- paddlex/configs/modules/layout_detection/PicoDet-L_layout_3cls.yaml +40 -0
- paddlex/configs/modules/layout_detection/PicoDet-S_layout_17cls.yaml +40 -0
- paddlex/configs/modules/layout_detection/PicoDet-S_layout_3cls.yaml +40 -0
- paddlex/configs/modules/layout_detection/PicoDet_layout_1x.yaml +40 -0
- paddlex/configs/modules/layout_detection/PicoDet_layout_1x_table.yaml +40 -0
- paddlex/configs/modules/layout_detection/RT-DETR-H_layout_17cls.yaml +40 -0
- paddlex/configs/modules/layout_detection/RT-DETR-H_layout_3cls.yaml +40 -0
- paddlex/configs/modules/mainbody_detection/PP-ShiTuV2_det.yaml +41 -0
- paddlex/configs/modules/multilingual_speech_recognition/whisper_base.yaml +12 -0
- paddlex/configs/modules/multilingual_speech_recognition/whisper_large.yaml +12 -0
- paddlex/configs/modules/multilingual_speech_recognition/whisper_medium.yaml +12 -0
- paddlex/configs/modules/multilingual_speech_recognition/whisper_small.yaml +12 -0
- paddlex/configs/modules/multilingual_speech_recognition/whisper_tiny.yaml +12 -0
- paddlex/configs/modules/object_detection/Cascade-FasterRCNN-ResNet50-FPN.yaml +41 -0
- paddlex/configs/modules/object_detection/Cascade-FasterRCNN-ResNet50-vd-SSLDv2-FPN.yaml +42 -0
- paddlex/configs/modules/object_detection/CenterNet-DLA-34.yaml +41 -0
- paddlex/configs/modules/object_detection/CenterNet-ResNet50.yaml +41 -0
- paddlex/configs/modules/object_detection/Co-DINO-R50.yaml +40 -0
- paddlex/configs/modules/object_detection/Co-DINO-Swin-L.yaml +40 -0
- paddlex/configs/modules/object_detection/Co-Deformable-DETR-R50.yaml +40 -0
- paddlex/configs/modules/object_detection/Co-Deformable-DETR-Swin-T.yaml +40 -0
- paddlex/configs/modules/object_detection/DETR-R50.yaml +42 -0
- paddlex/configs/modules/object_detection/FCOS-ResNet50.yaml +41 -0
- paddlex/configs/modules/object_detection/FasterRCNN-ResNeXt101-vd-FPN.yaml +42 -0
- paddlex/configs/modules/object_detection/FasterRCNN-ResNet101-FPN.yaml +42 -0
- paddlex/configs/modules/object_detection/FasterRCNN-ResNet101.yaml +42 -0
- paddlex/configs/modules/object_detection/FasterRCNN-ResNet34-FPN.yaml +42 -0
- paddlex/configs/modules/object_detection/FasterRCNN-ResNet50-FPN.yaml +42 -0
- paddlex/configs/modules/object_detection/FasterRCNN-ResNet50-vd-FPN.yaml +42 -0
- paddlex/configs/modules/object_detection/FasterRCNN-ResNet50-vd-SSLDv2-FPN.yaml +42 -0
- paddlex/configs/modules/object_detection/FasterRCNN-ResNet50.yaml +42 -0
- paddlex/configs/modules/object_detection/FasterRCNN-Swin-Tiny-FPN.yaml +42 -0
- paddlex/configs/modules/object_detection/PP-YOLOE_plus-L.yaml +40 -0
- paddlex/configs/modules/object_detection/PP-YOLOE_plus-M.yaml +40 -0
- paddlex/configs/modules/object_detection/PP-YOLOE_plus-S.yaml +40 -0
- paddlex/configs/modules/object_detection/PP-YOLOE_plus-X.yaml +40 -0
- paddlex/configs/modules/object_detection/PicoDet-L.yaml +40 -0
- paddlex/configs/modules/object_detection/PicoDet-M.yaml +42 -0
- paddlex/configs/modules/object_detection/PicoDet-S.yaml +40 -0
- paddlex/configs/modules/object_detection/PicoDet-XS.yaml +42 -0
- paddlex/configs/modules/object_detection/RT-DETR-H.yaml +40 -0
- paddlex/configs/modules/object_detection/RT-DETR-L.yaml +40 -0
- paddlex/configs/modules/object_detection/RT-DETR-R18.yaml +40 -0
- paddlex/configs/modules/object_detection/RT-DETR-R50.yaml +40 -0
- paddlex/configs/modules/object_detection/RT-DETR-X.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOX-L.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOX-M.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOX-N.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOX-S.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOX-T.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOX-X.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOv3-DarkNet53.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOv3-MobileNetV3.yaml +40 -0
- paddlex/configs/modules/object_detection/YOLOv3-ResNet50_vd_DCN.yaml +40 -0
- paddlex/configs/modules/open_vocabulary_detection/GroundingDINO-T.yaml +13 -0
- paddlex/configs/modules/open_vocabulary_detection/YOLO-Worldv2-L.yaml +13 -0
- paddlex/configs/modules/open_vocabulary_segmentation/SAM-H_box.yaml +17 -0
- paddlex/configs/modules/open_vocabulary_segmentation/SAM-H_point.yaml +15 -0
- paddlex/configs/modules/pedestrian_attribute_recognition/PP-LCNet_x1_0_pedestrian_attribute.yaml +41 -0
- paddlex/configs/modules/rotated_object_detection/PP-YOLOE-R-L.yaml +40 -0
- paddlex/configs/modules/seal_text_detection/PP-OCRv4_mobile_seal_det.yaml +40 -0
- paddlex/configs/modules/seal_text_detection/PP-OCRv4_server_seal_det.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/Deeplabv3-R101.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/Deeplabv3-R50.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/Deeplabv3_Plus-R101.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/Deeplabv3_Plus-R50.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/MaskFormer_small.yaml +42 -0
- paddlex/configs/modules/semantic_segmentation/MaskFormer_tiny.yaml +42 -0
- paddlex/configs/modules/semantic_segmentation/OCRNet_HRNet-W18.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/OCRNet_HRNet-W48.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/PP-LiteSeg-B.yaml +41 -0
- paddlex/configs/modules/semantic_segmentation/PP-LiteSeg-T.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SeaFormer_base.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SeaFormer_large.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SeaFormer_small.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SeaFormer_tiny.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SegFormer-B0.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SegFormer-B1.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SegFormer-B2.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SegFormer-B3.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SegFormer-B4.yaml +40 -0
- paddlex/configs/modules/semantic_segmentation/SegFormer-B5.yaml +40 -0
- paddlex/configs/modules/small_object_detection/PP-YOLOE_plus_SOD-L.yaml +42 -0
- paddlex/configs/modules/small_object_detection/PP-YOLOE_plus_SOD-S.yaml +42 -0
- paddlex/configs/modules/small_object_detection/PP-YOLOE_plus_SOD-largesize-L.yaml +42 -0
- paddlex/configs/modules/table_cells_detection/RT-DETR-L_wired_table_cell_det.yaml +40 -0
- paddlex/configs/modules/table_cells_detection/RT-DETR-L_wireless_table_cell_det.yaml +40 -0
- paddlex/configs/modules/table_classification/PP-LCNet_x1_0_table_cls.yaml +41 -0
- paddlex/configs/modules/table_structure_recognition/SLANeXt_wired.yaml +39 -0
- paddlex/configs/modules/table_structure_recognition/SLANeXt_wireless.yaml +39 -0
- paddlex/configs/modules/table_structure_recognition/SLANet.yaml +39 -0
- paddlex/configs/modules/table_structure_recognition/SLANet_plus.yaml +39 -0
- paddlex/configs/modules/text_detection/PP-OCRv3_mobile_det.yaml +40 -0
- paddlex/configs/modules/text_detection/PP-OCRv3_server_det.yaml +40 -0
- paddlex/configs/modules/text_detection/PP-OCRv4_mobile_det.yaml +40 -0
- paddlex/configs/modules/text_detection/PP-OCRv4_server_det.yaml +40 -0
- paddlex/configs/modules/text_detection/PP-OCRv5_mobile_det.yaml +40 -0
- paddlex/configs/modules/text_detection/PP-OCRv5_server_det.yaml +40 -0
- paddlex/configs/modules/text_recognition/PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/PP-OCRv4_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/PP-OCRv4_server_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/PP-OCRv4_server_rec_doc.yaml +39 -0
- paddlex/configs/modules/text_recognition/PP-OCRv5_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/PP-OCRv5_server_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/arabic_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/ch_RepSVTR_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/ch_SVTRv2_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/chinese_cht_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/cyrillic_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/devanagari_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/en_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/en_PP-OCRv4_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/japan_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/ka_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/korean_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/latin_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/ta_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/text_recognition/te_PP-OCRv3_mobile_rec.yaml +39 -0
- paddlex/configs/modules/textline_orientation/PP-LCNet_x0_25_textline_ori.yaml +41 -0
- paddlex/configs/modules/ts_anomaly_detection/AutoEncoder_ad.yaml +37 -0
- paddlex/configs/modules/ts_anomaly_detection/DLinear_ad.yaml +37 -0
- paddlex/configs/modules/ts_anomaly_detection/Nonstationary_ad.yaml +37 -0
- paddlex/configs/modules/ts_anomaly_detection/PatchTST_ad.yaml +37 -0
- paddlex/configs/modules/ts_anomaly_detection/TimesNet_ad.yaml +37 -0
- paddlex/configs/modules/ts_classification/TimesNet_cls.yaml +37 -0
- paddlex/configs/modules/ts_forecast/DLinear.yaml +38 -0
- paddlex/configs/modules/ts_forecast/NLinear.yaml +38 -0
- paddlex/configs/modules/ts_forecast/Nonstationary.yaml +38 -0
- paddlex/configs/modules/ts_forecast/PatchTST.yaml +38 -0
- paddlex/configs/modules/ts_forecast/RLinear.yaml +38 -0
- paddlex/configs/modules/ts_forecast/TiDE.yaml +38 -0
- paddlex/configs/modules/ts_forecast/TimesNet.yaml +38 -0
- paddlex/configs/modules/vehicle_attribute_recognition/PP-LCNet_x1_0_vehicle_attribute.yaml +41 -0
- paddlex/configs/modules/vehicle_detection/PP-YOLOE-L_vehicle.yaml +41 -0
- paddlex/configs/modules/vehicle_detection/PP-YOLOE-S_vehicle.yaml +42 -0
- paddlex/configs/modules/video_classification/PP-TSM-R50_8frames_uniform.yaml +42 -0
- paddlex/configs/modules/video_classification/PP-TSMv2-LCNetV2_16frames_uniform.yaml +42 -0
- paddlex/configs/modules/video_classification/PP-TSMv2-LCNetV2_8frames_uniform.yaml +42 -0
- paddlex/configs/modules/video_detection/YOWO.yaml +40 -0
- paddlex/configs/pipelines/3d_bev_detection.yaml +9 -0
- paddlex/configs/pipelines/OCR.yaml +45 -0
- paddlex/configs/pipelines/PP-ChatOCRv3-doc.yaml +151 -0
- paddlex/configs/pipelines/PP-ChatOCRv4-doc.yaml +237 -0
- paddlex/configs/pipelines/PP-ShiTuV2.yaml +18 -0
- paddlex/configs/pipelines/PP-StructureV3.yaml +226 -0
- paddlex/configs/pipelines/anomaly_detection.yaml +8 -0
- paddlex/configs/pipelines/doc_preprocessor.yaml +15 -0
- paddlex/configs/pipelines/doc_understanding.yaml +9 -0
- paddlex/configs/pipelines/face_recognition.yaml +18 -0
- paddlex/configs/pipelines/formula_recognition.yaml +39 -0
- paddlex/configs/pipelines/human_keypoint_detection.yaml +17 -0
- paddlex/configs/pipelines/image_classification.yaml +10 -0
- paddlex/configs/pipelines/image_multilabel_classification.yaml +9 -0
- paddlex/configs/pipelines/instance_segmentation.yaml +10 -0
- paddlex/configs/pipelines/layout_parsing.yaml +102 -0
- paddlex/configs/pipelines/multilingual_speech_recognition.yaml +9 -0
- paddlex/configs/pipelines/object_detection.yaml +10 -0
- paddlex/configs/pipelines/open_vocabulary_detection.yaml +12 -0
- paddlex/configs/pipelines/open_vocabulary_segmentation.yaml +13 -0
- paddlex/configs/pipelines/pedestrian_attribute_recognition.yaml +15 -0
- paddlex/configs/pipelines/rotated_object_detection.yaml +10 -0
- paddlex/configs/pipelines/seal_recognition.yaml +52 -0
- paddlex/configs/pipelines/semantic_segmentation.yaml +10 -0
- paddlex/configs/pipelines/small_object_detection.yaml +10 -0
- paddlex/configs/pipelines/table_recognition.yaml +57 -0
- paddlex/configs/pipelines/table_recognition_v2.yaml +82 -0
- paddlex/configs/pipelines/ts_anomaly_detection.yaml +8 -0
- paddlex/configs/pipelines/ts_classification.yaml +8 -0
- paddlex/configs/pipelines/ts_forecast.yaml +8 -0
- paddlex/configs/pipelines/vehicle_attribute_recognition.yaml +15 -0
- paddlex/configs/pipelines/video_classification.yaml +9 -0
- paddlex/configs/pipelines/video_detection.yaml +10 -0
- paddlex/constants.py +17 -0
- paddlex/engine.py +56 -0
- paddlex/hpip_links.html +31 -0
- paddlex/inference/__init__.py +19 -0
- paddlex/inference/common/__init__.py +13 -0
- paddlex/inference/common/batch_sampler/__init__.py +21 -0
- paddlex/inference/common/batch_sampler/audio_batch_sampler.py +83 -0
- paddlex/inference/common/batch_sampler/base_batch_sampler.py +94 -0
- paddlex/inference/common/batch_sampler/det_3d_batch_sampler.py +144 -0
- paddlex/inference/common/batch_sampler/doc_vlm_batch_sampler.py +87 -0
- paddlex/inference/common/batch_sampler/image_batch_sampler.py +121 -0
- paddlex/inference/common/batch_sampler/ts_batch_sampler.py +109 -0
- paddlex/inference/common/batch_sampler/video_batch_sampler.py +74 -0
- paddlex/inference/common/reader/__init__.py +19 -0
- paddlex/inference/common/reader/audio_reader.py +46 -0
- paddlex/inference/common/reader/det_3d_reader.py +241 -0
- paddlex/inference/common/reader/image_reader.py +73 -0
- paddlex/inference/common/reader/ts_reader.py +46 -0
- paddlex/inference/common/reader/video_reader.py +42 -0
- paddlex/inference/common/result/__init__.py +29 -0
- paddlex/inference/common/result/base_cv_result.py +41 -0
- paddlex/inference/common/result/base_result.py +72 -0
- paddlex/inference/common/result/base_ts_result.py +41 -0
- paddlex/inference/common/result/base_video_result.py +36 -0
- paddlex/inference/common/result/mixin.py +709 -0
- paddlex/inference/models/__init__.py +86 -0
- paddlex/inference/models/anomaly_detection/__init__.py +15 -0
- paddlex/inference/models/anomaly_detection/predictor.py +135 -0
- paddlex/inference/models/anomaly_detection/processors.py +53 -0
- paddlex/inference/models/anomaly_detection/result.py +71 -0
- paddlex/inference/models/base/__init__.py +15 -0
- paddlex/inference/models/base/predictor/__init__.py +15 -0
- paddlex/inference/models/base/predictor/base_predictor.py +414 -0
- paddlex/inference/models/common/__init__.py +26 -0
- paddlex/inference/models/common/static_infer.py +801 -0
- paddlex/inference/models/common/tokenizer/__init__.py +21 -0
- paddlex/inference/models/common/tokenizer/bert_tokenizer.py +655 -0
- paddlex/inference/models/common/tokenizer/clip_tokenizer.py +609 -0
- paddlex/inference/models/common/tokenizer/gpt_tokenizer.py +453 -0
- paddlex/inference/models/common/tokenizer/qwen2_5_tokenizer.py +112 -0
- paddlex/inference/models/common/tokenizer/qwen2_tokenizer.py +438 -0
- paddlex/inference/models/common/tokenizer/qwen_tokenizer.py +288 -0
- paddlex/inference/models/common/tokenizer/tokenizer_utils.py +2149 -0
- paddlex/inference/models/common/tokenizer/tokenizer_utils_base.py +3720 -0
- paddlex/inference/models/common/tokenizer/utils.py +66 -0
- paddlex/inference/models/common/tokenizer/vocab.py +647 -0
- paddlex/inference/models/common/ts/__init__.py +15 -0
- paddlex/inference/models/common/ts/funcs.py +540 -0
- paddlex/inference/models/common/ts/processors.py +322 -0
- paddlex/inference/models/common/vision/__init__.py +23 -0
- paddlex/inference/models/common/vision/funcs.py +98 -0
- paddlex/inference/models/common/vision/processors.py +285 -0
- paddlex/inference/models/common/vlm/__init__.py +13 -0
- paddlex/inference/models/common/vlm/activations.py +189 -0
- paddlex/inference/models/common/vlm/bert_padding.py +127 -0
- paddlex/inference/models/common/vlm/conversion_utils.py +99 -0
- paddlex/inference/models/common/vlm/distributed.py +229 -0
- paddlex/inference/models/common/vlm/flash_attn_utils.py +119 -0
- paddlex/inference/models/common/vlm/fusion_ops.py +205 -0
- paddlex/inference/models/common/vlm/generation/__init__.py +34 -0
- paddlex/inference/models/common/vlm/generation/configuration_utils.py +533 -0
- paddlex/inference/models/common/vlm/generation/logits_process.py +730 -0
- paddlex/inference/models/common/vlm/generation/stopping_criteria.py +106 -0
- paddlex/inference/models/common/vlm/generation/utils.py +2162 -0
- paddlex/inference/models/common/vlm/transformers/__init__.py +16 -0
- paddlex/inference/models/common/vlm/transformers/configuration_utils.py +1037 -0
- paddlex/inference/models/common/vlm/transformers/conversion_utils.py +408 -0
- paddlex/inference/models/common/vlm/transformers/model_outputs.py +1612 -0
- paddlex/inference/models/common/vlm/transformers/model_utils.py +2014 -0
- paddlex/inference/models/common/vlm/transformers/utils.py +178 -0
- paddlex/inference/models/common/vlm/utils.py +109 -0
- paddlex/inference/models/doc_vlm/__init__.py +15 -0
- paddlex/inference/models/doc_vlm/modeling/GOT_ocr_2_0.py +830 -0
- paddlex/inference/models/doc_vlm/modeling/__init__.py +17 -0
- paddlex/inference/models/doc_vlm/modeling/qwen2.py +1606 -0
- paddlex/inference/models/doc_vlm/modeling/qwen2_5_vl.py +3006 -0
- paddlex/inference/models/doc_vlm/modeling/qwen2_vl.py +2495 -0
- paddlex/inference/models/doc_vlm/predictor.py +253 -0
- paddlex/inference/models/doc_vlm/processors/GOT_ocr_2_0.py +97 -0
- paddlex/inference/models/doc_vlm/processors/__init__.py +17 -0
- paddlex/inference/models/doc_vlm/processors/common.py +561 -0
- paddlex/inference/models/doc_vlm/processors/qwen2_5_vl.py +548 -0
- paddlex/inference/models/doc_vlm/processors/qwen2_vl.py +543 -0
- paddlex/inference/models/doc_vlm/result.py +21 -0
- paddlex/inference/models/face_feature/__init__.py +15 -0
- paddlex/inference/models/face_feature/predictor.py +66 -0
- paddlex/inference/models/formula_recognition/__init__.py +15 -0
- paddlex/inference/models/formula_recognition/predictor.py +193 -0
- paddlex/inference/models/formula_recognition/processors.py +1015 -0
- paddlex/inference/models/formula_recognition/result.py +411 -0
- paddlex/inference/models/image_classification/__init__.py +15 -0
- paddlex/inference/models/image_classification/predictor.py +172 -0
- paddlex/inference/models/image_classification/processors.py +89 -0
- paddlex/inference/models/image_classification/result.py +93 -0
- paddlex/inference/models/image_feature/__init__.py +15 -0
- paddlex/inference/models/image_feature/predictor.py +146 -0
- paddlex/inference/models/image_feature/processors.py +31 -0
- paddlex/inference/models/image_feature/result.py +32 -0
- paddlex/inference/models/image_multilabel_classification/__init__.py +15 -0
- paddlex/inference/models/image_multilabel_classification/predictor.py +95 -0
- paddlex/inference/models/image_multilabel_classification/processors.py +89 -0
- paddlex/inference/models/image_multilabel_classification/result.py +96 -0
- paddlex/inference/models/image_unwarping/__init__.py +15 -0
- paddlex/inference/models/image_unwarping/predictor.py +97 -0
- paddlex/inference/models/image_unwarping/processors.py +92 -0
- paddlex/inference/models/image_unwarping/result.py +47 -0
- paddlex/inference/models/instance_segmentation/__init__.py +15 -0
- paddlex/inference/models/instance_segmentation/predictor.py +202 -0
- paddlex/inference/models/instance_segmentation/processors.py +102 -0
- paddlex/inference/models/instance_segmentation/result.py +162 -0
- paddlex/inference/models/keypoint_detection/__init__.py +15 -0
- paddlex/inference/models/keypoint_detection/predictor.py +190 -0
- paddlex/inference/models/keypoint_detection/processors.py +367 -0
- paddlex/inference/models/keypoint_detection/result.py +197 -0
- paddlex/inference/models/m_3d_bev_detection/__init__.py +15 -0
- paddlex/inference/models/m_3d_bev_detection/predictor.py +303 -0
- paddlex/inference/models/m_3d_bev_detection/processors.py +990 -0
- paddlex/inference/models/m_3d_bev_detection/result.py +68 -0
- paddlex/inference/models/m_3d_bev_detection/visualizer_3d.py +169 -0
- paddlex/inference/models/multilingual_speech_recognition/__init__.py +15 -0
- paddlex/inference/models/multilingual_speech_recognition/predictor.py +137 -0
- paddlex/inference/models/multilingual_speech_recognition/processors.py +1933 -0
- paddlex/inference/models/multilingual_speech_recognition/result.py +21 -0
- paddlex/inference/models/object_detection/__init__.py +15 -0
- paddlex/inference/models/object_detection/predictor.py +344 -0
- paddlex/inference/models/object_detection/processors.py +885 -0
- paddlex/inference/models/object_detection/result.py +114 -0
- paddlex/inference/models/object_detection/utils.py +70 -0
- paddlex/inference/models/open_vocabulary_detection/__init__.py +15 -0
- paddlex/inference/models/open_vocabulary_detection/predictor.py +172 -0
- paddlex/inference/models/open_vocabulary_detection/processors/__init__.py +16 -0
- paddlex/inference/models/open_vocabulary_detection/processors/common.py +114 -0
- paddlex/inference/models/open_vocabulary_detection/processors/groundingdino_processors.py +496 -0
- paddlex/inference/models/open_vocabulary_detection/processors/yoloworld_processors.py +209 -0
- paddlex/inference/models/open_vocabulary_segmentation/__init__.py +15 -0
- paddlex/inference/models/open_vocabulary_segmentation/predictor.py +113 -0
- paddlex/inference/models/open_vocabulary_segmentation/processors/__init__.py +15 -0
- paddlex/inference/models/open_vocabulary_segmentation/processors/sam_processer.py +249 -0
- paddlex/inference/models/open_vocabulary_segmentation/results/__init__.py +15 -0
- paddlex/inference/models/open_vocabulary_segmentation/results/sam_result.py +149 -0
- paddlex/inference/models/semantic_segmentation/__init__.py +15 -0
- paddlex/inference/models/semantic_segmentation/predictor.py +158 -0
- paddlex/inference/models/semantic_segmentation/processors.py +117 -0
- paddlex/inference/models/semantic_segmentation/result.py +73 -0
- paddlex/inference/models/table_structure_recognition/__init__.py +15 -0
- paddlex/inference/models/table_structure_recognition/predictor.py +161 -0
- paddlex/inference/models/table_structure_recognition/processors.py +229 -0
- paddlex/inference/models/table_structure_recognition/result.py +63 -0
- paddlex/inference/models/text_detection/__init__.py +15 -0
- paddlex/inference/models/text_detection/predictor.py +191 -0
- paddlex/inference/models/text_detection/processors.py +538 -0
- paddlex/inference/models/text_detection/result.py +46 -0
- paddlex/inference/models/text_recognition/__init__.py +15 -0
- paddlex/inference/models/text_recognition/predictor.py +98 -0
- paddlex/inference/models/text_recognition/processors.py +245 -0
- paddlex/inference/models/text_recognition/result.py +76 -0
- paddlex/inference/models/ts_anomaly_detection/__init__.py +15 -0
- paddlex/inference/models/ts_anomaly_detection/predictor.py +141 -0
- paddlex/inference/models/ts_anomaly_detection/processors.py +98 -0
- paddlex/inference/models/ts_anomaly_detection/result.py +83 -0
- paddlex/inference/models/ts_classification/__init__.py +15 -0
- paddlex/inference/models/ts_classification/predictor.py +122 -0
- paddlex/inference/models/ts_classification/processors.py +122 -0
- paddlex/inference/models/ts_classification/result.py +87 -0
- paddlex/inference/models/ts_forecasting/__init__.py +15 -0
- paddlex/inference/models/ts_forecasting/predictor.py +154 -0
- paddlex/inference/models/ts_forecasting/processors.py +158 -0
- paddlex/inference/models/ts_forecasting/result.py +96 -0
- paddlex/inference/models/video_classification/__init__.py +15 -0
- paddlex/inference/models/video_classification/predictor.py +141 -0
- paddlex/inference/models/video_classification/processors.py +409 -0
- paddlex/inference/models/video_classification/result.py +96 -0
- paddlex/inference/models/video_detection/__init__.py +15 -0
- paddlex/inference/models/video_detection/predictor.py +129 -0
- paddlex/inference/models/video_detection/processors.py +463 -0
- paddlex/inference/models/video_detection/result.py +109 -0
- paddlex/inference/pipelines/__init__.py +239 -0
- paddlex/inference/pipelines/_parallel.py +172 -0
- paddlex/inference/pipelines/anomaly_detection/__init__.py +15 -0
- paddlex/inference/pipelines/anomaly_detection/pipeline.py +82 -0
- paddlex/inference/pipelines/attribute_recognition/__init__.py +15 -0
- paddlex/inference/pipelines/attribute_recognition/pipeline.py +120 -0
- paddlex/inference/pipelines/attribute_recognition/result.py +102 -0
- paddlex/inference/pipelines/base.py +156 -0
- paddlex/inference/pipelines/components/__init__.py +29 -0
- paddlex/inference/pipelines/components/chat_server/__init__.py +16 -0
- paddlex/inference/pipelines/components/chat_server/base.py +39 -0
- paddlex/inference/pipelines/components/chat_server/openai_bot_chat.py +236 -0
- paddlex/inference/pipelines/components/common/__init__.py +19 -0
- paddlex/inference/pipelines/components/common/base_operator.py +37 -0
- paddlex/inference/pipelines/components/common/base_result.py +66 -0
- paddlex/inference/pipelines/components/common/convert_points_and_boxes.py +45 -0
- paddlex/inference/pipelines/components/common/crop_image_regions.py +556 -0
- paddlex/inference/pipelines/components/common/seal_det_warp.py +972 -0
- paddlex/inference/pipelines/components/common/sort_boxes.py +85 -0
- paddlex/inference/pipelines/components/common/warp_image.py +50 -0
- paddlex/inference/pipelines/components/faisser.py +357 -0
- paddlex/inference/pipelines/components/prompt_engineering/__init__.py +16 -0
- paddlex/inference/pipelines/components/prompt_engineering/base.py +35 -0
- paddlex/inference/pipelines/components/prompt_engineering/generate_ensemble_prompt.py +128 -0
- paddlex/inference/pipelines/components/prompt_engineering/generate_kie_prompt.py +148 -0
- paddlex/inference/pipelines/components/retriever/__init__.py +16 -0
- paddlex/inference/pipelines/components/retriever/base.py +228 -0
- paddlex/inference/pipelines/components/retriever/openai_bot_retriever.py +70 -0
- paddlex/inference/pipelines/components/retriever/qianfan_bot_retriever.py +166 -0
- paddlex/inference/pipelines/components/utils/__init__.py +13 -0
- paddlex/inference/pipelines/components/utils/mixin.py +206 -0
- paddlex/inference/pipelines/doc_preprocessor/__init__.py +15 -0
- paddlex/inference/pipelines/doc_preprocessor/pipeline.py +209 -0
- paddlex/inference/pipelines/doc_preprocessor/result.py +98 -0
- paddlex/inference/pipelines/doc_understanding/__init__.py +15 -0
- paddlex/inference/pipelines/doc_understanding/pipeline.py +71 -0
- paddlex/inference/pipelines/face_recognition/__init__.py +15 -0
- paddlex/inference/pipelines/face_recognition/pipeline.py +63 -0
- paddlex/inference/pipelines/face_recognition/result.py +44 -0
- paddlex/inference/pipelines/formula_recognition/__init__.py +15 -0
- paddlex/inference/pipelines/formula_recognition/pipeline.py +347 -0
- paddlex/inference/pipelines/formula_recognition/result.py +282 -0
- paddlex/inference/pipelines/image_classification/__init__.py +15 -0
- paddlex/inference/pipelines/image_classification/pipeline.py +90 -0
- paddlex/inference/pipelines/image_multilabel_classification/__init__.py +15 -0
- paddlex/inference/pipelines/image_multilabel_classification/pipeline.py +97 -0
- paddlex/inference/pipelines/instance_segmentation/__init__.py +15 -0
- paddlex/inference/pipelines/instance_segmentation/pipeline.py +91 -0
- paddlex/inference/pipelines/keypoint_detection/__init__.py +15 -0
- paddlex/inference/pipelines/keypoint_detection/pipeline.py +158 -0
- paddlex/inference/pipelines/layout_parsing/__init__.py +16 -0
- paddlex/inference/pipelines/layout_parsing/pipeline.py +568 -0
- paddlex/inference/pipelines/layout_parsing/pipeline_v2.py +1382 -0
- paddlex/inference/pipelines/layout_parsing/result.py +191 -0
- paddlex/inference/pipelines/layout_parsing/result_v2.py +745 -0
- paddlex/inference/pipelines/layout_parsing/setting.py +87 -0
- paddlex/inference/pipelines/layout_parsing/utils.py +951 -0
- paddlex/inference/pipelines/layout_parsing/xycut_enhanced/__init__.py +16 -0
- paddlex/inference/pipelines/layout_parsing/xycut_enhanced/utils.py +1143 -0
- paddlex/inference/pipelines/layout_parsing/xycut_enhanced/xycuts.py +562 -0
- paddlex/inference/pipelines/m_3d_bev_detection/__init__.py +15 -0
- paddlex/inference/pipelines/m_3d_bev_detection/pipeline.py +74 -0
- paddlex/inference/pipelines/multilingual_speech_recognition/__init__.py +15 -0
- paddlex/inference/pipelines/multilingual_speech_recognition/pipeline.py +78 -0
- paddlex/inference/pipelines/object_detection/__init__.py +15 -0
- paddlex/inference/pipelines/object_detection/pipeline.py +115 -0
- paddlex/inference/pipelines/ocr/__init__.py +15 -0
- paddlex/inference/pipelines/ocr/pipeline.py +463 -0
- paddlex/inference/pipelines/ocr/result.py +255 -0
- paddlex/inference/pipelines/open_vocabulary_detection/__init__.py +15 -0
- paddlex/inference/pipelines/open_vocabulary_detection/pipeline.py +86 -0
- paddlex/inference/pipelines/open_vocabulary_segmentation/__init__.py +15 -0
- paddlex/inference/pipelines/open_vocabulary_segmentation/pipeline.py +100 -0
- paddlex/inference/pipelines/pp_chatocr/__init__.py +16 -0
- paddlex/inference/pipelines/pp_chatocr/pipeline_base.py +111 -0
- paddlex/inference/pipelines/pp_chatocr/pipeline_v3.py +781 -0
- paddlex/inference/pipelines/pp_chatocr/pipeline_v4.py +992 -0
- paddlex/inference/pipelines/pp_shitu_v2/__init__.py +15 -0
- paddlex/inference/pipelines/pp_shitu_v2/pipeline.py +156 -0
- paddlex/inference/pipelines/pp_shitu_v2/result.py +126 -0
- paddlex/inference/pipelines/rotated_object_detection/__init__.py +15 -0
- paddlex/inference/pipelines/rotated_object_detection/pipeline.py +95 -0
- paddlex/inference/pipelines/seal_recognition/__init__.py +15 -0
- paddlex/inference/pipelines/seal_recognition/pipeline.py +335 -0
- paddlex/inference/pipelines/seal_recognition/result.py +89 -0
- paddlex/inference/pipelines/semantic_segmentation/__init__.py +15 -0
- paddlex/inference/pipelines/semantic_segmentation/pipeline.py +95 -0
- paddlex/inference/pipelines/small_object_detection/__init__.py +15 -0
- paddlex/inference/pipelines/small_object_detection/pipeline.py +95 -0
- paddlex/inference/pipelines/table_recognition/__init__.py +16 -0
- paddlex/inference/pipelines/table_recognition/pipeline.py +486 -0
- paddlex/inference/pipelines/table_recognition/pipeline_v2.py +1395 -0
- paddlex/inference/pipelines/table_recognition/result.py +218 -0
- paddlex/inference/pipelines/table_recognition/table_recognition_post_processing.py +366 -0
- paddlex/inference/pipelines/table_recognition/table_recognition_post_processing_v2.py +488 -0
- paddlex/inference/pipelines/table_recognition/utils.py +44 -0
- paddlex/inference/pipelines/ts_anomaly_detection/__init__.py +15 -0
- paddlex/inference/pipelines/ts_anomaly_detection/pipeline.py +72 -0
- paddlex/inference/pipelines/ts_classification/__init__.py +15 -0
- paddlex/inference/pipelines/ts_classification/pipeline.py +72 -0
- paddlex/inference/pipelines/ts_forecasting/__init__.py +15 -0
- paddlex/inference/pipelines/ts_forecasting/pipeline.py +72 -0
- paddlex/inference/pipelines/video_classification/__init__.py +15 -0
- paddlex/inference/pipelines/video_classification/pipeline.py +79 -0
- paddlex/inference/pipelines/video_detection/__init__.py +15 -0
- paddlex/inference/pipelines/video_detection/pipeline.py +86 -0
- paddlex/inference/serving/__init__.py +17 -0
- paddlex/inference/serving/basic_serving/__init__.py +18 -0
- paddlex/inference/serving/basic_serving/_app.py +221 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/__init__.py +44 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/_common/__init__.py +13 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/_common/common.py +104 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/_common/image_recognition.py +36 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/_common/ocr.py +95 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/anomaly_detection.py +67 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/doc_preprocessor.py +100 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/doc_understanding.py +153 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/face_recognition.py +226 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/formula_recognition.py +100 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/human_keypoint_detection.py +81 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/image_classification.py +69 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/image_multilabel_classification.py +73 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/instance_segmentation.py +87 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/layout_parsing.py +117 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/m_3d_bev_detection.py +79 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/multilingual_speech_recognition.py +92 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/object_detection.py +77 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/ocr.py +102 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/open_vocabulary_detection.py +81 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/open_vocabulary_segmentation.py +91 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/pedestrian_attribute_recognition.py +84 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/pp_chatocrv3_doc.py +193 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/pp_chatocrv4_doc.py +223 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/pp_shituv2.py +221 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/pp_structurev3.py +143 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/rotated_object_detection.py +81 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/seal_recognition.py +106 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/semantic_segmentation.py +67 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/small_object_detection.py +72 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/table_recognition.py +108 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/table_recognition_v2.py +113 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/ts_anomaly_detection.py +65 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/ts_classification.py +64 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/ts_forecast.py +65 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/vehicle_attribute_recognition.py +84 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/video_classification.py +76 -0
- paddlex/inference/serving/basic_serving/_pipeline_apps/video_detection.py +92 -0
- paddlex/inference/serving/basic_serving/_server.py +40 -0
- paddlex/inference/serving/infra/__init__.py +13 -0
- paddlex/inference/serving/infra/config.py +36 -0
- paddlex/inference/serving/infra/models.py +79 -0
- paddlex/inference/serving/infra/storage.py +180 -0
- paddlex/inference/serving/infra/utils.py +285 -0
- paddlex/inference/serving/schemas/__init__.py +13 -0
- paddlex/inference/serving/schemas/anomaly_detection.py +39 -0
- paddlex/inference/serving/schemas/doc_preprocessor.py +54 -0
- paddlex/inference/serving/schemas/doc_understanding.py +78 -0
- paddlex/inference/serving/schemas/face_recognition.py +124 -0
- paddlex/inference/serving/schemas/formula_recognition.py +56 -0
- paddlex/inference/serving/schemas/human_keypoint_detection.py +55 -0
- paddlex/inference/serving/schemas/image_classification.py +45 -0
- paddlex/inference/serving/schemas/image_multilabel_classification.py +47 -0
- paddlex/inference/serving/schemas/instance_segmentation.py +53 -0
- paddlex/inference/serving/schemas/layout_parsing.py +71 -0
- paddlex/inference/serving/schemas/m_3d_bev_detection.py +48 -0
- paddlex/inference/serving/schemas/multilingual_speech_recognition.py +57 -0
- paddlex/inference/serving/schemas/object_detection.py +52 -0
- paddlex/inference/serving/schemas/ocr.py +60 -0
- paddlex/inference/serving/schemas/open_vocabulary_detection.py +52 -0
- paddlex/inference/serving/schemas/open_vocabulary_segmentation.py +52 -0
- paddlex/inference/serving/schemas/pedestrian_attribute_recognition.py +61 -0
- paddlex/inference/serving/schemas/pp_chatocrv3_doc.py +133 -0
- paddlex/inference/serving/schemas/pp_chatocrv4_doc.py +150 -0
- paddlex/inference/serving/schemas/pp_shituv2.py +124 -0
- paddlex/inference/serving/schemas/pp_structurev3.py +88 -0
- paddlex/inference/serving/schemas/rotated_object_detection.py +52 -0
- paddlex/inference/serving/schemas/seal_recognition.py +62 -0
- paddlex/inference/serving/schemas/semantic_segmentation.py +45 -0
- paddlex/inference/serving/schemas/shared/__init__.py +13 -0
- paddlex/inference/serving/schemas/shared/classification.py +23 -0
- paddlex/inference/serving/schemas/shared/image_segmentation.py +28 -0
- paddlex/inference/serving/schemas/shared/object_detection.py +24 -0
- paddlex/inference/serving/schemas/shared/ocr.py +25 -0
- paddlex/inference/serving/schemas/small_object_detection.py +52 -0
- paddlex/inference/serving/schemas/table_recognition.py +64 -0
- paddlex/inference/serving/schemas/table_recognition_v2.py +69 -0
- paddlex/inference/serving/schemas/ts_anomaly_detection.py +37 -0
- paddlex/inference/serving/schemas/ts_classification.py +38 -0
- paddlex/inference/serving/schemas/ts_forecast.py +37 -0
- paddlex/inference/serving/schemas/vehicle_attribute_recognition.py +61 -0
- paddlex/inference/serving/schemas/video_classification.py +44 -0
- paddlex/inference/serving/schemas/video_detection.py +56 -0
- paddlex/inference/utils/__init__.py +13 -0
- paddlex/inference/utils/benchmark.py +379 -0
- paddlex/inference/utils/color_map.py +123 -0
- paddlex/inference/utils/get_pipeline_path.py +27 -0
- paddlex/inference/utils/hpi.py +254 -0
- paddlex/inference/utils/hpi_model_info_collection.json +2331 -0
- paddlex/inference/utils/io/__init__.py +36 -0
- paddlex/inference/utils/io/readers.py +504 -0
- paddlex/inference/utils/io/style.py +381 -0
- paddlex/inference/utils/io/tablepyxl.py +157 -0
- paddlex/inference/utils/io/writers.py +458 -0
- paddlex/inference/utils/model_paths.py +48 -0
- paddlex/inference/utils/new_ir_blocklist.py +27 -0
- paddlex/inference/utils/official_models.py +367 -0
- paddlex/inference/utils/pp_option.py +339 -0
- paddlex/inference/utils/trt_blocklist.py +43 -0
- paddlex/inference/utils/trt_config.py +420 -0
- paddlex/model.py +131 -0
- paddlex/modules/__init__.py +115 -0
- paddlex/modules/anomaly_detection/__init__.py +18 -0
- paddlex/modules/anomaly_detection/dataset_checker/__init__.py +94 -0
- paddlex/modules/anomaly_detection/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/anomaly_detection/dataset_checker/dataset_src/analyse_dataset.py +82 -0
- paddlex/modules/anomaly_detection/dataset_checker/dataset_src/check_dataset.py +91 -0
- paddlex/modules/anomaly_detection/dataset_checker/dataset_src/convert_dataset.py +233 -0
- paddlex/modules/anomaly_detection/dataset_checker/dataset_src/split_dataset.py +87 -0
- paddlex/modules/anomaly_detection/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/anomaly_detection/dataset_checker/dataset_src/utils/visualizer.py +76 -0
- paddlex/modules/anomaly_detection/evaluator.py +58 -0
- paddlex/modules/anomaly_detection/exportor.py +22 -0
- paddlex/modules/anomaly_detection/model_list.py +16 -0
- paddlex/modules/anomaly_detection/trainer.py +70 -0
- paddlex/modules/base/__init__.py +18 -0
- paddlex/modules/base/build_model.py +33 -0
- paddlex/modules/base/dataset_checker/__init__.py +16 -0
- paddlex/modules/base/dataset_checker/dataset_checker.py +169 -0
- paddlex/modules/base/dataset_checker/utils.py +108 -0
- paddlex/modules/base/evaluator.py +170 -0
- paddlex/modules/base/exportor.py +145 -0
- paddlex/modules/base/trainer.py +144 -0
- paddlex/modules/base/utils/__init__.py +13 -0
- paddlex/modules/base/utils/cinn_setting.py +89 -0
- paddlex/modules/base/utils/coco_eval.py +94 -0
- paddlex/modules/base/utils/topk_eval.py +118 -0
- paddlex/modules/doc_vlm/__init__.py +18 -0
- paddlex/modules/doc_vlm/dataset_checker.py +29 -0
- paddlex/modules/doc_vlm/evaluator.py +29 -0
- paddlex/modules/doc_vlm/exportor.py +29 -0
- paddlex/modules/doc_vlm/model_list.py +16 -0
- paddlex/modules/doc_vlm/trainer.py +41 -0
- paddlex/modules/face_recognition/__init__.py +18 -0
- paddlex/modules/face_recognition/dataset_checker/__init__.py +71 -0
- paddlex/modules/face_recognition/dataset_checker/dataset_src/__init__.py +16 -0
- paddlex/modules/face_recognition/dataset_checker/dataset_src/check_dataset.py +172 -0
- paddlex/modules/face_recognition/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/face_recognition/dataset_checker/dataset_src/utils/visualizer.py +153 -0
- paddlex/modules/face_recognition/evaluator.py +52 -0
- paddlex/modules/face_recognition/exportor.py +22 -0
- paddlex/modules/face_recognition/model_list.py +15 -0
- paddlex/modules/face_recognition/trainer.py +75 -0
- paddlex/modules/formula_recognition/__init__.py +18 -0
- paddlex/modules/formula_recognition/dataset_checker/__init__.py +113 -0
- paddlex/modules/formula_recognition/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/formula_recognition/dataset_checker/dataset_src/analyse_dataset.py +158 -0
- paddlex/modules/formula_recognition/dataset_checker/dataset_src/check_dataset.py +76 -0
- paddlex/modules/formula_recognition/dataset_checker/dataset_src/convert_dataset.py +95 -0
- paddlex/modules/formula_recognition/dataset_checker/dataset_src/split_dataset.py +80 -0
- paddlex/modules/formula_recognition/evaluator.py +80 -0
- paddlex/modules/formula_recognition/exportor.py +22 -0
- paddlex/modules/formula_recognition/model_list.py +23 -0
- paddlex/modules/formula_recognition/trainer.py +123 -0
- paddlex/modules/general_recognition/__init__.py +18 -0
- paddlex/modules/general_recognition/dataset_checker/__init__.py +107 -0
- paddlex/modules/general_recognition/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/general_recognition/dataset_checker/dataset_src/analyse_dataset.py +96 -0
- paddlex/modules/general_recognition/dataset_checker/dataset_src/check_dataset.py +99 -0
- paddlex/modules/general_recognition/dataset_checker/dataset_src/convert_dataset.py +100 -0
- paddlex/modules/general_recognition/dataset_checker/dataset_src/split_dataset.py +82 -0
- paddlex/modules/general_recognition/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/general_recognition/dataset_checker/dataset_src/utils/visualizer.py +147 -0
- paddlex/modules/general_recognition/evaluator.py +31 -0
- paddlex/modules/general_recognition/exportor.py +22 -0
- paddlex/modules/general_recognition/model_list.py +19 -0
- paddlex/modules/general_recognition/trainer.py +52 -0
- paddlex/modules/image_classification/__init__.py +18 -0
- paddlex/modules/image_classification/dataset_checker/__init__.py +104 -0
- paddlex/modules/image_classification/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/image_classification/dataset_checker/dataset_src/analyse_dataset.py +92 -0
- paddlex/modules/image_classification/dataset_checker/dataset_src/check_dataset.py +132 -0
- paddlex/modules/image_classification/dataset_checker/dataset_src/convert_dataset.py +51 -0
- paddlex/modules/image_classification/dataset_checker/dataset_src/split_dataset.py +81 -0
- paddlex/modules/image_classification/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/image_classification/dataset_checker/dataset_src/utils/visualizer.py +153 -0
- paddlex/modules/image_classification/evaluator.py +43 -0
- paddlex/modules/image_classification/exportor.py +22 -0
- paddlex/modules/image_classification/model_list.py +99 -0
- paddlex/modules/image_classification/trainer.py +82 -0
- paddlex/modules/image_unwarping/__init__.py +13 -0
- paddlex/modules/image_unwarping/model_list.py +17 -0
- paddlex/modules/instance_segmentation/__init__.py +18 -0
- paddlex/modules/instance_segmentation/dataset_checker/__init__.py +107 -0
- paddlex/modules/instance_segmentation/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/instance_segmentation/dataset_checker/dataset_src/analyse_dataset.py +82 -0
- paddlex/modules/instance_segmentation/dataset_checker/dataset_src/check_dataset.py +95 -0
- paddlex/modules/instance_segmentation/dataset_checker/dataset_src/convert_dataset.py +241 -0
- paddlex/modules/instance_segmentation/dataset_checker/dataset_src/split_dataset.py +122 -0
- paddlex/modules/instance_segmentation/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/instance_segmentation/dataset_checker/dataset_src/utils/visualizer.py +223 -0
- paddlex/modules/instance_segmentation/evaluator.py +32 -0
- paddlex/modules/instance_segmentation/exportor.py +22 -0
- paddlex/modules/instance_segmentation/model_list.py +33 -0
- paddlex/modules/instance_segmentation/trainer.py +31 -0
- paddlex/modules/keypoint_detection/__init__.py +18 -0
- paddlex/modules/keypoint_detection/dataset_checker/__init__.py +56 -0
- paddlex/modules/keypoint_detection/dataset_checker/dataset_src/__init__.py +15 -0
- paddlex/modules/keypoint_detection/dataset_checker/dataset_src/check_dataset.py +91 -0
- paddlex/modules/keypoint_detection/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/keypoint_detection/dataset_checker/dataset_src/utils/visualizer.py +124 -0
- paddlex/modules/keypoint_detection/evaluator.py +41 -0
- paddlex/modules/keypoint_detection/exportor.py +22 -0
- paddlex/modules/keypoint_detection/model_list.py +16 -0
- paddlex/modules/keypoint_detection/trainer.py +39 -0
- paddlex/modules/m_3d_bev_detection/__init__.py +18 -0
- paddlex/modules/m_3d_bev_detection/dataset_checker/__init__.py +95 -0
- paddlex/modules/m_3d_bev_detection/dataset_checker/dataset_src/__init__.py +17 -0
- paddlex/modules/m_3d_bev_detection/dataset_checker/dataset_src/analyse_dataset.py +106 -0
- paddlex/modules/m_3d_bev_detection/dataset_checker/dataset_src/check_dataset.py +101 -0
- paddlex/modules/m_3d_bev_detection/evaluator.py +46 -0
- paddlex/modules/m_3d_bev_detection/exportor.py +22 -0
- paddlex/modules/m_3d_bev_detection/model_list.py +18 -0
- paddlex/modules/m_3d_bev_detection/trainer.py +68 -0
- paddlex/modules/multilabel_classification/__init__.py +18 -0
- paddlex/modules/multilabel_classification/dataset_checker/__init__.py +106 -0
- paddlex/modules/multilabel_classification/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/multilabel_classification/dataset_checker/dataset_src/analyse_dataset.py +94 -0
- paddlex/modules/multilabel_classification/dataset_checker/dataset_src/check_dataset.py +132 -0
- paddlex/modules/multilabel_classification/dataset_checker/dataset_src/convert_dataset.py +120 -0
- paddlex/modules/multilabel_classification/dataset_checker/dataset_src/split_dataset.py +81 -0
- paddlex/modules/multilabel_classification/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/multilabel_classification/dataset_checker/dataset_src/utils/visualizer.py +149 -0
- paddlex/modules/multilabel_classification/evaluator.py +43 -0
- paddlex/modules/multilabel_classification/exportor.py +22 -0
- paddlex/modules/multilabel_classification/model_list.py +24 -0
- paddlex/modules/multilabel_classification/trainer.py +85 -0
- paddlex/modules/multilingual_speech_recognition/__init__.py +18 -0
- paddlex/modules/multilingual_speech_recognition/dataset_checker.py +27 -0
- paddlex/modules/multilingual_speech_recognition/evaluator.py +27 -0
- paddlex/modules/multilingual_speech_recognition/exportor.py +27 -0
- paddlex/modules/multilingual_speech_recognition/model_list.py +22 -0
- paddlex/modules/multilingual_speech_recognition/trainer.py +42 -0
- paddlex/modules/object_detection/__init__.py +18 -0
- paddlex/modules/object_detection/dataset_checker/__init__.py +106 -0
- paddlex/modules/object_detection/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/object_detection/dataset_checker/dataset_src/analyse_dataset.py +82 -0
- paddlex/modules/object_detection/dataset_checker/dataset_src/check_dataset.py +91 -0
- paddlex/modules/object_detection/dataset_checker/dataset_src/convert_dataset.py +438 -0
- paddlex/modules/object_detection/dataset_checker/dataset_src/split_dataset.py +123 -0
- paddlex/modules/object_detection/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/object_detection/dataset_checker/dataset_src/utils/visualizer.py +193 -0
- paddlex/modules/object_detection/evaluator.py +57 -0
- paddlex/modules/object_detection/exportor.py +22 -0
- paddlex/modules/object_detection/model_list.py +86 -0
- paddlex/modules/object_detection/trainer.py +98 -0
- paddlex/modules/open_vocabulary_detection/__init__.py +18 -0
- paddlex/modules/open_vocabulary_detection/dataset_checker.py +29 -0
- paddlex/modules/open_vocabulary_detection/evaluator.py +29 -0
- paddlex/modules/open_vocabulary_detection/exportor.py +29 -0
- paddlex/modules/open_vocabulary_detection/model_list.py +16 -0
- paddlex/modules/open_vocabulary_detection/trainer.py +44 -0
- paddlex/modules/open_vocabulary_segmentation/__init__.py +18 -0
- paddlex/modules/open_vocabulary_segmentation/dataset_checker.py +29 -0
- paddlex/modules/open_vocabulary_segmentation/evaluator.py +29 -0
- paddlex/modules/open_vocabulary_segmentation/exportor.py +29 -0
- paddlex/modules/open_vocabulary_segmentation/model_list.py +19 -0
- paddlex/modules/open_vocabulary_segmentation/trainer.py +44 -0
- paddlex/modules/semantic_segmentation/__init__.py +18 -0
- paddlex/modules/semantic_segmentation/dataset_checker/__init__.py +109 -0
- paddlex/modules/semantic_segmentation/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/semantic_segmentation/dataset_checker/dataset_src/analyse_dataset.py +76 -0
- paddlex/modules/semantic_segmentation/dataset_checker/dataset_src/check_dataset.py +80 -0
- paddlex/modules/semantic_segmentation/dataset_checker/dataset_src/convert_dataset.py +165 -0
- paddlex/modules/semantic_segmentation/dataset_checker/dataset_src/split_dataset.py +87 -0
- paddlex/modules/semantic_segmentation/dataset_checker/dataset_src/utils/__init__.py +13 -0
- paddlex/modules/semantic_segmentation/dataset_checker/dataset_src/utils/visualizer.py +75 -0
- paddlex/modules/semantic_segmentation/evaluator.py +58 -0
- paddlex/modules/semantic_segmentation/exportor.py +31 -0
- paddlex/modules/semantic_segmentation/model_list.py +37 -0
- paddlex/modules/semantic_segmentation/trainer.py +72 -0
- paddlex/modules/table_recognition/__init__.py +18 -0
- paddlex/modules/table_recognition/dataset_checker/__init__.py +98 -0
- paddlex/modules/table_recognition/dataset_checker/dataset_src/__init__.py +18 -0
- paddlex/modules/table_recognition/dataset_checker/dataset_src/analyse_dataset.py +59 -0
- paddlex/modules/table_recognition/dataset_checker/dataset_src/check_dataset.py +87 -0
- paddlex/modules/table_recognition/dataset_checker/dataset_src/split_dataset.py +80 -0
- paddlex/modules/table_recognition/evaluator.py +43 -0
- paddlex/modules/table_recognition/exportor.py +22 -0
- paddlex/modules/table_recognition/model_list.py +21 -0
- paddlex/modules/table_recognition/trainer.py +67 -0
- paddlex/modules/text_detection/__init__.py +18 -0
- paddlex/modules/text_detection/dataset_checker/__init__.py +107 -0
- paddlex/modules/text_detection/dataset_checker/dataset_src/__init__.py +18 -0
- paddlex/modules/text_detection/dataset_checker/dataset_src/analyse_dataset.py +220 -0
- paddlex/modules/text_detection/dataset_checker/dataset_src/check_dataset.py +106 -0
- paddlex/modules/text_detection/dataset_checker/dataset_src/split_dataset.py +140 -0
- paddlex/modules/text_detection/evaluator.py +41 -0
- paddlex/modules/text_detection/exportor.py +22 -0
- paddlex/modules/text_detection/model_list.py +26 -0
- paddlex/modules/text_detection/trainer.py +65 -0
- paddlex/modules/text_recognition/__init__.py +18 -0
- paddlex/modules/text_recognition/dataset_checker/__init__.py +125 -0
- paddlex/modules/text_recognition/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/text_recognition/dataset_checker/dataset_src/analyse_dataset.py +162 -0
- paddlex/modules/text_recognition/dataset_checker/dataset_src/check_dataset.py +104 -0
- paddlex/modules/text_recognition/dataset_checker/dataset_src/convert_dataset.py +95 -0
- paddlex/modules/text_recognition/dataset_checker/dataset_src/split_dataset.py +80 -0
- paddlex/modules/text_recognition/evaluator.py +64 -0
- paddlex/modules/text_recognition/exportor.py +22 -0
- paddlex/modules/text_recognition/model_list.py +36 -0
- paddlex/modules/text_recognition/trainer.py +105 -0
- paddlex/modules/ts_anomaly_detection/__init__.py +19 -0
- paddlex/modules/ts_anomaly_detection/dataset_checker/__init__.py +111 -0
- paddlex/modules/ts_anomaly_detection/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/ts_anomaly_detection/dataset_checker/dataset_src/analyse_dataset.py +19 -0
- paddlex/modules/ts_anomaly_detection/dataset_checker/dataset_src/check_dataset.py +64 -0
- paddlex/modules/ts_anomaly_detection/dataset_checker/dataset_src/convert_dataset.py +74 -0
- paddlex/modules/ts_anomaly_detection/dataset_checker/dataset_src/split_dataset.py +63 -0
- paddlex/modules/ts_anomaly_detection/evaluator.py +67 -0
- paddlex/modules/ts_anomaly_detection/exportor.py +44 -0
- paddlex/modules/ts_anomaly_detection/model_list.py +22 -0
- paddlex/modules/ts_anomaly_detection/trainer.py +113 -0
- paddlex/modules/ts_classification/__init__.py +19 -0
- paddlex/modules/ts_classification/dataset_checker/__init__.py +111 -0
- paddlex/modules/ts_classification/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/ts_classification/dataset_checker/dataset_src/analyse_dataset.py +77 -0
- paddlex/modules/ts_classification/dataset_checker/dataset_src/check_dataset.py +64 -0
- paddlex/modules/ts_classification/dataset_checker/dataset_src/convert_dataset.py +74 -0
- paddlex/modules/ts_classification/dataset_checker/dataset_src/split_dataset.py +88 -0
- paddlex/modules/ts_classification/evaluator.py +66 -0
- paddlex/modules/ts_classification/exportor.py +44 -0
- paddlex/modules/ts_classification/model_list.py +18 -0
- paddlex/modules/ts_classification/trainer.py +108 -0
- paddlex/modules/ts_forecast/__init__.py +19 -0
- paddlex/modules/ts_forecast/dataset_checker/__init__.py +111 -0
- paddlex/modules/ts_forecast/dataset_checker/dataset_src/__init__.py +19 -0
- paddlex/modules/ts_forecast/dataset_checker/dataset_src/analyse_dataset.py +19 -0
- paddlex/modules/ts_forecast/dataset_checker/dataset_src/check_dataset.py +64 -0
- paddlex/modules/ts_forecast/dataset_checker/dataset_src/convert_dataset.py +73 -0
- paddlex/modules/ts_forecast/dataset_checker/dataset_src/split_dataset.py +63 -0
- paddlex/modules/ts_forecast/evaluator.py +66 -0
- paddlex/modules/ts_forecast/exportor.py +44 -0
- paddlex/modules/ts_forecast/model_list.py +24 -0
- paddlex/modules/ts_forecast/trainer.py +108 -0
- paddlex/modules/video_classification/__init__.py +18 -0
- paddlex/modules/video_classification/dataset_checker/__init__.py +93 -0
- paddlex/modules/video_classification/dataset_checker/dataset_src/__init__.py +18 -0
- paddlex/modules/video_classification/dataset_checker/dataset_src/analyse_dataset.py +93 -0
- paddlex/modules/video_classification/dataset_checker/dataset_src/check_dataset.py +120 -0
- paddlex/modules/video_classification/dataset_checker/dataset_src/split_dataset.py +82 -0
- paddlex/modules/video_classification/evaluator.py +44 -0
- paddlex/modules/video_classification/exportor.py +22 -0
- paddlex/modules/video_classification/model_list.py +19 -0
- paddlex/modules/video_classification/trainer.py +88 -0
- paddlex/modules/video_detection/__init__.py +18 -0
- paddlex/modules/video_detection/dataset_checker/__init__.py +86 -0
- paddlex/modules/video_detection/dataset_checker/dataset_src/__init__.py +17 -0
- paddlex/modules/video_detection/dataset_checker/dataset_src/analyse_dataset.py +100 -0
- paddlex/modules/video_detection/dataset_checker/dataset_src/check_dataset.py +132 -0
- paddlex/modules/video_detection/evaluator.py +42 -0
- paddlex/modules/video_detection/exportor.py +22 -0
- paddlex/modules/video_detection/model_list.py +15 -0
- paddlex/modules/video_detection/trainer.py +82 -0
- paddlex/ops/__init__.py +152 -0
- paddlex/ops/iou3d_nms/iou3d_cpu.cpp +266 -0
- paddlex/ops/iou3d_nms/iou3d_cpu.h +28 -0
- paddlex/ops/iou3d_nms/iou3d_nms.cpp +206 -0
- paddlex/ops/iou3d_nms/iou3d_nms.h +35 -0
- paddlex/ops/iou3d_nms/iou3d_nms_api.cpp +114 -0
- paddlex/ops/iou3d_nms/iou3d_nms_kernel.cu +484 -0
- paddlex/ops/setup.py +37 -0
- paddlex/ops/voxel/voxelize_op.cc +194 -0
- paddlex/ops/voxel/voxelize_op.cu +346 -0
- paddlex/paddlex_cli.py +476 -0
- paddlex/repo_apis/Paddle3D_api/__init__.py +17 -0
- paddlex/repo_apis/Paddle3D_api/bev_fusion/__init__.py +18 -0
- paddlex/repo_apis/Paddle3D_api/bev_fusion/config.py +118 -0
- paddlex/repo_apis/Paddle3D_api/bev_fusion/model.py +238 -0
- paddlex/repo_apis/Paddle3D_api/bev_fusion/register.py +55 -0
- paddlex/repo_apis/Paddle3D_api/bev_fusion/runner.py +104 -0
- paddlex/repo_apis/Paddle3D_api/pp3d_config.py +145 -0
- paddlex/repo_apis/PaddleClas_api/__init__.py +17 -0
- paddlex/repo_apis/PaddleClas_api/cls/__init__.py +19 -0
- paddlex/repo_apis/PaddleClas_api/cls/config.py +595 -0
- paddlex/repo_apis/PaddleClas_api/cls/model.py +355 -0
- paddlex/repo_apis/PaddleClas_api/cls/register.py +907 -0
- paddlex/repo_apis/PaddleClas_api/cls/runner.py +218 -0
- paddlex/repo_apis/PaddleClas_api/shitu_rec/__init__.py +18 -0
- paddlex/repo_apis/PaddleClas_api/shitu_rec/config.py +141 -0
- paddlex/repo_apis/PaddleClas_api/shitu_rec/model.py +20 -0
- paddlex/repo_apis/PaddleClas_api/shitu_rec/register.py +68 -0
- paddlex/repo_apis/PaddleClas_api/shitu_rec/runner.py +50 -0
- paddlex/repo_apis/PaddleDetection_api/__init__.py +17 -0
- paddlex/repo_apis/PaddleDetection_api/config_helper.py +280 -0
- paddlex/repo_apis/PaddleDetection_api/instance_seg/__init__.py +18 -0
- paddlex/repo_apis/PaddleDetection_api/instance_seg/config.py +457 -0
- paddlex/repo_apis/PaddleDetection_api/instance_seg/model.py +403 -0
- paddlex/repo_apis/PaddleDetection_api/instance_seg/register.py +262 -0
- paddlex/repo_apis/PaddleDetection_api/instance_seg/runner.py +225 -0
- paddlex/repo_apis/PaddleDetection_api/object_det/__init__.py +19 -0
- paddlex/repo_apis/PaddleDetection_api/object_det/config.py +540 -0
- paddlex/repo_apis/PaddleDetection_api/object_det/model.py +429 -0
- paddlex/repo_apis/PaddleDetection_api/object_det/official_categories.py +245 -0
- paddlex/repo_apis/PaddleDetection_api/object_det/register.py +1135 -0
- paddlex/repo_apis/PaddleDetection_api/object_det/runner.py +225 -0
- paddlex/repo_apis/PaddleNLP_api/__init__.py +13 -0
- paddlex/repo_apis/PaddleOCR_api/__init__.py +22 -0
- paddlex/repo_apis/PaddleOCR_api/config_utils.py +53 -0
- paddlex/repo_apis/PaddleOCR_api/formula_rec/__init__.py +16 -0
- paddlex/repo_apis/PaddleOCR_api/formula_rec/config.py +571 -0
- paddlex/repo_apis/PaddleOCR_api/formula_rec/model.py +398 -0
- paddlex/repo_apis/PaddleOCR_api/formula_rec/register.py +99 -0
- paddlex/repo_apis/PaddleOCR_api/formula_rec/runner.py +239 -0
- paddlex/repo_apis/PaddleOCR_api/table_rec/__init__.py +16 -0
- paddlex/repo_apis/PaddleOCR_api/table_rec/config.py +64 -0
- paddlex/repo_apis/PaddleOCR_api/table_rec/model.py +126 -0
- paddlex/repo_apis/PaddleOCR_api/table_rec/register.py +70 -0
- paddlex/repo_apis/PaddleOCR_api/table_rec/runner.py +51 -0
- paddlex/repo_apis/PaddleOCR_api/text_det/__init__.py +16 -0
- paddlex/repo_apis/PaddleOCR_api/text_det/config.py +62 -0
- paddlex/repo_apis/PaddleOCR_api/text_det/model.py +72 -0
- paddlex/repo_apis/PaddleOCR_api/text_det/register.py +107 -0
- paddlex/repo_apis/PaddleOCR_api/text_det/runner.py +53 -0
- paddlex/repo_apis/PaddleOCR_api/text_rec/__init__.py +16 -0
- paddlex/repo_apis/PaddleOCR_api/text_rec/config.py +564 -0
- paddlex/repo_apis/PaddleOCR_api/text_rec/model.py +398 -0
- paddlex/repo_apis/PaddleOCR_api/text_rec/register.py +216 -0
- paddlex/repo_apis/PaddleOCR_api/text_rec/runner.py +239 -0
- paddlex/repo_apis/PaddleSeg_api/__init__.py +16 -0
- paddlex/repo_apis/PaddleSeg_api/base_seg_config.py +134 -0
- paddlex/repo_apis/PaddleSeg_api/seg/__init__.py +16 -0
- paddlex/repo_apis/PaddleSeg_api/seg/config.py +183 -0
- paddlex/repo_apis/PaddleSeg_api/seg/model.py +491 -0
- paddlex/repo_apis/PaddleSeg_api/seg/register.py +272 -0
- paddlex/repo_apis/PaddleSeg_api/seg/runner.py +261 -0
- paddlex/repo_apis/PaddleTS_api/__init__.py +20 -0
- paddlex/repo_apis/PaddleTS_api/ts_ad/__init__.py +16 -0
- paddlex/repo_apis/PaddleTS_api/ts_ad/config.py +88 -0
- paddlex/repo_apis/PaddleTS_api/ts_ad/register.py +146 -0
- paddlex/repo_apis/PaddleTS_api/ts_ad/runner.py +158 -0
- paddlex/repo_apis/PaddleTS_api/ts_base/__init__.py +13 -0
- paddlex/repo_apis/PaddleTS_api/ts_base/config.py +244 -0
- paddlex/repo_apis/PaddleTS_api/ts_base/model.py +276 -0
- paddlex/repo_apis/PaddleTS_api/ts_base/runner.py +158 -0
- paddlex/repo_apis/PaddleTS_api/ts_cls/__init__.py +16 -0
- paddlex/repo_apis/PaddleTS_api/ts_cls/config.py +72 -0
- paddlex/repo_apis/PaddleTS_api/ts_cls/register.py +59 -0
- paddlex/repo_apis/PaddleTS_api/ts_cls/runner.py +158 -0
- paddlex/repo_apis/PaddleTS_api/ts_fc/__init__.py +16 -0
- paddlex/repo_apis/PaddleTS_api/ts_fc/config.py +136 -0
- paddlex/repo_apis/PaddleTS_api/ts_fc/register.py +186 -0
- paddlex/repo_apis/PaddleVideo_api/__init__.py +17 -0
- paddlex/repo_apis/PaddleVideo_api/config_utils.py +51 -0
- paddlex/repo_apis/PaddleVideo_api/video_cls/__init__.py +19 -0
- paddlex/repo_apis/PaddleVideo_api/video_cls/config.py +548 -0
- paddlex/repo_apis/PaddleVideo_api/video_cls/model.py +346 -0
- paddlex/repo_apis/PaddleVideo_api/video_cls/register.py +70 -0
- paddlex/repo_apis/PaddleVideo_api/video_cls/runner.py +204 -0
- paddlex/repo_apis/PaddleVideo_api/video_det/__init__.py +19 -0
- paddlex/repo_apis/PaddleVideo_api/video_det/config.py +549 -0
- paddlex/repo_apis/PaddleVideo_api/video_det/model.py +298 -0
- paddlex/repo_apis/PaddleVideo_api/video_det/register.py +44 -0
- paddlex/repo_apis/PaddleVideo_api/video_det/runner.py +199 -0
- paddlex/repo_apis/__init__.py +13 -0
- paddlex/repo_apis/base/__init__.py +22 -0
- paddlex/repo_apis/base/config.py +237 -0
- paddlex/repo_apis/base/model.py +563 -0
- paddlex/repo_apis/base/register.py +135 -0
- paddlex/repo_apis/base/runner.py +390 -0
- paddlex/repo_apis/base/utils/__init__.py +13 -0
- paddlex/repo_apis/base/utils/arg.py +64 -0
- paddlex/repo_apis/base/utils/subprocess.py +107 -0
- paddlex/repo_manager/__init__.py +17 -0
- paddlex/repo_manager/core.py +253 -0
- paddlex/repo_manager/meta.py +180 -0
- paddlex/repo_manager/repo.py +425 -0
- paddlex/repo_manager/utils.py +148 -0
- paddlex/utils/__init__.py +1 -12
- paddlex/utils/cache.py +146 -0
- paddlex/utils/config.py +216 -0
- paddlex/utils/custom_device_list.py +311 -0
- paddlex/utils/deps.py +249 -0
- paddlex/utils/device.py +195 -0
- paddlex/utils/download.py +168 -182
- paddlex/utils/env.py +31 -48
- paddlex/utils/errors/__init__.py +17 -0
- paddlex/utils/errors/dataset_checker.py +78 -0
- paddlex/utils/errors/others.py +138 -0
- paddlex/utils/file_interface.py +211 -0
- paddlex/utils/flags.py +70 -0
- paddlex/utils/fonts/__init__.py +97 -0
- paddlex/utils/func_register.py +41 -0
- paddlex/utils/install.py +87 -0
- paddlex/utils/interactive_get_pipeline.py +55 -0
- paddlex/utils/lazy_loader.py +68 -0
- paddlex/utils/logging.py +140 -33
- paddlex/utils/misc.py +201 -0
- paddlex/utils/pipeline_arguments.py +719 -0
- paddlex/utils/result_saver.py +58 -0
- paddlex/utils/subclass_register.py +99 -0
- paddlex/version.py +55 -0
- paddlex-3.0.0.dist-info/METADATA +1168 -0
- paddlex-3.0.0.dist-info/RECORD +1093 -0
- paddlex-3.0.0.dist-info/WHEEL +5 -0
- paddlex-3.0.0.dist-info/entry_points.txt +2 -0
- paddlex-3.0.0.dist-info/licenses/LICENSE +169 -0
- paddlex-3.0.0.dist-info/top_level.txt +1 -0
- PaddleClas/__init__.py +0 -16
- PaddleClas/paddleclas.py +0 -375
- PaddleClas/ppcls/__init__.py +0 -20
- PaddleClas/ppcls/data/__init__.py +0 -15
- PaddleClas/ppcls/data/imaug/__init__.py +0 -94
- PaddleClas/ppcls/data/imaug/autoaugment.py +0 -264
- PaddleClas/ppcls/data/imaug/batch_operators.py +0 -117
- PaddleClas/ppcls/data/imaug/cutout.py +0 -41
- PaddleClas/ppcls/data/imaug/fmix.py +0 -217
- PaddleClas/ppcls/data/imaug/grid.py +0 -89
- PaddleClas/ppcls/data/imaug/hide_and_seek.py +0 -44
- PaddleClas/ppcls/data/imaug/operators.py +0 -244
- PaddleClas/ppcls/data/imaug/randaugment.py +0 -106
- PaddleClas/ppcls/data/imaug/random_erasing.py +0 -55
- PaddleClas/ppcls/data/reader.py +0 -318
- PaddleClas/ppcls/modeling/__init__.py +0 -20
- PaddleClas/ppcls/modeling/architectures/__init__.py +0 -51
- PaddleClas/ppcls/modeling/architectures/alexnet.py +0 -132
- PaddleClas/ppcls/modeling/architectures/darknet.py +0 -161
- PaddleClas/ppcls/modeling/architectures/densenet.py +0 -308
- PaddleClas/ppcls/modeling/architectures/distillation_models.py +0 -65
- PaddleClas/ppcls/modeling/architectures/distilled_vision_transformer.py +0 -196
- PaddleClas/ppcls/modeling/architectures/dpn.py +0 -425
- PaddleClas/ppcls/modeling/architectures/efficientnet.py +0 -901
- PaddleClas/ppcls/modeling/architectures/ghostnet.py +0 -331
- PaddleClas/ppcls/modeling/architectures/googlenet.py +0 -207
- PaddleClas/ppcls/modeling/architectures/hrnet.py +0 -742
- PaddleClas/ppcls/modeling/architectures/inception_v3.py +0 -481
- PaddleClas/ppcls/modeling/architectures/inception_v4.py +0 -455
- PaddleClas/ppcls/modeling/architectures/mixnet.py +0 -782
- PaddleClas/ppcls/modeling/architectures/mobilenet_v1.py +0 -266
- PaddleClas/ppcls/modeling/architectures/mobilenet_v2.py +0 -248
- PaddleClas/ppcls/modeling/architectures/mobilenet_v3.py +0 -359
- PaddleClas/ppcls/modeling/architectures/regnet.py +0 -383
- PaddleClas/ppcls/modeling/architectures/repvgg.py +0 -339
- PaddleClas/ppcls/modeling/architectures/res2net.py +0 -272
- PaddleClas/ppcls/modeling/architectures/res2net_vd.py +0 -295
- PaddleClas/ppcls/modeling/architectures/resnest.py +0 -705
- PaddleClas/ppcls/modeling/architectures/resnet.py +0 -316
- PaddleClas/ppcls/modeling/architectures/resnet_vc.py +0 -309
- PaddleClas/ppcls/modeling/architectures/resnet_vd.py +0 -354
- PaddleClas/ppcls/modeling/architectures/resnext.py +0 -253
- PaddleClas/ppcls/modeling/architectures/resnext101_wsl.py +0 -447
- PaddleClas/ppcls/modeling/architectures/resnext_vd.py +0 -266
- PaddleClas/ppcls/modeling/architectures/rexnet.py +0 -240
- PaddleClas/ppcls/modeling/architectures/se_resnet_vd.py +0 -378
- PaddleClas/ppcls/modeling/architectures/se_resnext.py +0 -290
- PaddleClas/ppcls/modeling/architectures/se_resnext_vd.py +0 -285
- PaddleClas/ppcls/modeling/architectures/shufflenet_v2.py +0 -320
- PaddleClas/ppcls/modeling/architectures/squeezenet.py +0 -154
- PaddleClas/ppcls/modeling/architectures/vgg.py +0 -152
- PaddleClas/ppcls/modeling/architectures/vision_transformer.py +0 -402
- PaddleClas/ppcls/modeling/architectures/xception.py +0 -345
- PaddleClas/ppcls/modeling/architectures/xception_deeplab.py +0 -386
- PaddleClas/ppcls/modeling/loss.py +0 -154
- PaddleClas/ppcls/modeling/utils.py +0 -53
- PaddleClas/ppcls/optimizer/__init__.py +0 -19
- PaddleClas/ppcls/optimizer/learning_rate.py +0 -159
- PaddleClas/ppcls/optimizer/optimizer.py +0 -165
- PaddleClas/ppcls/utils/__init__.py +0 -27
- PaddleClas/ppcls/utils/check.py +0 -151
- PaddleClas/ppcls/utils/config.py +0 -201
- PaddleClas/ppcls/utils/logger.py +0 -120
- PaddleClas/ppcls/utils/metrics.py +0 -107
- PaddleClas/ppcls/utils/misc.py +0 -62
- PaddleClas/ppcls/utils/model_zoo.py +0 -213
- PaddleClas/ppcls/utils/save_load.py +0 -163
- PaddleClas/setup.py +0 -55
- PaddleClas/tools/__init__.py +0 -15
- PaddleClas/tools/download.py +0 -50
- PaddleClas/tools/ema.py +0 -58
- PaddleClas/tools/eval.py +0 -112
- PaddleClas/tools/export_model.py +0 -85
- PaddleClas/tools/export_serving_model.py +0 -76
- PaddleClas/tools/infer/__init__.py +0 -16
- PaddleClas/tools/infer/infer.py +0 -94
- PaddleClas/tools/infer/predict.py +0 -117
- PaddleClas/tools/infer/utils.py +0 -233
- PaddleClas/tools/program.py +0 -444
- PaddleClas/tools/test_hubserving.py +0 -113
- PaddleClas/tools/train.py +0 -141
- paddlex/cls.py +0 -76
- paddlex/command.py +0 -215
- paddlex/cv/__init__.py +0 -17
- paddlex/cv/datasets/__init__.py +0 -18
- paddlex/cv/datasets/coco.py +0 -169
- paddlex/cv/datasets/imagenet.py +0 -88
- paddlex/cv/datasets/seg_dataset.py +0 -91
- paddlex/cv/datasets/voc.py +0 -301
- paddlex/cv/models/__init__.py +0 -18
- paddlex/cv/models/base.py +0 -623
- paddlex/cv/models/classifier.py +0 -814
- paddlex/cv/models/detector.py +0 -1747
- paddlex/cv/models/load_model.py +0 -126
- paddlex/cv/models/segmenter.py +0 -673
- paddlex/cv/models/slim/__init__.py +0 -13
- paddlex/cv/models/slim/prune.py +0 -55
- paddlex/cv/models/utils/__init__.py +0 -13
- paddlex/cv/models/utils/det_metrics/__init__.py +0 -15
- paddlex/cv/models/utils/det_metrics/coco_utils.py +0 -217
- paddlex/cv/models/utils/det_metrics/metrics.py +0 -220
- paddlex/cv/models/utils/ema.py +0 -48
- paddlex/cv/models/utils/seg_metrics.py +0 -62
- paddlex/cv/models/utils/visualize.py +0 -394
- paddlex/cv/transforms/__init__.py +0 -46
- paddlex/cv/transforms/batch_operators.py +0 -286
- paddlex/cv/transforms/box_utils.py +0 -41
- paddlex/cv/transforms/functions.py +0 -193
- paddlex/cv/transforms/operators.py +0 -1402
- paddlex/det.py +0 -43
- paddlex/paddleseg/__init__.py +0 -17
- paddlex/paddleseg/core/__init__.py +0 -20
- paddlex/paddleseg/core/infer.py +0 -289
- paddlex/paddleseg/core/predict.py +0 -145
- paddlex/paddleseg/core/train.py +0 -258
- paddlex/paddleseg/core/val.py +0 -172
- paddlex/paddleseg/cvlibs/__init__.py +0 -17
- paddlex/paddleseg/cvlibs/callbacks.py +0 -279
- paddlex/paddleseg/cvlibs/config.py +0 -359
- paddlex/paddleseg/cvlibs/manager.py +0 -142
- paddlex/paddleseg/cvlibs/param_init.py +0 -91
- paddlex/paddleseg/datasets/__init__.py +0 -21
- paddlex/paddleseg/datasets/ade.py +0 -112
- paddlex/paddleseg/datasets/cityscapes.py +0 -86
- paddlex/paddleseg/datasets/cocostuff.py +0 -79
- paddlex/paddleseg/datasets/dataset.py +0 -164
- paddlex/paddleseg/datasets/mini_deep_globe_road_extraction.py +0 -95
- paddlex/paddleseg/datasets/optic_disc_seg.py +0 -97
- paddlex/paddleseg/datasets/pascal_context.py +0 -80
- paddlex/paddleseg/datasets/voc.py +0 -113
- paddlex/paddleseg/models/__init__.py +0 -39
- paddlex/paddleseg/models/ann.py +0 -436
- paddlex/paddleseg/models/attention_unet.py +0 -189
- paddlex/paddleseg/models/backbones/__init__.py +0 -18
- paddlex/paddleseg/models/backbones/hrnet.py +0 -815
- paddlex/paddleseg/models/backbones/mobilenetv3.py +0 -365
- paddlex/paddleseg/models/backbones/resnet_vd.py +0 -364
- paddlex/paddleseg/models/backbones/xception_deeplab.py +0 -415
- paddlex/paddleseg/models/bisenet.py +0 -311
- paddlex/paddleseg/models/danet.py +0 -220
- paddlex/paddleseg/models/decoupled_segnet.py +0 -233
- paddlex/paddleseg/models/deeplab.py +0 -258
- paddlex/paddleseg/models/dnlnet.py +0 -231
- paddlex/paddleseg/models/emanet.py +0 -219
- paddlex/paddleseg/models/fast_scnn.py +0 -318
- paddlex/paddleseg/models/fcn.py +0 -135
- paddlex/paddleseg/models/gcnet.py +0 -223
- paddlex/paddleseg/models/gscnn.py +0 -357
- paddlex/paddleseg/models/hardnet.py +0 -309
- paddlex/paddleseg/models/isanet.py +0 -202
- paddlex/paddleseg/models/layers/__init__.py +0 -19
- paddlex/paddleseg/models/layers/activation.py +0 -73
- paddlex/paddleseg/models/layers/attention.py +0 -146
- paddlex/paddleseg/models/layers/layer_libs.py +0 -168
- paddlex/paddleseg/models/layers/nonlocal2d.py +0 -155
- paddlex/paddleseg/models/layers/pyramid_pool.py +0 -182
- paddlex/paddleseg/models/losses/__init__.py +0 -27
- paddlex/paddleseg/models/losses/binary_cross_entropy_loss.py +0 -174
- paddlex/paddleseg/models/losses/bootstrapped_cross_entropy.py +0 -73
- paddlex/paddleseg/models/losses/cross_entropy_loss.py +0 -94
- paddlex/paddleseg/models/losses/decoupledsegnet_relax_boundary_loss.py +0 -129
- paddlex/paddleseg/models/losses/dice_loss.py +0 -61
- paddlex/paddleseg/models/losses/edge_attention_loss.py +0 -78
- paddlex/paddleseg/models/losses/gscnn_dual_task_loss.py +0 -141
- paddlex/paddleseg/models/losses/l1_loss.py +0 -76
- paddlex/paddleseg/models/losses/lovasz_loss.py +0 -222
- paddlex/paddleseg/models/losses/mean_square_error_loss.py +0 -65
- paddlex/paddleseg/models/losses/mixed_loss.py +0 -58
- paddlex/paddleseg/models/losses/ohem_cross_entropy_loss.py +0 -99
- paddlex/paddleseg/models/losses/ohem_edge_attention_loss.py +0 -114
- paddlex/paddleseg/models/ocrnet.py +0 -248
- paddlex/paddleseg/models/pspnet.py +0 -147
- paddlex/paddleseg/models/sfnet.py +0 -236
- paddlex/paddleseg/models/shufflenet_slim.py +0 -268
- paddlex/paddleseg/models/u2net.py +0 -574
- paddlex/paddleseg/models/unet.py +0 -155
- paddlex/paddleseg/models/unet_3plus.py +0 -316
- paddlex/paddleseg/models/unet_plusplus.py +0 -237
- paddlex/paddleseg/transforms/__init__.py +0 -16
- paddlex/paddleseg/transforms/functional.py +0 -161
- paddlex/paddleseg/transforms/transforms.py +0 -937
- paddlex/paddleseg/utils/__init__.py +0 -22
- paddlex/paddleseg/utils/config_check.py +0 -60
- paddlex/paddleseg/utils/download.py +0 -163
- paddlex/paddleseg/utils/env/__init__.py +0 -16
- paddlex/paddleseg/utils/env/seg_env.py +0 -56
- paddlex/paddleseg/utils/env/sys_env.py +0 -122
- paddlex/paddleseg/utils/logger.py +0 -48
- paddlex/paddleseg/utils/metrics.py +0 -146
- paddlex/paddleseg/utils/progbar.py +0 -212
- paddlex/paddleseg/utils/timer.py +0 -53
- paddlex/paddleseg/utils/utils.py +0 -120
- paddlex/paddleseg/utils/visualize.py +0 -90
- paddlex/ppcls/__init__.py +0 -20
- paddlex/ppcls/data/__init__.py +0 -15
- paddlex/ppcls/data/imaug/__init__.py +0 -94
- paddlex/ppcls/data/imaug/autoaugment.py +0 -264
- paddlex/ppcls/data/imaug/batch_operators.py +0 -117
- paddlex/ppcls/data/imaug/cutout.py +0 -41
- paddlex/ppcls/data/imaug/fmix.py +0 -217
- paddlex/ppcls/data/imaug/grid.py +0 -89
- paddlex/ppcls/data/imaug/hide_and_seek.py +0 -44
- paddlex/ppcls/data/imaug/operators.py +0 -256
- paddlex/ppcls/data/imaug/randaugment.py +0 -106
- paddlex/ppcls/data/imaug/random_erasing.py +0 -55
- paddlex/ppcls/data/reader.py +0 -318
- paddlex/ppcls/modeling/__init__.py +0 -20
- paddlex/ppcls/modeling/architectures/__init__.py +0 -51
- paddlex/ppcls/modeling/architectures/alexnet.py +0 -132
- paddlex/ppcls/modeling/architectures/darknet.py +0 -161
- paddlex/ppcls/modeling/architectures/densenet.py +0 -308
- paddlex/ppcls/modeling/architectures/distillation_models.py +0 -65
- paddlex/ppcls/modeling/architectures/distilled_vision_transformer.py +0 -196
- paddlex/ppcls/modeling/architectures/dpn.py +0 -425
- paddlex/ppcls/modeling/architectures/efficientnet.py +0 -901
- paddlex/ppcls/modeling/architectures/ghostnet.py +0 -331
- paddlex/ppcls/modeling/architectures/googlenet.py +0 -207
- paddlex/ppcls/modeling/architectures/hrnet.py +0 -742
- paddlex/ppcls/modeling/architectures/inception_v3.py +0 -541
- paddlex/ppcls/modeling/architectures/inception_v4.py +0 -455
- paddlex/ppcls/modeling/architectures/mixnet.py +0 -782
- paddlex/ppcls/modeling/architectures/mobilenet_v1.py +0 -266
- paddlex/ppcls/modeling/architectures/mobilenet_v2.py +0 -248
- paddlex/ppcls/modeling/architectures/mobilenet_v3.py +0 -359
- paddlex/ppcls/modeling/architectures/regnet.py +0 -383
- paddlex/ppcls/modeling/architectures/repvgg.py +0 -339
- paddlex/ppcls/modeling/architectures/res2net.py +0 -272
- paddlex/ppcls/modeling/architectures/res2net_vd.py +0 -295
- paddlex/ppcls/modeling/architectures/resnest.py +0 -705
- paddlex/ppcls/modeling/architectures/resnet.py +0 -317
- paddlex/ppcls/modeling/architectures/resnet_vc.py +0 -309
- paddlex/ppcls/modeling/architectures/resnet_vd.py +0 -354
- paddlex/ppcls/modeling/architectures/resnext.py +0 -259
- paddlex/ppcls/modeling/architectures/resnext101_wsl.py +0 -447
- paddlex/ppcls/modeling/architectures/resnext_vd.py +0 -266
- paddlex/ppcls/modeling/architectures/rexnet.py +0 -240
- paddlex/ppcls/modeling/architectures/se_resnet_vd.py +0 -378
- paddlex/ppcls/modeling/architectures/se_resnext.py +0 -290
- paddlex/ppcls/modeling/architectures/se_resnext_vd.py +0 -285
- paddlex/ppcls/modeling/architectures/shufflenet_v2.py +0 -320
- paddlex/ppcls/modeling/architectures/squeezenet.py +0 -154
- paddlex/ppcls/modeling/architectures/vgg.py +0 -152
- paddlex/ppcls/modeling/architectures/vision_transformer.py +0 -402
- paddlex/ppcls/modeling/architectures/xception.py +0 -345
- paddlex/ppcls/modeling/architectures/xception_deeplab.py +0 -386
- paddlex/ppcls/modeling/loss.py +0 -158
- paddlex/ppcls/modeling/utils.py +0 -53
- paddlex/ppcls/optimizer/__init__.py +0 -19
- paddlex/ppcls/optimizer/learning_rate.py +0 -159
- paddlex/ppcls/optimizer/optimizer.py +0 -165
- paddlex/ppcls/utils/__init__.py +0 -27
- paddlex/ppcls/utils/check.py +0 -151
- paddlex/ppcls/utils/config.py +0 -201
- paddlex/ppcls/utils/logger.py +0 -120
- paddlex/ppcls/utils/metrics.py +0 -112
- paddlex/ppcls/utils/misc.py +0 -62
- paddlex/ppcls/utils/model_zoo.py +0 -213
- paddlex/ppcls/utils/save_load.py +0 -163
- paddlex/ppdet/__init__.py +0 -16
- paddlex/ppdet/core/__init__.py +0 -15
- paddlex/ppdet/core/config/__init__.py +0 -13
- paddlex/ppdet/core/config/schema.py +0 -248
- paddlex/ppdet/core/config/yaml_helpers.py +0 -118
- paddlex/ppdet/core/workspace.py +0 -279
- paddlex/ppdet/data/__init__.py +0 -21
- paddlex/ppdet/data/reader.py +0 -304
- paddlex/ppdet/data/shm_utils.py +0 -67
- paddlex/ppdet/data/source/__init__.py +0 -27
- paddlex/ppdet/data/source/category.py +0 -823
- paddlex/ppdet/data/source/coco.py +0 -243
- paddlex/ppdet/data/source/dataset.py +0 -192
- paddlex/ppdet/data/source/keypoint_coco.py +0 -656
- paddlex/ppdet/data/source/mot.py +0 -360
- paddlex/ppdet/data/source/voc.py +0 -204
- paddlex/ppdet/data/source/widerface.py +0 -180
- paddlex/ppdet/data/transform/__init__.py +0 -28
- paddlex/ppdet/data/transform/autoaugment_utils.py +0 -1593
- paddlex/ppdet/data/transform/batch_operators.py +0 -758
- paddlex/ppdet/data/transform/gridmask_utils.py +0 -83
- paddlex/ppdet/data/transform/keypoint_operators.py +0 -665
- paddlex/ppdet/data/transform/mot_operators.py +0 -636
- paddlex/ppdet/data/transform/op_helper.py +0 -468
- paddlex/ppdet/data/transform/operators.py +0 -2103
- paddlex/ppdet/engine/__init__.py +0 -29
- paddlex/ppdet/engine/callbacks.py +0 -262
- paddlex/ppdet/engine/env.py +0 -47
- paddlex/ppdet/engine/export_utils.py +0 -118
- paddlex/ppdet/engine/tracker.py +0 -425
- paddlex/ppdet/engine/trainer.py +0 -535
- paddlex/ppdet/metrics/__init__.py +0 -23
- paddlex/ppdet/metrics/coco_utils.py +0 -184
- paddlex/ppdet/metrics/json_results.py +0 -151
- paddlex/ppdet/metrics/keypoint_metrics.py +0 -202
- paddlex/ppdet/metrics/map_utils.py +0 -396
- paddlex/ppdet/metrics/metrics.py +0 -300
- paddlex/ppdet/metrics/mot_eval_utils.py +0 -192
- paddlex/ppdet/metrics/mot_metrics.py +0 -184
- paddlex/ppdet/metrics/widerface_utils.py +0 -393
- paddlex/ppdet/model_zoo/__init__.py +0 -18
- paddlex/ppdet/model_zoo/model_zoo.py +0 -86
- paddlex/ppdet/model_zoo/tests/__init__.py +0 -13
- paddlex/ppdet/model_zoo/tests/test_get_model.py +0 -48
- paddlex/ppdet/model_zoo/tests/test_list_model.py +0 -68
- paddlex/ppdet/modeling/__init__.py +0 -41
- paddlex/ppdet/modeling/architectures/__init__.py +0 -40
- paddlex/ppdet/modeling/architectures/cascade_rcnn.py +0 -144
- paddlex/ppdet/modeling/architectures/centernet.py +0 -103
- paddlex/ppdet/modeling/architectures/deepsort.py +0 -111
- paddlex/ppdet/modeling/architectures/fairmot.py +0 -107
- paddlex/ppdet/modeling/architectures/faster_rcnn.py +0 -106
- paddlex/ppdet/modeling/architectures/fcos.py +0 -105
- paddlex/ppdet/modeling/architectures/jde.py +0 -125
- paddlex/ppdet/modeling/architectures/keypoint_hrhrnet.py +0 -286
- paddlex/ppdet/modeling/architectures/keypoint_hrnet.py +0 -203
- paddlex/ppdet/modeling/architectures/mask_rcnn.py +0 -135
- paddlex/ppdet/modeling/architectures/meta_arch.py +0 -45
- paddlex/ppdet/modeling/architectures/s2anet.py +0 -103
- paddlex/ppdet/modeling/architectures/solov2.py +0 -110
- paddlex/ppdet/modeling/architectures/ssd.py +0 -84
- paddlex/ppdet/modeling/architectures/ttfnet.py +0 -98
- paddlex/ppdet/modeling/architectures/yolo.py +0 -104
- paddlex/ppdet/modeling/backbones/__init__.py +0 -37
- paddlex/ppdet/modeling/backbones/blazenet.py +0 -322
- paddlex/ppdet/modeling/backbones/darknet.py +0 -341
- paddlex/ppdet/modeling/backbones/dla.py +0 -244
- paddlex/ppdet/modeling/backbones/ghostnet.py +0 -476
- paddlex/ppdet/modeling/backbones/hrnet.py +0 -724
- paddlex/ppdet/modeling/backbones/mobilenet_v1.py +0 -410
- paddlex/ppdet/modeling/backbones/mobilenet_v3.py +0 -497
- paddlex/ppdet/modeling/backbones/name_adapter.py +0 -69
- paddlex/ppdet/modeling/backbones/res2net.py +0 -358
- paddlex/ppdet/modeling/backbones/resnet.py +0 -606
- paddlex/ppdet/modeling/backbones/senet.py +0 -140
- paddlex/ppdet/modeling/backbones/vgg.py +0 -216
- paddlex/ppdet/modeling/bbox_utils.py +0 -464
- paddlex/ppdet/modeling/heads/__init__.py +0 -41
- paddlex/ppdet/modeling/heads/bbox_head.py +0 -379
- paddlex/ppdet/modeling/heads/cascade_head.py +0 -285
- paddlex/ppdet/modeling/heads/centernet_head.py +0 -194
- paddlex/ppdet/modeling/heads/face_head.py +0 -113
- paddlex/ppdet/modeling/heads/fcos_head.py +0 -270
- paddlex/ppdet/modeling/heads/keypoint_hrhrnet_head.py +0 -108
- paddlex/ppdet/modeling/heads/mask_head.py +0 -253
- paddlex/ppdet/modeling/heads/roi_extractor.py +0 -111
- paddlex/ppdet/modeling/heads/s2anet_head.py +0 -845
- paddlex/ppdet/modeling/heads/solov2_head.py +0 -537
- paddlex/ppdet/modeling/heads/ssd_head.py +0 -175
- paddlex/ppdet/modeling/heads/ttf_head.py +0 -314
- paddlex/ppdet/modeling/heads/yolo_head.py +0 -124
- paddlex/ppdet/modeling/keypoint_utils.py +0 -302
- paddlex/ppdet/modeling/layers.py +0 -1142
- paddlex/ppdet/modeling/losses/__init__.py +0 -35
- paddlex/ppdet/modeling/losses/ctfocal_loss.py +0 -67
- paddlex/ppdet/modeling/losses/fairmot_loss.py +0 -41
- paddlex/ppdet/modeling/losses/fcos_loss.py +0 -225
- paddlex/ppdet/modeling/losses/iou_aware_loss.py +0 -48
- paddlex/ppdet/modeling/losses/iou_loss.py +0 -210
- paddlex/ppdet/modeling/losses/jde_loss.py +0 -182
- paddlex/ppdet/modeling/losses/keypoint_loss.py +0 -228
- paddlex/ppdet/modeling/losses/solov2_loss.py +0 -101
- paddlex/ppdet/modeling/losses/ssd_loss.py +0 -163
- paddlex/ppdet/modeling/losses/yolo_loss.py +0 -212
- paddlex/ppdet/modeling/mot/__init__.py +0 -25
- paddlex/ppdet/modeling/mot/matching/__init__.py +0 -19
- paddlex/ppdet/modeling/mot/matching/deepsort_matching.py +0 -382
- paddlex/ppdet/modeling/mot/matching/jde_matching.py +0 -145
- paddlex/ppdet/modeling/mot/motion/__init__.py +0 -17
- paddlex/ppdet/modeling/mot/motion/kalman_filter.py +0 -270
- paddlex/ppdet/modeling/mot/tracker/__init__.py +0 -23
- paddlex/ppdet/modeling/mot/tracker/base_jde_tracker.py +0 -267
- paddlex/ppdet/modeling/mot/tracker/base_sde_tracker.py +0 -145
- paddlex/ppdet/modeling/mot/tracker/deepsort_tracker.py +0 -165
- paddlex/ppdet/modeling/mot/tracker/jde_tracker.py +0 -262
- paddlex/ppdet/modeling/mot/utils.py +0 -181
- paddlex/ppdet/modeling/mot/visualization.py +0 -130
- paddlex/ppdet/modeling/necks/__init__.py +0 -25
- paddlex/ppdet/modeling/necks/centernet_fpn.py +0 -185
- paddlex/ppdet/modeling/necks/fpn.py +0 -233
- paddlex/ppdet/modeling/necks/hrfpn.py +0 -131
- paddlex/ppdet/modeling/necks/ttf_fpn.py +0 -243
- paddlex/ppdet/modeling/necks/yolo_fpn.py +0 -1034
- paddlex/ppdet/modeling/ops.py +0 -1599
- paddlex/ppdet/modeling/post_process.py +0 -449
- paddlex/ppdet/modeling/proposal_generator/__init__.py +0 -2
- paddlex/ppdet/modeling/proposal_generator/anchor_generator.py +0 -135
- paddlex/ppdet/modeling/proposal_generator/proposal_generator.py +0 -81
- paddlex/ppdet/modeling/proposal_generator/rpn_head.py +0 -269
- paddlex/ppdet/modeling/proposal_generator/target.py +0 -671
- paddlex/ppdet/modeling/proposal_generator/target_layer.py +0 -476
- paddlex/ppdet/modeling/reid/__init__.py +0 -23
- paddlex/ppdet/modeling/reid/fairmot_embedding_head.py +0 -117
- paddlex/ppdet/modeling/reid/jde_embedding_head.py +0 -189
- paddlex/ppdet/modeling/reid/pyramidal_embedding.py +0 -151
- paddlex/ppdet/modeling/reid/resnet.py +0 -320
- paddlex/ppdet/modeling/shape_spec.py +0 -33
- paddlex/ppdet/modeling/tests/__init__.py +0 -13
- paddlex/ppdet/modeling/tests/test_architectures.py +0 -59
- paddlex/ppdet/modeling/tests/test_base.py +0 -75
- paddlex/ppdet/modeling/tests/test_ops.py +0 -839
- paddlex/ppdet/modeling/tests/test_yolov3_loss.py +0 -420
- paddlex/ppdet/optimizer.py +0 -285
- paddlex/ppdet/slim/__init__.py +0 -62
- paddlex/ppdet/slim/distill.py +0 -111
- paddlex/ppdet/slim/prune.py +0 -85
- paddlex/ppdet/slim/quant.py +0 -52
- paddlex/ppdet/utils/__init__.py +0 -13
- paddlex/ppdet/utils/check.py +0 -93
- paddlex/ppdet/utils/checkpoint.py +0 -216
- paddlex/ppdet/utils/cli.py +0 -151
- paddlex/ppdet/utils/colormap.py +0 -56
- paddlex/ppdet/utils/download.py +0 -477
- paddlex/ppdet/utils/logger.py +0 -71
- paddlex/ppdet/utils/stats.py +0 -95
- paddlex/ppdet/utils/visualizer.py +0 -292
- paddlex/ppdet/utils/voc_utils.py +0 -87
- paddlex/seg.py +0 -38
- paddlex/tools/__init__.py +0 -16
- paddlex/tools/convert.py +0 -52
- paddlex/tools/dataset_conversion/__init__.py +0 -24
- paddlex/tools/dataset_conversion/x2coco.py +0 -379
- paddlex/tools/dataset_conversion/x2imagenet.py +0 -82
- paddlex/tools/dataset_conversion/x2seg.py +0 -343
- paddlex/tools/dataset_conversion/x2voc.py +0 -230
- paddlex/tools/dataset_split/__init__.py +0 -23
- paddlex/tools/dataset_split/coco_split.py +0 -69
- paddlex/tools/dataset_split/imagenet_split.py +0 -75
- paddlex/tools/dataset_split/seg_split.py +0 -96
- paddlex/tools/dataset_split/utils.py +0 -75
- paddlex/tools/dataset_split/voc_split.py +0 -91
- paddlex/tools/split.py +0 -41
- paddlex/utils/checkpoint.py +0 -439
- paddlex/utils/shm.py +0 -67
- paddlex/utils/stats.py +0 -68
- paddlex/utils/utils.py +0 -140
- paddlex-2.0.0rc4.dist-info/LICENSE +0 -201
- paddlex-2.0.0rc4.dist-info/METADATA +0 -29
- paddlex-2.0.0rc4.dist-info/RECORD +0 -445
- paddlex-2.0.0rc4.dist-info/WHEEL +0 -5
- paddlex-2.0.0rc4.dist-info/entry_points.txt +0 -3
- paddlex-2.0.0rc4.dist-info/top_level.txt +0 -2
@@ -0,0 +1,3006 @@
|
|
1
|
+
# Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
import math
|
16
|
+
from dataclasses import dataclass
|
17
|
+
from functools import partial
|
18
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
19
|
+
|
20
|
+
import paddle
|
21
|
+
import paddle.distributed.fleet.meta_parallel as mpu
|
22
|
+
import paddle.nn.functional as F
|
23
|
+
from paddle import Tensor, nn
|
24
|
+
from paddle.distributed import fleet
|
25
|
+
from paddle.distributed.fleet.meta_parallel import get_rng_state_tracker
|
26
|
+
from paddle.distributed.fleet.utils import recompute
|
27
|
+
|
28
|
+
from .....utils import logging
|
29
|
+
from .....utils.env import get_device_type
|
30
|
+
from ...common.vlm.activations import ACT2FN
|
31
|
+
from ...common.vlm.bert_padding import index_first_axis, pad_input, unpad_input
|
32
|
+
from ...common.vlm.flash_attn_utils import has_flash_attn_func
|
33
|
+
from ...common.vlm.transformers import PretrainedConfig, PretrainedModel
|
34
|
+
from ...common.vlm.transformers.model_outputs import (
|
35
|
+
BaseModelOutputWithPast,
|
36
|
+
ModelOutput,
|
37
|
+
)
|
38
|
+
|
39
|
+
|
40
|
+
class Qwen2_5_VLVisionConfig(PretrainedConfig):
|
41
|
+
model_type = "qwen2_5_vl"
|
42
|
+
base_config_key = "vision_config"
|
43
|
+
|
44
|
+
def __init__(
|
45
|
+
self,
|
46
|
+
depth=32,
|
47
|
+
hidden_size=3584,
|
48
|
+
hidden_act="silu",
|
49
|
+
intermediate_size=3420,
|
50
|
+
num_heads=16,
|
51
|
+
in_channels=3,
|
52
|
+
patch_size=14,
|
53
|
+
spatial_merge_size=2,
|
54
|
+
temporal_patch_size=2,
|
55
|
+
tokens_per_second=4,
|
56
|
+
window_size=112,
|
57
|
+
out_hidden_size=3584,
|
58
|
+
fullatt_block_indexes=[7, 15, 23, 31],
|
59
|
+
**kwargs,
|
60
|
+
):
|
61
|
+
super().__init__(**kwargs)
|
62
|
+
self.depth = depth
|
63
|
+
self.hidden_size = hidden_size
|
64
|
+
self.hidden_act = hidden_act
|
65
|
+
self.intermediate_size = intermediate_size
|
66
|
+
self.num_heads = num_heads
|
67
|
+
self.in_channels = in_channels
|
68
|
+
self.patch_size = patch_size
|
69
|
+
self.spatial_merge_size = spatial_merge_size
|
70
|
+
self.temporal_patch_size = temporal_patch_size
|
71
|
+
self.tokens_per_second = tokens_per_second
|
72
|
+
self.window_size = window_size
|
73
|
+
self.fullatt_block_indexes = fullatt_block_indexes
|
74
|
+
self.out_hidden_size = out_hidden_size
|
75
|
+
|
76
|
+
|
77
|
+
class Qwen2_5_VLConfig(PretrainedConfig):
|
78
|
+
"""
|
79
|
+
This is the configuration class to store the configuration of a [`Qwen2_5_VLModel`]. It is used to instantiate a
|
80
|
+
Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
81
|
+
with the defaults will yield a similar configuration to that of
|
82
|
+
Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
|
83
|
+
|
84
|
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
85
|
+
documentation from [`PretrainedConfig`] for more information.
|
86
|
+
|
87
|
+
|
88
|
+
Args:
|
89
|
+
vocab_size (`int`, *optional*, defaults to 152064):
|
90
|
+
Vocabulary size of the Qwen2_5_VL model. Defines the number of different tokens that can be represented by the
|
91
|
+
`inputs_ids` passed when calling [`Qwen2_5_VLModel`]
|
92
|
+
hidden_size (`int`, *optional*, defaults to 8192):
|
93
|
+
Dimension of the hidden representations.
|
94
|
+
intermediate_size (`int`, *optional*, defaults to 29568):
|
95
|
+
Dimension of the MLP representations.
|
96
|
+
num_hidden_layers (`int`, *optional*, defaults to 80):
|
97
|
+
Number of hidden layers in the Transformer encoder.
|
98
|
+
num_attention_heads (`int`, *optional*, defaults to 64):
|
99
|
+
Number of attention heads for each attention layer in the Transformer encoder.
|
100
|
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
101
|
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
102
|
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
103
|
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
104
|
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
105
|
+
by meanpooling all the original heads within that group. For more details checkout [this
|
106
|
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
107
|
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
108
|
+
The non-linear activation function (function or string) in the decoder.
|
109
|
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
110
|
+
The maximum sequence length that this model might ever be used with.
|
111
|
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
112
|
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
113
|
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
114
|
+
The epsilon used by the rms normalization layers.
|
115
|
+
use_cache (`bool`, *optional*, defaults to `True`):
|
116
|
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
117
|
+
relevant if `config.is_decoder=True`.
|
118
|
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
119
|
+
Whether the model's input and output word embeddings should be tied.
|
120
|
+
rope_theta (`float`, *optional*, defaults to 1000000.0):
|
121
|
+
The base period of the RoPE embeddings.
|
122
|
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
123
|
+
Whether to use sliding window attention.
|
124
|
+
sliding_window (`int`, *optional*, defaults to 4096):
|
125
|
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
126
|
+
max_window_layers (`int`, *optional*, defaults to 80):
|
127
|
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
128
|
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
129
|
+
The dropout ratio for the attention probabilities.
|
130
|
+
vision_config (`Dict`, *optional*):
|
131
|
+
The config for the visual encoder initialization.
|
132
|
+
rope_scaling (`Dict`, *optional*):
|
133
|
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
134
|
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
135
|
+
accordingly.
|
136
|
+
Expected contents:
|
137
|
+
`rope_type` (`str`):
|
138
|
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
139
|
+
'llama3'], with 'default' being the original RoPE implementation.
|
140
|
+
`factor` (`float`, *optional*):
|
141
|
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
142
|
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
143
|
+
original maximum pre-trained length.
|
144
|
+
`original_max_position_embeddings` (`int`, *optional*):
|
145
|
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
146
|
+
pretraining.
|
147
|
+
`attention_factor` (`float`, *optional*):
|
148
|
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
149
|
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
150
|
+
`factor` field to infer the suggested value.
|
151
|
+
`beta_fast` (`float`, *optional*):
|
152
|
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
153
|
+
ramp function. If unspecified, it defaults to 32.
|
154
|
+
`beta_slow` (`float`, *optional*):
|
155
|
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
156
|
+
ramp function. If unspecified, it defaults to 1.
|
157
|
+
`short_factor` (`List[float]`, *optional*):
|
158
|
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
159
|
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
160
|
+
size divided by the number of attention heads divided by 2
|
161
|
+
`long_factor` (`List[float]`, *optional*):
|
162
|
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
163
|
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
164
|
+
size divided by the number of attention heads divided by 2
|
165
|
+
`low_freq_factor` (`float`, *optional*):
|
166
|
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
167
|
+
`high_freq_factor` (`float`, *optional*):
|
168
|
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
169
|
+
|
170
|
+
```python
|
171
|
+
>>> from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLConfig
|
172
|
+
|
173
|
+
>>> # Initializing a Qwen2_5_VL style configuration
|
174
|
+
>>> configuration = Qwen2_5_VLConfig()
|
175
|
+
|
176
|
+
>>> # Initializing a model from the Qwen2-VL-7B style configuration
|
177
|
+
>>> model = Qwen2_5_VLForConditionalGeneration(configuration)
|
178
|
+
|
179
|
+
>>> # Accessing the model configuration
|
180
|
+
>>> configuration = model.config
|
181
|
+
```"""
|
182
|
+
|
183
|
+
model_type = "qwen2_5_vl"
|
184
|
+
sub_configs = {"vision_config": Qwen2_5_VLVisionConfig}
|
185
|
+
keys_to_ignore_at_inference = ["past_key_values"]
|
186
|
+
base_model_tp_plan = {
|
187
|
+
"layers.*.self_attn.q_proj": "colwise",
|
188
|
+
"layers.*.self_attn.k_proj": "colwise",
|
189
|
+
"layers.*.self_attn.v_proj": "colwise",
|
190
|
+
"layers.*.self_attn.o_proj": "rowwise",
|
191
|
+
"layers.*.mlp.gate_proj": "colwise",
|
192
|
+
"layers.*.mlp.up_proj": "colwise",
|
193
|
+
"layers.*.mlp.down_proj": "rowwise",
|
194
|
+
}
|
195
|
+
|
196
|
+
def __init__(
|
197
|
+
self,
|
198
|
+
vocab_size=152064,
|
199
|
+
hidden_size=8192,
|
200
|
+
intermediate_size=29568,
|
201
|
+
num_hidden_layers=80,
|
202
|
+
num_attention_heads=64,
|
203
|
+
num_key_value_heads=8,
|
204
|
+
hidden_act="silu",
|
205
|
+
max_position_embeddings=32768,
|
206
|
+
initializer_range=0.02,
|
207
|
+
rms_norm_eps=1e-05,
|
208
|
+
use_cache=True,
|
209
|
+
tie_word_embeddings=False,
|
210
|
+
rope_theta=1000000.0,
|
211
|
+
use_sliding_window=False,
|
212
|
+
sliding_window=4096,
|
213
|
+
max_window_layers=80,
|
214
|
+
attention_dropout=0.0,
|
215
|
+
vision_config=None,
|
216
|
+
rope_scaling=None,
|
217
|
+
**kwargs,
|
218
|
+
):
|
219
|
+
if isinstance(vision_config, dict):
|
220
|
+
self.vision_config = self.sub_configs["vision_config"](**vision_config)
|
221
|
+
elif vision_config is None:
|
222
|
+
self.vision_config = self.sub_configs["vision_config"]()
|
223
|
+
self.vocab_size = vocab_size
|
224
|
+
self.max_position_embeddings = max_position_embeddings
|
225
|
+
self.hidden_size = hidden_size
|
226
|
+
self.intermediate_size = intermediate_size
|
227
|
+
self.num_hidden_layers = num_hidden_layers
|
228
|
+
self.num_attention_heads = num_attention_heads
|
229
|
+
self.use_sliding_window = use_sliding_window
|
230
|
+
self.sliding_window = sliding_window
|
231
|
+
self.max_window_layers = max_window_layers
|
232
|
+
if num_key_value_heads is None:
|
233
|
+
num_key_value_heads = num_attention_heads
|
234
|
+
self.num_key_value_heads = num_key_value_heads
|
235
|
+
self.hidden_act = hidden_act
|
236
|
+
self.initializer_range = initializer_range
|
237
|
+
self.rms_norm_eps = rms_norm_eps
|
238
|
+
self.use_cache = use_cache
|
239
|
+
self.rope_theta = rope_theta
|
240
|
+
self.attention_dropout = attention_dropout
|
241
|
+
self.rope_scaling = rope_scaling
|
242
|
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
243
|
+
if self.rope_scaling["type"] == "mrope":
|
244
|
+
self.rope_scaling["type"] = "default"
|
245
|
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
246
|
+
|
247
|
+
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
248
|
+
|
249
|
+
|
250
|
+
flash_attn_func, flash_attn_varlen_func = has_flash_attn_func()
|
251
|
+
|
252
|
+
Linear = nn.Linear
|
253
|
+
ColumnParallelLinear = mpu.ColumnParallelLinear
|
254
|
+
RowParallelLinear = mpu.RowParallelLinear
|
255
|
+
|
256
|
+
|
257
|
+
def get_triangle_upper_mask(x, mask=None):
|
258
|
+
if mask is not None:
|
259
|
+
return mask
|
260
|
+
shape = x.shape
|
261
|
+
shape[1] = 1
|
262
|
+
mask = paddle.full(shape, paddle.finfo(x.dtype).min, dtype=x.dtype)
|
263
|
+
mask = paddle.triu(mask, diagonal=1)
|
264
|
+
mask.stop_gradient = True
|
265
|
+
return mask
|
266
|
+
|
267
|
+
|
268
|
+
def parallel_matmul(
|
269
|
+
x: Tensor, y: Tensor, transpose_y=True, tensor_parallel_output=True
|
270
|
+
):
|
271
|
+
is_fleet_init = True
|
272
|
+
tensor_parallel_degree = 1
|
273
|
+
try:
|
274
|
+
hcg = fleet.get_hybrid_communicate_group()
|
275
|
+
model_parallel_group = hcg.get_model_parallel_group()
|
276
|
+
tensor_parallel_degree = hcg.get_model_parallel_world_size()
|
277
|
+
except:
|
278
|
+
is_fleet_init = False
|
279
|
+
|
280
|
+
if paddle.in_dynamic_mode():
|
281
|
+
y_is_distributed = y.is_distributed
|
282
|
+
else:
|
283
|
+
y_is_distributed = tensor_parallel_degree > 1
|
284
|
+
|
285
|
+
if is_fleet_init and tensor_parallel_degree > 1 and y_is_distributed:
|
286
|
+
|
287
|
+
input_parallel = paddle.distributed.collective._c_identity(
|
288
|
+
x, group=model_parallel_group
|
289
|
+
)
|
290
|
+
logits = paddle.matmul(input_parallel, y, transpose_y=transpose_y)
|
291
|
+
|
292
|
+
if tensor_parallel_output:
|
293
|
+
return logits
|
294
|
+
return paddle.distributed.collective._c_concat(
|
295
|
+
logits, group=model_parallel_group
|
296
|
+
)
|
297
|
+
|
298
|
+
else:
|
299
|
+
logits = paddle.matmul(x, y, transpose_y=transpose_y)
|
300
|
+
return logits
|
301
|
+
|
302
|
+
|
303
|
+
def _compute_default_rope_parameters(
|
304
|
+
config: Optional[PretrainedConfig] = None,
|
305
|
+
device: Optional["paddle.device"] = None,
|
306
|
+
seq_len: Optional[int] = None,
|
307
|
+
**rope_kwargs,
|
308
|
+
) -> Tuple["paddle.Tensor", float]:
|
309
|
+
"""
|
310
|
+
Computes the inverse frequencies according to the original RoPE implementation
|
311
|
+
Args:
|
312
|
+
config ([`~transformers.PretrainedConfig`]):
|
313
|
+
The model configuration.
|
314
|
+
device (`paddle.device`):
|
315
|
+
The device to use for initialization of the inverse frequencies.
|
316
|
+
seq_len (`int`, *optional*):
|
317
|
+
The current sequence length. Unused for this type of RoPE.
|
318
|
+
rope_kwargs (`Dict`, *optional*):
|
319
|
+
BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
|
320
|
+
Returns:
|
321
|
+
Tuple of (`paddle.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
322
|
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
323
|
+
"""
|
324
|
+
if config is not None and len(rope_kwargs) > 0:
|
325
|
+
raise ValueError(
|
326
|
+
"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
|
327
|
+
f"`_compute_default_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
|
328
|
+
)
|
329
|
+
if len(rope_kwargs) > 0:
|
330
|
+
base = rope_kwargs["base"]
|
331
|
+
dim = rope_kwargs["dim"]
|
332
|
+
elif config is not None:
|
333
|
+
base = config.rope_theta
|
334
|
+
partial_rotary_factor = (
|
335
|
+
config.partial_rotary_factor
|
336
|
+
if hasattr(config, "partial_rotary_factor")
|
337
|
+
else 1.0
|
338
|
+
)
|
339
|
+
head_dim = getattr(
|
340
|
+
config, "head_dim", config.hidden_size // config.num_attention_heads
|
341
|
+
)
|
342
|
+
dim = int(head_dim * partial_rotary_factor)
|
343
|
+
|
344
|
+
attention_factor = 1.0 # Unused in this type of RoPE
|
345
|
+
|
346
|
+
# Compute the inverse frequencies
|
347
|
+
inv_freq = 1.0 / (
|
348
|
+
base ** (paddle.arange(0, dim, 2, dtype="int64").astype("float32") / dim)
|
349
|
+
)
|
350
|
+
return inv_freq, attention_factor
|
351
|
+
|
352
|
+
|
353
|
+
ROPE_INIT_FUNCTIONS = {
|
354
|
+
"default": _compute_default_rope_parameters,
|
355
|
+
}
|
356
|
+
|
357
|
+
|
358
|
+
def _get_unpad_data(attention_mask):
|
359
|
+
seqlens_in_batch = attention_mask.sum(axis=-1, dtype="int32")
|
360
|
+
indices = paddle.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
361
|
+
max_seqlen_in_batch = seqlens_in_batch.max().item() # [2, 1, 1323]
|
362
|
+
cu_seqlens = F.pad(
|
363
|
+
paddle.cumsum(seqlens_in_batch, axis=0), (1, 0), data_format="NCL"
|
364
|
+
)
|
365
|
+
return (
|
366
|
+
indices,
|
367
|
+
cu_seqlens,
|
368
|
+
max_seqlen_in_batch,
|
369
|
+
)
|
370
|
+
|
371
|
+
|
372
|
+
def is_casual_mask(attention_mask):
|
373
|
+
"""
|
374
|
+
Upper triangular of attention_mask equals to attention_mask is casual
|
375
|
+
"""
|
376
|
+
return (paddle.triu(attention_mask) == attention_mask).all().item()
|
377
|
+
|
378
|
+
|
379
|
+
def _make_causal_mask(input_ids_shape, past_key_values_length):
|
380
|
+
"""
|
381
|
+
Make causal mask used for self-attention
|
382
|
+
"""
|
383
|
+
batch_size, target_length = input_ids_shape # target_length: seq_len
|
384
|
+
|
385
|
+
mask = paddle.tril(paddle.ones((target_length, target_length), dtype="bool"))
|
386
|
+
|
387
|
+
if past_key_values_length > 0:
|
388
|
+
# [tgt_len, tgt_len + past_len]
|
389
|
+
mask = paddle.concat(
|
390
|
+
[paddle.ones([target_length, past_key_values_length], dtype="bool"), mask],
|
391
|
+
axis=-1,
|
392
|
+
)
|
393
|
+
|
394
|
+
# [bs, 1, tgt_len, tgt_len + past_len]
|
395
|
+
return mask[None, None, :, :].expand(
|
396
|
+
[batch_size, 1, target_length, target_length + past_key_values_length]
|
397
|
+
)
|
398
|
+
|
399
|
+
|
400
|
+
def _expand_2d_mask(mask, dtype, tgt_length):
|
401
|
+
"""
|
402
|
+
Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`.
|
403
|
+
"""
|
404
|
+
batch_size, src_length = mask.shape[0], mask.shape[-1]
|
405
|
+
tgt_length = tgt_length if tgt_length is not None else src_length
|
406
|
+
|
407
|
+
mask = mask[:, None, None, :].astype("bool")
|
408
|
+
mask.stop_gradient = True
|
409
|
+
expanded_mask = mask.expand([batch_size, 1, tgt_length, src_length])
|
410
|
+
|
411
|
+
return expanded_mask
|
412
|
+
|
413
|
+
|
414
|
+
@dataclass
|
415
|
+
class Qwen2_5_VLCausalLMOutputWithPast(ModelOutput):
|
416
|
+
"""
|
417
|
+
Base class for Qwen2_5_VL causal language model (or autoregressive) outputs.
|
418
|
+
|
419
|
+
Args:
|
420
|
+
loss (`paddle.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
421
|
+
Language modeling loss (for next-token prediction).
|
422
|
+
logits (`paddle.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
423
|
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
424
|
+
past_key_values (`tuple(tuple(paddle.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
425
|
+
Tuple of `tuple(paddle.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
426
|
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
|
427
|
+
|
428
|
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
429
|
+
`past_key_values` input) to speed up sequential decoding.
|
430
|
+
hidden_states (`tuple(paddle.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
431
|
+
Tuple of `paddle.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
432
|
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
433
|
+
|
434
|
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
435
|
+
attentions (`tuple(paddle.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
436
|
+
Tuple of `paddle.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
437
|
+
sequence_length)`.
|
438
|
+
|
439
|
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
440
|
+
heads.
|
441
|
+
rope_deltas (`paddle.LongTensor` of shape `(batch_size, )`, *optional*):
|
442
|
+
The rope index difference between sequence length and multimodal rope.
|
443
|
+
"""
|
444
|
+
|
445
|
+
loss: Optional[paddle.Tensor] = None
|
446
|
+
logits: paddle.float32 = None
|
447
|
+
past_key_values: Optional[List[paddle.Tensor]] = None
|
448
|
+
hidden_states: Optional[Tuple[paddle.Tensor]] = None
|
449
|
+
attentions: Optional[Tuple[paddle.Tensor]] = None
|
450
|
+
rope_deltas: Optional[paddle.Tensor] = None
|
451
|
+
|
452
|
+
|
453
|
+
class Qwen2_5_VLRotaryEmbedding(nn.Layer):
|
454
|
+
def __init__(
|
455
|
+
self,
|
456
|
+
dim=None,
|
457
|
+
max_position_embeddings=2048,
|
458
|
+
base=10000,
|
459
|
+
device=None,
|
460
|
+
scaling_factor=1.0,
|
461
|
+
rope_type="default",
|
462
|
+
config: Optional[Qwen2_5_VLConfig] = None,
|
463
|
+
):
|
464
|
+
super().__init__()
|
465
|
+
# TODO (joao): remove the `if` below, only used for BC
|
466
|
+
self.rope_kwargs = {}
|
467
|
+
if config is None:
|
468
|
+
logging.warning_once(
|
469
|
+
"`Qwen2_5_VLRotaryEmbedding` can now be fully parameterized by passing the model config through the "
|
470
|
+
"`config` argument. All other arguments will be removed in v4.46"
|
471
|
+
)
|
472
|
+
self.rope_kwargs = {
|
473
|
+
"rope_type": rope_type,
|
474
|
+
"factor": scaling_factor,
|
475
|
+
"dim": dim,
|
476
|
+
"base": base,
|
477
|
+
"max_position_embeddings": max_position_embeddings,
|
478
|
+
}
|
479
|
+
self.rope_type = rope_type
|
480
|
+
self.max_seq_len_cached = max_position_embeddings
|
481
|
+
self.original_max_seq_len = max_position_embeddings
|
482
|
+
else:
|
483
|
+
# BC: "rope_type" was originally "type"
|
484
|
+
if config.rope_scaling is not None:
|
485
|
+
self.rope_type = config.rope_scaling.get(
|
486
|
+
"rope_type", config.rope_scaling.get("type")
|
487
|
+
)
|
488
|
+
else:
|
489
|
+
self.rope_type = "default"
|
490
|
+
self.max_seq_len_cached = config.max_position_embeddings
|
491
|
+
self.original_max_seq_len = config.max_position_embeddings
|
492
|
+
|
493
|
+
self.config = config
|
494
|
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
495
|
+
|
496
|
+
self.inv_freq, self.attention_scaling = self.rope_init_fn(
|
497
|
+
self.config, device, **self.rope_kwargs
|
498
|
+
)
|
499
|
+
self.original_inv_freq = self.inv_freq
|
500
|
+
|
501
|
+
self._set_cos_sin_cache(seq_len=max_position_embeddings)
|
502
|
+
|
503
|
+
def _set_cos_sin_cache(self, seq_len):
|
504
|
+
self.max_seq_len_cached = seq_len
|
505
|
+
# [seq_len]
|
506
|
+
t = paddle.arange(seq_len, dtype="float32")
|
507
|
+
# [seq_len, dim/2]
|
508
|
+
freqs = paddle.einsum("i,j->ij", t, self.inv_freq)
|
509
|
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
510
|
+
# [seq_len, dim]
|
511
|
+
emb = paddle.concat([freqs, freqs], axis=-1)
|
512
|
+
# [1, seqlen, 1, dim]
|
513
|
+
self.cos_cached = emb.cos()
|
514
|
+
self.sin_cached = emb.sin()
|
515
|
+
|
516
|
+
def _dynamic_frequency_update(self, position_ids, device):
|
517
|
+
"""
|
518
|
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
519
|
+
1 - growing beyond the cached sequence length (allow scaling)
|
520
|
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
521
|
+
"""
|
522
|
+
seq_len = paddle.max(position_ids) + 1
|
523
|
+
if seq_len > self.max_seq_len_cached: # growth
|
524
|
+
inv_freq, self.attention_scaling = self.rope_init_fn(
|
525
|
+
self.config, device, seq_len=seq_len, **self.rope_kwargs
|
526
|
+
)
|
527
|
+
self.inv_freq = inv_freq
|
528
|
+
self.max_seq_len_cached = seq_len
|
529
|
+
|
530
|
+
if (
|
531
|
+
seq_len < self.original_max_seq_len
|
532
|
+
and self.max_seq_len_cached > self.original_max_seq_len
|
533
|
+
): # reset
|
534
|
+
self.inv_freq = self.original_inv_freq
|
535
|
+
self.max_seq_len_cached = self.original_max_seq_len
|
536
|
+
|
537
|
+
@paddle.no_grad()
|
538
|
+
def forward(self, x, position_ids):
|
539
|
+
if "dynamic" in self.rope_type:
|
540
|
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
541
|
+
|
542
|
+
# Core RoPE block. In contrast to other models, Qwen2_VL has different position ids for thw grids
|
543
|
+
# So we expand the inv_freq to shape (3, ...)
|
544
|
+
inv_freq_expanded = (
|
545
|
+
self.inv_freq[None, None, :, None]
|
546
|
+
.astype("float32")
|
547
|
+
.expand([3, position_ids.shape[1], -1, 1])
|
548
|
+
)
|
549
|
+
position_ids_expanded = position_ids[:, :, None, :].astype(
|
550
|
+
"float32"
|
551
|
+
) # shape (3, bs, 1, positions)
|
552
|
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
553
|
+
device_type = paddle.get_device()
|
554
|
+
device_type = (
|
555
|
+
device_type
|
556
|
+
if isinstance(device_type, str) and device_type != "mps"
|
557
|
+
else "cpu"
|
558
|
+
)
|
559
|
+
with paddle.amp.auto_cast():
|
560
|
+
# Compute frequencies by matrix multiplication and transpose
|
561
|
+
# inv_freq_expanded shape: [3, bs, dim/2, 1]
|
562
|
+
# position_ids_expanded shape: [3, bs, 1, positions]
|
563
|
+
# Result shape after matmul: [3, bs, dim/2, positions]
|
564
|
+
# After transpose: [3, bs, positions, dim/2]
|
565
|
+
freqs = paddle.matmul(inv_freq_expanded, position_ids_expanded)
|
566
|
+
freqs = freqs.transpose([0, 1, 3, 2])
|
567
|
+
emb = paddle.concat((freqs, freqs), axis=-1)
|
568
|
+
cos = emb.cos()
|
569
|
+
sin = emb.sin()
|
570
|
+
|
571
|
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
572
|
+
cos = cos * self.attention_scaling
|
573
|
+
sin = sin * self.attention_scaling
|
574
|
+
|
575
|
+
return cos.astype(x.dtype), sin.astype(x.dtype)
|
576
|
+
|
577
|
+
|
578
|
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
579
|
+
def rotate_half(x):
|
580
|
+
"""Rotates half the hidden dims of the input."""
|
581
|
+
x1 = x[..., : x.shape[-1] // 2]
|
582
|
+
x2 = x[..., x.shape[-1] // 2 :]
|
583
|
+
return paddle.concat([-x2, x1], axis=-1) # shape is the same as x
|
584
|
+
|
585
|
+
|
586
|
+
def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
|
587
|
+
"""Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
|
588
|
+
|
589
|
+
Explanation:
|
590
|
+
Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
|
591
|
+
sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
|
592
|
+
vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
|
593
|
+
Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
|
594
|
+
For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
|
595
|
+
height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
|
596
|
+
difference with modern LLMs.
|
597
|
+
|
598
|
+
Args:
|
599
|
+
q (`paddle.Tensor`): The query tensor.
|
600
|
+
k (`paddle.Tensor`): The key tensor.
|
601
|
+
cos (`paddle.Tensor`): The cosine part of the rotary embedding.
|
602
|
+
sin (`paddle.Tensor`): The sine part of the rotary embedding.
|
603
|
+
position_ids (`paddle.Tensor`):
|
604
|
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
605
|
+
used to pass offsetted position ids when working with a KV-cache.
|
606
|
+
mrope_section(`List(int)`):
|
607
|
+
Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
|
608
|
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
609
|
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
610
|
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
611
|
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
612
|
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
613
|
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
614
|
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
615
|
+
Returns:
|
616
|
+
`tuple(paddle.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
617
|
+
"""
|
618
|
+
|
619
|
+
# cos = cos[position_ids]
|
620
|
+
# sin = sin[position_ids]
|
621
|
+
mrope_section = mrope_section * 2
|
622
|
+
cos = paddle.concat(
|
623
|
+
x=[m[i % 3] for i, m in enumerate(cos.split(mrope_section, axis=-1))], axis=-1
|
624
|
+
).unsqueeze(axis=unsqueeze_dim)
|
625
|
+
sin = paddle.concat(
|
626
|
+
x=[m[i % 3] for i, m in enumerate(sin.split(mrope_section, axis=-1))], axis=-1
|
627
|
+
).unsqueeze(axis=unsqueeze_dim)
|
628
|
+
|
629
|
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
630
|
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
631
|
+
return q_embed, k_embed
|
632
|
+
|
633
|
+
|
634
|
+
def apply_rotary_pos_emb_vision(
|
635
|
+
tensor: paddle.Tensor, freqs: paddle.Tensor
|
636
|
+
) -> paddle.Tensor:
|
637
|
+
orig_dtype = tensor.dtype
|
638
|
+
|
639
|
+
with paddle.amp.auto_cast(False):
|
640
|
+
tensor = tensor.astype(dtype="float32")
|
641
|
+
cos = freqs.cos()
|
642
|
+
sin = freqs.sin()
|
643
|
+
cos = (
|
644
|
+
cos.unsqueeze(1)
|
645
|
+
.tile(repeat_times=[1, 1, 2])
|
646
|
+
.unsqueeze(0)
|
647
|
+
.astype(dtype="float32")
|
648
|
+
)
|
649
|
+
sin = (
|
650
|
+
sin.unsqueeze(1)
|
651
|
+
.tile(repeat_times=[1, 1, 2])
|
652
|
+
.unsqueeze(0)
|
653
|
+
.astype(dtype="float32")
|
654
|
+
)
|
655
|
+
output = tensor * cos + rotate_half(tensor) * sin
|
656
|
+
output = paddle.cast(output, orig_dtype)
|
657
|
+
return output
|
658
|
+
|
659
|
+
|
660
|
+
class Qwen2_5_VisionRotaryEmbedding(nn.Layer):
|
661
|
+
def __init__(self, dim: int, theta: float = 10000.0) -> None:
|
662
|
+
super().__init__()
|
663
|
+
self.inv_freq = 1.0 / theta ** (
|
664
|
+
paddle.arange(start=0, end=dim, step=2, dtype="float32") / dim
|
665
|
+
)
|
666
|
+
|
667
|
+
def forward(self, seqlen: int) -> paddle.Tensor:
|
668
|
+
seq = paddle.arange(seqlen).cast(self.inv_freq.dtype)
|
669
|
+
freqs = paddle.outer(x=seq, y=self.inv_freq)
|
670
|
+
return freqs
|
671
|
+
|
672
|
+
|
673
|
+
class Qwen2_5_VisionPatchEmbed(nn.Layer):
|
674
|
+
def __init__(
|
675
|
+
self,
|
676
|
+
patch_size: int = 14,
|
677
|
+
temporal_patch_size: int = 2,
|
678
|
+
in_channels: int = 3,
|
679
|
+
embed_dim: int = 1152,
|
680
|
+
) -> None:
|
681
|
+
super().__init__()
|
682
|
+
self.patch_size = patch_size
|
683
|
+
self.temporal_patch_size = temporal_patch_size
|
684
|
+
self.in_channels = in_channels
|
685
|
+
self.embed_dim = embed_dim
|
686
|
+
|
687
|
+
kernel_size = [temporal_patch_size, patch_size, patch_size]
|
688
|
+
self.proj = nn.Conv3D(
|
689
|
+
in_channels,
|
690
|
+
embed_dim,
|
691
|
+
kernel_size=kernel_size,
|
692
|
+
stride=kernel_size,
|
693
|
+
bias_attr=False,
|
694
|
+
)
|
695
|
+
|
696
|
+
def forward(self, hidden_states: paddle.Tensor) -> paddle.Tensor:
|
697
|
+
|
698
|
+
target_dtype = self.proj.weight.dtype
|
699
|
+
hidden_states = hidden_states.reshape(
|
700
|
+
[
|
701
|
+
-1,
|
702
|
+
self.in_channels,
|
703
|
+
self.temporal_patch_size,
|
704
|
+
self.patch_size,
|
705
|
+
self.patch_size,
|
706
|
+
]
|
707
|
+
)
|
708
|
+
|
709
|
+
# NOTE(changwenbin): AttributeError: 'Variable' object has no attribute 'to'.
|
710
|
+
# hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).reshape([-1, self.embed_dim])
|
711
|
+
hidden_states = self.proj(
|
712
|
+
paddle.cast(hidden_states, dtype=target_dtype)
|
713
|
+
).reshape([-1, self.embed_dim])
|
714
|
+
return hidden_states
|
715
|
+
|
716
|
+
|
717
|
+
class Qwen2_5_VLPatchMerger(paddle.nn.Layer):
|
718
|
+
def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
|
719
|
+
super().__init__()
|
720
|
+
self.hidden_size = context_dim * (spatial_merge_size**2)
|
721
|
+
self.ln_q = Qwen2RMSNorm(context_dim, eps=1e-6)
|
722
|
+
self.mlp = nn.Sequential(
|
723
|
+
nn.Linear(self.hidden_size, self.hidden_size),
|
724
|
+
nn.GELU(),
|
725
|
+
nn.Linear(self.hidden_size, dim),
|
726
|
+
)
|
727
|
+
|
728
|
+
def forward(self, x: paddle.Tensor) -> paddle.Tensor:
|
729
|
+
x = self.mlp(self.ln_q(x).reshape([-1, self.hidden_size]))
|
730
|
+
return x
|
731
|
+
|
732
|
+
|
733
|
+
class Qwen2_5_VLMLP(paddle.nn.Layer):
|
734
|
+
def __init__(self, config, bias: bool = False):
|
735
|
+
super().__init__()
|
736
|
+
self.hidden_size = config.hidden_size
|
737
|
+
self.intermediate_size = config.intermediate_size
|
738
|
+
self.gate_proj = paddle.nn.Linear(
|
739
|
+
in_features=self.hidden_size,
|
740
|
+
out_features=self.intermediate_size,
|
741
|
+
bias_attr=bias,
|
742
|
+
)
|
743
|
+
self.up_proj = paddle.nn.Linear(
|
744
|
+
in_features=self.hidden_size,
|
745
|
+
out_features=self.intermediate_size,
|
746
|
+
bias_attr=bias,
|
747
|
+
)
|
748
|
+
self.down_proj = paddle.nn.Linear(
|
749
|
+
in_features=self.intermediate_size,
|
750
|
+
out_features=self.hidden_size,
|
751
|
+
bias_attr=bias,
|
752
|
+
)
|
753
|
+
self.act_fn = ACT2FN[config.hidden_act]
|
754
|
+
|
755
|
+
def forward(self, hidden_state):
|
756
|
+
return self.down_proj(
|
757
|
+
self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state)
|
758
|
+
)
|
759
|
+
|
760
|
+
|
761
|
+
class Qwen2_5_VLVisionAttention(nn.Layer):
|
762
|
+
def __init__(self, dim: int, num_heads: int = 16) -> None:
|
763
|
+
super().__init__()
|
764
|
+
self.num_heads = num_heads
|
765
|
+
self.qkv = nn.Linear(dim, dim * 3, bias_attr=True)
|
766
|
+
self.proj = nn.Linear(dim, dim)
|
767
|
+
self.head_dim = dim // num_heads # must added
|
768
|
+
|
769
|
+
def forward(
|
770
|
+
self,
|
771
|
+
hidden_states: paddle.Tensor,
|
772
|
+
cu_seqlens: paddle.Tensor,
|
773
|
+
rotary_pos_emb: paddle.Tensor = None,
|
774
|
+
) -> paddle.Tensor:
|
775
|
+
seq_length = hidden_states.shape[0]
|
776
|
+
q, k, v = (
|
777
|
+
self.qkv(hidden_states)
|
778
|
+
.reshape([seq_length, 3, self.num_heads, -1])
|
779
|
+
.transpose([1, 0, 2, 3])
|
780
|
+
.unbind(0)
|
781
|
+
)
|
782
|
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
783
|
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
784
|
+
|
785
|
+
attention_mask = paddle.zeros([1, seq_length, seq_length], dtype="bool")
|
786
|
+
for i in range(1, len(cu_seqlens)):
|
787
|
+
attention_mask[
|
788
|
+
...,
|
789
|
+
cu_seqlens[i - 1] : cu_seqlens[i],
|
790
|
+
cu_seqlens[i - 1] : cu_seqlens[i],
|
791
|
+
] = True
|
792
|
+
|
793
|
+
zero = paddle.zeros(attention_mask.shape, dtype=hidden_states.dtype)
|
794
|
+
neg_inf = paddle.full_like(
|
795
|
+
attention_mask,
|
796
|
+
paddle.finfo(hidden_states.dtype).min,
|
797
|
+
dtype=hidden_states.dtype,
|
798
|
+
)
|
799
|
+
attention_mask = paddle.where(attention_mask, zero, neg_inf)
|
800
|
+
|
801
|
+
q = q.transpose([1, 0, 2])
|
802
|
+
k = k.transpose([1, 0, 2])
|
803
|
+
v = v.transpose([1, 0, 2])
|
804
|
+
attn_weights = paddle.matmul(q, k.transpose([0, 2, 1])) / math.sqrt(
|
805
|
+
self.head_dim
|
806
|
+
)
|
807
|
+
attn_weights = attn_weights + attention_mask
|
808
|
+
attn_weights = nn.functional.softmax(attn_weights, axis=-1)
|
809
|
+
attn_output = paddle.matmul(attn_weights, v)
|
810
|
+
attn_output = attn_output.transpose([1, 0, 2])
|
811
|
+
attn_output = attn_output.reshape([seq_length, -1])
|
812
|
+
attn_output = self.proj(attn_output)
|
813
|
+
return attn_output
|
814
|
+
|
815
|
+
|
816
|
+
class Qwen2_5_VLVisionFlashAttention2(nn.Layer):
|
817
|
+
def __init__(self, dim: int, num_heads: int = 16) -> None:
|
818
|
+
super().__init__()
|
819
|
+
self.num_heads = num_heads
|
820
|
+
self.qkv = nn.Linear(dim, dim * 3, bias_attr=True)
|
821
|
+
self.proj = nn.Linear(dim, dim)
|
822
|
+
self.head_dim = dim // num_heads # must added
|
823
|
+
|
824
|
+
def forward(
|
825
|
+
self,
|
826
|
+
hidden_states: paddle.Tensor,
|
827
|
+
cu_seqlens: paddle.Tensor,
|
828
|
+
rotary_pos_emb: paddle.Tensor = None,
|
829
|
+
) -> paddle.Tensor:
|
830
|
+
seq_length = tuple(hidden_states.shape)[0]
|
831
|
+
qkv = (
|
832
|
+
self.qkv(hidden_states)
|
833
|
+
.reshape([seq_length, 3, self.num_heads, -1])
|
834
|
+
.transpose(perm=[1, 0, 2, 3])
|
835
|
+
)
|
836
|
+
q, k, v = qkv.unbind(axis=0)
|
837
|
+
q = apply_rotary_pos_emb_flashatt(q.unsqueeze(axis=0), rotary_pos_emb).squeeze(
|
838
|
+
axis=0
|
839
|
+
)
|
840
|
+
k = apply_rotary_pos_emb_flashatt(k.unsqueeze(axis=0), rotary_pos_emb).squeeze(
|
841
|
+
axis=0
|
842
|
+
)
|
843
|
+
max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
|
844
|
+
softmax_scale = self.head_dim**-0.5 # TODO: 需要手动加上
|
845
|
+
attn_output = (
|
846
|
+
flash_attn_varlen_func( # flash_attn_unpadded
|
847
|
+
q.astype("bfloat16"), # 不支持float32
|
848
|
+
k.astype("bfloat16"),
|
849
|
+
v.astype("bfloat16"),
|
850
|
+
cu_seqlens,
|
851
|
+
cu_seqlens,
|
852
|
+
max_seqlen,
|
853
|
+
max_seqlen,
|
854
|
+
scale=softmax_scale, # TODO: 需要手动加上
|
855
|
+
)[0]
|
856
|
+
.squeeze(0)
|
857
|
+
.reshape([seq_length, -1])
|
858
|
+
)
|
859
|
+
|
860
|
+
attn_output = self.proj(attn_output)
|
861
|
+
return attn_output
|
862
|
+
|
863
|
+
|
864
|
+
class Qwen2_5_VLVisionSdpaAttention(nn.Layer):
|
865
|
+
def __init__(self, dim: int, num_heads: int = 16) -> None:
|
866
|
+
super().__init__()
|
867
|
+
self.num_heads = num_heads
|
868
|
+
self.qkv = nn.Linear(dim, dim * 3, bias_attr=True)
|
869
|
+
self.proj = nn.Linear(dim, dim)
|
870
|
+
|
871
|
+
is_bfloat16_supported = paddle.amp.is_bfloat16_supported()
|
872
|
+
if is_bfloat16_supported:
|
873
|
+
self.compute_dtype = "bfloat16"
|
874
|
+
else:
|
875
|
+
self.compute_dtype = "float16"
|
876
|
+
|
877
|
+
def forward(
|
878
|
+
self,
|
879
|
+
hidden_states: paddle.Tensor,
|
880
|
+
cu_seqlens: paddle.Tensor,
|
881
|
+
rotary_pos_emb: paddle.Tensor = None,
|
882
|
+
) -> paddle.Tensor:
|
883
|
+
seq_length = hidden_states.shape[0]
|
884
|
+
q, k, v = (
|
885
|
+
self.qkv(hidden_states)
|
886
|
+
.reshape([seq_length, 3, self.num_heads, -1])
|
887
|
+
.transpose([1, 0, 2, 3])
|
888
|
+
.unbind(0)
|
889
|
+
)
|
890
|
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb)
|
891
|
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb)
|
892
|
+
attention_mask = paddle.zeros([1, 1, seq_length, seq_length], dtype="bool")
|
893
|
+
for i in range(1, len(cu_seqlens)):
|
894
|
+
attention_mask[
|
895
|
+
...,
|
896
|
+
cu_seqlens[i - 1] : cu_seqlens[i],
|
897
|
+
cu_seqlens[i - 1] : cu_seqlens[i],
|
898
|
+
] = True
|
899
|
+
|
900
|
+
zero = paddle.zeros(attention_mask.shape, dtype=hidden_states.dtype)
|
901
|
+
neg_inf = paddle.full_like(
|
902
|
+
attention_mask,
|
903
|
+
paddle.finfo(hidden_states.dtype).min,
|
904
|
+
dtype=hidden_states.dtype,
|
905
|
+
)
|
906
|
+
attention_mask = paddle.where(attention_mask, zero, neg_inf)
|
907
|
+
v = v.unsqueeze(0)
|
908
|
+
|
909
|
+
attn_output = paddle.nn.functional.scaled_dot_product_attention(
|
910
|
+
query=q.astype(self.compute_dtype),
|
911
|
+
key=k.astype(self.compute_dtype),
|
912
|
+
value=v.astype(self.compute_dtype),
|
913
|
+
attn_mask=attention_mask.astype(self.compute_dtype),
|
914
|
+
dropout_p=0.0,
|
915
|
+
)
|
916
|
+
|
917
|
+
attn_output = attn_output.transpose([1, 0, 2])
|
918
|
+
attn_output = attn_output.reshape([seq_length, -1])
|
919
|
+
attn_output = self.proj(attn_output)
|
920
|
+
|
921
|
+
return attn_output
|
922
|
+
|
923
|
+
|
924
|
+
QWEN2_5_VL_VISION_ATTENTION_CLASSES = {
|
925
|
+
"eager": Qwen2_5_VLVisionAttention,
|
926
|
+
"flash_attention_2": Qwen2_5_VLVisionFlashAttention2,
|
927
|
+
"sdpa": Qwen2_5_VLVisionSdpaAttention,
|
928
|
+
}
|
929
|
+
|
930
|
+
|
931
|
+
class Qwen2_5_VLVisionBlock(paddle.nn.Layer):
|
932
|
+
def __init__(self, config, attn_implementation: str = "sdpa") -> None:
|
933
|
+
super().__init__()
|
934
|
+
self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
|
935
|
+
self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
|
936
|
+
self.attn = QWEN2_5_VL_VISION_ATTENTION_CLASSES[attn_implementation](
|
937
|
+
config.hidden_size, num_heads=config.num_heads
|
938
|
+
)
|
939
|
+
|
940
|
+
self.mlp = Qwen2_5_VLMLP(config, bias=True)
|
941
|
+
|
942
|
+
def forward(self, hidden_states, cu_seqlens, rotary_pos_emb) -> paddle.Tensor:
|
943
|
+
hidden_states = hidden_states + self.attn(
|
944
|
+
self.norm1(hidden_states),
|
945
|
+
cu_seqlens=cu_seqlens,
|
946
|
+
rotary_pos_emb=rotary_pos_emb,
|
947
|
+
)
|
948
|
+
hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
|
949
|
+
return hidden_states
|
950
|
+
|
951
|
+
|
952
|
+
def apply_rotary_emb(tensor, cos, sin):
|
953
|
+
"""
|
954
|
+
Apply rotary position embedding to the input tensor.
|
955
|
+
Args:
|
956
|
+
tensor (paddle.Tensor): The input tensor of shape [batch_size, seq_len, num_heads, head_dim]
|
957
|
+
cos (paddle.Tensor): The cosine part of the rotary embedding [seq_len, head_dim/2]
|
958
|
+
sin (paddle.Tensor): The sine part of the rotary embedding [seq_len, head_dim/2]
|
959
|
+
Returns:
|
960
|
+
paddle.Tensor: The tensor after applying rotary embedding
|
961
|
+
"""
|
962
|
+
# Split the tensor into two halves along the last dimension
|
963
|
+
dim = tensor.shape[-1]
|
964
|
+
half_dim = dim // 2
|
965
|
+
tensor1 = tensor[..., :half_dim]
|
966
|
+
tensor2 = tensor[..., half_dim:]
|
967
|
+
|
968
|
+
# Reshape cos/sin for broadcasting
|
969
|
+
# From [seq_len, head_dim/2] to [1, seq_len, 1, head_dim/2]
|
970
|
+
cos = cos.unsqueeze(0).unsqueeze(2)
|
971
|
+
sin = sin.unsqueeze(0).unsqueeze(2)
|
972
|
+
|
973
|
+
# Apply rotary embedding
|
974
|
+
# tensor1/tensor2 shape: [batch_size, seq_len, num_heads, head_dim/2]
|
975
|
+
# cos/sin shape: [1, seq_len, 1, head_dim/2]
|
976
|
+
rotated = paddle.concat(
|
977
|
+
[tensor1 * cos - tensor2 * sin, tensor1 * sin + tensor2 * cos], axis=-1
|
978
|
+
)
|
979
|
+
|
980
|
+
return rotated
|
981
|
+
|
982
|
+
|
983
|
+
def apply_rotary_pos_emb_flashatt(
|
984
|
+
tensor: paddle.Tensor, freqs: paddle.Tensor
|
985
|
+
) -> paddle.Tensor:
|
986
|
+
tensor_ = tensor.astype(dtype="float32")
|
987
|
+
cos = freqs.cos()
|
988
|
+
sin = freqs.sin()
|
989
|
+
output = apply_rotary_emb(tensor_, cos, sin).astype(dtype=tensor.dtype)
|
990
|
+
return output
|
991
|
+
|
992
|
+
|
993
|
+
# Copied from transformers.models.qwen2.modeling_qwen2.Qwen2RMSNorm
|
994
|
+
class Qwen2RMSNorm(nn.Layer):
|
995
|
+
def __init__(self, hidden_size, eps=1e-6):
|
996
|
+
"""
|
997
|
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
998
|
+
"""
|
999
|
+
super().__init__()
|
1000
|
+
self.weight = paddle.create_parameter(
|
1001
|
+
shape=[hidden_size],
|
1002
|
+
dtype=paddle.get_default_dtype(),
|
1003
|
+
default_initializer=nn.initializer.Constant(1.0),
|
1004
|
+
)
|
1005
|
+
self.variance_epsilon = eps
|
1006
|
+
|
1007
|
+
def forward(self, hidden_states):
|
1008
|
+
if paddle.in_dynamic_mode():
|
1009
|
+
with paddle.amp.auto_cast(False):
|
1010
|
+
variance = hidden_states.astype("float32").pow(2).mean(-1, keepdim=True)
|
1011
|
+
hidden_states = (
|
1012
|
+
paddle.rsqrt(variance + self.variance_epsilon) * hidden_states
|
1013
|
+
)
|
1014
|
+
else:
|
1015
|
+
variance = hidden_states.astype("float32").pow(2).mean(-1, keepdim=True)
|
1016
|
+
hidden_states = (
|
1017
|
+
paddle.rsqrt(variance + self.variance_epsilon) * hidden_states
|
1018
|
+
)
|
1019
|
+
|
1020
|
+
if self.weight.dtype in [paddle.float16, paddle.bfloat16]:
|
1021
|
+
hidden_states = paddle.cast(hidden_states, self.weight.dtype)
|
1022
|
+
return hidden_states * self.weight
|
1023
|
+
|
1024
|
+
|
1025
|
+
class Qwen2MLP(nn.Layer):
|
1026
|
+
def __init__(self, config):
|
1027
|
+
super().__init__()
|
1028
|
+
self.hidden_size = config.hidden_size
|
1029
|
+
self.intermediate_size = config.intermediate_size
|
1030
|
+
self.fuse_attention_ffn = config.fuse_attention_ffn
|
1031
|
+
self.tensor_parallel_degree = config.tensor_parallel_degree
|
1032
|
+
|
1033
|
+
if config.tensor_parallel_degree > 1:
|
1034
|
+
|
1035
|
+
self.gate_proj = ColumnParallelLinear(
|
1036
|
+
self.hidden_size,
|
1037
|
+
self.intermediate_size,
|
1038
|
+
gather_output=False,
|
1039
|
+
has_bias=False,
|
1040
|
+
)
|
1041
|
+
self.up_proj = ColumnParallelLinear(
|
1042
|
+
self.hidden_size,
|
1043
|
+
self.intermediate_size,
|
1044
|
+
gather_output=False,
|
1045
|
+
has_bias=False,
|
1046
|
+
)
|
1047
|
+
self.down_proj = RowParallelLinear(
|
1048
|
+
self.intermediate_size,
|
1049
|
+
self.hidden_size,
|
1050
|
+
input_is_parallel=True,
|
1051
|
+
has_bias=False,
|
1052
|
+
)
|
1053
|
+
else:
|
1054
|
+
if get_device_type() == "xpu":
|
1055
|
+
self.gate_proj = nn.Linear(
|
1056
|
+
self.hidden_size, self.intermediate_size, bias_attr=False
|
1057
|
+
) # w1
|
1058
|
+
self.up_proj = nn.Linear(
|
1059
|
+
self.hidden_size, self.intermediate_size, bias_attr=False
|
1060
|
+
) # w3
|
1061
|
+
self.down_proj = nn.Linear(
|
1062
|
+
self.intermediate_size, self.hidden_size, bias_attr=False
|
1063
|
+
) # w2
|
1064
|
+
else:
|
1065
|
+
self.gate_proj = Linear(
|
1066
|
+
self.hidden_size, self.intermediate_size, bias_attr=False
|
1067
|
+
) # w1
|
1068
|
+
self.up_proj = Linear(
|
1069
|
+
self.hidden_size, self.intermediate_size, bias_attr=False
|
1070
|
+
) # w3
|
1071
|
+
self.down_proj = Linear(
|
1072
|
+
self.intermediate_size, self.hidden_size, bias_attr=False
|
1073
|
+
) # w2
|
1074
|
+
|
1075
|
+
self.act_fn = ACT2FN[config.hidden_act]
|
1076
|
+
self.fuse_swiglu = False
|
1077
|
+
|
1078
|
+
def forward(self, x):
|
1079
|
+
x, y = self.gate_proj(x), self.up_proj(x)
|
1080
|
+
if self.fuse_swiglu:
|
1081
|
+
x = self.act_fn(x, y)
|
1082
|
+
else:
|
1083
|
+
x = self.act_fn(x) * y
|
1084
|
+
|
1085
|
+
return self.down_proj(x)
|
1086
|
+
|
1087
|
+
|
1088
|
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
1089
|
+
def repeat_kv(hidden_states: paddle.Tensor, n_rep: int) -> paddle.Tensor:
|
1090
|
+
"""
|
1091
|
+
This is the equivalent of paddle.repeat_interleave(x, axis=1, repeats=n_rep). The hidden states go from (batch,
|
1092
|
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
1093
|
+
"""
|
1094
|
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
1095
|
+
if n_rep == 1:
|
1096
|
+
return hidden_states
|
1097
|
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
1098
|
+
[batch, num_key_value_heads, n_rep, slen, head_dim]
|
1099
|
+
)
|
1100
|
+
return hidden_states.reshape([batch, num_key_value_heads * n_rep, slen, head_dim])
|
1101
|
+
|
1102
|
+
|
1103
|
+
class Qwen2_5_VLAttention(paddle.nn.Layer):
|
1104
|
+
"""
|
1105
|
+
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
1106
|
+
and "Generating Long Sequences with Sparse Transformers".
|
1107
|
+
"""
|
1108
|
+
|
1109
|
+
def __init__(self, config: Qwen2_5_VLConfig, layer_idx: Optional[int] = None):
|
1110
|
+
super().__init__()
|
1111
|
+
self.config = config
|
1112
|
+
self.layer_idx = layer_idx
|
1113
|
+
if layer_idx is None:
|
1114
|
+
logging.warning_once(
|
1115
|
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
1116
|
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
1117
|
+
"when creating this class."
|
1118
|
+
)
|
1119
|
+
|
1120
|
+
self.hidden_size = config.hidden_size
|
1121
|
+
self.num_heads = config.num_attention_heads
|
1122
|
+
self.head_dim = self.hidden_size // self.num_heads
|
1123
|
+
self.num_key_value_heads = config.num_key_value_heads
|
1124
|
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
1125
|
+
self.max_position_embeddings = config.max_position_embeddings
|
1126
|
+
self.rope_theta = config.rope_theta
|
1127
|
+
self.is_causal = True
|
1128
|
+
self.attention_dropout = config.attention_dropout
|
1129
|
+
self.rope_scaling = config.rope_scaling
|
1130
|
+
# self.sequence_parallel = config.sequence_parallel
|
1131
|
+
|
1132
|
+
if config.tensor_parallel_degree > 1:
|
1133
|
+
assert (
|
1134
|
+
self.num_heads % config.tensor_parallel_degree == 0
|
1135
|
+
), f"num_heads: {self.num_heads}, tensor_parallel_degree: {config.tensor_parallel_degree}"
|
1136
|
+
self.num_heads = self.num_heads // config.tensor_parallel_degree
|
1137
|
+
|
1138
|
+
assert (
|
1139
|
+
self.num_key_value_heads % config.tensor_parallel_degree == 0
|
1140
|
+
), f"num_key_value_heads: {self.num_key_value_heads}, tensor_parallel_degree: {config.tensor_parallel_degree}"
|
1141
|
+
self.num_key_value_heads = (
|
1142
|
+
self.num_key_value_heads // config.tensor_parallel_degree
|
1143
|
+
)
|
1144
|
+
|
1145
|
+
if config.tensor_parallel_degree > 1:
|
1146
|
+
self.q_proj = ColumnParallelLinear(
|
1147
|
+
self.hidden_size, self.hidden_size, has_bias=True, gather_output=False
|
1148
|
+
)
|
1149
|
+
self.k_proj = ColumnParallelLinear(self.hidden_size, self.config.num_key_value_heads * self.head_dim, has_bias=True, gather_output=False) # fmt:skip
|
1150
|
+
self.v_proj = ColumnParallelLinear(self.hidden_size, self.config.num_key_value_heads * self.head_dim, has_bias=True, gather_output=False) # fmt:skip
|
1151
|
+
self.o_proj = RowParallelLinear(
|
1152
|
+
self.hidden_size,
|
1153
|
+
self.hidden_size,
|
1154
|
+
has_bias=False,
|
1155
|
+
input_is_parallel=True,
|
1156
|
+
)
|
1157
|
+
else:
|
1158
|
+
self.q_proj = Linear(self.hidden_size, self.hidden_size, bias_attr=True)
|
1159
|
+
self.k_proj = Linear(
|
1160
|
+
self.hidden_size,
|
1161
|
+
self.config.num_key_value_heads * self.head_dim,
|
1162
|
+
bias_attr=True,
|
1163
|
+
)
|
1164
|
+
self.v_proj = Linear(
|
1165
|
+
self.hidden_size,
|
1166
|
+
self.config.num_key_value_heads * self.head_dim,
|
1167
|
+
bias_attr=True,
|
1168
|
+
)
|
1169
|
+
self.o_proj = Linear(self.hidden_size, self.hidden_size, bias_attr=False)
|
1170
|
+
|
1171
|
+
self.rotary_emb = Qwen2_5_VLRotaryEmbedding(
|
1172
|
+
self.head_dim,
|
1173
|
+
max_position_embeddings=self.max_position_embeddings,
|
1174
|
+
base=self.rope_theta,
|
1175
|
+
)
|
1176
|
+
|
1177
|
+
def forward(
|
1178
|
+
self,
|
1179
|
+
hidden_states: paddle.Tensor,
|
1180
|
+
attention_mask: Optional[paddle.Tensor] = None,
|
1181
|
+
position_ids: Optional[paddle.Tensor] = None,
|
1182
|
+
past_key_value: Optional[Tuple[paddle.Tensor]] = None, # Cache
|
1183
|
+
output_attentions: bool = False,
|
1184
|
+
use_cache: bool = False, # default true
|
1185
|
+
cache_position: Optional[paddle.Tensor] = None,
|
1186
|
+
) -> Tuple[paddle.Tensor, Optional[paddle.Tensor], Optional[Tuple[paddle.Tensor]]]:
|
1187
|
+
bsz, q_len, _ = hidden_states.shape
|
1188
|
+
|
1189
|
+
try:
|
1190
|
+
query_states = self.q_proj(hidden_states)
|
1191
|
+
key_states = self.k_proj(hidden_states)
|
1192
|
+
value_states = self.v_proj(hidden_states)
|
1193
|
+
except:
|
1194
|
+
hidden_states = hidden_states.astype(self.config.dtype)
|
1195
|
+
query_states = self.q_proj(hidden_states)
|
1196
|
+
key_states = self.k_proj(hidden_states)
|
1197
|
+
value_states = self.v_proj(hidden_states)
|
1198
|
+
|
1199
|
+
target_query_shape = [0, 0, self.num_heads, self.head_dim]
|
1200
|
+
target_key_value_shape = [0, 0, self.num_key_value_heads, self.head_dim]
|
1201
|
+
query_states = query_states.reshape(shape=target_query_shape)
|
1202
|
+
key_states = key_states.reshape(shape=target_key_value_shape)
|
1203
|
+
value_states = value_states.reshape(shape=target_key_value_shape)
|
1204
|
+
|
1205
|
+
new_perm = [0, 2, 1, 3]
|
1206
|
+
query_states = query_states.transpose(new_perm)
|
1207
|
+
key_states = key_states.transpose(new_perm)
|
1208
|
+
value_states = value_states.transpose(new_perm)
|
1209
|
+
|
1210
|
+
kv_seq_len = key_states.shape[
|
1211
|
+
-2
|
1212
|
+
] # q_len ######## [bs, num_head, seq_len, head_dim] # qwen2是 [-3]
|
1213
|
+
if past_key_value is not None:
|
1214
|
+
kv_seq_len += cache_position[0] + 1
|
1215
|
+
# kv_seq_len += past_key_value[0].shape[-2] # qwen2是 [-3]
|
1216
|
+
|
1217
|
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
1218
|
+
query_states, key_states = apply_multimodal_rotary_pos_emb(
|
1219
|
+
query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
|
1220
|
+
)
|
1221
|
+
|
1222
|
+
# [bs, num_head, seq_len, head_dim]
|
1223
|
+
if past_key_value is not None:
|
1224
|
+
# cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
1225
|
+
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
1226
|
+
key_states = paddle.concat(
|
1227
|
+
[past_key_value[0], key_states], axis=2
|
1228
|
+
) # qwen2是 axis=1, qwen2_vl是 axis=2
|
1229
|
+
value_states = paddle.concat(
|
1230
|
+
[past_key_value[1], value_states], axis=2
|
1231
|
+
) # qwen2是 axis=1
|
1232
|
+
past_key_value = (key_states, value_states) if use_cache else None
|
1233
|
+
|
1234
|
+
# repeat k/v heads if n_kv_heads < n_heads
|
1235
|
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
1236
|
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
1237
|
+
|
1238
|
+
query_states = query_states.astype("float32")
|
1239
|
+
key_states = key_states.astype("float32")
|
1240
|
+
value_states = value_states.astype("float32")
|
1241
|
+
|
1242
|
+
attn_weights = paddle.matmul(
|
1243
|
+
query_states, key_states.transpose([0, 1, 3, 2])
|
1244
|
+
) / math.sqrt(self.head_dim)
|
1245
|
+
|
1246
|
+
if attention_mask is not None:
|
1247
|
+
attn_weights = attn_weights + attention_mask
|
1248
|
+
attn_weights = nn.functional.softmax(attn_weights, axis=-1)
|
1249
|
+
attn_weights = nn.functional.dropout(
|
1250
|
+
x=attn_weights, p=self.attention_dropout, training=self.training
|
1251
|
+
)
|
1252
|
+
attn_output = paddle.matmul(
|
1253
|
+
attn_weights.cast(self.config.dtype), value_states.cast(self.config.dtype)
|
1254
|
+
)
|
1255
|
+
|
1256
|
+
if attn_output.shape != [bsz, self.num_heads, q_len, self.head_dim]:
|
1257
|
+
raise ValueError(
|
1258
|
+
f"`attn_output` should be of size {(bsz, q_len, self.num_heads, self.head_dim)}, but is"
|
1259
|
+
f" {attn_output.shape}"
|
1260
|
+
)
|
1261
|
+
|
1262
|
+
attn_output = attn_output.transpose([0, 2, 1, 3])
|
1263
|
+
attn_output = attn_output.reshape([bsz, q_len, -1])
|
1264
|
+
attn_output = self.o_proj(attn_output)
|
1265
|
+
if not output_attentions:
|
1266
|
+
attn_weights = None
|
1267
|
+
return attn_output, attn_weights, past_key_value
|
1268
|
+
|
1269
|
+
|
1270
|
+
class Qwen2_5_VLFlashAttention2(Qwen2_5_VLAttention):
|
1271
|
+
"""
|
1272
|
+
Qwen2_5_VL flash attention module, following Qwen2_5_VL attention module. This module inherits from `Qwen2_5_VLAttention`
|
1273
|
+
as the weights of the module stays untouched. The only required change would be on the forward pass
|
1274
|
+
where it needs to correctly call the public API of flash attention and deal with padding tokens
|
1275
|
+
in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
|
1276
|
+
config.max_window_layers layers.
|
1277
|
+
"""
|
1278
|
+
|
1279
|
+
def __init__(self, *args, **kwargs):
|
1280
|
+
super().__init__(*args, **kwargs)
|
1281
|
+
|
1282
|
+
def forward(
|
1283
|
+
self,
|
1284
|
+
hidden_states: paddle.Tensor,
|
1285
|
+
attention_mask: Optional[paddle.Tensor] = None,
|
1286
|
+
position_ids: Optional[paddle.Tensor] = None,
|
1287
|
+
past_key_value: Optional[Tuple[paddle.Tensor]] = None, # Cache
|
1288
|
+
output_attentions: bool = False,
|
1289
|
+
use_cache: bool = False, # default true
|
1290
|
+
cache_position: Optional[paddle.Tensor] = None,
|
1291
|
+
) -> Tuple[paddle.Tensor, Optional[paddle.Tensor], Optional[Tuple[paddle.Tensor]]]:
|
1292
|
+
bsz, q_len, _ = tuple(hidden_states.shape)
|
1293
|
+
try:
|
1294
|
+
query_states = self.q_proj(hidden_states)
|
1295
|
+
key_states = self.k_proj(hidden_states)
|
1296
|
+
value_states = self.v_proj(hidden_states)
|
1297
|
+
except:
|
1298
|
+
hidden_states = hidden_states.astype("bfloat16")
|
1299
|
+
query_states = self.q_proj(hidden_states)
|
1300
|
+
key_states = self.k_proj(hidden_states)
|
1301
|
+
value_states = self.v_proj(hidden_states)
|
1302
|
+
|
1303
|
+
target_query_shape = [0, 0, self.num_heads, self.head_dim]
|
1304
|
+
target_key_value_shape = [0, 0, self.num_key_value_heads, self.head_dim]
|
1305
|
+
query_states = query_states.reshape(shape=target_query_shape)
|
1306
|
+
key_states = key_states.reshape(shape=target_key_value_shape)
|
1307
|
+
value_states = value_states.reshape(shape=target_key_value_shape)
|
1308
|
+
|
1309
|
+
new_perm = [0, 2, 1, 3]
|
1310
|
+
# [1, 3599, 1536] [bsz, q_len, self.num_heads * self.head_dim]
|
1311
|
+
query_states = query_states.transpose(new_perm)
|
1312
|
+
key_states = key_states.transpose(new_perm)
|
1313
|
+
value_states = value_states.transpose(new_perm)
|
1314
|
+
|
1315
|
+
kv_seq_len = key_states.shape[
|
1316
|
+
-2
|
1317
|
+
] # q_len ######## [bs, num_head, seq_len, head_dim] # qwen2是 [-3]
|
1318
|
+
if past_key_value is not None:
|
1319
|
+
kv_seq_len += cache_position[0] + 1
|
1320
|
+
|
1321
|
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
1322
|
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
1323
|
+
query_states, key_states = apply_multimodal_rotary_pos_emb(
|
1324
|
+
query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
|
1325
|
+
)
|
1326
|
+
|
1327
|
+
if past_key_value is not None:
|
1328
|
+
# cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
1329
|
+
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
1330
|
+
key_states = paddle.concat(
|
1331
|
+
[past_key_value[0], key_states], axis=2
|
1332
|
+
) # qwen2是 axis=1, qwen2_vl是 axis=2
|
1333
|
+
value_states = paddle.concat(
|
1334
|
+
[past_key_value[1], value_states], axis=2
|
1335
|
+
) # qwen2是 axis=1
|
1336
|
+
past_key_value = (key_states, value_states) if use_cache else None
|
1337
|
+
|
1338
|
+
# repeat k/v heads if n_kv_heads < n_heads
|
1339
|
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
1340
|
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
1341
|
+
|
1342
|
+
# Reashape to the expected shape for Flash Attention
|
1343
|
+
# [1, 3599, 12, 128]
|
1344
|
+
query_states = query_states.transpose(perm=[0, 2, 1, 3])
|
1345
|
+
key_states = key_states.transpose(perm=[0, 2, 1, 3])
|
1346
|
+
value_states = value_states.transpose(perm=[0, 2, 1, 3])
|
1347
|
+
|
1348
|
+
attn_output = self._flash_attention_forward(
|
1349
|
+
query_states,
|
1350
|
+
key_states,
|
1351
|
+
value_states,
|
1352
|
+
attention_mask,
|
1353
|
+
q_len,
|
1354
|
+
# dropout=0.0 if not self.training else self.attention_dropout,
|
1355
|
+
# causal=self.is_causal,
|
1356
|
+
)
|
1357
|
+
|
1358
|
+
attn_output = attn_output.reshape([bsz, q_len, -1])
|
1359
|
+
attn_output = self.o_proj(attn_output)
|
1360
|
+
if not output_attentions:
|
1361
|
+
attn_weights = None
|
1362
|
+
return attn_output, attn_weights, past_key_value
|
1363
|
+
|
1364
|
+
def _flash_attention_forward(
|
1365
|
+
self,
|
1366
|
+
query_states,
|
1367
|
+
key_states,
|
1368
|
+
value_states,
|
1369
|
+
attention_mask,
|
1370
|
+
query_length,
|
1371
|
+
dropout=0.0,
|
1372
|
+
softmax_scale=None,
|
1373
|
+
):
|
1374
|
+
"""
|
1375
|
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
1376
|
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
1377
|
+
|
1378
|
+
Args:
|
1379
|
+
query_states (`paddle.Tensor`):
|
1380
|
+
Input query states to be passed to Flash Attention API
|
1381
|
+
key_states (`paddle.Tensor`):
|
1382
|
+
Input key states to be passed to Flash Attention API
|
1383
|
+
value_states (`paddle.Tensor`):
|
1384
|
+
Input value states to be passed to Flash Attention API
|
1385
|
+
attention_mask (`paddle.Tensor`):
|
1386
|
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
1387
|
+
position of padding tokens and 1 for the position of non-padding tokens.
|
1388
|
+
dropout (`int`, *optional*):
|
1389
|
+
Attention dropout
|
1390
|
+
softmax_scale (`float`, *optional*):
|
1391
|
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
1392
|
+
"""
|
1393
|
+
# Contains at least one padding token in the sequence
|
1394
|
+
causal = self.is_causal and query_length != 1
|
1395
|
+
head_dim = query_states.shape[-1]
|
1396
|
+
softmax_scale = head_dim**-0.5 # TODO: 需要手动加上
|
1397
|
+
|
1398
|
+
if attention_mask is not None: # attention_mask.shape # [2, 1, 1323, 1323]
|
1399
|
+
batch_size = query_states.shape[0] # [2, 1323, 12, 128]
|
1400
|
+
(
|
1401
|
+
query_states,
|
1402
|
+
key_states,
|
1403
|
+
value_states,
|
1404
|
+
indices_q,
|
1405
|
+
cu_seq_lens,
|
1406
|
+
max_seq_lens,
|
1407
|
+
) = self._unpad_input(
|
1408
|
+
query_states, key_states, value_states, attention_mask, query_length
|
1409
|
+
)
|
1410
|
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
1411
|
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
1412
|
+
|
1413
|
+
attn_output_unpad = flash_attn_varlen_func( # TODO: flash_attn_unpadded
|
1414
|
+
query_states, # [5998, 16, 128]
|
1415
|
+
key_states, # [5998, 8, 128]
|
1416
|
+
value_states, # [5998, 8, 128]
|
1417
|
+
cu_seqlens_q=cu_seqlens_q,
|
1418
|
+
cu_seqlens_k=cu_seqlens_k,
|
1419
|
+
max_seqlen_q=max_seqlen_in_batch_q,
|
1420
|
+
max_seqlen_k=max_seqlen_in_batch_k,
|
1421
|
+
scale=softmax_scale, # not softmax_scale=
|
1422
|
+
dropout=dropout,
|
1423
|
+
causal=causal,
|
1424
|
+
)[0]
|
1425
|
+
|
1426
|
+
attn_output = pad_input(
|
1427
|
+
attn_output_unpad, indices_q, batch_size, query_length
|
1428
|
+
)
|
1429
|
+
else:
|
1430
|
+
attn_output = flash_attn_func(
|
1431
|
+
query_states,
|
1432
|
+
key_states,
|
1433
|
+
value_states,
|
1434
|
+
dropout,
|
1435
|
+
causal=causal, # no softmax_scale=
|
1436
|
+
)[0]
|
1437
|
+
|
1438
|
+
# # 修改这里的维度转换,考虑并行策略下的维度
|
1439
|
+
# batch_size = query_states.shape[0]
|
1440
|
+
# hidden_size = self.num_heads * self.head_dim # 计算实际的 hidden_size
|
1441
|
+
# attn_output = attn_output.reshape([batch_size, query_length, hidden_size])
|
1442
|
+
|
1443
|
+
return attn_output
|
1444
|
+
|
1445
|
+
def _unpad_input(
|
1446
|
+
self, query_layer, key_layer, value_layer, attention_mask, query_length
|
1447
|
+
):
|
1448
|
+
# Note: This function was named _upad_input() in paddle transformers/modeling_flash_attention_utils.py
|
1449
|
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
1450
|
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
1451
|
+
|
1452
|
+
# TODO:cuda error
|
1453
|
+
key_layer = index_first_axis(
|
1454
|
+
key_layer.reshape([batch_size * kv_seq_len, num_key_value_heads, head_dim]),
|
1455
|
+
indices_k,
|
1456
|
+
)
|
1457
|
+
value_layer = index_first_axis(
|
1458
|
+
value_layer.reshape(
|
1459
|
+
[batch_size * kv_seq_len, num_key_value_heads, head_dim]
|
1460
|
+
),
|
1461
|
+
indices_k,
|
1462
|
+
)
|
1463
|
+
|
1464
|
+
if query_length == kv_seq_len:
|
1465
|
+
query_layer = index_first_axis(
|
1466
|
+
query_layer.reshape(
|
1467
|
+
[batch_size * kv_seq_len, self.num_heads, head_dim]
|
1468
|
+
),
|
1469
|
+
indices_k,
|
1470
|
+
)
|
1471
|
+
cu_seqlens_q = cu_seqlens_k
|
1472
|
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
1473
|
+
indices_q = indices_k
|
1474
|
+
elif query_length == 1:
|
1475
|
+
max_seqlen_in_batch_q = 1
|
1476
|
+
cu_seqlens_q = paddle.arange(
|
1477
|
+
batch_size + 1, dtype=paddle.int32
|
1478
|
+
) # There is a memcpy here, that is very bad.
|
1479
|
+
indices_q = cu_seqlens_q[:-1]
|
1480
|
+
query_layer = query_layer.squeeze(1)
|
1481
|
+
else:
|
1482
|
+
# The -q_len: slice assumes left padding.
|
1483
|
+
attention_mask = attention_mask[:, -query_length:]
|
1484
|
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
|
1485
|
+
query_layer, attention_mask
|
1486
|
+
)
|
1487
|
+
|
1488
|
+
return (
|
1489
|
+
query_layer,
|
1490
|
+
key_layer,
|
1491
|
+
value_layer,
|
1492
|
+
indices_q.to(paddle.int64),
|
1493
|
+
(cu_seqlens_q, cu_seqlens_k),
|
1494
|
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
1495
|
+
)
|
1496
|
+
|
1497
|
+
|
1498
|
+
class Qwen2_5_VLSdpaAttention(Qwen2_5_VLAttention):
|
1499
|
+
"""
|
1500
|
+
Qwen2 attention module using paddle.nn.functional.scaled_dot_product_attention. This module inherits from
|
1501
|
+
`Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
1502
|
+
SDPA API.
|
1503
|
+
"""
|
1504
|
+
|
1505
|
+
def forward(
|
1506
|
+
self,
|
1507
|
+
hidden_states: paddle.Tensor,
|
1508
|
+
attention_mask: Optional[paddle.Tensor] = None,
|
1509
|
+
position_ids: Optional[paddle.Tensor] = None,
|
1510
|
+
past_key_value: Optional[Tuple[paddle.Tensor]] = None,
|
1511
|
+
output_attentions: bool = False,
|
1512
|
+
use_cache: bool = False,
|
1513
|
+
cache_position: Optional[paddle.Tensor] = None,
|
1514
|
+
position_embeddings: Optional[Tuple[paddle.Tensor, paddle.Tensor]] = None,
|
1515
|
+
) -> Tuple[paddle.Tensor, Optional[paddle.Tensor], Optional[Tuple[paddle.Tensor]]]:
|
1516
|
+
if output_attentions:
|
1517
|
+
logging.warning_once(
|
1518
|
+
'Qwen2_5_VLModel is using Qwen2_5_VLSdpaAttention, but `paddle.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
1519
|
+
)
|
1520
|
+
return super().forward(
|
1521
|
+
hidden_states=hidden_states,
|
1522
|
+
attention_mask=attention_mask,
|
1523
|
+
position_ids=position_ids,
|
1524
|
+
past_key_value=past_key_value,
|
1525
|
+
output_attentions=output_attentions,
|
1526
|
+
use_cache=use_cache,
|
1527
|
+
cache_position=cache_position,
|
1528
|
+
position_embeddings=position_embeddings,
|
1529
|
+
)
|
1530
|
+
bsz, q_len, _ = hidden_states.shape
|
1531
|
+
|
1532
|
+
try:
|
1533
|
+
query_states = self.q_proj(hidden_states)
|
1534
|
+
key_states = self.k_proj(hidden_states)
|
1535
|
+
value_states = self.v_proj(hidden_states)
|
1536
|
+
except:
|
1537
|
+
hidden_states = hidden_states.astype(self.config.dtype)
|
1538
|
+
query_states = self.q_proj(hidden_states)
|
1539
|
+
key_states = self.k_proj(hidden_states)
|
1540
|
+
value_states = self.v_proj(hidden_states)
|
1541
|
+
|
1542
|
+
target_query_shape = [0, 0, self.num_heads, self.head_dim]
|
1543
|
+
target_key_value_shape = [0, 0, self.num_key_value_heads, self.head_dim]
|
1544
|
+
query_states = query_states.reshape(shape=target_query_shape)
|
1545
|
+
key_states = key_states.reshape(shape=target_key_value_shape)
|
1546
|
+
value_states = value_states.reshape(shape=target_key_value_shape)
|
1547
|
+
|
1548
|
+
new_perm = [0, 2, 1, 3]
|
1549
|
+
query_states = query_states.transpose(new_perm)
|
1550
|
+
key_states = key_states.transpose(new_perm)
|
1551
|
+
value_states = value_states.transpose(new_perm)
|
1552
|
+
|
1553
|
+
kv_seq_len = key_states.shape[
|
1554
|
+
-2
|
1555
|
+
] # q_len ######## [bs, num_head, seq_len, head_dim] # qwen2是 [-3]
|
1556
|
+
if past_key_value is not None:
|
1557
|
+
kv_seq_len += cache_position[0] + 1
|
1558
|
+
# kv_seq_len += past_key_value[0].shape[-2] # qwen2是 [-3]
|
1559
|
+
|
1560
|
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
1561
|
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
1562
|
+
query_states, key_states = apply_multimodal_rotary_pos_emb(
|
1563
|
+
query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
|
1564
|
+
)
|
1565
|
+
|
1566
|
+
if past_key_value is not None:
|
1567
|
+
# cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
1568
|
+
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
1569
|
+
key_states = paddle.concat(
|
1570
|
+
[past_key_value[0], key_states], axis=2
|
1571
|
+
) # qwen2是 axis=1, qwen2_vl是 axis=2
|
1572
|
+
value_states = paddle.concat(
|
1573
|
+
[past_key_value[1], value_states], axis=2
|
1574
|
+
) # qwen2是 axis=1
|
1575
|
+
past_key_value = (key_states, value_states) if use_cache else None
|
1576
|
+
|
1577
|
+
# repeat k/v heads if n_kv_heads < n_heads
|
1578
|
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
1579
|
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
1580
|
+
|
1581
|
+
# Reashape to the expected shape for Flash Attention
|
1582
|
+
# [1, 3599, 12, 128]
|
1583
|
+
query_states = query_states.transpose(perm=[0, 2, 1, 3])
|
1584
|
+
key_states = key_states.transpose(perm=[0, 2, 1, 3])
|
1585
|
+
value_states = value_states.transpose(perm=[0, 2, 1, 3])
|
1586
|
+
|
1587
|
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
1588
|
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
1589
|
+
# to infer the attention mask.
|
1590
|
+
attention_mask = None
|
1591
|
+
causal_mask = attention_mask
|
1592
|
+
# Convert attention mask slicing
|
1593
|
+
if attention_mask is not None:
|
1594
|
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-3]]
|
1595
|
+
|
1596
|
+
# Ensure contiguous tensors for PaddlePaddle
|
1597
|
+
if query_states.place.is_gpu_place() and attention_mask is not None:
|
1598
|
+
query_states = query_states.contiguous()
|
1599
|
+
key_states = key_states.contiguous()
|
1600
|
+
value_states = value_states.contiguous()
|
1601
|
+
|
1602
|
+
# Determine if the operation is causal
|
1603
|
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
1604
|
+
|
1605
|
+
attn_output = paddle.nn.functional.scaled_dot_product_attention(
|
1606
|
+
query_states,
|
1607
|
+
key_states,
|
1608
|
+
value_states,
|
1609
|
+
attn_mask=causal_mask,
|
1610
|
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
1611
|
+
is_causal=is_causal,
|
1612
|
+
)
|
1613
|
+
|
1614
|
+
attn_output = attn_output.reshape([bsz, q_len, -1])
|
1615
|
+
|
1616
|
+
# Apply the output projection
|
1617
|
+
attn_output = self.o_proj(attn_output)
|
1618
|
+
|
1619
|
+
return attn_output, None, past_key_value
|
1620
|
+
|
1621
|
+
|
1622
|
+
QWEN2_5_VL_ATTENTION_CLASSES = {
|
1623
|
+
"eager": Qwen2_5_VLAttention,
|
1624
|
+
"flash_attention_2": Qwen2_5_VLFlashAttention2,
|
1625
|
+
"sdpa": Qwen2_5_VLSdpaAttention,
|
1626
|
+
}
|
1627
|
+
|
1628
|
+
|
1629
|
+
class Qwen2_5_VLDecoderLayer(nn.Layer):
|
1630
|
+
def __init__(self, config: Qwen2_5_VLConfig, layer_idx: int):
|
1631
|
+
super().__init__()
|
1632
|
+
self.hidden_size = config.hidden_size
|
1633
|
+
# use_sliding_window false
|
1634
|
+
if (
|
1635
|
+
config.use_sliding_window
|
1636
|
+
and config.attn_implementation != "flash_attention_2"
|
1637
|
+
):
|
1638
|
+
logging.warning_once(
|
1639
|
+
f"Sliding Window Attention is enabled but not implemented for `{config.attn_implementation}`; "
|
1640
|
+
"unexpected results may be encountered."
|
1641
|
+
)
|
1642
|
+
self.self_attn = QWEN2_5_VL_ATTENTION_CLASSES[config._attn_implementation](
|
1643
|
+
config, layer_idx
|
1644
|
+
)
|
1645
|
+
self.mlp = Qwen2MLP(config)
|
1646
|
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1647
|
+
self.post_attention_layernorm = Qwen2RMSNorm(
|
1648
|
+
config.hidden_size, eps=config.rms_norm_eps
|
1649
|
+
)
|
1650
|
+
|
1651
|
+
def forward(
|
1652
|
+
self,
|
1653
|
+
hidden_states: paddle.Tensor,
|
1654
|
+
attention_mask: Optional[paddle.Tensor] = None,
|
1655
|
+
position_ids: Optional[paddle.Tensor] = None,
|
1656
|
+
past_key_value: Optional[Tuple[paddle.Tensor]] = None,
|
1657
|
+
output_attentions: Optional[bool] = False,
|
1658
|
+
use_cache: Optional[bool] = False,
|
1659
|
+
cache_position: Optional[paddle.Tensor] = None,
|
1660
|
+
**kwargs,
|
1661
|
+
):
|
1662
|
+
"""
|
1663
|
+
Args:
|
1664
|
+
hidden_states (`paddle.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
1665
|
+
attention_mask (`paddle.FloatTensor`, *optional*): attention mask of size
|
1666
|
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
1667
|
+
output_attentions (`bool`, *optional*):
|
1668
|
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
1669
|
+
returned tensors for more detail.
|
1670
|
+
use_cache (`bool`, *optional*):
|
1671
|
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
1672
|
+
(see `past_key_values`).
|
1673
|
+
past_key_value (`Tuple(paddle.FloatTensor)`, *optional*): cached past key and value projection states
|
1674
|
+
cache_position (`paddle.LongTensor` of shape `(sequence_length)`, *optional*):
|
1675
|
+
Indices depicting the position of the input sequence tokens in the sequence.
|
1676
|
+
position_embeddings (`Tuple[paddle.FloatTensor, paddle.FloatTensor]`, *optional*):
|
1677
|
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
1678
|
+
with `head_dim` being the embedding dimension of each attention head.
|
1679
|
+
kwargs (`dict`, *optional*):
|
1680
|
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
1681
|
+
into the model
|
1682
|
+
"""
|
1683
|
+
residual = hidden_states
|
1684
|
+
|
1685
|
+
hidden_states = self.input_layernorm(hidden_states)
|
1686
|
+
# Self Attention
|
1687
|
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
1688
|
+
hidden_states=hidden_states,
|
1689
|
+
attention_mask=attention_mask,
|
1690
|
+
position_ids=position_ids,
|
1691
|
+
past_key_value=past_key_value,
|
1692
|
+
output_attentions=output_attentions,
|
1693
|
+
use_cache=use_cache,
|
1694
|
+
cache_position=cache_position,
|
1695
|
+
)
|
1696
|
+
hidden_states = residual + hidden_states
|
1697
|
+
|
1698
|
+
# Fully Connected
|
1699
|
+
residual = hidden_states
|
1700
|
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
1701
|
+
hidden_states = self.mlp(hidden_states)
|
1702
|
+
hidden_states = residual + hidden_states
|
1703
|
+
|
1704
|
+
outputs = (hidden_states,)
|
1705
|
+
|
1706
|
+
if output_attentions:
|
1707
|
+
outputs += (self_attn_weights,)
|
1708
|
+
|
1709
|
+
if use_cache:
|
1710
|
+
outputs += (present_key_value,)
|
1711
|
+
|
1712
|
+
return outputs
|
1713
|
+
|
1714
|
+
|
1715
|
+
class Qwen2_5_VLPreTrainedModel(PretrainedModel):
|
1716
|
+
config_class = Qwen2_5_VLConfig
|
1717
|
+
base_model_prefix = "model"
|
1718
|
+
_no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
|
1719
|
+
_skip_keys_device_placement = "past_key_values"
|
1720
|
+
|
1721
|
+
def _init_weights(self, layer):
|
1722
|
+
std = 0.2
|
1723
|
+
if isinstance(layer, (nn.Linear, nn.Conv3D)):
|
1724
|
+
nn.initializer.Normal(mean=0.0, std=std)(layer.weight)
|
1725
|
+
if layer.bias is not None:
|
1726
|
+
nn.initializer.Constant(0.0)(layer.bias)
|
1727
|
+
elif isinstance(layer, nn.Embedding):
|
1728
|
+
nn.initializer.Normal(mean=0.0, std=std)(layer.weight)
|
1729
|
+
if layer._padding_idx is not None:
|
1730
|
+
with paddle.no_grad():
|
1731
|
+
layer.weight[layer._padding_idx] = 0.0
|
1732
|
+
|
1733
|
+
|
1734
|
+
class Qwen2_5_VisionTransformerPretrainedModel(Qwen2_5_VLPreTrainedModel):
|
1735
|
+
config_class = Qwen2_5_VLVisionConfig
|
1736
|
+
_no_split_modules = ["Qwen2_5_VLVisionBlock"]
|
1737
|
+
|
1738
|
+
def __init__(self, config, *inputs, **kwargs) -> None:
|
1739
|
+
super().__init__(config, *inputs, **kwargs)
|
1740
|
+
self.spatial_merge_size = config.spatial_merge_size
|
1741
|
+
|
1742
|
+
self.patch_size = config.patch_size
|
1743
|
+
self.fullatt_block_indexes = config.fullatt_block_indexes
|
1744
|
+
self.window_size = config.window_size
|
1745
|
+
self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
|
1746
|
+
self.patch_embed = Qwen2_5_VisionPatchEmbed(
|
1747
|
+
patch_size=config.patch_size,
|
1748
|
+
temporal_patch_size=config.temporal_patch_size,
|
1749
|
+
in_channels=config.in_channels,
|
1750
|
+
embed_dim=config.hidden_size,
|
1751
|
+
)
|
1752
|
+
head_dim = config.hidden_size // config.num_heads
|
1753
|
+
self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2)
|
1754
|
+
self.blocks = nn.LayerList(
|
1755
|
+
sublayers=[
|
1756
|
+
Qwen2_5_VLVisionBlock(config, config._attn_implementation)
|
1757
|
+
for _ in range(config.depth)
|
1758
|
+
]
|
1759
|
+
)
|
1760
|
+
self.merger = Qwen2_5_VLPatchMerger(
|
1761
|
+
dim=config.out_hidden_size,
|
1762
|
+
context_dim=config.hidden_size,
|
1763
|
+
spatial_merge_size=config.spatial_merge_size,
|
1764
|
+
)
|
1765
|
+
self.enable_recompute = False
|
1766
|
+
|
1767
|
+
def rot_pos_emb(self, grid_thw):
|
1768
|
+
pos_ids = []
|
1769
|
+
for t, h, w in grid_thw:
|
1770
|
+
hpos_ids = paddle.arange(h).unsqueeze(1).expand([-1, w])
|
1771
|
+
hpos_ids = hpos_ids.reshape(
|
1772
|
+
[
|
1773
|
+
h // self.spatial_merge_size,
|
1774
|
+
self.spatial_merge_size,
|
1775
|
+
w // self.spatial_merge_size,
|
1776
|
+
self.spatial_merge_size,
|
1777
|
+
]
|
1778
|
+
)
|
1779
|
+
hpos_ids = hpos_ids.transpose(perm=[0, 2, 1, 3])
|
1780
|
+
hpos_ids = hpos_ids.flatten()
|
1781
|
+
|
1782
|
+
wpos_ids = paddle.arange(w).unsqueeze(0).expand([h, -1])
|
1783
|
+
wpos_ids = wpos_ids.reshape(
|
1784
|
+
[
|
1785
|
+
h // self.spatial_merge_size,
|
1786
|
+
self.spatial_merge_size,
|
1787
|
+
w // self.spatial_merge_size,
|
1788
|
+
self.spatial_merge_size,
|
1789
|
+
]
|
1790
|
+
)
|
1791
|
+
wpos_ids = wpos_ids.transpose([0, 2, 1, 3])
|
1792
|
+
wpos_ids = wpos_ids.flatten()
|
1793
|
+
pos_ids.append(
|
1794
|
+
paddle.stack(x=[hpos_ids, wpos_ids], axis=-1).tile(repeat_times=[t, 1])
|
1795
|
+
)
|
1796
|
+
pos_ids = paddle.concat(x=pos_ids, axis=0)
|
1797
|
+
max_grid_size = grid_thw[:, 1:].max()
|
1798
|
+
rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
|
1799
|
+
rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(start_axis=1)
|
1800
|
+
return rotary_pos_emb
|
1801
|
+
|
1802
|
+
def get_window_index(self, grid_thw):
|
1803
|
+
window_index: list = []
|
1804
|
+
cu_window_seqlens: list = [0]
|
1805
|
+
window_index_id = 0
|
1806
|
+
vit_merger_window_size = (
|
1807
|
+
self.window_size // self.spatial_merge_size // self.patch_size
|
1808
|
+
)
|
1809
|
+
for grid_t, grid_h, grid_w in grid_thw:
|
1810
|
+
llm_grid_h, llm_grid_w = (
|
1811
|
+
grid_h // self.spatial_merge_size,
|
1812
|
+
grid_w // self.spatial_merge_size,
|
1813
|
+
)
|
1814
|
+
index = paddle.arange(end=grid_t * llm_grid_h * llm_grid_w).reshape(
|
1815
|
+
[grid_t, llm_grid_h, llm_grid_w]
|
1816
|
+
)
|
1817
|
+
pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size
|
1818
|
+
pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size
|
1819
|
+
num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size
|
1820
|
+
num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size
|
1821
|
+
index_padded = paddle.nn.functional.pad(
|
1822
|
+
x=index,
|
1823
|
+
pad=(0, pad_w, 0, pad_h),
|
1824
|
+
mode="constant",
|
1825
|
+
value=-100,
|
1826
|
+
pad_from_left_axis=False,
|
1827
|
+
)
|
1828
|
+
index_padded = index_padded.reshape(
|
1829
|
+
[
|
1830
|
+
grid_t,
|
1831
|
+
num_windows_h,
|
1832
|
+
vit_merger_window_size,
|
1833
|
+
num_windows_w,
|
1834
|
+
vit_merger_window_size,
|
1835
|
+
]
|
1836
|
+
)
|
1837
|
+
index_padded = index_padded.transpose(perm=[0, 1, 3, 2, 4]).reshape(
|
1838
|
+
[
|
1839
|
+
grid_t,
|
1840
|
+
num_windows_h * num_windows_w,
|
1841
|
+
vit_merger_window_size,
|
1842
|
+
vit_merger_window_size,
|
1843
|
+
]
|
1844
|
+
)
|
1845
|
+
seqlens = (index_padded != -100).sum(axis=[2, 3]).reshape([-1])
|
1846
|
+
index_padded = index_padded.reshape([-1])
|
1847
|
+
index_new = index_padded[index_padded != -100]
|
1848
|
+
window_index.append(index_new + window_index_id)
|
1849
|
+
cu_seqlens_tmp = (
|
1850
|
+
seqlens.cumsum(axis=0) * self.spatial_merge_unit + cu_window_seqlens[-1]
|
1851
|
+
)
|
1852
|
+
cu_window_seqlens.extend(cu_seqlens_tmp.tolist())
|
1853
|
+
window_index_id += (grid_t * llm_grid_h * llm_grid_w).item()
|
1854
|
+
window_index = paddle.concat(x=window_index, axis=0)
|
1855
|
+
return window_index, cu_window_seqlens
|
1856
|
+
|
1857
|
+
@paddle.jit.not_to_static
|
1858
|
+
def recompute_training_full(
|
1859
|
+
self,
|
1860
|
+
layer_module: nn.Layer,
|
1861
|
+
hidden_states: paddle.Tensor,
|
1862
|
+
cu_seqlens_now: paddle.Tensor,
|
1863
|
+
rotary_pos_emb: paddle.Tensor,
|
1864
|
+
):
|
1865
|
+
def create_custom_forward(module):
|
1866
|
+
def custom_forward(*inputs):
|
1867
|
+
return module(*inputs)
|
1868
|
+
|
1869
|
+
return custom_forward
|
1870
|
+
|
1871
|
+
hidden_states = recompute(
|
1872
|
+
create_custom_forward(layer_module),
|
1873
|
+
hidden_states,
|
1874
|
+
cu_seqlens_now,
|
1875
|
+
rotary_pos_emb,
|
1876
|
+
# use_reentrant=self.config.recompute_use_reentrant,
|
1877
|
+
)
|
1878
|
+
return hidden_states
|
1879
|
+
|
1880
|
+
def forward(
|
1881
|
+
self, hidden_states: paddle.Tensor, grid_thw: paddle.Tensor
|
1882
|
+
) -> paddle.Tensor:
|
1883
|
+
"""
|
1884
|
+
Args:
|
1885
|
+
hidden_states (`paddle.Tensor` of shape `(batch_size, seq_len, hidden_size)`):
|
1886
|
+
The final hidden states of the model.
|
1887
|
+
grid_thw (`paddle.Tensor` of shape `(num_images_or_videos, 3)`):
|
1888
|
+
The temporal, height and width of feature shape of each image in LLM.
|
1889
|
+
|
1890
|
+
Returns:
|
1891
|
+
`paddle.Tensor`: hidden_states.
|
1892
|
+
"""
|
1893
|
+
hidden_states = self.patch_embed(hidden_states)
|
1894
|
+
rotary_pos_emb = self.rot_pos_emb(grid_thw)
|
1895
|
+
window_index, cu_window_seqlens = self.get_window_index(grid_thw)
|
1896
|
+
cu_window_seqlens = paddle.to_tensor(
|
1897
|
+
data=cu_window_seqlens, dtype="int32", place=hidden_states.place
|
1898
|
+
)
|
1899
|
+
cu_window_seqlens = paddle.unique_consecutive(x=cu_window_seqlens)
|
1900
|
+
seq_len, _ = tuple(hidden_states.shape)
|
1901
|
+
hidden_states = hidden_states.reshape(
|
1902
|
+
[seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1]
|
1903
|
+
)
|
1904
|
+
hidden_states = hidden_states[window_index, :, :]
|
1905
|
+
hidden_states = hidden_states.reshape([seq_len, -1])
|
1906
|
+
rotary_pos_emb = rotary_pos_emb.reshape(
|
1907
|
+
[seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1]
|
1908
|
+
)
|
1909
|
+
rotary_pos_emb = rotary_pos_emb[window_index, :, :]
|
1910
|
+
rotary_pos_emb = rotary_pos_emb.reshape([seq_len, -1])
|
1911
|
+
|
1912
|
+
cu_seqlens = paddle.repeat_interleave(
|
1913
|
+
grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]
|
1914
|
+
).cumsum(axis=0, dtype="int32")
|
1915
|
+
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
|
1916
|
+
|
1917
|
+
for layer_num, blk in enumerate(self.blocks):
|
1918
|
+
if layer_num in self.fullatt_block_indexes:
|
1919
|
+
cu_seqlens_now = cu_seqlens
|
1920
|
+
else:
|
1921
|
+
cu_seqlens_now = cu_window_seqlens
|
1922
|
+
if self.enable_recompute and self.training:
|
1923
|
+
hidden_states = self.recompute_training_full(
|
1924
|
+
blk, hidden_states, cu_seqlens_now, rotary_pos_emb
|
1925
|
+
)
|
1926
|
+
else:
|
1927
|
+
hidden_states = blk(
|
1928
|
+
hidden_states,
|
1929
|
+
cu_seqlens=cu_seqlens_now,
|
1930
|
+
rotary_pos_emb=rotary_pos_emb,
|
1931
|
+
)
|
1932
|
+
|
1933
|
+
hidden_states = self.merger(hidden_states)
|
1934
|
+
reverse_indices = paddle.argsort(x=window_index)
|
1935
|
+
hidden_states = hidden_states[reverse_indices, :]
|
1936
|
+
|
1937
|
+
return hidden_states
|
1938
|
+
|
1939
|
+
|
1940
|
+
class Qwen2_5_VLModel(Qwen2_5_VLPreTrainedModel):
|
1941
|
+
def __init__(self, config: Qwen2_5_VLConfig):
|
1942
|
+
super().__init__(config)
|
1943
|
+
self.padding_idx = config.pad_token_id
|
1944
|
+
self.vocab_size = config.vocab_size
|
1945
|
+
self.hidden_size = config.hidden_size
|
1946
|
+
self.config = config
|
1947
|
+
# Recompute defaults to False and is controlled by Trainer
|
1948
|
+
|
1949
|
+
if (
|
1950
|
+
config.tensor_parallel_degree > 1
|
1951
|
+
and config.vocab_size % config.tensor_parallel_degree == 0
|
1952
|
+
):
|
1953
|
+
self.embed_tokens = mpu.VocabParallelEmbedding(
|
1954
|
+
self.vocab_size,
|
1955
|
+
self.hidden_size,
|
1956
|
+
weight_attr=paddle.ParamAttr(initializer=nn.initializer.XavierNormal()),
|
1957
|
+
)
|
1958
|
+
else:
|
1959
|
+
self.embed_tokens = nn.Embedding(
|
1960
|
+
self.vocab_size,
|
1961
|
+
self.hidden_size,
|
1962
|
+
)
|
1963
|
+
|
1964
|
+
# self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
1965
|
+
self.layers = nn.LayerList(
|
1966
|
+
[
|
1967
|
+
Qwen2_5_VLDecoderLayer(config, layer_idx)
|
1968
|
+
for layer_idx in range(config.num_hidden_layers)
|
1969
|
+
]
|
1970
|
+
)
|
1971
|
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1972
|
+
|
1973
|
+
self.enable_recompute = False
|
1974
|
+
|
1975
|
+
def get_input_embeddings(self):
|
1976
|
+
return self.embed_tokens
|
1977
|
+
|
1978
|
+
def set_input_embeddings(self, value):
|
1979
|
+
self.embed_tokens = value
|
1980
|
+
|
1981
|
+
@staticmethod
|
1982
|
+
def _prepare_decoder_attention_mask(
|
1983
|
+
attention_mask, input_shape, past_key_values_length, dtype
|
1984
|
+
):
|
1985
|
+
if attention_mask is not None:
|
1986
|
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
1987
|
+
if len(attention_mask.shape) == 2:
|
1988
|
+
expanded_attn_mask = _expand_2d_mask(
|
1989
|
+
attention_mask, dtype, tgt_length=input_shape[-1]
|
1990
|
+
)
|
1991
|
+
# For decoding phase in generation, seq_length = 1, we don't need to add causal mask
|
1992
|
+
if input_shape[-1] > 1:
|
1993
|
+
combined_attention_mask = _make_causal_mask(
|
1994
|
+
input_shape,
|
1995
|
+
past_key_values_length=past_key_values_length,
|
1996
|
+
)
|
1997
|
+
expanded_attn_mask = expanded_attn_mask & combined_attention_mask
|
1998
|
+
# [bsz, seq_len, seq_len] -> [bsz, 1, seq_len, seq_len]
|
1999
|
+
elif len(attention_mask.shape) == 3:
|
2000
|
+
expanded_attn_mask = attention_mask.unsqueeze(1).astype("bool")
|
2001
|
+
# if attention_mask is already 4-D, do nothing
|
2002
|
+
else:
|
2003
|
+
expanded_attn_mask = attention_mask
|
2004
|
+
else:
|
2005
|
+
expanded_attn_mask = _make_causal_mask(
|
2006
|
+
input_shape,
|
2007
|
+
past_key_values_length=past_key_values_length,
|
2008
|
+
)
|
2009
|
+
# Convert bool attention_mask to float attention mask, which will be added to attention_scores later
|
2010
|
+
expanded_attn_mask = paddle.where(
|
2011
|
+
expanded_attn_mask, 0.0, paddle.finfo(dtype).min
|
2012
|
+
).astype(dtype)
|
2013
|
+
return expanded_attn_mask
|
2014
|
+
|
2015
|
+
@paddle.jit.not_to_static
|
2016
|
+
def recompute_training_full(
|
2017
|
+
self,
|
2018
|
+
layer_module: nn.Layer,
|
2019
|
+
hidden_states: paddle.Tensor,
|
2020
|
+
position_ids: Optional[paddle.Tensor],
|
2021
|
+
attention_mask: paddle.Tensor,
|
2022
|
+
output_attentions: bool,
|
2023
|
+
past_key_value: paddle.Tensor,
|
2024
|
+
use_cache: bool,
|
2025
|
+
cache_position: Optional[paddle.Tensor] = None,
|
2026
|
+
):
|
2027
|
+
def create_custom_forward(module):
|
2028
|
+
def custom_forward(*inputs):
|
2029
|
+
return module(*inputs)
|
2030
|
+
|
2031
|
+
return custom_forward
|
2032
|
+
|
2033
|
+
hidden_states = recompute(
|
2034
|
+
create_custom_forward(layer_module),
|
2035
|
+
hidden_states,
|
2036
|
+
position_ids,
|
2037
|
+
attention_mask,
|
2038
|
+
output_attentions,
|
2039
|
+
past_key_value,
|
2040
|
+
use_cache,
|
2041
|
+
cache_position,
|
2042
|
+
use_reentrant=self.config.recompute_use_reentrant,
|
2043
|
+
)
|
2044
|
+
|
2045
|
+
return hidden_states
|
2046
|
+
|
2047
|
+
def forward(
|
2048
|
+
self,
|
2049
|
+
input_ids: paddle.Tensor = None,
|
2050
|
+
attention_mask: Optional[paddle.Tensor] = None,
|
2051
|
+
position_ids: Optional[paddle.Tensor] = None,
|
2052
|
+
past_key_values: Optional[List[paddle.Tensor]] = None,
|
2053
|
+
inputs_embeds: Optional[paddle.Tensor] = None,
|
2054
|
+
use_cache: Optional[bool] = None,
|
2055
|
+
output_attentions: Optional[bool] = None,
|
2056
|
+
output_hidden_states: Optional[bool] = None,
|
2057
|
+
return_dict: Optional[bool] = None,
|
2058
|
+
cache_position: Optional[paddle.Tensor] = None,
|
2059
|
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
2060
|
+
output_attentions = (
|
2061
|
+
output_attentions
|
2062
|
+
if output_attentions is not None
|
2063
|
+
else self.config.output_attentions
|
2064
|
+
)
|
2065
|
+
output_hidden_states = (
|
2066
|
+
output_hidden_states
|
2067
|
+
if output_hidden_states is not None
|
2068
|
+
else self.config.output_hidden_states
|
2069
|
+
)
|
2070
|
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
2071
|
+
|
2072
|
+
return_dict = (
|
2073
|
+
return_dict if return_dict is not None else self.config.use_return_dict
|
2074
|
+
)
|
2075
|
+
|
2076
|
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
2077
|
+
raise ValueError(
|
2078
|
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
2079
|
+
)
|
2080
|
+
elif input_ids is not None:
|
2081
|
+
batch_size, seq_length = input_ids.shape
|
2082
|
+
elif inputs_embeds is not None:
|
2083
|
+
batch_size, seq_length, _ = inputs_embeds.shape
|
2084
|
+
else:
|
2085
|
+
raise ValueError(
|
2086
|
+
"You have to specify either decoder_input_ids or decoder_inputs_embeds"
|
2087
|
+
)
|
2088
|
+
|
2089
|
+
if past_key_values is None:
|
2090
|
+
past_key_values = tuple([None] * len(self.layers))
|
2091
|
+
# NOTE: to make cache can be clear in-time
|
2092
|
+
past_key_values = list(past_key_values)
|
2093
|
+
|
2094
|
+
seq_length_with_past = seq_length
|
2095
|
+
cache_length = 0
|
2096
|
+
if past_key_values[0] is not None:
|
2097
|
+
cache_length = past_key_values[0][0].shape[2] # shape[1] in qwen2
|
2098
|
+
seq_length_with_past += cache_length
|
2099
|
+
|
2100
|
+
if inputs_embeds is None:
|
2101
|
+
inputs_embeds = self.embed_tokens(input_ids)
|
2102
|
+
|
2103
|
+
# embed positions
|
2104
|
+
if attention_mask is None:
|
2105
|
+
# [bs, seq_len]
|
2106
|
+
attention_mask = paddle.ones(
|
2107
|
+
(batch_size, seq_length_with_past), dtype=paddle.bool
|
2108
|
+
)
|
2109
|
+
|
2110
|
+
if self.config._attn_implementation == "flash_attention_2":
|
2111
|
+
causal_mask = attention_mask
|
2112
|
+
else:
|
2113
|
+
causal_mask = self._prepare_decoder_attention_mask(
|
2114
|
+
attention_mask,
|
2115
|
+
(batch_size, seq_length),
|
2116
|
+
cache_length,
|
2117
|
+
inputs_embeds.dtype,
|
2118
|
+
) # [bs, 1, seq_len, seq_len]
|
2119
|
+
|
2120
|
+
if cache_position is None:
|
2121
|
+
past_seen_tokens = (
|
2122
|
+
past_key_values[0][0].shape[2] if past_key_values[0] is not None else 0
|
2123
|
+
)
|
2124
|
+
cache_position = paddle.arange(
|
2125
|
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1]
|
2126
|
+
)
|
2127
|
+
|
2128
|
+
if position_ids is None:
|
2129
|
+
# the hard coded `3` is for temporal, height and width.
|
2130
|
+
position_ids = cache_position.reshape([1, 1, -1]).expand(
|
2131
|
+
[3, inputs_embeds.shape[0], -1]
|
2132
|
+
)
|
2133
|
+
|
2134
|
+
hidden_states = inputs_embeds
|
2135
|
+
|
2136
|
+
# decoder layers
|
2137
|
+
all_hidden_states = () if output_hidden_states else None
|
2138
|
+
all_self_attns = () if output_attentions else None
|
2139
|
+
next_decoder_cache = ()
|
2140
|
+
|
2141
|
+
for idx, (decoder_layer) in enumerate(self.layers):
|
2142
|
+
if output_hidden_states:
|
2143
|
+
all_hidden_states += (hidden_states,)
|
2144
|
+
past_key_value = (
|
2145
|
+
past_key_values[idx] if past_key_values is not None else None
|
2146
|
+
)
|
2147
|
+
|
2148
|
+
if self.enable_recompute and self.training:
|
2149
|
+
layer_outputs = self.recompute_training_full(
|
2150
|
+
decoder_layer,
|
2151
|
+
hidden_states,
|
2152
|
+
causal_mask,
|
2153
|
+
position_ids,
|
2154
|
+
past_key_value,
|
2155
|
+
output_attentions,
|
2156
|
+
use_cache,
|
2157
|
+
cache_position,
|
2158
|
+
)
|
2159
|
+
else:
|
2160
|
+
layer_outputs = decoder_layer(
|
2161
|
+
hidden_states,
|
2162
|
+
attention_mask=causal_mask,
|
2163
|
+
position_ids=position_ids,
|
2164
|
+
past_key_value=past_key_value,
|
2165
|
+
output_attentions=output_attentions, # False
|
2166
|
+
use_cache=use_cache, # True
|
2167
|
+
cache_position=cache_position,
|
2168
|
+
)
|
2169
|
+
|
2170
|
+
# NOTE: clear outdate cache after it has been used for memory saving
|
2171
|
+
past_key_value = past_key_values[idx] = None
|
2172
|
+
|
2173
|
+
hidden_states = layer_outputs[0]
|
2174
|
+
|
2175
|
+
next_decoder_cache = (
|
2176
|
+
next_decoder_cache + (layer_outputs[-1],) if use_cache else None
|
2177
|
+
)
|
2178
|
+
|
2179
|
+
if output_attentions:
|
2180
|
+
all_self_attns += (layer_outputs[1],)
|
2181
|
+
|
2182
|
+
hidden_states = self.norm(hidden_states)
|
2183
|
+
|
2184
|
+
# add hidden states from the last decoder layer
|
2185
|
+
if output_hidden_states:
|
2186
|
+
all_hidden_states += (hidden_states,)
|
2187
|
+
|
2188
|
+
next_cache = next_decoder_cache if use_cache else None
|
2189
|
+
|
2190
|
+
if not return_dict:
|
2191
|
+
return tuple(
|
2192
|
+
v
|
2193
|
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
2194
|
+
if v is not None
|
2195
|
+
)
|
2196
|
+
return BaseModelOutputWithPast(
|
2197
|
+
last_hidden_state=hidden_states,
|
2198
|
+
past_key_values=next_cache,
|
2199
|
+
hidden_states=all_hidden_states,
|
2200
|
+
attentions=all_self_attns,
|
2201
|
+
)
|
2202
|
+
|
2203
|
+
|
2204
|
+
class Qwen2LMHead(nn.Layer):
|
2205
|
+
def __init__(self, config, embedding_weights=None, transpose_y=False):
|
2206
|
+
super(Qwen2LMHead, self).__init__()
|
2207
|
+
self.config = config
|
2208
|
+
if (
|
2209
|
+
config.tensor_parallel_degree > 1
|
2210
|
+
and config.vocab_size % config.tensor_parallel_degree == 0
|
2211
|
+
):
|
2212
|
+
vocab_size = config.vocab_size // config.tensor_parallel_degree
|
2213
|
+
else:
|
2214
|
+
vocab_size = config.vocab_size
|
2215
|
+
|
2216
|
+
self.transpose_y = transpose_y
|
2217
|
+
if transpose_y:
|
2218
|
+
# only for weight from embedding_weights
|
2219
|
+
if embedding_weights is not None:
|
2220
|
+
self.weight = embedding_weights
|
2221
|
+
else:
|
2222
|
+
self.weight = self.create_parameter(
|
2223
|
+
shape=[vocab_size, config.hidden_size],
|
2224
|
+
dtype=paddle.get_default_dtype(),
|
2225
|
+
)
|
2226
|
+
else:
|
2227
|
+
|
2228
|
+
if vocab_size != config.vocab_size:
|
2229
|
+
with get_rng_state_tracker().rng_state():
|
2230
|
+
self.weight = self.create_parameter(
|
2231
|
+
shape=[config.hidden_size, vocab_size],
|
2232
|
+
dtype=paddle.get_default_dtype(),
|
2233
|
+
)
|
2234
|
+
else:
|
2235
|
+
self.weight = self.create_parameter(
|
2236
|
+
shape=[config.hidden_size, vocab_size],
|
2237
|
+
dtype=paddle.get_default_dtype(),
|
2238
|
+
)
|
2239
|
+
|
2240
|
+
# Must set distributed attr for Tensor Parallel !
|
2241
|
+
self.weight.is_distributed = (
|
2242
|
+
True if (vocab_size != config.vocab_size) else False
|
2243
|
+
)
|
2244
|
+
if self.weight.is_distributed:
|
2245
|
+
# for tie_word_embeddings
|
2246
|
+
self.weight.split_axis = 0 if self.transpose_y else 1
|
2247
|
+
|
2248
|
+
def forward(self, hidden_states, tensor_parallel_output=None):
|
2249
|
+
if tensor_parallel_output is None:
|
2250
|
+
tensor_parallel_output = self.config.tensor_parallel_output
|
2251
|
+
|
2252
|
+
# 确保数据类型一致
|
2253
|
+
if self.weight.dtype != hidden_states.dtype:
|
2254
|
+
hidden_states = paddle.cast(hidden_states, self.weight.dtype)
|
2255
|
+
|
2256
|
+
logits = parallel_matmul(
|
2257
|
+
hidden_states,
|
2258
|
+
self.weight,
|
2259
|
+
transpose_y=self.transpose_y,
|
2260
|
+
tensor_parallel_output=tensor_parallel_output,
|
2261
|
+
)
|
2262
|
+
return logits
|
2263
|
+
|
2264
|
+
|
2265
|
+
class Qwen2_5_VLForConditionalGeneration(Qwen2_5_VLPreTrainedModel):
|
2266
|
+
_tied_weights_keys = ["lm_head.weight"]
|
2267
|
+
config_class = Qwen2_5_VLConfig
|
2268
|
+
_no_split_modules = ["Qwen2VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
|
2269
|
+
|
2270
|
+
def __init__(self, config, attn_implementation="flash_attention_2"):
|
2271
|
+
super().__init__(config)
|
2272
|
+
config._attn_implementation = attn_implementation
|
2273
|
+
config.vision_config._attn_implementation = attn_implementation
|
2274
|
+
|
2275
|
+
self.visual = Qwen2_5_VisionTransformerPretrainedModel._from_config(
|
2276
|
+
config.vision_config
|
2277
|
+
)
|
2278
|
+
self.model = Qwen2_5_VLModel(config)
|
2279
|
+
self.vocab_size = config.vocab_size
|
2280
|
+
if config.tie_word_embeddings:
|
2281
|
+
self.lm_head = Qwen2LMHead(
|
2282
|
+
config,
|
2283
|
+
embedding_weights=self.model.embed_tokens.weight,
|
2284
|
+
transpose_y=True,
|
2285
|
+
)
|
2286
|
+
self.tie_weights()
|
2287
|
+
else:
|
2288
|
+
self.lm_head = Qwen2LMHead(config)
|
2289
|
+
self.padding_side = "left" # set it to left by default, user can use setter to change padding_sides
|
2290
|
+
|
2291
|
+
self.enable_recompute = False
|
2292
|
+
|
2293
|
+
def get_input_embeddings(self):
|
2294
|
+
return self.model.embed_tokens
|
2295
|
+
|
2296
|
+
def set_input_embeddings(self, value):
|
2297
|
+
self.model.embed_tokens = value
|
2298
|
+
|
2299
|
+
def get_output_embeddings(self):
|
2300
|
+
return self.lm_head
|
2301
|
+
|
2302
|
+
def set_output_embeddings(self, new_embeddings):
|
2303
|
+
self.lm_head = new_embeddings
|
2304
|
+
|
2305
|
+
def set_decoder(self, decoder):
|
2306
|
+
self.model = decoder
|
2307
|
+
|
2308
|
+
def get_decoder(self):
|
2309
|
+
return self.model
|
2310
|
+
|
2311
|
+
@classmethod
|
2312
|
+
def _get_tensor_parallel_mappings(cls, config: Qwen2_5_VLConfig, is_split=True):
|
2313
|
+
|
2314
|
+
logging.info("Qwen2 inference model _get_tensor_parallel_mappings")
|
2315
|
+
|
2316
|
+
from paddlenlp.transformers.conversion_utils import split_or_merge_func
|
2317
|
+
|
2318
|
+
fn = split_or_merge_func(
|
2319
|
+
is_split=is_split,
|
2320
|
+
tensor_parallel_degree=config.tensor_parallel_degree,
|
2321
|
+
tensor_parallel_rank=config.tensor_parallel_rank,
|
2322
|
+
num_attention_heads=config.num_attention_heads,
|
2323
|
+
)
|
2324
|
+
|
2325
|
+
def get_tensor_parallel_split_mappings(num_layers):
|
2326
|
+
final_actions = {}
|
2327
|
+
|
2328
|
+
base_actions = {
|
2329
|
+
"lm_head.weight": partial(fn, is_column=True),
|
2330
|
+
# Row Linear
|
2331
|
+
"embed_tokens.weight": partial(fn, is_column=False),
|
2332
|
+
"layers.0.self_attn.o_proj.weight": partial(fn, is_column=False),
|
2333
|
+
"layers.0.mlp.down_proj.weight": partial(fn, is_column=False),
|
2334
|
+
}
|
2335
|
+
|
2336
|
+
# Column Linear
|
2337
|
+
# if config.fuse_attention_qkv:
|
2338
|
+
# base_actions["layers.0.self_attn.qkv_proj.weight"] = partial(fn, is_column=True)
|
2339
|
+
# else:
|
2340
|
+
base_actions["layers.0.self_attn.q_proj.weight"] = partial(
|
2341
|
+
fn, is_column=True
|
2342
|
+
)
|
2343
|
+
base_actions["layers.0.self_attn.q_proj.bias"] = partial(fn, is_column=True)
|
2344
|
+
# if we have enough num_key_value_heads to split, then split it.
|
2345
|
+
if config.num_key_value_heads % config.tensor_parallel_degree == 0:
|
2346
|
+
base_actions["layers.0.self_attn.k_proj.weight"] = partial(
|
2347
|
+
fn, is_column=True
|
2348
|
+
)
|
2349
|
+
base_actions["layers.0.self_attn.v_proj.weight"] = partial(
|
2350
|
+
fn, is_column=True
|
2351
|
+
)
|
2352
|
+
base_actions["layers.0.self_attn.k_proj.bias"] = partial(
|
2353
|
+
fn, is_column=True
|
2354
|
+
)
|
2355
|
+
base_actions["layers.0.self_attn.v_proj.bias"] = partial(
|
2356
|
+
fn, is_column=True
|
2357
|
+
)
|
2358
|
+
|
2359
|
+
if config.fuse_attention_ffn:
|
2360
|
+
base_actions["layers.0.mlp.gate_up_fused_proj.weight"] = partial(
|
2361
|
+
fn, is_column=True, is_naive_2fuse=True
|
2362
|
+
)
|
2363
|
+
else:
|
2364
|
+
base_actions["layers.0.mlp.gate_proj.weight"] = partial(
|
2365
|
+
fn, is_column=True
|
2366
|
+
)
|
2367
|
+
base_actions["layers.0.mlp.up_proj.weight"] = partial(
|
2368
|
+
fn, is_column=True
|
2369
|
+
)
|
2370
|
+
|
2371
|
+
for key, action in base_actions.items():
|
2372
|
+
if "layers.0." in key:
|
2373
|
+
for i in range(num_layers):
|
2374
|
+
final_actions[key.replace("layers.0.", f"layers.{i}.")] = action
|
2375
|
+
final_actions[key] = action
|
2376
|
+
|
2377
|
+
return final_actions
|
2378
|
+
|
2379
|
+
mappings = get_tensor_parallel_split_mappings(config.num_hidden_layers)
|
2380
|
+
|
2381
|
+
return mappings
|
2382
|
+
|
2383
|
+
@staticmethod
|
2384
|
+
def get_rope_index(
|
2385
|
+
spatial_merge_size,
|
2386
|
+
image_token_id,
|
2387
|
+
video_token_id,
|
2388
|
+
vision_start_token_id,
|
2389
|
+
tokens_per_second,
|
2390
|
+
input_ids: Optional[paddle.Tensor] = None,
|
2391
|
+
image_grid_thw: Optional[paddle.Tensor] = None,
|
2392
|
+
video_grid_thw: Optional[paddle.Tensor] = None,
|
2393
|
+
second_per_grid_ts: Optional[paddle.Tensor] = None,
|
2394
|
+
attention_mask: Optional[paddle.Tensor] = None,
|
2395
|
+
) -> Tuple[paddle.Tensor, paddle.Tensor]:
|
2396
|
+
"""
|
2397
|
+
Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
|
2398
|
+
|
2399
|
+
Explanation:
|
2400
|
+
Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
|
2401
|
+
|
2402
|
+
For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
|
2403
|
+
Examples:
|
2404
|
+
input_ids: [T T T T T], here T is for text.
|
2405
|
+
temporal position_ids: [0, 1, 2, 3, 4]
|
2406
|
+
height position_ids: [0, 1, 2, 3, 4]
|
2407
|
+
width position_ids: [0, 1, 2, 3, 4]
|
2408
|
+
|
2409
|
+
For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
|
2410
|
+
and 1D rotary position embedding for text part.
|
2411
|
+
Examples:
|
2412
|
+
Temporal (Time): 3 patches, representing different segments of the video in time.
|
2413
|
+
Height: 2 patches, dividing each frame vertically.
|
2414
|
+
Width: 2 patches, dividing each frame horizontally.
|
2415
|
+
We also have some important parameters:
|
2416
|
+
fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
|
2417
|
+
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.
|
2418
|
+
temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
|
2419
|
+
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.
|
2420
|
+
input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
|
2421
|
+
vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
|
2422
|
+
vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
|
2423
|
+
vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
|
2424
|
+
text temporal position_ids: [101, 102, 103, 104, 105]
|
2425
|
+
text height position_ids: [101, 102, 103, 104, 105]
|
2426
|
+
text width position_ids: [101, 102, 103, 104, 105]
|
2427
|
+
Here we calculate the text start position_ids as the max vision position_ids plus 1.
|
2428
|
+
|
2429
|
+
Args:
|
2430
|
+
input_ids (`paddle.LongTensor` of shape `(batch_size, sequence_length)`):
|
2431
|
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
2432
|
+
it.
|
2433
|
+
image_grid_thw (`paddle.LongTensor` of shape `(num_images, 3)`, *optional*):
|
2434
|
+
The temporal, height and width of feature shape of each image in LLM.
|
2435
|
+
video_grid_thw (`paddle.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
2436
|
+
The temporal, height and width of feature shape of each video in LLM.
|
2437
|
+
second_per_grid_ts (`paddle.Tensor` of shape `(num_videos)`, *optional*):
|
2438
|
+
The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
|
2439
|
+
attention_mask (`paddle.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
2440
|
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
2441
|
+
|
2442
|
+
- 1 for tokens that are **not masked**,
|
2443
|
+
- 0 for tokens that are **masked**.
|
2444
|
+
|
2445
|
+
Returns:
|
2446
|
+
position_ids (`paddle.Tensor` of shape `(3, batch_size, sequence_length)`)
|
2447
|
+
mrope_position_deltas (`paddle.Tensor` of shape `(batch_size)`)
|
2448
|
+
"""
|
2449
|
+
# spatial_merge_size = self.config.vision_config.spatial_merge_size
|
2450
|
+
# image_token_id = self.config.image_token_id
|
2451
|
+
# video_token_id = self.config.video_token_id
|
2452
|
+
# vision_start_token_id = self.config.vision_start_token_id
|
2453
|
+
mrope_position_deltas = []
|
2454
|
+
if image_grid_thw is not None or video_grid_thw is not None:
|
2455
|
+
total_input_ids = input_ids
|
2456
|
+
position_ids = paddle.ones(
|
2457
|
+
[3, input_ids.shape[0], input_ids.shape[1]], dtype=input_ids.dtype
|
2458
|
+
)
|
2459
|
+
image_index, video_index = 0, 0
|
2460
|
+
for i, input_ids in enumerate(total_input_ids):
|
2461
|
+
# TODO: CUDA error in some paddle version
|
2462
|
+
if attention_mask is not None:
|
2463
|
+
input_ids = paddle.to_tensor(
|
2464
|
+
input_ids.cpu()[attention_mask[i].cpu() == 1]
|
2465
|
+
)
|
2466
|
+
image_nums, video_nums = 0, 0
|
2467
|
+
vision_start_indices = paddle.nonzero(
|
2468
|
+
input_ids == vision_start_token_id
|
2469
|
+
).squeeze(1)
|
2470
|
+
vision_tokens = input_ids[vision_start_indices + 1]
|
2471
|
+
image_nums = (
|
2472
|
+
(vision_tokens == image_token_id).sum()
|
2473
|
+
if vision_tokens.numel() > 0
|
2474
|
+
else 0
|
2475
|
+
)
|
2476
|
+
video_nums = (
|
2477
|
+
(vision_tokens == video_token_id).sum()
|
2478
|
+
if vision_tokens.numel() > 0
|
2479
|
+
else 0
|
2480
|
+
)
|
2481
|
+
input_tokens = input_ids.tolist()
|
2482
|
+
llm_pos_ids_list: list = []
|
2483
|
+
st = 0
|
2484
|
+
remain_images, remain_videos = image_nums, video_nums
|
2485
|
+
for _ in range(image_nums + video_nums):
|
2486
|
+
if image_token_id in input_tokens and remain_images > 0:
|
2487
|
+
ed_image = input_tokens.index(image_token_id, st)
|
2488
|
+
else:
|
2489
|
+
ed_image = len(input_tokens) + 1
|
2490
|
+
if video_token_id in input_tokens and remain_videos > 0:
|
2491
|
+
ed_video = input_tokens.index(video_token_id, st)
|
2492
|
+
else:
|
2493
|
+
ed_video = len(input_tokens) + 1
|
2494
|
+
if ed_image < ed_video:
|
2495
|
+
t, h, w = (
|
2496
|
+
image_grid_thw[image_index][0],
|
2497
|
+
image_grid_thw[image_index][1],
|
2498
|
+
image_grid_thw[image_index][2],
|
2499
|
+
)
|
2500
|
+
second_per_grid_t = 0
|
2501
|
+
image_index += 1
|
2502
|
+
remain_images -= 1
|
2503
|
+
ed = ed_image
|
2504
|
+
else:
|
2505
|
+
t, h, w = (
|
2506
|
+
video_grid_thw[video_index][0],
|
2507
|
+
video_grid_thw[video_index][1],
|
2508
|
+
video_grid_thw[video_index][2],
|
2509
|
+
)
|
2510
|
+
if second_per_grid_ts is not None:
|
2511
|
+
second_per_grid_t = second_per_grid_ts[video_index]
|
2512
|
+
else:
|
2513
|
+
second_per_grid_t = 1.0
|
2514
|
+
video_index += 1
|
2515
|
+
remain_videos -= 1
|
2516
|
+
ed = ed_video
|
2517
|
+
llm_grid_t, llm_grid_h, llm_grid_w = (
|
2518
|
+
t.item(),
|
2519
|
+
h.item() // spatial_merge_size,
|
2520
|
+
w.item() // spatial_merge_size,
|
2521
|
+
)
|
2522
|
+
text_len = ed - st
|
2523
|
+
st_idx = (
|
2524
|
+
llm_pos_ids_list[-1].max() + 1
|
2525
|
+
if len(llm_pos_ids_list) > 0
|
2526
|
+
else 0
|
2527
|
+
)
|
2528
|
+
llm_pos_ids_list.append(
|
2529
|
+
paddle.arange(text_len).reshape([1, -1]).expand([3, -1])
|
2530
|
+
+ st_idx
|
2531
|
+
)
|
2532
|
+
range_tensor = paddle.arange(end=llm_grid_t).reshape([-1, 1])
|
2533
|
+
expanded_range = range_tensor.expand(
|
2534
|
+
shape=[-1, llm_grid_h * llm_grid_w]
|
2535
|
+
)
|
2536
|
+
time_tensor = expanded_range * second_per_grid_t * tokens_per_second
|
2537
|
+
time_tensor_long = time_tensor.astype(dtype="int64")
|
2538
|
+
t_index = time_tensor_long.flatten()
|
2539
|
+
h_index = (
|
2540
|
+
paddle.arange(end=llm_grid_h)
|
2541
|
+
.reshape([1, -1, 1])
|
2542
|
+
.expand(shape=[llm_grid_t, -1, llm_grid_w])
|
2543
|
+
.flatten()
|
2544
|
+
)
|
2545
|
+
w_index = (
|
2546
|
+
paddle.arange(end=llm_grid_w)
|
2547
|
+
.reshape([1, 1, -1])
|
2548
|
+
.expand(shape=[llm_grid_t, llm_grid_h, -1])
|
2549
|
+
.flatten()
|
2550
|
+
)
|
2551
|
+
llm_pos_ids_list.append(
|
2552
|
+
paddle.stack([t_index, h_index, w_index]) + text_len + st_idx
|
2553
|
+
)
|
2554
|
+
st = ed + llm_grid_t * llm_grid_h * llm_grid_w
|
2555
|
+
|
2556
|
+
if st < len(input_tokens):
|
2557
|
+
st_idx = (
|
2558
|
+
llm_pos_ids_list[-1].max() + 1
|
2559
|
+
if len(llm_pos_ids_list) > 0
|
2560
|
+
else 0
|
2561
|
+
)
|
2562
|
+
text_len = len(input_tokens) - st
|
2563
|
+
llm_pos_ids_list.append(
|
2564
|
+
paddle.arange(text_len).reshape([1, -1]).expand([3, -1])
|
2565
|
+
+ st_idx
|
2566
|
+
)
|
2567
|
+
llm_positions = paddle.concat(llm_pos_ids_list, axis=1).reshape([3, -1])
|
2568
|
+
position_ids[..., i, attention_mask[i] == 1] = llm_positions
|
2569
|
+
|
2570
|
+
mrope_position_deltas.append(
|
2571
|
+
llm_positions.max() + 1 - len(total_input_ids[i])
|
2572
|
+
)
|
2573
|
+
mrope_position_deltas = paddle.to_tensor(mrope_position_deltas).unsqueeze(1)
|
2574
|
+
return position_ids, mrope_position_deltas
|
2575
|
+
else:
|
2576
|
+
if attention_mask is not None:
|
2577
|
+
position_ids = paddle.cast(attention_mask, dtype="int64").cumsum(-1) - 1
|
2578
|
+
position_ids.masked_fill_(mask=attention_mask == 0, value=1)
|
2579
|
+
position_ids = position_ids.unsqueeze(0).expand([3, -1, -1])
|
2580
|
+
max_position_ids = position_ids.max(0, keepdim=False)[0].max(
|
2581
|
+
-1, keepdim=True
|
2582
|
+
)[0]
|
2583
|
+
mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
|
2584
|
+
else:
|
2585
|
+
position_ids = (
|
2586
|
+
paddle.arange(input_ids.shape[1])
|
2587
|
+
.reshape([1, 1, -1])
|
2588
|
+
.expand(shape=[3, input_ids.shape[0], -1])
|
2589
|
+
)
|
2590
|
+
mrope_position_deltas = paddle.zeros(
|
2591
|
+
[input_ids.shape[0], 1], dtype=input_ids.dtype
|
2592
|
+
)
|
2593
|
+
return position_ids, mrope_position_deltas
|
2594
|
+
|
2595
|
+
def update_model_kwargs_for_generation(
|
2596
|
+
self,
|
2597
|
+
outputs: ModelOutput,
|
2598
|
+
model_kwargs: Dict[str, Any],
|
2599
|
+
is_encoder_decoder: bool = False,
|
2600
|
+
# num_new_tokens: int = 1,
|
2601
|
+
) -> Dict[str, Any]:
|
2602
|
+
model_kwargs = super().update_model_kwargs_for_generation(
|
2603
|
+
outputs=outputs,
|
2604
|
+
model_kwargs=model_kwargs,
|
2605
|
+
is_encoder_decoder=is_encoder_decoder,
|
2606
|
+
# num_new_tokens=num_new_tokens,
|
2607
|
+
)
|
2608
|
+
|
2609
|
+
# return logits + 28 layers k and v, TODO:
|
2610
|
+
if getattr(outputs, "rope_deltas", None) is not None:
|
2611
|
+
model_kwargs["rope_deltas"] = outputs.rope_deltas
|
2612
|
+
|
2613
|
+
return model_kwargs
|
2614
|
+
|
2615
|
+
# NOTE(changwenbin): Vision module added for high-performance inference.
|
2616
|
+
def vision_forward(
|
2617
|
+
self,
|
2618
|
+
input_ids: paddle.Tensor,
|
2619
|
+
inputs_embeds: Optional[paddle.Tensor] = None,
|
2620
|
+
attention_mask: Optional[paddle.Tensor] = None,
|
2621
|
+
position_ids: Optional[paddle.Tensor] = None,
|
2622
|
+
pixel_values: Optional[paddle.Tensor] = None,
|
2623
|
+
pixel_values_videos: Optional[paddle.Tensor] = None,
|
2624
|
+
image_grid_thw: Optional[paddle.Tensor] = None,
|
2625
|
+
video_grid_thw: Optional[paddle.Tensor] = None,
|
2626
|
+
rope_deltas: Optional[paddle.Tensor] = None,
|
2627
|
+
second_per_grid_ts: Optional[paddle.Tensor] = None,
|
2628
|
+
):
|
2629
|
+
|
2630
|
+
if inputs_embeds is None:
|
2631
|
+
# NOTE: (zhoukangkang、changwenbin) In the high-performance reasoning of Qwen2-vl,
|
2632
|
+
# in order to reduce video memory, the qwen2 embed_tokens method in Paddlenlp is reused here.
|
2633
|
+
from paddlenlp.experimental.transformers.qwen2.modeling import (
|
2634
|
+
Qwen2_5_VLForConditionalGenerationBlockInferenceModel,
|
2635
|
+
)
|
2636
|
+
|
2637
|
+
assert isinstance(
|
2638
|
+
self.model, Qwen2_5_VLForConditionalGenerationBlockInferenceModel
|
2639
|
+
), "model is not an instance of Qwen2_5_VLForConditionalGenerationBlockInferenceModel"
|
2640
|
+
|
2641
|
+
inputs_embeds = self.model.qwen2.embed_tokens(input_ids)
|
2642
|
+
if pixel_values is not None:
|
2643
|
+
pixel_values = paddle.cast(
|
2644
|
+
pixel_values, self.visual.patch_embed.proj.weight.dtype
|
2645
|
+
)
|
2646
|
+
image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
|
2647
|
+
image_mask = input_ids == self.config.image_token_id
|
2648
|
+
|
2649
|
+
inputs_embeds[image_mask] = image_embeds
|
2650
|
+
if pixel_values_videos is not None:
|
2651
|
+
pixel_values_videos = paddle.cast(
|
2652
|
+
pixel_values_videos, self.visual.patch_embed.proj.weight.dtype
|
2653
|
+
)
|
2654
|
+
video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
|
2655
|
+
video_mask = input_ids == self.config.video_token_id
|
2656
|
+
inputs_embeds[video_mask] = video_embeds
|
2657
|
+
if attention_mask is not None:
|
2658
|
+
attention_mask = attention_mask
|
2659
|
+
|
2660
|
+
return inputs_embeds
|
2661
|
+
|
2662
|
+
def forward(
|
2663
|
+
self,
|
2664
|
+
input_ids: paddle.Tensor = None, # [1, 400] sum 49356255
|
2665
|
+
attention_mask: Optional[paddle.Tensor] = None, # [1, 400] sum 396
|
2666
|
+
position_ids: Optional[paddle.Tensor] = None,
|
2667
|
+
past_key_values: Optional[List[paddle.Tensor]] = None,
|
2668
|
+
inputs_embeds: Optional[paddle.Tensor] = None,
|
2669
|
+
labels: Optional[paddle.Tensor] = None, # [1, 400] sum 354841
|
2670
|
+
use_cache: Optional[bool] = None,
|
2671
|
+
output_attentions: Optional[bool] = None,
|
2672
|
+
output_hidden_states: Optional[bool] = None,
|
2673
|
+
return_dict: Optional[bool] = None,
|
2674
|
+
pixel_values: Optional[
|
2675
|
+
paddle.Tensor
|
2676
|
+
] = None, # [1, 1224, 1176] sum 2658700.50000000
|
2677
|
+
pixel_values_videos: Optional[paddle.Tensor] = None,
|
2678
|
+
image_grid_thw: Optional[paddle.Tensor] = None, # [[1 , 36, 34]]
|
2679
|
+
video_grid_thw: Optional[paddle.Tensor] = None,
|
2680
|
+
rope_deltas: Optional[paddle.Tensor] = None,
|
2681
|
+
second_per_grid_ts: Optional[paddle.Tensor] = None,
|
2682
|
+
):
|
2683
|
+
"""
|
2684
|
+
Args:
|
2685
|
+
labels (`paddle.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
2686
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
2687
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
2688
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
2689
|
+
|
2690
|
+
Returns:
|
2691
|
+
|
2692
|
+
Example:
|
2693
|
+
|
2694
|
+
```python
|
2695
|
+
>>> from PIL import Image
|
2696
|
+
>>> import requests
|
2697
|
+
>>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
|
2698
|
+
|
2699
|
+
>>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
|
2700
|
+
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
|
2701
|
+
|
2702
|
+
>>> messages = [
|
2703
|
+
{
|
2704
|
+
"role": "user",
|
2705
|
+
"content": [
|
2706
|
+
{"type": "image"},
|
2707
|
+
{"type": "text", "text": "What is shown in this image?"},
|
2708
|
+
],
|
2709
|
+
},
|
2710
|
+
]
|
2711
|
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
2712
|
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
2713
|
+
|
2714
|
+
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
2715
|
+
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
|
2716
|
+
|
2717
|
+
>>> # Generate
|
2718
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
2719
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
2720
|
+
"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
|
2721
|
+
```"""
|
2722
|
+
|
2723
|
+
output_attentions = (
|
2724
|
+
output_attentions
|
2725
|
+
if output_attentions is not None
|
2726
|
+
else self.config.output_attentions
|
2727
|
+
)
|
2728
|
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states # fmt:skip
|
2729
|
+
# Note:始终为True
|
2730
|
+
return_dict = True # return_dict if return_dict is not None else self.config.use_return_dict
|
2731
|
+
|
2732
|
+
if inputs_embeds is None:
|
2733
|
+
inputs_embeds = self.model.embed_tokens(input_ids)
|
2734
|
+
if pixel_values is not None:
|
2735
|
+
# 确保 pixel_values 和 inputs_embeds 使用相同的数据类型
|
2736
|
+
pixel_values = paddle.cast(pixel_values, inputs_embeds.dtype)
|
2737
|
+
image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
|
2738
|
+
# 确保 image_embeds 和 inputs_embeds 使用相同的数据类型
|
2739
|
+
image_embeds = paddle.cast(image_embeds, inputs_embeds.dtype)
|
2740
|
+
image_mask = input_ids == self.config.image_token_id
|
2741
|
+
if self.training:
|
2742
|
+
inputs_embeds = inputs_embeds.clone()
|
2743
|
+
inputs_embeds[image_mask] = image_embeds
|
2744
|
+
if pixel_values_videos is not None:
|
2745
|
+
# 确保 pixel_values_videos 和 inputs_embeds 使用相同的数据类型
|
2746
|
+
pixel_values_videos = paddle.cast(
|
2747
|
+
pixel_values_videos, inputs_embeds.dtype
|
2748
|
+
)
|
2749
|
+
video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
|
2750
|
+
# 确保 video_embeds 和 inputs_embeds 使用相同的数据类型
|
2751
|
+
video_embeds = paddle.cast(video_embeds, inputs_embeds.dtype)
|
2752
|
+
video_mask = input_ids == self.config.video_token_id
|
2753
|
+
inputs_embeds[video_mask] = video_embeds
|
2754
|
+
if attention_mask is not None:
|
2755
|
+
attention_mask = attention_mask
|
2756
|
+
|
2757
|
+
outputs = self.model(
|
2758
|
+
input_ids=None,
|
2759
|
+
position_ids=position_ids,
|
2760
|
+
attention_mask=attention_mask,
|
2761
|
+
past_key_values=past_key_values,
|
2762
|
+
inputs_embeds=inputs_embeds,
|
2763
|
+
use_cache=use_cache,
|
2764
|
+
output_attentions=output_attentions,
|
2765
|
+
output_hidden_states=output_hidden_states,
|
2766
|
+
return_dict=return_dict,
|
2767
|
+
)
|
2768
|
+
|
2769
|
+
hidden_states = outputs[0]
|
2770
|
+
|
2771
|
+
tensor_parallel_output = (
|
2772
|
+
self.config.tensor_parallel_output
|
2773
|
+
and self.config.tensor_parallel_degree > 1
|
2774
|
+
)
|
2775
|
+
|
2776
|
+
logits = self.lm_head(
|
2777
|
+
hidden_states, tensor_parallel_output=tensor_parallel_output
|
2778
|
+
)
|
2779
|
+
# logits = paddle.cast(logits, "float32")
|
2780
|
+
|
2781
|
+
loss = None
|
2782
|
+
if labels is not None:
|
2783
|
+
# Shift so that tokens < n predict n
|
2784
|
+
shift_logits = logits[..., :-1, :] # [1, 395, 151936]
|
2785
|
+
shift_labels = labels[..., 1:] # [1, 395]
|
2786
|
+
# Flatten the tokens
|
2787
|
+
shift_logits = shift_logits.reshape([-1, self.config.vocab_size])
|
2788
|
+
shift_labels = shift_labels.reshape([-1])
|
2789
|
+
loss_fct = nn.CrossEntropyLoss(reduction="sum")
|
2790
|
+
loss = loss_fct(shift_logits, shift_labels)
|
2791
|
+
label_sum = paddle.sum(shift_labels != -100).cast("float32")
|
2792
|
+
loss = loss / label_sum
|
2793
|
+
|
2794
|
+
if not return_dict:
|
2795
|
+
# output = (logits,) + outputs[1:]
|
2796
|
+
# Note: (changwenbin) fix "can only concatenate tuple (not "list") to tuple".
|
2797
|
+
output = (logits,) + tuple(outputs[1:])
|
2798
|
+
return (loss,) + output if loss is not None else output
|
2799
|
+
# return logits + 28 layers k and v
|
2800
|
+
|
2801
|
+
return Qwen2_5_VLCausalLMOutputWithPast(
|
2802
|
+
loss=loss,
|
2803
|
+
logits=logits,
|
2804
|
+
past_key_values=outputs.past_key_values,
|
2805
|
+
hidden_states=outputs.hidden_states,
|
2806
|
+
attentions=outputs.attentions,
|
2807
|
+
rope_deltas=rope_deltas,
|
2808
|
+
)
|
2809
|
+
|
2810
|
+
def prepare_inputs_for_generation(
|
2811
|
+
self,
|
2812
|
+
input_ids, # [1, 3602] # [[151644, 8948, 198, ..., 151644, 77091, 198]]
|
2813
|
+
past_key_values=None, # DynamicCache
|
2814
|
+
attention_mask=None, # [1, 3602] 1
|
2815
|
+
inputs_embeds=None, # None
|
2816
|
+
cache_position=None, # [ 0, 1, 2, ..., 3599, 3600, 3601]
|
2817
|
+
position_ids=None, # None
|
2818
|
+
use_cache=True,
|
2819
|
+
pixel_values=None, # [14308, 1176]
|
2820
|
+
pixel_values_videos=None,
|
2821
|
+
image_grid_thw=None, # [1, 3] # [[ 1, 98, 146]]
|
2822
|
+
video_grid_thw=None,
|
2823
|
+
second_per_grid_ts=None,
|
2824
|
+
**kwargs,
|
2825
|
+
):
|
2826
|
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
2827
|
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
2828
|
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
2829
|
+
batch_size, seq_length = input_ids.shape
|
2830
|
+
if past_key_values is None:
|
2831
|
+
cache_position = paddle.arange(input_ids.shape[1])
|
2832
|
+
else:
|
2833
|
+
cache_position = paddle.to_tensor([seq_length - 1])
|
2834
|
+
|
2835
|
+
if past_key_values is not None:
|
2836
|
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
2837
|
+
|
2838
|
+
rope_deltas = kwargs.get("rope_deltas", None)
|
2839
|
+
|
2840
|
+
if attention_mask is not None and position_ids is None:
|
2841
|
+
if cache_position is None or (
|
2842
|
+
cache_position is not None and cache_position[0] == 0
|
2843
|
+
):
|
2844
|
+
position_ids, rope_deltas = self.get_rope_index(
|
2845
|
+
self.config.vision_config.spatial_merge_size,
|
2846
|
+
self.config.image_token_id,
|
2847
|
+
self.config.video_token_id,
|
2848
|
+
self.config.vision_start_token_id,
|
2849
|
+
self.config.vision_config.tokens_per_second,
|
2850
|
+
input_ids,
|
2851
|
+
image_grid_thw,
|
2852
|
+
video_grid_thw,
|
2853
|
+
second_per_grid_ts,
|
2854
|
+
attention_mask,
|
2855
|
+
)
|
2856
|
+
else:
|
2857
|
+
batch_size, seq_length = input_ids.shape
|
2858
|
+
delta = (
|
2859
|
+
cache_position[0] + rope_deltas
|
2860
|
+
if cache_position is not None and rope_deltas is not None
|
2861
|
+
else 0
|
2862
|
+
)
|
2863
|
+
position_ids = paddle.arange(seq_length)
|
2864
|
+
position_ids = position_ids.reshape([1, -1]).expand([batch_size, -1])
|
2865
|
+
position_ids = position_ids + delta
|
2866
|
+
position_ids = position_ids.unsqueeze(axis=0).expand([3, -1, -1])
|
2867
|
+
|
2868
|
+
if cache_position[0] != 0:
|
2869
|
+
pixel_values = None
|
2870
|
+
pixel_values_videos = None
|
2871
|
+
|
2872
|
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
2873
|
+
if inputs_embeds is not None and cache_position[0] == 0:
|
2874
|
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
2875
|
+
else:
|
2876
|
+
model_inputs = {"input_ids": input_ids}
|
2877
|
+
|
2878
|
+
model_inputs.update(
|
2879
|
+
{
|
2880
|
+
"position_ids": position_ids, # [3, 1, 3602]
|
2881
|
+
"past_key_values": past_key_values, # DynamicCache()
|
2882
|
+
"use_cache": use_cache, # 1
|
2883
|
+
"attention_mask": attention_mask, # [1, 3602]
|
2884
|
+
"pixel_values": pixel_values, # [14308, 1176]
|
2885
|
+
"pixel_values_videos": pixel_values_videos,
|
2886
|
+
"image_grid_thw": image_grid_thw, # [[ 1, 98, 146]]
|
2887
|
+
"video_grid_thw": video_grid_thw,
|
2888
|
+
"rope_deltas": rope_deltas, # [[-3504]]
|
2889
|
+
"second_per_grid_ts": second_per_grid_ts,
|
2890
|
+
}
|
2891
|
+
)
|
2892
|
+
return model_inputs
|
2893
|
+
|
2894
|
+
|
2895
|
+
class PPDocBee2TransformerPretrainedModel(Qwen2_5_VisionTransformerPretrainedModel):
|
2896
|
+
layer_idx = 15
|
2897
|
+
|
2898
|
+
def forward(
|
2899
|
+
self, hidden_states: paddle.Tensor, grid_thw: paddle.Tensor
|
2900
|
+
) -> paddle.Tensor:
|
2901
|
+
"""
|
2902
|
+
Args:
|
2903
|
+
hidden_states (`paddle.Tensor` of shape `(batch_size, seq_len, hidden_size)`):
|
2904
|
+
The final hidden states of the model.
|
2905
|
+
grid_thw (`paddle.Tensor` of shape `(num_images_or_videos, 3)`):
|
2906
|
+
The temporal, height and width of feature shape of each image in LLM.
|
2907
|
+
Returns:
|
2908
|
+
`paddle.Tensor`: hidden_states.
|
2909
|
+
"""
|
2910
|
+
"""
|
2911
|
+
Args:
|
2912
|
+
hidden_states (`paddle.Tensor` of shape `(batch_size, seq_len, hidden_size)`):
|
2913
|
+
The final hidden states of the model.
|
2914
|
+
grid_thw (`paddle.Tensor` of shape `(num_images_or_videos, 3)`):
|
2915
|
+
The temporal, height and width of feature shape of each image in LLM.
|
2916
|
+
|
2917
|
+
Returns:
|
2918
|
+
`paddle.Tensor`: hidden_states.
|
2919
|
+
"""
|
2920
|
+
hidden_states = self.patch_embed(hidden_states)
|
2921
|
+
rotary_pos_emb = self.rot_pos_emb(grid_thw)
|
2922
|
+
window_index, cu_window_seqlens = self.get_window_index(grid_thw)
|
2923
|
+
cu_window_seqlens = paddle.to_tensor(
|
2924
|
+
data=cu_window_seqlens, dtype="int32", place=hidden_states.place
|
2925
|
+
)
|
2926
|
+
cu_window_seqlens = paddle.unique_consecutive(x=cu_window_seqlens)
|
2927
|
+
seq_len, _ = tuple(hidden_states.shape)
|
2928
|
+
hidden_states = hidden_states.reshape(
|
2929
|
+
[seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1]
|
2930
|
+
)
|
2931
|
+
hidden_states = hidden_states[window_index, :, :]
|
2932
|
+
hidden_states = hidden_states.reshape([seq_len, -1])
|
2933
|
+
rotary_pos_emb = rotary_pos_emb.reshape(
|
2934
|
+
[seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1]
|
2935
|
+
)
|
2936
|
+
rotary_pos_emb = rotary_pos_emb[window_index, :, :]
|
2937
|
+
rotary_pos_emb = rotary_pos_emb.reshape([seq_len, -1])
|
2938
|
+
|
2939
|
+
cu_seqlens = paddle.repeat_interleave(
|
2940
|
+
grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]
|
2941
|
+
).cumsum(axis=0, dtype="int32")
|
2942
|
+
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
|
2943
|
+
multi_vit = []
|
2944
|
+
for layer_num, blk in enumerate(self.blocks):
|
2945
|
+
if layer_num in self.fullatt_block_indexes:
|
2946
|
+
cu_seqlens_now = cu_seqlens
|
2947
|
+
else:
|
2948
|
+
cu_seqlens_now = cu_window_seqlens
|
2949
|
+
if self.enable_recompute and self.training:
|
2950
|
+
hidden_states = self.recompute_training_full(
|
2951
|
+
blk, hidden_states, cu_seqlens_now, rotary_pos_emb
|
2952
|
+
)
|
2953
|
+
else:
|
2954
|
+
hidden_states = blk(
|
2955
|
+
hidden_states,
|
2956
|
+
cu_seqlens=cu_seqlens_now,
|
2957
|
+
rotary_pos_emb=rotary_pos_emb,
|
2958
|
+
)
|
2959
|
+
|
2960
|
+
multi_vit.append(hidden_states)
|
2961
|
+
layer_idx = type(self).layer_idx
|
2962
|
+
hidden_states = self.merger(hidden_states + multi_vit[layer_idx])
|
2963
|
+
reverse_indices = paddle.argsort(x=window_index)
|
2964
|
+
hidden_states = hidden_states[reverse_indices, :]
|
2965
|
+
|
2966
|
+
return hidden_states
|
2967
|
+
|
2968
|
+
|
2969
|
+
class PPDocBee2Inference(Qwen2_5_VLForConditionalGeneration):
|
2970
|
+
def __init__(self, config, attn_implementation="eager"):
|
2971
|
+
super(Qwen2_5_VLForConditionalGeneration, self).__init__(config)
|
2972
|
+
config._attn_implementation = attn_implementation
|
2973
|
+
config.vision_config._attn_implementation = attn_implementation
|
2974
|
+
|
2975
|
+
self.visual = PPDocBee2TransformerPretrainedModel._from_config(
|
2976
|
+
config.vision_config
|
2977
|
+
)
|
2978
|
+
self.model = Qwen2_5_VLModel(config)
|
2979
|
+
self.vocab_size = config.vocab_size
|
2980
|
+
if config.tie_word_embeddings:
|
2981
|
+
self.lm_head = Qwen2LMHead(
|
2982
|
+
config,
|
2983
|
+
embedding_weights=self.model.embed_tokens.weight,
|
2984
|
+
transpose_y=True,
|
2985
|
+
)
|
2986
|
+
self.tie_weights()
|
2987
|
+
else:
|
2988
|
+
self.lm_head = Qwen2LMHead(config)
|
2989
|
+
self.padding_side = "left"
|
2990
|
+
|
2991
|
+
self.enable_recompute = False
|
2992
|
+
|
2993
|
+
def generate(self, inputs, **kwargs):
|
2994
|
+
max_new_tokens = kwargs.get("max_new_tokens", 2048)
|
2995
|
+
temperature = kwargs.get("temperature", 0.1)
|
2996
|
+
top_p = kwargs.get("top_p", 0.001)
|
2997
|
+
top_k = kwargs.get("top_k", 1)
|
2998
|
+
with paddle.no_grad():
|
2999
|
+
generated_ids = super().generate(
|
3000
|
+
**inputs,
|
3001
|
+
max_new_tokens=max_new_tokens,
|
3002
|
+
temperature=temperature,
|
3003
|
+
top_p=top_p,
|
3004
|
+
top_k=top_k,
|
3005
|
+
)
|
3006
|
+
return generated_ids
|