accuracy_checker.py 12.4 KB
Newer Older
kahmed10's avatar
kahmed10 committed
1
2
3
#####################################################################################
# The MIT License (MIT)
#
4
# Copyright (c) 2015-2023 Advanced Micro Devices, Inc. All rights reserved.
kahmed10's avatar
kahmed10 committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#####################################################################################
import argparse
import numpy as np
import migraphx
import onnxruntime as ort
28
import sys
kahmed10's avatar
kahmed10 committed
29
30
31
32
33
34
35
36


def parse_args():
    parser = argparse.ArgumentParser(
        description=
        'MIGraphX accuracy checker. Use to verify onnx files to ensure MIGraphX\'s output \
                                                  is within tolerance of onnx runtime\'s expected output.'
    )
37
38
39
40
41
42
43
    file_args = parser.add_argument_group(title='file type arguments')
    file_args.add_argument('--onnx', type=str, help='path to onnx file')
    file_args.add_argument('--tf', type=str, help='path to tf pb file')
    parser.add_argument('--provider',
                        type=str,
                        default='CPUExecutionProvider',
                        help='execution provider for onnx runtime \
kahmed10's avatar
kahmed10 committed
44
45
46
47
48
49
50
51
                                (default = CPUExecutionProvider)')
    parser.add_argument('--batch',
                        type=int,
                        default=1,
                        help='batch size (if specified in onnx file)')
    parser.add_argument('--fill1',
                        action='store_true',
                        help='fill all arguments with a value of 1')
52
53
54
    parser.add_argument('--fill0',
                        action='store_true',
                        help='fill all arguments with a value of 0')
55
56
57
58
59
60
    parser.add_argument('--fp16',
                        action='store_true',
                        help='quantize MIGraphX model to fp16')
    parser.add_argument('--argmax',
                        action='store_true',
                        help='use argmax for accuracy')
kahmed10's avatar
kahmed10 committed
61
62
63
64
65
66
67
    parser.add_argument('--verbose',
                        action='store_true',
                        help='show verbose information (for debugging)')
    parser.add_argument('--tolerance',
                        type=float,
                        default=1e-3,
                        help='accuracy tolerance (default = 1e-3)')
68
69
70
71
    parser.add_argument('--input-dim',
                        type=str,
                        action='append',
                        help='specify input parameter dimension \
72
                                with the following format --input-dim input_name:dim0,dim1,dim2...'
73
                        )
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
    parser.add_argument('--target',
                        type=str,
                        default='gpu',
                        help='target to compile and run MIGraphX on')

    parser.add_argument('--ort-run',
                        dest="ort_run",
                        action='store_true',
                        default=False,
                        help='only perform an onnxruntime run')

    parser.add_argument('--ort-logging',
                        dest="ort_logging",
                        action='store_true',
                        default=False,
                        help='Turn on ort VERBOSE logging via session options')

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    parser.add_argument(
        '--disable-offload-copy',
        dest="offload_copy",
        action='store_false',
        default=True,
        help=
        'Disable offload copying (user must handle copy to and from device)')

    parser.add_argument(
        '--disable-fast-math',
        dest="fast_math",
        action='store_false',
        default=True,
        help='Disable fast math optimizations (etc: rewrite_gelu)')

    parser.add_argument('--exhaustive_tune',
                        dest="exhaustive_tune",
                        action='store_true',
                        default=False,
                        help='Enable exhaustive tuning for solutions')

kahmed10's avatar
kahmed10 committed
112
113
    args = parser.parse_args()

114
    return args, parser
kahmed10's avatar
kahmed10 committed
115
116
117
118
119
120
121


# taken from ../test_runner.py
def check_correctness(gold_outputs,
                      outputs,
                      rtol=1e-3,
                      atol=1e-3,
122
                      use_argmax=False,
kahmed10's avatar
kahmed10 committed
123
124
125
126
127
128
129
130
                      verbose=False):
    if len(gold_outputs) != len(outputs):
        print('Number of outputs {} is not equal to expected number {}'.format(
            len(outputs), len(gold_outputs)))
        return False

    out_num = len(gold_outputs)
    ret = True
131
132
133
134
135
136

    if not use_argmax:
        for i in range(out_num):
            if not np.allclose(gold_outputs[i], outputs[i], rtol, atol):
                ret = False
                if verbose:
137
138
                    with np.printoptions(threshold=np.inf):
                        print('\nOutput {} is incorrect ...'.format(i))
charlie's avatar
charlie committed
139
140
141
142
143
144
145
                        #print('Expected value: \n{}'.format(gold_outputs[i]))
                        #print('\n......\n')
                        #print('Actual value: \n{}\n'.format(outputs[i]))
                        diff = gold_outputs[i] - outputs[i]
                        #print(f'Difference: {diff}')
                        max_diff = np.max(np.abs(diff))
                        print(f'Max Difference: {max_diff}')
146
147
148
149
150
151
152
                else:
                    print('Outputs do not match')
                    break
    else:
        golden_argmax = np.argmax(gold_outputs)
        actual_argmax = np.argmax(outputs)
        if actual_argmax != golden_argmax:
kahmed10's avatar
kahmed10 committed
153
            ret = False
154
            print('\nOutput argmax is incorrect ...')
kahmed10's avatar
kahmed10 committed
155
            if verbose:
156
                print('Expected argmax value: \n{}'.format(golden_argmax))
kahmed10's avatar
kahmed10 committed
157
                print('......')
158
                print('Actual argmax value: \n{}\n'.format(actual_argmax))
kahmed10's avatar
kahmed10 committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    return ret


def get_np_datatype(in_type):
    datatypes = {
        'double_type': np.float64,
        'float_type': np.float32,
        'half_type': np.half,
        'int64_type': np.int64,
        'uint64_type': np.uint64,
        'int32_type': np.int32,
        'uint32_type': np.uint32,
        'int16_type': np.int16,
        'uint16_type': np.uint16,
        'int8_type': np.int8,
        'uint8_type': np.uint8,
175
        'bool_type': bool
kahmed10's avatar
kahmed10 committed
176
177
178
179
180
    }
    return datatypes[in_type]


def main():
181
    args, parser = parse_args()
kahmed10's avatar
kahmed10 committed
182

183
184
185
186
187
    use_onnx = True
    if args.onnx == None:
        use_onnx = False
    if not use_onnx and args.tf == None:
        print('Error: please specify either an onnx or tf pb file')
188
        parser.print_help()
189
190
        sys.exit(-1)

kahmed10's avatar
kahmed10 committed
191
    model_name = args.onnx
192

kahmed10's avatar
kahmed10 committed
193
194
    batch = args.batch

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    custom_inputs = args.input_dim

    input_dims = {}
    if custom_inputs != None:
        for input in custom_inputs:
            input_dim = ''.join(input.split(':')[:-1])
            dims = [int(dim) for dim in input.split(':')[-1].split(',')]
            input_dims[input_dim] = dims

    if use_onnx:
        if not input_dims:
            model = migraphx.parse_onnx(model_name, default_dim_value=batch)
        else:
            model = migraphx.parse_onnx(model_name,
                                        default_dim_value=batch,
                                        map_input_dims=input_dims)
    else:
        model_name = args.tf

        if not input_dims:
            model = migraphx.parse_tf(model_name, batch_size=batch)
        else:
            model = migraphx.parse_tf(model_name,
                                      batch_size=batch,
                                      map_input_dims=input_dims)
kahmed10's avatar
kahmed10 committed
220

221
222
223
    if (args.fp16):
        migraphx.quantize_fp16(model)

224
225
226
    if args.verbose:
        print(model)

227
    if not args.ort_run:
228
229
230
231
232
233
        model.compile(
            migraphx.get_target(args.target),
            offload_copy=args.offload_copy,
            fast_math=args.fast_math,
            exhaustive_tune=args.exhaustive_tune,
        )
kahmed10's avatar
kahmed10 committed
234
235
236
237
238

    params = {}
    test_inputs = {}
    for name, shape in model.get_parameter_shapes().items():
        if args.verbose:
239
            print(f'Parameter {name} -> {shape}')
kahmed10's avatar
kahmed10 committed
240
241
        in_shape = shape.lens()
        in_type = shape.type_string()
242
        if not args.fill1 and not args.fill0:
kahmed10's avatar
kahmed10 committed
243
244
            test_input = np.random.rand(*(in_shape)).astype(
                get_np_datatype(in_type))
245
        elif not args.fill0:
kahmed10's avatar
kahmed10 committed
246
            test_input = np.ones(in_shape).astype(get_np_datatype(in_type))
247
248
        else:
            test_input = np.zeros(in_shape).astype(get_np_datatype(in_type))
kahmed10's avatar
kahmed10 committed
249
        test_inputs[name] = test_input
250
251
252
253
        migraphx_arg = migraphx.argument(test_input)
        if not args.offload_copy:
            migraphx_arg = migraphx.to_gpu(migraphx_arg)
        params[name] = migraphx_arg
254

255
    if not args.ort_run:
256
257
258
259
        if not args.offload_copy:
            pred_migx = np.array(migraphx.from_gpu(model.run(params)[-1]))
        else:
            pred_migx = np.array(model.run(params)[-1])
kahmed10's avatar
kahmed10 committed
260

261
    if use_onnx:
262
263
264
265
266
267
268
269
270
        sess_op = ort.SessionOptions()

        if args.ort_logging:
            sess_op.log_verbosity_level = 0
            sess_op.log_severity_level = 0

        sess = ort.InferenceSession(model_name,
                                    sess_options=sess_op,
                                    providers=[args.provider])
kahmed10's avatar
kahmed10 committed
271

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        ort_params = {}
        for input in sess.get_inputs():
            ort_params[input.name] = test_inputs[input.name]

        try:
            pred_fw = sess.run(None, ort_params)[-1]
        except Exception as e:
            if any(input_dims):
                print(
                    'Error: custom input dim may not be compatible with onnx runtime'
                )
            raise e
    else:
        import tensorflow as tf

        def load_tf_graph(model_name):
            with tf.io.gfile.GFile(model_name, 'rb') as f:
                graph_def = tf.compat.v1.GraphDef()
                graph_def.ParseFromString(f.read())

            with tf.compat.v1.Graph().as_default() as graph:
                tf.graph_util.import_graph_def(graph_def)
            return graph

        graph = load_tf_graph(model_name)
        is_nhwc = False
        graph_ops = []
        for op in graph.get_operations():
            graph_ops.append(op.name)
            if 'Conv' in op.node_def.op:
                if 'NHWC' in op.get_attr('data_format').decode('utf-8'):
                    is_nhwc = True
        graph_ops_set = set(graph_ops)
        tf_dict = {}

        for name in test_inputs.keys():
            # graph.get_operations() adds 'import/' to the op name
            tf_name = f'import/{name}'
            if tf_name not in graph_ops_set:
                continue
            x = graph.get_tensor_by_name(f'{tf_name}:0')
            tf_input = test_inputs[name]
            # transpose input for NHWC model
            if tf_input.ndim == 4 and is_nhwc:
                tf_dict[x] = np.transpose(tf_input, (0, 2, 3, 1))
            else:
                tf_dict[x] = tf_input
kahmed10's avatar
kahmed10 committed
319

320
321
322
        # assume last node in graph is output
        # TODO: let user specify op name for output
        y = graph.get_tensor_by_name(f'{graph_ops[-1]}:0')
kahmed10's avatar
kahmed10 committed
323

324
325
326
        with tf.compat.v1.Session(graph=graph) as sess:
            y_out = sess.run(y, feed_dict=tf_dict)
            pred_fw = y_out
kahmed10's avatar
kahmed10 committed
327

328
329
    if not args.ort_run:
        is_correct = check_correctness(pred_fw, pred_migx, args.tolerance,
330
331
                                       args.tolerance, args.argmax,
                                       args.verbose)
332
333
334
335
336
337
        verbose_string = ' Rerun with --verbose for detailed information.' \
                if not args.verbose else ''
        if is_correct:
            print('PASSED: MIGraphX meets tolerance')
        else:
            print('FAILED: MIGraphX is not within tolerance.' + verbose_string)
kahmed10's avatar
kahmed10 committed
338
339
340
341


if __name__ == '__main__':
    main()