modeling_electra.py 68 KB

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