-
Notifications
You must be signed in to change notification settings - Fork 373
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
feature(cy): add dreamerV3 + MiniGrid code #725
Merged
Merged
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
46b5d86
support flat obs, discrete action;
Cloud-Pku 5ba6e68
fix one bug
Cloud-Pku ed40912
fix eval bug
Cloud-Pku ea82987
modify minigrid wrapper
Cloud-Pku 3ac1d8f
modify something
Cloud-Pku 6b15f52
fix onething
Cloud-Pku f91f130
polish & style check
Cloud-Pku d8df1e4
Merge branch 'main' of https://github.com/Cloud-Pku/DI-engine into dr…
Cloud-Pku 9c8f3b9
polish the code
Cloud-Pku dd60dce
Merge branch 'main' into dreamer_modify
Cloud-Pku 5cd6a4a
code polish
Cloud-Pku 2f45977
polish code
Cloud-Pku 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
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 |
---|---|---|
|
@@ -5,7 +5,7 @@ | |
|
||
from ding.utils import WORLD_MODEL_REGISTRY, lists_to_dicts | ||
from ding.utils.data import default_collate | ||
from ding.model import ConvEncoder | ||
from ding.model import ConvEncoder, FCEncoder | ||
from ding.world_model.base_world_model import WorldModel | ||
from ding.world_model.model.networks import RSSM, ConvDecoder | ||
from ding.torch_utils import to_device | ||
|
@@ -37,6 +37,7 @@ class DREAMERWorldModel(WorldModel, nn.Module): | |
norm='LayerNorm', | ||
grad_heads=['image', 'reward', 'discount'], | ||
units=512, | ||
image_dec_layers=2, | ||
reward_layers=2, | ||
discount_layers=2, | ||
value_layers=2, | ||
|
@@ -72,21 +73,26 @@ def __init__(self, cfg, env, tb_logger): | |
self._cfg.norm = nn.modules.normalization.LayerNorm # nn.LayerNorm | ||
self.state_size = self._cfg.state_size | ||
self.action_size = self._cfg.action_size | ||
self.action_type = self._cfg.action_type | ||
self.reward_size = self._cfg.reward_size | ||
self.hidden_size = self._cfg.hidden_size | ||
self.batch_size = self._cfg.batch_size | ||
if isinstance(self.state_size, int): | ||
self.encoder = FCEncoder(self.state_size, self._cfg.encoder_hidden_size_list, activation=torch.nn.SiLU()) | ||
PaParaZz1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.embed_size = self._cfg.encoder_hidden_size_list[-1] | ||
elif len(self.state_size) == 3: | ||
self.encoder = ConvEncoder( | ||
self.state_size, | ||
hidden_size_list=[32, 64, 128, 256, 4096], # to last layer 128? | ||
activation=torch.nn.SiLU(), | ||
kernel_size=self._cfg.encoder_kernels, | ||
layer_norm=True | ||
) | ||
self.embed_size = ( | ||
(self.state_size[1] // 2 ** (len(self._cfg.encoder_kernels))) ** 2 * self._cfg.cnn_depth * | ||
2 ** (len(self._cfg.encoder_kernels) - 1) | ||
) | ||
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. add else branch for better error hints |
||
|
||
self.encoder = ConvEncoder( | ||
self.state_size, | ||
hidden_size_list=[32, 64, 128, 256, 4096], # to last layer 128? | ||
activation=torch.nn.SiLU(), | ||
kernel_size=self._cfg.encoder_kernels, | ||
layer_norm=True | ||
) | ||
self.embed_size = ( | ||
(self.state_size[1] // 2 ** (len(self._cfg.encoder_kernels))) ** 2 * self._cfg.cnn_depth * | ||
2 ** (len(self._cfg.encoder_kernels) - 1) | ||
) | ||
self.dynamics = RSSM( | ||
self._cfg.dyn_stoch, | ||
self._cfg.dyn_deter, | ||
|
@@ -113,14 +119,28 @@ def __init__(self, cfg, env, tb_logger): | |
feat_size = self._cfg.dyn_stoch * self._cfg.dyn_discrete + self._cfg.dyn_deter | ||
else: | ||
feat_size = self._cfg.dyn_stoch + self._cfg.dyn_deter | ||
self.heads["image"] = ConvDecoder( | ||
feat_size, # pytorch version | ||
self._cfg.cnn_depth, | ||
self._cfg.act, | ||
self._cfg.norm, | ||
self.state_size, | ||
self._cfg.decoder_kernels, | ||
) | ||
|
||
if isinstance(self.state_size, int): | ||
self.heads['image'] = DenseHead( | ||
feat_size, | ||
(self.state_size, ), | ||
PaParaZz1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self._cfg.image_dec_layers, | ||
self._cfg.units, | ||
'SiLU', # self._cfg.act | ||
'LN', # self._cfg.norm | ||
dist='binary', | ||
outscale=0.0, | ||
device=self._cfg.device, | ||
) | ||
elif len(self.state_size) == 3: | ||
self.heads["image"] = ConvDecoder( | ||
feat_size, # pytorch version | ||
self._cfg.cnn_depth, | ||
self._cfg.act, | ||
self._cfg.norm, | ||
self.state_size, | ||
self._cfg.decoder_kernels, | ||
) | ||
self.heads["reward"] = DenseHead( | ||
feat_size, # dyn_stoch * dyn_discrete + dyn_deter | ||
(255, ), | ||
|
@@ -172,9 +192,31 @@ def train(self, env_buffer, envstep, train_iter, batch_size, batch_length): | |
data = {k: torch.stack(data[k], dim=1) for k in data} # -> {dict_key: Tensor([B, T, any_dims])} | ||
|
||
data['discount'] = data.get('discount', 1.0 - data['done'].float()) | ||
data['discount'] *= 0.997 | ||
data['weight'] = data.get('weight', None) | ||
data['image'] = data['obs'] - 0.5 | ||
if type(self.state_size) != int and len(self.state_size) == 3: | ||
data['image'] = data['obs'] - 0.5 | ||
else: | ||
data['image'] = data['obs'] | ||
if self.action_type == 'continuous': | ||
data['action'] *= (1.0 / torch.clip(torch.abs(data['action']), min=1.0)) | ||
else: | ||
|
||
def make_one_hot(x, num_classes): | ||
"""Convert class index tensor to one hot encoding tensor. | ||
Args: | ||
input: A tensor of shape [bs, 1, *] | ||
num_classes: An int of number of class | ||
Returns: | ||
A tensor of shape [bs, num_classes, *] | ||
""" | ||
x = x.to(torch.int64) | ||
shape = (*tuple(x.shape), num_classes) | ||
x = x.unsqueeze(-1) | ||
res = torch.zeros(shape).to(x) | ||
res = res.scatter_(-1, x, 1) | ||
return res.float() | ||
|
||
data['action'] = make_one_hot(data['action'], self.action_size) | ||
PaParaZz1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
data = to_device(data, self._cfg.device) | ||
if len(data['reward'].shape) == 2: | ||
data['reward'] = data['reward'].unsqueeze(-1) | ||
|
@@ -185,9 +227,9 @@ def train(self, env_buffer, envstep, train_iter, batch_size, batch_length): | |
|
||
self.requires_grad_(requires_grad=True) | ||
|
||
image = data['image'].reshape([-1] + list(data['image'].shape[-3:])) | ||
image = data['image'].reshape([-1] + list(data['image'].shape[2:])) | ||
embed = self.encoder(image) | ||
embed = embed.reshape(list(data['image'].shape[:-3]) + [embed.shape[-1]]) | ||
embed = embed.reshape(list(data['image'].shape[:2]) + [embed.shape[-1]]) | ||
|
||
post, prior = self.dynamics.observe(embed, data["action"]) | ||
kl_loss, kl_value, loss_lhs, loss_rhs = self.dynamics.kl_loss( | ||
|
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
Oops, something went wrong.
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.
add an assertion at the first occurrence of this string comparison