paddlex 3.0.0rc1__py3-none-any.whl → 3.0.2__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.
Files changed (240) hide show
  1. paddlex/.version +1 -1
  2. paddlex/__init__.py +1 -1
  3. paddlex/configs/modules/chart_parsing/PP-Chart2Table.yaml +13 -0
  4. paddlex/configs/modules/doc_vlm/PP-DocBee2-3B.yaml +14 -0
  5. paddlex/configs/modules/formula_recognition/PP-FormulaNet_plus-L.yaml +40 -0
  6. paddlex/configs/modules/formula_recognition/PP-FormulaNet_plus-M.yaml +40 -0
  7. paddlex/configs/modules/formula_recognition/PP-FormulaNet_plus-S.yaml +40 -0
  8. paddlex/configs/modules/layout_detection/PP-DocBlockLayout.yaml +40 -0
  9. paddlex/configs/modules/layout_detection/PP-DocLayout-L.yaml +2 -2
  10. paddlex/configs/modules/layout_detection/PP-DocLayout-M.yaml +2 -2
  11. paddlex/configs/modules/layout_detection/PP-DocLayout-S.yaml +2 -2
  12. paddlex/configs/modules/layout_detection/PP-DocLayout_plus-L.yaml +40 -0
  13. paddlex/configs/modules/text_detection/PP-OCRv5_mobile_det.yaml +40 -0
  14. paddlex/configs/modules/text_detection/PP-OCRv5_server_det.yaml +40 -0
  15. paddlex/configs/modules/text_recognition/PP-OCRv5_mobile_rec.yaml +39 -0
  16. paddlex/configs/modules/text_recognition/PP-OCRv5_server_rec.yaml +39 -0
  17. paddlex/configs/modules/textline_orientation/PP-LCNet_x1_0_textline_ori.yaml +41 -0
  18. paddlex/configs/pipelines/OCR.yaml +7 -6
  19. paddlex/configs/pipelines/PP-ChatOCRv3-doc.yaml +3 -1
  20. paddlex/configs/pipelines/PP-ChatOCRv4-doc.yaml +91 -34
  21. paddlex/configs/pipelines/PP-StructureV3.yaml +72 -72
  22. paddlex/configs/pipelines/doc_understanding.yaml +1 -1
  23. paddlex/configs/pipelines/formula_recognition.yaml +2 -2
  24. paddlex/configs/pipelines/layout_parsing.yaml +3 -2
  25. paddlex/configs/pipelines/seal_recognition.yaml +1 -0
  26. paddlex/configs/pipelines/table_recognition.yaml +2 -1
  27. paddlex/configs/pipelines/table_recognition_v2.yaml +7 -1
  28. paddlex/hpip_links.html +20 -20
  29. paddlex/inference/common/batch_sampler/doc_vlm_batch_sampler.py +33 -10
  30. paddlex/inference/common/batch_sampler/image_batch_sampler.py +34 -25
  31. paddlex/inference/common/result/mixin.py +19 -12
  32. paddlex/inference/models/base/predictor/base_predictor.py +2 -8
  33. paddlex/inference/models/common/static_infer.py +29 -73
  34. paddlex/inference/models/common/tokenizer/__init__.py +2 -0
  35. paddlex/inference/models/common/tokenizer/clip_tokenizer.py +1 -1
  36. paddlex/inference/models/common/tokenizer/gpt_tokenizer.py +2 -2
  37. paddlex/inference/models/common/tokenizer/qwen2_5_tokenizer.py +112 -0
  38. paddlex/inference/models/common/tokenizer/qwen2_tokenizer.py +7 -1
  39. paddlex/inference/models/common/tokenizer/qwen_tokenizer.py +288 -0
  40. paddlex/inference/models/common/tokenizer/tokenizer_utils.py +13 -13
  41. paddlex/inference/models/common/tokenizer/tokenizer_utils_base.py +3 -3
  42. paddlex/inference/models/common/tokenizer/vocab.py +7 -7
  43. paddlex/inference/models/common/ts/funcs.py +19 -8
  44. paddlex/inference/models/common/vlm/conversion_utils.py +99 -0
  45. paddlex/inference/models/common/vlm/fusion_ops.py +205 -0
  46. paddlex/inference/models/common/vlm/generation/configuration_utils.py +1 -1
  47. paddlex/inference/models/common/vlm/generation/logits_process.py +1 -1
  48. paddlex/inference/models/common/vlm/generation/utils.py +1 -1
  49. paddlex/inference/models/common/vlm/transformers/configuration_utils.py +3 -3
  50. paddlex/inference/models/common/vlm/transformers/conversion_utils.py +3 -3
  51. paddlex/inference/models/common/vlm/transformers/model_outputs.py +2 -2
  52. paddlex/inference/models/common/vlm/transformers/model_utils.py +7 -31
  53. paddlex/inference/models/doc_vlm/modeling/GOT_ocr_2_0.py +830 -0
  54. paddlex/inference/models/doc_vlm/modeling/__init__.py +2 -0
  55. paddlex/inference/models/doc_vlm/modeling/qwen2.py +1606 -0
  56. paddlex/inference/models/doc_vlm/modeling/qwen2_5_vl.py +3006 -0
  57. paddlex/inference/models/doc_vlm/modeling/qwen2_vl.py +0 -105
  58. paddlex/inference/models/doc_vlm/predictor.py +79 -24
  59. paddlex/inference/models/doc_vlm/processors/GOT_ocr_2_0.py +97 -0
  60. paddlex/inference/models/doc_vlm/processors/__init__.py +2 -0
  61. paddlex/inference/models/doc_vlm/processors/common.py +189 -0
  62. paddlex/inference/models/doc_vlm/processors/qwen2_5_vl.py +548 -0
  63. paddlex/inference/models/doc_vlm/processors/qwen2_vl.py +21 -176
  64. paddlex/inference/models/formula_recognition/predictor.py +8 -2
  65. paddlex/inference/models/formula_recognition/processors.py +90 -77
  66. paddlex/inference/models/formula_recognition/result.py +28 -27
  67. paddlex/inference/models/image_feature/processors.py +3 -4
  68. paddlex/inference/models/keypoint_detection/predictor.py +3 -0
  69. paddlex/inference/models/object_detection/predictor.py +2 -0
  70. paddlex/inference/models/object_detection/processors.py +28 -3
  71. paddlex/inference/models/object_detection/utils.py +2 -0
  72. paddlex/inference/models/table_structure_recognition/result.py +0 -10
  73. paddlex/inference/models/text_detection/predictor.py +8 -0
  74. paddlex/inference/models/text_detection/processors.py +44 -10
  75. paddlex/inference/models/text_detection/result.py +0 -10
  76. paddlex/inference/models/text_recognition/result.py +1 -1
  77. paddlex/inference/pipelines/__init__.py +9 -5
  78. paddlex/inference/pipelines/_parallel.py +172 -0
  79. paddlex/inference/pipelines/anomaly_detection/pipeline.py +16 -6
  80. paddlex/inference/pipelines/attribute_recognition/pipeline.py +11 -1
  81. paddlex/inference/pipelines/base.py +14 -4
  82. paddlex/inference/pipelines/components/faisser.py +1 -1
  83. paddlex/inference/pipelines/doc_preprocessor/pipeline.py +53 -27
  84. paddlex/inference/pipelines/formula_recognition/pipeline.py +120 -82
  85. paddlex/inference/pipelines/formula_recognition/result.py +1 -11
  86. paddlex/inference/pipelines/image_classification/pipeline.py +16 -6
  87. paddlex/inference/pipelines/image_multilabel_classification/pipeline.py +16 -6
  88. paddlex/inference/pipelines/instance_segmentation/pipeline.py +16 -6
  89. paddlex/inference/pipelines/keypoint_detection/pipeline.py +16 -6
  90. paddlex/inference/pipelines/layout_parsing/layout_objects.py +859 -0
  91. paddlex/inference/pipelines/layout_parsing/pipeline.py +34 -47
  92. paddlex/inference/pipelines/layout_parsing/pipeline_v2.py +832 -260
  93. paddlex/inference/pipelines/layout_parsing/result.py +4 -17
  94. paddlex/inference/pipelines/layout_parsing/result_v2.py +259 -245
  95. paddlex/inference/pipelines/layout_parsing/setting.py +88 -0
  96. paddlex/inference/pipelines/layout_parsing/utils.py +391 -2028
  97. paddlex/inference/pipelines/layout_parsing/xycut_enhanced/__init__.py +16 -0
  98. paddlex/inference/pipelines/layout_parsing/xycut_enhanced/utils.py +1199 -0
  99. paddlex/inference/pipelines/layout_parsing/xycut_enhanced/xycuts.py +615 -0
  100. paddlex/inference/pipelines/m_3d_bev_detection/pipeline.py +2 -2
  101. paddlex/inference/pipelines/multilingual_speech_recognition/pipeline.py +2 -2
  102. paddlex/inference/pipelines/object_detection/pipeline.py +16 -6
  103. paddlex/inference/pipelines/ocr/pipeline.py +127 -70
  104. paddlex/inference/pipelines/ocr/result.py +21 -18
  105. paddlex/inference/pipelines/open_vocabulary_detection/pipeline.py +2 -2
  106. paddlex/inference/pipelines/open_vocabulary_segmentation/pipeline.py +2 -2
  107. paddlex/inference/pipelines/pp_chatocr/pipeline_base.py +2 -2
  108. paddlex/inference/pipelines/pp_chatocr/pipeline_v3.py +2 -5
  109. paddlex/inference/pipelines/pp_chatocr/pipeline_v4.py +6 -6
  110. paddlex/inference/pipelines/rotated_object_detection/pipeline.py +16 -6
  111. paddlex/inference/pipelines/seal_recognition/pipeline.py +109 -53
  112. paddlex/inference/pipelines/semantic_segmentation/pipeline.py +16 -6
  113. paddlex/inference/pipelines/small_object_detection/pipeline.py +16 -6
  114. paddlex/inference/pipelines/table_recognition/pipeline.py +26 -18
  115. paddlex/inference/pipelines/table_recognition/pipeline_v2.py +624 -53
  116. paddlex/inference/pipelines/table_recognition/result.py +1 -1
  117. paddlex/inference/pipelines/table_recognition/table_recognition_post_processing_v2.py +9 -5
  118. paddlex/inference/pipelines/ts_anomaly_detection/pipeline.py +2 -2
  119. paddlex/inference/pipelines/ts_classification/pipeline.py +2 -2
  120. paddlex/inference/pipelines/ts_forecasting/pipeline.py +2 -2
  121. paddlex/inference/pipelines/video_classification/pipeline.py +2 -2
  122. paddlex/inference/pipelines/video_detection/pipeline.py +2 -2
  123. paddlex/inference/serving/basic_serving/_app.py +46 -13
  124. paddlex/inference/serving/basic_serving/_pipeline_apps/_common/common.py +5 -1
  125. paddlex/inference/serving/basic_serving/_pipeline_apps/layout_parsing.py +0 -1
  126. paddlex/inference/serving/basic_serving/_pipeline_apps/pp_chatocrv3_doc.py +0 -1
  127. paddlex/inference/serving/basic_serving/_pipeline_apps/pp_chatocrv4_doc.py +1 -1
  128. paddlex/inference/serving/basic_serving/_pipeline_apps/pp_structurev3.py +6 -2
  129. paddlex/inference/serving/basic_serving/_pipeline_apps/table_recognition.py +1 -5
  130. paddlex/inference/serving/basic_serving/_pipeline_apps/table_recognition_v2.py +4 -5
  131. paddlex/inference/serving/infra/utils.py +20 -22
  132. paddlex/inference/serving/schemas/formula_recognition.py +1 -1
  133. paddlex/inference/serving/schemas/layout_parsing.py +1 -2
  134. paddlex/inference/serving/schemas/pp_chatocrv3_doc.py +1 -2
  135. paddlex/inference/serving/schemas/pp_chatocrv4_doc.py +2 -2
  136. paddlex/inference/serving/schemas/pp_structurev3.py +10 -6
  137. paddlex/inference/serving/schemas/seal_recognition.py +1 -1
  138. paddlex/inference/serving/schemas/table_recognition.py +2 -6
  139. paddlex/inference/serving/schemas/table_recognition_v2.py +5 -6
  140. paddlex/inference/utils/hpi.py +30 -16
  141. paddlex/inference/utils/hpi_model_info_collection.json +666 -162
  142. paddlex/inference/utils/io/readers.py +12 -12
  143. paddlex/inference/utils/misc.py +20 -0
  144. paddlex/inference/utils/mkldnn_blocklist.py +59 -0
  145. paddlex/inference/utils/official_models.py +140 -5
  146. paddlex/inference/utils/pp_option.py +74 -9
  147. paddlex/model.py +2 -2
  148. paddlex/modules/__init__.py +1 -1
  149. paddlex/modules/anomaly_detection/evaluator.py +2 -2
  150. paddlex/modules/base/__init__.py +1 -1
  151. paddlex/modules/base/evaluator.py +5 -5
  152. paddlex/modules/base/trainer.py +1 -1
  153. paddlex/modules/doc_vlm/dataset_checker.py +2 -2
  154. paddlex/modules/doc_vlm/evaluator.py +2 -2
  155. paddlex/modules/doc_vlm/exportor.py +2 -2
  156. paddlex/modules/doc_vlm/model_list.py +1 -1
  157. paddlex/modules/doc_vlm/trainer.py +2 -2
  158. paddlex/modules/face_recognition/evaluator.py +2 -2
  159. paddlex/modules/formula_recognition/evaluator.py +5 -2
  160. paddlex/modules/formula_recognition/model_list.py +3 -0
  161. paddlex/modules/formula_recognition/trainer.py +3 -0
  162. paddlex/modules/general_recognition/evaluator.py +1 -1
  163. paddlex/modules/image_classification/evaluator.py +2 -2
  164. paddlex/modules/image_classification/model_list.py +1 -0
  165. paddlex/modules/instance_segmentation/evaluator.py +1 -1
  166. paddlex/modules/keypoint_detection/evaluator.py +1 -1
  167. paddlex/modules/m_3d_bev_detection/evaluator.py +2 -2
  168. paddlex/modules/multilabel_classification/evaluator.py +2 -2
  169. paddlex/modules/object_detection/dataset_checker/dataset_src/convert_dataset.py +4 -4
  170. paddlex/modules/object_detection/evaluator.py +2 -2
  171. paddlex/modules/object_detection/model_list.py +2 -0
  172. paddlex/modules/semantic_segmentation/dataset_checker/__init__.py +12 -2
  173. paddlex/modules/semantic_segmentation/evaluator.py +2 -2
  174. paddlex/modules/table_recognition/evaluator.py +2 -2
  175. paddlex/modules/text_detection/evaluator.py +2 -2
  176. paddlex/modules/text_detection/model_list.py +2 -0
  177. paddlex/modules/text_recognition/evaluator.py +2 -2
  178. paddlex/modules/text_recognition/model_list.py +2 -0
  179. paddlex/modules/ts_anomaly_detection/evaluator.py +2 -2
  180. paddlex/modules/ts_classification/dataset_checker/dataset_src/split_dataset.py +1 -1
  181. paddlex/modules/ts_classification/evaluator.py +2 -2
  182. paddlex/modules/ts_forecast/evaluator.py +2 -2
  183. paddlex/modules/video_classification/evaluator.py +2 -2
  184. paddlex/modules/video_detection/evaluator.py +2 -2
  185. paddlex/ops/__init__.py +8 -5
  186. paddlex/paddlex_cli.py +19 -13
  187. paddlex/repo_apis/Paddle3D_api/bev_fusion/model.py +2 -2
  188. paddlex/repo_apis/PaddleClas_api/cls/config.py +1 -1
  189. paddlex/repo_apis/PaddleClas_api/cls/model.py +1 -1
  190. paddlex/repo_apis/PaddleClas_api/cls/register.py +10 -0
  191. paddlex/repo_apis/PaddleClas_api/cls/runner.py +1 -1
  192. paddlex/repo_apis/PaddleDetection_api/instance_seg/model.py +1 -1
  193. paddlex/repo_apis/PaddleDetection_api/instance_seg/runner.py +1 -1
  194. paddlex/repo_apis/PaddleDetection_api/object_det/config.py +1 -1
  195. paddlex/repo_apis/PaddleDetection_api/object_det/model.py +1 -1
  196. paddlex/repo_apis/PaddleDetection_api/object_det/official_categories.py +25 -0
  197. paddlex/repo_apis/PaddleDetection_api/object_det/register.py +30 -0
  198. paddlex/repo_apis/PaddleDetection_api/object_det/runner.py +1 -1
  199. paddlex/repo_apis/PaddleOCR_api/formula_rec/config.py +3 -3
  200. paddlex/repo_apis/PaddleOCR_api/formula_rec/model.py +5 -9
  201. paddlex/repo_apis/PaddleOCR_api/formula_rec/register.py +27 -0
  202. paddlex/repo_apis/PaddleOCR_api/formula_rec/runner.py +1 -1
  203. paddlex/repo_apis/PaddleOCR_api/table_rec/model.py +1 -1
  204. paddlex/repo_apis/PaddleOCR_api/table_rec/runner.py +1 -1
  205. paddlex/repo_apis/PaddleOCR_api/text_det/model.py +1 -1
  206. paddlex/repo_apis/PaddleOCR_api/text_det/register.py +18 -0
  207. paddlex/repo_apis/PaddleOCR_api/text_det/runner.py +1 -1
  208. paddlex/repo_apis/PaddleOCR_api/text_rec/config.py +3 -3
  209. paddlex/repo_apis/PaddleOCR_api/text_rec/model.py +5 -9
  210. paddlex/repo_apis/PaddleOCR_api/text_rec/register.py +18 -0
  211. paddlex/repo_apis/PaddleOCR_api/text_rec/runner.py +1 -1
  212. paddlex/repo_apis/PaddleSeg_api/seg/model.py +1 -1
  213. paddlex/repo_apis/PaddleSeg_api/seg/runner.py +1 -1
  214. paddlex/repo_apis/PaddleTS_api/ts_ad/config.py +3 -3
  215. paddlex/repo_apis/PaddleTS_api/ts_cls/config.py +2 -2
  216. paddlex/repo_apis/PaddleTS_api/ts_fc/config.py +4 -4
  217. paddlex/repo_apis/PaddleVideo_api/video_cls/config.py +1 -1
  218. paddlex/repo_apis/PaddleVideo_api/video_cls/model.py +1 -1
  219. paddlex/repo_apis/PaddleVideo_api/video_cls/runner.py +1 -1
  220. paddlex/repo_apis/PaddleVideo_api/video_det/config.py +1 -1
  221. paddlex/repo_apis/PaddleVideo_api/video_det/model.py +1 -1
  222. paddlex/repo_apis/PaddleVideo_api/video_det/runner.py +1 -1
  223. paddlex/repo_apis/base/config.py +1 -1
  224. paddlex/repo_manager/core.py +3 -3
  225. paddlex/repo_manager/meta.py +6 -2
  226. paddlex/repo_manager/repo.py +17 -16
  227. paddlex/utils/custom_device_list.py +26 -2
  228. paddlex/utils/deps.py +3 -3
  229. paddlex/utils/device.py +5 -13
  230. paddlex/utils/env.py +4 -0
  231. paddlex/utils/flags.py +11 -4
  232. paddlex/utils/fonts/__init__.py +34 -4
  233. paddlex/utils/misc.py +1 -1
  234. paddlex/utils/subclass_register.py +2 -2
  235. {paddlex-3.0.0rc1.dist-info → paddlex-3.0.2.dist-info}/METADATA +349 -208
  236. {paddlex-3.0.0rc1.dist-info → paddlex-3.0.2.dist-info}/RECORD +240 -211
  237. {paddlex-3.0.0rc1.dist-info → paddlex-3.0.2.dist-info}/WHEEL +1 -1
  238. {paddlex-3.0.0rc1.dist-info → paddlex-3.0.2.dist-info}/entry_points.txt +1 -0
  239. {paddlex-3.0.0rc1.dist-info/licenses → paddlex-3.0.2.dist-info}/LICENSE +0 -0
  240. {paddlex-3.0.0rc1.dist-info → paddlex-3.0.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,830 @@
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
+ from functools import partial
16
+ from typing import List, Optional, Tuple, Type
17
+
18
+ import paddle
19
+ import paddle.nn as nn
20
+ import paddle.nn.functional as F
21
+
22
+ from ...common.vlm.transformers.model_outputs import CausalLMOutputWithPast
23
+ from .qwen2 import Qwen2Config, Qwen2ForCausalLM, Qwen2Model
24
+
25
+
26
+ class MLPBlock(paddle.nn.Layer):
27
+ def __init__(
28
+ self,
29
+ embedding_dim: int,
30
+ mlp_dim: int,
31
+ act: Type[paddle.nn.Layer] = paddle.nn.GELU,
32
+ ) -> None:
33
+ super().__init__()
34
+ self.lin1 = nn.Linear(embedding_dim, mlp_dim)
35
+ self.lin2 = nn.Linear(mlp_dim, embedding_dim)
36
+ self.act = act()
37
+
38
+ def forward(self, x: paddle.Tensor) -> paddle.Tensor:
39
+ return self.lin2(self.act(self.lin1(x)))
40
+
41
+
42
+ class LayerNorm2d(paddle.nn.Layer):
43
+ def __init__(self, num_channels: int, epsilon: float = 1e-06) -> None:
44
+ super().__init__()
45
+ self.weight = paddle.base.framework.EagerParamBase.from_tensor(
46
+ tensor=paddle.ones(shape=num_channels)
47
+ )
48
+ self.bias = paddle.base.framework.EagerParamBase.from_tensor(
49
+ tensor=paddle.zeros(shape=num_channels)
50
+ )
51
+ self.epsilon = epsilon
52
+
53
+ def forward(self, x: paddle.Tensor) -> paddle.Tensor:
54
+ u = x.mean(axis=1, keepdim=True)
55
+ s = (x - u).pow(y=2).mean(axis=1, keepdim=True)
56
+ x = (x - u) / paddle.sqrt(x=s + self.epsilon)
57
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
58
+ return x
59
+
60
+
61
+ class ImageEncoderViT(paddle.nn.Layer):
62
+ def __init__(
63
+ self,
64
+ img_size: int = 1024,
65
+ patch_size: int = 16,
66
+ in_chans: int = 3,
67
+ embed_dim: int = 768,
68
+ depth: int = 12,
69
+ num_heads: int = 12,
70
+ mlp_ratio: float = 4.0,
71
+ out_chans: int = 256,
72
+ qkv_bias: bool = True,
73
+ norm_layer: Type[nn.Layer] = nn.LayerNorm,
74
+ act_layer: Type[nn.Layer] = nn.GELU,
75
+ use_abs_pos: bool = True,
76
+ use_rel_pos: bool = False,
77
+ rel_pos_zero_init: bool = True,
78
+ window_size: int = 0,
79
+ global_attn_indexes: Tuple[int, ...] = (),
80
+ ) -> None:
81
+ """
82
+ Args:
83
+ img_size (int): Input image size.
84
+ patch_size (int): Patch size.
85
+ in_chans (int): Number of input image channels.
86
+ embed_dim (int): Patch embedding dimension.
87
+ depth (int): Depth of ViT.
88
+ num_heads (int): Number of attention heads in each ViT block.
89
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
90
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
91
+ norm_layer (nn.Layer): Normalization layer.
92
+ act_layer (nn.Layer): Activation layer.
93
+ use_abs_pos (bool): If True, use absolute positional embeddings.
94
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
95
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
96
+ window_size (int): Window size for window attention blocks.
97
+ global_attn_indexes (list): Indexes for blocks using global attention.
98
+ """
99
+ super().__init__()
100
+ self.img_size = img_size
101
+
102
+ self.patch_embed = PatchEmbed(
103
+ kernel_size=(patch_size, patch_size),
104
+ stride=(patch_size, patch_size),
105
+ in_chans=in_chans,
106
+ embed_dim=embed_dim,
107
+ )
108
+
109
+ self.pos_embed: Optional[paddle.base.framework.EagerParamBase.from_tensor] = (
110
+ None
111
+ )
112
+ if use_abs_pos:
113
+ self.pos_embed = paddle.base.framework.EagerParamBase.from_tensor(
114
+ tensor=paddle.zeros(
115
+ shape=[1, img_size // patch_size, img_size // patch_size, embed_dim]
116
+ )
117
+ )
118
+
119
+ self.blocks = paddle.nn.LayerList()
120
+ for i in range(depth):
121
+ block = Block(
122
+ dim=embed_dim,
123
+ num_heads=num_heads,
124
+ mlp_ratio=mlp_ratio,
125
+ qkv_bias=qkv_bias,
126
+ norm_layer=norm_layer,
127
+ act_layer=act_layer,
128
+ use_rel_pos=use_rel_pos,
129
+ rel_pos_zero_init=rel_pos_zero_init,
130
+ window_size=window_size if i not in global_attn_indexes else 0,
131
+ input_size=(img_size // patch_size, img_size // patch_size),
132
+ )
133
+ self.blocks.append(block)
134
+
135
+ self.neck = nn.Sequential(
136
+ nn.Conv2D(
137
+ embed_dim,
138
+ out_chans,
139
+ kernel_size=1,
140
+ bias_attr=False,
141
+ ),
142
+ LayerNorm2d(out_chans),
143
+ nn.Conv2D(
144
+ out_chans,
145
+ out_chans,
146
+ kernel_size=3,
147
+ padding=1,
148
+ bias_attr=False,
149
+ ),
150
+ LayerNorm2d(out_chans),
151
+ )
152
+
153
+ self.net_2 = nn.Conv2D(
154
+ 256, 512, kernel_size=3, stride=2, padding=1, bias_attr=False
155
+ )
156
+ self.net_3 = nn.Conv2D(
157
+ 512, 1024, kernel_size=3, stride=2, padding=1, bias_attr=False
158
+ )
159
+
160
+ def forward(self, x: paddle.Tensor) -> paddle.Tensor:
161
+ x = self.patch_embed(x)
162
+ if self.pos_embed is not None:
163
+ x = x + self.pos_embed
164
+ for blk in self.blocks:
165
+ x = blk(x)
166
+ x = self.neck(x.transpose([0, 3, 1, 2]))
167
+ x = self.net_2(x)
168
+ x = self.net_3(x)
169
+ return x
170
+
171
+
172
+ class Block(paddle.nn.Layer):
173
+ """Transformer blocks with support of window attention and residual propagation blocks"""
174
+
175
+ def __init__(
176
+ self,
177
+ dim: int,
178
+ num_heads: int,
179
+ mlp_ratio: float = 4.0,
180
+ qkv_bias: bool = True,
181
+ norm_layer: Type[nn.Layer] = nn.LayerNorm,
182
+ act_layer: Type[nn.Layer] = nn.GELU,
183
+ use_rel_pos: bool = False,
184
+ rel_pos_zero_init: bool = True,
185
+ window_size: int = 0,
186
+ input_size: Optional[Tuple[int, int]] = None,
187
+ ) -> None:
188
+ """
189
+ Args:
190
+ dim (int): Number of input channels.
191
+ num_heads (int): Number of attention heads in each ViT block.
192
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
193
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
194
+ norm_layer (nn.Layer): Normalization layer.
195
+ act_layer (nn.Layer): Activation layer.
196
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
197
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
198
+ window_size (int): Window size for window attention blocks. If it equals 0, then
199
+ use global attention.
200
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
201
+ positional parameter size.
202
+ """
203
+ super().__init__()
204
+ self.norm1 = norm_layer(dim)
205
+ self.attn = Attention(
206
+ dim,
207
+ num_heads=num_heads,
208
+ qkv_bias=qkv_bias,
209
+ use_rel_pos=use_rel_pos,
210
+ rel_pos_zero_init=rel_pos_zero_init,
211
+ input_size=input_size if window_size == 0 else (window_size, window_size),
212
+ )
213
+
214
+ self.norm2 = norm_layer(dim)
215
+ self.mlp = MLPBlock(
216
+ embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer
217
+ )
218
+
219
+ self.window_size = window_size
220
+
221
+ def forward(self, x: paddle.Tensor) -> paddle.Tensor:
222
+ shortcut = x
223
+ x = self.norm1(x)
224
+ # Window partition
225
+ if self.window_size > 0:
226
+ H, W = x.shape[1], x.shape[2]
227
+ x, pad_hw = window_partition(x, self.window_size)
228
+
229
+ x = self.attn(x)
230
+ # Reverse window partition
231
+ if self.window_size > 0:
232
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
233
+
234
+ x = shortcut + x
235
+ x = x + self.mlp(self.norm2(x))
236
+
237
+ return x
238
+
239
+
240
+ class Attention(paddle.nn.Layer):
241
+ """Multi-head Attention block with relative position embeddings."""
242
+
243
+ def __init__(
244
+ self,
245
+ dim: int,
246
+ num_heads: int = 8,
247
+ qkv_bias: bool = True,
248
+ use_rel_pos: bool = False,
249
+ rel_pos_zero_init: bool = True,
250
+ input_size: Optional[Tuple[int, int]] = None,
251
+ ) -> None:
252
+ """
253
+ Args:
254
+ dim (int): Number of input channels.
255
+ num_heads (int): Number of attention heads.
256
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
257
+ rel_pos (bool): If True, add relative positional embeddings to the attention map.
258
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
259
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
260
+ positional parameter size.
261
+ """
262
+ super().__init__()
263
+ self.num_heads = num_heads
264
+ head_dim = dim // num_heads
265
+ self.scale = head_dim**-0.5
266
+
267
+ self.qkv = nn.Linear(dim, dim * 3, bias_attr=qkv_bias)
268
+ self.proj = nn.Linear(dim, dim)
269
+
270
+ self.use_rel_pos = use_rel_pos
271
+ if self.use_rel_pos:
272
+ assert (
273
+ input_size is not None
274
+ ), "Input size must be provided if using relative positional encoding."
275
+ self.rel_pos_h = paddle.base.framework.EagerParamBase.from_tensor(
276
+ tensor=paddle.zeros(shape=[2 * input_size[0] - 1, head_dim])
277
+ )
278
+ self.rel_pos_w = paddle.base.framework.EagerParamBase.from_tensor(
279
+ tensor=paddle.zeros(shape=[2 * input_size[1] - 1, head_dim])
280
+ )
281
+
282
+ def forward(self, x: paddle.Tensor) -> paddle.Tensor:
283
+ B, H, W, _ = tuple(x.shape)
284
+ qkv = (
285
+ self.qkv(x)
286
+ .reshape([B, H * W, 3, self.num_heads, -1])
287
+ .transpose([2, 0, 3, 1, 4])
288
+ )
289
+ q, k, v = qkv.reshape([3, B * self.num_heads, H * W, -1]).unbind(axis=0)
290
+
291
+ attn = (q * self.scale) @ k.transpose([0, 2, 1])
292
+
293
+ if self.use_rel_pos:
294
+ attn = add_decomposed_rel_pos(
295
+ attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)
296
+ )
297
+
298
+ attn = F.softmax(attn, axis=-1)
299
+ x = (
300
+ (attn @ v)
301
+ .reshape([B, self.num_heads, H, W, -1])
302
+ .transpose([0, 2, 3, 1, 4])
303
+ .reshape([B, H, W, -1])
304
+ )
305
+ x = self.proj(x)
306
+
307
+ return x
308
+
309
+
310
+ def window_partition(
311
+ x: paddle.Tensor, window_size: int
312
+ ) -> Tuple[paddle.Tensor, Tuple[int, int]]:
313
+ """
314
+ Partition into non-overlapping windows with padding if needed.
315
+ Args:
316
+ x (tensor): input tokens with [B, H, W, C].
317
+ window_size (int): window size.
318
+
319
+ Returns:
320
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
321
+ (Hp, Wp): padded height and width before partition
322
+ """
323
+ B, H, W, C = tuple(x.shape)
324
+
325
+ pad_h = (window_size - H % window_size) % window_size
326
+ pad_w = (window_size - W % window_size) % window_size
327
+ if pad_h > 0 or pad_w > 0:
328
+ x = F.pad(x, pad=(0, pad_w, 0, pad_h), data_format="NHWC")
329
+ Hp, Wp = H + pad_h, W + pad_w
330
+
331
+ x = x.reshape(
332
+ [B, Hp // window_size, window_size, Wp // window_size, window_size, C]
333
+ )
334
+ windows = x.transpose([0, 1, 3, 2, 4, 5]).reshape([-1, window_size, window_size, C])
335
+ return windows, (Hp, Wp)
336
+
337
+
338
+ def window_unpartition(
339
+ windows: paddle.Tensor,
340
+ window_size: int,
341
+ pad_hw: Tuple[int, int],
342
+ hw: Tuple[int, int],
343
+ ) -> paddle.Tensor:
344
+ """
345
+ Window unpartition into original sequences and removing padding.
346
+ Args:
347
+ windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].
348
+ window_size (int): window size.
349
+ pad_hw (Tuple): padded height and width (Hp, Wp).
350
+ hw (Tuple): original height and width (H, W) before padding.
351
+
352
+ Returns:
353
+ x: unpartitioned sequences with [B, H, W, C].
354
+ """
355
+ Hp, Wp = pad_hw
356
+ H, W = hw
357
+ B = tuple(windows.shape)[0] // (Hp * Wp // window_size // window_size)
358
+ x = windows.reshape(
359
+ [B, Hp // window_size, Wp // window_size, window_size, window_size, -1]
360
+ )
361
+ x = x.transpose([0, 1, 3, 2, 4, 5]).reshape([B, Hp, Wp, -1])
362
+ if Hp > H or Wp > W:
363
+ x = x[:, :H, :W, :]
364
+ return x
365
+
366
+
367
+ def get_rel_pos(q_size: int, k_size: int, rel_pos: paddle.Tensor) -> paddle.Tensor:
368
+ """
369
+ Get relative positional embeddings according to the relative positions of
370
+ query and key sizes.
371
+ Args:
372
+ q_size (int): size of query q.
373
+ k_size (int): size of key k.
374
+ rel_pos (Tensor): relative position embeddings (L, C).
375
+
376
+ Returns:
377
+ Extracted positional embeddings according to relative positions.
378
+ """
379
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
380
+ if tuple(rel_pos.shape)[0] != max_rel_dist:
381
+ rel_pos_resized = paddle.nn.functional.interpolate(
382
+ rel_pos.reshape([1, tuple(rel_pos.shape)[0], -1]).transpose([0, 2, 1]),
383
+ size=max_rel_dist,
384
+ mode="linear",
385
+ )
386
+ rel_pos_resized = rel_pos_resized.reshape([-1, max_rel_dist]).transpose([1, 0])
387
+ else:
388
+ rel_pos_resized = rel_pos
389
+
390
+ q_coords = paddle.arange(end=q_size)[:, None] * max(k_size / q_size, 1.0)
391
+ k_coords = paddle.arange(end=k_size)[None, :] * max(q_size / k_size, 1.0)
392
+ relative_coords = q_coords - k_coords + (k_size - 1) * max(q_size / k_size, 1.0)
393
+ return rel_pos_resized[relative_coords.astype(dtype="int64")]
394
+
395
+
396
+ def add_decomposed_rel_pos(
397
+ attn: paddle.Tensor,
398
+ q: paddle.Tensor,
399
+ rel_pos_h: paddle.Tensor,
400
+ rel_pos_w: paddle.Tensor,
401
+ q_size: Tuple[int, int],
402
+ k_size: Tuple[int, int],
403
+ ) -> paddle.Tensor:
404
+ """
405
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
406
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
407
+ Args:
408
+ attn (Tensor): attention map.
409
+ q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
410
+ rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
411
+ rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
412
+ q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
413
+ k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
414
+
415
+ Returns:
416
+ attn (Tensor): attention map with added relative positional embeddings.
417
+ """
418
+ q_h, q_w = q_size
419
+ k_h, k_w = k_size
420
+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)
421
+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)
422
+
423
+ B, _, dim = tuple(q.shape)
424
+ r_q = q.reshape([B, q_h, q_w, dim])
425
+ rel_h = paddle.einsum("bhwc,hkc->bhwk", r_q, Rh)
426
+ rel_w = paddle.einsum("bhwc,wkc->bhwk", r_q, Rw)
427
+
428
+ attn = (
429
+ attn.reshape([B, q_h, q_w, k_h, k_w])
430
+ + rel_h[:, :, :, :, None]
431
+ + rel_w[:, :, :, None, :]
432
+ ).reshape([B, q_h * q_w, k_h * k_w])
433
+
434
+ return attn
435
+
436
+
437
+ class PatchEmbed(paddle.nn.Layer):
438
+ """
439
+ Image to Patch Embedding.
440
+ """
441
+
442
+ def __init__(
443
+ self,
444
+ kernel_size: Tuple[int, int] = (16, 16),
445
+ stride: Tuple[int, int] = (16, 16),
446
+ padding: Tuple[int, int] = (0, 0),
447
+ in_chans: int = 3,
448
+ embed_dim: int = 768,
449
+ ) -> None:
450
+ """
451
+ Args:
452
+ kernel_size (Tuple): kernel size of the projection layer.
453
+ stride (Tuple): stride of the projection layer.
454
+ padding (Tuple): padding size of the projection layer.
455
+ in_chans (int): Number of input image channels.
456
+ embed_dim (int): Patch embedding dimension.
457
+ """
458
+ super().__init__()
459
+ self.proj = nn.Conv2D(
460
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
461
+ )
462
+
463
+ def forward(self, x: paddle.Tensor) -> paddle.Tensor:
464
+ x = self.proj(x)
465
+ # B C H W -> B H W C
466
+ x = x.transpose([0, 2, 3, 1])
467
+ return x
468
+
469
+
470
+ DEFAULT_IMAGE_TOKEN = "<image>"
471
+ DEFAULT_IMAGE_PATCH_TOKEN = "<imgpad>"
472
+ DEFAULT_IM_START_TOKEN = "<img>"
473
+ DEFAULT_IM_END_TOKEN = "</img>"
474
+
475
+
476
+ class Qwen2LMHead(nn.Layer):
477
+ def __init__(
478
+ self,
479
+ config,
480
+ embedding_weights=None,
481
+ transpose_y=False,
482
+ tensor_parallel_output=1,
483
+ ):
484
+ super(Qwen2LMHead, self).__init__()
485
+ self.config = config
486
+ vocab_size = config.vocab_size
487
+
488
+ self.transpose_y = transpose_y
489
+ if transpose_y:
490
+ # only for weight from embedding_weights
491
+ if embedding_weights is not None:
492
+ self.weight = embedding_weights
493
+ else:
494
+ self.weight = self.create_parameter(
495
+ shape=[vocab_size, config.hidden_size],
496
+ dtype=paddle.get_default_dtype(),
497
+ )
498
+ else:
499
+ # for weight from model init
500
+ self.weight = self.create_parameter(
501
+ shape=[config.hidden_size, vocab_size],
502
+ dtype=paddle.get_default_dtype(),
503
+ )
504
+
505
+ def forward(self, hidden_states, tensor_parallel_output=1):
506
+ logits = paddle.matmul(hidden_states, self.weight, transpose_y=self.transpose_y)
507
+ return logits
508
+
509
+
510
+ class GOTConfig(Qwen2Config):
511
+ model_type = "GOT"
512
+
513
+
514
+ class GOTQwenModel(Qwen2Model):
515
+ config_class = GOTConfig
516
+
517
+ def __init__(self, config: Qwen2Config):
518
+ super(GOTQwenModel, self).__init__(config)
519
+ self.vision_tower_high = ImageEncoderViT(
520
+ depth=12,
521
+ embed_dim=768,
522
+ img_size=1024,
523
+ mlp_ratio=4,
524
+ norm_layer=partial(paddle.nn.LayerNorm, epsilon=1e-6),
525
+ num_heads=12,
526
+ patch_size=16,
527
+ qkv_bias=True,
528
+ use_rel_pos=True,
529
+ global_attn_indexes=[2, 5, 8, 11],
530
+ window_size=14,
531
+ out_chans=256,
532
+ )
533
+ self.mm_projector_vary = nn.Linear(1024, 1024)
534
+
535
+ def forward(
536
+ self,
537
+ input_ids: paddle.Tensor = None,
538
+ attention_mask: Optional[paddle.Tensor] = None,
539
+ position_ids: Optional[paddle.Tensor] = None,
540
+ past_key_values: Optional[List[paddle.Tensor]] = None,
541
+ inputs_embeds: Optional[paddle.Tensor] = None,
542
+ use_cache: Optional[bool] = None,
543
+ output_attentions: Optional[bool] = None,
544
+ output_hidden_states: Optional[bool] = None,
545
+ images: Optional[paddle.Tensor] = None,
546
+ return_dict: Optional[bool] = None,
547
+ ):
548
+ # HACK: replace back original embeddings for LLaVA pretraining
549
+ orig_embeds_params = getattr(self, "orig_embeds_params", None)
550
+ if orig_embeds_params is not None:
551
+ with paddle.no_grad():
552
+ self.get_input_embeddings().weight[: -self.num_new_tokens] = (
553
+ orig_embeds_params[: -self.num_new_tokens].data
554
+ )
555
+
556
+ if inputs_embeds is None:
557
+ inputs_embeds = self.embed_tokens(input_ids)
558
+
559
+ vision_tower_high = getattr(self, "vision_tower_high", None)
560
+
561
+ if (
562
+ vision_tower_high is not None
563
+ and (input_ids.shape[1] != 1 or self.training)
564
+ and images is not None
565
+ ):
566
+ use_im_start_end = getattr(self.config, "use_im_start_end", -1)
567
+
568
+ im_patch_token = getattr(self.config, "im_patch_token", -1)
569
+ im_start_token = getattr(self.config, "im_start_token", -1)
570
+ im_end_token = getattr(self.config, "im_end_token", -1)
571
+
572
+ im_patch_token = 151859
573
+ im_start_token = 151857
574
+ im_end_token = 151858
575
+
576
+ image_features = []
577
+
578
+ for image in images:
579
+ if self.training:
580
+ image = image[1]
581
+ P, C, H, W = image.shape
582
+ if P == 1:
583
+ with paddle.set_grad_enabled(False):
584
+ cnn_feature = vision_tower_high(image)
585
+ cnn_feature = cnn_feature.flatten(2).transpose(
586
+ [0, 2, 1]
587
+ ) # 256*1024
588
+ image_feature = self.mm_projector_vary(cnn_feature)
589
+ image_features.append(image_feature)
590
+
591
+ else:
592
+ image_patches = paddle.unbind(image)
593
+ image_patches_features = []
594
+ for image_patch in image_patches:
595
+ image_p = paddle.stack([image_patch])
596
+ with paddle.set_grad_enabled(False):
597
+ cnn_feature_p = vision_tower_high(image_p)
598
+ cnn_feature_p = cnn_feature_p.flatten(2).transpose(
599
+ [0, 2, 1]
600
+ )
601
+ image_feature_p = self.mm_projector_vary(cnn_feature_p)
602
+ image_patches_features.append(image_feature_p)
603
+ image_feature = paddle.concat(image_patches_features, axis=1)
604
+ image_features.append(image_feature)
605
+
606
+ dummy_image_features_2 = paddle.zeros(
607
+ [256, 1024], dtype=inputs_embeds.dtype
608
+ )
609
+ dummy_image_features = dummy_image_features_2
610
+ use_im_start_end = True
611
+ new_input_embeds = []
612
+ for cur_input_ids, cur_input_embeds, cur_image_features in zip(
613
+ input_ids, inputs_embeds, image_features
614
+ ):
615
+ if (cur_input_ids == im_patch_token).sum() == 0:
616
+ # multimodal LLM, but the current sample is not multimodal
617
+ cur_input_embeds = (
618
+ cur_input_embeds + (0.0 * dummy_image_features).sum()
619
+ )
620
+ new_input_embeds.append(cur_input_embeds)
621
+ continue
622
+
623
+ if use_im_start_end:
624
+ if (cur_input_ids == im_start_token).sum() != (
625
+ cur_input_ids == im_end_token
626
+ ).sum():
627
+ raise ValueError(
628
+ "The number of image start tokens and image end tokens should be the same."
629
+ )
630
+
631
+ image_start_tokens = paddle.where(cur_input_ids == im_start_token)[
632
+ 0
633
+ ]
634
+ for image_start_token_pos, per_cur_image_features in zip(
635
+ image_start_tokens, cur_image_features
636
+ ):
637
+ num_patches = per_cur_image_features.shape[0]
638
+
639
+ if (
640
+ cur_input_ids[image_start_token_pos + num_patches + 1]
641
+ != im_end_token
642
+ ):
643
+ raise ValueError(
644
+ "The image end token should follow the image start token."
645
+ )
646
+
647
+ cur_input_embeds = paddle.concat(
648
+ (
649
+ cur_input_embeds[: image_start_token_pos + 1],
650
+ per_cur_image_features,
651
+ cur_input_embeds[
652
+ image_start_token_pos + num_patches + 1 :
653
+ ],
654
+ ),
655
+ axis=0,
656
+ )
657
+
658
+ new_input_embeds.append(cur_input_embeds)
659
+ else:
660
+ raise NotImplementedError
661
+
662
+ inputs_embeds = paddle.stack(new_input_embeds, axis=0)
663
+
664
+ return super().forward(
665
+ input_ids=None,
666
+ attention_mask=attention_mask,
667
+ past_key_values=past_key_values,
668
+ inputs_embeds=inputs_embeds,
669
+ use_cache=use_cache,
670
+ position_ids=position_ids,
671
+ output_attentions=output_attentions,
672
+ output_hidden_states=output_hidden_states,
673
+ return_dict=return_dict,
674
+ )
675
+
676
+
677
+ class GOTQwenForCausalLM(Qwen2ForCausalLM):
678
+ config_class = GOTConfig
679
+
680
+ def __init__(self, config):
681
+ super(Qwen2ForCausalLM, self).__init__(config)
682
+ self.qwen2 = GOTQwenModel(config)
683
+
684
+ self.vocab_size = config.vocab_size
685
+
686
+ if config.tie_word_embeddings:
687
+ self.lm_head = Qwen2LMHead(
688
+ config,
689
+ embedding_weights=self.qwen2.embed_tokens.weight,
690
+ transpose_y=True,
691
+ )
692
+ self.tie_weights()
693
+ else:
694
+ self.lm_head = Qwen2LMHead(config)
695
+
696
+ self.eval()
697
+
698
+ def get_model(self):
699
+ return self.qwen2
700
+
701
+ def forward(
702
+ self,
703
+ input_ids: paddle.Tensor = None,
704
+ attention_mask: Optional[paddle.Tensor] = None,
705
+ position_ids: Optional[paddle.Tensor] = None,
706
+ past_key_values: Optional[List[paddle.Tensor]] = None,
707
+ inputs_embeds: Optional[paddle.Tensor] = None,
708
+ labels: Optional[paddle.Tensor] = None,
709
+ use_cache: Optional[bool] = None,
710
+ output_attentions: Optional[bool] = None,
711
+ output_hidden_states: Optional[bool] = None,
712
+ images: Optional[paddle.Tensor] = None,
713
+ return_dict: Optional[bool] = None,
714
+ ):
715
+ output_attentions = (
716
+ output_attentions
717
+ if output_attentions is not None
718
+ else self.config.output_attentions
719
+ )
720
+ output_hidden_states = (
721
+ output_hidden_states
722
+ if output_hidden_states is not None
723
+ else self.config.output_hidden_states
724
+ )
725
+ return_dict = (
726
+ return_dict if return_dict is not None else self.config.use_return_dict
727
+ )
728
+
729
+ outputs = self.qwen2(
730
+ input_ids=input_ids,
731
+ past_key_values=past_key_values,
732
+ attention_mask=attention_mask,
733
+ position_ids=position_ids,
734
+ inputs_embeds=inputs_embeds,
735
+ use_cache=use_cache,
736
+ output_attentions=output_attentions,
737
+ output_hidden_states=output_hidden_states,
738
+ images=images,
739
+ return_dict=return_dict,
740
+ )
741
+
742
+ hidden_states = outputs[0]
743
+ logits = self.lm_head(hidden_states)
744
+ logits = logits.astype(dtype="float32")
745
+
746
+ loss = None
747
+ if labels is not None:
748
+ # Shift so that tokens < n predict n
749
+ shift_logits = logits[..., :-1, :]
750
+ shift_labels = labels[..., 1:]
751
+ loss_fct = nn.CrossEntropyLoss(reduction="sum")
752
+ shift_logits = shift_logits.reshape([-1, self.config.vocab_size])
753
+ shift_labels = shift_labels.reshape([-1])
754
+
755
+ loss = loss_fct(shift_logits, shift_labels)
756
+ label_sum = paddle.sum(shift_labels != -100)
757
+ loss = loss / label_sum
758
+
759
+ if not return_dict:
760
+ output = (logits,) + outputs[1:]
761
+ return (loss,) + output if loss is not None else output
762
+
763
+ return CausalLMOutputWithPast(
764
+ loss=loss,
765
+ logits=logits,
766
+ past_key_values=outputs.past_key_values,
767
+ hidden_states=outputs.hidden_states,
768
+ attentions=outputs.attentions,
769
+ )
770
+
771
+ def prepare_inputs_for_generation(
772
+ self,
773
+ input_ids,
774
+ past_key_values=None,
775
+ attention_mask=None,
776
+ inputs_embeds=None,
777
+ **kwargs
778
+ ):
779
+ batch_size, seq_length = input_ids.shape
780
+ attention_mask = paddle.ones((batch_size, seq_length), dtype=paddle.bool)
781
+
782
+ # Omit tokens covered by past_key_values
783
+ if past_key_values is not None:
784
+ past_length = past_key_values[0][0].shape[1]
785
+ if past_length < input_ids.shape[1]:
786
+ input_ids = input_ids[:, past_length:]
787
+
788
+ position_ids = kwargs.get("position_ids", None)
789
+ if attention_mask is not None and position_ids is None:
790
+ # create position_ids on the fly for batch generation
791
+ position_ids = attention_mask.astype(dtype="int64").cumsum(-1) - 1
792
+ position_ids.masked_fill_(attention_mask == 0, 1)
793
+ if past_key_values:
794
+ position_ids = position_ids[:, -input_ids.shape[1] :]
795
+
796
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
797
+ if inputs_embeds is not None and past_key_values is None:
798
+ model_inputs = {"inputs_embeds": inputs_embeds}
799
+ else:
800
+ model_inputs = {"input_ids": input_ids}
801
+
802
+ model_inputs.update(
803
+ {
804
+ "position_ids": position_ids,
805
+ "past_key_values": past_key_values,
806
+ "use_cache": kwargs.get("use_cache"),
807
+ "attention_mask": attention_mask,
808
+ "images": kwargs.get("images", None),
809
+ }
810
+ )
811
+ return model_inputs
812
+
813
+
814
+ class PPChart2TableInference(GOTQwenForCausalLM):
815
+
816
+ def generate(self, inputs, **kwargs):
817
+ max_new_tokens = kwargs.get("max_new_tokens", 1024)
818
+ no_repeat_ngram_size = kwargs.get("no_repeat_ngram_size", 20)
819
+
820
+ with paddle.no_grad():
821
+ generated_ids = super().generate(
822
+ inputs["input_ids"],
823
+ images=inputs["images"],
824
+ do_sample=False,
825
+ num_beams=1,
826
+ no_repeat_ngram_size=no_repeat_ngram_size,
827
+ max_new_tokens=max_new_tokens,
828
+ )
829
+
830
+ return generated_ids