Beispiel #1
0
    def save(self, model: Model, model_path: Union[str, Path]) -> None:
        if isinstance(model_path, Path):
            model_path = model_path.as_posix()

        session_config = create_session_config(allow_growth=True)
        with tf.compat.v1.Session(config=session_config) as sess:
            tf.import_graph_def(model.handle, name="")

            is_func = is_function(sess.graph)
            if not is_func:
                infer_shape(sess.graph, {})

            inputs = {name: sess.graph.get_tensor_by_name(spec.name) for name, spec in model.inputs.items()}
            outputs = {name: sess.graph.get_tensor_by_name(spec.name) for name, spec in model.outputs.items()}

            def _ensure_shape(tensors_dict, tensors_specs):
                for name, tensor in tensors_dict.items():
                    if tensor.shape.rank is None:
                        tensor.set_shape(tensors_specs[name].shape)
                return tensors_dict

            inputs = _ensure_shape(inputs, model.inputs)
            outputs = _ensure_shape(outputs, model.outputs)

            LOGGER.info(inputs)
            LOGGER.info(outputs)

            tf.compat.v1.saved_model.simple_save(sess, model_path, inputs, outputs, legacy_init_op=None)
Beispiel #2
0
def graphs_from_tf(tf_graph,
                   input_names,
                   output_names,
                   shape_override=None,
                   const_node_values=None,
                   ignore_default=None,
                   use_default=None):
    """make tf2onnx internal subgraphs from the tensorflow subgraphs"""
    if shape_override is None:
        shape_override = {}
    ordered_func = resolve_functions(tf_graph)
    subgraphs = []
    for func in ordered_func:
        f_inputs_names = [t.name for t in func.inputs]
        f_output_names = [t.name for t in func.outputs]

        outputs_to_values, _ = compute_const_folding_using_tf(
            func, const_node_values, output_names)

        onnx_nodes, _, _, output_shapes, dtypes, _ = \
            tensorflow_to_onnx(func, shape_override, const_node_values, ignore_default, use_default)

        fg = Graph(onnx_nodes,
                   output_shapes,
                   dtypes,
                   input_names=f_inputs_names,
                   output_names=f_output_names,
                   is_subgraph=True,
                   graph_name=func.name)
        fold_constants_using_tf(fg, outputs_to_values)
        subgraphs.append(fg)

    is_func = is_function(tf_graph)
    if not is_func:
        tf_graph = infer_shape(tf_graph, shape_override)

    outputs_to_values, _ = compute_const_folding_using_tf(
        tf_graph, const_node_values, output_names)

    onnx_nodes, _, _, output_shapes, dtypes, _ = \
        tensorflow_to_onnx(tf_graph, shape_override, const_node_values, ignore_default, use_default)

    utils.check_io(input_names, output_names, output_shapes.keys())
    main_g = Graph(onnx_nodes,
                   output_shapes,
                   dtypes,
                   input_names=input_names,
                   output_names=output_names)
    fold_constants_using_tf(main_g, outputs_to_values)
    return main_g, subgraphs
Beispiel #3
0
def process_tf_graph(tf_graph, continue_on_error=False, verbose=False, target=None,
                     opset=None, custom_op_handlers=None, custom_rewriter=None,
                     extra_opset=None, shape_override=None, inputs_as_nchw=None,
                     input_names=None, output_names=None, is_subgraph=False):
    """Convert tensorflow graph to onnx graph.
        Args:
            tf_graph: tensorflow graph
            continue_on_error: if an op can't be processed (aka there is no mapping), continue
            verbose: print summary stats (deprecated)
            target: list of workarounds applied to help certain platforms
            opset: the opset to be used (int, default is latest)
            custom_op_handlers: dictionary of custom ops handlers
            custom_rewriter: list of custom graph rewriters
            extra_opset: list of extra opset's, for example the opset's used by custom ops
            shape_override: dict with inputs that override the shapes given by tensorflow
            inputs_as_nchw: transpose inputs in list from nchw to nchw
            input_names: list of input node names in graph, input name format as node_name:port_id
            output_names: list of output node names in graph, output name format as node_name:port_id
        Return:
            onnx graph
    """
    if verbose:
        logger.warning("Argument verbose for process_tf_graph is deprecated. Please use --verbose option instead.")
    del verbose

    opset = utils.find_opset(opset)
    if not is_subgraph:
        logger.info("Using tensorflow=%s, onnx=%s, tf2onnx=%s/%s",
                    get_tf_version(), utils.get_onnx_version(), tf2onnx.__version__, tf2onnx.version.git_version[:6])
        logger.info("Using opset <onnx, %s>", opset)
        if opset > schemas.get_max_supported_opset_version():
            logger.warning("Currently installed onnx package %s is too low to support opset %s, "
                           "please upgrade onnx package to avoid potential conversion issue.",
                           utils.get_onnx_version(), opset)

    is_func = is_function(tf_graph)
    if not is_func:
        tf_graph = infer_shape(tf_graph, shape_override)

    if shape_override is None:
        shape_override = {}
    if inputs_as_nchw is None:
        inputs_as_nchw = []
    if target is None:
        target = constants.DEFAULT_TARGET

    onnx_nodes, op_cnt, attr_cnt, output_shapes, dtypes, _ = tensorflow_to_onnx(tf_graph, shape_override)
    if not is_subgraph:
        # make tf2onnx internal subgraphs from the tensorflow subgraphs
        ordered_func = resolve_functions(tf_graph)
        for func in ordered_func:
            f_inputs_names = [t.name for t in func.inputs]
            f_output_names = [t.name for t in func.outputs]
            fg = process_tf_graph(func, continue_on_error, False, target, opset,
                                  custom_op_handlers, custom_rewriter,
                                  extra_opset, shape_override, inputs_as_nchw,
                                  f_inputs_names, f_output_names, is_subgraph=True)
            fg.graph_name = func.name
            fg.func_inputs = f_inputs_names
            set_function(func.name, fg)

    io_to_check = []
    if input_names:
        io_to_check.extend(input_names)
    if output_names:
        io_to_check.extend(output_names)

    if io_to_check:
        # check output existence in case user passed in wrong output ids
        non_exists = set(io_to_check) - set(output_shapes.keys())
        if non_exists:
            logger.error("\nFailed to convert: inputs/outputs specified do not exist, make sure your passed"
                         "in format: input/output_node_name:port_id. Problematical inputs/outputs are: %s \n",
                         non_exists)
            raise ValueError("Inputs/Outputs Not Found")

    g = Graph(onnx_nodes, output_shapes, dtypes, target, opset, extra_opset, output_names, is_subgraph=is_subgraph)

    # create ops mapping for the desired opsets
    ops_mapping = handler.tf_op.create_mapping(g.opset, g.extra_opset)

    # apply custom ops on top of the assembled opset. We can either complement the opset
    # or override existing ops with a custom op.
    if custom_op_handlers is not None:
        # below is a bit tricky since there are a few api's:
        # 1. the future way we want custom ops to be registered with the @tf_op decorator. THose handlers will be
        #     registered via the decorator on load of the module ... nothing is required here.
        # 2. the old custom op api: a dictionary of {name: (func, args[])
        #     We deal with this by using a compat_handler that wraps to old handler with a new style handler.
        #     This is tempoary to give people give to move to the new api and after tf2onnx-1.5 we want to remove this
        custom_opset = {}
        for k, v in custom_op_handlers.items():
            # FIXME: remove this after tf2onnx-1.5
            def compat_handler(ctx, node, **kwargs):
                # wrap old handler
                name = node.name
                args = kwargs["args"]
                func = kwargs["func"]
                return func(ctx, node, name, args)

            args = v[1]
            kwargs = {"func": v[0]}
            if args:
                onnx_op = args[0]
                kwargs["onnx_op"] = onnx_op
                args = args[1:]
            kwargs["args"] = args
            new_handler = handler.tf_op(k,
                                        domain=constants.TENSORFLOW_OPSET.domain,
                                        kwargs=kwargs)
            new_handler.register_compat_handler(compat_handler, 1)
            custom_opset[k] = (compat_handler, kwargs)
        ops_mapping.update(custom_opset)

    if inputs_as_nchw:
        transpose_inputs(g, inputs_as_nchw)

    # pre-processing graph rewrites
    # bi-directional re-writer should be placed after single directional re-writer
    rewriters = [rewrite_transpose, rewrite_flatten, rewrite_gemm,
                 rewrite_random_uniform, rewrite_random_uniform_fold_const,
                 rewrite_random_normal, rewrite_dropout, rewrite_eye,
                 rewrite_leakyrelu, rewrite_thresholded_relu, rewrite_conv2d_with_pad,
                 rewrite_single_direction_lstm, rewrite_bi_direction_lstm,
                 rewrite_single_direction_gru, rewrite_bi_direction_gru,
                 rewrite_custom_rnn_cell, rewrite_generic_loop, rewrite_cond,
                 rewrite_biasadd_with_conv2d,
                 ]

    if custom_rewriter is not None:
        rewriters.extend(custom_rewriter)

    run_rewriters(g, rewriters, continue_on_error)

    # some nodes may already copied into inner Graph, so remove them from main Graph.
    g.delete_unused_nodes(output_names)
    topological_sort(g, continue_on_error)

    mapped_op, unmapped_op, exceptions = tensorflow_onnx_mapping(g, ops_mapping)
    if unmapped_op:
        logger.error("Unsupported ops: %s", unmapped_op)
    if exceptions and not continue_on_error:
        raise exceptions[0]

    # post-processing rewriters
    late_rewriters = []
    if constants.TARGET_RS5 in target:
        late_rewriters.append(rewrite_incomplete_type_support_rs5)
    if constants.TARGET_RS6 in target:
        late_rewriters.append(rewrite_incomplete_type_support_rs6)
    if late_rewriters:
        run_rewriters(g, late_rewriters, continue_on_error)

    # onnx requires topological sorting
    topological_sort(g, continue_on_error)

    g.update_proto()

    logger.verbose(
        "Summay Stats:\n"
        "\ttensorflow ops: {}\n"
        "\ttensorflow attr: {}\n"
        "\tonnx mapped: {}\n"
        "\tonnx unmapped: {}".format(op_cnt, attr_cnt, mapped_op, unmapped_op))

    return g
Beispiel #4
0
def process_tf_graph(tf_graph,
                     continue_on_error=False,
                     verbose=False,
                     target=None,
                     opset=None,
                     custom_op_handlers=None,
                     custom_rewriter=None,
                     extra_opset=None,
                     shape_override=None,
                     inputs_as_nchw=None,
                     input_names=None,
                     output_names=None,
                     ignore_default=None,
                     use_default=None,
                     is_subgraph=False,
                     const_node_values=None,
                     tensors_to_rename=None,
                     initialized_tables=None,
                     tflite_path=None,
                     dequantize=False):
    """Convert tensorflow graph to onnx graph.
        Args:
            tf_graph: tensorflow graph
            continue_on_error: if an op can't be processed (aka there is no mapping), continue
            verbose: print summary stats (deprecated)
            target: list of workarounds applied to help certain platforms
            opset: the opset to be used (int, default is latest)
            custom_op_handlers: dictionary of custom ops handlers
            custom_rewriter: list of custom graph rewriters
            extra_opset: list of extra opset's, for example the opset's used by custom ops
            shape_override: dict with inputs that override the shapes given by tensorflow
            inputs_as_nchw: transpose inputs in list from nchw to nhwc
            input_names: list of input node names in graph, input name format as node_name:port_id. Optional.
            output_names: list of output node names in graph, format is node_name:port_id. Optional for tflite.
            ignore_default: list of node names of PlaceholderWithDefault ops to change into Placeholder ops
            use_default: list of node names of PlaceholderWithDefault ops to change into Identity ops using the default
            const_node_values: a dict returned by compress_graph_def mapping node names to tensor values
            tensors_to_rename: an optional dict (string->string) mapping tensor names to new names
            initialized_tables: mapping from table shared_names to tuple of keys and values of table
            tflite_path: Path to a tflite file to convert. If used, pass None to tf_graph
        Return:
            onnx graph
    """
    # NOTE: process_parsed_graph and Graph are always given tensors post-rename.
    # process_tf_graph (this function) gets tensors pre-rename.
    if verbose:
        logger.warning(
            "Argument verbose for process_tf_graph is deprecated. Please use --verbose option instead."
        )
    del verbose

    opset = utils.find_opset(opset)
    if not is_subgraph:
        logger.info("Using tensorflow=%s, onnx=%s, tf2onnx=%s/%s",
                    get_tf_version(), utils.get_onnx_version(),
                    tf2onnx.__version__, tf2onnx.version.git_version[:6])
        logger.info("Using opset <onnx, %s>", opset)
        if opset > schemas.get_max_supported_opset_version():
            logger.warning(
                "Currently installed onnx package %s is too low to support opset %s, "
                "please upgrade onnx package to avoid potential conversion issue.",
                utils.get_onnx_version(), opset)

    if shape_override is None:
        shape_override = {}
    if inputs_as_nchw is None:
        inputs_as_nchw = []
    if target is None:
        target = constants.DEFAULT_TARGET

    def check_io(input_names, output_names, output_shapes):
        io_to_check = []
        if input_names:
            io_to_check.extend(input_names)
        if output_names:
            io_to_check.extend(output_names)
        if io_to_check:
            # check output existence in case user passed in wrong output ids
            non_exists = set(io_to_check) - set(output_shapes.keys())
            if non_exists:
                logger.error(
                    "\nFailed to convert: inputs/outputs specified do not exist, make sure your passed"
                    "in format: input/output_node_name:port_id. Problematic inputs/outputs are: %s \n",
                    non_exists)
                raise ValueError("Inputs/Outputs Not Found")

    def rename_tensors_in_dict(d):
        if tensors_to_rename is None:
            return d
        return {tensors_to_rename.get(k, k): v for k, v in d.items()}

    def rename_tensors_in_list(tensors):
        if tensors_to_rename is None or tensors is None:
            return tensors
        return [tensors_to_rename.get(t, t) for t in tensors]

    def rename_tensors_in_nodes(onnx_nodes):
        if tensors_to_rename is None:
            return
        for n in onnx_nodes:
            n.input[:] = rename_tensors_in_list(n.input)
            n.output[:] = rename_tensors_in_list(n.output)

    if tflite_path is not None:
        tflite_graphs, opcodes, model, tensor_shapes = read_tflite_model(
            tflite_path)
        main_g = None
        inputs_as_nchw = rename_tensors_in_list(inputs_as_nchw)
        for i, tfl_graph in enumerate(tflite_graphs):
            is_main_g = i == len(tflite_graphs) - 1
            prefix = '' if is_main_g else tfl_graph.Name().decode() + '_'
            tensor_shapes_from_interpreter = None
            if is_main_g:
                tensor_shapes_from_interpreter = tensor_shapes
            onnx_nodes, op_cnt, attr_cnt, output_shapes, dtypes, f_inputs, f_outputs, graph_name = \
                parse_tflite_graph(tfl_graph, opcodes, model, prefix, tensor_shapes_from_interpreter)
            g_inputs = f_inputs
            g_outputs = f_outputs
            if is_main_g:
                # Override IO in main graph
                check_io(input_names, output_names, output_shapes)
                if input_names is not None:
                    g_inputs = input_names
                if output_names is not None:
                    g_outputs = output_names
            rename_tensors_in_nodes(onnx_nodes)
            g_inputs = rename_tensors_in_list(g_inputs)
            g_outputs = rename_tensors_in_list(g_outputs)
            output_shapes = rename_tensors_in_dict(output_shapes)
            dtypes = rename_tensors_in_dict(dtypes)
            g = Graph(onnx_nodes, output_shapes, dtypes, target, opset,
                      extra_opset, g_inputs, g_outputs, is_subgraph)
            fg = process_parsed_graph(g,
                                      custom_op_handlers,
                                      inputs_as_nchw,
                                      continue_on_error,
                                      custom_rewriter,
                                      target,
                                      g_outputs, {}, {}, {},
                                      op_cnt,
                                      attr_cnt,
                                      is_tflite=True,
                                      dequantize=dequantize)
            fg.graph_name = graph_name
            if is_main_g:
                main_g = fg
            else:
                set_function(graph_name, fg)

        return main_g

    is_func = is_function(tf_graph)
    if not is_func:
        tf_graph = infer_shape(tf_graph, shape_override)

    outputs_to_values, outputs_to_dtypes = compute_const_folding_using_tf(
        tf_graph, const_node_values, output_names)

    onnx_nodes, op_cnt, attr_cnt, output_shapes, dtypes, _ = \
        tensorflow_to_onnx(tf_graph, shape_override, const_node_values, ignore_default, use_default)
    if not is_subgraph:
        # make tf2onnx internal subgraphs from the tensorflow subgraphs
        ordered_func = resolve_functions(tf_graph)
        for func in ordered_func:
            f_inputs_names = [t.name for t in func.inputs]
            f_output_names = [t.name for t in func.outputs]
            fg = process_tf_graph(func,
                                  continue_on_error,
                                  False,
                                  target,
                                  opset,
                                  custom_op_handlers,
                                  custom_rewriter,
                                  extra_opset,
                                  shape_override,
                                  inputs_as_nchw,
                                  f_inputs_names,
                                  f_output_names,
                                  is_subgraph=True,
                                  const_node_values=const_node_values,
                                  tensors_to_rename=tensors_to_rename,
                                  initialized_tables=initialized_tables)
            fg.graph_name = func.name
            set_function(func.name, fg)

    check_io(input_names, output_names, output_shapes)

    if not is_subgraph:
        rename_tensors_in_nodes(onnx_nodes)
        input_names = rename_tensors_in_list(input_names)
        output_names = rename_tensors_in_list(output_names)
        output_shapes = rename_tensors_in_dict(output_shapes)
        dtypes = rename_tensors_in_dict(dtypes)
        inputs_as_nchw = rename_tensors_in_list(inputs_as_nchw)
    g = Graph(onnx_nodes, output_shapes, dtypes, target, opset, extra_opset,
              input_names, output_names, is_subgraph)
    g = process_parsed_graph(g, custom_op_handlers, inputs_as_nchw,
                             continue_on_error, custom_rewriter, target,
                             output_names, initialized_tables,
                             outputs_to_values, outputs_to_dtypes, op_cnt,
                             attr_cnt)
    return g