CSS-LM
924 строки · 37.5 Кб
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""" PyTorch DistilBERT model
16adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM)
17and in part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)
18"""
19
20
21import copy22import logging23import math24import warnings25
26import numpy as np27import torch28import torch.nn as nn29from torch.nn import CrossEntropyLoss30
31from .activations import gelu32from .configuration_distilbert import DistilBertConfig33from .file_utils import (34add_code_sample_docstrings,35add_start_docstrings,36add_start_docstrings_to_callable,37replace_return_docstrings,38)
39from .modeling_outputs import (40BaseModelOutput,41MaskedLMOutput,42MultipleChoiceModelOutput,43QuestionAnsweringModelOutput,44SequenceClassifierOutput,45TokenClassifierOutput,46)
47from .modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer48
49
50logger = logging.getLogger(__name__)51
52_CONFIG_FOR_DOC = "DistilBertConfig"53_TOKENIZER_FOR_DOC = "DistilBertTokenizer"54
55DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [56"distilbert-base-uncased",57"distilbert-base-uncased-distilled-squad",58"distilbert-base-cased",59"distilbert-base-cased-distilled-squad",60"distilbert-base-german-cased",61"distilbert-base-multilingual-cased",62"distilbert-base-uncased-finetuned-sst-2-english",63# See all DistilBERT models at https://huggingface.co/models?filter=distilbert64]
65
66
67# UTILS AND BUILDING BLOCKS OF THE ARCHITECTURE #
68
69
70def create_sinusoidal_embeddings(n_pos, dim, out):71position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])72out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))73out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))74out.detach_()75out.requires_grad = False76
77
78class Embeddings(nn.Module):79def __init__(self, config):80super().__init__()81self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)82self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)83if config.sinusoidal_pos_embds:84create_sinusoidal_embeddings(85n_pos=config.max_position_embeddings, dim=config.dim, out=self.position_embeddings.weight86)87
88self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)89self.dropout = nn.Dropout(config.dropout)90
91def forward(self, input_ids):92"""93Parameters
94----------
95input_ids: torch.tensor(bs, max_seq_length)
96The token ids to embed.
97
98Outputs
99-------
100embeddings: torch.tensor(bs, max_seq_length, dim)
101The embedded tokens (plus position embeddings, no token_type embeddings)
102"""
103seq_length = input_ids.size(1)104position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length)105position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # (bs, max_seq_length)106
107word_embeddings = self.word_embeddings(input_ids) # (bs, max_seq_length, dim)108position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim)109
110embeddings = word_embeddings + position_embeddings # (bs, max_seq_length, dim)111embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim)112embeddings = self.dropout(embeddings) # (bs, max_seq_length, dim)113return embeddings114
115
116class MultiHeadSelfAttention(nn.Module):117def __init__(self, config):118super().__init__()119
120self.n_heads = config.n_heads121self.dim = config.dim122self.dropout = nn.Dropout(p=config.attention_dropout)123
124assert self.dim % self.n_heads == 0125
126self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim)127self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim)128self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim)129self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim)130
131self.pruned_heads = set()132
133def prune_heads(self, heads):134attention_head_size = self.dim // self.n_heads135if len(heads) == 0:136return137heads, index = find_pruneable_heads_and_indices(heads, self.n_heads, attention_head_size, self.pruned_heads)138# Prune linear layers139self.q_lin = prune_linear_layer(self.q_lin, index)140self.k_lin = prune_linear_layer(self.k_lin, index)141self.v_lin = prune_linear_layer(self.v_lin, index)142self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)143# Update hyper params144self.n_heads = self.n_heads - len(heads)145self.dim = attention_head_size * self.n_heads146self.pruned_heads = self.pruned_heads.union(heads)147
148def forward(self, query, key, value, mask, head_mask=None, output_attentions=False):149"""150Parameters
151----------
152query: torch.tensor(bs, seq_length, dim)
153key: torch.tensor(bs, seq_length, dim)
154value: torch.tensor(bs, seq_length, dim)
155mask: torch.tensor(bs, seq_length)
156
157Outputs
158-------
159weights: torch.tensor(bs, n_heads, seq_length, seq_length)
160Attention weights
161context: torch.tensor(bs, seq_length, dim)
162Contextualized layer. Optional: only if `output_attentions=True`
163"""
164bs, q_length, dim = query.size()165k_length = key.size(1)166# assert dim == self.dim, 'Dimensions do not match: %s input vs %s configured' % (dim, self.dim)167# assert key.size() == value.size()168
169dim_per_head = self.dim // self.n_heads170
171mask_reshp = (bs, 1, 1, k_length)172
173def shape(x):174""" separate heads """175return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)176
177def unshape(x):178""" group heads """179return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)180
181q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)182k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)183v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)184
185q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)186scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, q_length, k_length)187mask = (mask == 0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length)188scores.masked_fill_(mask, -float("inf")) # (bs, n_heads, q_length, k_length)189
190weights = nn.Softmax(dim=-1)(scores) # (bs, n_heads, q_length, k_length)191weights = self.dropout(weights) # (bs, n_heads, q_length, k_length)192
193# Mask heads if we want to194if head_mask is not None:195weights = weights * head_mask196
197context = torch.matmul(weights, v) # (bs, n_heads, q_length, dim_per_head)198context = unshape(context) # (bs, q_length, dim)199context = self.out_lin(context) # (bs, q_length, dim)200
201if output_attentions:202return (context, weights)203else:204return (context,)205
206
207class FFN(nn.Module):208def __init__(self, config):209super().__init__()210self.dropout = nn.Dropout(p=config.dropout)211self.lin1 = nn.Linear(in_features=config.dim, out_features=config.hidden_dim)212self.lin2 = nn.Linear(in_features=config.hidden_dim, out_features=config.dim)213assert config.activation in ["relu", "gelu"], "activation ({}) must be in ['relu', 'gelu']".format(214config.activation215)216self.activation = gelu if config.activation == "gelu" else nn.ReLU()217
218def forward(self, input):219x = self.lin1(input)220x = self.activation(x)221x = self.lin2(x)222x = self.dropout(x)223return x224
225
226class TransformerBlock(nn.Module):227def __init__(self, config):228super().__init__()229
230assert config.dim % config.n_heads == 0231
232self.attention = MultiHeadSelfAttention(config)233self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)234
235self.ffn = FFN(config)236self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)237
238def forward(self, x, attn_mask=None, head_mask=None, output_attentions=False):239"""240Parameters
241----------
242x: torch.tensor(bs, seq_length, dim)
243attn_mask: torch.tensor(bs, seq_length)
244
245Outputs
246-------
247sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length)
248The attention weights
249ffn_output: torch.tensor(bs, seq_length, dim)
250The output of the transformer block contextualization.
251"""
252# Self-Attention253sa_output = self.attention(254query=x, key=x, value=x, mask=attn_mask, head_mask=head_mask, output_attentions=output_attentions,255)256if output_attentions:257sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)258else: # To handle these `output_attention` or `output_hidden_states` cases returning tuples259assert type(sa_output) == tuple260sa_output = sa_output[0]261sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)262
263# Feed Forward Network264ffn_output = self.ffn(sa_output) # (bs, seq_length, dim)265ffn_output = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)266
267output = (ffn_output,)268if output_attentions:269output = (sa_weights,) + output270return output271
272
273class Transformer(nn.Module):274def __init__(self, config):275super().__init__()276self.n_layers = config.n_layers277
278layer = TransformerBlock(config)279self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.n_layers)])280
281def forward(282self, x, attn_mask=None, head_mask=None, output_attentions=False, output_hidden_states=False, return_dict=None283):284"""285Parameters
286----------
287x: torch.tensor(bs, seq_length, dim)
288Input sequence embedded.
289attn_mask: torch.tensor(bs, seq_length)
290Attention mask on the sequence.
291
292Outputs
293-------
294hidden_state: torch.tensor(bs, seq_length, dim)
295Sequence of hiddens states in the last (top) layer
296all_hidden_states: Tuple[torch.tensor(bs, seq_length, dim)]
297Tuple of length n_layers with the hidden states from each layer.
298Optional: only if output_hidden_states=True
299all_attentions: Tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]
300Tuple of length n_layers with the attention weights from each layer
301Optional: only if output_attentions=True
302"""
303all_hidden_states = () if output_hidden_states else None304all_attentions = () if output_attentions else None305
306hidden_state = x307for i, layer_module in enumerate(self.layer):308if output_hidden_states:309all_hidden_states = all_hidden_states + (hidden_state,)310
311layer_outputs = layer_module(312x=hidden_state, attn_mask=attn_mask, head_mask=head_mask[i], output_attentions=output_attentions313)314hidden_state = layer_outputs[-1]315
316if output_attentions:317assert len(layer_outputs) == 2318attentions = layer_outputs[0]319all_attentions = all_attentions + (attentions,)320else:321assert len(layer_outputs) == 1322
323# Add last layer324if output_hidden_states:325all_hidden_states = all_hidden_states + (hidden_state,)326
327if not return_dict:328return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)329return BaseModelOutput(330last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions331)332
333
334# INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
335class DistilBertPreTrainedModel(PreTrainedModel):336""" An abstract class to handle weights initialization and337a simple interface for downloading and loading pretrained models.
338"""
339
340config_class = DistilBertConfig341load_tf_weights = None342base_model_prefix = "distilbert"343
344def _init_weights(self, module):345""" Initialize the weights.346"""
347if isinstance(module, nn.Embedding):348if module.weight.requires_grad:349module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)350if isinstance(module, nn.Linear):351module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)352elif isinstance(module, nn.LayerNorm):353module.bias.data.zero_()354module.weight.data.fill_(1.0)355if isinstance(module, nn.Linear) and module.bias is not None:356module.bias.data.zero_()357
358
359DISTILBERT_START_DOCSTRING = r"""360
361This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ sub-class.
362Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
363usage and behavior.
364
365Parameters:
366config (:class:`~transformers.DistilBertConfig`): Model configuration class with all the parameters of the model.
367Initializing with a config file does not load the weights associated with the model, only the configuration.
368Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
369"""
370
371DISTILBERT_INPUTS_DOCSTRING = r"""372Args:
373input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
374Indices of input sequence tokens in the vocabulary.
375
376Indices can be obtained using :class:`transformers.DistilBertTokenizer`.
377See :func:`transformers.PreTrainedTokenizer.encode` and
378:func:`transformers.PreTrainedTokenizer.__call__` for details.
379
380`What are input IDs? <../glossary.html#input-ids>`__
381attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
382Mask to avoid performing attention on padding token indices.
383Mask values selected in ``[0, 1]``:
384``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
385
386`What are attention masks? <../glossary.html#attention-mask>`__
387head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):
388Mask to nullify selected heads of the self-attention modules.
389Mask values selected in ``[0, 1]``:
390:obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.
391inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
392Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
393This is useful if you want more control over how to convert `input_ids` indices into associated vectors
394than the model's internal embedding lookup matrix.
395output_attentions (:obj:`bool`, `optional`, defaults to :obj:`None`):
396If set to ``True``, the attentions tensors of all attention layers are returned. See ``attentions`` under returned tensors for more detail.
397output_hidden_states (:obj:`bool`, `optional`, defaults to :obj:`None`):
398If set to ``True``, the hidden states of all layers are returned. See ``hidden_states`` under returned tensors for more detail.
399return_dict (:obj:`bool`, `optional`, defaults to :obj:`None`):
400If set to ``True``, the model will return a :class:`~transformers.file_utils.ModelOutput` instead of a
401plain tuple.
402"""
403
404
405@add_start_docstrings(406"The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.",407DISTILBERT_START_DOCSTRING,408)
409class DistilBertModel(DistilBertPreTrainedModel):410def __init__(self, config):411super().__init__(config)412
413self.embeddings = Embeddings(config) # Embeddings414self.transformer = Transformer(config) # Encoder415
416self.init_weights()417
418def get_input_embeddings(self):419return self.embeddings.word_embeddings420
421def set_input_embeddings(self, new_embeddings):422self.embeddings.word_embeddings = new_embeddings423
424def _prune_heads(self, heads_to_prune):425""" Prunes heads of the model.426heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
427See base class PreTrainedModel
428"""
429for layer, heads in heads_to_prune.items():430self.transformer.layer[layer].attention.prune_heads(heads)431
432@add_start_docstrings_to_callable(DISTILBERT_INPUTS_DOCSTRING)433@add_code_sample_docstrings(434tokenizer_class=_TOKENIZER_FOR_DOC,435checkpoint="distilbert-base-uncased",436output_type=BaseModelOutput,437config_class=_CONFIG_FOR_DOC,438)439@add_code_sample_docstrings(tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint="distilbert-base-uncased")440def forward(441self,442input_ids=None,443attention_mask=None,444head_mask=None,445inputs_embeds=None,446output_attentions=None,447output_hidden_states=None,448return_dict=None,449):450output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions451output_hidden_states = (452output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states453)454return_dict = return_dict if return_dict is not None else self.config.use_return_dict455
456if input_ids is not None and inputs_embeds is not None:457raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")458elif input_ids is not None:459input_shape = input_ids.size()460elif inputs_embeds is not None:461input_shape = inputs_embeds.size()[:-1]462else:463raise ValueError("You have to specify either input_ids or inputs_embeds")464
465device = input_ids.device if input_ids is not None else inputs_embeds.device466
467if attention_mask is None:468attention_mask = torch.ones(input_shape, device=device) # (bs, seq_length)469
470# Prepare head mask if needed471head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)472
473if inputs_embeds is None:474inputs_embeds = self.embeddings(input_ids) # (bs, seq_length, dim)475return self.transformer(476x=inputs_embeds,477attn_mask=attention_mask,478head_mask=head_mask,479output_attentions=output_attentions,480output_hidden_states=output_hidden_states,481return_dict=return_dict,482)483
484
485@add_start_docstrings(486"""DistilBert Model with a `masked language modeling` head on top. """, DISTILBERT_START_DOCSTRING,487)
488class DistilBertForMaskedLM(DistilBertPreTrainedModel):489def __init__(self, config):490super().__init__(config)491
492self.distilbert = DistilBertModel(config)493self.vocab_transform = nn.Linear(config.dim, config.dim)494self.vocab_layer_norm = nn.LayerNorm(config.dim, eps=1e-12)495self.vocab_projector = nn.Linear(config.dim, config.vocab_size)496
497self.init_weights()498
499self.mlm_loss_fct = nn.CrossEntropyLoss()500
501def get_output_embeddings(self):502return self.vocab_projector503
504@add_start_docstrings_to_callable(DISTILBERT_INPUTS_DOCSTRING)505@add_code_sample_docstrings(506tokenizer_class=_TOKENIZER_FOR_DOC,507checkpoint="distilbert-base-uncased",508output_type=MaskedLMOutput,509config_class=_CONFIG_FOR_DOC,510)511def forward(512self,513input_ids=None,514attention_mask=None,515head_mask=None,516inputs_embeds=None,517labels=None,518output_attentions=None,519output_hidden_states=None,520return_dict=None,521**kwargs522):523r"""524labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
525Labels for computing the masked language modeling loss.
526Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
527Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
528in ``[0, ..., config.vocab_size]``
529kwargs (:obj:`Dict[str, any]`, optional, defaults to `{}`):
530Used to hide legacy arguments that have been deprecated.
531"""
532if "masked_lm_labels" in kwargs:533warnings.warn(534"The `masked_lm_labels` argument is deprecated and will be removed in a future version, use `labels` instead.",535FutureWarning,536)537labels = kwargs.pop("masked_lm_labels")538assert kwargs == {}, f"Unexpected keyword arguments: {list(kwargs.keys())}."539return_dict = return_dict if return_dict is not None else self.config.use_return_dict540
541dlbrt_output = self.distilbert(542input_ids=input_ids,543attention_mask=attention_mask,544head_mask=head_mask,545inputs_embeds=inputs_embeds,546output_attentions=output_attentions,547output_hidden_states=output_hidden_states,548return_dict=return_dict,549)550hidden_states = dlbrt_output[0] # (bs, seq_length, dim)551prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)552prediction_logits = gelu(prediction_logits) # (bs, seq_length, dim)553prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)554prediction_logits = self.vocab_projector(prediction_logits) # (bs, seq_length, vocab_size)555
556mlm_loss = None557if labels is not None:558mlm_loss = self.mlm_loss_fct(prediction_logits.view(-1, prediction_logits.size(-1)), labels.view(-1))559
560if not return_dict:561output = (prediction_logits,) + dlbrt_output[1:]562return ((mlm_loss,) + output) if mlm_loss is not None else output563
564return MaskedLMOutput(565loss=mlm_loss,566logits=prediction_logits,567hidden_states=dlbrt_output.hidden_states,568attentions=dlbrt_output.attentions,569)570
571
572@add_start_docstrings(573"""DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of574the pooled output) e.g. for GLUE tasks. """,575DISTILBERT_START_DOCSTRING,576)
577class DistilBertForSequenceClassification(DistilBertPreTrainedModel):578def __init__(self, config):579super().__init__(config)580self.num_labels = config.num_labels581
582self.distilbert = DistilBertModel(config)583self.pre_classifier = nn.Linear(config.dim, config.dim)584self.classifier = nn.Linear(config.dim, config.num_labels)585self.dropout = nn.Dropout(config.seq_classif_dropout)586
587self.init_weights()588
589@add_start_docstrings_to_callable(DISTILBERT_INPUTS_DOCSTRING)590@add_code_sample_docstrings(591tokenizer_class=_TOKENIZER_FOR_DOC,592checkpoint="distilbert-base-uncased",593output_type=SequenceClassifierOutput,594config_class=_CONFIG_FOR_DOC,595)596def forward(597self,598input_ids=None,599attention_mask=None,600head_mask=None,601inputs_embeds=None,602labels=None,603output_attentions=None,604output_hidden_states=None,605return_dict=None,606):607r"""608labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
609Labels for computing the sequence classification/regression loss.
610Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
611If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
612If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
613"""
614return_dict = return_dict if return_dict is not None else self.config.use_return_dict615
616distilbert_output = self.distilbert(617input_ids=input_ids,618attention_mask=attention_mask,619head_mask=head_mask,620inputs_embeds=inputs_embeds,621output_attentions=output_attentions,622output_hidden_states=output_hidden_states,623return_dict=return_dict,624)625hidden_state = distilbert_output[0] # (bs, seq_len, dim)626pooled_output = hidden_state[:, 0] # (bs, dim)627pooled_output = self.pre_classifier(pooled_output) # (bs, dim)628pooled_output = nn.ReLU()(pooled_output) # (bs, dim)629pooled_output = self.dropout(pooled_output) # (bs, dim)630logits = self.classifier(pooled_output) # (bs, dim)631
632loss = None633if labels is not None:634if self.num_labels == 1:635loss_fct = nn.MSELoss()636loss = loss_fct(logits.view(-1), labels.view(-1))637else:638loss_fct = nn.CrossEntropyLoss()639loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))640
641if not return_dict:642output = (logits,) + distilbert_output[1:]643return ((loss,) + output) if loss is not None else output644
645return SequenceClassifierOutput(646loss=loss,647logits=logits,648hidden_states=distilbert_output.hidden_states,649attentions=distilbert_output.attentions,650)651
652
653@add_start_docstrings(654"""DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of655the hidden-states output to compute `span start logits` and `span end logits`). """,656DISTILBERT_START_DOCSTRING,657)
658class DistilBertForQuestionAnswering(DistilBertPreTrainedModel):659def __init__(self, config):660super().__init__(config)661
662self.distilbert = DistilBertModel(config)663self.qa_outputs = nn.Linear(config.dim, config.num_labels)664assert config.num_labels == 2665self.dropout = nn.Dropout(config.qa_dropout)666
667self.init_weights()668
669@add_start_docstrings_to_callable(DISTILBERT_INPUTS_DOCSTRING)670@add_code_sample_docstrings(671tokenizer_class=_TOKENIZER_FOR_DOC,672checkpoint="distilbert-base-uncased",673output_type=QuestionAnsweringModelOutput,674config_class=_CONFIG_FOR_DOC,675)676def forward(677self,678input_ids=None,679attention_mask=None,680head_mask=None,681inputs_embeds=None,682start_positions=None,683end_positions=None,684output_attentions=None,685output_hidden_states=None,686return_dict=None,687):688r"""689start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
690Labels for position (index) of the start of the labelled span for computing the token classification loss.
691Positions are clamped to the length of the sequence (`sequence_length`).
692Position outside of the sequence are not taken into account for computing the loss.
693end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
694Labels for position (index) of the end of the labelled span for computing the token classification loss.
695Positions are clamped to the length of the sequence (`sequence_length`).
696Position outside of the sequence are not taken into account for computing the loss.
697"""
698return_dict = return_dict if return_dict is not None else self.config.use_return_dict699
700distilbert_output = self.distilbert(701input_ids=input_ids,702attention_mask=attention_mask,703head_mask=head_mask,704inputs_embeds=inputs_embeds,705output_attentions=output_attentions,706output_hidden_states=output_hidden_states,707return_dict=return_dict,708)709hidden_states = distilbert_output[0] # (bs, max_query_len, dim)710
711hidden_states = self.dropout(hidden_states) # (bs, max_query_len, dim)712logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)713start_logits, end_logits = logits.split(1, dim=-1)714start_logits = start_logits.squeeze(-1) # (bs, max_query_len)715end_logits = end_logits.squeeze(-1) # (bs, max_query_len)716
717total_loss = None718if start_positions is not None and end_positions is not None:719# If we are on multi-GPU, split add a dimension720if len(start_positions.size()) > 1:721start_positions = start_positions.squeeze(-1)722if len(end_positions.size()) > 1:723end_positions = end_positions.squeeze(-1)724# sometimes the start/end positions are outside our model inputs, we ignore these terms725ignored_index = start_logits.size(1)726start_positions.clamp_(0, ignored_index)727end_positions.clamp_(0, ignored_index)728
729loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)730start_loss = loss_fct(start_logits, start_positions)731end_loss = loss_fct(end_logits, end_positions)732total_loss = (start_loss + end_loss) / 2733
734if not return_dict:735output = (start_logits, end_logits) + distilbert_output[1:]736return ((total_loss,) + output) if total_loss is not None else output737
738return QuestionAnsweringModelOutput(739loss=total_loss,740start_logits=start_logits,741end_logits=end_logits,742hidden_states=distilbert_output.hidden_states,743attentions=distilbert_output.attentions,744)745
746
747@add_start_docstrings(748"""DistilBert Model with a token classification head on top (a linear layer on top of749the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """,750DISTILBERT_START_DOCSTRING,751)
752class DistilBertForTokenClassification(DistilBertPreTrainedModel):753def __init__(self, config):754super().__init__(config)755self.num_labels = config.num_labels756
757self.distilbert = DistilBertModel(config)758self.dropout = nn.Dropout(config.dropout)759self.classifier = nn.Linear(config.hidden_size, config.num_labels)760
761self.init_weights()762
763@add_start_docstrings_to_callable(DISTILBERT_INPUTS_DOCSTRING)764@add_code_sample_docstrings(765tokenizer_class=_TOKENIZER_FOR_DOC,766checkpoint="distilbert-base-uncased",767output_type=TokenClassifierOutput,768config_class=_CONFIG_FOR_DOC,769)770def forward(771self,772input_ids=None,773attention_mask=None,774head_mask=None,775inputs_embeds=None,776labels=None,777output_attentions=None,778output_hidden_states=None,779return_dict=None,780):781r"""782labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
783Labels for computing the token classification loss.
784Indices should be in ``[0, ..., config.num_labels - 1]``.
785"""
786return_dict = return_dict if return_dict is not None else self.config.use_return_dict787
788outputs = self.distilbert(789input_ids,790attention_mask=attention_mask,791head_mask=head_mask,792inputs_embeds=inputs_embeds,793output_attentions=output_attentions,794output_hidden_states=output_hidden_states,795return_dict=return_dict,796)797
798sequence_output = outputs[0]799
800sequence_output = self.dropout(sequence_output)801logits = self.classifier(sequence_output)802
803loss = None804if labels is not None:805loss_fct = CrossEntropyLoss()806# Only keep active parts of the loss807if attention_mask is not None:808active_loss = attention_mask.view(-1) == 1809active_logits = logits.view(-1, self.num_labels)810active_labels = torch.where(811active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)812)813loss = loss_fct(active_logits, active_labels)814else:815loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))816
817if not return_dict:818output = (logits,) + outputs[1:]819return ((loss,) + output) if loss is not None else output820
821return TokenClassifierOutput(822loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions,823)824
825
826@add_start_docstrings(827"""DistilBert Model with a multiple choice classification head on top (a linear layer on top of828the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """,829DISTILBERT_START_DOCSTRING,830)
831class DistilBertForMultipleChoice(DistilBertPreTrainedModel):832def __init__(self, config):833super().__init__(config)834
835self.distilbert = DistilBertModel(config)836self.pre_classifier = nn.Linear(config.dim, config.dim)837self.classifier = nn.Linear(config.dim, 1)838self.dropout = nn.Dropout(config.seq_classif_dropout)839
840self.init_weights()841
842@add_start_docstrings_to_callable(DISTILBERT_INPUTS_DOCSTRING.format("(batch_size, num_choices, sequence_length)"))843@replace_return_docstrings(output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC)844def forward(845self,846input_ids=None,847attention_mask=None,848head_mask=None,849inputs_embeds=None,850labels=None,851output_attentions=None,852output_hidden_states=None,853return_dict=None,854):855r"""856labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
857Labels for computing the multiple choice classification loss.
858Indices should be in ``[0, ..., num_choices-1]`` where `num_choices` is the size of the second dimension
859of the input tensors. (see `input_ids` above)
860
861Returns:
862
863Examples::
864
865>>> from transformers import DistilBertTokenizer, DistilBertForMultipleChoice
866>>> import torch
867
868>>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-cased')
869>>> model = DistilBertForMultipleChoice.from_pretrained('distilbert-base-cased', return_dict=True)
870
871>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
872>>> choice0 = "It is eaten with a fork and a knife."
873>>> choice1 = "It is eaten while held in the hand."
874>>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
875
876>>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors='pt', padding=True)
877>>> outputs = model(**{k: v.unsqueeze(0) for k,v in encoding.items()}, labels=labels) # batch size is 1
878
879>>> # the linear classifier still needs to be trained
880>>> loss = outputs.loss
881>>> logits = outputs.logits
882"""
883return_dict = return_dict if return_dict is not None else self.config.use_return_dict884num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]885
886input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None887attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None888inputs_embeds = (889inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))890if inputs_embeds is not None891else None892)893
894outputs = self.distilbert(895input_ids,896attention_mask=attention_mask,897head_mask=head_mask,898inputs_embeds=inputs_embeds,899output_attentions=output_attentions,900output_hidden_states=output_hidden_states,901return_dict=return_dict,902)903
904hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)905pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)906pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)907pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)908pooled_output = self.dropout(pooled_output) # (bs * num_choices, dim)909logits = self.classifier(pooled_output) # (bs * num_choices, 1)910
911reshaped_logits = logits.view(-1, num_choices) # (bs, num_choices)912
913loss = None914if labels is not None:915loss_fct = CrossEntropyLoss()916loss = loss_fct(reshaped_logits, labels)917
918if not return_dict:919output = (reshaped_logits,) + outputs[1:]920return ((loss,) + output) if loss is not None else output921
922return MultipleChoiceModelOutput(923loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions,924)925