add recurrent actor and critic
This commit is contained in:
parent
134f787e24
commit
c2a7caf806
@ -71,16 +71,74 @@ class Critic(nn.Module):
|
|||||||
self.model += [nn.Linear(128, 1)]
|
self.model += [nn.Linear(128, 1)]
|
||||||
self.model = nn.Sequential(*self.model)
|
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):
|
def forward(self, s, a=None):
|
||||||
if not isinstance(s, torch.Tensor):
|
if not isinstance(s, torch.Tensor):
|
||||||
s = torch.tensor(s, device=self.device, dtype=torch.float)
|
s = torch.tensor(s, device=self.device, dtype=torch.float)
|
||||||
if a is not None and not isinstance(a, torch.Tensor):
|
# 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)
|
a = torch.tensor(a, device=self.device, dtype=torch.float)
|
||||||
batch = s.shape[0]
|
s = torch.cat([s, a], dim=1)
|
||||||
s = s.view(batch, -1)
|
s = self.fc2(s)
|
||||||
if a is None:
|
return s
|
||||||
logits = self.model(s)
|
|
||||||
else:
|
|
||||||
a = a.view(batch, -1)
|
|
||||||
logits = self.model(torch.cat([s, a], dim=1))
|
|
||||||
return logits
|
|
||||||
|
@ -47,8 +47,8 @@ class Critic(nn.Module):
|
|||||||
self.preprocess = preprocess_net
|
self.preprocess = preprocess_net
|
||||||
self.last = nn.Linear(128, 1)
|
self.last = nn.Linear(128, 1)
|
||||||
|
|
||||||
def forward(self, s):
|
def forward(self, s, **kwargs):
|
||||||
logits, h = self.preprocess(s, None)
|
logits, h = self.preprocess(s, state=kwargs.get('state', None))
|
||||||
logits = self.last(logits)
|
logits = self.last(logits)
|
||||||
return logits
|
return logits
|
||||||
|
|
||||||
@ -85,7 +85,7 @@ class Recurrent(nn.Module):
|
|||||||
# but pytorch rnn needs [len, bsz, ...]
|
# but pytorch rnn needs [len, bsz, ...]
|
||||||
s, (h, c) = self.nn(s, (state['h'].transpose(0, 1).contiguous(),
|
s, (h, c) = self.nn(s, (state['h'].transpose(0, 1).contiguous(),
|
||||||
state['c'].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, ...]
|
# please ensure the first dim is batch size: [bsz, len, ...]
|
||||||
return s, {'h': h.transpose(0, 1).detach(),
|
return s, {'h': h.transpose(0, 1).detach(),
|
||||||
'c': c.transpose(0, 1).detach()}
|
'c': c.transpose(0, 1).detach()}
|
||||||
|
@ -5,7 +5,7 @@ from tianshou.data.batch import Batch
|
|||||||
|
|
||||||
class ReplayBuffer(object):
|
class ReplayBuffer(object):
|
||||||
""":class:`~tianshou.data.ReplayBuffer` stores data generated from
|
""":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
|
of data, as mentioned in :class:`~tianshou.data.Batch`, based on
|
||||||
``numpy.ndarray``. Here is the usage:
|
``numpy.ndarray``. Here is the usage:
|
||||||
::
|
::
|
||||||
@ -282,6 +282,7 @@ class ReplayBuffer(object):
|
|||||||
return Batch(
|
return Batch(
|
||||||
obs=self.get(index, 'obs'),
|
obs=self.get(index, 'obs'),
|
||||||
act=self.act[index],
|
act=self.act[index],
|
||||||
|
# act_=self.get(index, 'act'), # stacked action, for RNN
|
||||||
rew=self.rew[index],
|
rew=self.rew[index],
|
||||||
done=self.done[index],
|
done=self.done[index],
|
||||||
obs_next=self.get(index, 'obs_next'),
|
obs_next=self.get(index, 'obs_next'),
|
||||||
@ -405,6 +406,7 @@ class PrioritizedReplayBuffer(ReplayBuffer):
|
|||||||
return Batch(
|
return Batch(
|
||||||
obs=self.get(index, 'obs'),
|
obs=self.get(index, 'obs'),
|
||||||
act=self.act[index],
|
act=self.act[index],
|
||||||
|
# act_=self.get(index, 'act'), # stacked action, for RNN
|
||||||
rew=self.rew[index],
|
rew=self.rew[index],
|
||||||
done=self.done[index],
|
done=self.done[index],
|
||||||
obs_next=self.get(index, 'obs_next'),
|
obs_next=self.get(index, 'obs_next'),
|
||||||
|
Loading…
x
Reference in New Issue
Block a user