modeling_camembert.py 71 KB

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