|
1 | 1 | import os
|
| 2 | +import threading |
2 | 3 | from mlagents.torch_utils import torch
|
3 | 4 |
|
4 | 5 | from mlagents_envs.logging_util import get_logger
|
|
8 | 9 | logger = get_logger(__name__)
|
9 | 10 |
|
10 | 11 |
|
| 12 | +class exporting_to_onnx: |
| 13 | + """ |
| 14 | + Set this context by calling |
| 15 | + ``` |
| 16 | + with exporting_to_onnx(): |
| 17 | + ``` |
| 18 | + Within this context, the variable exporting_to_onnx.is_exporting() will be true. |
| 19 | + This implementation is thread safe. |
| 20 | + """ |
| 21 | + |
| 22 | + _local_data = threading.local() |
| 23 | + _local_data._is_exporting = False |
| 24 | + |
| 25 | + def __enter__(self): |
| 26 | + self._local_data._is_exporting = True |
| 27 | + |
| 28 | + def __exit__(self, *args): |
| 29 | + self._local_data._is_exporting = False |
| 30 | + |
| 31 | + @staticmethod |
| 32 | + def is_exporting(): |
| 33 | + if not hasattr(exporting_to_onnx._local_data, "_is_exporting"): |
| 34 | + return False |
| 35 | + return exporting_to_onnx._local_data._is_exporting |
| 36 | + |
| 37 | + |
11 | 38 | class ModelSerializer:
|
12 | 39 | def __init__(self, policy):
|
13 | 40 | # ONNX only support input in NCHW (channel first) format.
|
@@ -61,13 +88,14 @@ def export_policy_model(self, output_filepath: str) -> None:
|
61 | 88 | onnx_output_path = f"{output_filepath}.onnx"
|
62 | 89 | logger.info(f"Converting to {onnx_output_path}")
|
63 | 90 |
|
64 |
| - torch.onnx.export( |
65 |
| - self.policy.actor_critic, |
66 |
| - self.dummy_input, |
67 |
| - onnx_output_path, |
68 |
| - opset_version=SerializationSettings.onnx_opset, |
69 |
| - input_names=self.input_names, |
70 |
| - output_names=self.output_names, |
71 |
| - dynamic_axes=self.dynamic_axes, |
72 |
| - ) |
| 91 | + with exporting_to_onnx(): |
| 92 | + torch.onnx.export( |
| 93 | + self.policy.actor_critic, |
| 94 | + self.dummy_input, |
| 95 | + onnx_output_path, |
| 96 | + opset_version=SerializationSettings.onnx_opset, |
| 97 | + input_names=self.input_names, |
| 98 | + output_names=self.output_names, |
| 99 | + dynamic_axes=self.dynamic_axes, |
| 100 | + ) |
73 | 101 | logger.info(f"Exported {onnx_output_path}")
|
0 commit comments