"vscode:/vscode.git/clone" did not exist on "cbcd5579d4e6688715d1c3258a7e6d2c5540dd10"
extract_for_distil.py 4.7 KB
Newer Older
VictorSanh's avatar
VictorSanh committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# coding=utf-8
# Copyright 2019-present, the HuggingFace Inc. team.
#
# 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
16
Preprocessing script before training DistilBERT.
VictorSanh's avatar
VictorSanh committed
17
"""
thomwolf's avatar
thomwolf committed
18
from transformers import BertForMaskedLM, RobertaForMaskedLM
19
20
21
22
import torch
import argparse

if __name__ == '__main__':
23
24
25
26
    parser = argparse.ArgumentParser(description="Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned Distillation")
    parser.add_argument("--model_type", default="bert", choices=["bert", "roberta"])
    parser.add_argument("--model_name", default='bert-base-uncased', type=str)
    parser.add_argument("--dump_checkpoint", default='serialization_dir/tf_bert-base-uncased_0247911.pth', type=str)
27
28
29
30
    parser.add_argument("--vocab_transform", action='store_true')
    args = parser.parse_args()


31
32
33
34
35
36
    if args.model_type == 'bert':
        model = BertForMaskedLM.from_pretrained(args.model_name)
        prefix = 'bert'
    elif args.model_type == 'roberta':
        model = RobertaForMaskedLM.from_pretrained(args.model_name)
        prefix = 'roberta'
37
38
39
40
41

    state_dict = model.state_dict()
    compressed_sd = {}

    for w in ['word_embeddings', 'position_embeddings']:
thomwolf's avatar
thomwolf committed
42
        compressed_sd[f'distilbert.embeddings.{w}.weight'] = \
43
            state_dict[f'{prefix}.embeddings.{w}.weight']
44
    for w in ['weight', 'bias']:
thomwolf's avatar
thomwolf committed
45
        compressed_sd[f'distilbert.embeddings.LayerNorm.{w}'] = \
46
            state_dict[f'{prefix}.embeddings.LayerNorm.{w}']
47
48
49
50

    std_idx = 0
    for teacher_idx in [0, 2, 4, 7, 9, 11]:
        for w in ['weight', 'bias']:
thomwolf's avatar
thomwolf committed
51
            compressed_sd[f'distilbert.transformer.layer.{std_idx}.attention.q_lin.{w}'] = \
52
                state_dict[f'{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}']
thomwolf's avatar
thomwolf committed
53
            compressed_sd[f'distilbert.transformer.layer.{std_idx}.attention.k_lin.{w}'] = \
54
                state_dict[f'{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}']
thomwolf's avatar
thomwolf committed
55
            compressed_sd[f'distilbert.transformer.layer.{std_idx}.attention.v_lin.{w}'] = \
56
                state_dict[f'{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}']
57

thomwolf's avatar
thomwolf committed
58
            compressed_sd[f'distilbert.transformer.layer.{std_idx}.attention.out_lin.{w}'] = \
59
                state_dict[f'{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}']
thomwolf's avatar
thomwolf committed
60
            compressed_sd[f'distilbert.transformer.layer.{std_idx}.sa_layer_norm.{w}'] = \
61
                state_dict[f'{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}']
62

thomwolf's avatar
thomwolf committed
63
            compressed_sd[f'distilbert.transformer.layer.{std_idx}.ffn.lin1.{w}'] = \
64
                state_dict[f'{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}']
thomwolf's avatar
thomwolf committed
65
            compressed_sd[f'distilbert.transformer.layer.{std_idx}.ffn.lin2.{w}'] = \
66
                state_dict[f'{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}']
thomwolf's avatar
thomwolf committed
67
            compressed_sd[f'distilbert.transformer.layer.{std_idx}.output_layer_norm.{w}'] = \
68
                state_dict[f'{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}']
69
70
        std_idx += 1

71
72
73
74
75
76
77
78
79
80
81
82
83
84
    if args.model_type == 'bert':
        compressed_sd[f'vocab_projector.weight'] = state_dict[f'cls.predictions.decoder.weight']
        compressed_sd[f'vocab_projector.bias'] = state_dict[f'cls.predictions.bias']
        if args.vocab_transform:
            for w in ['weight', 'bias']:
                compressed_sd[f'vocab_transform.{w}'] = state_dict[f'cls.predictions.transform.dense.{w}']
                compressed_sd[f'vocab_layer_norm.{w}'] = state_dict[f'cls.predictions.transform.LayerNorm.{w}']
    elif args.model_type == 'roberta':
        compressed_sd[f'vocab_projector.weight'] = state_dict[f'lm_head.decoder.weight']
        compressed_sd[f'vocab_projector.bias'] = state_dict[f'lm_head.bias']
        if args.vocab_transform:
            for w in ['weight', 'bias']:
                compressed_sd[f'vocab_transform.{w}'] = state_dict[f'lm_head.dense.{w}']
                compressed_sd[f'vocab_layer_norm.{w}'] = state_dict[f'lm_head.layer_norm.{w}']
85
86
87
88
89
90

    print(f'N layers selected for distillation: {std_idx}')
    print(f'Number of params transfered for distillation: {len(compressed_sd.keys())}')

    print(f'Save transfered checkpoint to {args.dump_checkpoint}.')
    torch.save(compressed_sd, args.dump_checkpoint)