modeling_xxx.py 31.4 KB
Newer Older
thomwolf's avatar
thomwolf committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# coding=utf-8
# Copyright 2018 XXX Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" PyTorch XXX model. """

####################################################
# In this template, replace all the XXX (various casings) with your model name
####################################################


import os

import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from .configuration_xxx import XxxConfig
29
30
31
32
33
34
35
36
37
from .file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_callable
from .modeling_outputs import (
    BaseModelOutputWithPooling,
    MaskedLMOutput,
    MultipleChoiceModelOutput,
    QuestionAnsweringModelOutput,
    SequenceClassifierOutput,
    TokenClassifierOutput,
)
38
from .modeling_utils import PreTrainedModel
39
from .utils import logging
Aymeric Augustin's avatar
Aymeric Augustin committed
40

thomwolf's avatar
thomwolf committed
41

42
logger = logging.get_logger(__name__)
thomwolf's avatar
thomwolf committed
43

44
45
46
_CONFIG_FOR_DOC = "XXXConfig"
_TOKENIZER_FOR_DOC = "XXXTokenizer"

thomwolf's avatar
thomwolf committed
47
####################################################
48
49
# This list contrains shortcut names for some of
# the pretrained weights provided with the models
thomwolf's avatar
thomwolf committed
50
####################################################
51
52
53
54
XXX_PRETRAINED_MODEL_ARCHIVE_LIST = [
    "xxx-base-uncased",
    "xxx-large-uncased",
]
thomwolf's avatar
thomwolf committed
55

56

thomwolf's avatar
thomwolf committed
57
58
59
60
61
####################################################
# This is a conversion method from TF 1.0 to PyTorch
# More details: https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28
####################################################
def load_tf_weights_in_xxx(model, config, tf_checkpoint_path):
Lysandre's avatar
Lysandre committed
62
    """Load tf checkpoints in a pytorch model."""
thomwolf's avatar
thomwolf committed
63
64
    try:
        import re
65

thomwolf's avatar
thomwolf committed
66
67
68
        import numpy as np
        import tensorflow as tf
    except ImportError:
69
70
71
72
        logger.error(
            "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
            "https://www.tensorflow.org/install/ for installation instructions."
        )
thomwolf's avatar
thomwolf committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
        raise
    tf_path = os.path.abspath(tf_checkpoint_path)
    logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
    # Load weights from TF model
    init_vars = tf.train.list_variables(tf_path)
    names = []
    arrays = []
    for name, shape in init_vars:
        logger.info("Loading TF weight {} with shape {}".format(name, shape))
        array = tf.train.load_variable(tf_path, name)
        names.append(name)
        arrays.append(array)

    for name, array in zip(names, arrays):
87
        name = name.split("/")
thomwolf's avatar
thomwolf committed
88
89
        # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
        # which are not required for using pretrained model
90
91
92
93
        if any(
            n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
            for n in name
        ):
thomwolf's avatar
thomwolf committed
94
95
96
97
            logger.info("Skipping {}".format("/".join(name)))
            continue
        pointer = model
        for m_name in name:
98
            if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
99
                scope_names = re.split(r"_(\d+)", m_name)
thomwolf's avatar
thomwolf committed
100
            else:
101
102
                scope_names = [m_name]
            if scope_names[0] == "kernel" or scope_names[0] == "gamma":
103
                pointer = getattr(pointer, "weight")
104
            elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
105
                pointer = getattr(pointer, "bias")
106
            elif scope_names[0] == "output_weights":
107
                pointer = getattr(pointer, "weight")
108
            elif scope_names[0] == "squad":
109
                pointer = getattr(pointer, "classifier")
thomwolf's avatar
thomwolf committed
110
111
            else:
                try:
112
                    pointer = getattr(pointer, scope_names[0])
thomwolf's avatar
thomwolf committed
113
114
115
                except AttributeError:
                    logger.info("Skipping {}".format("/".join(name)))
                    continue
116
117
            if len(scope_names) >= 2:
                num = int(scope_names[1])
thomwolf's avatar
thomwolf committed
118
                pointer = pointer[num]
119
120
121
        if m_name[-11:] == "_embeddings":
            pointer = getattr(pointer, "weight")
        elif m_name == "kernel":
thomwolf's avatar
thomwolf committed
122
123
            array = np.transpose(array)
        try:
Teven's avatar
Teven committed
124
125
126
            assert (
                pointer.shape == array.shape
            ), f"Pointer and array have mismatched shapes {pointer.shape} and {array.shape}"
thomwolf's avatar
thomwolf committed
127
128
129
130
131
132
133
134
135
136
137
        except AssertionError as e:
            e.args += (pointer.shape, array.shape)
            raise
        logger.info("Initialize PyTorch weight {}".format(name))
        pointer.data = torch.from_numpy(array)
    return model


####################################################
# PyTorch Models are constructed by sub-classing
# - torch.nn.Module for the layers and
Julien Chaumond's avatar
Julien Chaumond committed
138
# - PreTrainedModel for the models (itself a sub-class of torch.nn.Module)
thomwolf's avatar
thomwolf committed
139
140
141
142
143
144
145
146
####################################################

####################################################
# Here is an example of typical layer in a PyTorch model of the library
# The classes are usually identical to the TF 2.0 ones without the 'TF' prefix.
#
# See the conversion methods in modeling_tf_pytorch_utils.py for more details
####################################################
147
148
149
150
151
152
153
154

XxxAttention = nn.Module

XxxIntermediate = nn.Module

XxxOutput = nn.Module


thomwolf's avatar
thomwolf committed
155
156
class XxxLayer(nn.Module):
    def __init__(self, config):
Julien Chaumond's avatar
Julien Chaumond committed
157
        super().__init__()
thomwolf's avatar
thomwolf committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
        self.attention = XxxAttention(config)
        self.intermediate = XxxIntermediate(config)
        self.output = XxxOutput(config)

    def forward(self, hidden_states, attention_mask=None, head_mask=None):
        attention_outputs = self.attention(hidden_states, attention_mask, head_mask)
        attention_output = attention_outputs[0]
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        outputs = (layer_output,) + attention_outputs[1:]  # add attentions if we output them
        return outputs


####################################################
# PreTrainedModel is a sub-class of torch.nn.Module
# which take care of loading and saving pretrained weights
# and various common utilities.
#
# Here you just need to specify a few (self-explanatory)
# pointers for your model and the weights initialization
# method if its not fully covered by PreTrainedModel's default method
####################################################
180
181
182
183
184
185
186
187
188
189

XxxLayerNorm = torch.nn.LayerNorm

XxxEmbeddings = nn.Module

XxxEncoder = nn.Module

XxxPooler = nn.Module


thomwolf's avatar
thomwolf committed
190
class XxxPreTrainedModel(PreTrainedModel):
Lysandre's avatar
Lysandre committed
191
192
    """An abstract class to handle weights initialization and
    a simple interface for downloading and loading pretrained models.
thomwolf's avatar
thomwolf committed
193
    """
194

thomwolf's avatar
thomwolf committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    config_class = XxxConfig
    load_tf_weights = load_tf_weights_in_xxx
    base_model_prefix = "transformer"

    def _init_weights(self, module):
        """ Initialize the weights """
        if isinstance(module, (nn.Linear, nn.Embedding)):
            # Slightly different from the TF version which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
        elif isinstance(module, XxxLayerNorm):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0)
        if isinstance(module, nn.Linear) and module.bias is not None:
            module.bias.data.zero_()


212
213
214
XXX_START_DOCSTRING = r"""

    The XXX model was proposed in `XXX: Pre-training of Deep Bidirectional Transformers for Language Understanding
215
    <https://arxiv.org/abs/1810.04805>`__ by....
thomwolf's avatar
thomwolf committed
216

217
218
219
220
221
    This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
    methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
    pruning heads etc.)

    This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ subclass.
222
223
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
    usage and behavior.
thomwolf's avatar
thomwolf committed
224
225

    Parameters:
226
        config (:class:`~transformers.XxxConfig`): Model configuration class with all the parameters of the model.
thomwolf's avatar
thomwolf committed
227
228
229
230
231
232
            Initializing with a config file does not load the weights associated with the model, only the configuration.
            Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
"""

XXX_INPUTS_DOCSTRING = r"""
    Inputs:
233
        input_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`):
thomwolf's avatar
thomwolf committed
234
235
            Indices of input sequence tokens in the vocabulary.

236
237
238
            Indices can be obtained using :class:`~transformers.XxxTokenizer`.
            See :meth:`transformers.PreTrainedTokenizer.encode` and
            :meth:`transformers.PreTrainedTokenizer.__call__` for details.
239
240

            `What are input IDs? <../glossary.html#input-ids>`__
241
        attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `optional`):
thomwolf's avatar
thomwolf committed
242
243
            Mask to avoid performing attention on padding token indices.
            Mask values selected in ``[0, 1]``:
244
245
246

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **maked**.
247
248

            `What are attention masks? <../glossary.html#attention-mask>`__
249
        token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
thomwolf's avatar
thomwolf committed
250
            Segment token indices to indicate first and second portions of the inputs.
251
252
253
254
            Indices are selected in ``[0, 1]``:

            - 0 corresponds to a `sentence A` token,
            - 1 corresponds to a `sentence B` token.
255
256

            `What are token type IDs? <../glossary.html#token-type-ids>`_
257
        position_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
thomwolf's avatar
thomwolf committed
258
259
            Indices of positions of each input sequence tokens in the position embeddings.
            Selected in the range ``[0, config.max_position_embeddings - 1]``.
260
261

            `What are position IDs? <../glossary.html#position-ids>`_
262
        head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
thomwolf's avatar
thomwolf committed
263
264
            Mask to nullify selected heads of the self-attention modules.
            Mask values selected in ``[0, 1]``:
265
266
267
268
269

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`({0}, hidden_size)`, `optional`):
270
            Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
271
272
            This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
            vectors than the model's internal embedding lookup matrix.
273
        output_attentions (:obj:`bool`, `optional`):
274
275
            Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
            tensors for more detail.
276
        output_hidden_states (:obj:`bool`, `optional`):
277
278
            Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
            more detail.
279
        return_dict (:obj:`bool`, `optional`):
280
            Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
thomwolf's avatar
thomwolf committed
281
282
"""

283
284

@add_start_docstrings(
285
    "The bare XXX Model transformer outputting raw hidden-states without any specific head on top.",
286
287
    XXX_START_DOCSTRING,
)
thomwolf's avatar
thomwolf committed
288
289
class XxxModel(XxxPreTrainedModel):
    def __init__(self, config):
Julien Chaumond's avatar
Julien Chaumond committed
290
        super().__init__(config)
thomwolf's avatar
thomwolf committed
291
292
293
294
295
296
297

        self.embeddings = XxxEmbeddings(config)
        self.encoder = XxxEncoder(config)
        self.pooler = XxxPooler(config)

        self.init_weights()

thomwolf's avatar
thomwolf committed
298
    def get_input_embeddings(self):
thomwolf's avatar
thomwolf committed
299
300
        return self.embeddings.word_embeddings

thomwolf's avatar
thomwolf committed
301
    def set_input_embeddings(self, new_embeddings):
302
303
        self.embeddings.word_embeddings = new_embeddings

thomwolf's avatar
thomwolf committed
304
    def _prune_heads(self, heads_to_prune):
Lysandre's avatar
Lysandre committed
305
306
307
        """Prunes heads of the model.
        heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
        See base class PreTrainedModel
thomwolf's avatar
thomwolf committed
308
309
310
311
        """
        for layer, heads in heads_to_prune.items():
            self.encoder.layer[layer].attention.prune_heads(heads)

312
    @add_start_docstrings_to_callable(XXX_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
313
314
315
316
317
318
    @add_code_sample_docstrings(
        tokenizer_class=_TOKENIZER_FOR_DOC,
        checkpoint="xxx-base-uncased",
        output_type=BaseModelOutputWithPooling,
        config_class=_CONFIG_FOR_DOC,
    )
319
320
321
322
323
324
325
326
    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
327
328
        output_attentions=None,
        output_hidden_states=None,
329
        return_dict=None,
330
    ):
331
332
333
334
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
335
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
336

Julien Chaumond's avatar
Julien Chaumond committed
337
338
339
340
341
342
343
344
345
        if input_ids is not None and inputs_embeds is not None:
            raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
        elif input_ids is not None:
            input_shape = input_ids.size()
        elif inputs_embeds is not None:
            input_shape = inputs_embeds.size()[:-1]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

Julien Chaumond's avatar
Julien Chaumond committed
346
347
        device = input_ids.device if input_ids is not None else inputs_embeds.device

thomwolf's avatar
thomwolf committed
348
        if attention_mask is None:
Julien Chaumond's avatar
Julien Chaumond committed
349
            attention_mask = torch.ones(input_shape, device=device)
thomwolf's avatar
thomwolf committed
350
        if token_type_ids is None:
Julien Chaumond's avatar
Julien Chaumond committed
351
            token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
thomwolf's avatar
thomwolf committed
352

353
        extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device)
thomwolf's avatar
thomwolf committed
354
355
356
357
358
        # Prepare head mask if needed
        # 1.0 in head_mask indicate we keep the head
        # attention_probs has shape bsz x n_heads x N x N
        # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
        # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
359
        head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
thomwolf's avatar
thomwolf committed
360
361
362

        ##################################
        # Replace this with your model code
363
364
365
        embedding_output = self.embeddings(
            input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
        )
thomwolf's avatar
thomwolf committed
366
367
        encoder_outputs = self.encoder(embedding_output, extended_attention_mask, head_mask=head_mask)
        sequence_output = encoder_outputs[0]
368
        pooled_output = self.pooler(sequence_output)
thomwolf's avatar
thomwolf committed
369

370
        if not return_dict:
371
            return (sequence_output, pooled_output) + encoder_outputs[1:]
thomwolf's avatar
thomwolf committed
372

373
374
375
376
377
378
        return BaseModelOutputWithPooling(
            last_hidden_state=sequence_output,
            pooler_output=pooled_output,
            hidden_states=encoder_outputs.hidden_states,
            attentions=encoder_outputs.attentions,
        )
thomwolf's avatar
thomwolf committed
379

380

381
382
@add_start_docstrings("""XXX Model with a `language modeling` head on top. """, XXX_START_DOCSTRING)
class XxxForMaskedLM(XxxPreTrainedModel):
thomwolf's avatar
thomwolf committed
383
    def __init__(self, config):
Julien Chaumond's avatar
Julien Chaumond committed
384
        super().__init__(config)
thomwolf's avatar
thomwolf committed
385
386

        self.transformer = XxxModel(config)
387
        self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
thomwolf's avatar
thomwolf committed
388
389
390

        self.init_weights()

thomwolf's avatar
thomwolf committed
391
    def get_output_embeddings(self):
392
        return self.lm_head
thomwolf's avatar
thomwolf committed
393

394
    @add_start_docstrings_to_callable(XXX_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
395
396
397
398
399
400
    @add_code_sample_docstrings(
        tokenizer_class=_TOKENIZER_FOR_DOC,
        checkpoint="xxx-base-uncased",
        output_type=MaskedLMOutput,
        config_class=_CONFIG_FOR_DOC,
    )
401
402
403
404
405
406
407
408
    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
409
410
411
        labels=None,
        output_attentions=None,
        output_hidden_states=None,
412
        return_dict=None,
413
    ):
414
        r"""
415
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
416
417
418
419
420
            Labels for computing the masked language modeling loss.
            Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
            Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
            in ``[0, ..., config.vocab_size]``
        """
421
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
422
423
424
425
426
427
428
429

        outputs = self.transformer(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
430
431
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
432
            return_dict=return_dict,
433
        )
thomwolf's avatar
thomwolf committed
434
435

        sequence_output = outputs[0]
436
        prediction_scores = self.lm_head(sequence_output)
thomwolf's avatar
thomwolf committed
437

438
439
440
441
442
        masked_lm_loss = None
        if labels is not None:
            loss_fct = CrossEntropyLoss()  # -100 index = padding token
            masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))

443
        if not return_dict:
444
445
446
447
448
449
450
451
452
            output = (prediction_scores,) + outputs[2:]
            return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output

        return MaskedLMOutput(
            loss=masked_lm_loss,
            logits=prediction_scores,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )
thomwolf's avatar
thomwolf committed
453
454


455
@add_start_docstrings(
456
    """XXX Model transformer with a sequence classification/regression head on top (a linear layer on top of
thomwolf's avatar
thomwolf committed
457
    the pooled output) e.g. for GLUE tasks. """,
458
459
    XXX_START_DOCSTRING,
)
thomwolf's avatar
thomwolf committed
460
461
class XxxForSequenceClassification(XxxPreTrainedModel):
    def __init__(self, config):
Julien Chaumond's avatar
Julien Chaumond committed
462
        super().__init__(config)
thomwolf's avatar
thomwolf committed
463
464
465
466
467
468
469
470
        self.num_labels = config.num_labels

        self.transformer = XxxModel(config)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)

        self.init_weights()

471
    @add_start_docstrings_to_callable(XXX_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
472
473
474
475
476
477
    @add_code_sample_docstrings(
        tokenizer_class=_TOKENIZER_FOR_DOC,
        checkpoint="xxx-base-uncased",
        output_type=SequenceClassifierOutput,
        config_class=_CONFIG_FOR_DOC,
    )
478
479
480
481
482
483
484
485
486
    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        labels=None,
487
488
        output_attentions=None,
        output_hidden_states=None,
489
        return_dict=None,
490
    ):
491
        r"""
492
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
493
494
495
496
497
            Labels for computing the sequence classification/regression loss.
            Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
            If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
            If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
498
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
499
500
501
502
503
504
505
506

        outputs = self.transformer(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
507
508
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
509
            return_dict=return_dict,
510
        )
thomwolf's avatar
thomwolf committed
511
512
513
514
515
516

        pooled_output = outputs[1]

        pooled_output = self.dropout(pooled_output)
        logits = self.classifier(pooled_output)

517
        loss = None
thomwolf's avatar
thomwolf committed
518
519
520
521
522
523
524
525
526
        if labels is not None:
            if self.num_labels == 1:
                #  We are doing regression
                loss_fct = MSELoss()
                loss = loss_fct(logits.view(-1), labels.view(-1))
            else:
                loss_fct = CrossEntropyLoss()
                loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))

527
        if not return_dict:
528
529
530
531
            output = (logits,) + outputs[2:]
            return ((loss,) + output) if loss is not None else output

        return SequenceClassifierOutput(
Lysandre's avatar
Lysandre committed
532
533
534
535
            loss=loss,
            logits=logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
536
        )
thomwolf's avatar
thomwolf committed
537
538


539
@add_start_docstrings(
540
541
    """XXX Model with a multiple choice classification head on top (a linear layer on top of
    the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """,
542
543
    XXX_START_DOCSTRING,
)
544
545
546
class XxxForMultipleChoice(XxxPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
thomwolf's avatar
thomwolf committed
547

548
549
550
        self.transformer = XxxModel(config)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, 1)
thomwolf's avatar
thomwolf committed
551

552
553
        self.init_weights()

554
    @add_start_docstrings_to_callable(XXX_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
    @add_code_sample_docstrings(
        tokenizer_class=_TOKENIZER_FOR_DOC,
        checkpoint="xxx-base-uncased",
        output_type=MultipleChoiceModelOutput,
        config_class=_CONFIG_FOR_DOC,
    )
    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        labels=None,
        output_attentions=None,
        output_hidden_states=None,
572
        return_dict=None,
573
574
    ):
        r"""
575
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
576
            Labels for computing the multiple choice classification loss.
577
578
            Indices should be in ``[0, ..., num_choices-1]`` where :obj:`num_choices` is the size of the second dimension
            of the input tensors. (See :obj:`input_ids` above)
579
        """
580
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
        num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]

        input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
        attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
        token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
        position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
        inputs_embeds = (
            inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
            if inputs_embeds is not None
            else None
        )

        outputs = self.transformer(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
602
            return_dict=return_dict,
603
604
605
606
607
608
609
610
611
612
613
614
615
        )

        pooled_output = outputs[1]

        pooled_output = self.dropout(pooled_output)
        logits = self.classifier(pooled_output)
        reshaped_logits = logits.view(-1, num_choices)

        loss = None
        if labels is not None:
            loss_fct = CrossEntropyLoss()
            loss = loss_fct(reshaped_logits, labels)

616
        if not return_dict:
617
618
619
620
            output = (reshaped_logits,) + outputs[2:]
            return ((loss,) + output) if loss is not None else output

        return MultipleChoiceModelOutput(
Lysandre's avatar
Lysandre committed
621
622
623
624
            loss=loss,
            logits=reshaped_logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
625
        )
626

627
628
629
630
631
632
633

@add_start_docstrings(
    """XXX Model with a token classification head on top (a linear layer on top of
    the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """,
    XXX_START_DOCSTRING,
)
class XxxForTokenClassification(XxxPreTrainedModel):
thomwolf's avatar
thomwolf committed
634
    def __init__(self, config):
Julien Chaumond's avatar
Julien Chaumond committed
635
        super().__init__(config)
thomwolf's avatar
thomwolf committed
636
637
638
639
640
641
642
643
        self.num_labels = config.num_labels

        self.transformer = XxxModel(config)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

        self.init_weights()

644
    @add_start_docstrings_to_callable(XXX_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
645
646
647
648
649
650
    @add_code_sample_docstrings(
        tokenizer_class=_TOKENIZER_FOR_DOC,
        checkpoint="xxx-base-uncased",
        output_type=TokenClassifierOutput,
        config_class=_CONFIG_FOR_DOC,
    )
651
652
653
654
655
656
657
658
659
    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        labels=None,
660
661
        output_attentions=None,
        output_hidden_states=None,
662
        return_dict=None,
663
    ):
664
        r"""
665
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
666
667
668
            Labels for computing the token classification loss.
            Indices should be in ``[0, ..., config.num_labels - 1]``.
        """
669
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
670
671
672
673
674
675
676
677

        outputs = self.transformer(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
678
679
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
680
            return_dict=return_dict,
681
        )
thomwolf's avatar
thomwolf committed
682
683
684
685
686
687

        sequence_output = outputs[0]

        sequence_output = self.dropout(sequence_output)
        logits = self.classifier(sequence_output)

688
        loss = None
thomwolf's avatar
thomwolf committed
689
690
691
692
693
        if labels is not None:
            loss_fct = CrossEntropyLoss()
            # Only keep active parts of the loss
            if attention_mask is not None:
                active_loss = attention_mask.view(-1) == 1
694
695
696
697
                active_logits = logits.view(-1, self.num_labels)
                active_labels = torch.where(
                    active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
                )
thomwolf's avatar
thomwolf committed
698
699
700
701
                loss = loss_fct(active_logits, active_labels)
            else:
                loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))

702
        if not return_dict:
703
704
705
706
            output = (logits,) + outputs[2:]
            return ((loss,) + output) if loss is not None else output

        return TokenClassifierOutput(
Lysandre's avatar
Lysandre committed
707
708
709
710
            loss=loss,
            logits=logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
711
        )
thomwolf's avatar
thomwolf committed
712
713


714
@add_start_docstrings(
715
716
    """XXX Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """,
717
718
    XXX_START_DOCSTRING,
)
thomwolf's avatar
thomwolf committed
719
720
class XxxForQuestionAnswering(XxxPreTrainedModel):
    def __init__(self, config):
Julien Chaumond's avatar
Julien Chaumond committed
721
        super().__init__(config)
thomwolf's avatar
thomwolf committed
722
723
724
725
726
727
728
        self.num_labels = config.num_labels

        self.transformer = XxxModel(config)
        self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

        self.init_weights()

729
    @add_start_docstrings_to_callable(XXX_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
730
731
732
733
734
735
    @add_code_sample_docstrings(
        tokenizer_class=_TOKENIZER_FOR_DOC,
        checkpoint="xxx-base-uncased",
        output_type=QuestionAnsweringModelOutput,
        config_class=_CONFIG_FOR_DOC,
    )
736
737
738
739
740
741
742
743
744
745
    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        start_positions=None,
        end_positions=None,
746
747
        output_attentions=None,
        output_hidden_states=None,
748
        return_dict=None,
749
    ):
750
        r"""
751
        start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
752
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
753
            Positions are clamped to the length of the sequence (:obj:`sequence_length`).
754
            Position outside of the sequence are not taken into account for computing the loss.
755
        end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
756
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
757
            Positions are clamped to the length of the sequence (:obj:`sequence_length`).
758
759
            Position outside of the sequence are not taken into account for computing the loss.
        """
760
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
761
762
763
764
765
766
767
768

        outputs = self.transformer(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
769
770
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
771
            return_dict=return_dict,
772
        )
thomwolf's avatar
thomwolf committed
773
774
775
776
777
778
779
780

        sequence_output = outputs[0]

        logits = self.qa_outputs(sequence_output)
        start_logits, end_logits = logits.split(1, dim=-1)
        start_logits = start_logits.squeeze(-1)
        end_logits = end_logits.squeeze(-1)

781
        total_loss = None
thomwolf's avatar
thomwolf committed
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
        if start_positions is not None and end_positions is not None:
            # If we are on multi-GPU, split add a dimension
            if len(start_positions.size()) > 1:
                start_positions = start_positions.squeeze(-1)
            if len(end_positions.size()) > 1:
                end_positions = end_positions.squeeze(-1)
            # sometimes the start/end positions are outside our model inputs, we ignore these terms
            ignored_index = start_logits.size(1)
            start_positions.clamp_(0, ignored_index)
            end_positions.clamp_(0, ignored_index)

            loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
            start_loss = loss_fct(start_logits, start_positions)
            end_loss = loss_fct(end_logits, end_positions)
            total_loss = (start_loss + end_loss) / 2

798
        if not return_dict:
799
800
801
802
803
804
805
806
807
808
            output = (start_logits, end_logits) + outputs[2:]
            return ((total_loss,) + output) if total_loss is not None else output

        return QuestionAnsweringModelOutput(
            loss=total_loss,
            start_logits=start_logits,
            end_logits=end_logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )