PyTorch
ssl-aasist
custom_code
File size: 4,966 Bytes
b1b22fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import argparse
import torch

from omegaconf import OmegaConf

from fairseq.criterions.model_criterion import ModelCriterionConfig
from fairseq.dataclass.configs import FairseqConfig

from tasks import ImageClassificationConfig, ImagePretrainingConfig
from models.data2vec_image_classification import (
    Data2VecImageClassificationConfig,
    Data2VecImageClassificationModel,
)
from models.data2vec_vision import Data2VecVisionConfig, Data2VecVisionModel


def get_parser():
    parser = argparse.ArgumentParser(
        description="convert beit checkpoint into data2vec - vision checkpoint"
    )
    # fmt: off
    parser.add_argument('checkpoint', help='checkpoint to convert')
    parser.add_argument('--output', required=True, metavar='PATH', help='where to output converted checkpoint')
    parser.add_argument('--type', type=str, choices=['vision', 'image_classification'], default='image_classification', help='type of model to upgrade')
    parser.add_argument('--inception_norms', action='store_true', default=False)
    # fmt: on

    return parser


def update_checkpoint(model_dict, prefix, is_nested):

    replace_paths = {
        "cls_token": "model.cls_emb" if is_nested else "cls_emb",
        "patch_embed": "model.patch_embed" if is_nested else "patch_embed",
        "mask_token": "mask_emb",
    }

    starts_with = {
        "patch_embed.proj": "model.patch_embed.conv"
        if is_nested
        else "patch_embed.conv",
        "lm_head": "final_proj",
        "fc_norm": "fc_norm",
        "head": "head",
    }

    partial = {
        "mlp.fc1": "mlp.0",
        "mlp.fc2": "mlp.2",
    }

    for k in list(model_dict.keys()):
        for sw, r in starts_with.items():
            if k.startswith(sw):
                replace_paths[k] = k.replace(sw, r)
        for p, r in partial.items():
            if p in k:
                replace_paths[k] = prefix + k.replace(p, r)

    if prefix != "":
        for k in list(model_dict.keys()):
            if k not in replace_paths:
                replace_paths[k] = prefix + k

    for k in list(model_dict.keys()):
        if k in replace_paths:
            model_dict[replace_paths[k]] = model_dict[k]
            if k != replace_paths[k]:
                del model_dict[k]

    return model_dict


def main():
    parser = get_parser()
    args = parser.parse_args()

    cp = torch.load(args.checkpoint, map_location="cpu")

    cfg = FairseqConfig(
        criterion=ModelCriterionConfig(_name="model", log_keys=["correct"]),
    )

    if args.type == "image_classification":

        cfg.task = ImageClassificationConfig(
            _name="image_classification",
            data=".",
        )

        if args.inception_norms:
            cfg.task.normalization_mean = [0.5, 0.5, 0.5]
            cfg.task.normalization_std = [0.5, 0.5, 0.5]

        cfg.model = Data2VecImageClassificationConfig(
            _name="data2vec_image_classification",
        )
        cfg.model.pretrained_model_args = FairseqConfig(
            model=Data2VecVisionConfig(
                _name="data2vec_vision", shared_rel_pos_bias=False
            ),
            task=ImagePretrainingConfig(
                _name="image_pretraining",
            ),
        )

        cfg = OmegaConf.create(cfg)

        state = {
            "cfg": OmegaConf.to_container(cfg, resolve=True, enum_to_str=True),
            "model": cp["module"],
            "best_loss": None,
            "optimizer": None,
            "extra_state": {},
        }

        model = Data2VecImageClassificationModel(cfg.model)
        model.load_state_dict(
            update_checkpoint(state["model"], prefix="model.encoder.", is_nested=True),
            strict=True,
        )
    elif args.type == "vision":
        cfg.task = ImagePretrainingConfig(
            _name="image_pretraining",
            data=".",
        )

        if args.inception_norms:
            cfg.task.normalization_mean = [0.5, 0.5, 0.5]
            cfg.task.normalization_std = [0.5, 0.5, 0.5]

        cfg.model = Data2VecVisionConfig(
            _name="data2vec_vision",
        )
        cfg = OmegaConf.create(cfg)

        state = {
            "cfg": OmegaConf.to_container(cfg, resolve=True, enum_to_str=True),
            "model": cp["model"],
            "best_loss": None,
            "optimizer": None,
            "extra_state": {},
        }

        model = Data2VecVisionModel(cfg.model)
        model.load_state_dict(
            update_checkpoint(state["model"], prefix="encoder.", is_nested=False),
            strict=True,
        )
    else:
        raise Exception("unsupported type " + args.type)

    print(state["cfg"], state.keys())
    torch.save(state, args.output)


if __name__ == "__main__":
    main()