forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Feature] Make ProbabilisticActor compatible with Composite distribut…
…ions (pytorch#2220)
- Loading branch information
Showing
3 changed files
with
170 additions
and
7 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# | ||
# This source code is licensed under the MIT license found in the | ||
# LICENSE file in the root directory of this source tree. | ||
|
||
|
||
""" | ||
This code exemplifies how a composite actor can be built. | ||
The actor has two components: a categorical and a normal distributions. | ||
We use a ProbabilisticActor and explicitly pass it the key-map that we want through a 'name_map' | ||
argument. | ||
""" | ||
|
||
import torch | ||
from tensordict import TensorDict | ||
from tensordict.nn import CompositeDistribution, TensorDictModule | ||
from torch import distributions as d, nn | ||
|
||
from torchrl.modules import ProbabilisticActor | ||
|
||
|
||
class Module(nn.Module): | ||
def forward(self, x): | ||
return x[..., :3], x[..., 3:6], x[..., 6:] | ||
|
||
|
||
module = TensorDictModule( | ||
Module(), | ||
in_keys=["x"], | ||
out_keys=[ | ||
("params", "normal", "loc"), | ||
("params", "normal", "scale"), | ||
("params", "categ", "logits"), | ||
], | ||
) | ||
actor = ProbabilisticActor( | ||
module, | ||
in_keys=["params"], | ||
distribution_class=CompositeDistribution, | ||
distribution_kwargs={ | ||
"distribution_map": {"normal": d.Normal, "categ": d.Categorical}, | ||
"name_map": {"normal": ("action", "normal"), "categ": ("action", "categ")}, | ||
}, | ||
) | ||
print(actor.out_keys) | ||
|
||
data = TensorDict({"x": torch.rand(10)}, []) | ||
module(data) | ||
print(actor(data)) |
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