onnxbase.py 10.3 KB
Newer Older
W
wjj19950828 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2022  PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import os
W
wjj19950828 已提交
16 17
import sys
import importlib
W
wjj19950828 已提交
18 19 20 21
import numpy as np
import logging
import paddle
import onnx
W
wjj19950828 已提交
22
import shutil
W
wjj19950828 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
from onnx import helper
from onnx import TensorProto
from onnxruntime import InferenceSession

DTYPE_ONNX_STR_MAP = {
    'float32': TensorProto.FLOAT,
    'float64': TensorProto.DOUBLE,
    'int16': TensorProto.INT16,
    'int32': TensorProto.INT32,
    'int64': TensorProto.INT64,
    'bool': TensorProto.BOOL,
}


def compare(result, expect, delta=1e-10, rtol=1e-10):
    """
W
wjj19950828 已提交
39 40 41 42 43
    param meaning:
    result: onnx result
    expect: paddle result
    delta: absolute error
    rtol: relative error
W
wjj19950828 已提交
44 45 46 47 48 49
    """
    if type(result) == np.ndarray:
        if type(expect) == list:
            expect = expect[0]
        expect = np.array(expect)
        res = np.allclose(result, expect, atol=delta, rtol=rtol, equal_nan=True)
W
wjj19950828 已提交
50
        # print wrong results
W
wjj19950828 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
        if res is False:
            if result.dtype == np.bool_:
                diff = abs(result.astype("int32") - expect.astype("int32"))
            else:
                diff = abs(result - expect)
            logging.error("Output has diff! max diff: {}".format(np.amax(diff)))
        if result.dtype != expect.dtype:
            logging.error(
                "Different output data types! res type is: {}, and expect type is: {}".
                format(result.dtype, expect.dtype))
        assert res
        assert result.shape == expect.shape, "result.shape: {} != expect.shape: {}".format(
            result.shape, expect.shape)
        assert result.dtype == expect.dtype, "result.dtype: {} != expect.dtype: {}".format(
            result.dtype, expect.dtype)
W
wjj19950828 已提交
66
    elif isinstance(result, (list, tuple)):
W
wjj19950828 已提交
67 68 69 70 71
        for i in range(len(result)):
            if isinstance(result[i], (np.generic, np.ndarray)):
                compare(result[i], expect[i], delta, rtol)
            else:
                compare(result[i].numpy(), expect[i], delta, rtol)
W
wjj19950828 已提交
72 73 74
    # deal with scalar tensor
    elif len(expect) == 1:
        compare(result, expect[0], delta, rtol)
W
wjj19950828 已提交
75 76
    else:
        raise Exception("Compare diff wrong!!!!!!")
W
wjj19950828 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99


def randtool(dtype, low, high, shape):
    """
    np random tools
    """
    if dtype == "int":
        return np.random.randint(low, high, shape)

    elif dtype == "float":
        return low + (high - low) * np.random.random(shape)

    elif dtype == "bool":
        return np.random.randint(low, high, shape).astype("bool")


class ONNXConverter(object):
    """
     onnx model transfer to paddle
    """

    def __init__(self,
                 file_name,
W
wjj19950828 已提交
100 101
                 min_opset_version,
                 max_opset_version,
W
wjj19950828 已提交
102 103 104 105 106 107
                 op_type=[],
                 inputs_name=[],
                 outputs_name=[],
                 inputs_shape=[],
                 delta=1e-5,
                 rtol=1e-5,
W
wjj19950828 已提交
108
                 attrs=[],
W
wjj19950828 已提交
109
                 enable_onnx_checker=True,
W
wjj19950828 已提交
110
                 run_dynamic=False):
W
wjj19950828 已提交
111 112 113 114 115 116
        self.op_type = op_type
        assert isinstance(self.op_type,
                          str), "The dtype of op_type must be string!"
        self.seed = 33
        np.random.seed(self.seed)
        paddle.seed(self.seed)
W
wjj19950828 已提交
117
        self.places = ['cpu']
W
wjj19950828 已提交
118
        self.name = file_name
W
wjj19950828 已提交
119 120
        self.min_opset_version = min_opset_version
        self.max_opset_version = max_opset_version
W
wjj19950828 已提交
121 122 123 124 125 126 127 128 129 130 131
        self.pwd = os.getcwd()
        self.delta = delta
        self.rtol = rtol
        self.static = False
        self.kwargs_dict = {"input_data": ()}
        self.input_feed = {}
        self.inputs_dtype = []
        self.inputs_name = inputs_name
        self.outputs_name = outputs_name
        self.inputs_shape = inputs_shape
        self.attrs = attrs
W
wjj19950828 已提交
132
        self.enable_onnx_checker = enable_onnx_checker
W
wjj19950828 已提交
133
        self.run_dynamic = run_dynamic
W
wjj19950828 已提交
134 135 136 137 138 139 140 141 142 143

    def set_input_data(self, group_name, *args):
        """
        set input data
        """
        self.kwargs_dict[group_name] = args
        if isinstance(self.kwargs_dict[group_name][0], tuple):
            self.kwargs_dict[group_name] = self.kwargs_dict[group_name][0]

        i = 0
W
wjj19950828 已提交
144 145 146
        add_inputs_shape = False
        if len(self.inputs_shape) == 0:
            add_inputs_shape = True
W
wjj19950828 已提交
147 148 149 150 151
        for in_data in self.kwargs_dict[group_name]:
            if isinstance(in_data, list):
                for data in in_data:
                    self.inputs_dtype.append(str(data.dtype))
                    self.input_feed[self.inputs_name[i]] = data
W
wjj19950828 已提交
152 153
                    if add_inputs_shape:
                        self.inputs_shape.append(data.shape)
W
wjj19950828 已提交
154 155 156 157 158 159
                    i += 1
            else:
                if isinstance(in_data, tuple):
                    in_data = in_data[0]
                self.inputs_dtype.append(str(in_data.dtype))
                self.input_feed[self.inputs_name[i]] = in_data
W
wjj19950828 已提交
160 161
                if add_inputs_shape:
                    self.inputs_shape.append(in_data.shape)
W
wjj19950828 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
                i += 1

    def _mkdir(self):
        """
        make dir to save all
        """
        save_path = os.path.join(self.pwd, self.name)
        if not os.path.exists(save_path):
            os.mkdir(save_path)

    def _onnx_to_paddle(self, ver):
        """
        convert onnx to paddle
        """
        from x2paddle.convert import onnx2paddle
        onnx_path = os.path.join(self.pwd, self.name,
                                 self.name + '_' + str(ver) + '.onnx')
        paddle_path = os.path.join(self.pwd, self.name,
                                   self.name + '_' + str(ver) + '_paddle')
W
wjj19950828 已提交
181 182 183 184
        onnx2paddle(
            onnx_path,
            paddle_path,
            convert_to_lite=False,
W
wjj19950828 已提交
185 186
            enable_onnx_checker=self.enable_onnx_checker,
            disable_feedback=True)
W
wjj19950828 已提交
187 188 189 190 191

    def _mk_paddle_res(self, ver):
        """
        make paddle res
        """
W
wjj19950828 已提交
192 193
        # input data
        paddle_tensor_feed = list()
W
wjj19950828 已提交
194
        for i in range(len(self.input_feed)):
W
wjj19950828 已提交
195 196
            paddle_tensor_feed.append(
                paddle.to_tensor(self.input_feed[self.inputs_name[i]]))
W
wjj19950828 已提交
197 198

        if self.run_dynamic:
W
wjj19950828 已提交
199 200
            paddle_path = os.path.join(self.pwd, self.name,
                                       self.name + '_' + str(ver) + '_paddle/')
W
wjj19950828 已提交
201 202 203 204 205 206 207 208 209
            restore = paddle.load(os.path.join(paddle_path, "model.pdparams"))
            sys.path.insert(0, paddle_path)
            import x2paddle_code
            # Solve the problem of function overloading caused by traversing the model
            importlib.reload(x2paddle_code)
            model = getattr(x2paddle_code, "ONNXModel")()
            model.set_dict(restore)
            model.eval()
            result = model(*paddle_tensor_feed)
W
wjj19950828 已提交
210 211 212 213 214 215 216
        else:
            paddle_path = os.path.join(
                self.pwd, self.name,
                self.name + '_' + str(ver) + '_paddle/inference_model/model')
            paddle.disable_static()
            # run
            model = paddle.jit.load(paddle_path)
W
wjj19950828 已提交
217
            model.eval()
W
wjj19950828 已提交
218
            result = model(*paddle_tensor_feed)
W
wjj19950828 已提交
219
        shutil.rmtree(os.path.join(self.pwd, self.name))
W
wjj19950828 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        # get paddle outputs
        if isinstance(result, (tuple, list)):
            result = tuple(out.numpy() for out in result)
        else:
            result = (result.numpy(), )
        return result

    def _mk_onnx_res(self, ver):
        """
        make onnx res
        """
        sess = InferenceSession(
            os.path.join(self.pwd, self.name, self.name + '_' + str(ver) +
                         '.onnx'))
        ort_outs = sess.run(output_names=None, input_feed=self.input_feed)
        return ort_outs

    def set_onnx_inputs(self):
        graph_inputs = list()
        for i in range(len(self.inputs_name)):
            graph_inputs.append(
                helper.make_tensor_value_info(self.inputs_name[
                    i], DTYPE_ONNX_STR_MAP[self.inputs_dtype[i]],
                                              self.inputs_shape[i]))

        return graph_inputs

    def set_onnx_outputs(self):
        graph_outputs = list()
        for i in range(len(self.outputs_name)):
W
wjj19950828 已提交
250
            graph_outputs.append(onnx.ValueInfoProto(name=self.outputs_name[i]))
W
wjj19950828 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

        return graph_outputs

    def _mk_onnx_graph(self, ver):
        """
        make onnx graph
        """
        node = onnx.helper.make_node(
            self.op_type,
            inputs=self.inputs_name,
            outputs=self.outputs_name,
            **self.attrs, )
        graph_inputs = self.set_onnx_inputs()
        graph_outputs = self.set_onnx_outputs()
        graph = helper.make_graph(
            [node],
            self.name,
            graph_inputs,  # graph inputs
            graph_outputs,  # graph outputs
        )
        opset_imports = [helper.make_opsetid("", ver)]
        model = helper.make_model(
            graph, producer_name='onnx-example', opset_imports=opset_imports)
W
wjj19950828 已提交
274
        model = onnx.shape_inference.infer_shapes(model)
W
wjj19950828 已提交
275 276 277
        onnx.save(model,
                  os.path.join(self.pwd, self.name,
                               self.name + '_' + str(ver) + '.onnx'))
W
wjj19950828 已提交
278 279
        if self.enable_onnx_checker:
            onnx.checker.check_model(model)
W
wjj19950828 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293

    def run(self):
        """
        1. make onnx model
        2. convert onnx to paddle
        3. use onnx to make res
        4. compare diff
        """
        self._mkdir()
        for place in self.places:
            paddle.set_device(place)
            onnx_res = {}
            paddle_res = {}
            # export onnx models and make onnx res
W
wjj19950828 已提交
294
            for v in range(self.min_opset_version, self.max_opset_version + 1):
W
wjj19950828 已提交
295 296 297 298 299 300 301 302 303
                self._mk_onnx_graph(ver=v)
                self._onnx_to_paddle(ver=v)
                onnx_res[str(v)] = self._mk_onnx_res(ver=v)
                paddle_res[str(v)] = self._mk_paddle_res(ver=v)
                compare(
                    onnx_res[str(v)],
                    paddle_res[str(v)],
                    delta=self.delta,
                    rtol=self.rtol)