qwen2_5_vl.py 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006
  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. import math
  15. from dataclasses import dataclass
  16. from functools import partial
  17. from typing import Any, Dict, List, Optional, Tuple, Union
  18. import paddle
  19. import paddle.distributed.fleet.meta_parallel as mpu
  20. import paddle.nn.functional as F
  21. from paddle import Tensor, nn
  22. from paddle.distributed import fleet
  23. from paddle.distributed.fleet.meta_parallel import get_rng_state_tracker
  24. from paddle.distributed.fleet.utils import recompute
  25. from .....utils import logging
  26. from .....utils.env import get_device_type
  27. from ...common.vlm.activations import ACT2FN
  28. from ...common.vlm.bert_padding import index_first_axis, pad_input, unpad_input
  29. from ...common.vlm.flash_attn_utils import has_flash_attn_func
  30. from ...common.vlm.transformers import PretrainedConfig, PretrainedModel
  31. from ...common.vlm.transformers.model_outputs import (
  32. BaseModelOutputWithPast,
  33. ModelOutput,
  34. )
  35. class Qwen2_5_VLVisionConfig(PretrainedConfig):
  36. model_type = "qwen2_5_vl"
  37. base_config_key = "vision_config"
  38. def __init__(
  39. self,
  40. depth=32,
  41. hidden_size=3584,
  42. hidden_act="silu",
  43. intermediate_size=3420,
  44. num_heads=16,
  45. in_channels=3,
  46. patch_size=14,
  47. spatial_merge_size=2,
  48. temporal_patch_size=2,
  49. tokens_per_second=4,
  50. window_size=112,
  51. out_hidden_size=3584,
  52. fullatt_block_indexes=[7, 15, 23, 31],
  53. **kwargs,
  54. ):
  55. super().__init__(**kwargs)
  56. self.depth = depth
  57. self.hidden_size = hidden_size
  58. self.hidden_act = hidden_act
  59. self.intermediate_size = intermediate_size
  60. self.num_heads = num_heads
  61. self.in_channels = in_channels
  62. self.patch_size = patch_size
  63. self.spatial_merge_size = spatial_merge_size
  64. self.temporal_patch_size = temporal_patch_size
  65. self.tokens_per_second = tokens_per_second
  66. self.window_size = window_size
  67. self.fullatt_block_indexes = fullatt_block_indexes
  68. self.out_hidden_size = out_hidden_size
  69. class Qwen2_5_VLConfig(PretrainedConfig):
  70. """
  71. This is the configuration class to store the configuration of a [`Qwen2_5_VLModel`]. It is used to instantiate a
  72. Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
  73. with the defaults will yield a similar configuration to that of
  74. Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
  75. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  76. documentation from [`PretrainedConfig`] for more information.
  77. Args:
  78. vocab_size (`int`, *optional*, defaults to 152064):
  79. Vocabulary size of the Qwen2_5_VL model. Defines the number of different tokens that can be represented by the
  80. `inputs_ids` passed when calling [`Qwen2_5_VLModel`]
  81. hidden_size (`int`, *optional*, defaults to 8192):
  82. Dimension of the hidden representations.
  83. intermediate_size (`int`, *optional*, defaults to 29568):
  84. Dimension of the MLP representations.
  85. num_hidden_layers (`int`, *optional*, defaults to 80):
  86. Number of hidden layers in the Transformer encoder.
  87. num_attention_heads (`int`, *optional*, defaults to 64):
  88. Number of attention heads for each attention layer in the Transformer encoder.
  89. num_key_value_heads (`int`, *optional*, defaults to 8):
  90. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  91. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  92. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  93. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  94. by meanpooling all the original heads within that group. For more details checkout [this
  95. paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
  96. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  97. The non-linear activation function (function or string) in the decoder.
  98. max_position_embeddings (`int`, *optional*, defaults to 32768):
  99. The maximum sequence length that this model might ever be used with.
  100. initializer_range (`float`, *optional*, defaults to 0.02):
  101. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  102. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  103. The epsilon used by the rms normalization layers.
  104. use_cache (`bool`, *optional*, defaults to `True`):
  105. Whether or not the model should return the last key/values attentions (not used by all models). Only
  106. relevant if `config.is_decoder=True`.
  107. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  108. Whether the model's input and output word embeddings should be tied.
  109. rope_theta (`float`, *optional*, defaults to 1000000.0):
  110. The base period of the RoPE embeddings.
  111. use_sliding_window (`bool`, *optional*, defaults to `False`):
  112. Whether to use sliding window attention.
  113. sliding_window (`int`, *optional*, defaults to 4096):
  114. Sliding window attention (SWA) window size. If not specified, will default to `4096`.
  115. max_window_layers (`int`, *optional*, defaults to 80):
  116. The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
  117. attention_dropout (`float`, *optional*, defaults to 0.0):
  118. The dropout ratio for the attention probabilities.
  119. vision_config (`Dict`, *optional*):
  120. The config for the visual encoder initialization.
  121. rope_scaling (`Dict`, *optional*):
  122. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  123. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  124. accordingly.
  125. Expected contents:
  126. `rope_type` (`str`):
  127. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  128. 'llama3'], with 'default' being the original RoPE implementation.
  129. `factor` (`float`, *optional*):
  130. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  131. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  132. original maximum pre-trained length.
  133. `original_max_position_embeddings` (`int`, *optional*):
  134. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  135. pretraining.
  136. `attention_factor` (`float`, *optional*):
  137. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  138. computation. If unspecified, it defaults to value recommended by the implementation, using the
  139. `factor` field to infer the suggested value.
  140. `beta_fast` (`float`, *optional*):
  141. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  142. ramp function. If unspecified, it defaults to 32.
  143. `beta_slow` (`float`, *optional*):
  144. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  145. ramp function. If unspecified, it defaults to 1.
  146. `short_factor` (`List[float]`, *optional*):
  147. Only used with 'longrope'. The scaling factor to be applied to short contexts (<
  148. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  149. size divided by the number of attention heads divided by 2
  150. `long_factor` (`List[float]`, *optional*):
  151. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  152. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  153. size divided by the number of attention heads divided by 2
  154. `low_freq_factor` (`float`, *optional*):
  155. Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
  156. `high_freq_factor` (`float`, *optional*):
  157. Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
  158. ```python
  159. >>> from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLConfig
  160. >>> # Initializing a Qwen2_5_VL style configuration
  161. >>> configuration = Qwen2_5_VLConfig()
  162. >>> # Initializing a model from the Qwen2-VL-7B style configuration
  163. >>> model = Qwen2_5_VLForConditionalGeneration(configuration)
  164. >>> # Accessing the model configuration
  165. >>> configuration = model.config
  166. ```"""
  167. model_type = "qwen2_5_vl"
  168. sub_configs = {"vision_config": Qwen2_5_VLVisionConfig}
  169. keys_to_ignore_at_inference = ["past_key_values"]
  170. base_model_tp_plan = {
  171. "layers.*.self_attn.q_proj": "colwise",
  172. "layers.*.self_attn.k_proj": "colwise",
  173. "layers.*.self_attn.v_proj": "colwise",
  174. "layers.*.self_attn.o_proj": "rowwise",
  175. "layers.*.mlp.gate_proj": "colwise",
  176. "layers.*.mlp.up_proj": "colwise",
  177. "layers.*.mlp.down_proj": "rowwise",
  178. }
  179. def __init__(
  180. self,
  181. vocab_size=152064,
  182. hidden_size=8192,
  183. intermediate_size=29568,
  184. num_hidden_layers=80,
  185. num_attention_heads=64,
  186. num_key_value_heads=8,
  187. hidden_act="silu",
  188. max_position_embeddings=32768,
  189. initializer_range=0.02,
  190. rms_norm_eps=1e-05,
  191. use_cache=True,
  192. tie_word_embeddings=False,
  193. rope_theta=1000000.0,
  194. use_sliding_window=False,
  195. sliding_window=4096,
  196. max_window_layers=80,
  197. attention_dropout=0.0,
  198. vision_config=None,
  199. rope_scaling=None,
  200. **kwargs,
  201. ):
  202. if isinstance(vision_config, dict):
  203. self.vision_config = self.sub_configs["vision_config"](**vision_config)
  204. elif vision_config is None:
  205. self.vision_config = self.sub_configs["vision_config"]()
  206. self.vocab_size = vocab_size
  207. self.max_position_embeddings = max_position_embeddings
  208. self.hidden_size = hidden_size
  209. self.intermediate_size = intermediate_size
  210. self.num_hidden_layers = num_hidden_layers
  211. self.num_attention_heads = num_attention_heads
  212. self.use_sliding_window = use_sliding_window
  213. self.sliding_window = sliding_window
  214. self.max_window_layers = max_window_layers
  215. if num_key_value_heads is None:
  216. num_key_value_heads = num_attention_heads
  217. self.num_key_value_heads = num_key_value_heads
  218. self.hidden_act = hidden_act
  219. self.initializer_range = initializer_range
  220. self.rms_norm_eps = rms_norm_eps
  221. self.use_cache = use_cache
  222. self.rope_theta = rope_theta
  223. self.attention_dropout = attention_dropout
  224. self.rope_scaling = rope_scaling
  225. if self.rope_scaling is not None and "type" in self.rope_scaling:
  226. if self.rope_scaling["type"] == "mrope":
  227. self.rope_scaling["type"] = "default"
  228. self.rope_scaling["rope_type"] = self.rope_scaling["type"]
  229. super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
  230. flash_attn_func, flash_attn_varlen_func = has_flash_attn_func()
  231. Linear = nn.Linear
  232. ColumnParallelLinear = mpu.ColumnParallelLinear
  233. RowParallelLinear = mpu.RowParallelLinear
  234. def get_triangle_upper_mask(x, mask=None):
  235. if mask is not None:
  236. return mask
  237. shape = x.shape
  238. shape[1] = 1
  239. mask = paddle.full(shape, paddle.finfo(x.dtype).min, dtype=x.dtype)
  240. mask = paddle.triu(mask, diagonal=1)
  241. mask.stop_gradient = True
  242. return mask
  243. def parallel_matmul(
  244. x: Tensor, y: Tensor, transpose_y=True, tensor_parallel_output=True
  245. ):
  246. is_fleet_init = True
  247. tensor_parallel_degree = 1
  248. try:
  249. hcg = fleet.get_hybrid_communicate_group()
  250. model_parallel_group = hcg.get_model_parallel_group()
  251. tensor_parallel_degree = hcg.get_model_parallel_world_size()
  252. except:
  253. is_fleet_init = False
  254. if paddle.in_dynamic_mode():
  255. y_is_distributed = y.is_distributed
  256. else:
  257. y_is_distributed = tensor_parallel_degree > 1
  258. if is_fleet_init and tensor_parallel_degree > 1 and y_is_distributed:
  259. input_parallel = paddle.distributed.collective._c_identity(
  260. x, group=model_parallel_group
  261. )
  262. logits = paddle.matmul(input_parallel, y, transpose_y=transpose_y)
  263. if tensor_parallel_output:
  264. return logits
  265. return paddle.distributed.collective._c_concat(
  266. logits, group=model_parallel_group
  267. )
  268. else:
  269. logits = paddle.matmul(x, y, transpose_y=transpose_y)
  270. return logits
  271. def _compute_default_rope_parameters(
  272. config: Optional[PretrainedConfig] = None,
  273. device: Optional["paddle.device"] = None,
  274. seq_len: Optional[int] = None,
  275. **rope_kwargs,
  276. ) -> Tuple["paddle.Tensor", float]:
  277. """
  278. Computes the inverse frequencies according to the original RoPE implementation
  279. Args:
  280. config ([`~transformers.PretrainedConfig`]):
  281. The model configuration.
  282. device (`paddle.device`):
  283. The device to use for initialization of the inverse frequencies.
  284. seq_len (`int`, *optional*):
  285. The current sequence length. Unused for this type of RoPE.
  286. rope_kwargs (`Dict`, *optional*):
  287. BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
  288. Returns:
  289. Tuple of (`paddle.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
  290. post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
  291. """
  292. if config is not None and len(rope_kwargs) > 0:
  293. raise ValueError(
  294. "Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
  295. f"`_compute_default_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
  296. )
  297. if len(rope_kwargs) > 0:
  298. base = rope_kwargs["base"]
  299. dim = rope_kwargs["dim"]
  300. elif config is not None:
  301. base = config.rope_theta
  302. partial_rotary_factor = (
  303. config.partial_rotary_factor
  304. if hasattr(config, "partial_rotary_factor")
  305. else 1.0
  306. )
  307. head_dim = getattr(
  308. config, "head_dim", config.hidden_size // config.num_attention_heads
  309. )
  310. dim = int(head_dim * partial_rotary_factor)
  311. attention_factor = 1.0 # Unused in this type of RoPE
  312. # Compute the inverse frequencies
  313. inv_freq = 1.0 / (
  314. base ** (paddle.arange(0, dim, 2, dtype="int64").astype("float32") / dim)
  315. )
  316. return inv_freq, attention_factor
  317. ROPE_INIT_FUNCTIONS = {
  318. "default": _compute_default_rope_parameters,
  319. }
  320. def _get_unpad_data(attention_mask):
  321. seqlens_in_batch = attention_mask.sum(axis=-1, dtype="int32")
  322. indices = paddle.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
  323. max_seqlen_in_batch = seqlens_in_batch.max().item() # [2, 1, 1323]
  324. cu_seqlens = F.pad(
  325. paddle.cumsum(seqlens_in_batch, axis=0), (1, 0), data_format="NCL"
  326. )
  327. return (
  328. indices,
  329. cu_seqlens,
  330. max_seqlen_in_batch,
  331. )
  332. def is_casual_mask(attention_mask):
  333. """
  334. Upper triangular of attention_mask equals to attention_mask is casual
  335. """
  336. return (paddle.triu(attention_mask) == attention_mask).all().item()
  337. def _make_causal_mask(input_ids_shape, past_key_values_length):
  338. """
  339. Make causal mask used for self-attention
  340. """
  341. batch_size, target_length = input_ids_shape # target_length: seq_len
  342. mask = paddle.tril(paddle.ones((target_length, target_length), dtype="bool"))
  343. if past_key_values_length > 0:
  344. # [tgt_len, tgt_len + past_len]
  345. mask = paddle.concat(
  346. [paddle.ones([target_length, past_key_values_length], dtype="bool"), mask],
  347. axis=-1,
  348. )
  349. # [bs, 1, tgt_len, tgt_len + past_len]
  350. return mask[None, None, :, :].expand(
  351. [batch_size, 1, target_length, target_length + past_key_values_length]
  352. )
  353. def _expand_2d_mask(mask, dtype, tgt_length):
  354. """
  355. Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`.
  356. """
  357. batch_size, src_length = mask.shape[0], mask.shape[-1]
  358. tgt_length = tgt_length if tgt_length is not None else src_length
  359. mask = mask[:, None, None, :].astype("bool")
  360. mask.stop_gradient = True
  361. expanded_mask = mask.expand([batch_size, 1, tgt_length, src_length])
  362. return expanded_mask
  363. @dataclass
  364. class Qwen2_5_VLCausalLMOutputWithPast(ModelOutput):
  365. """
  366. Base class for Qwen2_5_VL causal language model (or autoregressive) outputs.
  367. Args:
  368. loss (`paddle.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  369. Language modeling loss (for next-token prediction).
  370. logits (`paddle.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
  371. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  372. past_key_values (`tuple(tuple(paddle.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  373. Tuple of `tuple(paddle.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
  374. `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
  375. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  376. `past_key_values` input) to speed up sequential decoding.
  377. hidden_states (`tuple(paddle.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  378. Tuple of `paddle.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  379. one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
  380. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
  381. attentions (`tuple(paddle.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  382. Tuple of `paddle.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  383. sequence_length)`.
  384. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  385. heads.
  386. rope_deltas (`paddle.LongTensor` of shape `(batch_size, )`, *optional*):
  387. The rope index difference between sequence length and multimodal rope.
  388. """
  389. loss: Optional[paddle.Tensor] = None
  390. logits: paddle.float32 = None
  391. past_key_values: Optional[List[paddle.Tensor]] = None
  392. hidden_states: Optional[Tuple[paddle.Tensor]] = None
  393. attentions: Optional[Tuple[paddle.Tensor]] = None
  394. rope_deltas: Optional[paddle.Tensor] = None
  395. class Qwen2_5_VLRotaryEmbedding(nn.Layer):
  396. def __init__(
  397. self,
  398. dim=None,
  399. max_position_embeddings=2048,
  400. base=10000,
  401. device=None,
  402. scaling_factor=1.0,
  403. rope_type="default",
  404. config: Optional[Qwen2_5_VLConfig] = None,
  405. ):
  406. super().__init__()
  407. # TODO (joao): remove the `if` below, only used for BC
  408. self.rope_kwargs = {}
  409. if config is None:
  410. logging.warning_once(
  411. "`Qwen2_5_VLRotaryEmbedding` can now be fully parameterized by passing the model config through the "
  412. "`config` argument. All other arguments will be removed in v4.46"
  413. )
  414. self.rope_kwargs = {
  415. "rope_type": rope_type,
  416. "factor": scaling_factor,
  417. "dim": dim,
  418. "base": base,
  419. "max_position_embeddings": max_position_embeddings,
  420. }
  421. self.rope_type = rope_type
  422. self.max_seq_len_cached = max_position_embeddings
  423. self.original_max_seq_len = max_position_embeddings
  424. else:
  425. # BC: "rope_type" was originally "type"
  426. if config.rope_scaling is not None:
  427. self.rope_type = config.rope_scaling.get(
  428. "rope_type", config.rope_scaling.get("type")
  429. )
  430. else:
  431. self.rope_type = "default"
  432. self.max_seq_len_cached = config.max_position_embeddings
  433. self.original_max_seq_len = config.max_position_embeddings
  434. self.config = config
  435. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  436. self.inv_freq, self.attention_scaling = self.rope_init_fn(
  437. self.config, device, **self.rope_kwargs
  438. )
  439. self.original_inv_freq = self.inv_freq
  440. self._set_cos_sin_cache(seq_len=max_position_embeddings)
  441. def _set_cos_sin_cache(self, seq_len):
  442. self.max_seq_len_cached = seq_len
  443. # [seq_len]
  444. t = paddle.arange(seq_len, dtype="float32")
  445. # [seq_len, dim/2]
  446. freqs = paddle.einsum("i,j->ij", t, self.inv_freq)
  447. # Different from paper, but it uses a different permutation in order to obtain the same calculation
  448. # [seq_len, dim]
  449. emb = paddle.concat([freqs, freqs], axis=-1)
  450. # [1, seqlen, 1, dim]
  451. self.cos_cached = emb.cos()
  452. self.sin_cached = emb.sin()
  453. def _dynamic_frequency_update(self, position_ids, device):
  454. """
  455. dynamic RoPE layers should recompute `inv_freq` in the following situations:
  456. 1 - growing beyond the cached sequence length (allow scaling)
  457. 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
  458. """
  459. seq_len = paddle.max(position_ids) + 1
  460. if seq_len > self.max_seq_len_cached: # growth
  461. inv_freq, self.attention_scaling = self.rope_init_fn(
  462. self.config, device, seq_len=seq_len, **self.rope_kwargs
  463. )
  464. self.inv_freq = inv_freq
  465. self.max_seq_len_cached = seq_len
  466. if (
  467. seq_len < self.original_max_seq_len
  468. and self.max_seq_len_cached > self.original_max_seq_len
  469. ): # reset
  470. self.inv_freq = self.original_inv_freq
  471. self.max_seq_len_cached = self.original_max_seq_len
  472. @paddle.no_grad()
  473. def forward(self, x, position_ids):
  474. if "dynamic" in self.rope_type:
  475. self._dynamic_frequency_update(position_ids, device=x.device)
  476. # Core RoPE block. In contrast to other models, Qwen2_VL has different position ids for thw grids
  477. # So we expand the inv_freq to shape (3, ...)
  478. inv_freq_expanded = (
  479. self.inv_freq[None, None, :, None]
  480. .astype("float32")
  481. .expand([3, position_ids.shape[1], -1, 1])
  482. )
  483. position_ids_expanded = position_ids[:, :, None, :].astype(
  484. "float32"
  485. ) # shape (3, bs, 1, positions)
  486. # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
  487. device_type = paddle.get_device()
  488. device_type = (
  489. device_type
  490. if isinstance(device_type, str) and device_type != "mps"
  491. else "cpu"
  492. )
  493. with paddle.amp.auto_cast():
  494. # Compute frequencies by matrix multiplication and transpose
  495. # inv_freq_expanded shape: [3, bs, dim/2, 1]
  496. # position_ids_expanded shape: [3, bs, 1, positions]
  497. # Result shape after matmul: [3, bs, dim/2, positions]
  498. # After transpose: [3, bs, positions, dim/2]
  499. freqs = paddle.matmul(inv_freq_expanded, position_ids_expanded)
  500. freqs = freqs.transpose([0, 1, 3, 2])
  501. emb = paddle.concat((freqs, freqs), axis=-1)
  502. cos = emb.cos()
  503. sin = emb.sin()
  504. # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
  505. cos = cos * self.attention_scaling
  506. sin = sin * self.attention_scaling
  507. return cos.astype(x.dtype), sin.astype(x.dtype)
  508. # Copied from transformers.models.llama.modeling_llama.rotate_half
  509. def rotate_half(x):
  510. """Rotates half the hidden dims of the input."""
  511. x1 = x[..., : x.shape[-1] // 2]
  512. x2 = x[..., x.shape[-1] // 2 :]
  513. return paddle.concat([-x2, x1], axis=-1) # shape is the same as x
  514. def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
  515. """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
  516. Explanation:
  517. Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
  518. sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
  519. vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
  520. Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
  521. For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
  522. height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
  523. difference with modern LLMs.
  524. Args:
  525. q (`paddle.Tensor`): The query tensor.
  526. k (`paddle.Tensor`): The key tensor.
  527. cos (`paddle.Tensor`): The cosine part of the rotary embedding.
  528. sin (`paddle.Tensor`): The sine part of the rotary embedding.
  529. position_ids (`paddle.Tensor`):
  530. The position indices of the tokens corresponding to the query and key tensors. For example, this can be
  531. used to pass offsetted position ids when working with a KV-cache.
  532. mrope_section(`List(int)`):
  533. Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
  534. unsqueeze_dim (`int`, *optional*, defaults to 1):
  535. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  536. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  537. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  538. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  539. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  540. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  541. Returns:
  542. `tuple(paddle.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  543. """
  544. # cos = cos[position_ids]
  545. # sin = sin[position_ids]
  546. mrope_section = mrope_section * 2
  547. cos = paddle.concat(
  548. x=[m[i % 3] for i, m in enumerate(cos.split(mrope_section, axis=-1))], axis=-1
  549. ).unsqueeze(axis=unsqueeze_dim)
  550. sin = paddle.concat(
  551. x=[m[i % 3] for i, m in enumerate(sin.split(mrope_section, axis=-1))], axis=-1
  552. ).unsqueeze(axis=unsqueeze_dim)
  553. q_embed = (q * cos) + (rotate_half(q) * sin)
  554. k_embed = (k * cos) + (rotate_half(k) * sin)
  555. return q_embed, k_embed
  556. def apply_rotary_pos_emb_vision(
  557. tensor: paddle.Tensor, freqs: paddle.Tensor
  558. ) -> paddle.Tensor:
  559. orig_dtype = tensor.dtype
  560. with paddle.amp.auto_cast(False):
  561. tensor = tensor.astype(dtype="float32")
  562. cos = freqs.cos()
  563. sin = freqs.sin()
  564. cos = (
  565. cos.unsqueeze(1)
  566. .tile(repeat_times=[1, 1, 2])
  567. .unsqueeze(0)
  568. .astype(dtype="float32")
  569. )
  570. sin = (
  571. sin.unsqueeze(1)
  572. .tile(repeat_times=[1, 1, 2])
  573. .unsqueeze(0)
  574. .astype(dtype="float32")
  575. )
  576. output = tensor * cos + rotate_half(tensor) * sin
  577. output = paddle.cast(output, orig_dtype)
  578. return output
  579. class Qwen2_5_VisionRotaryEmbedding(nn.Layer):
  580. def __init__(self, dim: int, theta: float = 10000.0) -> None:
  581. super().__init__()
  582. self.inv_freq = 1.0 / theta ** (
  583. paddle.arange(start=0, end=dim, step=2, dtype="float32") / dim
  584. )
  585. def forward(self, seqlen: int) -> paddle.Tensor:
  586. seq = paddle.arange(seqlen).cast(self.inv_freq.dtype)
  587. freqs = paddle.outer(x=seq, y=self.inv_freq)
  588. return freqs
  589. class Qwen2_5_VisionPatchEmbed(nn.Layer):
  590. def __init__(
  591. self,
  592. patch_size: int = 14,
  593. temporal_patch_size: int = 2,
  594. in_channels: int = 3,
  595. embed_dim: int = 1152,
  596. ) -> None:
  597. super().__init__()
  598. self.patch_size = patch_size
  599. self.temporal_patch_size = temporal_patch_size
  600. self.in_channels = in_channels
  601. self.embed_dim = embed_dim
  602. kernel_size = [temporal_patch_size, patch_size, patch_size]
  603. self.proj = nn.Conv3D(
  604. in_channels,
  605. embed_dim,
  606. kernel_size=kernel_size,
  607. stride=kernel_size,
  608. bias_attr=False,
  609. )
  610. def forward(self, hidden_states: paddle.Tensor) -> paddle.Tensor:
  611. target_dtype = self.proj.weight.dtype
  612. hidden_states = hidden_states.reshape(
  613. [
  614. -1,
  615. self.in_channels,
  616. self.temporal_patch_size,
  617. self.patch_size,
  618. self.patch_size,
  619. ]
  620. )
  621. # NOTE(changwenbin): AttributeError: 'Variable' object has no attribute 'to'.
  622. # hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).reshape([-1, self.embed_dim])
  623. hidden_states = self.proj(
  624. paddle.cast(hidden_states, dtype=target_dtype)
  625. ).reshape([-1, self.embed_dim])
  626. return hidden_states
  627. class Qwen2_5_VLPatchMerger(paddle.nn.Layer):
  628. def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
  629. super().__init__()
  630. self.hidden_size = context_dim * (spatial_merge_size**2)
  631. self.ln_q = Qwen2RMSNorm(context_dim, eps=1e-6)
  632. self.mlp = nn.Sequential(
  633. nn.Linear(self.hidden_size, self.hidden_size),
  634. nn.GELU(),
  635. nn.Linear(self.hidden_size, dim),
  636. )
  637. def forward(self, x: paddle.Tensor) -> paddle.Tensor:
  638. x = self.mlp(self.ln_q(x).reshape([-1, self.hidden_size]))
  639. return x
  640. class Qwen2_5_VLMLP(paddle.nn.Layer):
  641. def __init__(self, config, bias: bool = False):
  642. super().__init__()
  643. self.hidden_size = config.hidden_size
  644. self.intermediate_size = config.intermediate_size
  645. self.gate_proj = paddle.nn.Linear(
  646. in_features=self.hidden_size,
  647. out_features=self.intermediate_size,
  648. bias_attr=bias,
  649. )
  650. self.up_proj = paddle.nn.Linear(
  651. in_features=self.hidden_size,
  652. out_features=self.intermediate_size,
  653. bias_attr=bias,
  654. )
  655. self.down_proj = paddle.nn.Linear(
  656. in_features=self.intermediate_size,
  657. out_features=self.hidden_size,
  658. bias_attr=bias,
  659. )
  660. self.act_fn = ACT2FN[config.hidden_act]
  661. def forward(self, hidden_state):
  662. return self.down_proj(
  663. self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state)
  664. )
  665. class Qwen2_5_VLVisionAttention(nn.Layer):
  666. def __init__(self, dim: int, num_heads: int = 16) -> None:
  667. super().__init__()
  668. self.num_heads = num_heads
  669. self.qkv = nn.Linear(dim, dim * 3, bias_attr=True)
  670. self.proj = nn.Linear(dim, dim)
  671. self.head_dim = dim // num_heads # must added
  672. def forward(
  673. self,
  674. hidden_states: paddle.Tensor,
  675. cu_seqlens: paddle.Tensor,
  676. rotary_pos_emb: paddle.Tensor = None,
  677. ) -> paddle.Tensor:
  678. seq_length = hidden_states.shape[0]
  679. q, k, v = (
  680. self.qkv(hidden_states)
  681. .reshape([seq_length, 3, self.num_heads, -1])
  682. .transpose([1, 0, 2, 3])
  683. .unbind(0)
  684. )
  685. q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
  686. k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
  687. attention_mask = paddle.zeros([1, seq_length, seq_length], dtype="bool")
  688. for i in range(1, len(cu_seqlens)):
  689. attention_mask[
  690. ...,
  691. cu_seqlens[i - 1] : cu_seqlens[i],
  692. cu_seqlens[i - 1] : cu_seqlens[i],
  693. ] = True
  694. zero = paddle.zeros(attention_mask.shape, dtype=hidden_states.dtype)
  695. neg_inf = paddle.full_like(
  696. attention_mask,
  697. paddle.finfo(hidden_states.dtype).min,
  698. dtype=hidden_states.dtype,
  699. )
  700. attention_mask = paddle.where(attention_mask, zero, neg_inf)
  701. q = q.transpose([1, 0, 2])
  702. k = k.transpose([1, 0, 2])
  703. v = v.transpose([1, 0, 2])
  704. attn_weights = paddle.matmul(q, k.transpose([0, 2, 1])) / math.sqrt(
  705. self.head_dim
  706. )
  707. attn_weights = attn_weights + attention_mask
  708. attn_weights = nn.functional.softmax(attn_weights, axis=-1)
  709. attn_output = paddle.matmul(attn_weights, v)
  710. attn_output = attn_output.transpose([1, 0, 2])
  711. attn_output = attn_output.reshape([seq_length, -1])
  712. attn_output = self.proj(attn_output)
  713. return attn_output
  714. class Qwen2_5_VLVisionFlashAttention2(nn.Layer):
  715. def __init__(self, dim: int, num_heads: int = 16) -> None:
  716. super().__init__()
  717. self.num_heads = num_heads
  718. self.qkv = nn.Linear(dim, dim * 3, bias_attr=True)
  719. self.proj = nn.Linear(dim, dim)
  720. self.head_dim = dim // num_heads # must added
  721. def forward(
  722. self,
  723. hidden_states: paddle.Tensor,
  724. cu_seqlens: paddle.Tensor,
  725. rotary_pos_emb: paddle.Tensor = None,
  726. ) -> paddle.Tensor:
  727. seq_length = tuple(hidden_states.shape)[0]
  728. qkv = (
  729. self.qkv(hidden_states)
  730. .reshape([seq_length, 3, self.num_heads, -1])
  731. .transpose(perm=[1, 0, 2, 3])
  732. )
  733. q, k, v = qkv.unbind(axis=0)
  734. q = apply_rotary_pos_emb_flashatt(q.unsqueeze(axis=0), rotary_pos_emb).squeeze(
  735. axis=0
  736. )
  737. k = apply_rotary_pos_emb_flashatt(k.unsqueeze(axis=0), rotary_pos_emb).squeeze(
  738. axis=0
  739. )
  740. max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
  741. softmax_scale = self.head_dim**-0.5 # TODO: 需要手动加上
  742. attn_output = (
  743. flash_attn_varlen_func( # flash_attn_unpadded
  744. q.astype("bfloat16"), # 不支持float32
  745. k.astype("bfloat16"),
  746. v.astype("bfloat16"),
  747. cu_seqlens,
  748. cu_seqlens,
  749. max_seqlen,
  750. max_seqlen,
  751. scale=softmax_scale, # TODO: 需要手动加上
  752. )[0]
  753. .squeeze(0)
  754. .reshape([seq_length, -1])
  755. )
  756. attn_output = self.proj(attn_output)
  757. return attn_output
  758. class Qwen2_5_VLVisionSdpaAttention(nn.Layer):
  759. def __init__(self, dim: int, num_heads: int = 16) -> None:
  760. super().__init__()
  761. self.num_heads = num_heads
  762. self.qkv = nn.Linear(dim, dim * 3, bias_attr=True)
  763. self.proj = nn.Linear(dim, dim)
  764. is_bfloat16_supported = paddle.amp.is_bfloat16_supported()
  765. if is_bfloat16_supported:
  766. self.compute_dtype = "bfloat16"
  767. else:
  768. self.compute_dtype = "float16"
  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)
  783. k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb)
  784. attention_mask = paddle.zeros([1, 1, seq_length, seq_length], dtype="bool")
  785. for i in range(1, len(cu_seqlens)):
  786. attention_mask[
  787. ...,
  788. cu_seqlens[i - 1] : cu_seqlens[i],
  789. cu_seqlens[i - 1] : cu_seqlens[i],
  790. ] = True
  791. zero = paddle.zeros(attention_mask.shape, dtype=hidden_states.dtype)
  792. neg_inf = paddle.full_like(
  793. attention_mask,
  794. paddle.finfo(hidden_states.dtype).min,
  795. dtype=hidden_states.dtype,
  796. )
  797. attention_mask = paddle.where(attention_mask, zero, neg_inf)
  798. v = v.unsqueeze(0)
  799. attn_output = paddle.nn.functional.scaled_dot_product_attention(
  800. query=q.astype(self.compute_dtype),
  801. key=k.astype(self.compute_dtype),
  802. value=v.astype(self.compute_dtype),
  803. attn_mask=attention_mask.astype(self.compute_dtype),
  804. dropout_p=0.0,
  805. )
  806. attn_output = attn_output.transpose([1, 0, 2])
  807. attn_output = attn_output.reshape([seq_length, -1])
  808. attn_output = self.proj(attn_output)
  809. return attn_output
  810. QWEN2_5_VL_VISION_ATTENTION_CLASSES = {
  811. "eager": Qwen2_5_VLVisionAttention,
  812. "flash_attention_2": Qwen2_5_VLVisionFlashAttention2,
  813. "sdpa": Qwen2_5_VLVisionSdpaAttention,
  814. }
  815. class Qwen2_5_VLVisionBlock(paddle.nn.Layer):
  816. def __init__(self, config, attn_implementation: str = "sdpa") -> None:
  817. super().__init__()
  818. self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
  819. self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
  820. self.attn = QWEN2_5_VL_VISION_ATTENTION_CLASSES[attn_implementation](
  821. config.hidden_size, num_heads=config.num_heads
  822. )
  823. self.mlp = Qwen2_5_VLMLP(config, bias=True)
  824. def forward(self, hidden_states, cu_seqlens, rotary_pos_emb) -> paddle.Tensor:
  825. hidden_states = hidden_states + self.attn(
  826. self.norm1(hidden_states),
  827. cu_seqlens=cu_seqlens,
  828. rotary_pos_emb=rotary_pos_emb,
  829. )
  830. hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
  831. return hidden_states
  832. def apply_rotary_emb(tensor, cos, sin):
  833. """
  834. Apply rotary position embedding to the input tensor.
  835. Args:
  836. tensor (paddle.Tensor): The input tensor of shape [batch_size, seq_len, num_heads, head_dim]
  837. cos (paddle.Tensor): The cosine part of the rotary embedding [seq_len, head_dim/2]
  838. sin (paddle.Tensor): The sine part of the rotary embedding [seq_len, head_dim/2]
  839. Returns:
  840. paddle.Tensor: The tensor after applying rotary embedding
  841. """
  842. # Split the tensor into two halves along the last dimension
  843. dim = tensor.shape[-1]
  844. half_dim = dim // 2
  845. tensor1 = tensor[..., :half_dim]
  846. tensor2 = tensor[..., half_dim:]
  847. # Reshape cos/sin for broadcasting
  848. # From [seq_len, head_dim/2] to [1, seq_len, 1, head_dim/2]
  849. cos = cos.unsqueeze(0).unsqueeze(2)
  850. sin = sin.unsqueeze(0).unsqueeze(2)
  851. # Apply rotary embedding
  852. # tensor1/tensor2 shape: [batch_size, seq_len, num_heads, head_dim/2]
  853. # cos/sin shape: [1, seq_len, 1, head_dim/2]
  854. rotated = paddle.concat(
  855. [tensor1 * cos - tensor2 * sin, tensor1 * sin + tensor2 * cos], axis=-1
  856. )
  857. return rotated
  858. def apply_rotary_pos_emb_flashatt(
  859. tensor: paddle.Tensor, freqs: paddle.Tensor
  860. ) -> paddle.Tensor:
  861. tensor_ = tensor.astype(dtype="float32")
  862. cos = freqs.cos()
  863. sin = freqs.sin()
  864. output = apply_rotary_emb(tensor_, cos, sin).astype(dtype=tensor.dtype)
  865. return output
  866. # Copied from transformers.models.qwen2.modeling_qwen2.Qwen2RMSNorm
  867. class Qwen2RMSNorm(nn.Layer):
  868. def __init__(self, hidden_size, eps=1e-6):
  869. """
  870. Qwen2RMSNorm is equivalent to T5LayerNorm
  871. """
  872. super().__init__()
  873. self.weight = paddle.create_parameter(
  874. shape=[hidden_size],
  875. dtype=paddle.get_default_dtype(),
  876. default_initializer=nn.initializer.Constant(1.0),
  877. )
  878. self.variance_epsilon = eps
  879. def forward(self, hidden_states):
  880. if paddle.in_dynamic_mode():
  881. with paddle.amp.auto_cast(False):
  882. variance = hidden_states.astype("float32").pow(2).mean(-1, keepdim=True)
  883. hidden_states = (
  884. paddle.rsqrt(variance + self.variance_epsilon) * hidden_states
  885. )
  886. else:
  887. variance = hidden_states.astype("float32").pow(2).mean(-1, keepdim=True)
  888. hidden_states = (
  889. paddle.rsqrt(variance + self.variance_epsilon) * hidden_states
  890. )
  891. if self.weight.dtype in [paddle.float16, paddle.bfloat16]:
  892. hidden_states = paddle.cast(hidden_states, self.weight.dtype)
  893. return hidden_states * self.weight
  894. class Qwen2MLP(nn.Layer):
  895. def __init__(self, config):
  896. super().__init__()
  897. self.hidden_size = config.hidden_size
  898. self.intermediate_size = config.intermediate_size
  899. self.fuse_attention_ffn = config.fuse_attention_ffn
  900. self.tensor_parallel_degree = config.tensor_parallel_degree
  901. if config.tensor_parallel_degree > 1:
  902. self.gate_proj = ColumnParallelLinear(
  903. self.hidden_size,
  904. self.intermediate_size,
  905. gather_output=False,
  906. has_bias=False,
  907. )
  908. self.up_proj = ColumnParallelLinear(
  909. self.hidden_size,
  910. self.intermediate_size,
  911. gather_output=False,
  912. has_bias=False,
  913. )
  914. self.down_proj = RowParallelLinear(
  915. self.intermediate_size,
  916. self.hidden_size,
  917. input_is_parallel=True,
  918. has_bias=False,
  919. )
  920. else:
  921. if get_device_type() == "xpu":
  922. self.gate_proj = nn.Linear(
  923. self.hidden_size, self.intermediate_size, bias_attr=False
  924. ) # w1
  925. self.up_proj = nn.Linear(
  926. self.hidden_size, self.intermediate_size, bias_attr=False
  927. ) # w3
  928. self.down_proj = nn.Linear(
  929. self.intermediate_size, self.hidden_size, bias_attr=False
  930. ) # w2
  931. else:
  932. self.gate_proj = Linear(
  933. self.hidden_size, self.intermediate_size, bias_attr=False
  934. ) # w1
  935. self.up_proj = Linear(
  936. self.hidden_size, self.intermediate_size, bias_attr=False
  937. ) # w3
  938. self.down_proj = Linear(
  939. self.intermediate_size, self.hidden_size, bias_attr=False
  940. ) # w2
  941. self.act_fn = ACT2FN[config.hidden_act]
  942. self.fuse_swiglu = False
  943. def forward(self, x):
  944. x, y = self.gate_proj(x), self.up_proj(x)
  945. if self.fuse_swiglu:
  946. x = self.act_fn(x, y)
  947. else:
  948. x = self.act_fn(x) * y
  949. return self.down_proj(x)
  950. # Copied from transformers.models.llama.modeling_llama.repeat_kv
  951. def repeat_kv(hidden_states: paddle.Tensor, n_rep: int) -> paddle.Tensor:
  952. """
  953. This is the equivalent of paddle.repeat_interleave(x, axis=1, repeats=n_rep). The hidden states go from (batch,
  954. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  955. """
  956. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  957. if n_rep == 1:
  958. return hidden_states
  959. hidden_states = hidden_states[:, :, None, :, :].expand(
  960. [batch, num_key_value_heads, n_rep, slen, head_dim]
  961. )
  962. return hidden_states.reshape([batch, num_key_value_heads * n_rep, slen, head_dim])
  963. class Qwen2_5_VLAttention(paddle.nn.Layer):
  964. """
  965. Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
  966. and "Generating Long Sequences with Sparse Transformers".
  967. """
  968. def __init__(self, config: Qwen2_5_VLConfig, layer_idx: Optional[int] = None):
  969. super().__init__()
  970. self.config = config
  971. self.layer_idx = layer_idx
  972. if layer_idx is None:
  973. logging.warning_once(
  974. f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
  975. "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
  976. "when creating this class."
  977. )
  978. self.hidden_size = config.hidden_size
  979. self.num_heads = config.num_attention_heads
  980. self.head_dim = self.hidden_size // self.num_heads
  981. self.num_key_value_heads = config.num_key_value_heads
  982. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  983. self.max_position_embeddings = config.max_position_embeddings
  984. self.rope_theta = config.rope_theta
  985. self.is_causal = True
  986. self.attention_dropout = config.attention_dropout
  987. self.rope_scaling = config.rope_scaling
  988. # self.sequence_parallel = config.sequence_parallel
  989. if config.tensor_parallel_degree > 1:
  990. assert (
  991. self.num_heads % config.tensor_parallel_degree == 0
  992. ), f"num_heads: {self.num_heads}, tensor_parallel_degree: {config.tensor_parallel_degree}"
  993. self.num_heads = self.num_heads // config.tensor_parallel_degree
  994. assert (
  995. self.num_key_value_heads % config.tensor_parallel_degree == 0
  996. ), f"num_key_value_heads: {self.num_key_value_heads}, tensor_parallel_degree: {config.tensor_parallel_degree}"
  997. self.num_key_value_heads = (
  998. self.num_key_value_heads // config.tensor_parallel_degree
  999. )
  1000. if config.tensor_parallel_degree > 1:
  1001. self.q_proj = ColumnParallelLinear(
  1002. self.hidden_size, self.hidden_size, has_bias=True, gather_output=False
  1003. )
  1004. self.k_proj = ColumnParallelLinear(self.hidden_size, self.config.num_key_value_heads * self.head_dim, has_bias=True, gather_output=False) # fmt:skip
  1005. self.v_proj = ColumnParallelLinear(self.hidden_size, self.config.num_key_value_heads * self.head_dim, has_bias=True, gather_output=False) # fmt:skip
  1006. self.o_proj = RowParallelLinear(
  1007. self.hidden_size,
  1008. self.hidden_size,
  1009. has_bias=False,
  1010. input_is_parallel=True,
  1011. )
  1012. else:
  1013. self.q_proj = Linear(self.hidden_size, self.hidden_size, bias_attr=True)
  1014. self.k_proj = Linear(
  1015. self.hidden_size,
  1016. self.config.num_key_value_heads * self.head_dim,
  1017. bias_attr=True,
  1018. )
  1019. self.v_proj = Linear(
  1020. self.hidden_size,
  1021. self.config.num_key_value_heads * self.head_dim,
  1022. bias_attr=True,
  1023. )
  1024. self.o_proj = Linear(self.hidden_size, self.hidden_size, bias_attr=False)
  1025. self.rotary_emb = Qwen2_5_VLRotaryEmbedding(
  1026. self.head_dim,
  1027. max_position_embeddings=self.max_position_embeddings,
  1028. base=self.rope_theta,
  1029. )
  1030. def forward(
  1031. self,
  1032. hidden_states: paddle.Tensor,
  1033. attention_mask: Optional[paddle.Tensor] = None,
  1034. position_ids: Optional[paddle.Tensor] = None,
  1035. past_key_value: Optional[Tuple[paddle.Tensor]] = None, # Cache
  1036. output_attentions: bool = False,
  1037. use_cache: bool = False, # default true
  1038. cache_position: Optional[paddle.Tensor] = None,
  1039. ) -> Tuple[paddle.Tensor, Optional[paddle.Tensor], Optional[Tuple[paddle.Tensor]]]:
  1040. bsz, q_len, _ = hidden_states.shape
  1041. try:
  1042. query_states = self.q_proj(hidden_states)
  1043. key_states = self.k_proj(hidden_states)
  1044. value_states = self.v_proj(hidden_states)
  1045. except:
  1046. hidden_states = hidden_states.astype(self.config.dtype)
  1047. query_states = self.q_proj(hidden_states)
  1048. key_states = self.k_proj(hidden_states)
  1049. value_states = self.v_proj(hidden_states)
  1050. target_query_shape = [0, 0, self.num_heads, self.head_dim]
  1051. target_key_value_shape = [0, 0, self.num_key_value_heads, self.head_dim]
  1052. query_states = query_states.reshape(shape=target_query_shape)
  1053. key_states = key_states.reshape(shape=target_key_value_shape)
  1054. value_states = value_states.reshape(shape=target_key_value_shape)
  1055. new_perm = [0, 2, 1, 3]
  1056. query_states = query_states.transpose(new_perm)
  1057. key_states = key_states.transpose(new_perm)
  1058. value_states = value_states.transpose(new_perm)
  1059. kv_seq_len = key_states.shape[
  1060. -2
  1061. ] # q_len ######## [bs, num_head, seq_len, head_dim] # qwen2是 [-3]
  1062. if past_key_value is not None:
  1063. kv_seq_len += cache_position[0] + 1
  1064. # kv_seq_len += past_key_value[0].shape[-2] # qwen2是 [-3]
  1065. cos, sin = self.rotary_emb(value_states, position_ids)
  1066. query_states, key_states = apply_multimodal_rotary_pos_emb(
  1067. query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
  1068. )
  1069. # [bs, num_head, seq_len, head_dim]
  1070. if past_key_value is not None:
  1071. # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
  1072. # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  1073. key_states = paddle.concat(
  1074. [past_key_value[0], key_states], axis=2
  1075. ) # qwen2是 axis=1, qwen2_vl是 axis=2
  1076. value_states = paddle.concat(
  1077. [past_key_value[1], value_states], axis=2
  1078. ) # qwen2是 axis=1
  1079. past_key_value = (key_states, value_states) if use_cache else None
  1080. # repeat k/v heads if n_kv_heads < n_heads
  1081. key_states = repeat_kv(key_states, self.num_key_value_groups)
  1082. value_states = repeat_kv(value_states, self.num_key_value_groups)
  1083. query_states = query_states.astype("float32")
  1084. key_states = key_states.astype("float32")
  1085. value_states = value_states.astype("float32")
  1086. attn_weights = paddle.matmul(
  1087. query_states, key_states.transpose([0, 1, 3, 2])
  1088. ) / math.sqrt(self.head_dim)
  1089. if attention_mask is not None:
  1090. attn_weights = attn_weights + attention_mask
  1091. attn_weights = nn.functional.softmax(attn_weights, axis=-1)
  1092. attn_weights = nn.functional.dropout(
  1093. x=attn_weights, p=self.attention_dropout, training=self.training
  1094. )
  1095. attn_output = paddle.matmul(
  1096. attn_weights.cast(self.config.dtype), value_states.cast(self.config.dtype)
  1097. )
  1098. if attn_output.shape != [bsz, self.num_heads, q_len, self.head_dim]:
  1099. raise ValueError(
  1100. f"`attn_output` should be of size {(bsz, q_len, self.num_heads, self.head_dim)}, but is"
  1101. f" {attn_output.shape}"
  1102. )
  1103. attn_output = attn_output.transpose([0, 2, 1, 3])
  1104. attn_output = attn_output.reshape([bsz, q_len, -1])
  1105. attn_output = self.o_proj(attn_output)
  1106. if not output_attentions:
  1107. attn_weights = None
  1108. return attn_output, attn_weights, past_key_value
  1109. class Qwen2_5_VLFlashAttention2(Qwen2_5_VLAttention):
  1110. """
  1111. Qwen2_5_VL flash attention module, following Qwen2_5_VL attention module. This module inherits from `Qwen2_5_VLAttention`
  1112. as the weights of the module stays untouched. The only required change would be on the forward pass
  1113. where it needs to correctly call the public API of flash attention and deal with padding tokens
  1114. in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
  1115. config.max_window_layers layers.
  1116. """
  1117. def __init__(self, *args, **kwargs):
  1118. super().__init__(*args, **kwargs)
  1119. def forward(
  1120. self,
  1121. hidden_states: paddle.Tensor,
  1122. attention_mask: Optional[paddle.Tensor] = None,
  1123. position_ids: Optional[paddle.Tensor] = None,
  1124. past_key_value: Optional[Tuple[paddle.Tensor]] = None, # Cache
  1125. output_attentions: bool = False,
  1126. use_cache: bool = False, # default true
  1127. cache_position: Optional[paddle.Tensor] = None,
  1128. ) -> Tuple[paddle.Tensor, Optional[paddle.Tensor], Optional[Tuple[paddle.Tensor]]]:
  1129. bsz, q_len, _ = tuple(hidden_states.shape)
  1130. try:
  1131. query_states = self.q_proj(hidden_states)
  1132. key_states = self.k_proj(hidden_states)
  1133. value_states = self.v_proj(hidden_states)
  1134. except:
  1135. hidden_states = hidden_states.astype("bfloat16")
  1136. query_states = self.q_proj(hidden_states)
  1137. key_states = self.k_proj(hidden_states)
  1138. value_states = self.v_proj(hidden_states)
  1139. target_query_shape = [0, 0, self.num_heads, self.head_dim]
  1140. target_key_value_shape = [0, 0, self.num_key_value_heads, self.head_dim]
  1141. query_states = query_states.reshape(shape=target_query_shape)
  1142. key_states = key_states.reshape(shape=target_key_value_shape)
  1143. value_states = value_states.reshape(shape=target_key_value_shape)
  1144. new_perm = [0, 2, 1, 3]
  1145. # [1, 3599, 1536] [bsz, q_len, self.num_heads * self.head_dim]
  1146. query_states = query_states.transpose(new_perm)
  1147. key_states = key_states.transpose(new_perm)
  1148. value_states = value_states.transpose(new_perm)
  1149. kv_seq_len = key_states.shape[
  1150. -2
  1151. ] # q_len ######## [bs, num_head, seq_len, head_dim] # qwen2是 [-3]
  1152. if past_key_value is not None:
  1153. kv_seq_len += cache_position[0] + 1
  1154. # Because the input can be padded, the absolute sequence length depends on the max position id.
  1155. cos, sin = self.rotary_emb(value_states, position_ids)
  1156. query_states, key_states = apply_multimodal_rotary_pos_emb(
  1157. query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
  1158. )
  1159. if past_key_value is not None:
  1160. # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
  1161. # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  1162. key_states = paddle.concat(
  1163. [past_key_value[0], key_states], axis=2
  1164. ) # qwen2是 axis=1, qwen2_vl是 axis=2
  1165. value_states = paddle.concat(
  1166. [past_key_value[1], value_states], axis=2
  1167. ) # qwen2是 axis=1
  1168. past_key_value = (key_states, value_states) if use_cache else None
  1169. # repeat k/v heads if n_kv_heads < n_heads
  1170. key_states = repeat_kv(key_states, self.num_key_value_groups)
  1171. value_states = repeat_kv(value_states, self.num_key_value_groups)
  1172. # Reashape to the expected shape for Flash Attention
  1173. # [1, 3599, 12, 128]
  1174. query_states = query_states.transpose(perm=[0, 2, 1, 3])
  1175. key_states = key_states.transpose(perm=[0, 2, 1, 3])
  1176. value_states = value_states.transpose(perm=[0, 2, 1, 3])
  1177. attn_output = self._flash_attention_forward(
  1178. query_states,
  1179. key_states,
  1180. value_states,
  1181. attention_mask,
  1182. q_len,
  1183. # dropout=0.0 if not self.training else self.attention_dropout,
  1184. # causal=self.is_causal,
  1185. )
  1186. attn_output = attn_output.reshape([bsz, q_len, -1])
  1187. attn_output = self.o_proj(attn_output)
  1188. if not output_attentions:
  1189. attn_weights = None
  1190. return attn_output, attn_weights, past_key_value
  1191. def _flash_attention_forward(
  1192. self,
  1193. query_states,
  1194. key_states,
  1195. value_states,
  1196. attention_mask,
  1197. query_length,
  1198. dropout=0.0,
  1199. softmax_scale=None,
  1200. ):
  1201. """
  1202. Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
  1203. first unpad the input, then computes the attention scores and pad the final attention scores.
  1204. Args:
  1205. query_states (`paddle.Tensor`):
  1206. Input query states to be passed to Flash Attention API
  1207. key_states (`paddle.Tensor`):
  1208. Input key states to be passed to Flash Attention API
  1209. value_states (`paddle.Tensor`):
  1210. Input value states to be passed to Flash Attention API
  1211. attention_mask (`paddle.Tensor`):
  1212. The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
  1213. position of padding tokens and 1 for the position of non-padding tokens.
  1214. dropout (`int`, *optional*):
  1215. Attention dropout
  1216. softmax_scale (`float`, *optional*):
  1217. The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
  1218. """
  1219. # Contains at least one padding token in the sequence
  1220. causal = self.is_causal and query_length != 1
  1221. head_dim = query_states.shape[-1]
  1222. softmax_scale = head_dim**-0.5 # TODO: 需要手动加上
  1223. if attention_mask is not None: # attention_mask.shape # [2, 1, 1323, 1323]
  1224. batch_size = query_states.shape[0] # [2, 1323, 12, 128]
  1225. (
  1226. query_states,
  1227. key_states,
  1228. value_states,
  1229. indices_q,
  1230. cu_seq_lens,
  1231. max_seq_lens,
  1232. ) = self._unpad_input(
  1233. query_states, key_states, value_states, attention_mask, query_length
  1234. )
  1235. cu_seqlens_q, cu_seqlens_k = cu_seq_lens
  1236. max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
  1237. attn_output_unpad = flash_attn_varlen_func( # TODO: flash_attn_unpadded
  1238. query_states, # [5998, 16, 128]
  1239. key_states, # [5998, 8, 128]
  1240. value_states, # [5998, 8, 128]
  1241. cu_seqlens_q=cu_seqlens_q,
  1242. cu_seqlens_k=cu_seqlens_k,
  1243. max_seqlen_q=max_seqlen_in_batch_q,
  1244. max_seqlen_k=max_seqlen_in_batch_k,
  1245. scale=softmax_scale, # not softmax_scale=
  1246. dropout=dropout,
  1247. causal=causal,
  1248. )[0]
  1249. attn_output = pad_input(
  1250. attn_output_unpad, indices_q, batch_size, query_length
  1251. )
  1252. else:
  1253. attn_output = flash_attn_func(
  1254. query_states,
  1255. key_states,
  1256. value_states,
  1257. dropout,
  1258. causal=causal, # no softmax_scale=
  1259. )[0]
  1260. # # 修改这里的维度转换,考虑并行策略下的维度
  1261. # batch_size = query_states.shape[0]
  1262. # hidden_size = self.num_heads * self.head_dim # 计算实际的 hidden_size
  1263. # attn_output = attn_output.reshape([batch_size, query_length, hidden_size])
  1264. return attn_output
  1265. def _unpad_input(
  1266. self, query_layer, key_layer, value_layer, attention_mask, query_length
  1267. ):
  1268. # Note: This function was named _upad_input() in paddle transformers/modeling_flash_attention_utils.py
  1269. indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
  1270. batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
  1271. # TODO:cuda error
  1272. key_layer = index_first_axis(
  1273. key_layer.reshape([batch_size * kv_seq_len, num_key_value_heads, head_dim]),
  1274. indices_k,
  1275. )
  1276. value_layer = index_first_axis(
  1277. value_layer.reshape(
  1278. [batch_size * kv_seq_len, num_key_value_heads, head_dim]
  1279. ),
  1280. indices_k,
  1281. )
  1282. if query_length == kv_seq_len:
  1283. query_layer = index_first_axis(
  1284. query_layer.reshape(
  1285. [batch_size * kv_seq_len, self.num_heads, head_dim]
  1286. ),
  1287. indices_k,
  1288. )
  1289. cu_seqlens_q = cu_seqlens_k
  1290. max_seqlen_in_batch_q = max_seqlen_in_batch_k
  1291. indices_q = indices_k
  1292. elif query_length == 1:
  1293. max_seqlen_in_batch_q = 1
  1294. cu_seqlens_q = paddle.arange(
  1295. batch_size + 1, dtype=paddle.int32
  1296. ) # There is a memcpy here, that is very bad.
  1297. indices_q = cu_seqlens_q[:-1]
  1298. query_layer = query_layer.squeeze(1)
  1299. else:
  1300. # The -q_len: slice assumes left padding.
  1301. attention_mask = attention_mask[:, -query_length:]
  1302. query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
  1303. query_layer, attention_mask
  1304. )
  1305. return (
  1306. query_layer,
  1307. key_layer,
  1308. value_layer,
  1309. indices_q.to(paddle.int64),
  1310. (cu_seqlens_q, cu_seqlens_k),
  1311. (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
  1312. )
  1313. class Qwen2_5_VLSdpaAttention(Qwen2_5_VLAttention):
  1314. """
  1315. Qwen2 attention module using paddle.nn.functional.scaled_dot_product_attention. This module inherits from
  1316. `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
  1317. SDPA API.
  1318. """
  1319. def forward(
  1320. self,
  1321. hidden_states: paddle.Tensor,
  1322. attention_mask: Optional[paddle.Tensor] = None,
  1323. position_ids: Optional[paddle.Tensor] = None,
  1324. past_key_value: Optional[Tuple[paddle.Tensor]] = None,
  1325. output_attentions: bool = False,
  1326. use_cache: bool = False,
  1327. cache_position: Optional[paddle.Tensor] = None,
  1328. position_embeddings: Optional[Tuple[paddle.Tensor, paddle.Tensor]] = None,
  1329. ) -> Tuple[paddle.Tensor, Optional[paddle.Tensor], Optional[Tuple[paddle.Tensor]]]:
  1330. if output_attentions:
  1331. logging.warning_once(
  1332. '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.'
  1333. )
  1334. return super().forward(
  1335. hidden_states=hidden_states,
  1336. attention_mask=attention_mask,
  1337. position_ids=position_ids,
  1338. past_key_value=past_key_value,
  1339. output_attentions=output_attentions,
  1340. use_cache=use_cache,
  1341. cache_position=cache_position,
  1342. position_embeddings=position_embeddings,
  1343. )
  1344. bsz, q_len, _ = hidden_states.shape
  1345. try:
  1346. query_states = self.q_proj(hidden_states)
  1347. key_states = self.k_proj(hidden_states)
  1348. value_states = self.v_proj(hidden_states)
  1349. except:
  1350. hidden_states = hidden_states.astype(self.config.dtype)
  1351. query_states = self.q_proj(hidden_states)
  1352. key_states = self.k_proj(hidden_states)
  1353. value_states = self.v_proj(hidden_states)
  1354. target_query_shape = [0, 0, self.num_heads, self.head_dim]
  1355. target_key_value_shape = [0, 0, self.num_key_value_heads, self.head_dim]
  1356. query_states = query_states.reshape(shape=target_query_shape)
  1357. key_states = key_states.reshape(shape=target_key_value_shape)
  1358. value_states = value_states.reshape(shape=target_key_value_shape)
  1359. new_perm = [0, 2, 1, 3]
  1360. query_states = query_states.transpose(new_perm)
  1361. key_states = key_states.transpose(new_perm)
  1362. value_states = value_states.transpose(new_perm)
  1363. kv_seq_len = key_states.shape[
  1364. -2
  1365. ] # q_len ######## [bs, num_head, seq_len, head_dim] # qwen2是 [-3]
  1366. if past_key_value is not None:
  1367. kv_seq_len += cache_position[0] + 1
  1368. # kv_seq_len += past_key_value[0].shape[-2] # qwen2是 [-3]
  1369. # Because the input can be padded, the absolute sequence length depends on the max position id.
  1370. cos, sin = self.rotary_emb(value_states, position_ids)
  1371. query_states, key_states = apply_multimodal_rotary_pos_emb(
  1372. query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
  1373. )
  1374. if past_key_value is not None:
  1375. # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
  1376. # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  1377. key_states = paddle.concat(
  1378. [past_key_value[0], key_states], axis=2
  1379. ) # qwen2是 axis=1, qwen2_vl是 axis=2
  1380. value_states = paddle.concat(
  1381. [past_key_value[1], value_states], axis=2
  1382. ) # qwen2是 axis=1
  1383. past_key_value = (key_states, value_states) if use_cache else None
  1384. # repeat k/v heads if n_kv_heads < n_heads
  1385. key_states = repeat_kv(key_states, self.num_key_value_groups)
  1386. value_states = repeat_kv(value_states, self.num_key_value_groups)
  1387. # Reashape to the expected shape for Flash Attention
  1388. # [1, 3599, 12, 128]
  1389. query_states = query_states.transpose(perm=[0, 2, 1, 3])
  1390. key_states = key_states.transpose(perm=[0, 2, 1, 3])
  1391. value_states = value_states.transpose(perm=[0, 2, 1, 3])
  1392. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  1393. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  1394. # to infer the attention mask.
  1395. attention_mask = None
  1396. causal_mask = attention_mask
  1397. # Convert attention mask slicing
  1398. if attention_mask is not None:
  1399. causal_mask = attention_mask[:, :, :, : key_states.shape[-3]]
  1400. # Ensure contiguous tensors for PaddlePaddle
  1401. if query_states.place.is_gpu_place() and attention_mask is not None:
  1402. query_states = query_states.contiguous()
  1403. key_states = key_states.contiguous()
  1404. value_states = value_states.contiguous()
  1405. # Determine if the operation is causal
  1406. is_causal = True if causal_mask is None and q_len > 1 else False
  1407. attn_output = paddle.nn.functional.scaled_dot_product_attention(
  1408. query_states,
  1409. key_states,
  1410. value_states,
  1411. attn_mask=causal_mask,
  1412. dropout_p=self.attention_dropout if self.training else 0.0,
  1413. is_causal=is_causal,
  1414. )
  1415. attn_output = attn_output.reshape([bsz, q_len, -1])
  1416. # Apply the output projection
  1417. attn_output = self.o_proj(attn_output)
  1418. return attn_output, None, past_key_value
  1419. QWEN2_5_VL_ATTENTION_CLASSES = {
  1420. "eager": Qwen2_5_VLAttention,
  1421. "flash_attention_2": Qwen2_5_VLFlashAttention2,
  1422. "sdpa": Qwen2_5_VLSdpaAttention,
  1423. }
  1424. class Qwen2_5_VLDecoderLayer(nn.Layer):
  1425. def __init__(self, config: Qwen2_5_VLConfig, layer_idx: int):
  1426. super().__init__()
  1427. self.hidden_size = config.hidden_size
  1428. # use_sliding_window false
  1429. if (
  1430. config.use_sliding_window
  1431. and config.attn_implementation != "flash_attention_2"
  1432. ):
  1433. logging.warning_once(
  1434. f"Sliding Window Attention is enabled but not implemented for `{config.attn_implementation}`; "
  1435. "unexpected results may be encountered."
  1436. )
  1437. self.self_attn = QWEN2_5_VL_ATTENTION_CLASSES[config._attn_implementation](
  1438. config, layer_idx
  1439. )
  1440. self.mlp = Qwen2MLP(config)
  1441. self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  1442. self.post_attention_layernorm = Qwen2RMSNorm(
  1443. config.hidden_size, eps=config.rms_norm_eps
  1444. )
  1445. def forward(
  1446. self,
  1447. hidden_states: paddle.Tensor,
  1448. attention_mask: Optional[paddle.Tensor] = None,
  1449. position_ids: Optional[paddle.Tensor] = None,
  1450. past_key_value: Optional[Tuple[paddle.Tensor]] = None,
  1451. output_attentions: Optional[bool] = False,
  1452. use_cache: Optional[bool] = False,
  1453. cache_position: Optional[paddle.Tensor] = None,
  1454. **kwargs,
  1455. ):
  1456. """
  1457. Args:
  1458. hidden_states (`paddle.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  1459. attention_mask (`paddle.FloatTensor`, *optional*): attention mask of size
  1460. `(batch, sequence_length)` where padding elements are indicated by 0.
  1461. output_attentions (`bool`, *optional*):
  1462. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1463. returned tensors for more detail.
  1464. use_cache (`bool`, *optional*):
  1465. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  1466. (see `past_key_values`).
  1467. past_key_value (`Tuple(paddle.FloatTensor)`, *optional*): cached past key and value projection states
  1468. cache_position (`paddle.LongTensor` of shape `(sequence_length)`, *optional*):
  1469. Indices depicting the position of the input sequence tokens in the sequence.
  1470. position_embeddings (`Tuple[paddle.FloatTensor, paddle.FloatTensor]`, *optional*):
  1471. Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
  1472. with `head_dim` being the embedding dimension of each attention head.
  1473. kwargs (`dict`, *optional*):
  1474. Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
  1475. into the model
  1476. """
  1477. residual = hidden_states
  1478. hidden_states = self.input_layernorm(hidden_states)
  1479. # Self Attention
  1480. hidden_states, self_attn_weights, present_key_value = self.self_attn(
  1481. hidden_states=hidden_states,
  1482. attention_mask=attention_mask,
  1483. position_ids=position_ids,
  1484. past_key_value=past_key_value,
  1485. output_attentions=output_attentions,
  1486. use_cache=use_cache,
  1487. cache_position=cache_position,
  1488. )
  1489. hidden_states = residual + hidden_states
  1490. # Fully Connected
  1491. residual = hidden_states
  1492. hidden_states = self.post_attention_layernorm(hidden_states)
  1493. hidden_states = self.mlp(hidden_states)
  1494. hidden_states = residual + hidden_states
  1495. outputs = (hidden_states,)
  1496. if output_attentions:
  1497. outputs += (self_attn_weights,)
  1498. if use_cache:
  1499. outputs += (present_key_value,)
  1500. return outputs
  1501. class Qwen2_5_VLPreTrainedModel(PretrainedModel):
  1502. config_class = Qwen2_5_VLConfig
  1503. base_model_prefix = "model"
  1504. _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
  1505. _skip_keys_device_placement = "past_key_values"
  1506. def _init_weights(self, layer):
  1507. std = 0.2
  1508. if isinstance(layer, (nn.Linear, nn.Conv3D)):
  1509. nn.initializer.Normal(mean=0.0, std=std)(layer.weight)
  1510. if layer.bias is not None:
  1511. nn.initializer.Constant(0.0)(layer.bias)
  1512. elif isinstance(layer, nn.Embedding):
  1513. nn.initializer.Normal(mean=0.0, std=std)(layer.weight)
  1514. if layer._padding_idx is not None:
  1515. with paddle.no_grad():
  1516. layer.weight[layer._padding_idx] = 0.0
  1517. class Qwen2_5_VisionTransformerPretrainedModel(Qwen2_5_VLPreTrainedModel):
  1518. config_class = Qwen2_5_VLVisionConfig
  1519. _no_split_modules = ["Qwen2_5_VLVisionBlock"]
  1520. def __init__(self, config, *inputs, **kwargs) -> None:
  1521. super().__init__(config, *inputs, **kwargs)
  1522. self.spatial_merge_size = config.spatial_merge_size
  1523. self.patch_size = config.patch_size
  1524. self.fullatt_block_indexes = config.fullatt_block_indexes
  1525. self.window_size = config.window_size
  1526. self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
  1527. self.patch_embed = Qwen2_5_VisionPatchEmbed(
  1528. patch_size=config.patch_size,
  1529. temporal_patch_size=config.temporal_patch_size,
  1530. in_channels=config.in_channels,
  1531. embed_dim=config.hidden_size,
  1532. )
  1533. head_dim = config.hidden_size // config.num_heads
  1534. self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2)
  1535. self.blocks = nn.LayerList(
  1536. sublayers=[
  1537. Qwen2_5_VLVisionBlock(config, config._attn_implementation)
  1538. for _ in range(config.depth)
  1539. ]
  1540. )
  1541. self.merger = Qwen2_5_VLPatchMerger(
  1542. dim=config.out_hidden_size,
  1543. context_dim=config.hidden_size,
  1544. spatial_merge_size=config.spatial_merge_size,
  1545. )
  1546. self.enable_recompute = False
  1547. def rot_pos_emb(self, grid_thw):
  1548. pos_ids = []
  1549. for t, h, w in grid_thw:
  1550. hpos_ids = paddle.arange(h).unsqueeze(1).expand([-1, w])
  1551. hpos_ids = hpos_ids.reshape(
  1552. [
  1553. h // self.spatial_merge_size,
  1554. self.spatial_merge_size,
  1555. w // self.spatial_merge_size,
  1556. self.spatial_merge_size,
  1557. ]
  1558. )
  1559. hpos_ids = hpos_ids.transpose(perm=[0, 2, 1, 3])
  1560. hpos_ids = hpos_ids.flatten()
  1561. wpos_ids = paddle.arange(w).unsqueeze(0).expand([h, -1])
  1562. wpos_ids = wpos_ids.reshape(
  1563. [
  1564. h // self.spatial_merge_size,
  1565. self.spatial_merge_size,
  1566. w // self.spatial_merge_size,
  1567. self.spatial_merge_size,
  1568. ]
  1569. )
  1570. wpos_ids = wpos_ids.transpose([0, 2, 1, 3])
  1571. wpos_ids = wpos_ids.flatten()
  1572. pos_ids.append(
  1573. paddle.stack(x=[hpos_ids, wpos_ids], axis=-1).tile(repeat_times=[t, 1])
  1574. )
  1575. pos_ids = paddle.concat(x=pos_ids, axis=0)
  1576. max_grid_size = grid_thw[:, 1:].max()
  1577. rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
  1578. rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(start_axis=1)
  1579. return rotary_pos_emb
  1580. def get_window_index(self, grid_thw):
  1581. window_index: list = []
  1582. cu_window_seqlens: list = [0]
  1583. window_index_id = 0
  1584. vit_merger_window_size = (
  1585. self.window_size // self.spatial_merge_size // self.patch_size
  1586. )
  1587. for grid_t, grid_h, grid_w in grid_thw:
  1588. llm_grid_h, llm_grid_w = (
  1589. grid_h // self.spatial_merge_size,
  1590. grid_w // self.spatial_merge_size,
  1591. )
  1592. index = paddle.arange(end=grid_t * llm_grid_h * llm_grid_w).reshape(
  1593. [grid_t, llm_grid_h, llm_grid_w]
  1594. )
  1595. pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size
  1596. pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size
  1597. num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size
  1598. num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size
  1599. index_padded = paddle.nn.functional.pad(
  1600. x=index,
  1601. pad=(0, pad_w, 0, pad_h),
  1602. mode="constant",
  1603. value=-100,
  1604. pad_from_left_axis=False,
  1605. )
  1606. index_padded = index_padded.reshape(
  1607. [
  1608. grid_t,
  1609. num_windows_h,
  1610. vit_merger_window_size,
  1611. num_windows_w,
  1612. vit_merger_window_size,
  1613. ]
  1614. )
  1615. index_padded = index_padded.transpose(perm=[0, 1, 3, 2, 4]).reshape(
  1616. [
  1617. grid_t,
  1618. num_windows_h * num_windows_w,
  1619. vit_merger_window_size,
  1620. vit_merger_window_size,
  1621. ]
  1622. )
  1623. seqlens = (index_padded != -100).sum(axis=[2, 3]).reshape([-1])
  1624. index_padded = index_padded.reshape([-1])
  1625. index_new = index_padded[index_padded != -100]
  1626. window_index.append(index_new + window_index_id)
  1627. cu_seqlens_tmp = (
  1628. seqlens.cumsum(axis=0) * self.spatial_merge_unit + cu_window_seqlens[-1]
  1629. )
  1630. cu_window_seqlens.extend(cu_seqlens_tmp.tolist())
  1631. window_index_id += (grid_t * llm_grid_h * llm_grid_w).item()
  1632. window_index = paddle.concat(x=window_index, axis=0)
  1633. return window_index, cu_window_seqlens
  1634. @paddle.jit.not_to_static
  1635. def recompute_training_full(
  1636. self,
  1637. layer_module: nn.Layer,
  1638. hidden_states: paddle.Tensor,
  1639. cu_seqlens_now: paddle.Tensor,
  1640. rotary_pos_emb: paddle.Tensor,
  1641. ):
  1642. def create_custom_forward(module):
  1643. def custom_forward(*inputs):
  1644. return module(*inputs)
  1645. return custom_forward
  1646. hidden_states = recompute(
  1647. create_custom_forward(layer_module),
  1648. hidden_states,
  1649. cu_seqlens_now,
  1650. rotary_pos_emb,
  1651. # use_reentrant=self.config.recompute_use_reentrant,
  1652. )
  1653. return hidden_states
  1654. def forward(
  1655. self, hidden_states: paddle.Tensor, grid_thw: paddle.Tensor
  1656. ) -> paddle.Tensor:
  1657. """
  1658. Args:
  1659. hidden_states (`paddle.Tensor` of shape `(batch_size, seq_len, hidden_size)`):
  1660. The final hidden states of the model.
  1661. grid_thw (`paddle.Tensor` of shape `(num_images_or_videos, 3)`):
  1662. The temporal, height and width of feature shape of each image in LLM.
  1663. Returns:
  1664. `paddle.Tensor`: hidden_states.
  1665. """
  1666. hidden_states = self.patch_embed(hidden_states)
  1667. rotary_pos_emb = self.rot_pos_emb(grid_thw)
  1668. window_index, cu_window_seqlens = self.get_window_index(grid_thw)
  1669. cu_window_seqlens = paddle.to_tensor(
  1670. data=cu_window_seqlens, dtype="int32", place=hidden_states.place
  1671. )
  1672. cu_window_seqlens = paddle.unique_consecutive(x=cu_window_seqlens)
  1673. seq_len, _ = tuple(hidden_states.shape)
  1674. hidden_states = hidden_states.reshape(
  1675. [seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1]
  1676. )
  1677. hidden_states = hidden_states[window_index, :, :]
  1678. hidden_states = hidden_states.reshape([seq_len, -1])
  1679. rotary_pos_emb = rotary_pos_emb.reshape(
  1680. [seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1]
  1681. )
  1682. rotary_pos_emb = rotary_pos_emb[window_index, :, :]
  1683. rotary_pos_emb = rotary_pos_emb.reshape([seq_len, -1])
  1684. cu_seqlens = paddle.repeat_interleave(
  1685. grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]
  1686. ).cumsum(axis=0, dtype="int32")
  1687. cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
  1688. for layer_num, blk in enumerate(self.blocks):
  1689. if layer_num in self.fullatt_block_indexes:
  1690. cu_seqlens_now = cu_seqlens
  1691. else:
  1692. cu_seqlens_now = cu_window_seqlens
  1693. if self.enable_recompute and self.training:
  1694. hidden_states = self.recompute_training_full(
  1695. blk, hidden_states, cu_seqlens_now, rotary_pos_emb
  1696. )
  1697. else:
  1698. hidden_states = blk(
  1699. hidden_states,
  1700. cu_seqlens=cu_seqlens_now,
  1701. rotary_pos_emb=rotary_pos_emb,
  1702. )
  1703. hidden_states = self.merger(hidden_states)
  1704. reverse_indices = paddle.argsort(x=window_index)
  1705. hidden_states = hidden_states[reverse_indices, :]
  1706. return hidden_states
  1707. class Qwen2_5_VLModel(Qwen2_5_VLPreTrainedModel):
  1708. def __init__(self, config: Qwen2_5_VLConfig):
  1709. super().__init__(config)
  1710. self.padding_idx = config.pad_token_id
  1711. self.vocab_size = config.vocab_size
  1712. self.hidden_size = config.hidden_size
  1713. self.config = config
  1714. # Recompute defaults to False and is controlled by Trainer
  1715. if (
  1716. config.tensor_parallel_degree > 1
  1717. and config.vocab_size % config.tensor_parallel_degree == 0
  1718. ):
  1719. self.embed_tokens = mpu.VocabParallelEmbedding(
  1720. self.vocab_size,
  1721. self.hidden_size,
  1722. weight_attr=paddle.ParamAttr(initializer=nn.initializer.XavierNormal()),
  1723. )
  1724. else:
  1725. self.embed_tokens = nn.Embedding(
  1726. self.vocab_size,
  1727. self.hidden_size,
  1728. )
  1729. # self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  1730. self.layers = nn.LayerList(
  1731. [
  1732. Qwen2_5_VLDecoderLayer(config, layer_idx)
  1733. for layer_idx in range(config.num_hidden_layers)
  1734. ]
  1735. )
  1736. self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  1737. self.enable_recompute = False
  1738. def get_input_embeddings(self):
  1739. return self.embed_tokens
  1740. def set_input_embeddings(self, value):
  1741. self.embed_tokens = value
  1742. @staticmethod
  1743. def _prepare_decoder_attention_mask(
  1744. attention_mask, input_shape, past_key_values_length, dtype
  1745. ):
  1746. if attention_mask is not None:
  1747. # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
  1748. if len(attention_mask.shape) == 2:
  1749. expanded_attn_mask = _expand_2d_mask(
  1750. attention_mask, dtype, tgt_length=input_shape[-1]
  1751. )
  1752. # For decoding phase in generation, seq_length = 1, we don't need to add causal mask
  1753. if input_shape[-1] > 1:
  1754. combined_attention_mask = _make_causal_mask(
  1755. input_shape,
  1756. past_key_values_length=past_key_values_length,
  1757. )
  1758. expanded_attn_mask = expanded_attn_mask & combined_attention_mask
  1759. # [bsz, seq_len, seq_len] -> [bsz, 1, seq_len, seq_len]
  1760. elif len(attention_mask.shape) == 3:
  1761. expanded_attn_mask = attention_mask.unsqueeze(1).astype("bool")
  1762. # if attention_mask is already 4-D, do nothing
  1763. else:
  1764. expanded_attn_mask = attention_mask
  1765. else:
  1766. expanded_attn_mask = _make_causal_mask(
  1767. input_shape,
  1768. past_key_values_length=past_key_values_length,
  1769. )
  1770. # Convert bool attention_mask to float attention mask, which will be added to attention_scores later
  1771. expanded_attn_mask = paddle.where(
  1772. expanded_attn_mask, 0.0, paddle.finfo(dtype).min
  1773. ).astype(dtype)
  1774. return expanded_attn_mask
  1775. @paddle.jit.not_to_static
  1776. def recompute_training_full(
  1777. self,
  1778. layer_module: nn.Layer,
  1779. hidden_states: paddle.Tensor,
  1780. position_ids: Optional[paddle.Tensor],
  1781. attention_mask: paddle.Tensor,
  1782. output_attentions: bool,
  1783. past_key_value: paddle.Tensor,
  1784. use_cache: bool,
  1785. cache_position: Optional[paddle.Tensor] = None,
  1786. ):
  1787. def create_custom_forward(module):
  1788. def custom_forward(*inputs):
  1789. return module(*inputs)
  1790. return custom_forward
  1791. hidden_states = recompute(
  1792. create_custom_forward(layer_module),
  1793. hidden_states,
  1794. position_ids,
  1795. attention_mask,
  1796. output_attentions,
  1797. past_key_value,
  1798. use_cache,
  1799. cache_position,
  1800. use_reentrant=self.config.recompute_use_reentrant,
  1801. )
  1802. return hidden_states
  1803. def forward(
  1804. self,
  1805. input_ids: paddle.Tensor = None,
  1806. attention_mask: Optional[paddle.Tensor] = None,
  1807. position_ids: Optional[paddle.Tensor] = None,
  1808. past_key_values: Optional[List[paddle.Tensor]] = None,
  1809. inputs_embeds: Optional[paddle.Tensor] = None,
  1810. use_cache: Optional[bool] = None,
  1811. output_attentions: Optional[bool] = None,
  1812. output_hidden_states: Optional[bool] = None,
  1813. return_dict: Optional[bool] = None,
  1814. cache_position: Optional[paddle.Tensor] = None,
  1815. ) -> Union[Tuple, BaseModelOutputWithPast]:
  1816. output_attentions = (
  1817. output_attentions
  1818. if output_attentions is not None
  1819. else self.config.output_attentions
  1820. )
  1821. output_hidden_states = (
  1822. output_hidden_states
  1823. if output_hidden_states is not None
  1824. else self.config.output_hidden_states
  1825. )
  1826. use_cache = use_cache if use_cache is not None else self.config.use_cache
  1827. return_dict = (
  1828. return_dict if return_dict is not None else self.config.use_return_dict
  1829. )
  1830. if (input_ids is None) ^ (inputs_embeds is not None):
  1831. raise ValueError(
  1832. "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
  1833. )
  1834. elif input_ids is not None:
  1835. batch_size, seq_length = input_ids.shape
  1836. elif inputs_embeds is not None:
  1837. batch_size, seq_length, _ = inputs_embeds.shape
  1838. else:
  1839. raise ValueError(
  1840. "You have to specify either decoder_input_ids or decoder_inputs_embeds"
  1841. )
  1842. if past_key_values is None:
  1843. past_key_values = tuple([None] * len(self.layers))
  1844. # NOTE: to make cache can be clear in-time
  1845. past_key_values = list(past_key_values)
  1846. seq_length_with_past = seq_length
  1847. cache_length = 0
  1848. if past_key_values[0] is not None:
  1849. cache_length = past_key_values[0][0].shape[2] # shape[1] in qwen2
  1850. seq_length_with_past += cache_length
  1851. if inputs_embeds is None:
  1852. inputs_embeds = self.embed_tokens(input_ids)
  1853. # embed positions
  1854. if attention_mask is None:
  1855. # [bs, seq_len]
  1856. attention_mask = paddle.ones(
  1857. (batch_size, seq_length_with_past), dtype=paddle.bool
  1858. )
  1859. if self.config._attn_implementation == "flash_attention_2":
  1860. causal_mask = attention_mask
  1861. else:
  1862. causal_mask = self._prepare_decoder_attention_mask(
  1863. attention_mask,
  1864. (batch_size, seq_length),
  1865. cache_length,
  1866. inputs_embeds.dtype,
  1867. ) # [bs, 1, seq_len, seq_len]
  1868. if cache_position is None:
  1869. past_seen_tokens = (
  1870. past_key_values[0][0].shape[2] if past_key_values[0] is not None else 0
  1871. )
  1872. cache_position = paddle.arange(
  1873. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1]
  1874. )
  1875. if position_ids is None:
  1876. # the hard coded `3` is for temporal, height and width.
  1877. position_ids = cache_position.reshape([1, 1, -1]).expand(
  1878. [3, inputs_embeds.shape[0], -1]
  1879. )
  1880. hidden_states = inputs_embeds
  1881. # decoder layers
  1882. all_hidden_states = () if output_hidden_states else None
  1883. all_self_attns = () if output_attentions else None
  1884. next_decoder_cache = ()
  1885. for idx, (decoder_layer) in enumerate(self.layers):
  1886. if output_hidden_states:
  1887. all_hidden_states += (hidden_states,)
  1888. past_key_value = (
  1889. past_key_values[idx] if past_key_values is not None else None
  1890. )
  1891. if self.enable_recompute and self.training:
  1892. layer_outputs = self.recompute_training_full(
  1893. decoder_layer,
  1894. hidden_states,
  1895. causal_mask,
  1896. position_ids,
  1897. past_key_value,
  1898. output_attentions,
  1899. use_cache,
  1900. cache_position,
  1901. )
  1902. else:
  1903. layer_outputs = decoder_layer(
  1904. hidden_states,
  1905. attention_mask=causal_mask,
  1906. position_ids=position_ids,
  1907. past_key_value=past_key_value,
  1908. output_attentions=output_attentions, # False
  1909. use_cache=use_cache, # True
  1910. cache_position=cache_position,
  1911. )
  1912. # NOTE: clear outdate cache after it has been used for memory saving
  1913. past_key_value = past_key_values[idx] = None
  1914. hidden_states = layer_outputs[0]
  1915. next_decoder_cache = (
  1916. next_decoder_cache + (layer_outputs[-1],) if use_cache else None
  1917. )
  1918. if output_attentions:
  1919. all_self_attns += (layer_outputs[1],)
  1920. hidden_states = self.norm(hidden_states)
  1921. # add hidden states from the last decoder layer
  1922. if output_hidden_states:
  1923. all_hidden_states += (hidden_states,)
  1924. next_cache = next_decoder_cache if use_cache else None
  1925. if not return_dict:
  1926. return tuple(
  1927. v
  1928. for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
  1929. if v is not None
  1930. )
  1931. return BaseModelOutputWithPast(
  1932. last_hidden_state=hidden_states,
  1933. past_key_values=next_cache,
  1934. hidden_states=all_hidden_states,
  1935. attentions=all_self_attns,
  1936. )
  1937. class Qwen2LMHead(nn.Layer):
  1938. def __init__(self, config, embedding_weights=None, transpose_y=False):
  1939. super(Qwen2LMHead, self).__init__()
  1940. self.config = config
  1941. if (
  1942. config.tensor_parallel_degree > 1
  1943. and config.vocab_size % config.tensor_parallel_degree == 0
  1944. ):
  1945. vocab_size = config.vocab_size // config.tensor_parallel_degree
  1946. else:
  1947. vocab_size = config.vocab_size
  1948. self.transpose_y = transpose_y
  1949. if transpose_y:
  1950. # only for weight from embedding_weights
  1951. if embedding_weights is not None:
  1952. self.weight = embedding_weights
  1953. else:
  1954. self.weight = self.create_parameter(
  1955. shape=[vocab_size, config.hidden_size],
  1956. dtype=paddle.get_default_dtype(),
  1957. )
  1958. else:
  1959. if vocab_size != config.vocab_size:
  1960. with get_rng_state_tracker().rng_state():
  1961. self.weight = self.create_parameter(
  1962. shape=[config.hidden_size, vocab_size],
  1963. dtype=paddle.get_default_dtype(),
  1964. )
  1965. else:
  1966. self.weight = self.create_parameter(
  1967. shape=[config.hidden_size, vocab_size],
  1968. dtype=paddle.get_default_dtype(),
  1969. )
  1970. # Must set distributed attr for Tensor Parallel !
  1971. self.weight.is_distributed = (
  1972. True if (vocab_size != config.vocab_size) else False
  1973. )
  1974. if self.weight.is_distributed:
  1975. # for tie_word_embeddings
  1976. self.weight.split_axis = 0 if self.transpose_y else 1
  1977. def forward(self, hidden_states, tensor_parallel_output=None):
  1978. if tensor_parallel_output is None:
  1979. tensor_parallel_output = self.config.tensor_parallel_output
  1980. # 确保数据类型一致
  1981. if self.weight.dtype != hidden_states.dtype:
  1982. hidden_states = paddle.cast(hidden_states, self.weight.dtype)
  1983. logits = parallel_matmul(
  1984. hidden_states,
  1985. self.weight,
  1986. transpose_y=self.transpose_y,
  1987. tensor_parallel_output=tensor_parallel_output,
  1988. )
  1989. return logits
  1990. class Qwen2_5_VLForConditionalGeneration(Qwen2_5_VLPreTrainedModel):
  1991. _tied_weights_keys = ["lm_head.weight"]
  1992. config_class = Qwen2_5_VLConfig
  1993. _no_split_modules = ["Qwen2VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
  1994. def __init__(self, config, attn_implementation="flash_attention_2"):
  1995. super().__init__(config)
  1996. config._attn_implementation = attn_implementation
  1997. config.vision_config._attn_implementation = attn_implementation
  1998. self.visual = Qwen2_5_VisionTransformerPretrainedModel._from_config(
  1999. config.vision_config
  2000. )
  2001. self.model = Qwen2_5_VLModel(config)
  2002. self.vocab_size = config.vocab_size
  2003. if config.tie_word_embeddings:
  2004. self.lm_head = Qwen2LMHead(
  2005. config,
  2006. embedding_weights=self.model.embed_tokens.weight,
  2007. transpose_y=True,
  2008. )
  2009. self.tie_weights()
  2010. else:
  2011. self.lm_head = Qwen2LMHead(config)
  2012. self.padding_side = "left" # set it to left by default, user can use setter to change padding_sides
  2013. self.enable_recompute = False
  2014. def get_input_embeddings(self):
  2015. return self.model.embed_tokens
  2016. def set_input_embeddings(self, value):
  2017. self.model.embed_tokens = value
  2018. def get_output_embeddings(self):
  2019. return self.lm_head
  2020. def set_output_embeddings(self, new_embeddings):
  2021. self.lm_head = new_embeddings
  2022. def set_decoder(self, decoder):
  2023. self.model = decoder
  2024. def get_decoder(self):
  2025. return self.model
  2026. @classmethod
  2027. def _get_tensor_parallel_mappings(cls, config: Qwen2_5_VLConfig, is_split=True):
  2028. logging.info("Qwen2 inference model _get_tensor_parallel_mappings")
  2029. from paddlenlp.transformers.conversion_utils import split_or_merge_func
  2030. fn = split_or_merge_func(
  2031. is_split=is_split,
  2032. tensor_parallel_degree=config.tensor_parallel_degree,
  2033. tensor_parallel_rank=config.tensor_parallel_rank,
  2034. num_attention_heads=config.num_attention_heads,
  2035. )
  2036. def get_tensor_parallel_split_mappings(num_layers):
  2037. final_actions = {}
  2038. base_actions = {
  2039. "lm_head.weight": partial(fn, is_column=True),
  2040. # Row Linear
  2041. "embed_tokens.weight": partial(fn, is_column=False),
  2042. "layers.0.self_attn.o_proj.weight": partial(fn, is_column=False),
  2043. "layers.0.mlp.down_proj.weight": partial(fn, is_column=False),
  2044. }
  2045. # Column Linear
  2046. # if config.fuse_attention_qkv:
  2047. # base_actions["layers.0.self_attn.qkv_proj.weight"] = partial(fn, is_column=True)
  2048. # else:
  2049. base_actions["layers.0.self_attn.q_proj.weight"] = partial(
  2050. fn, is_column=True
  2051. )
  2052. base_actions["layers.0.self_attn.q_proj.bias"] = partial(fn, is_column=True)
  2053. # if we have enough num_key_value_heads to split, then split it.
  2054. if config.num_key_value_heads % config.tensor_parallel_degree == 0:
  2055. base_actions["layers.0.self_attn.k_proj.weight"] = partial(
  2056. fn, is_column=True
  2057. )
  2058. base_actions["layers.0.self_attn.v_proj.weight"] = partial(
  2059. fn, is_column=True
  2060. )
  2061. base_actions["layers.0.self_attn.k_proj.bias"] = partial(
  2062. fn, is_column=True
  2063. )
  2064. base_actions["layers.0.self_attn.v_proj.bias"] = partial(
  2065. fn, is_column=True
  2066. )
  2067. if config.fuse_attention_ffn:
  2068. base_actions["layers.0.mlp.gate_up_fused_proj.weight"] = partial(
  2069. fn, is_column=True, is_naive_2fuse=True
  2070. )
  2071. else:
  2072. base_actions["layers.0.mlp.gate_proj.weight"] = partial(
  2073. fn, is_column=True
  2074. )
  2075. base_actions["layers.0.mlp.up_proj.weight"] = partial(
  2076. fn, is_column=True
  2077. )
  2078. for key, action in base_actions.items():
  2079. if "layers.0." in key:
  2080. for i in range(num_layers):
  2081. final_actions[key.replace("layers.0.", f"layers.{i}.")] = action
  2082. final_actions[key] = action
  2083. return final_actions
  2084. mappings = get_tensor_parallel_split_mappings(config.num_hidden_layers)
  2085. return mappings
  2086. @staticmethod
  2087. def get_rope_index(
  2088. spatial_merge_size,
  2089. image_token_id,
  2090. video_token_id,
  2091. vision_start_token_id,
  2092. tokens_per_second,
  2093. input_ids: Optional[paddle.Tensor] = None,
  2094. image_grid_thw: Optional[paddle.Tensor] = None,
  2095. video_grid_thw: Optional[paddle.Tensor] = None,
  2096. second_per_grid_ts: Optional[paddle.Tensor] = None,
  2097. attention_mask: Optional[paddle.Tensor] = None,
  2098. ) -> Tuple[paddle.Tensor, paddle.Tensor]:
  2099. """
  2100. Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
  2101. Explanation:
  2102. Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
  2103. For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
  2104. Examples:
  2105. input_ids: [T T T T T], here T is for text.
  2106. temporal position_ids: [0, 1, 2, 3, 4]
  2107. height position_ids: [0, 1, 2, 3, 4]
  2108. width position_ids: [0, 1, 2, 3, 4]
  2109. For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
  2110. and 1D rotary position embedding for text part.
  2111. Examples:
  2112. Temporal (Time): 3 patches, representing different segments of the video in time.
  2113. Height: 2 patches, dividing each frame vertically.
  2114. Width: 2 patches, dividing each frame horizontally.
  2115. We also have some important parameters:
  2116. fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
  2117. 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.
  2118. temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
  2119. 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.
  2120. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
  2121. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
  2122. vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
  2123. vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
  2124. text temporal position_ids: [101, 102, 103, 104, 105]
  2125. text height position_ids: [101, 102, 103, 104, 105]
  2126. text width position_ids: [101, 102, 103, 104, 105]
  2127. Here we calculate the text start position_ids as the max vision position_ids plus 1.
  2128. Args:
  2129. input_ids (`paddle.LongTensor` of shape `(batch_size, sequence_length)`):
  2130. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
  2131. it.
  2132. image_grid_thw (`paddle.LongTensor` of shape `(num_images, 3)`, *optional*):
  2133. The temporal, height and width of feature shape of each image in LLM.
  2134. video_grid_thw (`paddle.LongTensor` of shape `(num_videos, 3)`, *optional*):
  2135. The temporal, height and width of feature shape of each video in LLM.
  2136. second_per_grid_ts (`paddle.Tensor` of shape `(num_videos)`, *optional*):
  2137. The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
  2138. attention_mask (`paddle.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  2139. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  2140. - 1 for tokens that are **not masked**,
  2141. - 0 for tokens that are **masked**.
  2142. Returns:
  2143. position_ids (`paddle.Tensor` of shape `(3, batch_size, sequence_length)`)
  2144. mrope_position_deltas (`paddle.Tensor` of shape `(batch_size)`)
  2145. """
  2146. # spatial_merge_size = self.config.vision_config.spatial_merge_size
  2147. # image_token_id = self.config.image_token_id
  2148. # video_token_id = self.config.video_token_id
  2149. # vision_start_token_id = self.config.vision_start_token_id
  2150. mrope_position_deltas = []
  2151. if image_grid_thw is not None or video_grid_thw is not None:
  2152. total_input_ids = input_ids
  2153. position_ids = paddle.ones(
  2154. [3, input_ids.shape[0], input_ids.shape[1]], dtype=input_ids.dtype
  2155. )
  2156. image_index, video_index = 0, 0
  2157. for i, input_ids in enumerate(total_input_ids):
  2158. # TODO: CUDA error in some paddle version
  2159. if attention_mask is not None:
  2160. input_ids = paddle.to_tensor(
  2161. input_ids.cpu()[attention_mask[i].cpu() == 1]
  2162. )
  2163. image_nums, video_nums = 0, 0
  2164. vision_start_indices = paddle.nonzero(
  2165. input_ids == vision_start_token_id
  2166. ).squeeze(1)
  2167. vision_tokens = input_ids[vision_start_indices + 1]
  2168. image_nums = (
  2169. (vision_tokens == image_token_id).sum()
  2170. if vision_tokens.numel() > 0
  2171. else 0
  2172. )
  2173. video_nums = (
  2174. (vision_tokens == video_token_id).sum()
  2175. if vision_tokens.numel() > 0
  2176. else 0
  2177. )
  2178. input_tokens = input_ids.tolist()
  2179. llm_pos_ids_list: list = []
  2180. st = 0
  2181. remain_images, remain_videos = image_nums, video_nums
  2182. for _ in range(image_nums + video_nums):
  2183. if image_token_id in input_tokens and remain_images > 0:
  2184. ed_image = input_tokens.index(image_token_id, st)
  2185. else:
  2186. ed_image = len(input_tokens) + 1
  2187. if video_token_id in input_tokens and remain_videos > 0:
  2188. ed_video = input_tokens.index(video_token_id, st)
  2189. else:
  2190. ed_video = len(input_tokens) + 1
  2191. if ed_image < ed_video:
  2192. t, h, w = (
  2193. image_grid_thw[image_index][0],
  2194. image_grid_thw[image_index][1],
  2195. image_grid_thw[image_index][2],
  2196. )
  2197. second_per_grid_t = 0
  2198. image_index += 1
  2199. remain_images -= 1
  2200. ed = ed_image
  2201. else:
  2202. t, h, w = (
  2203. video_grid_thw[video_index][0],
  2204. video_grid_thw[video_index][1],
  2205. video_grid_thw[video_index][2],
  2206. )
  2207. if second_per_grid_ts is not None:
  2208. second_per_grid_t = second_per_grid_ts[video_index]
  2209. else:
  2210. second_per_grid_t = 1.0
  2211. video_index += 1
  2212. remain_videos -= 1
  2213. ed = ed_video
  2214. llm_grid_t, llm_grid_h, llm_grid_w = (
  2215. t.item(),
  2216. h.item() // spatial_merge_size,
  2217. w.item() // spatial_merge_size,
  2218. )
  2219. text_len = ed - st
  2220. st_idx = (
  2221. llm_pos_ids_list[-1].max() + 1
  2222. if len(llm_pos_ids_list) > 0
  2223. else 0
  2224. )
  2225. llm_pos_ids_list.append(
  2226. paddle.arange(text_len).reshape([1, -1]).expand([3, -1])
  2227. + st_idx
  2228. )
  2229. range_tensor = paddle.arange(end=llm_grid_t).reshape([-1, 1])
  2230. expanded_range = range_tensor.expand(
  2231. shape=[-1, llm_grid_h * llm_grid_w]
  2232. )
  2233. time_tensor = expanded_range * second_per_grid_t * tokens_per_second
  2234. time_tensor_long = time_tensor.astype(dtype="int64")
  2235. t_index = time_tensor_long.flatten()
  2236. h_index = (
  2237. paddle.arange(end=llm_grid_h)
  2238. .reshape([1, -1, 1])
  2239. .expand(shape=[llm_grid_t, -1, llm_grid_w])
  2240. .flatten()
  2241. )
  2242. w_index = (
  2243. paddle.arange(end=llm_grid_w)
  2244. .reshape([1, 1, -1])
  2245. .expand(shape=[llm_grid_t, llm_grid_h, -1])
  2246. .flatten()
  2247. )
  2248. llm_pos_ids_list.append(
  2249. paddle.stack([t_index, h_index, w_index]) + text_len + st_idx
  2250. )
  2251. st = ed + llm_grid_t * llm_grid_h * llm_grid_w
  2252. if st < len(input_tokens):
  2253. st_idx = (
  2254. llm_pos_ids_list[-1].max() + 1
  2255. if len(llm_pos_ids_list) > 0
  2256. else 0
  2257. )
  2258. text_len = len(input_tokens) - st
  2259. llm_pos_ids_list.append(
  2260. paddle.arange(text_len).reshape([1, -1]).expand([3, -1])
  2261. + st_idx
  2262. )
  2263. llm_positions = paddle.concat(llm_pos_ids_list, axis=1).reshape([3, -1])
  2264. position_ids[..., i, attention_mask[i] == 1] = llm_positions
  2265. mrope_position_deltas.append(
  2266. llm_positions.max() + 1 - len(total_input_ids[i])
  2267. )
  2268. mrope_position_deltas = paddle.to_tensor(mrope_position_deltas).unsqueeze(1)
  2269. return position_ids, mrope_position_deltas
  2270. else:
  2271. if attention_mask is not None:
  2272. position_ids = paddle.cast(attention_mask, dtype="int64").cumsum(-1) - 1
  2273. position_ids.masked_fill_(mask=attention_mask == 0, value=1)
  2274. position_ids = position_ids.unsqueeze(0).expand([3, -1, -1])
  2275. max_position_ids = position_ids.max(0, keepdim=False)[0].max(
  2276. -1, keepdim=True
  2277. )[0]
  2278. mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
  2279. else:
  2280. position_ids = (
  2281. paddle.arange(input_ids.shape[1])
  2282. .reshape([1, 1, -1])
  2283. .expand(shape=[3, input_ids.shape[0], -1])
  2284. )
  2285. mrope_position_deltas = paddle.zeros(
  2286. [input_ids.shape[0], 1], dtype=input_ids.dtype
  2287. )
  2288. return position_ids, mrope_position_deltas
  2289. def update_model_kwargs_for_generation(
  2290. self,
  2291. outputs: ModelOutput,
  2292. model_kwargs: Dict[str, Any],
  2293. is_encoder_decoder: bool = False,
  2294. # num_new_tokens: int = 1,
  2295. ) -> Dict[str, Any]:
  2296. model_kwargs = super().update_model_kwargs_for_generation(
  2297. outputs=outputs,
  2298. model_kwargs=model_kwargs,
  2299. is_encoder_decoder=is_encoder_decoder,
  2300. # num_new_tokens=num_new_tokens,
  2301. )
  2302. # return logits + 28 layers k and v, TODO:
  2303. if getattr(outputs, "rope_deltas", None) is not None:
  2304. model_kwargs["rope_deltas"] = outputs.rope_deltas
  2305. return model_kwargs
  2306. # NOTE(changwenbin): Vision module added for high-performance inference.
  2307. def vision_forward(
  2308. self,
  2309. input_ids: paddle.Tensor,
  2310. inputs_embeds: Optional[paddle.Tensor] = None,
  2311. attention_mask: Optional[paddle.Tensor] = None,
  2312. position_ids: Optional[paddle.Tensor] = None,
  2313. pixel_values: Optional[paddle.Tensor] = None,
  2314. pixel_values_videos: Optional[paddle.Tensor] = None,
  2315. image_grid_thw: Optional[paddle.Tensor] = None,
  2316. video_grid_thw: Optional[paddle.Tensor] = None,
  2317. rope_deltas: Optional[paddle.Tensor] = None,
  2318. second_per_grid_ts: Optional[paddle.Tensor] = None,
  2319. ):
  2320. if inputs_embeds is None:
  2321. # NOTE: (zhoukangkang、changwenbin) In the high-performance reasoning of Qwen2-vl,
  2322. # in order to reduce video memory, the qwen2 embed_tokens method in Paddlenlp is reused here.
  2323. from paddlenlp.experimental.transformers.qwen2.modeling import (
  2324. Qwen2_5_VLForConditionalGenerationBlockInferenceModel,
  2325. )
  2326. assert isinstance(
  2327. self.model, Qwen2_5_VLForConditionalGenerationBlockInferenceModel
  2328. ), "model is not an instance of Qwen2_5_VLForConditionalGenerationBlockInferenceModel"
  2329. inputs_embeds = self.model.qwen2.embed_tokens(input_ids)
  2330. if pixel_values is not None:
  2331. pixel_values = paddle.cast(
  2332. pixel_values, self.visual.patch_embed.proj.weight.dtype
  2333. )
  2334. image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
  2335. image_mask = input_ids == self.config.image_token_id
  2336. inputs_embeds[image_mask] = image_embeds
  2337. if pixel_values_videos is not None:
  2338. pixel_values_videos = paddle.cast(
  2339. pixel_values_videos, self.visual.patch_embed.proj.weight.dtype
  2340. )
  2341. video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
  2342. video_mask = input_ids == self.config.video_token_id
  2343. inputs_embeds[video_mask] = video_embeds
  2344. if attention_mask is not None:
  2345. attention_mask = attention_mask
  2346. return inputs_embeds
  2347. def forward(
  2348. self,
  2349. input_ids: paddle.Tensor = None, # [1, 400] sum 49356255
  2350. attention_mask: Optional[paddle.Tensor] = None, # [1, 400] sum 396
  2351. position_ids: Optional[paddle.Tensor] = None,
  2352. past_key_values: Optional[List[paddle.Tensor]] = None,
  2353. inputs_embeds: Optional[paddle.Tensor] = None,
  2354. labels: Optional[paddle.Tensor] = None, # [1, 400] sum 354841
  2355. use_cache: Optional[bool] = None,
  2356. output_attentions: Optional[bool] = None,
  2357. output_hidden_states: Optional[bool] = None,
  2358. return_dict: Optional[bool] = None,
  2359. pixel_values: Optional[
  2360. paddle.Tensor
  2361. ] = None, # [1, 1224, 1176] sum 2658700.50000000
  2362. pixel_values_videos: Optional[paddle.Tensor] = None,
  2363. image_grid_thw: Optional[paddle.Tensor] = None, # [[1 , 36, 34]]
  2364. video_grid_thw: Optional[paddle.Tensor] = None,
  2365. rope_deltas: Optional[paddle.Tensor] = None,
  2366. second_per_grid_ts: Optional[paddle.Tensor] = None,
  2367. ):
  2368. """
  2369. Args:
  2370. labels (`paddle.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  2371. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  2372. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  2373. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  2374. Returns:
  2375. Example:
  2376. ```python
  2377. >>> from PIL import Image
  2378. >>> import requests
  2379. >>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
  2380. >>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
  2381. >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
  2382. >>> messages = [
  2383. {
  2384. "role": "user",
  2385. "content": [
  2386. {"type": "image"},
  2387. {"type": "text", "text": "What is shown in this image?"},
  2388. ],
  2389. },
  2390. ]
  2391. >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
  2392. >>> image = Image.open(requests.get(url, stream=True).raw)
  2393. >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
  2394. >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
  2395. >>> # Generate
  2396. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  2397. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  2398. "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 ..."
  2399. ```"""
  2400. output_attentions = (
  2401. output_attentions
  2402. if output_attentions is not None
  2403. else self.config.output_attentions
  2404. )
  2405. output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states # fmt:skip
  2406. # Note:始终为True
  2407. return_dict = True # return_dict if return_dict is not None else self.config.use_return_dict
  2408. if inputs_embeds is None:
  2409. inputs_embeds = self.model.embed_tokens(input_ids)
  2410. if pixel_values is not None:
  2411. # 确保 pixel_values 和 inputs_embeds 使用相同的数据类型
  2412. pixel_values = paddle.cast(pixel_values, inputs_embeds.dtype)
  2413. image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
  2414. # 确保 image_embeds 和 inputs_embeds 使用相同的数据类型
  2415. image_embeds = paddle.cast(image_embeds, inputs_embeds.dtype)
  2416. image_mask = input_ids == self.config.image_token_id
  2417. if self.training:
  2418. inputs_embeds = inputs_embeds.clone()
  2419. inputs_embeds[image_mask] = image_embeds
  2420. if pixel_values_videos is not None:
  2421. # 确保 pixel_values_videos 和 inputs_embeds 使用相同的数据类型
  2422. pixel_values_videos = paddle.cast(
  2423. pixel_values_videos, inputs_embeds.dtype
  2424. )
  2425. video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
  2426. # 确保 video_embeds 和 inputs_embeds 使用相同的数据类型
  2427. video_embeds = paddle.cast(video_embeds, inputs_embeds.dtype)
  2428. video_mask = input_ids == self.config.video_token_id
  2429. inputs_embeds[video_mask] = video_embeds
  2430. if attention_mask is not None:
  2431. attention_mask = attention_mask
  2432. outputs = self.model(
  2433. input_ids=None,
  2434. position_ids=position_ids,
  2435. attention_mask=attention_mask,
  2436. past_key_values=past_key_values,
  2437. inputs_embeds=inputs_embeds,
  2438. use_cache=use_cache,
  2439. output_attentions=output_attentions,
  2440. output_hidden_states=output_hidden_states,
  2441. return_dict=return_dict,
  2442. )
  2443. hidden_states = outputs[0]
  2444. tensor_parallel_output = (
  2445. self.config.tensor_parallel_output
  2446. and self.config.tensor_parallel_degree > 1
  2447. )
  2448. logits = self.lm_head(
  2449. hidden_states, tensor_parallel_output=tensor_parallel_output
  2450. )
  2451. # logits = paddle.cast(logits, "float32")
  2452. loss = None
  2453. if labels is not None:
  2454. # Shift so that tokens < n predict n
  2455. shift_logits = logits[..., :-1, :] # [1, 395, 151936]
  2456. shift_labels = labels[..., 1:] # [1, 395]
  2457. # Flatten the tokens
  2458. shift_logits = shift_logits.reshape([-1, self.config.vocab_size])
  2459. shift_labels = shift_labels.reshape([-1])
  2460. loss_fct = nn.CrossEntropyLoss(reduction="sum")
  2461. loss = loss_fct(shift_logits, shift_labels)
  2462. label_sum = paddle.sum(shift_labels != -100).cast("float32")
  2463. loss = loss / label_sum
  2464. if not return_dict:
  2465. # output = (logits,) + outputs[1:]
  2466. # Note: (changwenbin) fix "can only concatenate tuple (not "list") to tuple".
  2467. output = (logits,) + tuple(outputs[1:])
  2468. return (loss,) + output if loss is not None else output
  2469. # return logits + 28 layers k and v
  2470. return Qwen2_5_VLCausalLMOutputWithPast(
  2471. loss=loss,
  2472. logits=logits,
  2473. past_key_values=outputs.past_key_values,
  2474. hidden_states=outputs.hidden_states,
  2475. attentions=outputs.attentions,
  2476. rope_deltas=rope_deltas,
  2477. )
  2478. def prepare_inputs_for_generation(
  2479. self,
  2480. input_ids, # [1, 3602] # [[151644, 8948, 198, ..., 151644, 77091, 198]]
  2481. past_key_values=None, # DynamicCache
  2482. attention_mask=None, # [1, 3602] 1
  2483. inputs_embeds=None, # None
  2484. cache_position=None, # [ 0, 1, 2, ..., 3599, 3600, 3601]
  2485. position_ids=None, # None
  2486. use_cache=True,
  2487. pixel_values=None, # [14308, 1176]
  2488. pixel_values_videos=None,
  2489. image_grid_thw=None, # [1, 3] # [[ 1, 98, 146]]
  2490. video_grid_thw=None,
  2491. second_per_grid_ts=None,
  2492. **kwargs,
  2493. ):
  2494. # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
  2495. # Exception 1: when passing input_embeds, input_ids may be missing entries
  2496. # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
  2497. batch_size, seq_length = input_ids.shape
  2498. if past_key_values is None:
  2499. cache_position = paddle.arange(input_ids.shape[1])
  2500. else:
  2501. cache_position = paddle.to_tensor([seq_length - 1])
  2502. if past_key_values is not None:
  2503. input_ids = input_ids[:, -1].unsqueeze(-1)
  2504. rope_deltas = kwargs.get("rope_deltas", None)
  2505. if attention_mask is not None and position_ids is None:
  2506. if cache_position is None or (
  2507. cache_position is not None and cache_position[0] == 0
  2508. ):
  2509. position_ids, rope_deltas = self.get_rope_index(
  2510. self.config.vision_config.spatial_merge_size,
  2511. self.config.image_token_id,
  2512. self.config.video_token_id,
  2513. self.config.vision_start_token_id,
  2514. self.config.vision_config.tokens_per_second,
  2515. input_ids,
  2516. image_grid_thw,
  2517. video_grid_thw,
  2518. second_per_grid_ts,
  2519. attention_mask,
  2520. )
  2521. else:
  2522. batch_size, seq_length = input_ids.shape
  2523. delta = (
  2524. cache_position[0] + rope_deltas
  2525. if cache_position is not None and rope_deltas is not None
  2526. else 0
  2527. )
  2528. position_ids = paddle.arange(seq_length)
  2529. position_ids = position_ids.reshape([1, -1]).expand([batch_size, -1])
  2530. position_ids = position_ids + delta
  2531. position_ids = position_ids.unsqueeze(axis=0).expand([3, -1, -1])
  2532. if cache_position[0] != 0:
  2533. pixel_values = None
  2534. pixel_values_videos = None
  2535. # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
  2536. if inputs_embeds is not None and cache_position[0] == 0:
  2537. model_inputs = {"inputs_embeds": inputs_embeds}
  2538. else:
  2539. model_inputs = {"input_ids": input_ids}
  2540. model_inputs.update(
  2541. {
  2542. "position_ids": position_ids, # [3, 1, 3602]
  2543. "past_key_values": past_key_values, # DynamicCache()
  2544. "use_cache": use_cache, # 1
  2545. "attention_mask": attention_mask, # [1, 3602]
  2546. "pixel_values": pixel_values, # [14308, 1176]
  2547. "pixel_values_videos": pixel_values_videos,
  2548. "image_grid_thw": image_grid_thw, # [[ 1, 98, 146]]
  2549. "video_grid_thw": video_grid_thw,
  2550. "rope_deltas": rope_deltas, # [[-3504]]
  2551. "second_per_grid_ts": second_per_grid_ts,
  2552. }
  2553. )
  2554. return model_inputs
  2555. class PPDocBee2TransformerPretrainedModel(Qwen2_5_VisionTransformerPretrainedModel):
  2556. layer_idx = 15
  2557. def forward(
  2558. self, hidden_states: paddle.Tensor, grid_thw: paddle.Tensor
  2559. ) -> paddle.Tensor:
  2560. """
  2561. Args:
  2562. hidden_states (`paddle.Tensor` of shape `(batch_size, seq_len, hidden_size)`):
  2563. The final hidden states of the model.
  2564. grid_thw (`paddle.Tensor` of shape `(num_images_or_videos, 3)`):
  2565. The temporal, height and width of feature shape of each image in LLM.
  2566. Returns:
  2567. `paddle.Tensor`: hidden_states.
  2568. """
  2569. """
  2570. Args:
  2571. hidden_states (`paddle.Tensor` of shape `(batch_size, seq_len, hidden_size)`):
  2572. The final hidden states of the model.
  2573. grid_thw (`paddle.Tensor` of shape `(num_images_or_videos, 3)`):
  2574. The temporal, height and width of feature shape of each image in LLM.
  2575. Returns:
  2576. `paddle.Tensor`: hidden_states.
  2577. """
  2578. hidden_states = self.patch_embed(hidden_states)
  2579. rotary_pos_emb = self.rot_pos_emb(grid_thw)
  2580. window_index, cu_window_seqlens = self.get_window_index(grid_thw)
  2581. cu_window_seqlens = paddle.to_tensor(
  2582. data=cu_window_seqlens, dtype="int32", place=hidden_states.place
  2583. )
  2584. cu_window_seqlens = paddle.unique_consecutive(x=cu_window_seqlens)
  2585. seq_len, _ = tuple(hidden_states.shape)
  2586. hidden_states = hidden_states.reshape(
  2587. [seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1]
  2588. )
  2589. hidden_states = hidden_states[window_index, :, :]
  2590. hidden_states = hidden_states.reshape([seq_len, -1])
  2591. rotary_pos_emb = rotary_pos_emb.reshape(
  2592. [seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1]
  2593. )
  2594. rotary_pos_emb = rotary_pos_emb[window_index, :, :]
  2595. rotary_pos_emb = rotary_pos_emb.reshape([seq_len, -1])
  2596. cu_seqlens = paddle.repeat_interleave(
  2597. grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]
  2598. ).cumsum(axis=0, dtype="int32")
  2599. cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
  2600. multi_vit = []
  2601. for layer_num, blk in enumerate(self.blocks):
  2602. if layer_num in self.fullatt_block_indexes:
  2603. cu_seqlens_now = cu_seqlens
  2604. else:
  2605. cu_seqlens_now = cu_window_seqlens
  2606. if self.enable_recompute and self.training:
  2607. hidden_states = self.recompute_training_full(
  2608. blk, hidden_states, cu_seqlens_now, rotary_pos_emb
  2609. )
  2610. else:
  2611. hidden_states = blk(
  2612. hidden_states,
  2613. cu_seqlens=cu_seqlens_now,
  2614. rotary_pos_emb=rotary_pos_emb,
  2615. )
  2616. multi_vit.append(hidden_states)
  2617. layer_idx = type(self).layer_idx
  2618. hidden_states = self.merger(hidden_states + multi_vit[layer_idx])
  2619. reverse_indices = paddle.argsort(x=window_index)
  2620. hidden_states = hidden_states[reverse_indices, :]
  2621. return hidden_states
  2622. class PPDocBee2Inference(Qwen2_5_VLForConditionalGeneration):
  2623. def __init__(self, config, attn_implementation="eager"):
  2624. super(Qwen2_5_VLForConditionalGeneration, self).__init__(config)
  2625. config._attn_implementation = attn_implementation
  2626. config.vision_config._attn_implementation = attn_implementation
  2627. self.visual = PPDocBee2TransformerPretrainedModel._from_config(
  2628. config.vision_config
  2629. )
  2630. self.model = Qwen2_5_VLModel(config)
  2631. self.vocab_size = config.vocab_size
  2632. if config.tie_word_embeddings:
  2633. self.lm_head = Qwen2LMHead(
  2634. config,
  2635. embedding_weights=self.model.embed_tokens.weight,
  2636. transpose_y=True,
  2637. )
  2638. self.tie_weights()
  2639. else:
  2640. self.lm_head = Qwen2LMHead(config)
  2641. self.padding_side = "left"
  2642. self.enable_recompute = False
  2643. def generate(self, inputs, **kwargs):
  2644. max_new_tokens = kwargs.get("max_new_tokens", 2048)
  2645. temperature = kwargs.get("temperature", 0.1)
  2646. top_p = kwargs.get("top_p", 0.001)
  2647. top_k = kwargs.get("top_k", 1)
  2648. with paddle.no_grad():
  2649. generated_ids = super().generate(
  2650. **inputs,
  2651. max_new_tokens=max_new_tokens,
  2652. temperature=temperature,
  2653. top_p=top_p,
  2654. top_k=top_k,
  2655. )
  2656. return generated_ids