modeling_ernie.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  1. # coding=utf-8
  2. # Copyright 2022 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch ERNIE model."""
  16. import math
  17. import warnings
  18. from dataclasses import dataclass
  19. from typing import Optional, Union
  20. import torch
  21. from torch import nn
  22. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  23. from ...activations import ACT2FN
  24. from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
  25. from ...generation import GenerationMixin
  26. from ...modeling_layers import GradientCheckpointingLayer
  27. from ...modeling_outputs import (
  28. BaseModelOutputWithPastAndCrossAttentions,
  29. BaseModelOutputWithPoolingAndCrossAttentions,
  30. CausalLMOutputWithCrossAttentions,
  31. MaskedLMOutput,
  32. MultipleChoiceModelOutput,
  33. NextSentencePredictorOutput,
  34. QuestionAnsweringModelOutput,
  35. SequenceClassifierOutput,
  36. TokenClassifierOutput,
  37. )
  38. from ...modeling_utils import PreTrainedModel
  39. from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
  40. from ...utils import ModelOutput, auto_docstring, logging
  41. from ...utils.deprecation import deprecate_kwarg
  42. from .configuration_ernie import ErnieConfig
  43. logger = logging.get_logger(__name__)
  44. class ErnieEmbeddings(nn.Module):
  45. """Construct the embeddings from word, position and token_type embeddings."""
  46. def __init__(self, config):
  47. super().__init__()
  48. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
  49. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
  50. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  51. self.use_task_id = config.use_task_id
  52. if config.use_task_id:
  53. self.task_type_embeddings = nn.Embedding(config.task_type_vocab_size, config.hidden_size)
  54. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  55. # any TensorFlow checkpoint file
  56. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  57. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  58. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  59. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  60. self.register_buffer(
  61. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  62. )
  63. self.register_buffer(
  64. "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
  65. )
  66. def forward(
  67. self,
  68. input_ids: Optional[torch.LongTensor] = None,
  69. token_type_ids: Optional[torch.LongTensor] = None,
  70. task_type_ids: Optional[torch.LongTensor] = None,
  71. position_ids: Optional[torch.LongTensor] = None,
  72. inputs_embeds: Optional[torch.FloatTensor] = None,
  73. past_key_values_length: int = 0,
  74. ) -> torch.Tensor:
  75. if input_ids is not None:
  76. input_shape = input_ids.size()
  77. else:
  78. input_shape = inputs_embeds.size()[:-1]
  79. seq_length = input_shape[1]
  80. if position_ids is None:
  81. position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
  82. # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
  83. # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
  84. # issue #5664
  85. if token_type_ids is None:
  86. if hasattr(self, "token_type_ids"):
  87. buffered_token_type_ids = self.token_type_ids[:, :seq_length]
  88. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
  89. token_type_ids = buffered_token_type_ids_expanded
  90. else:
  91. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  92. if inputs_embeds is None:
  93. inputs_embeds = self.word_embeddings(input_ids)
  94. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  95. embeddings = inputs_embeds + token_type_embeddings
  96. if self.position_embedding_type == "absolute":
  97. position_embeddings = self.position_embeddings(position_ids)
  98. embeddings += position_embeddings
  99. # add `task_type_id` for ERNIE model
  100. if self.use_task_id:
  101. if task_type_ids is None:
  102. task_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  103. task_type_embeddings = self.task_type_embeddings(task_type_ids)
  104. embeddings += task_type_embeddings
  105. embeddings = self.LayerNorm(embeddings)
  106. embeddings = self.dropout(embeddings)
  107. return embeddings
  108. # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Ernie
  109. class ErnieSelfAttention(nn.Module):
  110. def __init__(self, config, position_embedding_type=None, layer_idx=None):
  111. super().__init__()
  112. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  113. raise ValueError(
  114. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  115. f"heads ({config.num_attention_heads})"
  116. )
  117. self.num_attention_heads = config.num_attention_heads
  118. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  119. self.all_head_size = self.num_attention_heads * self.attention_head_size
  120. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  121. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  122. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  123. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  124. self.position_embedding_type = position_embedding_type or getattr(
  125. config, "position_embedding_type", "absolute"
  126. )
  127. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  128. self.max_position_embeddings = config.max_position_embeddings
  129. self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
  130. self.is_decoder = config.is_decoder
  131. self.layer_idx = layer_idx
  132. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  133. def forward(
  134. self,
  135. hidden_states: torch.Tensor,
  136. attention_mask: Optional[torch.FloatTensor] = None,
  137. head_mask: Optional[torch.FloatTensor] = None,
  138. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  139. past_key_values: Optional[Cache] = None,
  140. output_attentions: Optional[bool] = False,
  141. cache_position: Optional[torch.Tensor] = None,
  142. ) -> tuple[torch.Tensor]:
  143. batch_size, seq_length, _ = hidden_states.shape
  144. query_layer = self.query(hidden_states)
  145. query_layer = query_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
  146. 1, 2
  147. )
  148. is_updated = False
  149. is_cross_attention = encoder_hidden_states is not None
  150. if past_key_values is not None:
  151. if isinstance(past_key_values, EncoderDecoderCache):
  152. is_updated = past_key_values.is_updated.get(self.layer_idx)
  153. if is_cross_attention:
  154. # after the first generated id, we can subsequently re-use all key/value_layer from cache
  155. curr_past_key_value = past_key_values.cross_attention_cache
  156. else:
  157. curr_past_key_value = past_key_values.self_attention_cache
  158. else:
  159. curr_past_key_value = past_key_values
  160. current_states = encoder_hidden_states if is_cross_attention else hidden_states
  161. if is_cross_attention and past_key_values is not None and is_updated:
  162. # reuse k,v, cross_attentions
  163. key_layer = curr_past_key_value.layers[self.layer_idx].keys
  164. value_layer = curr_past_key_value.layers[self.layer_idx].values
  165. else:
  166. key_layer = self.key(current_states)
  167. key_layer = key_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
  168. 1, 2
  169. )
  170. value_layer = self.value(current_states)
  171. value_layer = value_layer.view(
  172. batch_size, -1, self.num_attention_heads, self.attention_head_size
  173. ).transpose(1, 2)
  174. if past_key_values is not None:
  175. # save all key/value_layer to cache to be re-used for fast auto-regressive generation
  176. cache_position = cache_position if not is_cross_attention else None
  177. key_layer, value_layer = curr_past_key_value.update(
  178. key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
  179. )
  180. # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
  181. if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
  182. past_key_values.is_updated[self.layer_idx] = True
  183. # Take the dot product between "query" and "key" to get the raw attention scores.
  184. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  185. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  186. query_length, key_length = query_layer.shape[2], key_layer.shape[2]
  187. if past_key_values is not None:
  188. position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
  189. -1, 1
  190. )
  191. else:
  192. position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
  193. position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
  194. distance = position_ids_l - position_ids_r
  195. positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
  196. positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
  197. if self.position_embedding_type == "relative_key":
  198. relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  199. attention_scores = attention_scores + relative_position_scores
  200. elif self.position_embedding_type == "relative_key_query":
  201. relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  202. relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
  203. attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
  204. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  205. if attention_mask is not None:
  206. # Apply the attention mask is (precomputed for all layers in ErnieModel forward() function)
  207. attention_scores = attention_scores + attention_mask
  208. # Normalize the attention scores to probabilities.
  209. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  210. # This is actually dropping out entire tokens to attend to, which might
  211. # seem a bit unusual, but is taken from the original Transformer paper.
  212. attention_probs = self.dropout(attention_probs)
  213. # Mask heads if we want to
  214. if head_mask is not None:
  215. attention_probs = attention_probs * head_mask
  216. context_layer = torch.matmul(attention_probs, value_layer)
  217. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  218. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  219. context_layer = context_layer.view(new_context_layer_shape)
  220. return context_layer, attention_probs
  221. # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Ernie
  222. class ErnieSelfOutput(nn.Module):
  223. def __init__(self, config):
  224. super().__init__()
  225. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  226. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  227. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  228. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  229. hidden_states = self.dense(hidden_states)
  230. hidden_states = self.dropout(hidden_states)
  231. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  232. return hidden_states
  233. ERNIE_SELF_ATTENTION_CLASSES = {
  234. "eager": ErnieSelfAttention,
  235. }
  236. # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Ernie,BERT->ERNIE
  237. class ErnieAttention(nn.Module):
  238. def __init__(self, config, position_embedding_type=None, layer_idx=None):
  239. super().__init__()
  240. self.self = ERNIE_SELF_ATTENTION_CLASSES[config._attn_implementation](
  241. config,
  242. position_embedding_type=position_embedding_type,
  243. layer_idx=layer_idx,
  244. )
  245. self.output = ErnieSelfOutput(config)
  246. self.pruned_heads = set()
  247. def prune_heads(self, heads):
  248. if len(heads) == 0:
  249. return
  250. heads, index = find_pruneable_heads_and_indices(
  251. heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
  252. )
  253. # Prune linear layers
  254. self.self.query = prune_linear_layer(self.self.query, index)
  255. self.self.key = prune_linear_layer(self.self.key, index)
  256. self.self.value = prune_linear_layer(self.self.value, index)
  257. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  258. # Update hyper params and store pruned heads
  259. self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
  260. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  261. self.pruned_heads = self.pruned_heads.union(heads)
  262. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  263. def forward(
  264. self,
  265. hidden_states: torch.Tensor,
  266. attention_mask: Optional[torch.FloatTensor] = None,
  267. head_mask: Optional[torch.FloatTensor] = None,
  268. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  269. past_key_values: Optional[Cache] = None,
  270. output_attentions: Optional[bool] = False,
  271. cache_position: Optional[torch.Tensor] = None,
  272. ) -> tuple[torch.Tensor]:
  273. self_outputs = self.self(
  274. hidden_states,
  275. attention_mask=attention_mask,
  276. head_mask=head_mask,
  277. encoder_hidden_states=encoder_hidden_states,
  278. past_key_values=past_key_values,
  279. output_attentions=output_attentions,
  280. cache_position=cache_position,
  281. )
  282. attention_output = self.output(self_outputs[0], hidden_states)
  283. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  284. return outputs
  285. # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Ernie
  286. class ErnieIntermediate(nn.Module):
  287. def __init__(self, config):
  288. super().__init__()
  289. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  290. if isinstance(config.hidden_act, str):
  291. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  292. else:
  293. self.intermediate_act_fn = config.hidden_act
  294. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  295. hidden_states = self.dense(hidden_states)
  296. hidden_states = self.intermediate_act_fn(hidden_states)
  297. return hidden_states
  298. # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Ernie
  299. class ErnieOutput(nn.Module):
  300. def __init__(self, config):
  301. super().__init__()
  302. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  303. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  304. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  305. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  306. hidden_states = self.dense(hidden_states)
  307. hidden_states = self.dropout(hidden_states)
  308. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  309. return hidden_states
  310. # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Ernie
  311. class ErnieLayer(GradientCheckpointingLayer):
  312. def __init__(self, config, layer_idx=None):
  313. super().__init__()
  314. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  315. self.seq_len_dim = 1
  316. self.attention = ErnieAttention(config, layer_idx=layer_idx)
  317. self.is_decoder = config.is_decoder
  318. self.add_cross_attention = config.add_cross_attention
  319. if self.add_cross_attention:
  320. if not self.is_decoder:
  321. raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
  322. self.crossattention = ErnieAttention(config, position_embedding_type="absolute", layer_idx=layer_idx)
  323. self.intermediate = ErnieIntermediate(config)
  324. self.output = ErnieOutput(config)
  325. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  326. def forward(
  327. self,
  328. hidden_states: torch.Tensor,
  329. attention_mask: Optional[torch.FloatTensor] = None,
  330. head_mask: Optional[torch.FloatTensor] = None,
  331. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  332. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  333. past_key_values: Optional[Cache] = None,
  334. output_attentions: Optional[bool] = False,
  335. cache_position: Optional[torch.Tensor] = None,
  336. ) -> tuple[torch.Tensor]:
  337. self_attention_outputs = self.attention(
  338. hidden_states,
  339. attention_mask=attention_mask,
  340. head_mask=head_mask,
  341. output_attentions=output_attentions,
  342. past_key_values=past_key_values,
  343. cache_position=cache_position,
  344. )
  345. attention_output = self_attention_outputs[0]
  346. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  347. if self.is_decoder and encoder_hidden_states is not None:
  348. if not hasattr(self, "crossattention"):
  349. raise ValueError(
  350. f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
  351. " by setting `config.add_cross_attention=True`"
  352. )
  353. cross_attention_outputs = self.crossattention(
  354. attention_output,
  355. attention_mask=encoder_attention_mask,
  356. head_mask=head_mask,
  357. encoder_hidden_states=encoder_hidden_states,
  358. past_key_values=past_key_values,
  359. output_attentions=output_attentions,
  360. cache_position=cache_position,
  361. )
  362. attention_output = cross_attention_outputs[0]
  363. outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
  364. layer_output = apply_chunking_to_forward(
  365. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  366. )
  367. outputs = (layer_output,) + outputs
  368. return outputs
  369. def feed_forward_chunk(self, attention_output):
  370. intermediate_output = self.intermediate(attention_output)
  371. layer_output = self.output(intermediate_output, attention_output)
  372. return layer_output
  373. # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Ernie
  374. class ErnieEncoder(nn.Module):
  375. def __init__(self, config, layer_idx=None):
  376. super().__init__()
  377. self.config = config
  378. self.layer = nn.ModuleList([ErnieLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
  379. self.gradient_checkpointing = False
  380. def forward(
  381. self,
  382. hidden_states: torch.Tensor,
  383. attention_mask: Optional[torch.FloatTensor] = None,
  384. head_mask: Optional[torch.FloatTensor] = None,
  385. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  386. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  387. past_key_values: Optional[Cache] = None,
  388. use_cache: Optional[bool] = None,
  389. output_attentions: Optional[bool] = False,
  390. output_hidden_states: Optional[bool] = False,
  391. return_dict: Optional[bool] = True,
  392. cache_position: Optional[torch.Tensor] = None,
  393. ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
  394. all_hidden_states = () if output_hidden_states else None
  395. all_self_attentions = () if output_attentions else None
  396. all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
  397. if self.gradient_checkpointing and self.training:
  398. if use_cache:
  399. logger.warning_once(
  400. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  401. )
  402. use_cache = False
  403. if use_cache and self.config.is_decoder and past_key_values is None:
  404. past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
  405. if use_cache and self.config.is_decoder and isinstance(past_key_values, tuple):
  406. logger.warning_once(
  407. "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
  408. "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
  409. "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
  410. )
  411. past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
  412. for i, layer_module in enumerate(self.layer):
  413. if output_hidden_states:
  414. all_hidden_states = all_hidden_states + (hidden_states,)
  415. layer_head_mask = head_mask[i] if head_mask is not None else None
  416. layer_outputs = layer_module(
  417. hidden_states,
  418. attention_mask,
  419. layer_head_mask,
  420. encoder_hidden_states, # as a positional argument for gradient checkpointing
  421. encoder_attention_mask=encoder_attention_mask,
  422. past_key_values=past_key_values,
  423. output_attentions=output_attentions,
  424. cache_position=cache_position,
  425. )
  426. hidden_states = layer_outputs[0]
  427. if output_attentions:
  428. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  429. if self.config.add_cross_attention:
  430. all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
  431. if output_hidden_states:
  432. all_hidden_states = all_hidden_states + (hidden_states,)
  433. if not return_dict:
  434. return tuple(
  435. v
  436. for v in [
  437. hidden_states,
  438. past_key_values,
  439. all_hidden_states,
  440. all_self_attentions,
  441. all_cross_attentions,
  442. ]
  443. if v is not None
  444. )
  445. return BaseModelOutputWithPastAndCrossAttentions(
  446. last_hidden_state=hidden_states,
  447. past_key_values=past_key_values,
  448. hidden_states=all_hidden_states,
  449. attentions=all_self_attentions,
  450. cross_attentions=all_cross_attentions,
  451. )
  452. # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->Ernie
  453. class ErniePooler(nn.Module):
  454. def __init__(self, config):
  455. super().__init__()
  456. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  457. self.activation = nn.Tanh()
  458. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  459. # We "pool" the model by simply taking the hidden state corresponding
  460. # to the first token.
  461. first_token_tensor = hidden_states[:, 0]
  462. pooled_output = self.dense(first_token_tensor)
  463. pooled_output = self.activation(pooled_output)
  464. return pooled_output
  465. # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Ernie
  466. class ErniePredictionHeadTransform(nn.Module):
  467. def __init__(self, config):
  468. super().__init__()
  469. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  470. if isinstance(config.hidden_act, str):
  471. self.transform_act_fn = ACT2FN[config.hidden_act]
  472. else:
  473. self.transform_act_fn = config.hidden_act
  474. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  475. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  476. hidden_states = self.dense(hidden_states)
  477. hidden_states = self.transform_act_fn(hidden_states)
  478. hidden_states = self.LayerNorm(hidden_states)
  479. return hidden_states
  480. # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Ernie
  481. class ErnieLMPredictionHead(nn.Module):
  482. def __init__(self, config):
  483. super().__init__()
  484. self.transform = ErniePredictionHeadTransform(config)
  485. # The output weights are the same as the input embeddings, but there is
  486. # an output-only bias for each token.
  487. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  488. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  489. # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
  490. self.decoder.bias = self.bias
  491. def _tie_weights(self):
  492. self.decoder.bias = self.bias
  493. def forward(self, hidden_states):
  494. hidden_states = self.transform(hidden_states)
  495. hidden_states = self.decoder(hidden_states)
  496. return hidden_states
  497. # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Ernie
  498. class ErnieOnlyMLMHead(nn.Module):
  499. def __init__(self, config):
  500. super().__init__()
  501. self.predictions = ErnieLMPredictionHead(config)
  502. def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
  503. prediction_scores = self.predictions(sequence_output)
  504. return prediction_scores
  505. # Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->Ernie
  506. class ErnieOnlyNSPHead(nn.Module):
  507. def __init__(self, config):
  508. super().__init__()
  509. self.seq_relationship = nn.Linear(config.hidden_size, 2)
  510. def forward(self, pooled_output):
  511. seq_relationship_score = self.seq_relationship(pooled_output)
  512. return seq_relationship_score
  513. # Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->Ernie
  514. class ErniePreTrainingHeads(nn.Module):
  515. def __init__(self, config):
  516. super().__init__()
  517. self.predictions = ErnieLMPredictionHead(config)
  518. self.seq_relationship = nn.Linear(config.hidden_size, 2)
  519. def forward(self, sequence_output, pooled_output):
  520. prediction_scores = self.predictions(sequence_output)
  521. seq_relationship_score = self.seq_relationship(pooled_output)
  522. return prediction_scores, seq_relationship_score
  523. @auto_docstring
  524. class ErniePreTrainedModel(PreTrainedModel):
  525. config: ErnieConfig
  526. base_model_prefix = "ernie"
  527. supports_gradient_checkpointing = True
  528. def _init_weights(self, module):
  529. """Initialize the weights"""
  530. if isinstance(module, nn.Linear):
  531. # Slightly different from the TF version which uses truncated_normal for initialization
  532. # cf https://github.com/pytorch/pytorch/pull/5617
  533. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  534. if module.bias is not None:
  535. module.bias.data.zero_()
  536. elif isinstance(module, nn.Embedding):
  537. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  538. if module.padding_idx is not None:
  539. module.weight.data[module.padding_idx].zero_()
  540. elif isinstance(module, nn.LayerNorm):
  541. module.bias.data.zero_()
  542. module.weight.data.fill_(1.0)
  543. @dataclass
  544. @auto_docstring(
  545. custom_intro="""
  546. Output type of [`ErnieForPreTraining`].
  547. """
  548. )
  549. # Copied from transformers.models.bert.modeling_bert.BertForPreTrainingOutput with Bert->Ernie
  550. class ErnieForPreTrainingOutput(ModelOutput):
  551. r"""
  552. loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
  553. Total loss as the sum of the masked language modeling loss and the next sequence prediction
  554. (classification) loss.
  555. prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
  556. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  557. seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
  558. Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
  559. before SoftMax).
  560. """
  561. loss: Optional[torch.FloatTensor] = None
  562. prediction_logits: Optional[torch.FloatTensor] = None
  563. seq_relationship_logits: Optional[torch.FloatTensor] = None
  564. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  565. attentions: Optional[tuple[torch.FloatTensor]] = None
  566. @auto_docstring(
  567. custom_intro="""
  568. The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
  569. cross-attention is added between the self-attention layers, following the architecture described in [Attention is
  570. all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
  571. Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
  572. To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
  573. to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
  574. """
  575. )
  576. class ErnieModel(ErniePreTrainedModel):
  577. # Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->Ernie
  578. def __init__(self, config, add_pooling_layer=True):
  579. r"""
  580. add_pooling_layer (bool, *optional*, defaults to `True`):
  581. Whether to add a pooling layer
  582. """
  583. super().__init__(config)
  584. self.config = config
  585. self.embeddings = ErnieEmbeddings(config)
  586. self.encoder = ErnieEncoder(config)
  587. self.pooler = ErniePooler(config) if add_pooling_layer else None
  588. # Initialize weights and apply final processing
  589. self.post_init()
  590. # Copied from transformers.models.bert.modeling_bert.BertModel.get_input_embeddings
  591. def get_input_embeddings(self):
  592. return self.embeddings.word_embeddings
  593. # Copied from transformers.models.bert.modeling_bert.BertModel.set_input_embeddings
  594. def set_input_embeddings(self, value):
  595. self.embeddings.word_embeddings = value
  596. # Copied from transformers.models.bert.modeling_bert.BertModel._prune_heads
  597. def _prune_heads(self, heads_to_prune):
  598. """
  599. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  600. class PreTrainedModel
  601. """
  602. for layer, heads in heads_to_prune.items():
  603. self.encoder.layer[layer].attention.prune_heads(heads)
  604. @auto_docstring
  605. def forward(
  606. self,
  607. input_ids: Optional[torch.Tensor] = None,
  608. attention_mask: Optional[torch.Tensor] = None,
  609. token_type_ids: Optional[torch.Tensor] = None,
  610. task_type_ids: Optional[torch.Tensor] = None,
  611. position_ids: Optional[torch.Tensor] = None,
  612. head_mask: Optional[torch.Tensor] = None,
  613. inputs_embeds: Optional[torch.Tensor] = None,
  614. encoder_hidden_states: Optional[torch.Tensor] = None,
  615. encoder_attention_mask: Optional[torch.Tensor] = None,
  616. past_key_values: Optional[Cache] = None,
  617. use_cache: Optional[bool] = None,
  618. output_attentions: Optional[bool] = None,
  619. output_hidden_states: Optional[bool] = None,
  620. return_dict: Optional[bool] = None,
  621. ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
  622. r"""
  623. task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  624. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  625. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  626. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  627. config.task_type_vocab_size-1]
  628. """
  629. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  630. output_hidden_states = (
  631. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  632. )
  633. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  634. if self.config.is_decoder:
  635. use_cache = use_cache if use_cache is not None else self.config.use_cache
  636. else:
  637. use_cache = False
  638. if input_ids is not None and inputs_embeds is not None:
  639. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  640. elif input_ids is not None:
  641. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  642. input_shape = input_ids.size()
  643. elif inputs_embeds is not None:
  644. input_shape = inputs_embeds.size()[:-1]
  645. else:
  646. raise ValueError("You have to specify either input_ids or inputs_embeds")
  647. batch_size, seq_length = input_shape
  648. device = input_ids.device if input_ids is not None else inputs_embeds.device
  649. past_key_values_length = 0
  650. if past_key_values is not None:
  651. past_key_values_length = (
  652. past_key_values[0][0].shape[-2]
  653. if not isinstance(past_key_values, Cache)
  654. else past_key_values.get_seq_length()
  655. )
  656. if attention_mask is None:
  657. attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
  658. if token_type_ids is None:
  659. if hasattr(self.embeddings, "token_type_ids"):
  660. buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
  661. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
  662. token_type_ids = buffered_token_type_ids_expanded
  663. else:
  664. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
  665. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  666. # ourselves in which case we just need to make it broadcastable to all heads.
  667. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
  668. # If a 2D or 3D attention mask is provided for the cross-attention
  669. # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
  670. if self.config.is_decoder and encoder_hidden_states is not None:
  671. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
  672. encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
  673. if encoder_attention_mask is None:
  674. encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
  675. encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
  676. else:
  677. encoder_extended_attention_mask = None
  678. # Prepare head mask if needed
  679. # 1.0 in head_mask indicate we keep the head
  680. # attention_probs has shape bsz x n_heads x N x N
  681. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  682. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  683. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  684. embedding_output = self.embeddings(
  685. input_ids=input_ids,
  686. position_ids=position_ids,
  687. token_type_ids=token_type_ids,
  688. task_type_ids=task_type_ids,
  689. inputs_embeds=inputs_embeds,
  690. past_key_values_length=past_key_values_length,
  691. )
  692. encoder_outputs = self.encoder(
  693. embedding_output,
  694. attention_mask=extended_attention_mask,
  695. head_mask=head_mask,
  696. encoder_hidden_states=encoder_hidden_states,
  697. encoder_attention_mask=encoder_extended_attention_mask,
  698. past_key_values=past_key_values,
  699. use_cache=use_cache,
  700. output_attentions=output_attentions,
  701. output_hidden_states=output_hidden_states,
  702. return_dict=return_dict,
  703. )
  704. sequence_output = encoder_outputs[0]
  705. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  706. if not return_dict:
  707. return (sequence_output, pooled_output) + encoder_outputs[1:]
  708. return BaseModelOutputWithPoolingAndCrossAttentions(
  709. last_hidden_state=sequence_output,
  710. pooler_output=pooled_output,
  711. past_key_values=encoder_outputs.past_key_values,
  712. hidden_states=encoder_outputs.hidden_states,
  713. attentions=encoder_outputs.attentions,
  714. cross_attentions=encoder_outputs.cross_attentions,
  715. )
  716. @auto_docstring(
  717. custom_intro="""
  718. Ernie Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
  719. sentence prediction (classification)` head.
  720. """
  721. )
  722. class ErnieForPreTraining(ErniePreTrainedModel):
  723. _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
  724. # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.__init__ with Bert->Ernie,bert->ernie
  725. def __init__(self, config):
  726. super().__init__(config)
  727. self.ernie = ErnieModel(config)
  728. self.cls = ErniePreTrainingHeads(config)
  729. # Initialize weights and apply final processing
  730. self.post_init()
  731. # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.get_output_embeddings
  732. def get_output_embeddings(self):
  733. return self.cls.predictions.decoder
  734. # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.set_output_embeddings
  735. def set_output_embeddings(self, new_embeddings):
  736. self.cls.predictions.decoder = new_embeddings
  737. self.cls.predictions.bias = new_embeddings.bias
  738. @auto_docstring
  739. def forward(
  740. self,
  741. input_ids: Optional[torch.Tensor] = None,
  742. attention_mask: Optional[torch.Tensor] = None,
  743. token_type_ids: Optional[torch.Tensor] = None,
  744. task_type_ids: Optional[torch.Tensor] = None,
  745. position_ids: Optional[torch.Tensor] = None,
  746. head_mask: Optional[torch.Tensor] = None,
  747. inputs_embeds: Optional[torch.Tensor] = None,
  748. labels: Optional[torch.Tensor] = None,
  749. next_sentence_label: Optional[torch.Tensor] = None,
  750. output_attentions: Optional[bool] = None,
  751. output_hidden_states: Optional[bool] = None,
  752. return_dict: Optional[bool] = None,
  753. ) -> Union[tuple[torch.Tensor], ErnieForPreTrainingOutput]:
  754. r"""
  755. task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  756. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  757. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  758. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  759. config.task_type_vocab_size-1]
  760. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  761. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  762. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
  763. the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
  764. next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  765. Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
  766. pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
  767. - 0 indicates sequence B is a continuation of sequence A,
  768. - 1 indicates sequence B is a random sequence.
  769. Example:
  770. ```python
  771. >>> from transformers import AutoTokenizer, ErnieForPreTraining
  772. >>> import torch
  773. >>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
  774. >>> model = ErnieForPreTraining.from_pretrained("nghuyong/ernie-1.0-base-zh")
  775. >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
  776. >>> outputs = model(**inputs)
  777. >>> prediction_logits = outputs.prediction_logits
  778. >>> seq_relationship_logits = outputs.seq_relationship_logits
  779. ```
  780. """
  781. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  782. outputs = self.ernie(
  783. input_ids,
  784. attention_mask=attention_mask,
  785. token_type_ids=token_type_ids,
  786. task_type_ids=task_type_ids,
  787. position_ids=position_ids,
  788. head_mask=head_mask,
  789. inputs_embeds=inputs_embeds,
  790. output_attentions=output_attentions,
  791. output_hidden_states=output_hidden_states,
  792. return_dict=return_dict,
  793. )
  794. sequence_output, pooled_output = outputs[:2]
  795. prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
  796. total_loss = None
  797. if labels is not None and next_sentence_label is not None:
  798. loss_fct = CrossEntropyLoss()
  799. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  800. next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
  801. total_loss = masked_lm_loss + next_sentence_loss
  802. if not return_dict:
  803. output = (prediction_scores, seq_relationship_score) + outputs[2:]
  804. return ((total_loss,) + output) if total_loss is not None else output
  805. return ErnieForPreTrainingOutput(
  806. loss=total_loss,
  807. prediction_logits=prediction_scores,
  808. seq_relationship_logits=seq_relationship_score,
  809. hidden_states=outputs.hidden_states,
  810. attentions=outputs.attentions,
  811. )
  812. @auto_docstring(
  813. custom_intro="""
  814. Ernie Model with a `language modeling` head on top for CLM fine-tuning.
  815. """
  816. )
  817. class ErnieForCausalLM(ErniePreTrainedModel, GenerationMixin):
  818. _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
  819. # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.__init__ with BertLMHeadModel->ErnieForCausalLM,Bert->Ernie,bert->ernie
  820. def __init__(self, config):
  821. super().__init__(config)
  822. if not config.is_decoder:
  823. logger.warning("If you want to use `ErnieForCausalLM` as a standalone, add `is_decoder=True.`")
  824. self.ernie = ErnieModel(config, add_pooling_layer=False)
  825. self.cls = ErnieOnlyMLMHead(config)
  826. # Initialize weights and apply final processing
  827. self.post_init()
  828. # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.get_output_embeddings
  829. def get_output_embeddings(self):
  830. return self.cls.predictions.decoder
  831. # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.set_output_embeddings
  832. def set_output_embeddings(self, new_embeddings):
  833. self.cls.predictions.decoder = new_embeddings
  834. self.cls.predictions.bias = new_embeddings.bias
  835. @auto_docstring
  836. def forward(
  837. self,
  838. input_ids: Optional[torch.Tensor] = None,
  839. attention_mask: Optional[torch.Tensor] = None,
  840. token_type_ids: Optional[torch.Tensor] = None,
  841. task_type_ids: Optional[torch.Tensor] = None,
  842. position_ids: Optional[torch.Tensor] = None,
  843. head_mask: Optional[torch.Tensor] = None,
  844. inputs_embeds: Optional[torch.Tensor] = None,
  845. encoder_hidden_states: Optional[torch.Tensor] = None,
  846. encoder_attention_mask: Optional[torch.Tensor] = None,
  847. labels: Optional[torch.Tensor] = None,
  848. past_key_values: Optional[Cache] = None,
  849. use_cache: Optional[bool] = None,
  850. output_attentions: Optional[bool] = None,
  851. output_hidden_states: Optional[bool] = None,
  852. return_dict: Optional[bool] = None,
  853. **kwargs,
  854. ) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
  855. r"""
  856. task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  857. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  858. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  859. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  860. config.task_type_vocab_size-1]
  861. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  862. Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
  863. `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
  864. ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
  865. """
  866. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  867. if labels is not None:
  868. use_cache = False
  869. outputs = self.ernie(
  870. input_ids,
  871. attention_mask=attention_mask,
  872. token_type_ids=token_type_ids,
  873. task_type_ids=task_type_ids,
  874. position_ids=position_ids,
  875. head_mask=head_mask,
  876. inputs_embeds=inputs_embeds,
  877. encoder_hidden_states=encoder_hidden_states,
  878. encoder_attention_mask=encoder_attention_mask,
  879. past_key_values=past_key_values,
  880. use_cache=use_cache,
  881. output_attentions=output_attentions,
  882. output_hidden_states=output_hidden_states,
  883. return_dict=return_dict,
  884. )
  885. sequence_output = outputs[0]
  886. prediction_scores = self.cls(sequence_output)
  887. lm_loss = None
  888. if labels is not None:
  889. lm_loss = self.loss_function(
  890. prediction_scores,
  891. labels,
  892. vocab_size=self.config.vocab_size,
  893. **kwargs,
  894. )
  895. if not return_dict:
  896. output = (prediction_scores,) + outputs[2:]
  897. return ((lm_loss,) + output) if lm_loss is not None else output
  898. return CausalLMOutputWithCrossAttentions(
  899. loss=lm_loss,
  900. logits=prediction_scores,
  901. past_key_values=outputs.past_key_values,
  902. hidden_states=outputs.hidden_states,
  903. attentions=outputs.attentions,
  904. cross_attentions=outputs.cross_attentions,
  905. )
  906. @auto_docstring
  907. class ErnieForMaskedLM(ErniePreTrainedModel):
  908. _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
  909. # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.__init__ with Bert->Ernie,bert->ernie
  910. def __init__(self, config):
  911. super().__init__(config)
  912. if config.is_decoder:
  913. logger.warning(
  914. "If you want to use `ErnieForMaskedLM` make sure `config.is_decoder=False` for "
  915. "bi-directional self-attention."
  916. )
  917. self.ernie = ErnieModel(config, add_pooling_layer=False)
  918. self.cls = ErnieOnlyMLMHead(config)
  919. # Initialize weights and apply final processing
  920. self.post_init()
  921. # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.get_output_embeddings
  922. def get_output_embeddings(self):
  923. return self.cls.predictions.decoder
  924. # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.set_output_embeddings
  925. def set_output_embeddings(self, new_embeddings):
  926. self.cls.predictions.decoder = new_embeddings
  927. self.cls.predictions.bias = new_embeddings.bias
  928. @auto_docstring
  929. def forward(
  930. self,
  931. input_ids: Optional[torch.Tensor] = None,
  932. attention_mask: Optional[torch.Tensor] = None,
  933. token_type_ids: Optional[torch.Tensor] = None,
  934. task_type_ids: Optional[torch.Tensor] = None,
  935. position_ids: Optional[torch.Tensor] = None,
  936. head_mask: Optional[torch.Tensor] = None,
  937. inputs_embeds: Optional[torch.Tensor] = None,
  938. encoder_hidden_states: Optional[torch.Tensor] = None,
  939. encoder_attention_mask: Optional[torch.Tensor] = None,
  940. labels: Optional[torch.Tensor] = None,
  941. output_attentions: Optional[bool] = None,
  942. output_hidden_states: Optional[bool] = None,
  943. return_dict: Optional[bool] = None,
  944. ) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
  945. r"""
  946. task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  947. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  948. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  949. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  950. config.task_type_vocab_size-1]
  951. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  952. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  953. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  954. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
  955. """
  956. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  957. outputs = self.ernie(
  958. input_ids,
  959. attention_mask=attention_mask,
  960. token_type_ids=token_type_ids,
  961. task_type_ids=task_type_ids,
  962. position_ids=position_ids,
  963. head_mask=head_mask,
  964. inputs_embeds=inputs_embeds,
  965. encoder_hidden_states=encoder_hidden_states,
  966. encoder_attention_mask=encoder_attention_mask,
  967. output_attentions=output_attentions,
  968. output_hidden_states=output_hidden_states,
  969. return_dict=return_dict,
  970. )
  971. sequence_output = outputs[0]
  972. prediction_scores = self.cls(sequence_output)
  973. masked_lm_loss = None
  974. if labels is not None:
  975. loss_fct = CrossEntropyLoss() # -100 index = padding token
  976. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  977. if not return_dict:
  978. output = (prediction_scores,) + outputs[2:]
  979. return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
  980. return MaskedLMOutput(
  981. loss=masked_lm_loss,
  982. logits=prediction_scores,
  983. hidden_states=outputs.hidden_states,
  984. attentions=outputs.attentions,
  985. )
  986. # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.prepare_inputs_for_generation
  987. def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
  988. input_shape = input_ids.shape
  989. effective_batch_size = input_shape[0]
  990. # add a dummy token
  991. if self.config.pad_token_id is None:
  992. raise ValueError("The PAD token should be defined for generation")
  993. attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
  994. dummy_token = torch.full(
  995. (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
  996. )
  997. input_ids = torch.cat([input_ids, dummy_token], dim=1)
  998. return {"input_ids": input_ids, "attention_mask": attention_mask}
  999. @classmethod
  1000. def can_generate(cls) -> bool:
  1001. """
  1002. Legacy correction: ErnieForMaskedLM can't call `generate()` from `GenerationMixin`, even though it has a
  1003. `prepare_inputs_for_generation` method.
  1004. """
  1005. return False
  1006. @auto_docstring(
  1007. custom_intro="""
  1008. Ernie Model with a `next sentence prediction (classification)` head on top.
  1009. """
  1010. )
  1011. class ErnieForNextSentencePrediction(ErniePreTrainedModel):
  1012. # Copied from transformers.models.bert.modeling_bert.BertForNextSentencePrediction.__init__ with Bert->Ernie,bert->ernie
  1013. def __init__(self, config):
  1014. super().__init__(config)
  1015. self.ernie = ErnieModel(config)
  1016. self.cls = ErnieOnlyNSPHead(config)
  1017. # Initialize weights and apply final processing
  1018. self.post_init()
  1019. @auto_docstring
  1020. def forward(
  1021. self,
  1022. input_ids: Optional[torch.Tensor] = None,
  1023. attention_mask: Optional[torch.Tensor] = None,
  1024. token_type_ids: Optional[torch.Tensor] = None,
  1025. task_type_ids: Optional[torch.Tensor] = None,
  1026. position_ids: Optional[torch.Tensor] = None,
  1027. head_mask: Optional[torch.Tensor] = None,
  1028. inputs_embeds: Optional[torch.Tensor] = None,
  1029. labels: Optional[torch.Tensor] = None,
  1030. output_attentions: Optional[bool] = None,
  1031. output_hidden_states: Optional[bool] = None,
  1032. return_dict: Optional[bool] = None,
  1033. **kwargs,
  1034. ) -> Union[tuple[torch.Tensor], NextSentencePredictorOutput]:
  1035. r"""
  1036. task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1037. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  1038. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  1039. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  1040. config.task_type_vocab_size-1]
  1041. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1042. Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
  1043. (see `input_ids` docstring). Indices should be in `[0, 1]`:
  1044. - 0 indicates sequence B is a continuation of sequence A,
  1045. - 1 indicates sequence B is a random sequence.
  1046. Example:
  1047. ```python
  1048. >>> from transformers import AutoTokenizer, ErnieForNextSentencePrediction
  1049. >>> import torch
  1050. >>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
  1051. >>> model = ErnieForNextSentencePrediction.from_pretrained("nghuyong/ernie-1.0-base-zh")
  1052. >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
  1053. >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
  1054. >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
  1055. >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
  1056. >>> logits = outputs.logits
  1057. >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
  1058. ```
  1059. """
  1060. if "next_sentence_label" in kwargs:
  1061. warnings.warn(
  1062. "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
  1063. " `labels` instead.",
  1064. FutureWarning,
  1065. )
  1066. labels = kwargs.pop("next_sentence_label")
  1067. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1068. outputs = self.ernie(
  1069. input_ids,
  1070. attention_mask=attention_mask,
  1071. token_type_ids=token_type_ids,
  1072. task_type_ids=task_type_ids,
  1073. position_ids=position_ids,
  1074. head_mask=head_mask,
  1075. inputs_embeds=inputs_embeds,
  1076. output_attentions=output_attentions,
  1077. output_hidden_states=output_hidden_states,
  1078. return_dict=return_dict,
  1079. )
  1080. pooled_output = outputs[1]
  1081. seq_relationship_scores = self.cls(pooled_output)
  1082. next_sentence_loss = None
  1083. if labels is not None:
  1084. loss_fct = CrossEntropyLoss()
  1085. next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
  1086. if not return_dict:
  1087. output = (seq_relationship_scores,) + outputs[2:]
  1088. return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
  1089. return NextSentencePredictorOutput(
  1090. loss=next_sentence_loss,
  1091. logits=seq_relationship_scores,
  1092. hidden_states=outputs.hidden_states,
  1093. attentions=outputs.attentions,
  1094. )
  1095. @auto_docstring(
  1096. custom_intro="""
  1097. Ernie Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
  1098. output) e.g. for GLUE tasks.
  1099. """
  1100. )
  1101. class ErnieForSequenceClassification(ErniePreTrainedModel):
  1102. # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification.__init__ with Bert->Ernie,bert->ernie
  1103. def __init__(self, config):
  1104. super().__init__(config)
  1105. self.num_labels = config.num_labels
  1106. self.config = config
  1107. self.ernie = ErnieModel(config)
  1108. classifier_dropout = (
  1109. config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
  1110. )
  1111. self.dropout = nn.Dropout(classifier_dropout)
  1112. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1113. # Initialize weights and apply final processing
  1114. self.post_init()
  1115. @auto_docstring
  1116. def forward(
  1117. self,
  1118. input_ids: Optional[torch.Tensor] = None,
  1119. attention_mask: Optional[torch.Tensor] = None,
  1120. token_type_ids: Optional[torch.Tensor] = None,
  1121. task_type_ids: Optional[torch.Tensor] = None,
  1122. position_ids: Optional[torch.Tensor] = None,
  1123. head_mask: Optional[torch.Tensor] = None,
  1124. inputs_embeds: Optional[torch.Tensor] = None,
  1125. labels: Optional[torch.Tensor] = None,
  1126. output_attentions: Optional[bool] = None,
  1127. output_hidden_states: Optional[bool] = None,
  1128. return_dict: Optional[bool] = None,
  1129. ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
  1130. r"""
  1131. task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1132. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  1133. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  1134. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  1135. config.task_type_vocab_size-1]
  1136. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1137. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1138. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1139. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1140. """
  1141. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1142. outputs = self.ernie(
  1143. input_ids,
  1144. attention_mask=attention_mask,
  1145. token_type_ids=token_type_ids,
  1146. task_type_ids=task_type_ids,
  1147. position_ids=position_ids,
  1148. head_mask=head_mask,
  1149. inputs_embeds=inputs_embeds,
  1150. output_attentions=output_attentions,
  1151. output_hidden_states=output_hidden_states,
  1152. return_dict=return_dict,
  1153. )
  1154. pooled_output = outputs[1]
  1155. pooled_output = self.dropout(pooled_output)
  1156. logits = self.classifier(pooled_output)
  1157. loss = None
  1158. if labels is not None:
  1159. if self.config.problem_type is None:
  1160. if self.num_labels == 1:
  1161. self.config.problem_type = "regression"
  1162. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  1163. self.config.problem_type = "single_label_classification"
  1164. else:
  1165. self.config.problem_type = "multi_label_classification"
  1166. if self.config.problem_type == "regression":
  1167. loss_fct = MSELoss()
  1168. if self.num_labels == 1:
  1169. loss = loss_fct(logits.squeeze(), labels.squeeze())
  1170. else:
  1171. loss = loss_fct(logits, labels)
  1172. elif self.config.problem_type == "single_label_classification":
  1173. loss_fct = CrossEntropyLoss()
  1174. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1175. elif self.config.problem_type == "multi_label_classification":
  1176. loss_fct = BCEWithLogitsLoss()
  1177. loss = loss_fct(logits, labels)
  1178. if not return_dict:
  1179. output = (logits,) + outputs[2:]
  1180. return ((loss,) + output) if loss is not None else output
  1181. return SequenceClassifierOutput(
  1182. loss=loss,
  1183. logits=logits,
  1184. hidden_states=outputs.hidden_states,
  1185. attentions=outputs.attentions,
  1186. )
  1187. @auto_docstring
  1188. class ErnieForMultipleChoice(ErniePreTrainedModel):
  1189. # Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice.__init__ with Bert->Ernie,bert->ernie
  1190. def __init__(self, config):
  1191. super().__init__(config)
  1192. self.ernie = ErnieModel(config)
  1193. classifier_dropout = (
  1194. config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
  1195. )
  1196. self.dropout = nn.Dropout(classifier_dropout)
  1197. self.classifier = nn.Linear(config.hidden_size, 1)
  1198. # Initialize weights and apply final processing
  1199. self.post_init()
  1200. @auto_docstring
  1201. def forward(
  1202. self,
  1203. input_ids: Optional[torch.Tensor] = None,
  1204. attention_mask: Optional[torch.Tensor] = None,
  1205. token_type_ids: Optional[torch.Tensor] = None,
  1206. task_type_ids: Optional[torch.Tensor] = None,
  1207. position_ids: Optional[torch.Tensor] = None,
  1208. head_mask: Optional[torch.Tensor] = None,
  1209. inputs_embeds: Optional[torch.Tensor] = None,
  1210. labels: Optional[torch.Tensor] = None,
  1211. output_attentions: Optional[bool] = None,
  1212. output_hidden_states: Optional[bool] = None,
  1213. return_dict: Optional[bool] = None,
  1214. ) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
  1215. r"""
  1216. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
  1217. Indices of input sequence tokens in the vocabulary.
  1218. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1219. [`PreTrainedTokenizer.__call__`] for details.
  1220. [What are input IDs?](../glossary#input-ids)
  1221. token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1222. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1223. 1]`:
  1224. - 0 corresponds to a *sentence A* token,
  1225. - 1 corresponds to a *sentence B* token.
  1226. [What are token type IDs?](../glossary#token-type-ids)
  1227. task_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1228. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  1229. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  1230. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  1231. config.task_type_vocab_size-1]
  1232. position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1233. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  1234. config.max_position_embeddings - 1]`.
  1235. [What are position IDs?](../glossary#position-ids)
  1236. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
  1237. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  1238. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  1239. model's internal embedding lookup matrix.
  1240. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1241. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  1242. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  1243. `input_ids` above)
  1244. """
  1245. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1246. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  1247. input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  1248. attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  1249. token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  1250. position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
  1251. inputs_embeds = (
  1252. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  1253. if inputs_embeds is not None
  1254. else None
  1255. )
  1256. outputs = self.ernie(
  1257. input_ids,
  1258. attention_mask=attention_mask,
  1259. token_type_ids=token_type_ids,
  1260. task_type_ids=task_type_ids,
  1261. position_ids=position_ids,
  1262. head_mask=head_mask,
  1263. inputs_embeds=inputs_embeds,
  1264. output_attentions=output_attentions,
  1265. output_hidden_states=output_hidden_states,
  1266. return_dict=return_dict,
  1267. )
  1268. pooled_output = outputs[1]
  1269. pooled_output = self.dropout(pooled_output)
  1270. logits = self.classifier(pooled_output)
  1271. reshaped_logits = logits.view(-1, num_choices)
  1272. loss = None
  1273. if labels is not None:
  1274. loss_fct = CrossEntropyLoss()
  1275. loss = loss_fct(reshaped_logits, labels)
  1276. if not return_dict:
  1277. output = (reshaped_logits,) + outputs[2:]
  1278. return ((loss,) + output) if loss is not None else output
  1279. return MultipleChoiceModelOutput(
  1280. loss=loss,
  1281. logits=reshaped_logits,
  1282. hidden_states=outputs.hidden_states,
  1283. attentions=outputs.attentions,
  1284. )
  1285. @auto_docstring
  1286. class ErnieForTokenClassification(ErniePreTrainedModel):
  1287. # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification.__init__ with Bert->Ernie,bert->ernie
  1288. def __init__(self, config):
  1289. super().__init__(config)
  1290. self.num_labels = config.num_labels
  1291. self.ernie = ErnieModel(config, add_pooling_layer=False)
  1292. classifier_dropout = (
  1293. config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
  1294. )
  1295. self.dropout = nn.Dropout(classifier_dropout)
  1296. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1297. # Initialize weights and apply final processing
  1298. self.post_init()
  1299. @auto_docstring
  1300. def forward(
  1301. self,
  1302. input_ids: Optional[torch.Tensor] = None,
  1303. attention_mask: Optional[torch.Tensor] = None,
  1304. token_type_ids: Optional[torch.Tensor] = None,
  1305. task_type_ids: Optional[torch.Tensor] = None,
  1306. position_ids: Optional[torch.Tensor] = None,
  1307. head_mask: Optional[torch.Tensor] = None,
  1308. inputs_embeds: Optional[torch.Tensor] = None,
  1309. labels: Optional[torch.Tensor] = None,
  1310. output_attentions: Optional[bool] = None,
  1311. output_hidden_states: Optional[bool] = None,
  1312. return_dict: Optional[bool] = None,
  1313. ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
  1314. r"""
  1315. task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1316. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  1317. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  1318. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  1319. config.task_type_vocab_size-1]
  1320. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1321. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  1322. """
  1323. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1324. outputs = self.ernie(
  1325. input_ids,
  1326. attention_mask=attention_mask,
  1327. token_type_ids=token_type_ids,
  1328. task_type_ids=task_type_ids,
  1329. position_ids=position_ids,
  1330. head_mask=head_mask,
  1331. inputs_embeds=inputs_embeds,
  1332. output_attentions=output_attentions,
  1333. output_hidden_states=output_hidden_states,
  1334. return_dict=return_dict,
  1335. )
  1336. sequence_output = outputs[0]
  1337. sequence_output = self.dropout(sequence_output)
  1338. logits = self.classifier(sequence_output)
  1339. loss = None
  1340. if labels is not None:
  1341. loss_fct = CrossEntropyLoss()
  1342. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1343. if not return_dict:
  1344. output = (logits,) + outputs[2:]
  1345. return ((loss,) + output) if loss is not None else output
  1346. return TokenClassifierOutput(
  1347. loss=loss,
  1348. logits=logits,
  1349. hidden_states=outputs.hidden_states,
  1350. attentions=outputs.attentions,
  1351. )
  1352. @auto_docstring
  1353. class ErnieForQuestionAnswering(ErniePreTrainedModel):
  1354. # Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering.__init__ with Bert->Ernie,bert->ernie
  1355. def __init__(self, config):
  1356. super().__init__(config)
  1357. self.num_labels = config.num_labels
  1358. self.ernie = ErnieModel(config, add_pooling_layer=False)
  1359. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1360. # Initialize weights and apply final processing
  1361. self.post_init()
  1362. @auto_docstring
  1363. def forward(
  1364. self,
  1365. input_ids: Optional[torch.Tensor] = None,
  1366. attention_mask: Optional[torch.Tensor] = None,
  1367. token_type_ids: Optional[torch.Tensor] = None,
  1368. task_type_ids: Optional[torch.Tensor] = None,
  1369. position_ids: Optional[torch.Tensor] = None,
  1370. head_mask: Optional[torch.Tensor] = None,
  1371. inputs_embeds: Optional[torch.Tensor] = None,
  1372. start_positions: Optional[torch.Tensor] = None,
  1373. end_positions: Optional[torch.Tensor] = None,
  1374. output_attentions: Optional[bool] = None,
  1375. output_hidden_states: Optional[bool] = None,
  1376. return_dict: Optional[bool] = None,
  1377. ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
  1378. r"""
  1379. task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1380. Task type embedding is a special embedding to represent the characteristic of different tasks, such as
  1381. word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
  1382. assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
  1383. config.task_type_vocab_size-1]
  1384. """
  1385. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1386. outputs = self.ernie(
  1387. input_ids,
  1388. attention_mask=attention_mask,
  1389. token_type_ids=token_type_ids,
  1390. task_type_ids=task_type_ids,
  1391. position_ids=position_ids,
  1392. head_mask=head_mask,
  1393. inputs_embeds=inputs_embeds,
  1394. output_attentions=output_attentions,
  1395. output_hidden_states=output_hidden_states,
  1396. return_dict=return_dict,
  1397. )
  1398. sequence_output = outputs[0]
  1399. logits = self.qa_outputs(sequence_output)
  1400. start_logits, end_logits = logits.split(1, dim=-1)
  1401. start_logits = start_logits.squeeze(-1).contiguous()
  1402. end_logits = end_logits.squeeze(-1).contiguous()
  1403. total_loss = None
  1404. if start_positions is not None and end_positions is not None:
  1405. # If we are on multi-GPU, split add a dimension
  1406. if len(start_positions.size()) > 1:
  1407. start_positions = start_positions.squeeze(-1)
  1408. if len(end_positions.size()) > 1:
  1409. end_positions = end_positions.squeeze(-1)
  1410. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1411. ignored_index = start_logits.size(1)
  1412. start_positions = start_positions.clamp(0, ignored_index)
  1413. end_positions = end_positions.clamp(0, ignored_index)
  1414. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1415. start_loss = loss_fct(start_logits, start_positions)
  1416. end_loss = loss_fct(end_logits, end_positions)
  1417. total_loss = (start_loss + end_loss) / 2
  1418. if not return_dict:
  1419. output = (start_logits, end_logits) + outputs[2:]
  1420. return ((total_loss,) + output) if total_loss is not None else output
  1421. return QuestionAnsweringModelOutput(
  1422. loss=total_loss,
  1423. start_logits=start_logits,
  1424. end_logits=end_logits,
  1425. hidden_states=outputs.hidden_states,
  1426. attentions=outputs.attentions,
  1427. )
  1428. __all__ = [
  1429. "ErnieForCausalLM",
  1430. "ErnieForMaskedLM",
  1431. "ErnieForMultipleChoice",
  1432. "ErnieForNextSentencePrediction",
  1433. "ErnieForPreTraining",
  1434. "ErnieForQuestionAnswering",
  1435. "ErnieForSequenceClassification",
  1436. "ErnieForTokenClassification",
  1437. "ErnieModel",
  1438. "ErniePreTrainedModel",
  1439. ]