modeling_electra.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  1. # coding=utf-8
  2. # Copyright 2019 The Google AI Language Team Authors and 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 ELECTRA model."""
  16. import math
  17. import os
  18. from dataclasses import dataclass
  19. from typing import List, Optional, Tuple, Union
  20. import torch
  21. import torch.utils.checkpoint
  22. from torch import nn
  23. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  24. from ...activations import ACT2FN, get_activation
  25. from ...generation import GenerationMixin
  26. from ...modeling_outputs import (
  27. BaseModelOutputWithCrossAttentions,
  28. BaseModelOutputWithPastAndCrossAttentions,
  29. CausalLMOutputWithCrossAttentions,
  30. MaskedLMOutput,
  31. MultipleChoiceModelOutput,
  32. QuestionAnsweringModelOutput,
  33. SequenceClassifierOutput,
  34. TokenClassifierOutput,
  35. )
  36. from ...modeling_utils import PreTrainedModel, SequenceSummary
  37. from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
  38. from ...utils import (
  39. ModelOutput,
  40. add_code_sample_docstrings,
  41. add_start_docstrings,
  42. add_start_docstrings_to_model_forward,
  43. logging,
  44. replace_return_docstrings,
  45. )
  46. from .configuration_electra import ElectraConfig
  47. logger = logging.get_logger(__name__)
  48. _CHECKPOINT_FOR_DOC = "google/electra-small-discriminator"
  49. _CONFIG_FOR_DOC = "ElectraConfig"
  50. def load_tf_weights_in_electra(model, config, tf_checkpoint_path, discriminator_or_generator="discriminator"):
  51. """Load tf checkpoints in a pytorch model."""
  52. try:
  53. import re
  54. import numpy as np
  55. import tensorflow as tf
  56. except ImportError:
  57. logger.error(
  58. "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
  59. "https://www.tensorflow.org/install/ for installation instructions."
  60. )
  61. raise
  62. tf_path = os.path.abspath(tf_checkpoint_path)
  63. logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
  64. # Load weights from TF model
  65. init_vars = tf.train.list_variables(tf_path)
  66. names = []
  67. arrays = []
  68. for name, shape in init_vars:
  69. logger.info(f"Loading TF weight {name} with shape {shape}")
  70. array = tf.train.load_variable(tf_path, name)
  71. names.append(name)
  72. arrays.append(array)
  73. for name, array in zip(names, arrays):
  74. original_name: str = name
  75. try:
  76. if isinstance(model, ElectraForMaskedLM):
  77. name = name.replace("electra/embeddings/", "generator/embeddings/")
  78. if discriminator_or_generator == "generator":
  79. name = name.replace("electra/", "discriminator/")
  80. name = name.replace("generator/", "electra/")
  81. name = name.replace("dense_1", "dense_prediction")
  82. name = name.replace("generator_predictions/output_bias", "generator_lm_head/bias")
  83. name = name.split("/")
  84. # print(original_name, name)
  85. # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
  86. # which are not required for using pretrained model
  87. if any(n in ["global_step", "temperature"] for n in name):
  88. logger.info(f"Skipping {original_name}")
  89. continue
  90. pointer = model
  91. for m_name in name:
  92. if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
  93. scope_names = re.split(r"_(\d+)", m_name)
  94. else:
  95. scope_names = [m_name]
  96. if scope_names[0] == "kernel" or scope_names[0] == "gamma":
  97. pointer = getattr(pointer, "weight")
  98. elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
  99. pointer = getattr(pointer, "bias")
  100. elif scope_names[0] == "output_weights":
  101. pointer = getattr(pointer, "weight")
  102. elif scope_names[0] == "squad":
  103. pointer = getattr(pointer, "classifier")
  104. else:
  105. pointer = getattr(pointer, scope_names[0])
  106. if len(scope_names) >= 2:
  107. num = int(scope_names[1])
  108. pointer = pointer[num]
  109. if m_name.endswith("_embeddings"):
  110. pointer = getattr(pointer, "weight")
  111. elif m_name == "kernel":
  112. array = np.transpose(array)
  113. try:
  114. if pointer.shape != array.shape:
  115. raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
  116. except ValueError as e:
  117. e.args += (pointer.shape, array.shape)
  118. raise
  119. print(f"Initialize PyTorch weight {name}", original_name)
  120. pointer.data = torch.from_numpy(array)
  121. except AttributeError as e:
  122. print(f"Skipping {original_name}", name, e)
  123. continue
  124. return model
  125. class ElectraEmbeddings(nn.Module):
  126. """Construct the embeddings from word, position and token_type embeddings."""
  127. def __init__(self, config):
  128. super().__init__()
  129. self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
  130. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
  131. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
  132. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  133. # any TensorFlow checkpoint file
  134. self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
  135. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  136. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  137. self.register_buffer(
  138. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  139. )
  140. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  141. self.register_buffer(
  142. "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
  143. )
  144. # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.forward
  145. def forward(
  146. self,
  147. input_ids: Optional[torch.LongTensor] = None,
  148. token_type_ids: Optional[torch.LongTensor] = None,
  149. position_ids: Optional[torch.LongTensor] = None,
  150. inputs_embeds: Optional[torch.FloatTensor] = None,
  151. past_key_values_length: int = 0,
  152. ) -> torch.Tensor:
  153. if input_ids is not None:
  154. input_shape = input_ids.size()
  155. else:
  156. input_shape = inputs_embeds.size()[:-1]
  157. seq_length = input_shape[1]
  158. if position_ids is None:
  159. position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
  160. # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
  161. # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
  162. # issue #5664
  163. if token_type_ids is None:
  164. if hasattr(self, "token_type_ids"):
  165. buffered_token_type_ids = self.token_type_ids[:, :seq_length]
  166. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
  167. token_type_ids = buffered_token_type_ids_expanded
  168. else:
  169. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  170. if inputs_embeds is None:
  171. inputs_embeds = self.word_embeddings(input_ids)
  172. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  173. embeddings = inputs_embeds + token_type_embeddings
  174. if self.position_embedding_type == "absolute":
  175. position_embeddings = self.position_embeddings(position_ids)
  176. embeddings += position_embeddings
  177. embeddings = self.LayerNorm(embeddings)
  178. embeddings = self.dropout(embeddings)
  179. return embeddings
  180. # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Electra
  181. class ElectraSelfAttention(nn.Module):
  182. def __init__(self, config, position_embedding_type=None):
  183. super().__init__()
  184. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  185. raise ValueError(
  186. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  187. f"heads ({config.num_attention_heads})"
  188. )
  189. self.num_attention_heads = config.num_attention_heads
  190. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  191. self.all_head_size = self.num_attention_heads * self.attention_head_size
  192. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  193. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  194. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  195. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  196. self.position_embedding_type = position_embedding_type or getattr(
  197. config, "position_embedding_type", "absolute"
  198. )
  199. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  200. self.max_position_embeddings = config.max_position_embeddings
  201. self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
  202. self.is_decoder = config.is_decoder
  203. def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
  204. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  205. x = x.view(new_x_shape)
  206. return x.permute(0, 2, 1, 3)
  207. def forward(
  208. self,
  209. hidden_states: torch.Tensor,
  210. attention_mask: Optional[torch.FloatTensor] = None,
  211. head_mask: Optional[torch.FloatTensor] = None,
  212. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  213. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  214. past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  215. output_attentions: Optional[bool] = False,
  216. ) -> Tuple[torch.Tensor]:
  217. mixed_query_layer = self.query(hidden_states)
  218. # If this is instantiated as a cross-attention module, the keys
  219. # and values come from an encoder; the attention mask needs to be
  220. # such that the encoder's padding tokens are not attended to.
  221. is_cross_attention = encoder_hidden_states is not None
  222. if is_cross_attention and past_key_value is not None:
  223. # reuse k,v, cross_attentions
  224. key_layer = past_key_value[0]
  225. value_layer = past_key_value[1]
  226. attention_mask = encoder_attention_mask
  227. elif is_cross_attention:
  228. key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
  229. value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
  230. attention_mask = encoder_attention_mask
  231. elif past_key_value is not None:
  232. key_layer = self.transpose_for_scores(self.key(hidden_states))
  233. value_layer = self.transpose_for_scores(self.value(hidden_states))
  234. key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
  235. value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
  236. else:
  237. key_layer = self.transpose_for_scores(self.key(hidden_states))
  238. value_layer = self.transpose_for_scores(self.value(hidden_states))
  239. query_layer = self.transpose_for_scores(mixed_query_layer)
  240. use_cache = past_key_value is not None
  241. if self.is_decoder:
  242. # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
  243. # Further calls to cross_attention layer can then reuse all cross-attention
  244. # key/value_states (first "if" case)
  245. # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
  246. # all previous decoder key/value_states. Further calls to uni-directional self-attention
  247. # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
  248. # if encoder bi-directional self-attention `past_key_value` is always `None`
  249. past_key_value = (key_layer, value_layer)
  250. # Take the dot product between "query" and "key" to get the raw attention scores.
  251. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  252. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  253. query_length, key_length = query_layer.shape[2], key_layer.shape[2]
  254. if use_cache:
  255. position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
  256. -1, 1
  257. )
  258. else:
  259. position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
  260. position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
  261. distance = position_ids_l - position_ids_r
  262. positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
  263. positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
  264. if self.position_embedding_type == "relative_key":
  265. relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  266. attention_scores = attention_scores + relative_position_scores
  267. elif self.position_embedding_type == "relative_key_query":
  268. relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  269. relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
  270. attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
  271. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  272. if attention_mask is not None:
  273. # Apply the attention mask is (precomputed for all layers in ElectraModel forward() function)
  274. attention_scores = attention_scores + attention_mask
  275. # Normalize the attention scores to probabilities.
  276. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  277. # This is actually dropping out entire tokens to attend to, which might
  278. # seem a bit unusual, but is taken from the original Transformer paper.
  279. attention_probs = self.dropout(attention_probs)
  280. # Mask heads if we want to
  281. if head_mask is not None:
  282. attention_probs = attention_probs * head_mask
  283. context_layer = torch.matmul(attention_probs, value_layer)
  284. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  285. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  286. context_layer = context_layer.view(new_context_layer_shape)
  287. outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
  288. if self.is_decoder:
  289. outputs = outputs + (past_key_value,)
  290. return outputs
  291. # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
  292. class ElectraSelfOutput(nn.Module):
  293. def __init__(self, config):
  294. super().__init__()
  295. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  296. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  297. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  298. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  299. hidden_states = self.dense(hidden_states)
  300. hidden_states = self.dropout(hidden_states)
  301. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  302. return hidden_states
  303. ELECTRA_SELF_ATTENTION_CLASSES = {
  304. "eager": ElectraSelfAttention,
  305. }
  306. # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Electra,BERT->ELECTRA
  307. class ElectraAttention(nn.Module):
  308. def __init__(self, config, position_embedding_type=None):
  309. super().__init__()
  310. self.self = ELECTRA_SELF_ATTENTION_CLASSES[config._attn_implementation](
  311. config, position_embedding_type=position_embedding_type
  312. )
  313. self.output = ElectraSelfOutput(config)
  314. self.pruned_heads = set()
  315. def prune_heads(self, heads):
  316. if len(heads) == 0:
  317. return
  318. heads, index = find_pruneable_heads_and_indices(
  319. heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
  320. )
  321. # Prune linear layers
  322. self.self.query = prune_linear_layer(self.self.query, index)
  323. self.self.key = prune_linear_layer(self.self.key, index)
  324. self.self.value = prune_linear_layer(self.self.value, index)
  325. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  326. # Update hyper params and store pruned heads
  327. self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
  328. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  329. self.pruned_heads = self.pruned_heads.union(heads)
  330. def forward(
  331. self,
  332. hidden_states: torch.Tensor,
  333. attention_mask: Optional[torch.FloatTensor] = None,
  334. head_mask: Optional[torch.FloatTensor] = None,
  335. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  336. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  337. past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  338. output_attentions: Optional[bool] = False,
  339. ) -> Tuple[torch.Tensor]:
  340. self_outputs = self.self(
  341. hidden_states,
  342. attention_mask,
  343. head_mask,
  344. encoder_hidden_states,
  345. encoder_attention_mask,
  346. past_key_value,
  347. output_attentions,
  348. )
  349. attention_output = self.output(self_outputs[0], hidden_states)
  350. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  351. return outputs
  352. # Copied from transformers.models.bert.modeling_bert.BertIntermediate
  353. class ElectraIntermediate(nn.Module):
  354. def __init__(self, config):
  355. super().__init__()
  356. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  357. if isinstance(config.hidden_act, str):
  358. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  359. else:
  360. self.intermediate_act_fn = config.hidden_act
  361. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  362. hidden_states = self.dense(hidden_states)
  363. hidden_states = self.intermediate_act_fn(hidden_states)
  364. return hidden_states
  365. # Copied from transformers.models.bert.modeling_bert.BertOutput
  366. class ElectraOutput(nn.Module):
  367. def __init__(self, config):
  368. super().__init__()
  369. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  370. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  371. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  372. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  373. hidden_states = self.dense(hidden_states)
  374. hidden_states = self.dropout(hidden_states)
  375. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  376. return hidden_states
  377. # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Electra
  378. class ElectraLayer(nn.Module):
  379. def __init__(self, config):
  380. super().__init__()
  381. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  382. self.seq_len_dim = 1
  383. self.attention = ElectraAttention(config)
  384. self.is_decoder = config.is_decoder
  385. self.add_cross_attention = config.add_cross_attention
  386. if self.add_cross_attention:
  387. if not self.is_decoder:
  388. raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
  389. self.crossattention = ElectraAttention(config, position_embedding_type="absolute")
  390. self.intermediate = ElectraIntermediate(config)
  391. self.output = ElectraOutput(config)
  392. def forward(
  393. self,
  394. hidden_states: torch.Tensor,
  395. attention_mask: Optional[torch.FloatTensor] = None,
  396. head_mask: Optional[torch.FloatTensor] = None,
  397. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  398. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  399. past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  400. output_attentions: Optional[bool] = False,
  401. ) -> Tuple[torch.Tensor]:
  402. # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
  403. self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
  404. self_attention_outputs = self.attention(
  405. hidden_states,
  406. attention_mask,
  407. head_mask,
  408. output_attentions=output_attentions,
  409. past_key_value=self_attn_past_key_value,
  410. )
  411. attention_output = self_attention_outputs[0]
  412. # if decoder, the last output is tuple of self-attn cache
  413. if self.is_decoder:
  414. outputs = self_attention_outputs[1:-1]
  415. present_key_value = self_attention_outputs[-1]
  416. else:
  417. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  418. cross_attn_present_key_value = None
  419. if self.is_decoder and encoder_hidden_states is not None:
  420. if not hasattr(self, "crossattention"):
  421. raise ValueError(
  422. f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
  423. " by setting `config.add_cross_attention=True`"
  424. )
  425. # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
  426. cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
  427. cross_attention_outputs = self.crossattention(
  428. attention_output,
  429. attention_mask,
  430. head_mask,
  431. encoder_hidden_states,
  432. encoder_attention_mask,
  433. cross_attn_past_key_value,
  434. output_attentions,
  435. )
  436. attention_output = cross_attention_outputs[0]
  437. outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
  438. # add cross-attn cache to positions 3,4 of present_key_value tuple
  439. cross_attn_present_key_value = cross_attention_outputs[-1]
  440. present_key_value = present_key_value + cross_attn_present_key_value
  441. layer_output = apply_chunking_to_forward(
  442. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  443. )
  444. outputs = (layer_output,) + outputs
  445. # if decoder, return the attn key/values as the last output
  446. if self.is_decoder:
  447. outputs = outputs + (present_key_value,)
  448. return outputs
  449. def feed_forward_chunk(self, attention_output):
  450. intermediate_output = self.intermediate(attention_output)
  451. layer_output = self.output(intermediate_output, attention_output)
  452. return layer_output
  453. # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Electra
  454. class ElectraEncoder(nn.Module):
  455. def __init__(self, config):
  456. super().__init__()
  457. self.config = config
  458. self.layer = nn.ModuleList([ElectraLayer(config) for _ in range(config.num_hidden_layers)])
  459. self.gradient_checkpointing = False
  460. def forward(
  461. self,
  462. hidden_states: torch.Tensor,
  463. attention_mask: Optional[torch.FloatTensor] = None,
  464. head_mask: Optional[torch.FloatTensor] = None,
  465. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  466. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  467. past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  468. use_cache: Optional[bool] = None,
  469. output_attentions: Optional[bool] = False,
  470. output_hidden_states: Optional[bool] = False,
  471. return_dict: Optional[bool] = True,
  472. ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
  473. all_hidden_states = () if output_hidden_states else None
  474. all_self_attentions = () if output_attentions else None
  475. all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
  476. if self.gradient_checkpointing and self.training:
  477. if use_cache:
  478. logger.warning_once(
  479. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  480. )
  481. use_cache = False
  482. next_decoder_cache = () if use_cache else None
  483. for i, layer_module in enumerate(self.layer):
  484. if output_hidden_states:
  485. all_hidden_states = all_hidden_states + (hidden_states,)
  486. layer_head_mask = head_mask[i] if head_mask is not None else None
  487. past_key_value = past_key_values[i] if past_key_values is not None else None
  488. if self.gradient_checkpointing and self.training:
  489. layer_outputs = self._gradient_checkpointing_func(
  490. layer_module.__call__,
  491. hidden_states,
  492. attention_mask,
  493. layer_head_mask,
  494. encoder_hidden_states,
  495. encoder_attention_mask,
  496. past_key_value,
  497. output_attentions,
  498. )
  499. else:
  500. layer_outputs = layer_module(
  501. hidden_states,
  502. attention_mask,
  503. layer_head_mask,
  504. encoder_hidden_states,
  505. encoder_attention_mask,
  506. past_key_value,
  507. output_attentions,
  508. )
  509. hidden_states = layer_outputs[0]
  510. if use_cache:
  511. next_decoder_cache += (layer_outputs[-1],)
  512. if output_attentions:
  513. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  514. if self.config.add_cross_attention:
  515. all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
  516. if output_hidden_states:
  517. all_hidden_states = all_hidden_states + (hidden_states,)
  518. if not return_dict:
  519. return tuple(
  520. v
  521. for v in [
  522. hidden_states,
  523. next_decoder_cache,
  524. all_hidden_states,
  525. all_self_attentions,
  526. all_cross_attentions,
  527. ]
  528. if v is not None
  529. )
  530. return BaseModelOutputWithPastAndCrossAttentions(
  531. last_hidden_state=hidden_states,
  532. past_key_values=next_decoder_cache,
  533. hidden_states=all_hidden_states,
  534. attentions=all_self_attentions,
  535. cross_attentions=all_cross_attentions,
  536. )
  537. class ElectraDiscriminatorPredictions(nn.Module):
  538. """Prediction module for the discriminator, made up of two dense layers."""
  539. def __init__(self, config):
  540. super().__init__()
  541. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  542. self.activation = get_activation(config.hidden_act)
  543. self.dense_prediction = nn.Linear(config.hidden_size, 1)
  544. self.config = config
  545. def forward(self, discriminator_hidden_states):
  546. hidden_states = self.dense(discriminator_hidden_states)
  547. hidden_states = self.activation(hidden_states)
  548. logits = self.dense_prediction(hidden_states).squeeze(-1)
  549. return logits
  550. class ElectraGeneratorPredictions(nn.Module):
  551. """Prediction module for the generator, made up of two dense layers."""
  552. def __init__(self, config):
  553. super().__init__()
  554. self.activation = get_activation("gelu")
  555. self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
  556. self.dense = nn.Linear(config.hidden_size, config.embedding_size)
  557. def forward(self, generator_hidden_states):
  558. hidden_states = self.dense(generator_hidden_states)
  559. hidden_states = self.activation(hidden_states)
  560. hidden_states = self.LayerNorm(hidden_states)
  561. return hidden_states
  562. class ElectraPreTrainedModel(PreTrainedModel):
  563. """
  564. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  565. models.
  566. """
  567. config_class = ElectraConfig
  568. load_tf_weights = load_tf_weights_in_electra
  569. base_model_prefix = "electra"
  570. supports_gradient_checkpointing = True
  571. # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
  572. def _init_weights(self, module):
  573. """Initialize the weights"""
  574. if isinstance(module, nn.Linear):
  575. # Slightly different from the TF version which uses truncated_normal for initialization
  576. # cf https://github.com/pytorch/pytorch/pull/5617
  577. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  578. if module.bias is not None:
  579. module.bias.data.zero_()
  580. elif isinstance(module, nn.Embedding):
  581. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  582. if module.padding_idx is not None:
  583. module.weight.data[module.padding_idx].zero_()
  584. elif isinstance(module, nn.LayerNorm):
  585. module.bias.data.zero_()
  586. module.weight.data.fill_(1.0)
  587. @dataclass
  588. class ElectraForPreTrainingOutput(ModelOutput):
  589. """
  590. Output type of [`ElectraForPreTraining`].
  591. Args:
  592. loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
  593. Total loss of the ELECTRA objective.
  594. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  595. Prediction scores of the head (scores for each token before SoftMax).
  596. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  597. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  598. shape `(batch_size, sequence_length, hidden_size)`.
  599. Hidden-states of the model at the output of each layer plus the initial embedding outputs.
  600. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  601. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  602. sequence_length)`.
  603. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  604. heads.
  605. """
  606. loss: Optional[torch.FloatTensor] = None
  607. logits: torch.FloatTensor = None
  608. hidden_states: Optional[Tuple[torch.FloatTensor]] = None
  609. attentions: Optional[Tuple[torch.FloatTensor]] = None
  610. ELECTRA_START_DOCSTRING = r"""
  611. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  612. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  613. etc.)
  614. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  615. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  616. and behavior.
  617. Parameters:
  618. config ([`ElectraConfig`]): Model configuration class with all the parameters of the model.
  619. Initializing with a config file does not load the weights associated with the model, only the
  620. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  621. """
  622. ELECTRA_INPUTS_DOCSTRING = r"""
  623. Args:
  624. input_ids (`torch.LongTensor` of shape `({0})`):
  625. Indices of input sequence tokens in the vocabulary.
  626. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  627. [`PreTrainedTokenizer.__call__`] for details.
  628. [What are input IDs?](../glossary#input-ids)
  629. attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
  630. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  631. - 1 for tokens that are **not masked**,
  632. - 0 for tokens that are **masked**.
  633. [What are attention masks?](../glossary#attention-mask)
  634. token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
  635. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  636. 1]`:
  637. - 0 corresponds to a *sentence A* token,
  638. - 1 corresponds to a *sentence B* token.
  639. [What are token type IDs?](../glossary#token-type-ids)
  640. position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
  641. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  642. config.max_position_embeddings - 1]`.
  643. [What are position IDs?](../glossary#position-ids)
  644. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
  645. Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
  646. - 1 indicates the head is **not masked**,
  647. - 0 indicates the head is **masked**.
  648. inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
  649. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  650. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  651. model's internal embedding lookup matrix.
  652. encoder_hidden_states (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
  653. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
  654. the model is configured as a decoder.
  655. encoder_attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
  656. Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
  657. the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
  658. - 1 indicates the head is **not masked**,
  659. - 0 indicates the head is **masked**.
  660. output_attentions (`bool`, *optional*):
  661. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  662. tensors for more detail.
  663. output_hidden_states (`bool`, *optional*):
  664. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  665. more detail.
  666. return_dict (`bool`, *optional*):
  667. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  668. """
  669. @add_start_docstrings(
  670. "The bare Electra Model transformer outputting raw hidden-states without any specific head on top. Identical to "
  671. "the BERT model except that it uses an additional linear layer between the embedding layer and the encoder if the "
  672. "hidden size and embedding size are different. "
  673. ""
  674. "Both the generator and discriminator checkpoints may be loaded into this model.",
  675. ELECTRA_START_DOCSTRING,
  676. )
  677. class ElectraModel(ElectraPreTrainedModel):
  678. def __init__(self, config):
  679. super().__init__(config)
  680. self.embeddings = ElectraEmbeddings(config)
  681. if config.embedding_size != config.hidden_size:
  682. self.embeddings_project = nn.Linear(config.embedding_size, config.hidden_size)
  683. self.encoder = ElectraEncoder(config)
  684. self.config = config
  685. # Initialize weights and apply final processing
  686. self.post_init()
  687. def get_input_embeddings(self):
  688. return self.embeddings.word_embeddings
  689. def set_input_embeddings(self, value):
  690. self.embeddings.word_embeddings = value
  691. def _prune_heads(self, heads_to_prune):
  692. """
  693. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  694. class PreTrainedModel
  695. """
  696. for layer, heads in heads_to_prune.items():
  697. self.encoder.layer[layer].attention.prune_heads(heads)
  698. @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  699. @add_code_sample_docstrings(
  700. checkpoint=_CHECKPOINT_FOR_DOC,
  701. output_type=BaseModelOutputWithCrossAttentions,
  702. config_class=_CONFIG_FOR_DOC,
  703. )
  704. def forward(
  705. self,
  706. input_ids: Optional[torch.Tensor] = None,
  707. attention_mask: Optional[torch.Tensor] = None,
  708. token_type_ids: Optional[torch.Tensor] = None,
  709. position_ids: Optional[torch.Tensor] = None,
  710. head_mask: Optional[torch.Tensor] = None,
  711. inputs_embeds: Optional[torch.Tensor] = None,
  712. encoder_hidden_states: Optional[torch.Tensor] = None,
  713. encoder_attention_mask: Optional[torch.Tensor] = None,
  714. past_key_values: Optional[List[torch.FloatTensor]] = None,
  715. use_cache: Optional[bool] = None,
  716. output_attentions: Optional[bool] = None,
  717. output_hidden_states: Optional[bool] = None,
  718. return_dict: Optional[bool] = None,
  719. ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithCrossAttentions]:
  720. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  721. output_hidden_states = (
  722. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  723. )
  724. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  725. if input_ids is not None and inputs_embeds is not None:
  726. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  727. elif input_ids is not None:
  728. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  729. input_shape = input_ids.size()
  730. elif inputs_embeds is not None:
  731. input_shape = inputs_embeds.size()[:-1]
  732. else:
  733. raise ValueError("You have to specify either input_ids or inputs_embeds")
  734. batch_size, seq_length = input_shape
  735. device = input_ids.device if input_ids is not None else inputs_embeds.device
  736. # past_key_values_length
  737. past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
  738. if attention_mask is None:
  739. attention_mask = torch.ones(input_shape, device=device)
  740. if token_type_ids is None:
  741. if hasattr(self.embeddings, "token_type_ids"):
  742. buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
  743. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
  744. token_type_ids = buffered_token_type_ids_expanded
  745. else:
  746. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
  747. extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
  748. # If a 2D or 3D attention mask is provided for the cross-attention
  749. # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
  750. if self.config.is_decoder and encoder_hidden_states is not None:
  751. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
  752. encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
  753. if encoder_attention_mask is None:
  754. encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
  755. encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
  756. else:
  757. encoder_extended_attention_mask = None
  758. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  759. hidden_states = self.embeddings(
  760. input_ids=input_ids,
  761. position_ids=position_ids,
  762. token_type_ids=token_type_ids,
  763. inputs_embeds=inputs_embeds,
  764. past_key_values_length=past_key_values_length,
  765. )
  766. if hasattr(self, "embeddings_project"):
  767. hidden_states = self.embeddings_project(hidden_states)
  768. hidden_states = self.encoder(
  769. hidden_states,
  770. attention_mask=extended_attention_mask,
  771. head_mask=head_mask,
  772. encoder_hidden_states=encoder_hidden_states,
  773. encoder_attention_mask=encoder_extended_attention_mask,
  774. past_key_values=past_key_values,
  775. use_cache=use_cache,
  776. output_attentions=output_attentions,
  777. output_hidden_states=output_hidden_states,
  778. return_dict=return_dict,
  779. )
  780. return hidden_states
  781. class ElectraClassificationHead(nn.Module):
  782. """Head for sentence-level classification tasks."""
  783. def __init__(self, config):
  784. super().__init__()
  785. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  786. classifier_dropout = (
  787. config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
  788. )
  789. self.activation = get_activation("gelu")
  790. self.dropout = nn.Dropout(classifier_dropout)
  791. self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
  792. def forward(self, features, **kwargs):
  793. x = features[:, 0, :] # take <s> token (equiv. to [CLS])
  794. x = self.dropout(x)
  795. x = self.dense(x)
  796. x = self.activation(x) # although BERT uses tanh here, it seems Electra authors used gelu here
  797. x = self.dropout(x)
  798. x = self.out_proj(x)
  799. return x
  800. @add_start_docstrings(
  801. """
  802. ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the
  803. pooled output) e.g. for GLUE tasks.
  804. """,
  805. ELECTRA_START_DOCSTRING,
  806. )
  807. class ElectraForSequenceClassification(ElectraPreTrainedModel):
  808. def __init__(self, config):
  809. super().__init__(config)
  810. self.num_labels = config.num_labels
  811. self.config = config
  812. self.electra = ElectraModel(config)
  813. self.classifier = ElectraClassificationHead(config)
  814. # Initialize weights and apply final processing
  815. self.post_init()
  816. @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  817. @add_code_sample_docstrings(
  818. checkpoint="bhadresh-savani/electra-base-emotion",
  819. output_type=SequenceClassifierOutput,
  820. config_class=_CONFIG_FOR_DOC,
  821. expected_output="'joy'",
  822. expected_loss=0.06,
  823. )
  824. def forward(
  825. self,
  826. input_ids: Optional[torch.Tensor] = None,
  827. attention_mask: Optional[torch.Tensor] = None,
  828. token_type_ids: Optional[torch.Tensor] = None,
  829. position_ids: Optional[torch.Tensor] = None,
  830. head_mask: Optional[torch.Tensor] = None,
  831. inputs_embeds: Optional[torch.Tensor] = None,
  832. labels: Optional[torch.Tensor] = None,
  833. output_attentions: Optional[bool] = None,
  834. output_hidden_states: Optional[bool] = None,
  835. return_dict: Optional[bool] = None,
  836. ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
  837. r"""
  838. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  839. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  840. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  841. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  842. """
  843. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  844. discriminator_hidden_states = self.electra(
  845. input_ids,
  846. attention_mask=attention_mask,
  847. token_type_ids=token_type_ids,
  848. position_ids=position_ids,
  849. head_mask=head_mask,
  850. inputs_embeds=inputs_embeds,
  851. output_attentions=output_attentions,
  852. output_hidden_states=output_hidden_states,
  853. return_dict=return_dict,
  854. )
  855. sequence_output = discriminator_hidden_states[0]
  856. logits = self.classifier(sequence_output)
  857. loss = None
  858. if labels is not None:
  859. if self.config.problem_type is None:
  860. if self.num_labels == 1:
  861. self.config.problem_type = "regression"
  862. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  863. self.config.problem_type = "single_label_classification"
  864. else:
  865. self.config.problem_type = "multi_label_classification"
  866. if self.config.problem_type == "regression":
  867. loss_fct = MSELoss()
  868. if self.num_labels == 1:
  869. loss = loss_fct(logits.squeeze(), labels.squeeze())
  870. else:
  871. loss = loss_fct(logits, labels)
  872. elif self.config.problem_type == "single_label_classification":
  873. loss_fct = CrossEntropyLoss()
  874. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  875. elif self.config.problem_type == "multi_label_classification":
  876. loss_fct = BCEWithLogitsLoss()
  877. loss = loss_fct(logits, labels)
  878. if not return_dict:
  879. output = (logits,) + discriminator_hidden_states[1:]
  880. return ((loss,) + output) if loss is not None else output
  881. return SequenceClassifierOutput(
  882. loss=loss,
  883. logits=logits,
  884. hidden_states=discriminator_hidden_states.hidden_states,
  885. attentions=discriminator_hidden_states.attentions,
  886. )
  887. @add_start_docstrings(
  888. """
  889. Electra model with a binary classification head on top as used during pretraining for identifying generated tokens.
  890. It is recommended to load the discriminator checkpoint into that model.
  891. """,
  892. ELECTRA_START_DOCSTRING,
  893. )
  894. class ElectraForPreTraining(ElectraPreTrainedModel):
  895. def __init__(self, config):
  896. super().__init__(config)
  897. self.electra = ElectraModel(config)
  898. self.discriminator_predictions = ElectraDiscriminatorPredictions(config)
  899. # Initialize weights and apply final processing
  900. self.post_init()
  901. @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  902. @replace_return_docstrings(output_type=ElectraForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
  903. def forward(
  904. self,
  905. input_ids: Optional[torch.Tensor] = None,
  906. attention_mask: Optional[torch.Tensor] = None,
  907. token_type_ids: Optional[torch.Tensor] = None,
  908. position_ids: Optional[torch.Tensor] = None,
  909. head_mask: Optional[torch.Tensor] = None,
  910. inputs_embeds: Optional[torch.Tensor] = None,
  911. labels: Optional[torch.Tensor] = None,
  912. output_attentions: Optional[bool] = None,
  913. output_hidden_states: Optional[bool] = None,
  914. return_dict: Optional[bool] = None,
  915. ) -> Union[Tuple[torch.Tensor], ElectraForPreTrainingOutput]:
  916. r"""
  917. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  918. Labels for computing the ELECTRA loss. Input should be a sequence of tokens (see `input_ids` docstring)
  919. Indices should be in `[0, 1]`:
  920. - 0 indicates the token is an original token,
  921. - 1 indicates the token was replaced.
  922. Returns:
  923. Examples:
  924. ```python
  925. >>> from transformers import ElectraForPreTraining, AutoTokenizer
  926. >>> import torch
  927. >>> discriminator = ElectraForPreTraining.from_pretrained("google/electra-base-discriminator")
  928. >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-base-discriminator")
  929. >>> sentence = "The quick brown fox jumps over the lazy dog"
  930. >>> fake_sentence = "The quick brown fox fake over the lazy dog"
  931. >>> fake_tokens = tokenizer.tokenize(fake_sentence, add_special_tokens=True)
  932. >>> fake_inputs = tokenizer.encode(fake_sentence, return_tensors="pt")
  933. >>> discriminator_outputs = discriminator(fake_inputs)
  934. >>> predictions = torch.round((torch.sign(discriminator_outputs[0]) + 1) / 2)
  935. >>> fake_tokens
  936. ['[CLS]', 'the', 'quick', 'brown', 'fox', 'fake', 'over', 'the', 'lazy', 'dog', '[SEP]']
  937. >>> predictions.squeeze().tolist()
  938. [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
  939. ```"""
  940. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  941. discriminator_hidden_states = self.electra(
  942. input_ids,
  943. attention_mask=attention_mask,
  944. token_type_ids=token_type_ids,
  945. position_ids=position_ids,
  946. head_mask=head_mask,
  947. inputs_embeds=inputs_embeds,
  948. output_attentions=output_attentions,
  949. output_hidden_states=output_hidden_states,
  950. return_dict=return_dict,
  951. )
  952. discriminator_sequence_output = discriminator_hidden_states[0]
  953. logits = self.discriminator_predictions(discriminator_sequence_output)
  954. loss = None
  955. if labels is not None:
  956. loss_fct = nn.BCEWithLogitsLoss()
  957. if attention_mask is not None:
  958. active_loss = attention_mask.view(-1, discriminator_sequence_output.shape[1]) == 1
  959. active_logits = logits.view(-1, discriminator_sequence_output.shape[1])[active_loss]
  960. active_labels = labels[active_loss]
  961. loss = loss_fct(active_logits, active_labels.float())
  962. else:
  963. loss = loss_fct(logits.view(-1, discriminator_sequence_output.shape[1]), labels.float())
  964. if not return_dict:
  965. output = (logits,) + discriminator_hidden_states[1:]
  966. return ((loss,) + output) if loss is not None else output
  967. return ElectraForPreTrainingOutput(
  968. loss=loss,
  969. logits=logits,
  970. hidden_states=discriminator_hidden_states.hidden_states,
  971. attentions=discriminator_hidden_states.attentions,
  972. )
  973. @add_start_docstrings(
  974. """
  975. Electra model with a language modeling head on top.
  976. Even though both the discriminator and generator may be loaded into this model, the generator is the only model of
  977. the two to have been trained for the masked language modeling task.
  978. """,
  979. ELECTRA_START_DOCSTRING,
  980. )
  981. class ElectraForMaskedLM(ElectraPreTrainedModel):
  982. _tied_weights_keys = ["generator_lm_head.weight"]
  983. def __init__(self, config):
  984. super().__init__(config)
  985. self.electra = ElectraModel(config)
  986. self.generator_predictions = ElectraGeneratorPredictions(config)
  987. self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
  988. # Initialize weights and apply final processing
  989. self.post_init()
  990. def get_output_embeddings(self):
  991. return self.generator_lm_head
  992. def set_output_embeddings(self, word_embeddings):
  993. self.generator_lm_head = word_embeddings
  994. @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  995. @add_code_sample_docstrings(
  996. checkpoint="google/electra-small-generator",
  997. output_type=MaskedLMOutput,
  998. config_class=_CONFIG_FOR_DOC,
  999. mask="[MASK]",
  1000. expected_output="'paris'",
  1001. expected_loss=1.22,
  1002. )
  1003. def forward(
  1004. self,
  1005. input_ids: Optional[torch.Tensor] = None,
  1006. attention_mask: Optional[torch.Tensor] = None,
  1007. token_type_ids: Optional[torch.Tensor] = None,
  1008. position_ids: Optional[torch.Tensor] = None,
  1009. head_mask: Optional[torch.Tensor] = None,
  1010. inputs_embeds: Optional[torch.Tensor] = None,
  1011. labels: Optional[torch.Tensor] = None,
  1012. output_attentions: Optional[bool] = None,
  1013. output_hidden_states: Optional[bool] = None,
  1014. return_dict: Optional[bool] = None,
  1015. ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
  1016. r"""
  1017. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1018. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  1019. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  1020. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
  1021. """
  1022. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1023. generator_hidden_states = self.electra(
  1024. input_ids,
  1025. attention_mask=attention_mask,
  1026. token_type_ids=token_type_ids,
  1027. position_ids=position_ids,
  1028. head_mask=head_mask,
  1029. inputs_embeds=inputs_embeds,
  1030. output_attentions=output_attentions,
  1031. output_hidden_states=output_hidden_states,
  1032. return_dict=return_dict,
  1033. )
  1034. generator_sequence_output = generator_hidden_states[0]
  1035. prediction_scores = self.generator_predictions(generator_sequence_output)
  1036. prediction_scores = self.generator_lm_head(prediction_scores)
  1037. loss = None
  1038. # Masked language modeling softmax layer
  1039. if labels is not None:
  1040. loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
  1041. loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  1042. if not return_dict:
  1043. output = (prediction_scores,) + generator_hidden_states[1:]
  1044. return ((loss,) + output) if loss is not None else output
  1045. return MaskedLMOutput(
  1046. loss=loss,
  1047. logits=prediction_scores,
  1048. hidden_states=generator_hidden_states.hidden_states,
  1049. attentions=generator_hidden_states.attentions,
  1050. )
  1051. @add_start_docstrings(
  1052. """
  1053. Electra model with a token classification head on top.
  1054. Both the discriminator and generator may be loaded into this model.
  1055. """,
  1056. ELECTRA_START_DOCSTRING,
  1057. )
  1058. class ElectraForTokenClassification(ElectraPreTrainedModel):
  1059. def __init__(self, config):
  1060. super().__init__(config)
  1061. self.num_labels = config.num_labels
  1062. self.electra = ElectraModel(config)
  1063. classifier_dropout = (
  1064. config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
  1065. )
  1066. self.dropout = nn.Dropout(classifier_dropout)
  1067. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1068. # Initialize weights and apply final processing
  1069. self.post_init()
  1070. @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  1071. @add_code_sample_docstrings(
  1072. checkpoint="bhadresh-savani/electra-base-discriminator-finetuned-conll03-english",
  1073. output_type=TokenClassifierOutput,
  1074. config_class=_CONFIG_FOR_DOC,
  1075. expected_output="['B-LOC', 'B-ORG', 'O', 'O', 'O', 'O', 'O', 'B-LOC', 'O', 'B-LOC', 'I-LOC']",
  1076. expected_loss=0.11,
  1077. )
  1078. def forward(
  1079. self,
  1080. input_ids: Optional[torch.Tensor] = None,
  1081. attention_mask: Optional[torch.Tensor] = None,
  1082. token_type_ids: Optional[torch.Tensor] = None,
  1083. position_ids: Optional[torch.Tensor] = None,
  1084. head_mask: Optional[torch.Tensor] = None,
  1085. inputs_embeds: Optional[torch.Tensor] = None,
  1086. labels: Optional[torch.Tensor] = None,
  1087. output_attentions: Optional[bool] = None,
  1088. output_hidden_states: Optional[bool] = None,
  1089. return_dict: Optional[bool] = None,
  1090. ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
  1091. r"""
  1092. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1093. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  1094. """
  1095. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1096. discriminator_hidden_states = self.electra(
  1097. input_ids,
  1098. attention_mask=attention_mask,
  1099. token_type_ids=token_type_ids,
  1100. position_ids=position_ids,
  1101. head_mask=head_mask,
  1102. inputs_embeds=inputs_embeds,
  1103. output_attentions=output_attentions,
  1104. output_hidden_states=output_hidden_states,
  1105. return_dict=return_dict,
  1106. )
  1107. discriminator_sequence_output = discriminator_hidden_states[0]
  1108. discriminator_sequence_output = self.dropout(discriminator_sequence_output)
  1109. logits = self.classifier(discriminator_sequence_output)
  1110. loss = None
  1111. if labels is not None:
  1112. loss_fct = CrossEntropyLoss()
  1113. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1114. if not return_dict:
  1115. output = (logits,) + discriminator_hidden_states[1:]
  1116. return ((loss,) + output) if loss is not None else output
  1117. return TokenClassifierOutput(
  1118. loss=loss,
  1119. logits=logits,
  1120. hidden_states=discriminator_hidden_states.hidden_states,
  1121. attentions=discriminator_hidden_states.attentions,
  1122. )
  1123. @add_start_docstrings(
  1124. """
  1125. ELECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
  1126. layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
  1127. """,
  1128. ELECTRA_START_DOCSTRING,
  1129. )
  1130. class ElectraForQuestionAnswering(ElectraPreTrainedModel):
  1131. config_class = ElectraConfig
  1132. base_model_prefix = "electra"
  1133. def __init__(self, config):
  1134. super().__init__(config)
  1135. self.num_labels = config.num_labels
  1136. self.electra = ElectraModel(config)
  1137. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1138. # Initialize weights and apply final processing
  1139. self.post_init()
  1140. @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  1141. @add_code_sample_docstrings(
  1142. checkpoint="bhadresh-savani/electra-base-squad2",
  1143. output_type=QuestionAnsweringModelOutput,
  1144. config_class=_CONFIG_FOR_DOC,
  1145. qa_target_start_index=11,
  1146. qa_target_end_index=12,
  1147. expected_output="'a nice puppet'",
  1148. expected_loss=2.64,
  1149. )
  1150. def forward(
  1151. self,
  1152. input_ids: Optional[torch.Tensor] = None,
  1153. attention_mask: Optional[torch.Tensor] = None,
  1154. token_type_ids: Optional[torch.Tensor] = None,
  1155. position_ids: Optional[torch.Tensor] = None,
  1156. head_mask: Optional[torch.Tensor] = None,
  1157. inputs_embeds: Optional[torch.Tensor] = None,
  1158. start_positions: Optional[torch.Tensor] = None,
  1159. end_positions: Optional[torch.Tensor] = None,
  1160. output_attentions: Optional[bool] = None,
  1161. output_hidden_states: Optional[bool] = None,
  1162. return_dict: Optional[bool] = None,
  1163. ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
  1164. r"""
  1165. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1166. Labels for position (index) of the start of the labelled span for computing the token classification loss.
  1167. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
  1168. are not taken into account for computing the loss.
  1169. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1170. Labels for position (index) of the end of the labelled span for computing the token classification loss.
  1171. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
  1172. are not taken into account for computing the loss.
  1173. """
  1174. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1175. discriminator_hidden_states = self.electra(
  1176. input_ids,
  1177. attention_mask=attention_mask,
  1178. token_type_ids=token_type_ids,
  1179. position_ids=position_ids,
  1180. head_mask=head_mask,
  1181. inputs_embeds=inputs_embeds,
  1182. output_attentions=output_attentions,
  1183. output_hidden_states=output_hidden_states,
  1184. )
  1185. sequence_output = discriminator_hidden_states[0]
  1186. logits = self.qa_outputs(sequence_output)
  1187. start_logits, end_logits = logits.split(1, dim=-1)
  1188. start_logits = start_logits.squeeze(-1).contiguous()
  1189. end_logits = end_logits.squeeze(-1).contiguous()
  1190. total_loss = None
  1191. if start_positions is not None and end_positions is not None:
  1192. # If we are on multi-GPU, split add a dimension
  1193. if len(start_positions.size()) > 1:
  1194. start_positions = start_positions.squeeze(-1)
  1195. if len(end_positions.size()) > 1:
  1196. end_positions = end_positions.squeeze(-1)
  1197. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1198. ignored_index = start_logits.size(1)
  1199. start_positions = start_positions.clamp(0, ignored_index)
  1200. end_positions = end_positions.clamp(0, ignored_index)
  1201. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1202. start_loss = loss_fct(start_logits, start_positions)
  1203. end_loss = loss_fct(end_logits, end_positions)
  1204. total_loss = (start_loss + end_loss) / 2
  1205. if not return_dict:
  1206. output = (
  1207. start_logits,
  1208. end_logits,
  1209. ) + discriminator_hidden_states[1:]
  1210. return ((total_loss,) + output) if total_loss is not None else output
  1211. return QuestionAnsweringModelOutput(
  1212. loss=total_loss,
  1213. start_logits=start_logits,
  1214. end_logits=end_logits,
  1215. hidden_states=discriminator_hidden_states.hidden_states,
  1216. attentions=discriminator_hidden_states.attentions,
  1217. )
  1218. @add_start_docstrings(
  1219. """
  1220. ELECTRA Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
  1221. softmax) e.g. for RocStories/SWAG tasks.
  1222. """,
  1223. ELECTRA_START_DOCSTRING,
  1224. )
  1225. class ElectraForMultipleChoice(ElectraPreTrainedModel):
  1226. def __init__(self, config):
  1227. super().__init__(config)
  1228. self.electra = ElectraModel(config)
  1229. self.sequence_summary = SequenceSummary(config)
  1230. self.classifier = nn.Linear(config.hidden_size, 1)
  1231. # Initialize weights and apply final processing
  1232. self.post_init()
  1233. @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
  1234. @add_code_sample_docstrings(
  1235. checkpoint=_CHECKPOINT_FOR_DOC,
  1236. output_type=MultipleChoiceModelOutput,
  1237. config_class=_CONFIG_FOR_DOC,
  1238. )
  1239. def forward(
  1240. self,
  1241. input_ids: Optional[torch.Tensor] = None,
  1242. attention_mask: Optional[torch.Tensor] = None,
  1243. token_type_ids: Optional[torch.Tensor] = None,
  1244. position_ids: Optional[torch.Tensor] = None,
  1245. head_mask: Optional[torch.Tensor] = None,
  1246. inputs_embeds: Optional[torch.Tensor] = None,
  1247. labels: Optional[torch.Tensor] = None,
  1248. output_attentions: Optional[bool] = None,
  1249. output_hidden_states: Optional[bool] = None,
  1250. return_dict: Optional[bool] = None,
  1251. ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
  1252. r"""
  1253. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1254. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  1255. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  1256. `input_ids` above)
  1257. """
  1258. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1259. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  1260. input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  1261. attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  1262. token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  1263. position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
  1264. inputs_embeds = (
  1265. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  1266. if inputs_embeds is not None
  1267. else None
  1268. )
  1269. discriminator_hidden_states = self.electra(
  1270. input_ids,
  1271. attention_mask=attention_mask,
  1272. token_type_ids=token_type_ids,
  1273. position_ids=position_ids,
  1274. head_mask=head_mask,
  1275. inputs_embeds=inputs_embeds,
  1276. output_attentions=output_attentions,
  1277. output_hidden_states=output_hidden_states,
  1278. return_dict=return_dict,
  1279. )
  1280. sequence_output = discriminator_hidden_states[0]
  1281. pooled_output = self.sequence_summary(sequence_output)
  1282. logits = self.classifier(pooled_output)
  1283. reshaped_logits = logits.view(-1, num_choices)
  1284. loss = None
  1285. if labels is not None:
  1286. loss_fct = CrossEntropyLoss()
  1287. loss = loss_fct(reshaped_logits, labels)
  1288. if not return_dict:
  1289. output = (reshaped_logits,) + discriminator_hidden_states[1:]
  1290. return ((loss,) + output) if loss is not None else output
  1291. return MultipleChoiceModelOutput(
  1292. loss=loss,
  1293. logits=reshaped_logits,
  1294. hidden_states=discriminator_hidden_states.hidden_states,
  1295. attentions=discriminator_hidden_states.attentions,
  1296. )
  1297. @add_start_docstrings(
  1298. """ELECTRA Model with a `language modeling` head on top for CLM fine-tuning.""", ELECTRA_START_DOCSTRING
  1299. )
  1300. class ElectraForCausalLM(ElectraPreTrainedModel, GenerationMixin):
  1301. _tied_weights_keys = ["generator_lm_head.weight"]
  1302. def __init__(self, config):
  1303. super().__init__(config)
  1304. if not config.is_decoder:
  1305. logger.warning("If you want to use `ElectraForCausalLM` as a standalone, add `is_decoder=True.`")
  1306. self.electra = ElectraModel(config)
  1307. self.generator_predictions = ElectraGeneratorPredictions(config)
  1308. self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
  1309. self.init_weights()
  1310. def get_output_embeddings(self):
  1311. return self.generator_lm_head
  1312. def set_output_embeddings(self, new_embeddings):
  1313. self.generator_lm_head = new_embeddings
  1314. @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  1315. @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
  1316. def forward(
  1317. self,
  1318. input_ids: Optional[torch.Tensor] = None,
  1319. attention_mask: Optional[torch.Tensor] = None,
  1320. token_type_ids: Optional[torch.Tensor] = None,
  1321. position_ids: Optional[torch.Tensor] = None,
  1322. head_mask: Optional[torch.Tensor] = None,
  1323. inputs_embeds: Optional[torch.Tensor] = None,
  1324. encoder_hidden_states: Optional[torch.Tensor] = None,
  1325. encoder_attention_mask: Optional[torch.Tensor] = None,
  1326. labels: Optional[torch.Tensor] = None,
  1327. past_key_values: Optional[List[torch.Tensor]] = None,
  1328. use_cache: Optional[bool] = None,
  1329. output_attentions: Optional[bool] = None,
  1330. output_hidden_states: Optional[bool] = None,
  1331. return_dict: Optional[bool] = None,
  1332. ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
  1333. r"""
  1334. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1335. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
  1336. the model is configured as a decoder.
  1337. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1338. Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
  1339. the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
  1340. - 1 for tokens that are **not masked**,
  1341. - 0 for tokens that are **masked**.
  1342. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1343. Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
  1344. `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
  1345. ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
  1346. past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
  1347. Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
  1348. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
  1349. don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
  1350. `decoder_input_ids` of shape `(batch_size, sequence_length)`.
  1351. use_cache (`bool`, *optional*):
  1352. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  1353. `past_key_values`).
  1354. Returns:
  1355. Example:
  1356. ```python
  1357. >>> from transformers import AutoTokenizer, ElectraForCausalLM, ElectraConfig
  1358. >>> import torch
  1359. >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-base-generator")
  1360. >>> config = ElectraConfig.from_pretrained("google/electra-base-generator")
  1361. >>> config.is_decoder = True
  1362. >>> model = ElectraForCausalLM.from_pretrained("google/electra-base-generator", config=config)
  1363. >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
  1364. >>> outputs = model(**inputs)
  1365. >>> prediction_logits = outputs.logits
  1366. ```"""
  1367. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1368. if labels is not None:
  1369. use_cache = False
  1370. outputs = self.electra(
  1371. input_ids,
  1372. attention_mask=attention_mask,
  1373. token_type_ids=token_type_ids,
  1374. position_ids=position_ids,
  1375. head_mask=head_mask,
  1376. inputs_embeds=inputs_embeds,
  1377. encoder_hidden_states=encoder_hidden_states,
  1378. encoder_attention_mask=encoder_attention_mask,
  1379. past_key_values=past_key_values,
  1380. use_cache=use_cache,
  1381. output_attentions=output_attentions,
  1382. output_hidden_states=output_hidden_states,
  1383. return_dict=return_dict,
  1384. )
  1385. sequence_output = outputs[0]
  1386. prediction_scores = self.generator_lm_head(self.generator_predictions(sequence_output))
  1387. lm_loss = None
  1388. if labels is not None:
  1389. # we are doing next-token prediction; shift prediction scores and input ids by one
  1390. shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
  1391. labels = labels[:, 1:].contiguous()
  1392. loss_fct = CrossEntropyLoss()
  1393. lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  1394. if not return_dict:
  1395. output = (prediction_scores,) + outputs[1:]
  1396. return ((lm_loss,) + output) if lm_loss is not None else output
  1397. return CausalLMOutputWithCrossAttentions(
  1398. loss=lm_loss,
  1399. logits=prediction_scores,
  1400. past_key_values=outputs.past_key_values,
  1401. hidden_states=outputs.hidden_states,
  1402. attentions=outputs.attentions,
  1403. cross_attentions=outputs.cross_attentions,
  1404. )
  1405. # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM._reorder_cache
  1406. def _reorder_cache(self, past_key_values, beam_idx):
  1407. reordered_past = ()
  1408. for layer_past in past_key_values:
  1409. reordered_past += (
  1410. tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
  1411. )
  1412. return reordered_past