add recurrent actor and critic

This commit is contained in:
Trinkle23897 2020-04-30 16:31:40 +08:00
parent 134f787e24
commit c2a7caf806
3 changed files with 74 additions and 14 deletions

View File

@ -71,16 +71,74 @@ class Critic(nn.Module):
self.model += [nn.Linear(128, 1)]
self.model = nn.Sequential(*self.model)
def forward(self, s, a=None, **kwargs):
if not isinstance(s, torch.Tensor):
s = torch.tensor(s, device=self.device, dtype=torch.float)
batch = s.shape[0]
s = s.view(batch, -1)
if a is not None:
if not isinstance(a, torch.Tensor):
a = torch.tensor(a, device=self.device, dtype=torch.float)
a = a.view(batch, -1)
s = torch.cat([s, a], dim=1)
logits = self.model(s)
return logits
class RecurrentActorProb(nn.Module):
def __init__(self, layer_num, state_shape, action_shape,
max_action, device='cpu'):
super().__init__()
self.device = device
self.nn = nn.LSTM(input_size=np.prod(state_shape), hidden_size=128,
num_layers=layer_num, batch_first=True)
self.mu = nn.Linear(128, np.prod(action_shape))
self.sigma = nn.Parameter(torch.zeros(np.prod(action_shape), 1))
def forward(self, s, **kwargs):
if not isinstance(s, torch.Tensor):
s = torch.tensor(s, device=self.device, dtype=torch.float)
# s [bsz, len, dim] (training) or [bsz, dim] (evaluation)
# In short, the tensor's shape in training phase is longer than which
# in evaluation phase.
if len(s.shape) == 2:
bsz, dim = s.shape
length = 1
else:
bsz, length, dim = s.shape
s = s.view(bsz, length, -1)
logits, _ = self.nn(s)
logits = logits[:, -1]
mu = self.mu(logits)
shape = [1] * len(mu.shape)
shape[1] = -1
sigma = (self.sigma.view(shape) + torch.zeros_like(mu)).exp()
return (mu, sigma), None
class RecurrentCritic(nn.Module):
def __init__(self, layer_num, state_shape, action_shape=0, device='cpu'):
super().__init__()
self.state_shape = state_shape
self.action_shape = action_shape
self.device = device
self.nn = nn.LSTM(input_size=np.prod(state_shape), hidden_size=128,
num_layers=layer_num, batch_first=True)
self.fc2 = nn.Linear(128 + np.prod(action_shape), 1)
def forward(self, s, a=None):
if not isinstance(s, torch.Tensor):
s = torch.tensor(s, device=self.device, dtype=torch.float)
if a is not None and not isinstance(a, torch.Tensor):
a = torch.tensor(a, device=self.device, dtype=torch.float)
batch = s.shape[0]
s = s.view(batch, -1)
if a is None:
logits = self.model(s)
else:
a = a.view(batch, -1)
logits = self.model(torch.cat([s, a], dim=1))
return logits
# s [bsz, len, dim] (training) or [bsz, dim] (evaluation)
# In short, the tensor's shape in training phase is longer than which
# in evaluation phase.
assert len(s.shape) == 3
self.nn.flatten_parameters()
s, (h, c) = self.nn(s)
s = s[:, -1]
if a is not None:
if not isinstance(a, torch.Tensor):
a = torch.tensor(a, device=self.device, dtype=torch.float)
s = torch.cat([s, a], dim=1)
s = self.fc2(s)
return s

View File

@ -47,8 +47,8 @@ class Critic(nn.Module):
self.preprocess = preprocess_net
self.last = nn.Linear(128, 1)
def forward(self, s):
logits, h = self.preprocess(s, None)
def forward(self, s, **kwargs):
logits, h = self.preprocess(s, state=kwargs.get('state', None))
logits = self.last(logits)
return logits
@ -85,7 +85,7 @@ class Recurrent(nn.Module):
# but pytorch rnn needs [len, bsz, ...]
s, (h, c) = self.nn(s, (state['h'].transpose(0, 1).contiguous(),
state['c'].transpose(0, 1).contiguous()))
s = self.fc2(s)[:, -1]
s = self.fc2(s[:, -1])
# please ensure the first dim is batch size: [bsz, len, ...]
return s, {'h': h.transpose(0, 1).detach(),
'c': c.transpose(0, 1).detach()}

View File

@ -5,7 +5,7 @@ from tianshou.data.batch import Batch
class ReplayBuffer(object):
""":class:`~tianshou.data.ReplayBuffer` stores data generated from
interaction between the policy and environment. It stores basically 6 types
interaction between the policy and environment. It stores basically 7 types
of data, as mentioned in :class:`~tianshou.data.Batch`, based on
``numpy.ndarray``. Here is the usage:
::
@ -282,6 +282,7 @@ class ReplayBuffer(object):
return Batch(
obs=self.get(index, 'obs'),
act=self.act[index],
# act_=self.get(index, 'act'), # stacked action, for RNN
rew=self.rew[index],
done=self.done[index],
obs_next=self.get(index, 'obs_next'),
@ -405,6 +406,7 @@ class PrioritizedReplayBuffer(ReplayBuffer):
return Batch(
obs=self.get(index, 'obs'),
act=self.act[index],
# act_=self.get(index, 'act'), # stacked action, for RNN
rew=self.rew[index],
done=self.done[index],
obs_next=self.get(index, 'obs_next'),