modeling_distilbert.py 36.6 KB
Newer Older
VictorSanh's avatar
wip  
VictorSanh committed
1
# coding=utf-8
thomwolf's avatar
thomwolf committed
2
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
VictorSanh's avatar
wip  
VictorSanh committed
3
4
5
6
7
8
9
10
11
12
13
14
#
# 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.
thomwolf's avatar
thomwolf committed
15
16
17
""" PyTorch DistilBERT model
    adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM)
    and in part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)
VictorSanh's avatar
wip  
VictorSanh committed
18
19
20
21
22
23
"""
from __future__ import absolute_import, division, print_function, unicode_literals

import json
import logging
import math
VictorSanh's avatar
VictorSanh committed
24
import copy
VictorSanh's avatar
wip  
VictorSanh committed
25
26
27
28
29
30
31
32
33
import sys
from io import open

import itertools
import numpy as np

import torch
import torch.nn as nn

34
from pytorch_transformers.modeling_utils import PretrainedConfig, PreTrainedModel, add_start_docstrings, prune_linear_layer
VictorSanh's avatar
wip  
VictorSanh committed
35
36
37
38
39

import logging
logger = logging.getLogger(__name__)


thomwolf's avatar
thomwolf committed
40
41
42
DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP = {
    'distilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-pytorch_model.bin",
    'distilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-distilled-squad-pytorch_model.bin"
VictorSanh's avatar
wip  
VictorSanh committed
43
44
}

thomwolf's avatar
thomwolf committed
45
46
47
DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    'distilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-config.json",
    'distilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-uncased-distilled-squad-config.json"
VictorSanh's avatar
wip  
VictorSanh committed
48
49
50
}


thomwolf's avatar
thomwolf committed
51
52
class DistilBertConfig(PretrainedConfig):
    pretrained_config_archive_map = DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
VictorSanh's avatar
wip  
VictorSanh committed
53
54
55
56
57
58
59
60

    def __init__(self,
                 vocab_size_or_config_json_file=30522,
                 max_position_embeddings=512,
                 sinusoidal_pos_embds=True,
                 n_layers=6,
                 n_heads=12,
                 dim=768,
VictorSanh's avatar
VictorSanh committed
61
                 hidden_dim=4*768,
VictorSanh's avatar
wip  
VictorSanh committed
62
63
64
65
                 dropout=0.1,
                 attention_dropout=0.1,
                 activation='gelu',
                 initializer_range=0.02,
VictorSanh's avatar
VictorSanh committed
66
                 tie_weights_=True,
67
68
                 qa_dropout=0.1,
                 seq_classif_dropout=0.2,
VictorSanh's avatar
wip  
VictorSanh committed
69
                 **kwargs):
thomwolf's avatar
thomwolf committed
70
        super(DistilBertConfig, self).__init__(**kwargs)
VictorSanh's avatar
wip  
VictorSanh committed
71

VictorSanh's avatar
VictorSanh committed
72
        if isinstance(vocab_size_or_config_json_file, str) or (sys.version_info[0] == 2
VictorSanh's avatar
wip  
VictorSanh committed
73
74
75
76
77
78
79
80
81
82
83
84
                        and isinstance(vocab_size_or_config_json_file, unicode)):
            with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader:
                json_config = json.loads(reader.read())
            for key, value in json_config.items():
                self.__dict__[key] = value
        elif isinstance(vocab_size_or_config_json_file, int):
            self.vocab_size = vocab_size_or_config_json_file
            self.max_position_embeddings = max_position_embeddings
            self.sinusoidal_pos_embds = sinusoidal_pos_embds
            self.n_layers = n_layers
            self.n_heads = n_heads
            self.dim = dim
VictorSanh's avatar
VictorSanh committed
85
            self.hidden_dim = hidden_dim
VictorSanh's avatar
wip  
VictorSanh committed
86
87
88
89
            self.dropout = dropout
            self.attention_dropout = attention_dropout
            self.activation = activation
            self.initializer_range = initializer_range
VictorSanh's avatar
VictorSanh committed
90
            self.tie_weights_ = tie_weights_
91
92
            self.qa_dropout = qa_dropout
            self.seq_classif_dropout = seq_classif_dropout
VictorSanh's avatar
wip  
VictorSanh committed
93
94
        else:
            raise ValueError("First argument must be either a vocabulary size (int)"
95
                             " or the path to a pretrained model config file (str)")
96
97
    @property
    def hidden_size(self):
98
        return self.dim
99
100
101
102
103
104
105
106

    @property
    def num_attention_heads(self):
        return self.n_heads

    @property
    def num_hidden_layers(self):
        return self.n_layers
VictorSanh's avatar
wip  
VictorSanh committed
107
108


VictorSanh's avatar
VictorSanh committed
109
### UTILS AND BUILDING BLOCKS OF THE ARCHITECTURE ###
VictorSanh's avatar
wip  
VictorSanh committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def gelu(x):
    return 0.5 * x * (1.0 + torch.erf(x / math.sqrt(2.0)))

def create_sinusoidal_embeddings(n_pos, dim, out):
    position_enc = np.array([
        [pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)]
        for pos in range(n_pos)
    ])
    out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
    out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
    out.detach_()
    out.requires_grad = False

class Embeddings(nn.Module):
    def __init__(self,
                 config):
        super(Embeddings, self).__init__()
VictorSanh's avatar
VictorSanh committed
127
        self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=0)
VictorSanh's avatar
wip  
VictorSanh committed
128
        self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)
VictorSanh's avatar
VictorSanh committed
129
        if config.sinusoidal_pos_embds:
VictorSanh's avatar
wip  
VictorSanh committed
130
131
132
133
134
135
136
137
138
139
140
            create_sinusoidal_embeddings(n_pos=config.max_position_embeddings,
                                         dim=config.dim,
                                         out=self.position_embeddings.weight)

        self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)
        self.dropout = nn.Dropout(config.dropout)

    def forward(self, input_ids):
        """
        Parameters
        ----------
VictorSanh's avatar
VictorSanh committed
141
142
143
144
145
146
147
        input_ids: torch.tensor(bs, max_seq_length)
            The token ids to embed.

        Outputs
        -------
        embeddings: torch.tensor(bs, max_seq_length, dim)
            The embedded tokens (plus position embeddings, no token_type embeddings)
VictorSanh's avatar
wip  
VictorSanh committed
148
149
150
151
152
153
154
155
        """
        seq_length = input_ids.size(1)
        position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length)
        position_ids = position_ids.unsqueeze(0).expand_as(input_ids)                      # (bs, max_seq_length)

        word_embeddings = self.word_embeddings(input_ids)                   # (bs, max_seq_length, dim)
        position_embeddings = self.position_embeddings(position_ids)        # (bs, max_seq_length, dim)

VictorSanh's avatar
VictorSanh committed
156
157
158
        embeddings = word_embeddings + position_embeddings  # (bs, max_seq_length, dim)
        embeddings = self.LayerNorm(embeddings)             # (bs, max_seq_length, dim)
        embeddings = self.dropout(embeddings)               # (bs, max_seq_length, dim)
VictorSanh's avatar
wip  
VictorSanh committed
159
160
161
        return embeddings

class MultiHeadSelfAttention(nn.Module):
LysandreJik's avatar
LysandreJik committed
162
    def __init__(self, config):
VictorSanh's avatar
wip  
VictorSanh committed
163
164
165
166
167
168
169
170
171
        super(MultiHeadSelfAttention, self).__init__()

        self.n_heads = config.n_heads
        self.dim = config.dim
        self.dropout = nn.Dropout(p=config.attention_dropout)
        self.output_attentions = config.output_attentions

        assert self.dim % self.n_heads == 0

VictorSanh's avatar
VictorSanh committed
172
173
174
175
        self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
        self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
        self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
        self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
VictorSanh's avatar
wip  
VictorSanh committed
176

177
178
        self.pruned_heads = set()

179
180
181
182
183
    def prune_heads(self, heads):
        attention_head_size = self.dim // self.n_heads
        if len(heads) == 0:
            return
        mask = torch.ones(self.n_heads, attention_head_size)
184
        heads = set(heads) - self.pruned_heads
185
        for head in heads:
186
            head -= sum(1 if h < head else 0 for h in self.pruned_heads)
187
188
189
190
191
192
193
194
195
196
197
            mask[head] = 0
        mask = mask.view(-1).contiguous().eq(1)
        index = torch.arange(len(mask))[mask].long()
        # Prune linear layers
        self.q_lin = prune_linear_layer(self.q_lin, index)
        self.k_lin = prune_linear_layer(self.k_lin, index)
        self.v_lin = prune_linear_layer(self.v_lin, index)
        self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
        # Update hyper params
        self.n_heads = self.n_heads - len(heads)
        self.dim = attention_head_size * self.n_heads
198
        self.pruned_heads = self.pruned_heads.union(heads)
199

LysandreJik's avatar
LysandreJik committed
200
    def forward(self, query, key, value, mask, head_mask = None):
VictorSanh's avatar
wip  
VictorSanh committed
201
202
203
204
205
206
207
208
        """
        Parameters
        ----------
        query: torch.tensor(bs, seq_length, dim)
        key: torch.tensor(bs, seq_length, dim)
        value: torch.tensor(bs, seq_length, dim)
        mask: torch.tensor(bs, seq_length)

VictorSanh's avatar
VictorSanh committed
209
210
        Outputs
        -------
VictorSanh's avatar
wip  
VictorSanh committed
211
212
213
        weights: torch.tensor(bs, n_heads, seq_length, seq_length)
            Attention weights
        context: torch.tensor(bs, seq_length, dim)
VictorSanh's avatar
VictorSanh committed
214
            Contextualized layer. Optional: only if `output_attentions=True`
VictorSanh's avatar
wip  
VictorSanh committed
215
216
217
        """
        bs, q_length, dim = query.size()
        k_length = key.size(1)
218
219
        # assert dim == self.dim, 'Dimensions do not match: %s input vs %s configured' % (dim, self.dim)
        # assert key.size() == value.size()
VictorSanh's avatar
wip  
VictorSanh committed
220

221
        dim_per_head = self.dim // self.n_heads
VictorSanh's avatar
wip  
VictorSanh committed
222
223
224
225
226
227
228
229
230
231
232

        assert 2 <= mask.dim() <= 3
        causal = (mask.dim() == 3)
        mask_reshp = (bs, 1, 1, k_length)

        def shape(x):
            """ separate heads """
            return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)

        def unshape(x):
            """ group heads """
233
            return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)
VictorSanh's avatar
wip  
VictorSanh committed
234
235
236
237
238
239
240
241
242
243
244
245

        q = shape(self.q_lin(query))           # (bs, n_heads, q_length, dim_per_head)
        k = shape(self.k_lin(key))             # (bs, n_heads, k_length, dim_per_head)
        v = shape(self.v_lin(value))           # (bs, n_heads, k_length, dim_per_head)

        q = q / math.sqrt(dim_per_head)                     # (bs, n_heads, q_length, dim_per_head)
        scores = torch.matmul(q, k.transpose(2,3))          # (bs, n_heads, q_length, k_length)
        mask = (mask==0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length)
        scores.masked_fill_(mask, -float('inf'))            # (bs, n_heads, q_length, k_length)

        weights = nn.Softmax(dim=-1)(scores)   # (bs, n_heads, q_length, k_length)
        weights = self.dropout(weights)        # (bs, n_heads, q_length, k_length)
246
247
248
249
250

        # Mask heads if we want to
        if head_mask is not None:
            weights = weights * head_mask

VictorSanh's avatar
wip  
VictorSanh committed
251
252
253
254
255
        context = torch.matmul(weights, v)     # (bs, n_heads, q_length, dim_per_head)
        context = unshape(context)             # (bs, q_length, dim)
        context = self.out_lin(context)        # (bs, q_length, dim)

        if self.output_attentions:
VictorSanh's avatar
VictorSanh committed
256
            return (context, weights)
VictorSanh's avatar
wip  
VictorSanh committed
257
        else:
VictorSanh's avatar
VictorSanh committed
258
            return (context,)
VictorSanh's avatar
wip  
VictorSanh committed
259
260

class FFN(nn.Module):
LysandreJik's avatar
LysandreJik committed
261
    def __init__(self, config):
VictorSanh's avatar
wip  
VictorSanh committed
262
263
264
265
        super(FFN, self).__init__()
        self.dropout = nn.Dropout(p=config.dropout)
        self.lin1 = nn.Linear(in_features=config.dim, out_features=config.hidden_dim)
        self.lin2 = nn.Linear(in_features=config.hidden_dim, out_features=config.dim)
266
        assert config.activation in ['relu', 'gelu'], "activation ({}) must be in ['relu', 'gelu']".format(config.activation)
VictorSanh's avatar
VictorSanh committed
267
        self.activation = gelu if config.activation == 'gelu' else nn.ReLU()
VictorSanh's avatar
wip  
VictorSanh committed
268

LysandreJik's avatar
LysandreJik committed
269
    def forward(self, input):
VictorSanh's avatar
wip  
VictorSanh committed
270
271
272
273
274
275
276
        x = self.lin1(input)
        x = self.activation(x)
        x = self.lin2(x)
        x = self.dropout(x)
        return x

class TransformerBlock(nn.Module):
LysandreJik's avatar
LysandreJik committed
277
    def __init__(self, config):
VictorSanh's avatar
wip  
VictorSanh committed
278
279
280
281
282
283
284
285
286
        super(TransformerBlock, self).__init__()

        self.n_heads = config.n_heads
        self.dim = config.dim
        self.hidden_dim = config.hidden_dim
        self.dropout = nn.Dropout(p=config.dropout)
        self.activation = config.activation
        self.output_attentions = config.output_attentions

VictorSanh's avatar
VictorSanh committed
287
        assert config.dim % config.n_heads == 0
VictorSanh's avatar
wip  
VictorSanh committed
288

VictorSanh's avatar
VictorSanh committed
289
        self.attention = MultiHeadSelfAttention(config)
VictorSanh's avatar
wip  
VictorSanh committed
290
291
        self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)

VictorSanh's avatar
VictorSanh committed
292
        self.ffn = FFN(config)
VictorSanh's avatar
wip  
VictorSanh committed
293
294
        self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)

LysandreJik's avatar
LysandreJik committed
295
    def forward(self, x, attn_mask=None, head_mask=None):
VictorSanh's avatar
wip  
VictorSanh committed
296
297
298
299
300
        """
        Parameters
        ----------
        x: torch.tensor(bs, seq_length, dim)
        attn_mask: torch.tensor(bs, seq_length)
VictorSanh's avatar
VictorSanh committed
301
302
303
304
305
306
307

        Outputs
        -------
        sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length)
            The attention weights
        ffn_output: torch.tensor(bs, seq_length, dim)
            The output of the transformer block contextualization.
VictorSanh's avatar
wip  
VictorSanh committed
308
309
        """
        # Self-Attention
310
        sa_output = self.attention(query=x, key=x, value=x, mask=attn_mask, head_mask=head_mask)
VictorSanh's avatar
wip  
VictorSanh committed
311
        if self.output_attentions:
VictorSanh's avatar
VictorSanh committed
312
            sa_output, sa_weights = sa_output                  # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
VictorSanh's avatar
VictorSanh committed
313
314
        else: # To handle these `output_attention` or `output_hidden_states` cases returning tuples
            assert type(sa_output) == tuple
VictorSanh's avatar
VictorSanh committed
315
            sa_output = sa_output[0]
VictorSanh's avatar
wip  
VictorSanh committed
316
317
318
319
320
321
        sa_output = self.sa_layer_norm(sa_output + x)          # (bs, seq_length, dim)

        # Feed Forward Network
        ffn_output = self.ffn(sa_output)                             # (bs, seq_length, dim)
        ffn_output = self.output_layer_norm(ffn_output + sa_output)  # (bs, seq_length, dim)

VictorSanh's avatar
VictorSanh committed
322
        output = (ffn_output,)
VictorSanh's avatar
wip  
VictorSanh committed
323
        if self.output_attentions:
VictorSanh's avatar
VictorSanh committed
324
325
            output = (sa_weights,) + output
        return output
VictorSanh's avatar
wip  
VictorSanh committed
326

327

VictorSanh's avatar
wip  
VictorSanh committed
328
class Transformer(nn.Module):
LysandreJik's avatar
LysandreJik committed
329
    def __init__(self, config):
VictorSanh's avatar
wip  
VictorSanh committed
330
331
332
        super(Transformer, self).__init__()
        self.n_layers = config.n_layers
        self.output_attentions = config.output_attentions
VictorSanh's avatar
VictorSanh committed
333
        self.output_hidden_states = config.output_hidden_states
VictorSanh's avatar
wip  
VictorSanh committed
334

VictorSanh's avatar
VictorSanh committed
335
336
        layer = TransformerBlock(config)
        self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.n_layers)])
VictorSanh's avatar
wip  
VictorSanh committed
337

LysandreJik's avatar
LysandreJik committed
338
    def forward(self, x, attn_mask=None, head_mask=None):
VictorSanh's avatar
wip  
VictorSanh committed
339
340
341
342
        """
        Parameters
        ----------
        x: torch.tensor(bs, seq_length, dim)
VictorSanh's avatar
VictorSanh committed
343
            Input sequence embedded.
VictorSanh's avatar
wip  
VictorSanh committed
344
        attn_mask: torch.tensor(bs, seq_length)
VictorSanh's avatar
VictorSanh committed
345
346
347
348
349
350
351
352
353
354
355
356
            Attention mask on the sequence.

        Outputs
        -------
        hidden_state: torch.tensor(bs, seq_length, dim)
            Sequence of hiddens states in the last (top) layer
        all_hidden_states: Tuple[torch.tensor(bs, seq_length, dim)]
            Tuple of length n_layers with the hidden states from each layer.
            Optional: only if output_hidden_states=True
        all_attentions: Tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]
            Tuple of length n_layers with the attention weights from each layer
            Optional: only if output_attentions=True
VictorSanh's avatar
wip  
VictorSanh committed
357
        """
VictorSanh's avatar
VictorSanh committed
358
359
        all_hidden_states = ()
        all_attentions = ()
VictorSanh's avatar
wip  
VictorSanh committed
360

VictorSanh's avatar
VictorSanh committed
361
        hidden_state = x
362
363
364
365
366
367
368
369
370
        for i, layer_module in enumerate(self.layer):
            if self.output_hidden_states:
                all_hidden_states = all_hidden_states + (hidden_state,)

            layer_outputs = layer_module(x=hidden_state,
                                         attn_mask=attn_mask,
                                         head_mask=head_mask[i])
            hidden_state = layer_outputs[-1]

VictorSanh's avatar
wip  
VictorSanh committed
371
            if self.output_attentions:
372
373
                assert len(layer_outputs) == 2
                attentions = layer_outputs[0]
VictorSanh's avatar
VictorSanh committed
374
                all_attentions = all_attentions + (attentions,)
375
376
377
378
379
            else:
                assert len(layer_outputs) == 1

        # Add last layer
        if self.output_hidden_states:
VictorSanh's avatar
VictorSanh committed
380
            all_hidden_states = all_hidden_states + (hidden_state,)
VictorSanh's avatar
wip  
VictorSanh committed
381

VictorSanh's avatar
VictorSanh committed
382
383
384
        outputs = (hidden_state,)
        if self.output_hidden_states:
            outputs = outputs + (all_hidden_states,)
VictorSanh's avatar
wip  
VictorSanh committed
385
        if self.output_attentions:
VictorSanh's avatar
VictorSanh committed
386
            outputs = outputs + (all_attentions,)
387
        return outputs  # last-layer hidden state, (all hidden states), (all attentions)
VictorSanh's avatar
VictorSanh committed
388
389
390


### INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL ###
thomwolf's avatar
thomwolf committed
391
class DistilBertPreTrainedModel(PreTrainedModel):
VictorSanh's avatar
VictorSanh committed
392
393
394
    """ An abstract class to handle weights initialization and
        a simple interface for downloading and loading pretrained models.
    """
thomwolf's avatar
thomwolf committed
395
396
    config_class = DistilBertConfig
    pretrained_model_archive_map = DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP
VictorSanh's avatar
VictorSanh committed
397
    load_tf_weights = None
thomwolf's avatar
thomwolf committed
398
    base_model_prefix = "distilbert"
VictorSanh's avatar
VictorSanh committed
399
400

    def __init__(self, *inputs, **kwargs):
thomwolf's avatar
thomwolf committed
401
        super(DistilBertPreTrainedModel, self).__init__(*inputs, **kwargs)
VictorSanh's avatar
VictorSanh committed
402
    
403
    def _init_weights(self, module):
VictorSanh's avatar
VictorSanh committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
        """ Initialize the weights.
        """
        if isinstance(module, nn.Embedding):
            if module.weight.requires_grad:
                module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
        if isinstance(module, nn.Linear):
            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
        elif isinstance(module, nn.LayerNorm):
            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_()


thomwolf's avatar
thomwolf committed
418
419
DISTILBERT_START_DOCSTRING = r"""
    DistilBERT is a small, fast, cheap and light Transformer model
420
421
422
423
    trained by distilling Bert base. It has 40% less parameters than
    `bert-base-uncased`, runs 60% faster while preserving over 95% of
    Bert's performances as measured on the GLUE language understanding benchmark.

thomwolf's avatar
thomwolf committed
424
    Here are the differences between the interface of Bert and DistilBert:
425

LysandreJik's avatar
LysandreJik committed
426
    - DistilBert doesn't have `token_type_ids`, you don't need to indicate which token belongs to which segment. Just separate your segments with the separation token `tokenizer.sep_token` (or `[SEP]`)
thomwolf's avatar
thomwolf committed
427
    - DistilBert doesn't have options to select the input positions (`position_ids` input). This could be added if necessary though, just let's us know if you need this option.
VictorSanh's avatar
VictorSanh committed
428

thomwolf's avatar
thomwolf committed
429
    For more information on DistilBERT, please refer to our
430
431
432
    `detailed blog post`_
    
    .. _`detailed blog post`:
LysandreJik's avatar
LysandreJik committed
433
        https://medium.com/huggingface/distilbert-8cf3380435b5
VictorSanh's avatar
VictorSanh committed
434
435

    Parameters:
thomwolf's avatar
thomwolf committed
436
        config (:class:`~pytorch_transformers.DistilBertConfig`): Model configuration class with all the parameters of the model. 
VictorSanh's avatar
VictorSanh committed
437
438
439
440
            Initializing with a config file does not load the weights associated with the model, only the configuration.
            Check out the :meth:`~pytorch_transformers.PreTrainedModel.from_pretrained` method to load the model weights.
"""

thomwolf's avatar
thomwolf committed
441
DISTILBERT_INPUTS_DOCSTRING = r"""
VictorSanh's avatar
VictorSanh committed
442
    Inputs:
LysandreJik's avatar
LysandreJik committed
443
444
445
        **input_ids** ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
            Indices of input sequence tokens in the vocabulary.
            The input sequences should start with `[CLS]` and end with `[SEP]` tokens.
VictorSanh's avatar
VictorSanh committed
446
            
thomwolf's avatar
thomwolf committed
447
            For now, ONLY BertTokenizer(`bert-base-uncased`) is supported and you should use this tokenizer when using DistilBERT.
VictorSanh's avatar
VictorSanh committed
448
449
450
451
        **attention_mask**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
            Mask to avoid performing attention on padding token indices.
            Mask values selected in ``[0, 1]``:
            ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
452
453
454
455
        **head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:
            Mask to nullify selected heads of the self-attention modules.
            Mask values selected in ``[0, 1]``:
            ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.
VictorSanh's avatar
VictorSanh committed
456
457
"""

thomwolf's avatar
thomwolf committed
458
459
460
@add_start_docstrings("The bare DistilBERT encoder/transformer outputing raw hidden-states without any specific head on top.",
                      DISTILBERT_START_DOCSTRING, DISTILBERT_INPUTS_DOCSTRING)
class DistilBertModel(DistilBertPreTrainedModel):
VictorSanh's avatar
VictorSanh committed
461
    r"""
462
463
464
465
466
467
468
469
470
471
472
473
474
    Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
        **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``
            Sequence of hidden-states at the output of the last layer of the model.
        **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
            list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
            of shape ``(batch_size, sequence_length, hidden_size)``:
            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        **attentions**: (`optional`, returned when ``config.output_attentions=True``)
            list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

    Examples::

thomwolf's avatar
thomwolf committed
475
476
        tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
        model = DistilBertModel.from_pretrained('distilbert-base-uncased')
477
478
479
480
        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids)
        last_hidden_states = outputs[0]  # The last hidden-state is the first element of the output tuple

VictorSanh's avatar
VictorSanh committed
481
482
    """
    def __init__(self, config):
thomwolf's avatar
thomwolf committed
483
        super(DistilBertModel, self).__init__(config)
VictorSanh's avatar
VictorSanh committed
484
485
486
487

        self.embeddings = Embeddings(config)   # Embeddings
        self.transformer = Transformer(config) # Encoder

488
        self.init_weights()
VictorSanh's avatar
VictorSanh committed
489

490
491
492
493
494
495
496
497
498
499
500
501
502
503
    def _resize_token_embeddings(self, new_num_tokens):
        old_embeddings = self.embeddings.word_embeddings
        new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)
        self.embeddings.word_embeddings = new_embeddings
        return self.embeddings.word_embeddings

    def _prune_heads(self, heads_to_prune):
        """ Prunes heads of the model.
            heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
            See base class PreTrainedModel
        """
        for layer, heads in heads_to_prune.items():
            self.transformer.layer[layer].attention.prune_heads(heads)

VictorSanh's avatar
VictorSanh committed
504
    def forward(self,
LysandreJik's avatar
LysandreJik committed
505
                input_ids, attention_mask=None, head_mask=None):
VictorSanh's avatar
VictorSanh committed
506
507
        if attention_mask is None:
            attention_mask = torch.ones_like(input_ids) # (bs, seq_length)
VictorSanh's avatar
wip  
VictorSanh committed
508

509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
        # 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]
        if head_mask is not None:
            if head_mask.dim() == 1:
                head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
                head_mask = head_mask.expand(self.config.num_hidden_layers, -1, -1, -1, -1)
            elif head_mask.dim() == 2:
                head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)  # We can specify head_mask for each layer
            head_mask = head_mask.to(dtype=next(self.parameters()).dtype) # switch to fload if need + fp16 compatibility
        else:
            head_mask = [None] * self.config.num_hidden_layers

VictorSanh's avatar
VictorSanh committed
524
525
        embedding_output = self.embeddings(input_ids)   # (bs, seq_length, dim)
        tfmr_output = self.transformer(x=embedding_output,
526
527
                                       attn_mask=attention_mask,
                                       head_mask=head_mask)
VictorSanh's avatar
VictorSanh committed
528
        hidden_state = tfmr_output[0]
529
530
531
        output = (hidden_state, ) + tfmr_output[1:]

        return output # last-layer hidden-state, (all hidden_states), (all attentions)
VictorSanh's avatar
wip  
VictorSanh committed
532
533


thomwolf's avatar
thomwolf committed
534
535
536
@add_start_docstrings("""DistilBert Model with a `masked language modeling` head on top. """,
                      DISTILBERT_START_DOCSTRING, DISTILBERT_INPUTS_DOCSTRING)
class DistilBertForMaskedLM(DistilBertPreTrainedModel):
VictorSanh's avatar
VictorSanh committed
537
    r"""
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
        **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
            Labels for computing the masked language modeling loss.
            Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
            Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels
            in ``[0, ..., config.vocab_size]``

    Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
        **loss**: (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
            Masked language modeling loss.
        **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
            list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
            of shape ``(batch_size, sequence_length, hidden_size)``:
            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        **attentions**: (`optional`, returned when ``config.output_attentions=True``)
            list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

    Examples::

thomwolf's avatar
thomwolf committed
559
560
        tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
        model = DistilBertForMaskedLM.from_pretrained('distilbert-base-uncased')
561
562
563
        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids, masked_lm_labels=input_ids)
        loss, prediction_scores = outputs[:2]
VictorSanh's avatar
VictorSanh committed
564
565

    """
VictorSanh's avatar
VictorSanh committed
566
    def __init__(self, config):
thomwolf's avatar
thomwolf committed
567
        super(DistilBertForMaskedLM, self).__init__(config)
VictorSanh's avatar
VictorSanh committed
568
569
        self.output_attentions = config.output_attentions
        self.output_hidden_states = config.output_hidden_states
VictorSanh's avatar
wip  
VictorSanh committed
570

thomwolf's avatar
thomwolf committed
571
        self.distilbert = DistilBertModel(config)
VictorSanh's avatar
VictorSanh committed
572
573
574
575
        self.vocab_transform = nn.Linear(config.dim, config.dim)
        self.vocab_layer_norm = nn.LayerNorm(config.dim, eps=1e-12)
        self.vocab_projector = nn.Linear(config.dim, config.vocab_size)

576
        self.init_weights()
VictorSanh's avatar
VictorSanh committed
577
        self.tie_weights()
VictorSanh's avatar
VictorSanh committed
578
579
580

        self.mlm_loss_fct = nn.CrossEntropyLoss(ignore_index=-1)

VictorSanh's avatar
VictorSanh committed
581
    def tie_weights(self):
582
583
        """ Make sure we are sharing the input and output embeddings.
            Export to TorchScript can't handle parameter sharing so we are cloning them instead.
VictorSanh's avatar
VictorSanh committed
584
        """
585
        self._tie_or_clone_weights(self.vocab_projector,
thomwolf's avatar
thomwolf committed
586
                                   self.distilbert.embeddings.word_embeddings)
VictorSanh's avatar
VictorSanh committed
587

LysandreJik's avatar
LysandreJik committed
588
    def forward(self, input_ids, attention_mask=None, masked_lm_labels=None, head_mask=None):
thomwolf's avatar
thomwolf committed
589
        dlbrt_output = self.distilbert(input_ids=input_ids,
590
591
                                    attention_mask=attention_mask,
                                    head_mask=head_mask)
VictorSanh's avatar
VictorSanh committed
592
        hidden_states = dlbrt_output[0]                              # (bs, seq_length, dim)
VictorSanh's avatar
VictorSanh committed
593
594
595
596
597
        prediction_logits = self.vocab_transform(hidden_states)      # (bs, seq_length, dim)
        prediction_logits = gelu(prediction_logits)                  # (bs, seq_length, dim)
        prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
        prediction_logits = self.vocab_projector(prediction_logits)  # (bs, seq_length, vocab_size)

598
        outputs = (prediction_logits, ) + dlbrt_output[1:]
VictorSanh's avatar
VictorSanh committed
599
600
601
602
603
        if masked_lm_labels is not None:
            mlm_loss = self.mlm_loss_fct(prediction_logits.view(-1, prediction_logits.size(-1)),
                                         masked_lm_labels.view(-1))
            outputs = (mlm_loss,) + outputs     

604
605
        return outputs # (mlm_loss), prediction_logits, (all hidden_states), (all attentions)

VictorSanh's avatar
VictorSanh committed
606

thomwolf's avatar
thomwolf committed
607
@add_start_docstrings("""DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of
VictorSanh's avatar
VictorSanh committed
608
                         the pooled output) e.g. for GLUE tasks. """,
thomwolf's avatar
thomwolf committed
609
610
                      DISTILBERT_START_DOCSTRING, DISTILBERT_INPUTS_DOCSTRING)
class DistilBertForSequenceClassification(DistilBertPreTrainedModel):
VictorSanh's avatar
VictorSanh committed
611
    r"""
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
        **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
            Labels for computing the sequence classification/regression loss.
            Indices should be in ``[0, ..., config.num_labels - 1]``.
            If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss),
            If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy).

    Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
        **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
            Classification (or regression if config.num_labels==1) loss.
        **logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``
            Classification (or regression if config.num_labels==1) scores (before SoftMax).
        **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
            list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
            of shape ``(batch_size, sequence_length, hidden_size)``:
            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        **attentions**: (`optional`, returned when ``config.output_attentions=True``)
            list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

    Examples::

thomwolf's avatar
thomwolf committed
633
634
        tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
        model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased')
635
636
637
638
639
        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0)  # Batch size 1
        labels = torch.tensor([1]).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids, labels=labels)
        loss, logits = outputs[:2]

VictorSanh's avatar
VictorSanh committed
640
641
    """
    def __init__(self, config):
thomwolf's avatar
thomwolf committed
642
        super(DistilBertForSequenceClassification, self).__init__(config)
VictorSanh's avatar
VictorSanh committed
643
644
        self.num_labels = config.num_labels

thomwolf's avatar
thomwolf committed
645
        self.distilbert = DistilBertModel(config)
VictorSanh's avatar
VictorSanh committed
646
647
648
649
        self.pre_classifier = nn.Linear(config.dim, config.dim)
        self.classifier = nn.Linear(config.dim, config.num_labels)
        self.dropout = nn.Dropout(config.seq_classif_dropout)

650
        self.init_weights()
VictorSanh's avatar
VictorSanh committed
651

LysandreJik's avatar
LysandreJik committed
652
    def forward(self, input_ids,  attention_mask=None, labels=None, head_mask=None):
thomwolf's avatar
thomwolf committed
653
        distilbert_output = self.distilbert(input_ids=input_ids,
654
655
                                      attention_mask=attention_mask,
                                      head_mask=head_mask)
thomwolf's avatar
thomwolf committed
656
        hidden_state = distilbert_output[0]                    # (bs, seq_len, dim)
657
        pooled_output = hidden_state[:, 0]                    # (bs, dim)
VictorSanh's avatar
VictorSanh committed
658
659
660
661
662
        pooled_output = self.pre_classifier(pooled_output)   # (bs, dim)
        pooled_output = nn.ReLU()(pooled_output)             # (bs, dim)
        pooled_output = self.dropout(pooled_output)         # (bs, dim)
        logits = self.classifier(pooled_output)              # (bs, dim)

thomwolf's avatar
thomwolf committed
663
        outputs = (logits,) + distilbert_output[1:]
VictorSanh's avatar
VictorSanh committed
664
665
666
667
668
669
670
671
672
673
674
        if labels is not None:
            if self.num_labels == 1:
                loss_fct = nn.MSELoss()
                loss = loss_fct(logits.view(-1), labels.view(-1))
            else:
                loss_fct = nn.CrossEntropyLoss()
                loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
            outputs = (loss,) + outputs

        return outputs  # (loss), logits, (hidden_states), (attentions)

675

thomwolf's avatar
thomwolf committed
676
@add_start_docstrings("""DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of
VictorSanh's avatar
VictorSanh committed
677
                         the hidden-states output to compute `span start logits` and `span end logits`). """,
thomwolf's avatar
thomwolf committed
678
679
                      DISTILBERT_START_DOCSTRING, DISTILBERT_INPUTS_DOCSTRING)
class DistilBertForQuestionAnswering(DistilBertPreTrainedModel):
VictorSanh's avatar
VictorSanh committed
680
    r"""
681
        **start_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
VictorSanh's avatar
VictorSanh committed
682
683
684
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`).
            Position outside of the sequence are not taken into account for computing the loss.
685
        **end_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
VictorSanh's avatar
VictorSanh committed
686
687
688
689
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`).
            Position outside of the sequence are not taken into account for computing the loss.

690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
    Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
        **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
            Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
        **start_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``
            Span-start scores (before SoftMax).
        **end_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``
            Span-end scores (before SoftMax).
        **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
            list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
            of shape ``(batch_size, sequence_length, hidden_size)``:
            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        **attentions**: (`optional`, returned when ``config.output_attentions=True``)
            list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

    Examples::

thomwolf's avatar
thomwolf committed
707
708
        tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
        model = DistilBertForQuestionAnswering.from_pretrained('distilbert-base-uncased')
709
710
711
712
713
714
        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0)  # Batch size 1
        start_positions = torch.tensor([1])
        end_positions = torch.tensor([3])
        outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
        loss, start_scores, end_scores = outputs[:2]

VictorSanh's avatar
VictorSanh committed
715
716
    """
    def __init__(self, config):
thomwolf's avatar
thomwolf committed
717
        super(DistilBertForQuestionAnswering, self).__init__(config)
VictorSanh's avatar
VictorSanh committed
718

thomwolf's avatar
thomwolf committed
719
        self.distilbert = DistilBertModel(config)
VictorSanh's avatar
VictorSanh committed
720
721
722
723
        self.qa_outputs = nn.Linear(config.dim, config.num_labels)
        assert config.num_labels == 2
        self.dropout = nn.Dropout(config.qa_dropout)

724
        self.init_weights()
VictorSanh's avatar
VictorSanh committed
725
        
LysandreJik's avatar
LysandreJik committed
726
    def forward(self, input_ids, attention_mask=None, start_positions=None, end_positions=None, head_mask=None):
thomwolf's avatar
thomwolf committed
727
        distilbert_output = self.distilbert(input_ids=input_ids,
728
729
                                      attention_mask=attention_mask,
                                      head_mask=head_mask)
thomwolf's avatar
thomwolf committed
730
        hidden_states = distilbert_output[0]                                 # (bs, max_query_len, dim)
VictorSanh's avatar
VictorSanh committed
731

VictorSanh's avatar
wip  
VictorSanh committed
732
733
734
735
736
737
        hidden_states = self.dropout(hidden_states)                       # (bs, max_query_len, dim)
        logits = self.qa_outputs(hidden_states)                           # (bs, max_query_len, 2)
        start_logits, end_logits = logits.split(1, dim=-1)
        start_logits = start_logits.squeeze(-1)                           # (bs, max_query_len)
        end_logits = end_logits.squeeze(-1)                               # (bs, max_query_len)

thomwolf's avatar
thomwolf committed
738
        outputs = (start_logits, end_logits,) + distilbert_output[1:]
VictorSanh's avatar
wip  
VictorSanh committed
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
        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 = nn.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
            outputs = (total_loss,) + outputs

VictorSanh's avatar
VictorSanh committed
756
        return outputs  # (loss), start_logits, end_logits, (hidden_states), (attentions)