modeling_rembert.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. # coding=utf-8
  2. # Copyright 2021 The HuggingFace Team The HuggingFace Inc. team. All rights reserved.
  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 RemBERT model."""
  16. import math
  17. import os
  18. from typing import Optional, Union
  19. import torch
  20. from torch import nn
  21. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  22. from ...activations import ACT2FN
  23. from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
  24. from ...generation import GenerationMixin
  25. from ...modeling_layers import GradientCheckpointingLayer
  26. from ...modeling_outputs import (
  27. BaseModelOutputWithPastAndCrossAttentions,
  28. BaseModelOutputWithPoolingAndCrossAttentions,
  29. CausalLMOutputWithCrossAttentions,
  30. MaskedLMOutput,
  31. MultipleChoiceModelOutput,
  32. QuestionAnsweringModelOutput,
  33. SequenceClassifierOutput,
  34. TokenClassifierOutput,
  35. )
  36. from ...modeling_utils import PreTrainedModel
  37. from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
  38. from ...utils import auto_docstring, logging
  39. from ...utils.deprecation import deprecate_kwarg
  40. from .configuration_rembert import RemBertConfig
  41. logger = logging.get_logger(__name__)
  42. def load_tf_weights_in_rembert(model, config, tf_checkpoint_path):
  43. """Load tf checkpoints in a pytorch model."""
  44. try:
  45. import re
  46. import numpy as np
  47. import tensorflow as tf
  48. except ImportError:
  49. logger.error(
  50. "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
  51. "https://www.tensorflow.org/install/ for installation instructions."
  52. )
  53. raise
  54. tf_path = os.path.abspath(tf_checkpoint_path)
  55. logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
  56. # Load weights from TF model
  57. init_vars = tf.train.list_variables(tf_path)
  58. names = []
  59. arrays = []
  60. for name, shape in init_vars:
  61. # Checkpoint is 12Gb, save memory by not loading useless variables
  62. # Output embedding and cls are reset at classification time
  63. if any(deny in name for deny in ("adam_v", "adam_m", "output_embedding", "cls")):
  64. # logger.info("Skipping loading of %s", name)
  65. continue
  66. logger.info(f"Loading TF weight {name} with shape {shape}")
  67. array = tf.train.load_variable(tf_path, name)
  68. names.append(name)
  69. arrays.append(array)
  70. for name, array in zip(names, arrays):
  71. # Replace prefix with right one
  72. name = name.replace("bert/", "rembert/")
  73. # The pooler is a linear layer
  74. # name = name.replace("pooler/dense", "pooler")
  75. name = name.split("/")
  76. # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
  77. # which are not required for using pretrained model
  78. if any(
  79. n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
  80. for n in name
  81. ):
  82. logger.info(f"Skipping {'/'.join(name)}")
  83. continue
  84. pointer = model
  85. for m_name in name:
  86. if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
  87. scope_names = re.split(r"_(\d+)", m_name)
  88. else:
  89. scope_names = [m_name]
  90. if scope_names[0] == "kernel" or scope_names[0] == "gamma":
  91. pointer = getattr(pointer, "weight")
  92. elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
  93. pointer = getattr(pointer, "bias")
  94. elif scope_names[0] == "output_weights":
  95. pointer = getattr(pointer, "weight")
  96. elif scope_names[0] == "squad":
  97. pointer = getattr(pointer, "classifier")
  98. else:
  99. try:
  100. pointer = getattr(pointer, scope_names[0])
  101. except AttributeError:
  102. logger.info("Skipping {}".format("/".join(name)))
  103. continue
  104. if len(scope_names) >= 2:
  105. num = int(scope_names[1])
  106. pointer = pointer[num]
  107. if m_name[-11:] == "_embeddings":
  108. pointer = getattr(pointer, "weight")
  109. elif m_name == "kernel":
  110. array = np.transpose(array)
  111. try:
  112. if pointer.shape != array.shape:
  113. raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
  114. except AssertionError as e:
  115. e.args += (pointer.shape, array.shape)
  116. raise
  117. logger.info(f"Initialize PyTorch weight {name}")
  118. pointer.data = torch.from_numpy(array)
  119. return model
  120. class RemBertEmbeddings(nn.Module):
  121. """Construct the embeddings from word, position and token_type embeddings."""
  122. def __init__(self, config):
  123. super().__init__()
  124. self.word_embeddings = nn.Embedding(
  125. config.vocab_size, config.input_embedding_size, padding_idx=config.pad_token_id
  126. )
  127. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.input_embedding_size)
  128. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.input_embedding_size)
  129. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  130. # any TensorFlow checkpoint file
  131. self.LayerNorm = nn.LayerNorm(config.input_embedding_size, eps=config.layer_norm_eps)
  132. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  133. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  134. self.register_buffer(
  135. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  136. )
  137. def forward(
  138. self,
  139. input_ids: Optional[torch.LongTensor] = None,
  140. token_type_ids: Optional[torch.LongTensor] = None,
  141. position_ids: Optional[torch.LongTensor] = None,
  142. inputs_embeds: Optional[torch.FloatTensor] = None,
  143. past_key_values_length: int = 0,
  144. ) -> torch.Tensor:
  145. if input_ids is not None:
  146. input_shape = input_ids.size()
  147. else:
  148. input_shape = inputs_embeds.size()[:-1]
  149. seq_length = input_shape[1]
  150. if position_ids is None:
  151. position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
  152. if token_type_ids is None:
  153. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  154. if inputs_embeds is None:
  155. inputs_embeds = self.word_embeddings(input_ids)
  156. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  157. embeddings = inputs_embeds + token_type_embeddings
  158. position_embeddings = self.position_embeddings(position_ids)
  159. embeddings += position_embeddings
  160. embeddings = self.LayerNorm(embeddings)
  161. embeddings = self.dropout(embeddings)
  162. return embeddings
  163. # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->RemBert
  164. class RemBertPooler(nn.Module):
  165. def __init__(self, config):
  166. super().__init__()
  167. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  168. self.activation = nn.Tanh()
  169. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  170. # We "pool" the model by simply taking the hidden state corresponding
  171. # to the first token.
  172. first_token_tensor = hidden_states[:, 0]
  173. pooled_output = self.dense(first_token_tensor)
  174. pooled_output = self.activation(pooled_output)
  175. return pooled_output
  176. class RemBertSelfAttention(nn.Module):
  177. def __init__(self, config, layer_idx=None):
  178. super().__init__()
  179. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  180. raise ValueError(
  181. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  182. f"heads ({config.num_attention_heads})"
  183. )
  184. self.num_attention_heads = config.num_attention_heads
  185. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  186. self.all_head_size = self.num_attention_heads * self.attention_head_size
  187. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  188. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  189. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  190. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  191. self.is_decoder = config.is_decoder
  192. self.layer_idx = layer_idx
  193. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  194. def forward(
  195. self,
  196. hidden_states: torch.Tensor,
  197. attention_mask: Optional[torch.FloatTensor] = None,
  198. head_mask: Optional[torch.FloatTensor] = None,
  199. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  200. past_key_values: Optional[Cache] = None,
  201. output_attentions: bool = False,
  202. cache_position: Optional[torch.Tensor] = None,
  203. ) -> tuple:
  204. batch_size, seq_length, _ = hidden_states.shape
  205. query_layer = (
  206. self.query(hidden_states)
  207. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  208. .transpose(1, 2)
  209. )
  210. is_updated = False
  211. is_cross_attention = encoder_hidden_states is not None
  212. if past_key_values is not None:
  213. if isinstance(past_key_values, EncoderDecoderCache):
  214. is_updated = past_key_values.is_updated.get(self.layer_idx)
  215. if is_cross_attention:
  216. # after the first generated id, we can subsequently re-use all key/value_layer from cache
  217. curr_past_key_value = past_key_values.cross_attention_cache
  218. else:
  219. curr_past_key_value = past_key_values.self_attention_cache
  220. else:
  221. curr_past_key_value = past_key_values
  222. current_states = encoder_hidden_states if is_cross_attention else hidden_states
  223. if is_cross_attention and past_key_values is not None and is_updated:
  224. # reuse k,v, cross_attentions
  225. key_layer = curr_past_key_value.layers[self.layer_idx].keys
  226. value_layer = curr_past_key_value.layers[self.layer_idx].values
  227. else:
  228. key_layer = (
  229. self.key(current_states)
  230. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  231. .transpose(1, 2)
  232. )
  233. value_layer = (
  234. self.value(current_states)
  235. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  236. .transpose(1, 2)
  237. )
  238. if past_key_values is not None:
  239. # save all key/value_layer to cache to be re-used for fast auto-regressive generation
  240. cache_position = cache_position if not is_cross_attention else None
  241. key_layer, value_layer = curr_past_key_value.update(
  242. key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
  243. )
  244. # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
  245. if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
  246. past_key_values.is_updated[self.layer_idx] = True
  247. # Take the dot product between "query" and "key" to get the raw attention scores.
  248. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  249. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  250. if attention_mask is not None:
  251. # Apply the attention mask is (precomputed for all layers in RemBertModel forward() function)
  252. attention_scores = attention_scores + attention_mask
  253. # Normalize the attention scores to probabilities.
  254. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  255. # This is actually dropping out entire tokens to attend to, which might
  256. # seem a bit unusual, but is taken from the original Transformer paper.
  257. attention_probs = self.dropout(attention_probs)
  258. # Mask heads if we want to
  259. if head_mask is not None:
  260. attention_probs = attention_probs * head_mask
  261. context_layer = torch.matmul(attention_probs, value_layer)
  262. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  263. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  264. context_layer = context_layer.view(*new_context_layer_shape)
  265. return context_layer, attention_probs
  266. # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->RemBert
  267. class RemBertSelfOutput(nn.Module):
  268. def __init__(self, config):
  269. super().__init__()
  270. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  271. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  272. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  273. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  274. hidden_states = self.dense(hidden_states)
  275. hidden_states = self.dropout(hidden_states)
  276. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  277. return hidden_states
  278. class RemBertAttention(nn.Module):
  279. def __init__(self, config, layer_idx=None):
  280. super().__init__()
  281. self.self = RemBertSelfAttention(config, layer_idx=layer_idx)
  282. self.output = RemBertSelfOutput(config)
  283. self.pruned_heads = set()
  284. # Copied from transformers.models.bert.modeling_bert.BertAttention.prune_heads
  285. def prune_heads(self, heads):
  286. if len(heads) == 0:
  287. return
  288. heads, index = find_pruneable_heads_and_indices(
  289. heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
  290. )
  291. # Prune linear layers
  292. self.self.query = prune_linear_layer(self.self.query, index)
  293. self.self.key = prune_linear_layer(self.self.key, index)
  294. self.self.value = prune_linear_layer(self.self.value, index)
  295. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  296. # Update hyper params and store pruned heads
  297. self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
  298. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  299. self.pruned_heads = self.pruned_heads.union(heads)
  300. # Copied from transformers.models.bert.modeling_bert.BertAttention.forward
  301. def forward(
  302. self,
  303. hidden_states: torch.Tensor,
  304. attention_mask: Optional[torch.FloatTensor] = None,
  305. head_mask: Optional[torch.FloatTensor] = None,
  306. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  307. past_key_values: Optional[Cache] = None,
  308. output_attentions: Optional[bool] = False,
  309. cache_position: Optional[torch.Tensor] = None,
  310. ) -> tuple[torch.Tensor]:
  311. self_outputs = self.self(
  312. hidden_states,
  313. attention_mask=attention_mask,
  314. head_mask=head_mask,
  315. encoder_hidden_states=encoder_hidden_states,
  316. past_key_values=past_key_values,
  317. output_attentions=output_attentions,
  318. cache_position=cache_position,
  319. )
  320. attention_output = self.output(self_outputs[0], hidden_states)
  321. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  322. return outputs
  323. # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->RemBert
  324. class RemBertIntermediate(nn.Module):
  325. def __init__(self, config):
  326. super().__init__()
  327. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  328. if isinstance(config.hidden_act, str):
  329. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  330. else:
  331. self.intermediate_act_fn = config.hidden_act
  332. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  333. hidden_states = self.dense(hidden_states)
  334. hidden_states = self.intermediate_act_fn(hidden_states)
  335. return hidden_states
  336. # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->RemBert
  337. class RemBertOutput(nn.Module):
  338. def __init__(self, config):
  339. super().__init__()
  340. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  341. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  342. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  343. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  344. hidden_states = self.dense(hidden_states)
  345. hidden_states = self.dropout(hidden_states)
  346. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  347. return hidden_states
  348. class RemBertLayer(GradientCheckpointingLayer):
  349. def __init__(self, config, layer_idx=None):
  350. super().__init__()
  351. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  352. self.seq_len_dim = 1
  353. self.attention = RemBertAttention(config, layer_idx)
  354. self.is_decoder = config.is_decoder
  355. self.add_cross_attention = config.add_cross_attention
  356. if self.add_cross_attention:
  357. if not self.is_decoder:
  358. raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
  359. self.crossattention = RemBertAttention(config, layer_idx=layer_idx)
  360. self.intermediate = RemBertIntermediate(config)
  361. self.output = RemBertOutput(config)
  362. # Copied from transformers.models.bert.modeling_bert.BertLayer.forward
  363. def forward(
  364. self,
  365. hidden_states: torch.Tensor,
  366. attention_mask: Optional[torch.FloatTensor] = None,
  367. head_mask: Optional[torch.FloatTensor] = None,
  368. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  369. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  370. past_key_values: Optional[Cache] = None,
  371. output_attentions: Optional[bool] = False,
  372. cache_position: Optional[torch.Tensor] = None,
  373. ) -> tuple[torch.Tensor]:
  374. self_attention_outputs = self.attention(
  375. hidden_states,
  376. attention_mask=attention_mask,
  377. head_mask=head_mask,
  378. output_attentions=output_attentions,
  379. past_key_values=past_key_values,
  380. cache_position=cache_position,
  381. )
  382. attention_output = self_attention_outputs[0]
  383. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  384. if self.is_decoder and encoder_hidden_states is not None:
  385. if not hasattr(self, "crossattention"):
  386. raise ValueError(
  387. f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
  388. " by setting `config.add_cross_attention=True`"
  389. )
  390. cross_attention_outputs = self.crossattention(
  391. attention_output,
  392. attention_mask=encoder_attention_mask,
  393. head_mask=head_mask,
  394. encoder_hidden_states=encoder_hidden_states,
  395. past_key_values=past_key_values,
  396. output_attentions=output_attentions,
  397. cache_position=cache_position,
  398. )
  399. attention_output = cross_attention_outputs[0]
  400. outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
  401. layer_output = apply_chunking_to_forward(
  402. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  403. )
  404. outputs = (layer_output,) + outputs
  405. return outputs
  406. # Copied from transformers.models.bert.modeling_bert.BertLayer.feed_forward_chunk
  407. def feed_forward_chunk(self, attention_output):
  408. intermediate_output = self.intermediate(attention_output)
  409. layer_output = self.output(intermediate_output, attention_output)
  410. return layer_output
  411. class RemBertEncoder(nn.Module):
  412. def __init__(self, config):
  413. super().__init__()
  414. self.config = config
  415. self.embedding_hidden_mapping_in = nn.Linear(config.input_embedding_size, config.hidden_size)
  416. self.layer = nn.ModuleList([RemBertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
  417. self.gradient_checkpointing = False
  418. def forward(
  419. self,
  420. hidden_states: torch.Tensor,
  421. attention_mask: Optional[torch.FloatTensor] = None,
  422. head_mask: Optional[torch.FloatTensor] = None,
  423. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  424. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  425. past_key_values: Optional[Cache] = None,
  426. use_cache: Optional[bool] = None,
  427. output_attentions: bool = False,
  428. output_hidden_states: bool = False,
  429. return_dict: bool = True,
  430. cache_position: Optional[torch.Tensor] = None,
  431. ) -> Union[tuple, BaseModelOutputWithPastAndCrossAttentions]:
  432. if self.gradient_checkpointing and self.training:
  433. if use_cache:
  434. logger.warning_once(
  435. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  436. )
  437. use_cache = False
  438. if use_cache and past_key_values is None:
  439. past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
  440. if use_cache and isinstance(past_key_values, tuple):
  441. logger.warning_once(
  442. "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
  443. "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
  444. "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
  445. )
  446. past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
  447. hidden_states = self.embedding_hidden_mapping_in(hidden_states)
  448. all_hidden_states = () if output_hidden_states else None
  449. all_self_attentions = () if output_attentions else None
  450. all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
  451. for i, layer_module in enumerate(self.layer):
  452. if output_hidden_states:
  453. all_hidden_states = all_hidden_states + (hidden_states,)
  454. layer_head_mask = head_mask[i] if head_mask is not None else None
  455. layer_outputs = layer_module(
  456. hidden_states,
  457. attention_mask,
  458. layer_head_mask,
  459. encoder_hidden_states,
  460. encoder_attention_mask,
  461. past_key_values,
  462. output_attentions,
  463. )
  464. hidden_states = layer_outputs[0]
  465. if output_attentions:
  466. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  467. if self.config.add_cross_attention:
  468. all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
  469. if output_hidden_states:
  470. all_hidden_states = all_hidden_states + (hidden_states,)
  471. if not return_dict:
  472. return tuple(
  473. v
  474. for v in [
  475. hidden_states,
  476. past_key_values,
  477. all_hidden_states,
  478. all_self_attentions,
  479. all_cross_attentions,
  480. ]
  481. if v is not None
  482. )
  483. return BaseModelOutputWithPastAndCrossAttentions(
  484. last_hidden_state=hidden_states,
  485. past_key_values=past_key_values,
  486. hidden_states=all_hidden_states,
  487. attentions=all_self_attentions,
  488. cross_attentions=all_cross_attentions,
  489. )
  490. # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->RemBert
  491. class RemBertPredictionHeadTransform(nn.Module):
  492. def __init__(self, config):
  493. super().__init__()
  494. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  495. if isinstance(config.hidden_act, str):
  496. self.transform_act_fn = ACT2FN[config.hidden_act]
  497. else:
  498. self.transform_act_fn = config.hidden_act
  499. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  500. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  501. hidden_states = self.dense(hidden_states)
  502. hidden_states = self.transform_act_fn(hidden_states)
  503. hidden_states = self.LayerNorm(hidden_states)
  504. return hidden_states
  505. class RemBertLMPredictionHead(nn.Module):
  506. def __init__(self, config):
  507. super().__init__()
  508. self.dense = nn.Linear(config.hidden_size, config.output_embedding_size)
  509. self.decoder = nn.Linear(config.output_embedding_size, config.vocab_size)
  510. self.activation = ACT2FN[config.hidden_act]
  511. self.LayerNorm = nn.LayerNorm(config.output_embedding_size, eps=config.layer_norm_eps)
  512. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  513. hidden_states = self.dense(hidden_states)
  514. hidden_states = self.activation(hidden_states)
  515. hidden_states = self.LayerNorm(hidden_states)
  516. hidden_states = self.decoder(hidden_states)
  517. return hidden_states
  518. # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->RemBert
  519. class RemBertOnlyMLMHead(nn.Module):
  520. def __init__(self, config):
  521. super().__init__()
  522. self.predictions = RemBertLMPredictionHead(config)
  523. def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
  524. prediction_scores = self.predictions(sequence_output)
  525. return prediction_scores
  526. @auto_docstring
  527. class RemBertPreTrainedModel(PreTrainedModel):
  528. config: RemBertConfig
  529. load_tf_weights = load_tf_weights_in_rembert
  530. base_model_prefix = "rembert"
  531. supports_gradient_checkpointing = True
  532. def _init_weights(self, module):
  533. """Initialize the weights"""
  534. if isinstance(module, nn.Linear):
  535. # Slightly different from the TF version which uses truncated_normal for initialization
  536. # cf https://github.com/pytorch/pytorch/pull/5617
  537. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  538. if module.bias is not None:
  539. module.bias.data.zero_()
  540. elif isinstance(module, nn.Embedding):
  541. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  542. if module.padding_idx is not None:
  543. module.weight.data[module.padding_idx].zero_()
  544. elif isinstance(module, nn.LayerNorm):
  545. module.bias.data.zero_()
  546. module.weight.data.fill_(1.0)
  547. @auto_docstring(
  548. custom_intro="""
  549. The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
  550. cross-attention is added between the self-attention layers, following the architecture described in [Attention is
  551. all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
  552. Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
  553. To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
  554. to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
  555. `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
  556. """
  557. )
  558. class RemBertModel(RemBertPreTrainedModel):
  559. def __init__(self, config, add_pooling_layer=True):
  560. r"""
  561. add_pooling_layer (bool, *optional*, defaults to `True`):
  562. Whether to add a pooling layer
  563. """
  564. super().__init__(config)
  565. self.config = config
  566. self.embeddings = RemBertEmbeddings(config)
  567. self.encoder = RemBertEncoder(config)
  568. self.pooler = RemBertPooler(config) if add_pooling_layer else None
  569. # Initialize weights and apply final processing
  570. self.post_init()
  571. def get_input_embeddings(self):
  572. return self.embeddings.word_embeddings
  573. def set_input_embeddings(self, value):
  574. self.embeddings.word_embeddings = value
  575. def _prune_heads(self, heads_to_prune):
  576. """
  577. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  578. class PreTrainedModel
  579. """
  580. for layer, heads in heads_to_prune.items():
  581. self.encoder.layer[layer].attention.prune_heads(heads)
  582. @auto_docstring
  583. def forward(
  584. self,
  585. input_ids: Optional[torch.LongTensor] = None,
  586. attention_mask: Optional[torch.LongTensor] = None,
  587. token_type_ids: Optional[torch.LongTensor] = None,
  588. position_ids: Optional[torch.LongTensor] = None,
  589. head_mask: Optional[torch.FloatTensor] = None,
  590. inputs_embeds: Optional[torch.FloatTensor] = None,
  591. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  592. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  593. past_key_values: Optional[Cache] = None,
  594. use_cache: Optional[bool] = None,
  595. output_attentions: Optional[bool] = None,
  596. output_hidden_states: Optional[bool] = None,
  597. return_dict: Optional[bool] = None,
  598. cache_position: Optional[torch.Tensor] = None,
  599. ) -> Union[tuple, BaseModelOutputWithPoolingAndCrossAttentions]:
  600. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  601. output_hidden_states = (
  602. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  603. )
  604. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  605. if self.config.is_decoder:
  606. use_cache = use_cache if use_cache is not None else self.config.use_cache
  607. else:
  608. use_cache = False
  609. if input_ids is not None and inputs_embeds is not None:
  610. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  611. elif input_ids is not None:
  612. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  613. input_shape = input_ids.size()
  614. elif inputs_embeds is not None:
  615. input_shape = inputs_embeds.size()[:-1]
  616. else:
  617. raise ValueError("You have to specify either input_ids or inputs_embeds")
  618. batch_size, seq_length = input_shape
  619. device = input_ids.device if input_ids is not None else inputs_embeds.device
  620. past_key_values_length = 0
  621. if past_key_values is not None:
  622. past_key_values_length = (
  623. past_key_values[0][0].shape[-2]
  624. if not isinstance(past_key_values, Cache)
  625. else past_key_values.get_seq_length()
  626. )
  627. if attention_mask is None:
  628. attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
  629. if token_type_ids is None:
  630. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
  631. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  632. # ourselves in which case we just need to make it broadcastable to all heads.
  633. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
  634. # If a 2D or 3D attention mask is provided for the cross-attention
  635. # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
  636. if self.config.is_decoder and encoder_hidden_states is not None:
  637. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
  638. encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
  639. if encoder_attention_mask is None:
  640. encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
  641. encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
  642. else:
  643. encoder_extended_attention_mask = None
  644. # Prepare head mask if needed
  645. # 1.0 in head_mask indicate we keep the head
  646. # attention_probs has shape bsz x n_heads x N x N
  647. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  648. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  649. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  650. embedding_output = self.embeddings(
  651. input_ids=input_ids,
  652. position_ids=position_ids,
  653. token_type_ids=token_type_ids,
  654. inputs_embeds=inputs_embeds,
  655. past_key_values_length=past_key_values_length,
  656. )
  657. encoder_outputs = self.encoder(
  658. embedding_output,
  659. attention_mask=extended_attention_mask,
  660. head_mask=head_mask,
  661. encoder_hidden_states=encoder_hidden_states,
  662. encoder_attention_mask=encoder_extended_attention_mask,
  663. past_key_values=past_key_values,
  664. use_cache=use_cache,
  665. output_attentions=output_attentions,
  666. output_hidden_states=output_hidden_states,
  667. return_dict=return_dict,
  668. cache_position=cache_position,
  669. )
  670. sequence_output = encoder_outputs[0]
  671. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  672. if not return_dict:
  673. return (sequence_output, pooled_output) + encoder_outputs[1:]
  674. return BaseModelOutputWithPoolingAndCrossAttentions(
  675. last_hidden_state=sequence_output,
  676. pooler_output=pooled_output,
  677. past_key_values=encoder_outputs.past_key_values,
  678. hidden_states=encoder_outputs.hidden_states,
  679. attentions=encoder_outputs.attentions,
  680. cross_attentions=encoder_outputs.cross_attentions,
  681. )
  682. @auto_docstring
  683. class RemBertForMaskedLM(RemBertPreTrainedModel):
  684. _tied_weights_keys = ["cls.predictions.decoder.weight"]
  685. def __init__(self, config):
  686. super().__init__(config)
  687. if config.is_decoder:
  688. logger.warning(
  689. "If you want to use `RemBertForMaskedLM` make sure `config.is_decoder=False` for "
  690. "bi-directional self-attention."
  691. )
  692. self.rembert = RemBertModel(config, add_pooling_layer=False)
  693. self.cls = RemBertOnlyMLMHead(config)
  694. # Initialize weights and apply final processing
  695. self.post_init()
  696. def get_output_embeddings(self):
  697. return self.cls.predictions.decoder
  698. def set_output_embeddings(self, new_embeddings):
  699. self.cls.predictions.decoder = new_embeddings
  700. @auto_docstring
  701. def forward(
  702. self,
  703. input_ids: Optional[torch.LongTensor] = None,
  704. attention_mask: Optional[torch.LongTensor] = None,
  705. token_type_ids: Optional[torch.LongTensor] = None,
  706. position_ids: Optional[torch.LongTensor] = None,
  707. head_mask: Optional[torch.FloatTensor] = None,
  708. inputs_embeds: Optional[torch.FloatTensor] = None,
  709. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  710. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  711. labels: Optional[torch.LongTensor] = None,
  712. output_attentions: Optional[bool] = None,
  713. output_hidden_states: Optional[bool] = None,
  714. return_dict: Optional[bool] = None,
  715. ) -> Union[tuple, MaskedLMOutput]:
  716. r"""
  717. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  718. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  719. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  720. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  721. """
  722. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  723. outputs = self.rembert(
  724. input_ids,
  725. attention_mask=attention_mask,
  726. token_type_ids=token_type_ids,
  727. position_ids=position_ids,
  728. head_mask=head_mask,
  729. inputs_embeds=inputs_embeds,
  730. encoder_hidden_states=encoder_hidden_states,
  731. encoder_attention_mask=encoder_attention_mask,
  732. output_attentions=output_attentions,
  733. output_hidden_states=output_hidden_states,
  734. return_dict=return_dict,
  735. )
  736. sequence_output = outputs[0]
  737. prediction_scores = self.cls(sequence_output)
  738. masked_lm_loss = None
  739. if labels is not None:
  740. loss_fct = CrossEntropyLoss() # -100 index = padding token
  741. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  742. if not return_dict:
  743. output = (prediction_scores,) + outputs[2:]
  744. return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
  745. return MaskedLMOutput(
  746. loss=masked_lm_loss,
  747. logits=prediction_scores,
  748. hidden_states=outputs.hidden_states,
  749. attentions=outputs.attentions,
  750. )
  751. def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
  752. input_shape = input_ids.shape
  753. effective_batch_size = input_shape[0]
  754. # add a dummy token
  755. assert self.config.pad_token_id is not None, "The PAD token should be defined for generation"
  756. attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
  757. dummy_token = torch.full(
  758. (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
  759. )
  760. input_ids = torch.cat([input_ids, dummy_token], dim=1)
  761. return {"input_ids": input_ids, "attention_mask": attention_mask}
  762. @classmethod
  763. def can_generate(cls) -> bool:
  764. """
  765. Legacy correction: RemBertForMaskedLM can't call `generate()` from `GenerationMixin`, even though it has a
  766. `prepare_inputs_for_generation` method.
  767. """
  768. return False
  769. @auto_docstring(
  770. custom_intro="""
  771. RemBERT Model with a `language modeling` head on top for CLM fine-tuning.
  772. """
  773. )
  774. class RemBertForCausalLM(RemBertPreTrainedModel, GenerationMixin):
  775. _tied_weights_keys = ["cls.predictions.decoder.weight"]
  776. def __init__(self, config):
  777. super().__init__(config)
  778. if not config.is_decoder:
  779. logger.warning("If you want to use `RemBertForCausalLM` as a standalone, add `is_decoder=True.`")
  780. self.rembert = RemBertModel(config, add_pooling_layer=False)
  781. self.cls = RemBertOnlyMLMHead(config)
  782. # Initialize weights and apply final processing
  783. self.post_init()
  784. def get_output_embeddings(self):
  785. return self.cls.predictions.decoder
  786. def set_output_embeddings(self, new_embeddings):
  787. self.cls.predictions.decoder = new_embeddings
  788. @auto_docstring
  789. def forward(
  790. self,
  791. input_ids: Optional[torch.LongTensor] = None,
  792. attention_mask: Optional[torch.LongTensor] = None,
  793. token_type_ids: Optional[torch.LongTensor] = None,
  794. position_ids: Optional[torch.LongTensor] = None,
  795. head_mask: Optional[torch.FloatTensor] = None,
  796. inputs_embeds: Optional[torch.FloatTensor] = None,
  797. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  798. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  799. past_key_values: Optional[Cache] = None,
  800. labels: Optional[torch.LongTensor] = None,
  801. use_cache: Optional[bool] = None,
  802. output_attentions: Optional[bool] = None,
  803. output_hidden_states: Optional[bool] = None,
  804. return_dict: Optional[bool] = None,
  805. **kwargs,
  806. ) -> Union[tuple, CausalLMOutputWithCrossAttentions]:
  807. r"""
  808. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  809. Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
  810. `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
  811. ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
  812. Example:
  813. ```python
  814. >>> from transformers import AutoTokenizer, RemBertForCausalLM, RemBertConfig
  815. >>> import torch
  816. >>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
  817. >>> config = RemBertConfig.from_pretrained("google/rembert")
  818. >>> config.is_decoder = True
  819. >>> model = RemBertForCausalLM.from_pretrained("google/rembert", config=config)
  820. >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
  821. >>> outputs = model(**inputs)
  822. >>> prediction_logits = outputs.logits
  823. ```"""
  824. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  825. outputs = self.rembert(
  826. input_ids,
  827. attention_mask=attention_mask,
  828. token_type_ids=token_type_ids,
  829. position_ids=position_ids,
  830. head_mask=head_mask,
  831. inputs_embeds=inputs_embeds,
  832. encoder_hidden_states=encoder_hidden_states,
  833. encoder_attention_mask=encoder_attention_mask,
  834. past_key_values=past_key_values,
  835. use_cache=use_cache,
  836. output_attentions=output_attentions,
  837. output_hidden_states=output_hidden_states,
  838. return_dict=return_dict,
  839. )
  840. sequence_output = outputs[0]
  841. prediction_scores = self.cls(sequence_output)
  842. lm_loss = None
  843. if labels is not None:
  844. lm_loss = self.loss_function(
  845. prediction_scores,
  846. labels,
  847. vocab_size=self.config.vocab_size,
  848. **kwargs,
  849. )
  850. if not return_dict:
  851. output = (prediction_scores,) + outputs[2:]
  852. return ((lm_loss,) + output) if lm_loss is not None else output
  853. return CausalLMOutputWithCrossAttentions(
  854. loss=lm_loss,
  855. logits=prediction_scores,
  856. past_key_values=outputs.past_key_values,
  857. hidden_states=outputs.hidden_states,
  858. attentions=outputs.attentions,
  859. cross_attentions=outputs.cross_attentions,
  860. )
  861. @auto_docstring(
  862. custom_intro="""
  863. RemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
  864. pooled output) e.g. for GLUE tasks.
  865. """
  866. )
  867. class RemBertForSequenceClassification(RemBertPreTrainedModel):
  868. def __init__(self, config):
  869. super().__init__(config)
  870. self.num_labels = config.num_labels
  871. self.rembert = RemBertModel(config)
  872. self.dropout = nn.Dropout(config.classifier_dropout_prob)
  873. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  874. # Initialize weights and apply final processing
  875. self.post_init()
  876. @auto_docstring
  877. def forward(
  878. self,
  879. input_ids: Optional[torch.FloatTensor] = None,
  880. attention_mask: Optional[torch.FloatTensor] = None,
  881. token_type_ids: Optional[torch.LongTensor] = None,
  882. position_ids: Optional[torch.FloatTensor] = None,
  883. head_mask: Optional[torch.FloatTensor] = None,
  884. inputs_embeds: Optional[torch.FloatTensor] = None,
  885. labels: Optional[torch.LongTensor] = None,
  886. output_attentions: Optional[bool] = None,
  887. output_hidden_states: Optional[bool] = None,
  888. return_dict: Optional[bool] = None,
  889. ) -> Union[tuple, SequenceClassifierOutput]:
  890. r"""
  891. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  892. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  893. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  894. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  895. """
  896. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  897. outputs = self.rembert(
  898. input_ids,
  899. attention_mask=attention_mask,
  900. token_type_ids=token_type_ids,
  901. position_ids=position_ids,
  902. head_mask=head_mask,
  903. inputs_embeds=inputs_embeds,
  904. output_attentions=output_attentions,
  905. output_hidden_states=output_hidden_states,
  906. return_dict=return_dict,
  907. )
  908. pooled_output = outputs[1]
  909. pooled_output = self.dropout(pooled_output)
  910. logits = self.classifier(pooled_output)
  911. loss = None
  912. if labels is not None:
  913. if self.config.problem_type is None:
  914. if self.num_labels == 1:
  915. self.config.problem_type = "regression"
  916. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  917. self.config.problem_type = "single_label_classification"
  918. else:
  919. self.config.problem_type = "multi_label_classification"
  920. if self.config.problem_type == "regression":
  921. loss_fct = MSELoss()
  922. if self.num_labels == 1:
  923. loss = loss_fct(logits.squeeze(), labels.squeeze())
  924. else:
  925. loss = loss_fct(logits, labels)
  926. elif self.config.problem_type == "single_label_classification":
  927. loss_fct = CrossEntropyLoss()
  928. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  929. elif self.config.problem_type == "multi_label_classification":
  930. loss_fct = BCEWithLogitsLoss()
  931. loss = loss_fct(logits, labels)
  932. if not return_dict:
  933. output = (logits,) + outputs[2:]
  934. return ((loss,) + output) if loss is not None else output
  935. return SequenceClassifierOutput(
  936. loss=loss,
  937. logits=logits,
  938. hidden_states=outputs.hidden_states,
  939. attentions=outputs.attentions,
  940. )
  941. @auto_docstring
  942. class RemBertForMultipleChoice(RemBertPreTrainedModel):
  943. def __init__(self, config):
  944. super().__init__(config)
  945. self.rembert = RemBertModel(config)
  946. self.dropout = nn.Dropout(config.classifier_dropout_prob)
  947. self.classifier = nn.Linear(config.hidden_size, 1)
  948. # Initialize weights and apply final processing
  949. self.post_init()
  950. @auto_docstring
  951. def forward(
  952. self,
  953. input_ids: Optional[torch.FloatTensor] = None,
  954. attention_mask: Optional[torch.FloatTensor] = None,
  955. token_type_ids: Optional[torch.LongTensor] = None,
  956. position_ids: Optional[torch.FloatTensor] = None,
  957. head_mask: Optional[torch.FloatTensor] = None,
  958. inputs_embeds: Optional[torch.FloatTensor] = None,
  959. labels: Optional[torch.LongTensor] = None,
  960. output_attentions: Optional[bool] = None,
  961. output_hidden_states: Optional[bool] = None,
  962. return_dict: Optional[bool] = None,
  963. ) -> Union[tuple, MultipleChoiceModelOutput]:
  964. r"""
  965. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
  966. Indices of input sequence tokens in the vocabulary.
  967. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  968. [`PreTrainedTokenizer.__call__`] for details.
  969. [What are input IDs?](../glossary#input-ids)
  970. token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  971. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  972. 1]`:
  973. - 0 corresponds to a *sentence A* token,
  974. - 1 corresponds to a *sentence B* token.
  975. [What are token type IDs?](../glossary#token-type-ids)
  976. position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  977. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  978. config.max_position_embeddings - 1]`.
  979. [What are position IDs?](../glossary#position-ids)
  980. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
  981. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  982. is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
  983. model's internal embedding lookup matrix.
  984. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  985. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  986. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  987. `input_ids` above)
  988. """
  989. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  990. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  991. input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  992. attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  993. token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  994. position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
  995. inputs_embeds = (
  996. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  997. if inputs_embeds is not None
  998. else None
  999. )
  1000. outputs = self.rembert(
  1001. input_ids,
  1002. attention_mask=attention_mask,
  1003. token_type_ids=token_type_ids,
  1004. position_ids=position_ids,
  1005. head_mask=head_mask,
  1006. inputs_embeds=inputs_embeds,
  1007. output_attentions=output_attentions,
  1008. output_hidden_states=output_hidden_states,
  1009. return_dict=return_dict,
  1010. )
  1011. pooled_output = outputs[1]
  1012. pooled_output = self.dropout(pooled_output)
  1013. logits = self.classifier(pooled_output)
  1014. reshaped_logits = logits.view(-1, num_choices)
  1015. loss = None
  1016. if labels is not None:
  1017. loss_fct = CrossEntropyLoss()
  1018. loss = loss_fct(reshaped_logits, labels)
  1019. if not return_dict:
  1020. output = (reshaped_logits,) + outputs[2:]
  1021. return ((loss,) + output) if loss is not None else output
  1022. return MultipleChoiceModelOutput(
  1023. loss=loss,
  1024. logits=reshaped_logits,
  1025. hidden_states=outputs.hidden_states,
  1026. attentions=outputs.attentions,
  1027. )
  1028. @auto_docstring
  1029. class RemBertForTokenClassification(RemBertPreTrainedModel):
  1030. def __init__(self, config):
  1031. super().__init__(config)
  1032. self.num_labels = config.num_labels
  1033. self.rembert = RemBertModel(config, add_pooling_layer=False)
  1034. self.dropout = nn.Dropout(config.classifier_dropout_prob)
  1035. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1036. # Initialize weights and apply final processing
  1037. self.post_init()
  1038. @auto_docstring
  1039. def forward(
  1040. self,
  1041. input_ids: Optional[torch.FloatTensor] = None,
  1042. attention_mask: Optional[torch.FloatTensor] = None,
  1043. token_type_ids: Optional[torch.LongTensor] = None,
  1044. position_ids: Optional[torch.FloatTensor] = None,
  1045. head_mask: Optional[torch.FloatTensor] = None,
  1046. inputs_embeds: Optional[torch.FloatTensor] = None,
  1047. labels: Optional[torch.LongTensor] = None,
  1048. output_attentions: Optional[bool] = None,
  1049. output_hidden_states: Optional[bool] = None,
  1050. return_dict: Optional[bool] = None,
  1051. ) -> Union[tuple, TokenClassifierOutput]:
  1052. r"""
  1053. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1054. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  1055. """
  1056. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1057. outputs = self.rembert(
  1058. input_ids,
  1059. attention_mask=attention_mask,
  1060. token_type_ids=token_type_ids,
  1061. position_ids=position_ids,
  1062. head_mask=head_mask,
  1063. inputs_embeds=inputs_embeds,
  1064. output_attentions=output_attentions,
  1065. output_hidden_states=output_hidden_states,
  1066. return_dict=return_dict,
  1067. )
  1068. sequence_output = outputs[0]
  1069. sequence_output = self.dropout(sequence_output)
  1070. logits = self.classifier(sequence_output)
  1071. loss = None
  1072. if labels is not None:
  1073. loss_fct = CrossEntropyLoss()
  1074. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1075. if not return_dict:
  1076. output = (logits,) + outputs[2:]
  1077. return ((loss,) + output) if loss is not None else output
  1078. return TokenClassifierOutput(
  1079. loss=loss,
  1080. logits=logits,
  1081. hidden_states=outputs.hidden_states,
  1082. attentions=outputs.attentions,
  1083. )
  1084. @auto_docstring
  1085. class RemBertForQuestionAnswering(RemBertPreTrainedModel):
  1086. def __init__(self, config):
  1087. super().__init__(config)
  1088. self.num_labels = config.num_labels
  1089. self.rembert = RemBertModel(config, add_pooling_layer=False)
  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.FloatTensor] = None,
  1097. attention_mask: Optional[torch.FloatTensor] = None,
  1098. token_type_ids: Optional[torch.LongTensor] = None,
  1099. position_ids: Optional[torch.FloatTensor] = None,
  1100. head_mask: Optional[torch.FloatTensor] = None,
  1101. inputs_embeds: Optional[torch.FloatTensor] = None,
  1102. start_positions: Optional[torch.LongTensor] = None,
  1103. end_positions: Optional[torch.LongTensor] = None,
  1104. output_attentions: Optional[bool] = None,
  1105. output_hidden_states: Optional[bool] = None,
  1106. return_dict: Optional[bool] = None,
  1107. ) -> Union[tuple, QuestionAnsweringModelOutput]:
  1108. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1109. outputs = self.rembert(
  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. return_dict=return_dict,
  1119. )
  1120. sequence_output = outputs[0]
  1121. logits = self.qa_outputs(sequence_output)
  1122. start_logits, end_logits = logits.split(1, dim=-1)
  1123. start_logits = start_logits.squeeze(-1)
  1124. end_logits = end_logits.squeeze(-1)
  1125. total_loss = None
  1126. if start_positions is not None and end_positions is not None:
  1127. # If we are on multi-GPU, split add a dimension
  1128. if len(start_positions.size()) > 1:
  1129. start_positions = start_positions.squeeze(-1)
  1130. if len(end_positions.size()) > 1:
  1131. end_positions = end_positions.squeeze(-1)
  1132. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1133. ignored_index = start_logits.size(1)
  1134. start_positions.clamp_(0, ignored_index)
  1135. end_positions.clamp_(0, ignored_index)
  1136. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1137. start_loss = loss_fct(start_logits, start_positions)
  1138. end_loss = loss_fct(end_logits, end_positions)
  1139. total_loss = (start_loss + end_loss) / 2
  1140. if not return_dict:
  1141. output = (start_logits, end_logits) + outputs[2:]
  1142. return ((total_loss,) + output) if total_loss is not None else output
  1143. return QuestionAnsweringModelOutput(
  1144. loss=total_loss,
  1145. start_logits=start_logits,
  1146. end_logits=end_logits,
  1147. hidden_states=outputs.hidden_states,
  1148. attentions=outputs.attentions,
  1149. )
  1150. __all__ = [
  1151. "RemBertForCausalLM",
  1152. "RemBertForMaskedLM",
  1153. "RemBertForMultipleChoice",
  1154. "RemBertForQuestionAnswering",
  1155. "RemBertForSequenceClassification",
  1156. "RemBertForTokenClassification",
  1157. "RemBertLayer",
  1158. "RemBertModel",
  1159. "RemBertPreTrainedModel",
  1160. "load_tf_weights_in_rembert",
  1161. ]