|
| 1 | +import logging |
| 2 | +from typing import Any, List, Set, NamedTuple |
| 3 | + |
| 4 | +try: |
| 5 | + import onnx |
| 6 | + from tf2onnx.tfonnx import process_tf_graph, tf_optimize |
| 7 | + from tf2onnx import optimizer |
| 8 | + |
| 9 | + ONNX_EXPORT_ENABLED = True |
| 10 | +except ImportError: |
| 11 | + # Either onnx and tf2onnx not installed, or they're not compatible with the version of tensorflow |
| 12 | + ONNX_EXPORT_ENABLED = False |
| 13 | + pass |
| 14 | + |
| 15 | +from mlagents.tf_utils import tf |
| 16 | + |
| 17 | +from tensorflow.python.platform import gfile |
| 18 | +from tensorflow.python.framework import graph_util |
| 19 | +from mlagents.trainers import tensorflow_to_barracuda as tf2bc |
| 20 | + |
| 21 | +logger = logging.getLogger("mlagents.trainers") |
| 22 | + |
| 23 | +POSSIBLE_INPUT_NODES = frozenset( |
| 24 | + [ |
| 25 | + "action_masks", |
| 26 | + "epsilon", |
| 27 | + "prev_action", |
| 28 | + "recurrent_in", |
| 29 | + "sequence_length", |
| 30 | + "vector_observation", |
| 31 | + ] |
| 32 | +) |
| 33 | + |
| 34 | +POSSIBLE_OUTPUT_NODES = frozenset( |
| 35 | + ["action", "action_probs", "recurrent_out", "value_estimate"] |
| 36 | +) |
| 37 | + |
| 38 | +MODEL_CONSTANTS = frozenset( |
| 39 | + ["action_output_shape", "is_continuous_control", "memory_size", "version_number"] |
| 40 | +) |
| 41 | +VISUAL_OBSERVATION_PREFIX = "visual_observation_" |
| 42 | + |
| 43 | + |
| 44 | +class SerializationSettings(NamedTuple): |
| 45 | + model_path: str |
| 46 | + brain_name: str |
| 47 | + convert_to_barracuda: bool = True |
| 48 | + convert_to_onnx: bool = True |
| 49 | + onnx_opset: int = 9 |
| 50 | + |
| 51 | + |
| 52 | +def export_policy_model( |
| 53 | + settings: SerializationSettings, graph: tf.Graph, sess: tf.Session |
| 54 | +) -> None: |
| 55 | + """ |
| 56 | + Exports latest saved model to .nn format for Unity embedding. |
| 57 | + """ |
| 58 | + frozen_graph_def = _make_frozen_graph(settings, graph, sess) |
| 59 | + # Save frozen graph |
| 60 | + frozen_graph_def_path = settings.model_path + "/frozen_graph_def.pb" |
| 61 | + with gfile.GFile(frozen_graph_def_path, "wb") as f: |
| 62 | + f.write(frozen_graph_def.SerializeToString()) |
| 63 | + |
| 64 | + # Convert to barracuda |
| 65 | + if settings.convert_to_barracuda: |
| 66 | + tf2bc.convert(frozen_graph_def_path, settings.model_path + ".nn") |
| 67 | + logger.info(f"Exported {settings.model_path}.nn file") |
| 68 | + |
| 69 | + # Save to onnx too (if we were able to import it) |
| 70 | + if ONNX_EXPORT_ENABLED and settings.convert_to_onnx: |
| 71 | + try: |
| 72 | + onnx_graph = convert_frozen_to_onnx(settings, frozen_graph_def) |
| 73 | + onnx_output_path = settings.model_path + ".onnx" |
| 74 | + with open(onnx_output_path, "wb") as f: |
| 75 | + f.write(onnx_graph.SerializeToString()) |
| 76 | + logger.info(f"Converting to {onnx_output_path}") |
| 77 | + except Exception: |
| 78 | + logger.exception( |
| 79 | + "Exception trying to save ONNX graph. Please report this error on " |
| 80 | + "https://github.com/Unity-Technologies/ml-agents/issues and " |
| 81 | + "attach a copy of frozen_graph_def.pb" |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +def _make_frozen_graph( |
| 86 | + settings: SerializationSettings, graph: tf.Graph, sess: tf.Session |
| 87 | +) -> tf.GraphDef: |
| 88 | + with graph.as_default(): |
| 89 | + target_nodes = ",".join(_process_graph(settings, graph)) |
| 90 | + graph_def = graph.as_graph_def() |
| 91 | + output_graph_def = graph_util.convert_variables_to_constants( |
| 92 | + sess, graph_def, target_nodes.replace(" ", "").split(",") |
| 93 | + ) |
| 94 | + return output_graph_def |
| 95 | + |
| 96 | + |
| 97 | +def convert_frozen_to_onnx( |
| 98 | + settings: SerializationSettings, frozen_graph_def: tf.GraphDef |
| 99 | +) -> Any: |
| 100 | + # This is basically https://github.com/onnx/tensorflow-onnx/blob/master/tf2onnx/convert.py |
| 101 | + |
| 102 | + # Some constants in the graph need to be read by the inference system. |
| 103 | + # These aren't used by the model anywhere, so trying to make sure they propagate |
| 104 | + # through conversion and import is a losing battle. Instead, save them now, |
| 105 | + # so that we can add them back later. |
| 106 | + constant_values = {} |
| 107 | + for n in frozen_graph_def.node: |
| 108 | + if n.name in MODEL_CONSTANTS: |
| 109 | + val = n.attr["value"].tensor.int_val[0] |
| 110 | + constant_values[n.name] = val |
| 111 | + |
| 112 | + inputs = _get_input_node_names(frozen_graph_def) |
| 113 | + outputs = _get_output_node_names(frozen_graph_def) |
| 114 | + logger.info(f"onnx export - inputs:{inputs} outputs:{outputs}") |
| 115 | + |
| 116 | + frozen_graph_def = tf_optimize( |
| 117 | + inputs, outputs, frozen_graph_def, fold_constant=True |
| 118 | + ) |
| 119 | + |
| 120 | + with tf.Graph().as_default() as tf_graph: |
| 121 | + tf.import_graph_def(frozen_graph_def, name="") |
| 122 | + with tf.Session(graph=tf_graph): |
| 123 | + g = process_tf_graph( |
| 124 | + tf_graph, |
| 125 | + input_names=inputs, |
| 126 | + output_names=outputs, |
| 127 | + opset=settings.onnx_opset, |
| 128 | + ) |
| 129 | + |
| 130 | + onnx_graph = optimizer.optimize_graph(g) |
| 131 | + model_proto = onnx_graph.make_model(settings.brain_name) |
| 132 | + |
| 133 | + # Save the constant values back the graph initializer. |
| 134 | + # This will ensure the importer gets them as global constants. |
| 135 | + constant_nodes = [] |
| 136 | + for k, v in constant_values.items(): |
| 137 | + constant_node = _make_onnx_node_for_constant(k, v) |
| 138 | + constant_nodes.append(constant_node) |
| 139 | + model_proto.graph.initializer.extend(constant_nodes) |
| 140 | + return model_proto |
| 141 | + |
| 142 | + |
| 143 | +def _make_onnx_node_for_constant(name: str, value: int) -> Any: |
| 144 | + tensor_value = onnx.TensorProto( |
| 145 | + data_type=onnx.TensorProto.INT32, |
| 146 | + name=name, |
| 147 | + int32_data=[value], |
| 148 | + dims=[1, 1, 1, 1], |
| 149 | + ) |
| 150 | + return tensor_value |
| 151 | + |
| 152 | + |
| 153 | +def _get_input_node_names(frozen_graph_def: Any) -> List[str]: |
| 154 | + """ |
| 155 | + Get the list of input node names from the graph. |
| 156 | + Names are suffixed with ":0" |
| 157 | + """ |
| 158 | + node_names = _get_frozen_graph_node_names(frozen_graph_def) |
| 159 | + input_names = node_names & POSSIBLE_INPUT_NODES |
| 160 | + |
| 161 | + # Check visual inputs sequentially, and exit as soon as we don't find one |
| 162 | + vis_index = 0 |
| 163 | + while True: |
| 164 | + vis_node_name = f"{VISUAL_OBSERVATION_PREFIX}{vis_index}" |
| 165 | + if vis_node_name in node_names: |
| 166 | + input_names.add(vis_node_name) |
| 167 | + else: |
| 168 | + break |
| 169 | + vis_index += 1 |
| 170 | + # Append the port |
| 171 | + return [f"{n}:0" for n in input_names] |
| 172 | + |
| 173 | + |
| 174 | +def _get_output_node_names(frozen_graph_def: Any) -> List[str]: |
| 175 | + """ |
| 176 | + Get the list of output node names from the graph. |
| 177 | + Names are suffixed with ":0" |
| 178 | + """ |
| 179 | + node_names = _get_frozen_graph_node_names(frozen_graph_def) |
| 180 | + output_names = node_names & POSSIBLE_OUTPUT_NODES |
| 181 | + # Append the port |
| 182 | + return [f"{n}:0" for n in output_names] |
| 183 | + |
| 184 | + |
| 185 | +def _get_frozen_graph_node_names(frozen_graph_def: Any) -> Set[str]: |
| 186 | + """ |
| 187 | + Get all the node names from the graph. |
| 188 | + """ |
| 189 | + names = set() |
| 190 | + for node in frozen_graph_def.node: |
| 191 | + names.add(node.name) |
| 192 | + return names |
| 193 | + |
| 194 | + |
| 195 | +def _process_graph(settings: SerializationSettings, graph: tf.Graph) -> List[str]: |
| 196 | + """ |
| 197 | + Gets the list of the output nodes present in the graph for inference |
| 198 | + :return: list of node names |
| 199 | + """ |
| 200 | + all_nodes = [x.name for x in graph.as_graph_def().node] |
| 201 | + nodes = [x for x in all_nodes if x in POSSIBLE_OUTPUT_NODES | MODEL_CONSTANTS] |
| 202 | + logger.info("List of nodes to export for brain :" + settings.brain_name) |
| 203 | + for n in nodes: |
| 204 | + logger.info("\t" + n) |
| 205 | + return nodes |
0 commit comments