-
Notifications
You must be signed in to change notification settings - Fork 5.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[RLlib] ONNX example script: Enhance to work with torch + LSTM #43592
Merged
sven1977
merged 8 commits into
ray-project:master
from
sven1977:onnx_example_script_for_torch_plus_lstm
Jun 14, 2024
+145
−0
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
9ea6037
wip
sven1977 bbbb145
Merge branch 'master' of https://github.com/ray-project/ray into onnx…
sven1977 5e99eb9
Merge branch 'master' of https://github.com/ray-project/ray into onnx…
sven1977 e62ba19
lstm example working fine (with --use-lstm) option
sven1977 f23ae6e
wip
sven1977 305586b
wip
sven1977 0b94078
Merge branch 'master' of https://github.com/ray-project/ray into onnx…
sven1977 fd5e479
wip
sven1977 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
# @OldAPIStack | ||
|
||
import numpy as np | ||
import onnxruntime | ||
|
||
import ray | ||
import ray.rllib.algorithms.ppo as ppo | ||
from ray.rllib.utils.framework import try_import_torch | ||
from ray.rllib.utils.test_utils import add_rllib_example_script_args, check | ||
from ray.rllib.utils.torch_utils import convert_to_torch_tensor | ||
|
||
torch, _ = try_import_torch() | ||
|
||
parser = add_rllib_example_script_args() | ||
parser.set_defaults(num_env_runners=1) | ||
|
||
|
||
class ONNXCompatibleWrapper(torch.nn.Module): | ||
def __init__(self, original_model): | ||
super(ONNXCompatibleWrapper, self).__init__() | ||
self.original_model = original_model | ||
|
||
def forward(self, a, b0, b1, c): | ||
# Convert the separate tensor inputs back into the list format | ||
# expected by the original model's forward method. | ||
b = [b0, b1] | ||
ret = self.original_model({"obs": a}, b, c) | ||
# results, state_out_0, state_out_1 | ||
return ret[0], ret[1][0], ret[1][1] | ||
|
||
|
||
if __name__ == "__main__": | ||
args = parser.parse_args() | ||
|
||
ray.init(local_mode=args.local_mode) | ||
|
||
# Configure our PPO Algorithm. | ||
config = ( | ||
ppo.PPOConfig() | ||
# ONNX is not supported by RLModule API yet. | ||
.api_stack( | ||
enable_rl_module_and_learner=args.enable_new_api_stack, | ||
enable_env_runner_and_connector_v2=args.enable_new_api_stack, | ||
) | ||
.environment("CartPole-v1") | ||
.env_runners(num_env_runners=args.num_env_runners) | ||
.training(model={"use_lstm": True}) | ||
) | ||
|
||
B = 3 | ||
T = 5 | ||
LSTM_CELL = 256 | ||
|
||
# Input data for a python inference forward call. | ||
test_data_python = { | ||
"obs": np.random.uniform(0, 1.0, size=(B * T, 4)).astype(np.float32), | ||
"state_ins": [ | ||
np.random.uniform(0, 1.0, size=(B, LSTM_CELL)).astype(np.float32), | ||
np.random.uniform(0, 1.0, size=(B, LSTM_CELL)).astype(np.float32), | ||
], | ||
"seq_lens": np.array([T] * B, np.float32), | ||
} | ||
# Input data for the ONNX session. | ||
test_data_onnx = { | ||
"obs": test_data_python["obs"], | ||
"state_in_0": test_data_python["state_ins"][0], | ||
"state_in_1": test_data_python["state_ins"][1], | ||
"seq_lens": test_data_python["seq_lens"], | ||
} | ||
|
||
# Input data for compiling the ONNX model. | ||
test_data_onnx_input = convert_to_torch_tensor(test_data_onnx) | ||
|
||
# Initialize a PPO Algorithm. | ||
algo = config.build() | ||
|
||
# You could train the model here | ||
# algo.train() | ||
|
||
# Let's run inference on the torch model | ||
policy = algo.get_policy() | ||
result_pytorch, _ = policy.model( | ||
{ | ||
"obs": torch.tensor(test_data_python["obs"]), | ||
}, | ||
[ | ||
torch.tensor(test_data_python["state_ins"][0]), | ||
torch.tensor(test_data_python["state_ins"][1]), | ||
], | ||
torch.tensor(test_data_python["seq_lens"]), | ||
) | ||
|
||
# Evaluate tensor to fetch numpy array | ||
result_pytorch = result_pytorch.detach().numpy() | ||
|
||
# This line will export the model to ONNX. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The comment is a bid misleading - I guess it was intended for the code block below? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
onnx_compatible = ONNXCompatibleWrapper(policy.model) | ||
exported_model_file = "model.onnx" | ||
input_names = [ | ||
"obs", | ||
"state_in_0", | ||
"state_in_1", | ||
"seq_lens", | ||
] | ||
|
||
torch.onnx.export( | ||
onnx_compatible, | ||
tuple(test_data_onnx_input[n] for n in input_names), | ||
exported_model_file, | ||
export_params=True, | ||
opset_version=11, | ||
do_constant_folding=True, | ||
input_names=input_names, | ||
output_names=[ | ||
"output", | ||
"state_out_0", | ||
"state_out_1", | ||
], | ||
dynamic_axes={k: {0: "batch_size"} for k in input_names}, | ||
) | ||
# Start an inference session for the ONNX model | ||
session = onnxruntime.InferenceSession(exported_model_file, None) | ||
result_onnx = session.run(["output"], test_data_onnx) | ||
|
||
# These results should be equal! | ||
print("PYTORCH", result_pytorch) | ||
print("ONNX", result_onnx[0]) | ||
|
||
check(result_pytorch, result_onnx[0]) | ||
print("Model outputs are equal. PASSED") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If
enable_rl_module_and_learner
isTrue
, it needs themodel_config
inrl_module(model_config_dict= ...)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
True, but this examples does NOT work yet on the new stack. I'll add an assert that --enable-new-api-stack is off.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done