-
Notifications
You must be signed in to change notification settings - Fork 7.2k
[rllib] Add docs on how to use TF eager execution #4927
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
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
f461009
docs
ericl 16cfd8f
eager docs
ericl 72a0c7e
test
ericl f9da578
note
ericl c1605eb
auto eager
ericl 558c704
typo
ericl a69324f
cast comment
ericl fa31649
raise error
ericl 77daae0
add asserts
ericl 84b0553
support eager with ppo
ericl e9e0c73
a2c eager
ericl eea2099
Merge remote-tracking branch 'upstream/master' into eager-docs
ericl 1efb0c3
stats
ericl 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -367,6 +367,13 @@ The ``"monitor": true`` config can be used to save Gym episode videos to the res | |
| openaigym.video.0.31403.video000000.meta.json | ||
| openaigym.video.0.31403.video000000.mp4 | ||
|
|
||
| TensorFlow Eager | ||
| ~~~~~~~~~~~~~~~~ | ||
|
|
||
| While RLlib uses TF graph mode for all computations, you can still leverage TF eager to inspect the intermediate state of computations using `tf.py_function <https://www.tensorflow.org/api_docs/python/tf/py_function>`__. Here's an example of using eager mode in `a custom RLlib model and loss <https://github.com/ray-project/ray/blob/master/python/ray/rllib/examples/eager_execution.py>`__. | ||
|
|
||
| There is also experimental support for running the entire loss function in eager mode. This can be enabled with ``use_eager: True``, e.g., ``rllib train --env=CartPole-v0 --run=PPO --config='{"use_eager": true, "simple_optimizer": true}'``. However this currently only works for a couple algorithms. | ||
|
Contributor
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. can you specify "a couple"
Contributor
Author
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. Going to fill this out in ModelV2 -- hopefully by that time we will support most algos. |
||
|
|
||
| Episode Traces | ||
| ~~~~~~~~~~~~~~ | ||
|
|
||
|
|
||
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,101 @@ | ||
| from __future__ import absolute_import | ||
| from __future__ import division | ||
| from __future__ import print_function | ||
|
|
||
| import argparse | ||
| import random | ||
|
|
||
| import ray | ||
| from ray import tune | ||
| from ray.rllib.agents.trainer_template import build_trainer | ||
| from ray.rllib.models import FullyConnectedNetwork, Model, ModelCatalog | ||
| from ray.rllib.policy.sample_batch import SampleBatch | ||
| from ray.rllib.policy.tf_policy_template import build_tf_policy | ||
| from ray.rllib.utils import try_import_tf | ||
|
|
||
| tf = try_import_tf() | ||
|
|
||
| parser = argparse.ArgumentParser() | ||
| parser.add_argument("--iters", type=int, default=200) | ||
|
|
||
|
|
||
| class EagerModel(Model): | ||
| """Example of using embedded eager execution in a custom model. | ||
|
|
||
| This shows how to use tf.py_function() to execute a snippet of TF code | ||
| in eager mode. Here the `self.forward_eager` method just prints out | ||
| the intermediate tensor for debug purposes, but you can in general | ||
| perform any TF eager operation in tf.py_function(). | ||
| """ | ||
|
|
||
| def _build_layers_v2(self, input_dict, num_outputs, options): | ||
| self.fcnet = FullyConnectedNetwork(input_dict, self.obs_space, | ||
| self.action_space, num_outputs, | ||
| options) | ||
| feature_out = tf.py_function(self.forward_eager, | ||
| [self.fcnet.last_layer], tf.float32) | ||
|
|
||
| with tf.control_dependencies([feature_out]): | ||
| return tf.identity(self.fcnet.outputs), feature_out | ||
|
|
||
| def forward_eager(self, feature_layer): | ||
| assert tf.executing_eagerly() | ||
| if random.random() > 0.99: | ||
| print("Eagerly printing the feature layer mean value", | ||
| tf.reduce_mean(feature_layer)) | ||
| return feature_layer | ||
|
|
||
|
|
||
| def policy_gradient_loss(policy, batch_tensors): | ||
| """Example of using embedded eager execution in a custom loss. | ||
|
|
||
| Here `compute_penalty` prints the actions and rewards for debugging, and | ||
| also computes a (dummy) penalty term to add to the loss. | ||
|
|
||
| Alternatively, you can set config["use_eager"] = True, which will try to | ||
| automatically eagerify the entire loss function. However, this only works | ||
| if your loss doesn't reference any non-eager tensors. It also won't work | ||
| with the multi-GPU optimizer used by PPO. | ||
| """ | ||
|
|
||
| def compute_penalty(actions, rewards): | ||
| assert tf.executing_eagerly() | ||
| penalty = tf.reduce_mean(tf.cast(actions, tf.float32)) | ||
| if random.random() > 0.9: | ||
| print("The eagerly computed penalty is", penalty, actions, rewards) | ||
| return penalty | ||
|
|
||
| actions = batch_tensors[SampleBatch.ACTIONS] | ||
| rewards = batch_tensors[SampleBatch.REWARDS] | ||
| penalty = tf.py_function( | ||
| compute_penalty, [actions, rewards], Tout=tf.float32) | ||
|
|
||
| return penalty - tf.reduce_mean(policy.action_dist.logp(actions) * rewards) | ||
|
|
||
|
|
||
| # <class 'ray.rllib.policy.tf_policy_template.MyTFPolicy'> | ||
| MyTFPolicy = build_tf_policy( | ||
| name="MyTFPolicy", | ||
| loss_fn=policy_gradient_loss, | ||
| ) | ||
|
|
||
| # <class 'ray.rllib.agents.trainer_template.MyCustomTrainer'> | ||
| MyTrainer = build_trainer( | ||
| name="MyCustomTrainer", | ||
| default_policy=MyTFPolicy, | ||
| ) | ||
|
|
||
| if __name__ == "__main__": | ||
| ray.init() | ||
| args = parser.parse_args() | ||
| ModelCatalog.register_custom_model("eager_model", EagerModel) | ||
| tune.run( | ||
| MyTrainer, | ||
| stop={"training_iteration": args.iters}, | ||
| config={ | ||
| "env": "CartPole-v0", | ||
| "num_workers": 0, | ||
| "model": { | ||
| "custom_model": "eager_model" | ||
| }, | ||
| }) |
This file contains hidden or 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
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.
So is the trick mainly to run py_functions in the static mode?
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.
Yep. Right now this is limited to loss_fn, but with ModelV2 this can also include the model forward pass.