def test_mean_values_with_data_name(self):
        graph_ref = build_graph(nodes, [
            *connect('parameter', '0:add_mean'),
            *connect('mean', '1:add_mean'),
            *connect('add_mean', 'result'),
        ])

        mean_values = parse_tuple_pairs('(1,2,3)')
        scale_values = parse_tuple_pairs('')
        mean_scale = get_mean_scale_dictionary(mean_values, scale_values, None)
        argv = Namespace(mean_scale_values=mean_scale)

        graph = build_graph(nodes, [*connect('parameter', 'result')],
                            nodes_with_edges_only=True,
                            cli=argv)
        self.set_graph_attrs(graph, ['parameter'])
        self.set_graph_attrs(graph_ref, ['parameter'])
        graph.graph['layout'] = 'NCHW'

        AddMeanScaleValues().find_and_replace_pattern(graph)
        (flag, resp) = compare_graphs(graph,
                                      graph_ref,
                                      'result',
                                      check_op_attrs=True)
        self.assertTrue(flag, resp)
        self.check_graph_attrs(graph, graph_ref, ['parameter'])
Esempio n. 2
0
 def test_scale_only_no_input(self):
     scale_values = "(1.1,22.22,333.333)"
     mean_values = ""
     mean = parse_tuple_pairs(mean_values)
     scale = parse_tuple_pairs(scale_values)
     result = get_mean_scale_dictionary(mean, scale, None)
     exp_res = [[None, np.array([1.1, 22.22, 333.333])]]
     for i in range(len(exp_res)):
         for j in range(len(exp_res[i])):
             if type(exp_res[i][j]) is np.ndarray:
                 npt.assert_array_equal(exp_res[i][j], result[i][j])
             else:
                 self.assertEqual(exp_res[i][j], result[i][j])
Esempio n. 3
0
 def test_mean_only_input(self):
     mean_values = "data(1.1,22.22,333.333)"
     result = get_mean_scale_dictionary(parse_tuple_pairs(mean_values),
                                        parse_tuple_pairs(''), None)
     exp_res = {
         'data': {
             'mean': np.array([1.1, 22.22, 333.333]),
             'scale': None
         }
     }
     for input in exp_res.keys():
         for key in exp_res[input].keys():
             if type(exp_res[input][key]) is np.ndarray:
                 npt.assert_array_equal(exp_res[input][key],
                                        result[input][key])
             else:
                 self.assertEqual(exp_res[input][key], result[input][key])
Esempio n. 4
0
 def test_tuple_parser_no_inputs(self):
     tuple_values = "(1.1,22.22,333.333),[2.2,33.33,444.444]"
     result = parse_tuple_pairs(tuple_values)
     exp_res = [
         np.array([1.1, 22.22, 333.333]),
         np.array([2.2, 33.33, 444.444])
     ]
     for i in range(0, len(exp_res)):
         npt.assert_array_equal(result[i], exp_res[i])
Esempio n. 5
0
 def test_tuple_parser_same_values(self):
     tuple_values = "data(1.1,22.22,333.333),info[1.1,22.22,333.333]"
     result = parse_tuple_pairs(tuple_values)
     exp_res = {
         'data': np.array([1.1, 22.22, 333.333]),
         'info': np.array([1.1, 22.22, 333.333])
     }
     for el in exp_res.keys():
         npt.assert_array_equal(result[el], exp_res[el])
Esempio n. 6
0
 def test_tuple_parser_name_digits_only(self):
     tuple_values = "0448(1.1,22.22,333.333),0449[2.2,33.33,444.444]"
     result = parse_tuple_pairs(tuple_values)
     exp_res = {
         '0448': np.array([1.1, 22.22, 333.333]),
         '0449': np.array([2.2, 33.33, 444.444])
     }
     for el in exp_res.keys():
         npt.assert_array_equal(result[el], exp_res[el])
Esempio n. 7
0
 def test_multi_mean_scale_arrays_no_input(self):
     mean_values = "(1.1,22.22,333.333),(2.1,33.22,444.333)"
     scale_values = "[1.1,22.22,333.333],[2.1,33.22,444.333]"
     result = get_mean_scale_dictionary(parse_tuple_pairs(mean_values),
                                        parse_tuple_pairs(scale_values),
                                        None)
     exp_res = [
         [
             np.array([1.1, 22.22, 333.333]),  # mean
             np.array([1.1, 22.22, 333.333])  # scale
         ],
         [
             np.array([2.1, 33.22, 444.333]),  # mean
             np.array([2.1, 33.22, 444.333])  # scale
         ]
     ]
     for i in range(0, len(exp_res)):
         for j in range(0, len(exp_res[i])):
             npt.assert_array_equal(exp_res[i][j], result[i][j])
Esempio n. 8
0
 def test_scale_only_with_input(self):
     scale_values = "(1.1,22.22,333.333)"
     mean_values = ""
     mean = parse_tuple_pairs(mean_values)
     scale = parse_tuple_pairs(scale_values)
     result = get_mean_scale_dictionary(mean, scale, 'data')
     exp_res = {
         'data': {
             'mean': None,
             'scale': np.array([1.1, 22.22, 333.333])
         }
     }
     for input in exp_res.keys():
         for key in exp_res[input].keys():
             if type(exp_res[input][key]) is np.ndarray:
                 npt.assert_array_equal(exp_res[input][key],
                                        result[input][key])
             else:
                 self.assertEqual(exp_res[input][key], result[input][key])
Esempio n. 9
0
 def test_values_match_input_name(self):
     # to be sure that we correctly processes complex names
     res_values = parse_tuple_pairs(
         "input255(255),input255.0(255.0),multi-dotted.input.3.(255,128,64)"
     )
     exp_res = {
         'input255': np.array([255.0]),
         'input255.0': np.array([255.0]),
         'multi-dotted.input.3.': np.array([255., 128., 64.])
     }
     self.assertEqual(len(exp_res), len(res_values))
     for i, j in zip(exp_res, res_values):
         self.assertEqual(i, j)
         npt.assert_array_equal(exp_res[i], res_values[j])
Esempio n. 10
0
 def test_multi_mean_scale_no_input(self):
     mean_values = "data(1.1,22.22,333.333),info(2.1,33.22,444.333)"
     scale_values = "data[1.1,22.22,333.333],info[2.1,33.22,444.333]"
     result = get_mean_scale_dictionary(parse_tuple_pairs(mean_values),
                                        parse_tuple_pairs(scale_values),
                                        None)
     exp_res = {
         'data': {
             'mean': np.array([1.1, 22.22, 333.333]),
             'scale': np.array([1.1, 22.22, 333.333])
         },
         'info': {
             'mean': np.array([2.1, 33.22, 444.333]),
             'scale': np.array([2.1, 33.22, 444.333])
         }
     }
     for input in exp_res.keys():
         for key in exp_res[input].keys():
             if type(exp_res[input][key]) is np.ndarray:
                 npt.assert_array_equal(exp_res[input][key],
                                        result[input][key])
             else:
                 self.assertEqual(exp_res[input][key], result[input][key])
Esempio n. 11
0
def arguments_post_parsing(argv: argparse.Namespace):
    moc_front_end, available_moc_front_ends = get_moc_frontends(argv)

    is_tf, is_caffe, is_mxnet, is_kaldi, is_onnx =\
        deduce_framework_by_namespace(argv) if not moc_front_end else [False, False, False, False, False]

    if any([is_tf, is_caffe, is_mxnet, is_kaldi, is_onnx]):
        if new_extensions_used(argv):
            raise Error('New kind of extensions used on legacy path')
        if new_transformations_config_used(argv):
            raise Error(
                'New kind of transformations configuration used on legacy path'
            )
    else:  # new frontend used
        frameworks = ['tf', 'caffe', 'mxnet', 'kaldi', 'onnx']
        frameworks = list(set(frameworks + available_moc_front_ends))
        if argv.framework not in frameworks:
            if argv.use_legacy_frontend:
                raise Error(
                    'Framework {} is not a valid target when using the --use_legacy_frontend flag. '
                    'The following legacy frameworks are available: {}' +
                    refer_to_faq_msg(15), argv.framework, frameworks)
            else:
                raise Error(
                    'Framework {} is not a valid target. Please use --framework with one from the list: {}. '
                    + refer_to_faq_msg(15), argv.framework, frameworks)

    if is_tf and not argv.input_model and not argv.saved_model_dir and not argv.input_meta_graph:
        raise Error(
            'Path to input model or saved model dir is required: use --input_model, --saved_model_dir or '
            '--input_meta_graph')
    elif is_mxnet and not argv.input_model and not argv.input_symbol and not argv.pretrained_model_name:
        raise Error(
            'Path to input model or input symbol or pretrained_model_name is required: use --input_model or '
            '--input_symbol or --pretrained_model_name')
    elif is_caffe and not argv.input_model and not argv.input_proto:
        raise Error(
            'Path to input model or input proto is required: use --input_model or --input_proto'
        )
    elif (is_kaldi or is_onnx) and not argv.input_model:
        raise Error('Path to input model is required: use --input_model.')

    log.debug(str(argv))
    log.debug("Model Optimizer started")

    model_name = "<UNKNOWN_NAME>"
    if argv.model_name:
        model_name = argv.model_name
    elif argv.input_model:
        model_name = get_model_name(argv.input_model)
    elif is_tf and argv.saved_model_dir:
        model_name = "saved_model"
    elif is_tf and argv.input_meta_graph:
        model_name = get_model_name(argv.input_meta_graph)
    elif is_mxnet and argv.input_symbol:
        model_name = get_model_name(argv.input_symbol)
    argv.model_name = model_name

    log.debug('Output model name would be {}{{.xml, .bin}}'.format(
        argv.model_name))

    # if --input_proto is not provided, try to retrieve another one
    # by suffix substitution from model file name
    if is_caffe and not argv.input_proto:
        argv.input_proto = replace_ext(argv.input_model, '.caffemodel',
                                       '.prototxt')

        if not argv.input_proto:
            raise Error(
                "Cannot find prototxt file: for Caffe please specify --input_proto - a "
                +
                "protobuf file that stores topology and --input_model that stores "
                + "pretrained weights. " + refer_to_faq_msg(20))
        log.info('Deduced name for prototxt: {}'.format(argv.input_proto))

    if not argv.silent:
        print_argv(argv, is_caffe, is_tf, is_mxnet, is_kaldi, is_onnx,
                   argv.model_name)

    # This try-except is additional reinsurance that the IE
    # dependency search does not break the MO pipeline
    def raise_ie_not_found():
        raise Error(
            "Could not find the Inference Engine or nGraph Python API.\n"
            "Consider building the Inference Engine and nGraph Python APIs from sources or try to install OpenVINO (TM) Toolkit using \"install_prerequisites.{}\""
            .format("bat" if sys.platform == "windows" else "sh"))

    try:
        if not find_ie_version(silent=argv.silent):
            raise_ie_not_found()
    except Exception as e:
        log.error(e)
        raise_ie_not_found()

    if 'data_type' in argv and argv.data_type in ['FP16', 'half']:
        argv.data_type = 'FP32'
        argv.compress_fp16 = True
    else:
        argv.compress_fp16 = False

    # This is just to check that transform key is valid and transformations are available
    check_available_transforms(parse_transform(argv.transform))

    if argv.legacy_ir_generation and len(argv.transform) != 0:
        raise Error(
            "--legacy_ir_generation and --transform keys can not be used at the same time."
        )

    # For C++ frontends there are no specific Python installation requirements, check only generic ones
    if moc_front_end:
        ret_code = check_requirements()
    else:
        ret_code = check_requirements(framework=argv.framework)
    if ret_code:
        raise Error(
            'check_requirements exited with return code {}'.format(ret_code))

    if is_tf and argv.tensorflow_use_custom_operations_config is not None:
        argv.transformations_config = argv.tensorflow_use_custom_operations_config

    if is_caffe and argv.mean_file and argv.mean_values:
        raise Error(
            'Both --mean_file and mean_values are specified. Specify either mean file or mean values. '
            + refer_to_faq_msg(17))
    elif is_caffe and argv.mean_file and argv.mean_file_offsets:
        values = get_tuple_values(argv.mean_file_offsets,
                                  t=int,
                                  num_exp_values=2)
        mean_file_offsets = mo_array([int(x) for x in values[0].split(',')])
        if not all([offset >= 0 for offset in mean_file_offsets]):
            raise Error(
                "Negative value specified for --mean_file_offsets option. "
                "Please specify positive integer values in format '(x,y)'. " +
                refer_to_faq_msg(18))
        argv.mean_file_offsets = mean_file_offsets

    if argv.scale and argv.scale_values:
        raise Error(
            'Both --scale and --scale_values are defined. Specify either scale factor or scale values per input '
            + 'channels. ' + refer_to_faq_msg(19))

    if argv.scale and argv.scale < 1.0:
        log.error(
            "The scale value is less than 1.0. This is most probably an issue because the scale value specifies "
            "floating point value which all input values will be *divided*.",
            extra={'is_warning': True})

    if argv.input_model and (is_tf and argv.saved_model_dir):
        raise Error('Both --input_model and --saved_model_dir are defined. '
                    'Specify either input model or saved model directory.')
    if is_tf:
        if argv.saved_model_tags is not None:
            if ' ' in argv.saved_model_tags:
                raise Error(
                    'Incorrect saved model tag was provided. Specify --saved_model_tags with no spaces in it'
                )
            argv.saved_model_tags = argv.saved_model_tags.split(',')

    argv.output = argv.output.split(',') if argv.output else None

    inputs_list, argv.placeholder_shapes, argv.placeholder_data_types = get_placeholder_shapes(
        argv.input, argv.input_shape, argv.batch)
    argv.inputs_list = inputs_list

    mean_values = parse_tuple_pairs(argv.mean_values)
    scale_values = parse_tuple_pairs(argv.scale_values)
    mean_scale = get_mean_scale_dictionary(mean_values, scale_values,
                                           argv.input)
    argv.mean_scale_values = mean_scale
    argv.layout_values = get_layout_values(argv.layout, argv.source_layout,
                                           argv.target_layout)

    if not os.path.exists(argv.output_dir):
        try:
            os.makedirs(argv.output_dir)
        except PermissionError as e:
            raise Error(
                "Failed to create directory {}. Permission denied! " +
                refer_to_faq_msg(22), argv.output_dir) from e
    else:
        if not os.access(argv.output_dir, os.W_OK):
            raise Error(
                "Output directory {} is not writable for current user. " +
                refer_to_faq_msg(22), argv.output_dir)

    log.debug("Placeholder shapes : {}".format(argv.placeholder_shapes))

    argv.freeze_placeholder_with_value, argv.input = get_freeze_placeholder_values(
        argv.input, argv.freeze_placeholder_with_value)

    load_extensions(argv, is_tf, is_caffe, is_mxnet, is_kaldi, is_onnx)

    return argv
def _prepare_ir(argv, old_api=False):
    log.debug(str(argv))
    log.debug("Model Optimizer started")

    model_name = "<UNKNOWN_NAME>"
    if argv.model_name:
        model_name = argv.model_name
    elif argv.input_model:
        model_name = argv.input_model.__class__.__name__
    argv.model_name = model_name

    log.debug('Output model name would be {}{{.xml, .bin}}'.format(
        argv.model_name))

    if not argv.silent:
        print_argv(argv, False, False, False, False, False, argv.model_name)

    if argv.scale and argv.scale_values:
        raise Error(
            'Both --scale and --scale_values are defined. Specify either scale factor or scale values per input '
            + 'channels. ' + refer_to_faq_msg(19))

    if argv.scale and argv.scale < 1.0:
        log.error(
            "The scale value is less than 1.0. This is most probably an issue because the scale value specifies "
            "floating point value which all input values will be *divided*.",
            extra={'is_warning': True})

    argv.output = argv.output.split(',') if argv.output else None

    argv.inputs_list, argv.placeholder_shapes, argv.placeholder_data_types = get_placeholder_shapes(
        argv.input, argv.input_shape, argv.batch)

    mean_values = parse_tuple_pairs(argv.mean_values)
    scale_values = parse_tuple_pairs(argv.scale_values)
    mean_scale = get_mean_scale_dictionary(mean_values, scale_values,
                                           argv.input)
    argv.mean_scale_values = mean_scale

    if not os.path.exists(argv.output_dir):
        try:
            os.makedirs(argv.output_dir)
        except PermissionError as e:
            raise Error(
                "Failed to create directory {}. Permission denied! " +
                refer_to_faq_msg(22), argv.output_dir) from e
    else:
        if not os.access(argv.output_dir, os.W_OK):
            raise Error(
                "Output directory {} is not writable for current user. " +
                refer_to_faq_msg(22), argv.output_dir)

    log.debug("Placeholder shapes : {}".format(argv.placeholder_shapes))

    ret_res = 1
    if hasattr(argv,
               'extensions') and argv.extensions and argv.extensions != '':
        extensions = argv.extensions.split(',')
    else:
        extensions = None

    argv.freeze_placeholder_with_value, argv.input = get_freeze_placeholder_values(
        argv.input, argv.freeze_placeholder_with_value)

    import_extensions.load_dirs(argv.framework, extensions, get_front_classes)

    graph = unified_pipeline(argv)
    if old_api:
        return graph
    else:
        return graph, None
Esempio n. 13
0
 def test_mean_do_not_match_input(self):
     scale_values = parse_tuple_pairs("input1(255),input2(255)")
     mean_values = parse_tuple_pairs("input_not_present(255),input2(255)")
     self.assertRaises(Error, get_mean_scale_dictionary, mean_values,
                       scale_values, "input1,input2")