pytorch2mlmodel.py 5.22 KB
Newer Older
1
# Copyright (c) OpenMMLab. All rights reserved.
unknown's avatar
unknown committed
2
3
4
import argparse
import os
import os.path as osp
5
import warnings
unknown's avatar
unknown committed
6
7
8
9
10
11
12
13
14
15
16
17
from functools import partial

import mmcv
import numpy as np
import torch
from mmcv.runner import load_checkpoint
from torch import nn

from mmcls.models import build_classifier

torch.manual_seed(3)

18
19
20
21
22
try:
    import coremltools as ct
except ImportError:
    raise ImportError('Please install coremltools to enable output file.')

unknown's avatar
unknown committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

def _demo_mm_inputs(input_shape: tuple, num_classes: int):
    """Create a superset of inputs needed to run test or train batches.

    Args:
        input_shape (tuple):
            input batch dimensions
        num_classes (int):
            number of semantic classes
    """
    (N, C, H, W) = input_shape
    rng = np.random.RandomState(0)
    imgs = rng.rand(*input_shape)
    gt_labels = rng.randint(
        low=0, high=num_classes, size=(N, 1)).astype(np.uint8)
    mm_inputs = {
        'imgs': torch.FloatTensor(imgs).requires_grad_(False),
        'gt_labels': torch.LongTensor(gt_labels),
    }
    return mm_inputs


45
46
47
48
49
50
def pytorch2mlmodel(model: nn.Module, input_shape: tuple, output_file: str,
                    add_norm: bool, norm: dict):
    """Export Pytorch model to mlmodel format that can be deployed in apple
    devices through torch.jit.trace and the coremltools library.

       Optionally, embed the normalization step as a layer to the model.
unknown's avatar
unknown committed
51
52
53
54
55
56
57
58

    Args:
        model (nn.Module): Pytorch model we want to export.
        input_shape (tuple): Use this input shape to construct
            the corresponding dummy input and execute the model.
        show (bool): Whether print the computation graph. Default: False.
        output_file (string): The path to where we store the output
            TorchScript model.
59
60
61
62
        add_norm (bool): Whether to embed the normalization layer to the
            output model.
        norm (dict): image normalization config for embedding it as a layer
            to the output model.
unknown's avatar
unknown committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    """
    model.cpu().eval()

    num_classes = model.head.num_classes
    mm_inputs = _demo_mm_inputs(input_shape, num_classes)

    imgs = mm_inputs.pop('imgs')
    img_list = [img[None, :] for img in imgs]
    model.forward = partial(model.forward, img_metas={}, return_loss=False)

    with torch.no_grad():
        trace_model = torch.jit.trace(model, img_list[0])
        save_dir, _ = osp.split(output_file)
        if save_dir:
            os.makedirs(save_dir, exist_ok=True)

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
        if add_norm:
            means, stds = norm.mean, norm.std
            if stds.count(stds[0]) != len(stds):
                warnings.warn(f'Image std from config is {stds}. However, '
                              'current version of coremltools (5.1) uses a '
                              'global std rather than the channel-specific '
                              'values that torchvision uses. A mean will be '
                              'taken but this might tamper with the resulting '
                              'model\'s predictions. For more details refer '
                              'to the coreml docs on ImageType pre-processing')
                scale = np.mean(stds)
            else:
                scale = stds[0]

            bias = [-mean / scale for mean in means]
            image_input = ct.ImageType(
                name='input_1',
                shape=input_shape,
                scale=1 / scale,
                bias=bias,
                color_layout='RGB',
                channel_first=True)

            coreml_model = ct.convert(trace_model, inputs=[image_input])
            coreml_model.save(output_file)
        else:
            coreml_model = ct.convert(
                trace_model, inputs=[ct.TensorType(shape=input_shape)])
            coreml_model.save(output_file)

        print(f'Successfully exported coreml model: {output_file}')
unknown's avatar
unknown committed
110
111
112
113


def parse_args():
    parser = argparse.ArgumentParser(
114
        description='Convert MMCls to MlModel format for apple devices')
unknown's avatar
unknown committed
115
116
    parser.add_argument('config', help='test config file path')
    parser.add_argument('--checkpoint', help='checkpoint file', type=str)
117
    parser.add_argument('--output-file', type=str, default='model.mlmodel')
unknown's avatar
unknown committed
118
119
120
121
122
123
    parser.add_argument(
        '--shape',
        type=int,
        nargs='+',
        default=[224, 224],
        help='input image size')
124
125
126
127
    parser.add_argument(
        '--add-norm-layer',
        action='store_true',
        help='embed normalization layer to deployed model')
unknown's avatar
unknown committed
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
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    args = parse_args()

    if len(args.shape) == 1:
        input_shape = (1, 3, args.shape[0], args.shape[0])
    elif len(args.shape) == 2:
        input_shape = (
            1,
            3,
        ) + tuple(args.shape)
    else:
        raise ValueError('invalid input shape')

    cfg = mmcv.Config.fromfile(args.config)
    cfg.model.pretrained = None

    # build the model and load checkpoint
    classifier = build_classifier(cfg.model)

    if args.checkpoint:
        load_checkpoint(classifier, args.checkpoint, map_location='cpu')

154
155
    # convert model to mlmodel file
    pytorch2mlmodel(
unknown's avatar
unknown committed
156
157
158
        classifier,
        input_shape,
        output_file=args.output_file,
159
160
        add_norm=args.add_norm_layer,
        norm=cfg.img_norm_cfg)