modeling_distilbert.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  1. # coding=utf-8
  2. # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
  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. """
  16. PyTorch DistilBERT model adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM) and in
  17. part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)
  18. """
  19. import math
  20. from typing import Optional, Union
  21. import numpy as np
  22. import torch
  23. from torch import nn
  24. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  25. from ...activations import get_activation
  26. from ...configuration_utils import PretrainedConfig
  27. from ...integrations.deepspeed import is_deepspeed_zero3_enabled
  28. from ...modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa
  29. from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
  30. from ...modeling_layers import GradientCheckpointingLayer
  31. from ...modeling_outputs import (
  32. BaseModelOutput,
  33. MaskedLMOutput,
  34. MultipleChoiceModelOutput,
  35. QuestionAnsweringModelOutput,
  36. SequenceClassifierOutput,
  37. TokenClassifierOutput,
  38. )
  39. from ...modeling_utils import PreTrainedModel
  40. from ...pytorch_utils import (
  41. apply_chunking_to_forward,
  42. find_pruneable_heads_and_indices,
  43. prune_linear_layer,
  44. )
  45. from ...utils import (
  46. auto_docstring,
  47. logging,
  48. )
  49. from .configuration_distilbert import DistilBertConfig
  50. if is_flash_attn_available():
  51. from ...modeling_flash_attention_utils import _flash_attention_forward
  52. logger = logging.get_logger(__name__)
  53. # UTILS AND BUILDING BLOCKS OF THE ARCHITECTURE #
  54. def create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
  55. if is_deepspeed_zero3_enabled():
  56. import deepspeed
  57. with deepspeed.zero.GatheredParameters(out, modifier_rank=0):
  58. if torch.distributed.get_rank() == 0:
  59. _create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
  60. else:
  61. _create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
  62. def _create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
  63. position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
  64. out.requires_grad = False
  65. out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
  66. out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
  67. out.detach_()
  68. class Embeddings(nn.Module):
  69. def __init__(self, config: PretrainedConfig):
  70. super().__init__()
  71. self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)
  72. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)
  73. self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)
  74. self.dropout = nn.Dropout(config.dropout)
  75. self.register_buffer(
  76. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  77. )
  78. def forward(self, input_ids: torch.Tensor, input_embeds: Optional[torch.Tensor] = None) -> torch.Tensor:
  79. """
  80. Parameters:
  81. input_ids (torch.Tensor):
  82. torch.tensor(bs, max_seq_length) The token ids to embed.
  83. input_embeds (*optional*, torch.Tensor):
  84. The pre-computed word embeddings. Can only be passed if the input ids are `None`.
  85. Returns: torch.tensor(bs, max_seq_length, dim) The embedded tokens (plus position embeddings, no token_type
  86. embeddings)
  87. """
  88. if input_ids is not None:
  89. input_embeds = self.word_embeddings(input_ids) # (bs, max_seq_length, dim)
  90. seq_length = input_embeds.size(1)
  91. # Setting the position-ids to the registered buffer in constructor, it helps
  92. # when tracing the model without passing position-ids, solves
  93. # issues similar to issue #5664
  94. if hasattr(self, "position_ids"):
  95. position_ids = self.position_ids[:, :seq_length]
  96. else:
  97. position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length)
  98. position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # (bs, max_seq_length)
  99. position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim)
  100. embeddings = input_embeds + position_embeddings # (bs, max_seq_length, dim)
  101. embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim)
  102. embeddings = self.dropout(embeddings) # (bs, max_seq_length, dim)
  103. return embeddings
  104. class MultiHeadSelfAttention(nn.Module):
  105. def __init__(self, config: PretrainedConfig):
  106. super().__init__()
  107. self.config = config
  108. self.n_heads = config.n_heads
  109. self.dim = config.dim
  110. self.dropout = nn.Dropout(p=config.attention_dropout)
  111. self.is_causal = False
  112. # Have an even number of multi heads that divide the dimensions
  113. if self.dim % self.n_heads != 0:
  114. # Raise value errors for even multi-head attention nodes
  115. raise ValueError(f"self.n_heads: {self.n_heads} must divide self.dim: {self.dim} evenly")
  116. self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
  117. self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
  118. self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
  119. self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
  120. self.pruned_heads: set[int] = set()
  121. self.attention_head_size = self.dim // self.n_heads
  122. def prune_heads(self, heads: list[int]):
  123. if len(heads) == 0:
  124. return
  125. heads, index = find_pruneable_heads_and_indices(
  126. heads, self.n_heads, self.attention_head_size, self.pruned_heads
  127. )
  128. # Prune linear layers
  129. self.q_lin = prune_linear_layer(self.q_lin, index)
  130. self.k_lin = prune_linear_layer(self.k_lin, index)
  131. self.v_lin = prune_linear_layer(self.v_lin, index)
  132. self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
  133. # Update hyper params
  134. self.n_heads = self.n_heads - len(heads)
  135. self.dim = self.attention_head_size * self.n_heads
  136. self.pruned_heads = self.pruned_heads.union(heads)
  137. def forward(
  138. self,
  139. query: torch.Tensor,
  140. key: torch.Tensor,
  141. value: torch.Tensor,
  142. mask: torch.Tensor,
  143. head_mask: Optional[torch.Tensor] = None,
  144. output_attentions: bool = False,
  145. ) -> tuple[torch.Tensor, ...]:
  146. """
  147. Parameters:
  148. query: torch.tensor(bs, seq_length, dim)
  149. key: torch.tensor(bs, seq_length, dim)
  150. value: torch.tensor(bs, seq_length, dim)
  151. mask: torch.tensor(bs, seq_length)
  152. Returns:
  153. weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
  154. seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
  155. """
  156. bs, q_length, dim = query.size()
  157. k_length = key.size(1)
  158. # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
  159. # assert key.size() == value.size()
  160. dim_per_head = self.dim // self.n_heads
  161. mask_reshp = (bs, 1, 1, k_length)
  162. def shape(x: torch.Tensor) -> torch.Tensor:
  163. """separate heads"""
  164. return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)
  165. def unshape(x: torch.Tensor) -> torch.Tensor:
  166. """group heads"""
  167. return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)
  168. q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
  169. k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
  170. v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
  171. q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)
  172. scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, q_length, k_length)
  173. mask = (mask == 0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length)
  174. scores = scores.masked_fill(
  175. mask, torch.tensor(torch.finfo(scores.dtype).min)
  176. ) # (bs, n_heads, q_length, k_length)
  177. weights = nn.functional.softmax(scores, dim=-1) # (bs, n_heads, q_length, k_length)
  178. weights = self.dropout(weights) # (bs, n_heads, q_length, k_length)
  179. # Mask heads if we want to
  180. if head_mask is not None:
  181. weights = weights * head_mask
  182. context = torch.matmul(weights, v) # (bs, n_heads, q_length, dim_per_head)
  183. context = unshape(context) # (bs, q_length, dim)
  184. context = self.out_lin(context) # (bs, q_length, dim)
  185. if output_attentions:
  186. return (context, weights)
  187. else:
  188. return (context,)
  189. class DistilBertFlashAttention2(MultiHeadSelfAttention):
  190. """
  191. DistilBert flash attention module. This module inherits from `MultiHeadSelfAttention` as the weights of the module
  192. stays untouched. The only required change would be on the forward pass where it needs to correctly call the public
  193. API of flash attention and deal with padding tokens in case the input contains any of them.
  194. """
  195. def __init__(self, *args, **kwargs):
  196. super().__init__(*args, **kwargs)
  197. # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
  198. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
  199. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
  200. self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
  201. def forward(
  202. self,
  203. query: torch.Tensor,
  204. key: torch.Tensor,
  205. value: torch.Tensor,
  206. mask: torch.Tensor,
  207. head_mask: Optional[torch.Tensor] = None,
  208. output_attentions: bool = False,
  209. ) -> tuple[torch.Tensor, ...]:
  210. """
  211. Parameters:
  212. query: torch.tensor(bs, seq_length, dim)
  213. key: torch.tensor(bs, seq_length, dim)
  214. value: torch.tensor(bs, seq_length, dim)
  215. mask: torch.tensor(bs, seq_length)
  216. Returns:
  217. weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
  218. seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
  219. """
  220. batch_size, q_length, dim = query.size()
  221. dim_per_head = self.dim // self.n_heads
  222. def reshape(x: torch.Tensor) -> torch.Tensor:
  223. """separate heads"""
  224. return x.view(batch_size, -1, self.n_heads, dim_per_head)
  225. # Flash attention requires the input to have the shape
  226. # batch_size x seq_length x head_dim x hidden_dim
  227. query_states = reshape(self.q_lin(query))
  228. key_states = reshape(self.k_lin(key))
  229. value_states = reshape(self.v_lin(value))
  230. attn_dropout = self.config.attention_dropout if self.training else 0.0
  231. # In PEFT, usually we cast the layer norms in float32 for training stability reasons
  232. # therefore the input hidden states gets silently casted in float32. Hence, we need
  233. # cast them back in the correct dtype just to be sure everything works as expected.
  234. # This might slowdown training & inference so it is recommended to not cast the LayerNorms
  235. # in fp32. (LlamaRMSNorm handles it correctly)
  236. device_type = query_states.device.type if query_states.device.type != "mps" else "cpu"
  237. if query_states.dtype == torch.float32:
  238. if torch.is_autocast_enabled():
  239. target_dtype = (
  240. torch.get_autocast_dtype(device_type)
  241. if hasattr(torch, "get_autocast_dtype")
  242. else torch.get_autocast_gpu_dtype()
  243. )
  244. # Handle the case where the model is quantized
  245. elif hasattr(self.config, "_pre_quantization_dtype"):
  246. target_dtype = self.config._pre_quantization_dtype
  247. else:
  248. target_dtype = self.q_lin.weight.dtype
  249. logger.warning_once(
  250. f"The input hidden states seems to be silently casted in float32, this might be related to"
  251. f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
  252. f" {target_dtype}."
  253. )
  254. query_states = query_states.to(target_dtype)
  255. key_states = key_states.to(target_dtype)
  256. value_states = value_states.to(target_dtype)
  257. attn_weights = _flash_attention_forward(
  258. query_states,
  259. key_states,
  260. value_states,
  261. mask,
  262. q_length,
  263. dropout=attn_dropout,
  264. use_top_left_mask=self._flash_attn_uses_top_left_mask,
  265. is_causal=self.is_causal,
  266. )
  267. attn_weights_reshaped = attn_weights.reshape(batch_size, q_length, self.n_heads * dim_per_head)
  268. attn_output = self.out_lin(attn_weights_reshaped)
  269. if output_attentions:
  270. return (attn_output, attn_weights)
  271. else:
  272. return (attn_output,)
  273. class DistilBertSdpaAttention(MultiHeadSelfAttention):
  274. def __init__(self, config: PretrainedConfig):
  275. super().__init__(config=config)
  276. self.dropout_prob = config.attention_dropout
  277. def forward(
  278. self,
  279. query: torch.Tensor,
  280. key: torch.Tensor,
  281. value: torch.Tensor,
  282. mask: torch.Tensor,
  283. head_mask: Optional[torch.Tensor] = None,
  284. output_attentions: bool = False,
  285. ) -> tuple[torch.Tensor, ...]:
  286. """
  287. Parameters:
  288. query: torch.tensor(bs, seq_length, dim)
  289. key: torch.tensor(bs, seq_length, dim)
  290. value: torch.tensor(bs, seq_length, dim)
  291. mask: torch.tensor(bs, seq_length)
  292. Returns:
  293. weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
  294. seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
  295. """
  296. if output_attentions or head_mask is not None:
  297. logger.warning_once(
  298. "DistilBertSdpaAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support"
  299. " `output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but specifying"
  300. " the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be"
  301. ' removed using the argument `attn_implementation="eager"` when loading the model.'
  302. )
  303. return super().forward(
  304. query,
  305. key,
  306. value,
  307. mask,
  308. head_mask,
  309. output_attentions,
  310. )
  311. batch_size, _, _ = query.size()
  312. dim_per_head = self.dim // self.n_heads
  313. def shape(x: torch.Tensor) -> torch.Tensor:
  314. """separate heads"""
  315. return x.view(batch_size, -1, self.n_heads, dim_per_head).transpose(1, 2)
  316. def unshape(x: torch.Tensor) -> torch.Tensor:
  317. """group heads"""
  318. return x.transpose(1, 2).contiguous().view(batch_size, -1, self.n_heads * dim_per_head)
  319. q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
  320. k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
  321. v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
  322. attn_output = torch.nn.functional.scaled_dot_product_attention(
  323. q,
  324. k,
  325. v,
  326. attn_mask=mask,
  327. dropout_p=self.dropout_prob if self.training else 0.0,
  328. is_causal=False,
  329. )
  330. attn_output = unshape(attn_output)
  331. attn_output = self.out_lin(attn_output)
  332. return (attn_output,)
  333. class FFN(nn.Module):
  334. def __init__(self, config: PretrainedConfig):
  335. super().__init__()
  336. self.dropout = nn.Dropout(p=config.dropout)
  337. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  338. self.seq_len_dim = 1
  339. self.lin1 = nn.Linear(in_features=config.dim, out_features=config.hidden_dim)
  340. self.lin2 = nn.Linear(in_features=config.hidden_dim, out_features=config.dim)
  341. self.activation = get_activation(config.activation)
  342. def forward(self, input: torch.Tensor) -> torch.Tensor:
  343. return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
  344. def ff_chunk(self, input: torch.Tensor) -> torch.Tensor:
  345. x = self.lin1(input)
  346. x = self.activation(x)
  347. x = self.lin2(x)
  348. x = self.dropout(x)
  349. return x
  350. DISTILBERT_ATTENTION_CLASSES = {
  351. "eager": MultiHeadSelfAttention,
  352. "flash_attention_2": DistilBertFlashAttention2,
  353. "sdpa": DistilBertSdpaAttention,
  354. }
  355. class TransformerBlock(GradientCheckpointingLayer):
  356. def __init__(self, config: PretrainedConfig):
  357. super().__init__()
  358. # Have an even number of Configure multi-heads
  359. if config.dim % config.n_heads != 0:
  360. raise ValueError(f"config.n_heads {config.n_heads} must divide config.dim {config.dim} evenly")
  361. self.attention = DISTILBERT_ATTENTION_CLASSES[config._attn_implementation](config)
  362. self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
  363. self.ffn = FFN(config)
  364. self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
  365. def forward(
  366. self,
  367. x: torch.Tensor,
  368. attn_mask: Optional[torch.Tensor] = None,
  369. head_mask: Optional[torch.Tensor] = None,
  370. output_attentions: bool = False,
  371. ) -> tuple[torch.Tensor, ...]:
  372. """
  373. Parameters:
  374. x: torch.tensor(bs, seq_length, dim)
  375. attn_mask: torch.tensor(bs, seq_length)
  376. Returns:
  377. sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
  378. torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization.
  379. """
  380. # Self-Attention
  381. sa_output = self.attention(
  382. query=x,
  383. key=x,
  384. value=x,
  385. mask=attn_mask,
  386. head_mask=head_mask,
  387. output_attentions=output_attentions,
  388. )
  389. if output_attentions:
  390. sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
  391. else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
  392. if type(sa_output) is not tuple:
  393. raise TypeError(f"sa_output must be a tuple but it is {type(sa_output)} type")
  394. sa_output = sa_output[0]
  395. sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
  396. # Feed Forward Network
  397. ffn_output = self.ffn(sa_output) # (bs, seq_length, dim)
  398. ffn_output: torch.Tensor = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
  399. output = (ffn_output,)
  400. if output_attentions:
  401. output = (sa_weights,) + output
  402. return output
  403. class Transformer(nn.Module):
  404. def __init__(self, config: PretrainedConfig):
  405. super().__init__()
  406. self.n_layers = config.n_layers
  407. self.layer = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
  408. self.gradient_checkpointing = False
  409. def forward(
  410. self,
  411. x: torch.Tensor,
  412. attn_mask: Optional[torch.Tensor] = None,
  413. head_mask: Optional[torch.Tensor] = None,
  414. output_attentions: bool = False,
  415. output_hidden_states: bool = False,
  416. return_dict: Optional[bool] = None,
  417. ) -> Union[BaseModelOutput, tuple[torch.Tensor, ...]]: # docstyle-ignore
  418. """
  419. Parameters:
  420. x: torch.tensor(bs, seq_length, dim) Input sequence embedded.
  421. attn_mask: torch.tensor(bs, seq_length) Attention mask on the sequence.
  422. Returns:
  423. hidden_state: torch.tensor(bs, seq_length, dim) Sequence of hidden states in the last (top)
  424. layer all_hidden_states: tuple[torch.tensor(bs, seq_length, dim)]
  425. Tuple of length n_layers with the hidden states from each layer.
  426. Optional: only if output_hidden_states=True
  427. all_attentions: tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]
  428. Tuple of length n_layers with the attention weights from each layer
  429. Optional: only if output_attentions=True
  430. """
  431. all_hidden_states = () if output_hidden_states else None
  432. all_attentions = () if output_attentions else None
  433. hidden_state = x
  434. for i, layer_module in enumerate(self.layer):
  435. if output_hidden_states:
  436. all_hidden_states = all_hidden_states + (hidden_state,)
  437. layer_outputs = layer_module(
  438. hidden_state,
  439. attn_mask,
  440. head_mask[i],
  441. output_attentions,
  442. )
  443. hidden_state = layer_outputs[-1]
  444. if output_attentions:
  445. if len(layer_outputs) != 2:
  446. raise ValueError(f"The length of the layer_outputs should be 2, but it is {len(layer_outputs)}")
  447. attentions = layer_outputs[0]
  448. all_attentions = all_attentions + (attentions,)
  449. else:
  450. if len(layer_outputs) != 1:
  451. raise ValueError(f"The length of the layer_outputs should be 1, but it is {len(layer_outputs)}")
  452. # Add last layer
  453. if output_hidden_states:
  454. all_hidden_states = all_hidden_states + (hidden_state,)
  455. if not return_dict:
  456. return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)
  457. return BaseModelOutput(
  458. last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions
  459. )
  460. # INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
  461. @auto_docstring
  462. class DistilBertPreTrainedModel(PreTrainedModel):
  463. config: DistilBertConfig
  464. load_tf_weights = None
  465. base_model_prefix = "distilbert"
  466. supports_gradient_checkpointing = True
  467. _supports_flash_attn = True
  468. _supports_sdpa = True
  469. def _init_weights(self, module: nn.Module):
  470. """Initialize the weights."""
  471. if isinstance(module, nn.Linear):
  472. # Slightly different from the TF version which uses truncated_normal for initialization
  473. # cf https://github.com/pytorch/pytorch/pull/5617
  474. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  475. if module.bias is not None:
  476. module.bias.data.zero_()
  477. elif isinstance(module, nn.Embedding):
  478. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  479. if module.padding_idx is not None:
  480. module.weight.data[module.padding_idx].zero_()
  481. elif isinstance(module, nn.LayerNorm):
  482. module.bias.data.zero_()
  483. module.weight.data.fill_(1.0)
  484. elif isinstance(module, Embeddings) and self.config.sinusoidal_pos_embds:
  485. create_sinusoidal_embeddings(
  486. self.config.max_position_embeddings, self.config.dim, module.position_embeddings.weight
  487. )
  488. @auto_docstring
  489. class DistilBertModel(DistilBertPreTrainedModel):
  490. def __init__(self, config: PretrainedConfig):
  491. super().__init__(config)
  492. self.embeddings = Embeddings(config) # Embeddings
  493. self.transformer = Transformer(config) # Encoder
  494. # Initialize weights and apply final processing
  495. self.post_init()
  496. def get_position_embeddings(self) -> nn.Embedding:
  497. """
  498. Returns the position embeddings
  499. """
  500. return self.embeddings.position_embeddings
  501. def resize_position_embeddings(self, new_num_position_embeddings: int):
  502. """
  503. Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
  504. Arguments:
  505. new_num_position_embeddings (`int`):
  506. The number of new position embedding matrix. If position embeddings are learned, increasing the size
  507. will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
  508. end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
  509. size will add correct vectors at the end following the position encoding algorithm, whereas reducing
  510. the size will remove vectors from the end.
  511. """
  512. num_position_embeds_diff = new_num_position_embeddings - self.config.max_position_embeddings
  513. # no resizing needs to be done if the length stays the same
  514. if num_position_embeds_diff == 0:
  515. return
  516. logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
  517. self.config.max_position_embeddings = new_num_position_embeddings
  518. old_position_embeddings_weight = self.embeddings.position_embeddings.weight.clone()
  519. self.embeddings.position_embeddings = nn.Embedding(self.config.max_position_embeddings, self.config.dim)
  520. if self.config.sinusoidal_pos_embds:
  521. create_sinusoidal_embeddings(
  522. n_pos=self.config.max_position_embeddings, dim=self.config.dim, out=self.position_embeddings.weight
  523. )
  524. else:
  525. with torch.no_grad():
  526. if num_position_embeds_diff > 0:
  527. self.embeddings.position_embeddings.weight[:-num_position_embeds_diff] = nn.Parameter(
  528. old_position_embeddings_weight
  529. )
  530. else:
  531. self.embeddings.position_embeddings.weight = nn.Parameter(
  532. old_position_embeddings_weight[:num_position_embeds_diff]
  533. )
  534. # move position_embeddings to correct device
  535. self.embeddings.position_embeddings.to(self.device)
  536. def get_input_embeddings(self) -> nn.Embedding:
  537. return self.embeddings.word_embeddings
  538. def set_input_embeddings(self, new_embeddings: nn.Embedding):
  539. self.embeddings.word_embeddings = new_embeddings
  540. def _prune_heads(self, heads_to_prune: dict[int, list[list[int]]]):
  541. """
  542. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  543. class PreTrainedModel
  544. """
  545. for layer, heads in heads_to_prune.items():
  546. self.transformer.layer[layer].attention.prune_heads(heads)
  547. @auto_docstring
  548. def forward(
  549. self,
  550. input_ids: Optional[torch.Tensor] = None,
  551. attention_mask: Optional[torch.Tensor] = None,
  552. head_mask: Optional[torch.Tensor] = None,
  553. inputs_embeds: Optional[torch.Tensor] = None,
  554. output_attentions: Optional[bool] = None,
  555. output_hidden_states: Optional[bool] = None,
  556. return_dict: Optional[bool] = None,
  557. ) -> Union[BaseModelOutput, tuple[torch.Tensor, ...]]:
  558. r"""
  559. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
  560. Indices of input sequence tokens in the vocabulary.
  561. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  562. [`PreTrainedTokenizer.__call__`] for details.
  563. [What are input IDs?](../glossary#input-ids)
  564. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, hidden_size)`, *optional*):
  565. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  566. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  567. model's internal embedding lookup matrix.
  568. """
  569. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  570. output_hidden_states = (
  571. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  572. )
  573. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  574. if input_ids is not None and inputs_embeds is not None:
  575. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  576. elif input_ids is not None:
  577. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  578. input_shape = input_ids.size()
  579. elif inputs_embeds is not None:
  580. input_shape = inputs_embeds.size()[:-1]
  581. else:
  582. raise ValueError("You have to specify either input_ids or inputs_embeds")
  583. device = input_ids.device if input_ids is not None else inputs_embeds.device
  584. head_mask_is_none = head_mask is None
  585. # Prepare head mask if needed
  586. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  587. embeddings = self.embeddings(input_ids, inputs_embeds) # (bs, seq_length, dim)
  588. if self.config._attn_implementation == "flash_attention_2":
  589. attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
  590. else:
  591. if attention_mask is None:
  592. attention_mask = torch.ones(input_shape, device=device) # (bs, seq_length)
  593. if self.config._attn_implementation == "sdpa" and head_mask_is_none and not output_attentions:
  594. attention_mask = _prepare_4d_attention_mask_for_sdpa(
  595. attention_mask, embeddings.dtype, tgt_len=input_shape[1]
  596. )
  597. return self.transformer(
  598. x=embeddings,
  599. attn_mask=attention_mask,
  600. head_mask=head_mask,
  601. output_attentions=output_attentions,
  602. output_hidden_states=output_hidden_states,
  603. return_dict=return_dict,
  604. )
  605. @auto_docstring(
  606. custom_intro="""
  607. DistilBert Model with a `masked language modeling` head on top.
  608. """
  609. )
  610. class DistilBertForMaskedLM(DistilBertPreTrainedModel):
  611. _tied_weights_keys = ["vocab_projector.weight"]
  612. def __init__(self, config: PretrainedConfig):
  613. super().__init__(config)
  614. self.activation = get_activation(config.activation)
  615. self.distilbert = DistilBertModel(config)
  616. self.vocab_transform = nn.Linear(config.dim, config.dim)
  617. self.vocab_layer_norm = nn.LayerNorm(config.dim, eps=1e-12)
  618. self.vocab_projector = nn.Linear(config.dim, config.vocab_size)
  619. # Initialize weights and apply final processing
  620. self.post_init()
  621. self.mlm_loss_fct = nn.CrossEntropyLoss()
  622. def get_position_embeddings(self) -> nn.Embedding:
  623. """
  624. Returns the position embeddings
  625. """
  626. return self.distilbert.get_position_embeddings()
  627. def resize_position_embeddings(self, new_num_position_embeddings: int):
  628. """
  629. Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
  630. Arguments:
  631. new_num_position_embeddings (`int`):
  632. The number of new position embedding matrix. If position embeddings are learned, increasing the size
  633. will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
  634. end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
  635. size will add correct vectors at the end following the position encoding algorithm, whereas reducing
  636. the size will remove vectors from the end.
  637. """
  638. self.distilbert.resize_position_embeddings(new_num_position_embeddings)
  639. def get_output_embeddings(self) -> nn.Module:
  640. return self.vocab_projector
  641. def set_output_embeddings(self, new_embeddings: nn.Module):
  642. self.vocab_projector = new_embeddings
  643. @auto_docstring
  644. def forward(
  645. self,
  646. input_ids: Optional[torch.Tensor] = None,
  647. attention_mask: Optional[torch.Tensor] = None,
  648. head_mask: Optional[torch.Tensor] = None,
  649. inputs_embeds: Optional[torch.Tensor] = None,
  650. labels: Optional[torch.LongTensor] = None,
  651. output_attentions: Optional[bool] = None,
  652. output_hidden_states: Optional[bool] = None,
  653. return_dict: Optional[bool] = None,
  654. ) -> Union[MaskedLMOutput, tuple[torch.Tensor, ...]]:
  655. r"""
  656. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
  657. Indices of input sequence tokens in the vocabulary.
  658. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  659. [`PreTrainedTokenizer.__call__`] for details.
  660. [What are input IDs?](../glossary#input-ids)
  661. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, hidden_size)`, *optional*):
  662. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  663. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  664. model's internal embedding lookup matrix.
  665. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  666. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  667. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  668. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  669. """
  670. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  671. dlbrt_output = self.distilbert(
  672. input_ids=input_ids,
  673. attention_mask=attention_mask,
  674. head_mask=head_mask,
  675. inputs_embeds=inputs_embeds,
  676. output_attentions=output_attentions,
  677. output_hidden_states=output_hidden_states,
  678. return_dict=return_dict,
  679. )
  680. hidden_states = dlbrt_output[0] # (bs, seq_length, dim)
  681. prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)
  682. prediction_logits = self.activation(prediction_logits) # (bs, seq_length, dim)
  683. prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
  684. prediction_logits = self.vocab_projector(prediction_logits) # (bs, seq_length, vocab_size)
  685. mlm_loss = None
  686. if labels is not None:
  687. mlm_loss = self.mlm_loss_fct(prediction_logits.view(-1, prediction_logits.size(-1)), labels.view(-1))
  688. if not return_dict:
  689. output = (prediction_logits,) + dlbrt_output[1:]
  690. return ((mlm_loss,) + output) if mlm_loss is not None else output
  691. return MaskedLMOutput(
  692. loss=mlm_loss,
  693. logits=prediction_logits,
  694. hidden_states=dlbrt_output.hidden_states,
  695. attentions=dlbrt_output.attentions,
  696. )
  697. @auto_docstring(
  698. custom_intro="""
  699. DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
  700. pooled output) e.g. for GLUE tasks.
  701. """
  702. )
  703. class DistilBertForSequenceClassification(DistilBertPreTrainedModel):
  704. def __init__(self, config: PretrainedConfig):
  705. super().__init__(config)
  706. self.num_labels = config.num_labels
  707. self.config = config
  708. self.distilbert = DistilBertModel(config)
  709. self.pre_classifier = nn.Linear(config.dim, config.dim)
  710. self.classifier = nn.Linear(config.dim, config.num_labels)
  711. self.dropout = nn.Dropout(config.seq_classif_dropout)
  712. # Initialize weights and apply final processing
  713. self.post_init()
  714. def get_position_embeddings(self) -> nn.Embedding:
  715. """
  716. Returns the position embeddings
  717. """
  718. return self.distilbert.get_position_embeddings()
  719. def resize_position_embeddings(self, new_num_position_embeddings: int):
  720. """
  721. Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
  722. Arguments:
  723. new_num_position_embeddings (`int`):
  724. The number of new position embedding matrix. If position embeddings are learned, increasing the size
  725. will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
  726. end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
  727. size will add correct vectors at the end following the position encoding algorithm, whereas reducing
  728. the size will remove vectors from the end.
  729. """
  730. self.distilbert.resize_position_embeddings(new_num_position_embeddings)
  731. @auto_docstring
  732. def forward(
  733. self,
  734. input_ids: Optional[torch.Tensor] = None,
  735. attention_mask: Optional[torch.Tensor] = None,
  736. head_mask: Optional[torch.Tensor] = None,
  737. inputs_embeds: Optional[torch.Tensor] = None,
  738. labels: Optional[torch.LongTensor] = None,
  739. output_attentions: Optional[bool] = None,
  740. output_hidden_states: Optional[bool] = None,
  741. return_dict: Optional[bool] = None,
  742. ) -> Union[SequenceClassifierOutput, tuple[torch.Tensor, ...]]:
  743. r"""
  744. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  745. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  746. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  747. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  748. """
  749. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  750. distilbert_output = self.distilbert(
  751. input_ids=input_ids,
  752. attention_mask=attention_mask,
  753. head_mask=head_mask,
  754. inputs_embeds=inputs_embeds,
  755. output_attentions=output_attentions,
  756. output_hidden_states=output_hidden_states,
  757. return_dict=return_dict,
  758. )
  759. hidden_state = distilbert_output[0] # (bs, seq_len, dim)
  760. pooled_output = hidden_state[:, 0] # (bs, dim)
  761. pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
  762. pooled_output = nn.ReLU()(pooled_output) # (bs, dim)
  763. pooled_output = self.dropout(pooled_output) # (bs, dim)
  764. logits = self.classifier(pooled_output) # (bs, num_labels)
  765. loss = None
  766. if labels is not None:
  767. if self.config.problem_type is None:
  768. if self.num_labels == 1:
  769. self.config.problem_type = "regression"
  770. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  771. self.config.problem_type = "single_label_classification"
  772. else:
  773. self.config.problem_type = "multi_label_classification"
  774. if self.config.problem_type == "regression":
  775. loss_fct = MSELoss()
  776. if self.num_labels == 1:
  777. loss = loss_fct(logits.squeeze(), labels.squeeze())
  778. else:
  779. loss = loss_fct(logits, labels)
  780. elif self.config.problem_type == "single_label_classification":
  781. loss_fct = CrossEntropyLoss()
  782. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  783. elif self.config.problem_type == "multi_label_classification":
  784. loss_fct = BCEWithLogitsLoss()
  785. loss = loss_fct(logits, labels)
  786. if not return_dict:
  787. output = (logits,) + distilbert_output[1:]
  788. return ((loss,) + output) if loss is not None else output
  789. return SequenceClassifierOutput(
  790. loss=loss,
  791. logits=logits,
  792. hidden_states=distilbert_output.hidden_states,
  793. attentions=distilbert_output.attentions,
  794. )
  795. @auto_docstring
  796. class DistilBertForQuestionAnswering(DistilBertPreTrainedModel):
  797. def __init__(self, config: PretrainedConfig):
  798. super().__init__(config)
  799. self.distilbert = DistilBertModel(config)
  800. self.qa_outputs = nn.Linear(config.dim, config.num_labels)
  801. if config.num_labels != 2:
  802. raise ValueError(f"config.num_labels should be 2, but it is {config.num_labels}")
  803. self.dropout = nn.Dropout(config.qa_dropout)
  804. # Initialize weights and apply final processing
  805. self.post_init()
  806. def get_position_embeddings(self) -> nn.Embedding:
  807. """
  808. Returns the position embeddings
  809. """
  810. return self.distilbert.get_position_embeddings()
  811. def resize_position_embeddings(self, new_num_position_embeddings: int):
  812. """
  813. Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
  814. Arguments:
  815. new_num_position_embeddings (`int`):
  816. The number of new position embedding matrix. If position embeddings are learned, increasing the size
  817. will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
  818. end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
  819. size will add correct vectors at the end following the position encoding algorithm, whereas reducing
  820. the size will remove vectors from the end.
  821. """
  822. self.distilbert.resize_position_embeddings(new_num_position_embeddings)
  823. @auto_docstring
  824. def forward(
  825. self,
  826. input_ids: Optional[torch.Tensor] = None,
  827. attention_mask: Optional[torch.Tensor] = None,
  828. head_mask: Optional[torch.Tensor] = None,
  829. inputs_embeds: Optional[torch.Tensor] = None,
  830. start_positions: Optional[torch.Tensor] = None,
  831. end_positions: Optional[torch.Tensor] = None,
  832. output_attentions: Optional[bool] = None,
  833. output_hidden_states: Optional[bool] = None,
  834. return_dict: Optional[bool] = None,
  835. ) -> Union[QuestionAnsweringModelOutput, tuple[torch.Tensor, ...]]:
  836. r"""
  837. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
  838. Indices of input sequence tokens in the vocabulary.
  839. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  840. [`PreTrainedTokenizer.__call__`] for details.
  841. [What are input IDs?](../glossary#input-ids)
  842. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, hidden_size)`, *optional*):
  843. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  844. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  845. model's internal embedding lookup matrix.
  846. """
  847. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  848. distilbert_output = self.distilbert(
  849. input_ids=input_ids,
  850. attention_mask=attention_mask,
  851. head_mask=head_mask,
  852. inputs_embeds=inputs_embeds,
  853. output_attentions=output_attentions,
  854. output_hidden_states=output_hidden_states,
  855. return_dict=return_dict,
  856. )
  857. hidden_states = distilbert_output[0] # (bs, max_query_len, dim)
  858. hidden_states = self.dropout(hidden_states) # (bs, max_query_len, dim)
  859. logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)
  860. start_logits, end_logits = logits.split(1, dim=-1)
  861. start_logits = start_logits.squeeze(-1).contiguous() # (bs, max_query_len)
  862. end_logits = end_logits.squeeze(-1).contiguous() # (bs, max_query_len)
  863. total_loss = None
  864. if start_positions is not None and end_positions is not None:
  865. # If we are on multi-GPU, split add a dimension
  866. if len(start_positions.size()) > 1:
  867. start_positions = start_positions.squeeze(-1)
  868. if len(end_positions.size()) > 1:
  869. end_positions = end_positions.squeeze(-1)
  870. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  871. ignored_index = start_logits.size(1)
  872. start_positions = start_positions.clamp(0, ignored_index)
  873. end_positions = end_positions.clamp(0, ignored_index)
  874. loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
  875. start_loss = loss_fct(start_logits, start_positions)
  876. end_loss = loss_fct(end_logits, end_positions)
  877. total_loss = (start_loss + end_loss) / 2
  878. if not return_dict:
  879. output = (start_logits, end_logits) + distilbert_output[1:]
  880. return ((total_loss,) + output) if total_loss is not None else output
  881. return QuestionAnsweringModelOutput(
  882. loss=total_loss,
  883. start_logits=start_logits,
  884. end_logits=end_logits,
  885. hidden_states=distilbert_output.hidden_states,
  886. attentions=distilbert_output.attentions,
  887. )
  888. @auto_docstring
  889. class DistilBertForTokenClassification(DistilBertPreTrainedModel):
  890. def __init__(self, config: PretrainedConfig):
  891. super().__init__(config)
  892. self.num_labels = config.num_labels
  893. self.distilbert = DistilBertModel(config)
  894. self.dropout = nn.Dropout(config.dropout)
  895. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  896. # Initialize weights and apply final processing
  897. self.post_init()
  898. def get_position_embeddings(self) -> nn.Embedding:
  899. """
  900. Returns the position embeddings
  901. """
  902. return self.distilbert.get_position_embeddings()
  903. def resize_position_embeddings(self, new_num_position_embeddings: int):
  904. """
  905. Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
  906. Arguments:
  907. new_num_position_embeddings (`int`):
  908. The number of new position embedding matrix. If position embeddings are learned, increasing the size
  909. will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
  910. end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
  911. size will add correct vectors at the end following the position encoding algorithm, whereas reducing
  912. the size will remove vectors from the end.
  913. """
  914. self.distilbert.resize_position_embeddings(new_num_position_embeddings)
  915. @auto_docstring
  916. def forward(
  917. self,
  918. input_ids: Optional[torch.Tensor] = None,
  919. attention_mask: Optional[torch.Tensor] = None,
  920. head_mask: Optional[torch.Tensor] = None,
  921. inputs_embeds: Optional[torch.Tensor] = None,
  922. labels: Optional[torch.LongTensor] = None,
  923. output_attentions: Optional[bool] = None,
  924. output_hidden_states: Optional[bool] = None,
  925. return_dict: Optional[bool] = None,
  926. ) -> Union[TokenClassifierOutput, tuple[torch.Tensor, ...]]:
  927. r"""
  928. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  929. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  930. """
  931. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  932. outputs = self.distilbert(
  933. input_ids,
  934. attention_mask=attention_mask,
  935. head_mask=head_mask,
  936. inputs_embeds=inputs_embeds,
  937. output_attentions=output_attentions,
  938. output_hidden_states=output_hidden_states,
  939. return_dict=return_dict,
  940. )
  941. sequence_output = outputs[0]
  942. sequence_output = self.dropout(sequence_output)
  943. logits = self.classifier(sequence_output)
  944. loss = None
  945. if labels is not None:
  946. loss_fct = CrossEntropyLoss()
  947. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  948. if not return_dict:
  949. output = (logits,) + outputs[1:]
  950. return ((loss,) + output) if loss is not None else output
  951. return TokenClassifierOutput(
  952. loss=loss,
  953. logits=logits,
  954. hidden_states=outputs.hidden_states,
  955. attentions=outputs.attentions,
  956. )
  957. @auto_docstring
  958. class DistilBertForMultipleChoice(DistilBertPreTrainedModel):
  959. def __init__(self, config: PretrainedConfig):
  960. super().__init__(config)
  961. self.distilbert = DistilBertModel(config)
  962. self.pre_classifier = nn.Linear(config.dim, config.dim)
  963. self.classifier = nn.Linear(config.dim, 1)
  964. self.dropout = nn.Dropout(config.seq_classif_dropout)
  965. # Initialize weights and apply final processing
  966. self.post_init()
  967. def get_position_embeddings(self) -> nn.Embedding:
  968. """
  969. Returns the position embeddings
  970. """
  971. return self.distilbert.get_position_embeddings()
  972. def resize_position_embeddings(self, new_num_position_embeddings: int):
  973. """
  974. Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
  975. Arguments:
  976. new_num_position_embeddings (`int`)
  977. The number of new position embeddings. If position embeddings are learned, increasing the size will add
  978. newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
  979. position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
  980. add correct vectors at the end following the position encoding algorithm, whereas reducing the size
  981. will remove vectors from the end.
  982. """
  983. self.distilbert.resize_position_embeddings(new_num_position_embeddings)
  984. @auto_docstring
  985. def forward(
  986. self,
  987. input_ids: Optional[torch.Tensor] = None,
  988. attention_mask: Optional[torch.Tensor] = None,
  989. head_mask: Optional[torch.Tensor] = None,
  990. inputs_embeds: Optional[torch.Tensor] = None,
  991. labels: Optional[torch.LongTensor] = None,
  992. output_attentions: Optional[bool] = None,
  993. output_hidden_states: Optional[bool] = None,
  994. return_dict: Optional[bool] = None,
  995. ) -> Union[MultipleChoiceModelOutput, tuple[torch.Tensor, ...]]:
  996. r"""
  997. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
  998. Indices of input sequence tokens in the vocabulary.
  999. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1000. [`PreTrainedTokenizer.__call__`] for details.
  1001. [What are input IDs?](../glossary#input-ids)
  1002. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
  1003. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  1004. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  1005. model's internal embedding lookup matrix.
  1006. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1007. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  1008. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  1009. `input_ids` above)
  1010. Examples:
  1011. ```python
  1012. >>> from transformers import AutoTokenizer, DistilBertForMultipleChoice
  1013. >>> import torch
  1014. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
  1015. >>> model = DistilBertForMultipleChoice.from_pretrained("distilbert-base-cased")
  1016. >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
  1017. >>> choice0 = "It is eaten with a fork and a knife."
  1018. >>> choice1 = "It is eaten while held in the hand."
  1019. >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
  1020. >>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors="pt", padding=True)
  1021. >>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels) # batch size is 1
  1022. >>> # the linear classifier still needs to be trained
  1023. >>> loss = outputs.loss
  1024. >>> logits = outputs.logits
  1025. ```"""
  1026. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1027. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  1028. input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  1029. attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  1030. inputs_embeds = (
  1031. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  1032. if inputs_embeds is not None
  1033. else None
  1034. )
  1035. outputs = self.distilbert(
  1036. input_ids,
  1037. attention_mask=attention_mask,
  1038. head_mask=head_mask,
  1039. inputs_embeds=inputs_embeds,
  1040. output_attentions=output_attentions,
  1041. output_hidden_states=output_hidden_states,
  1042. return_dict=return_dict,
  1043. )
  1044. hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
  1045. pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
  1046. pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
  1047. pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
  1048. pooled_output = self.dropout(pooled_output) # (bs * num_choices, dim)
  1049. logits = self.classifier(pooled_output) # (bs * num_choices, 1)
  1050. reshaped_logits = logits.view(-1, num_choices) # (bs, num_choices)
  1051. loss = None
  1052. if labels is not None:
  1053. loss_fct = CrossEntropyLoss()
  1054. loss = loss_fct(reshaped_logits, labels)
  1055. if not return_dict:
  1056. output = (reshaped_logits,) + outputs[1:]
  1057. return ((loss,) + output) if loss is not None else output
  1058. return MultipleChoiceModelOutput(
  1059. loss=loss,
  1060. logits=reshaped_logits,
  1061. hidden_states=outputs.hidden_states,
  1062. attentions=outputs.attentions,
  1063. )
  1064. __all__ = [
  1065. "DistilBertForMaskedLM",
  1066. "DistilBertForMultipleChoice",
  1067. "DistilBertForQuestionAnswering",
  1068. "DistilBertForSequenceClassification",
  1069. "DistilBertForTokenClassification",
  1070. "DistilBertModel",
  1071. "DistilBertPreTrainedModel",
  1072. ]