TuTuHuss
commited on
Commit
·
6340080
1
Parent(s):
918fbe1
update(hus): update additional file and data from official server
Browse files- README.md +24 -0
- ppof_ch4_code_p1.py +324 -0
- ppof_ch4_data_lunarlander.pkl +3 -0
- ppof_ch4_data_p1.zip +3 -0
- ppof_ch5_code_p1.py +193 -0
- ppof_ch6_code_p1.py +79 -0
- ppof_ch7_code_p1.py +114 -0
- ppof_logo.png +0 -0
README.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
---
|
| 4 |
+
|
| 5 |
+
<div align="center">
|
| 6 |
+
<a href="https://github.com/opendilab/PPOxFamily"><img width="500px" height="auto" src="./ppof_logo.png"></a>
|
| 7 |
+
</div>
|
| 8 |
+
|
| 9 |
+
# PPO x Family 决策智能入门公开课
|
| 10 |
+
欢迎来到 [**PPO x Family**](https://github.com/opendilab/PPOxFamily) 系列决策智能入门公开课。该系列将深入理解深度强化学习算法 PPO ,灵活运用**一个 PPO 算法**解决几乎**所有常见的决策智能应用** ,帮助一切对于深度强化学习技术有好奇心的人,轻便且高效地制作应用原型,了解和学习最强大最易用的 PPO Family 。
|
| 11 |
+
|
| 12 |
+
# NEWS
|
| 13 |
+
|
| 14 |
+
- 2025.03.14: 此存储库用于为[**PPO x Family**](https://github.com/opendilab/PPOxFamily)提供课程作业数据集及其他相关附加材料
|
| 15 |
+
|
| 16 |
+
# File Structure
|
| 17 |
+
|
| 18 |
+
. <br>
|
| 19 |
+
├── README.md <br>
|
| 20 |
+
├── asserts <br>
|
| 21 |
+
└── ppof_logo.png <br>
|
| 22 |
+
├── ppof_ch4_code_p1.py [[1]](https://github.com/opendilab/PPOxFamily/blob/main/chapter4_reward/chapter4_hw_solution.pdf)<br>
|
| 23 |
+
├── ppof_ch4_data_lunarlander.pkl [[1]](https://github.com/opendilab/PPOxFamily/blob/main/chapter4_reward/popart.py) [[2]](https://github.com/opendilab/PPOxFamily/blob/main/chapter4_reward/popart_zh.py)<br>
|
| 24 |
+
├── ppof_ch4_data_p1.zip [[1]](https://github.com/opendilab/PPOxFamily/blob/main/chapter4_reward/chapter4_hw_solution.pdf)<br>
|
| 25 |
+
├── ppof_ch5_code_p1.py [[1]](https://github.com/opendilab/PPOxFamily/blob/main/chapter5_time/chapter5_hw_solution.pdf)<br>
|
| 26 |
+
├── ppof_ch6_code_p1.py [[1]](https://github.com/opendilab/PPOxFamily/blob/main/chapter6_marl/chapter6_hw_solution.pdf)<br>
|
| 27 |
+
└── ppof_ch7_code_p1.py[[1]](https://github.com/opendilab/PPOxFamily/blob/main/chapter7_tricks/chapter7_hw_solution.pdf)<br>
|
ppof_ch4_code_p1.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pip install minigrid
|
| 2 |
+
from typing import Union, Tuple, Dict, List, Optional
|
| 3 |
+
from multiprocessing import Process
|
| 4 |
+
import multiprocessing as mp
|
| 5 |
+
import random
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import torch.optim as optim
|
| 11 |
+
import minigrid
|
| 12 |
+
import gymnasium as gym
|
| 13 |
+
from torch.optim.lr_scheduler import ExponentialLR, MultiStepLR
|
| 14 |
+
from tensorboardX import SummaryWriter
|
| 15 |
+
from minigrid.wrappers import FlatObsWrapper
|
| 16 |
+
|
| 17 |
+
random.seed(0)
|
| 18 |
+
np.random.seed(0)
|
| 19 |
+
torch.manual_seed(0)
|
| 20 |
+
if torch.cuda.is_available():
|
| 21 |
+
device = torch.device("cuda:0")
|
| 22 |
+
else:
|
| 23 |
+
device = torch.device("cpu")
|
| 24 |
+
|
| 25 |
+
train_config = dict(
|
| 26 |
+
train_iter=1024,
|
| 27 |
+
train_data_count=128,
|
| 28 |
+
test_data_count=4096,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
little_RND_net_config = dict(
|
| 32 |
+
exp_name="little_rnd_network",
|
| 33 |
+
observation_shape=2835,
|
| 34 |
+
hidden_size_list=[32, 16],
|
| 35 |
+
learning_rate=1e-3,
|
| 36 |
+
batch_size=64,
|
| 37 |
+
update_per_collect=100,
|
| 38 |
+
obs_norm=True,
|
| 39 |
+
obs_norm_clamp_min=-1,
|
| 40 |
+
obs_norm_clamp_max=1,
|
| 41 |
+
reward_mse_ratio=1e5,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
small_RND_net_config = dict(
|
| 45 |
+
exp_name="small_rnd_network",
|
| 46 |
+
observation_shape=2835,
|
| 47 |
+
hidden_size_list=[64, 64],
|
| 48 |
+
learning_rate=1e-3,
|
| 49 |
+
batch_size=64,
|
| 50 |
+
update_per_collect=100,
|
| 51 |
+
obs_norm=True,
|
| 52 |
+
obs_norm_clamp_min=-1,
|
| 53 |
+
obs_norm_clamp_max=1,
|
| 54 |
+
reward_mse_ratio=1e5,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
standard_RND_net_config = dict(
|
| 58 |
+
exp_name="standard_rnd_network",
|
| 59 |
+
observation_shape=2835,
|
| 60 |
+
hidden_size_list=[128, 64],
|
| 61 |
+
learning_rate=1e-3,
|
| 62 |
+
batch_size=64,
|
| 63 |
+
update_per_collect=100,
|
| 64 |
+
obs_norm=True,
|
| 65 |
+
obs_norm_clamp_min=-1,
|
| 66 |
+
obs_norm_clamp_max=1,
|
| 67 |
+
reward_mse_ratio=1e5,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
large_RND_net_config = dict(
|
| 71 |
+
exp_name="large_RND_network",
|
| 72 |
+
observation_shape=2835,
|
| 73 |
+
hidden_size_list=[256, 256],
|
| 74 |
+
learning_rate=1e-3,
|
| 75 |
+
batch_size=64,
|
| 76 |
+
update_per_collect=100,
|
| 77 |
+
obs_norm=True,
|
| 78 |
+
obs_norm_clamp_min=-1,
|
| 79 |
+
obs_norm_clamp_max=1,
|
| 80 |
+
reward_mse_ratio=1e5,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
very_large_RND_net_config = dict(
|
| 84 |
+
exp_name="very_large_RND_network",
|
| 85 |
+
observation_shape=2835,
|
| 86 |
+
hidden_size_list=[512, 512],
|
| 87 |
+
learning_rate=1e-3,
|
| 88 |
+
batch_size=64,
|
| 89 |
+
update_per_collect=100,
|
| 90 |
+
obs_norm=True,
|
| 91 |
+
obs_norm_clamp_min=-1,
|
| 92 |
+
obs_norm_clamp_max=1,
|
| 93 |
+
reward_mse_ratio=1e5,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
class FCEncoder(nn.Module):
|
| 97 |
+
def __init__(
|
| 98 |
+
self,
|
| 99 |
+
obs_shape: int,
|
| 100 |
+
hidden_size_list,
|
| 101 |
+
activation: Optional[nn.Module] = nn.ReLU(),
|
| 102 |
+
) -> None:
|
| 103 |
+
super(FCEncoder, self).__init__()
|
| 104 |
+
self.obs_shape = obs_shape
|
| 105 |
+
self.act = activation
|
| 106 |
+
self.init = nn.Linear(obs_shape, hidden_size_list[0])
|
| 107 |
+
|
| 108 |
+
layers = []
|
| 109 |
+
for i in range(len(hidden_size_list) - 1):
|
| 110 |
+
layers.append(nn.Linear(hidden_size_list[i], hidden_size_list[i + 1]))
|
| 111 |
+
layers.append(self.act)
|
| 112 |
+
self.main = nn.Sequential(*layers)
|
| 113 |
+
|
| 114 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 115 |
+
x = self.act(self.init(x))
|
| 116 |
+
x = self.main(x)
|
| 117 |
+
return x
|
| 118 |
+
|
| 119 |
+
class RndNetwork(nn.Module):
|
| 120 |
+
def __init__(self, obs_shape: Union[int, list], hidden_size_list: list) -> None:
|
| 121 |
+
super(RndNetwork, self).__init__()
|
| 122 |
+
self.target = FCEncoder(obs_shape, hidden_size_list)
|
| 123 |
+
self.predictor = FCEncoder(obs_shape, hidden_size_list)
|
| 124 |
+
|
| 125 |
+
for param in self.target.parameters():
|
| 126 |
+
param.requires_grad = False
|
| 127 |
+
|
| 128 |
+
def forward(self, obs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 129 |
+
predict_feature = self.predictor(obs)
|
| 130 |
+
with torch.no_grad():
|
| 131 |
+
target_feature = self.target(obs)
|
| 132 |
+
return predict_feature, target_feature
|
| 133 |
+
|
| 134 |
+
class RunningMeanStd(object):
|
| 135 |
+
def __init__(self, epsilon=1e-4, shape=(), device=torch.device('cpu')):
|
| 136 |
+
self._epsilon = epsilon
|
| 137 |
+
self._shape = shape
|
| 138 |
+
self._device = device
|
| 139 |
+
self.reset()
|
| 140 |
+
|
| 141 |
+
def update(self, x):
|
| 142 |
+
batch_mean = np.mean(x, axis=0)
|
| 143 |
+
batch_var = np.var(x, axis=0)
|
| 144 |
+
batch_count = x.shape[0]
|
| 145 |
+
|
| 146 |
+
new_count = batch_count + self._count
|
| 147 |
+
mean_delta = batch_mean - self._mean
|
| 148 |
+
new_mean = self._mean + mean_delta * batch_count / new_count
|
| 149 |
+
# this method for calculating new variable might be numerically unstable
|
| 150 |
+
m_a = self._var * self._count
|
| 151 |
+
m_b = batch_var * batch_count
|
| 152 |
+
m2 = m_a + m_b + np.square(mean_delta) * self._count * batch_count / new_count
|
| 153 |
+
new_var = m2 / new_count
|
| 154 |
+
self._mean = new_mean
|
| 155 |
+
self._var = new_var
|
| 156 |
+
self._count = new_count
|
| 157 |
+
|
| 158 |
+
def reset(self):
|
| 159 |
+
if len(self._shape) > 0:
|
| 160 |
+
self._mean = np.zeros(self._shape, 'float32')
|
| 161 |
+
self._var = np.ones(self._shape, 'float32')
|
| 162 |
+
else:
|
| 163 |
+
self._mean, self._var = 0., 1.
|
| 164 |
+
self._count = self._epsilon
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def mean(self) -> np.ndarray:
|
| 168 |
+
if np.isscalar(self._mean):
|
| 169 |
+
return self._mean
|
| 170 |
+
else:
|
| 171 |
+
return torch.FloatTensor(self._mean).to(self._device)
|
| 172 |
+
|
| 173 |
+
@property
|
| 174 |
+
def std(self) -> np.ndarray:
|
| 175 |
+
std = np.sqrt(self._var + 1e-8)
|
| 176 |
+
if np.isscalar(std):
|
| 177 |
+
return std
|
| 178 |
+
else:
|
| 179 |
+
return torch.FloatTensor(std).to(self._device)
|
| 180 |
+
|
| 181 |
+
class RndRewardModel():
|
| 182 |
+
|
| 183 |
+
def __init__(self, config) -> None: # noqa
|
| 184 |
+
super(RndRewardModel, self).__init__()
|
| 185 |
+
self.cfg = config
|
| 186 |
+
|
| 187 |
+
self.tb_logger = SummaryWriter(config["exp_name"])
|
| 188 |
+
self.reward_model = RndNetwork(
|
| 189 |
+
obs_shape=config["observation_shape"], hidden_size_list=config["hidden_size_list"]
|
| 190 |
+
).to(device)
|
| 191 |
+
|
| 192 |
+
self.opt = optim.Adam(self.reward_model.predictor.parameters(), config["learning_rate"])
|
| 193 |
+
self.scheduler = ExponentialLR(self.opt, gamma=0.997)
|
| 194 |
+
|
| 195 |
+
self.estimate_cnt_rnd = 0
|
| 196 |
+
if self.cfg["obs_norm"]:
|
| 197 |
+
self._running_mean_std_rnd_obs = RunningMeanStd(epsilon=1e-4, device=device)
|
| 198 |
+
|
| 199 |
+
def __del__(self):
|
| 200 |
+
self.tb_logger.flush()
|
| 201 |
+
self.tb_logger.close()
|
| 202 |
+
|
| 203 |
+
def train(self, data) -> None:
|
| 204 |
+
for _ in range(self.cfg["update_per_collect"]):
|
| 205 |
+
train_data: list = random.sample(data, self.cfg["batch_size"])
|
| 206 |
+
train_data: torch.Tensor = torch.stack(train_data).to(device)
|
| 207 |
+
if self.cfg["obs_norm"]:
|
| 208 |
+
# Note: observation normalization: transform obs to mean 0, std 1
|
| 209 |
+
self._running_mean_std_rnd_obs.update(train_data.cpu().numpy())
|
| 210 |
+
train_data = (train_data - self._running_mean_std_rnd_obs.mean) / self._running_mean_std_rnd_obs.std
|
| 211 |
+
train_data = torch.clamp(
|
| 212 |
+
train_data, min=self.cfg["obs_norm_clamp_min"], max=self.cfg["obs_norm_clamp_max"]
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
predict_feature, target_feature = self.reward_model(train_data)
|
| 216 |
+
loss = F.mse_loss(predict_feature, target_feature.detach())
|
| 217 |
+
self.opt.zero_grad()
|
| 218 |
+
loss.backward()
|
| 219 |
+
self.opt.step()
|
| 220 |
+
self.scheduler.step()
|
| 221 |
+
|
| 222 |
+
def estimate(self, data: list) -> List[Dict]:
|
| 223 |
+
"""
|
| 224 |
+
estimate the rnd intrinsic reward
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
obs = torch.stack(data).to(device)
|
| 228 |
+
if self.cfg["obs_norm"]:
|
| 229 |
+
# Note: observation normalization: transform obs to mean 0, std 1
|
| 230 |
+
obs = (obs - self._running_mean_std_rnd_obs.mean) / self._running_mean_std_rnd_obs.std
|
| 231 |
+
obs = torch.clamp(obs, min=self.cfg["obs_norm_clamp_min"], max=self.cfg["obs_norm_clamp_max"])
|
| 232 |
+
|
| 233 |
+
with torch.no_grad():
|
| 234 |
+
self.estimate_cnt_rnd += 1
|
| 235 |
+
predict_feature, target_feature = self.reward_model(obs)
|
| 236 |
+
mse = F.mse_loss(predict_feature, target_feature, reduction='none').mean(dim=1)
|
| 237 |
+
self.tb_logger.add_scalar('rnd_reward/mse', mse.cpu().numpy().mean(), self.estimate_cnt_rnd)
|
| 238 |
+
|
| 239 |
+
# Note: according to the min-max normalization, transform rnd reward to [0,1]
|
| 240 |
+
rnd_reward = mse * self.cfg["reward_mse_ratio"] #(mse - mse.min()) / (mse.max() - mse.min() + 1e-11)
|
| 241 |
+
|
| 242 |
+
self.tb_logger.add_scalar('rnd_reward/rnd_reward_max', rnd_reward.max(), self.estimate_cnt_rnd)
|
| 243 |
+
self.tb_logger.add_scalar('rnd_reward/rnd_reward_mean', rnd_reward.mean(), self.estimate_cnt_rnd)
|
| 244 |
+
self.tb_logger.add_scalar('rnd_reward/rnd_reward_min', rnd_reward.min(), self.estimate_cnt_rnd)
|
| 245 |
+
|
| 246 |
+
rnd_reward = torch.chunk(rnd_reward, rnd_reward.shape[0], dim=0)
|
| 247 |
+
|
| 248 |
+
def training(config, train_data, test_data):
|
| 249 |
+
rnd_reward_model = RndRewardModel(config=config)
|
| 250 |
+
for i in range(train_config["train_iter"]):
|
| 251 |
+
rnd_reward_model.train([torch.Tensor(item["last_observation"]) for item in train_data[i]])
|
| 252 |
+
rnd_reward_model.estimate([torch.Tensor(item["last_observation"]) for item in test_data])
|
| 253 |
+
|
| 254 |
+
def main():
|
| 255 |
+
env = gym.make("MiniGrid-Empty-8x8-v0")
|
| 256 |
+
env_obs = FlatObsWrapper(env)
|
| 257 |
+
|
| 258 |
+
train_data = []
|
| 259 |
+
test_data = []
|
| 260 |
+
|
| 261 |
+
for i in range(train_config["train_iter"]):
|
| 262 |
+
|
| 263 |
+
train_data_per_iter = []
|
| 264 |
+
|
| 265 |
+
while len(train_data_per_iter) < train_config["train_data_count"]:
|
| 266 |
+
last_observation, _ = env_obs.reset()
|
| 267 |
+
terminated = False
|
| 268 |
+
while terminated != True and len(train_data_per_iter) < train_config["train_data_count"]:
|
| 269 |
+
action = env_obs.action_space.sample()
|
| 270 |
+
observation, reward, terminated, truncated, info = env_obs.step(action)
|
| 271 |
+
train_data_per_iter.append(
|
| 272 |
+
{
|
| 273 |
+
"last_observation": last_observation,
|
| 274 |
+
"action": action,
|
| 275 |
+
"reward": reward,
|
| 276 |
+
"observation": observation
|
| 277 |
+
}
|
| 278 |
+
)
|
| 279 |
+
last_observation = observation
|
| 280 |
+
env_obs.close()
|
| 281 |
+
|
| 282 |
+
train_data.append(train_data_per_iter)
|
| 283 |
+
|
| 284 |
+
while len(test_data) < train_config["test_data_count"]:
|
| 285 |
+
last_observation, _ = env_obs.reset()
|
| 286 |
+
terminated = False
|
| 287 |
+
while terminated != True and len(train_data_per_iter) < train_config["test_data_count"]:
|
| 288 |
+
action = env_obs.action_space.sample()
|
| 289 |
+
observation, reward, terminated, truncated, info = env_obs.step(action)
|
| 290 |
+
test_data.append(
|
| 291 |
+
{
|
| 292 |
+
"last_observation": last_observation,
|
| 293 |
+
"action": action,
|
| 294 |
+
"reward": reward,
|
| 295 |
+
"observation": observation
|
| 296 |
+
}
|
| 297 |
+
)
|
| 298 |
+
last_observation = observation
|
| 299 |
+
env_obs.close()
|
| 300 |
+
|
| 301 |
+
p0 = Process(target=training, args=(little_RND_net_config, train_data, test_data))
|
| 302 |
+
p0.start()
|
| 303 |
+
|
| 304 |
+
p1 = Process(target=training, args=(small_RND_net_config, train_data, test_data))
|
| 305 |
+
p1.start()
|
| 306 |
+
|
| 307 |
+
p2 = Process(target=training, args=(standard_RND_net_config, train_data, test_data))
|
| 308 |
+
p2.start()
|
| 309 |
+
|
| 310 |
+
p3 = Process(target=training, args=(large_RND_net_config, train_data, test_data))
|
| 311 |
+
p3.start()
|
| 312 |
+
|
| 313 |
+
p4 = Process(target=training, args=(very_large_RND_net_config, train_data, test_data))
|
| 314 |
+
p4.start()
|
| 315 |
+
|
| 316 |
+
p0.join()
|
| 317 |
+
p1.join()
|
| 318 |
+
p2.join()
|
| 319 |
+
p3.join()
|
| 320 |
+
p4.join()
|
| 321 |
+
|
| 322 |
+
if __name__ == "__main__":
|
| 323 |
+
mp.set_start_method('spawn')
|
| 324 |
+
main()
|
ppof_ch4_data_lunarlander.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ff98aa71827552cd72afc108edddac8e1d77df3499c624dc6f16e256b2a79d61
|
| 3 |
+
size 99443
|
ppof_ch4_data_p1.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c993afb3adb533830ae271f86ba9fb587e70216385f6f20e88dab7fa8f583d8
|
| 3 |
+
size 4035833
|
ppof_ch5_code_p1.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Long Short Term Memory (LSTM) <link https://ieeexplore.ieee.org/abstract/document/6795963 link> is a kind of recurrent neural network that can capture long-short term information.
|
| 3 |
+
This document mainly includes:
|
| 4 |
+
- Pytorch implementation for LSTM.
|
| 5 |
+
- An example to test LSTM.
|
| 6 |
+
For beginners, you can refer to <link https://zhuanlan.zhihu.com/p/32085405 link> to learn the basics about how LSTM works.
|
| 7 |
+
"""
|
| 8 |
+
from typing import Optional, Union, Tuple, List, Dict
|
| 9 |
+
import math
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from ding.torch_utils import build_normalization
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class LSTM(nn.Module):
|
| 16 |
+
"""
|
| 17 |
+
**Overview:**
|
| 18 |
+
Implementation of LSTM cell with layer norm.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
input_size: int,
|
| 24 |
+
hidden_size: int,
|
| 25 |
+
num_layers: int,
|
| 26 |
+
norm_type: Optional[str] = 'LN',
|
| 27 |
+
dropout: float = 0.
|
| 28 |
+
) -> None:
|
| 29 |
+
# Initialize arguments.
|
| 30 |
+
super(LSTM, self).__init__()
|
| 31 |
+
self.input_size = input_size
|
| 32 |
+
self.hidden_size = hidden_size
|
| 33 |
+
self.num_layers = num_layers
|
| 34 |
+
# Initialize normalization functions.
|
| 35 |
+
norm_func = build_normalization(norm_type)
|
| 36 |
+
self.norm = nn.ModuleList([norm_func(hidden_size * 4) for _ in range(2 * num_layers)])
|
| 37 |
+
# Initialize LSTM parameters.
|
| 38 |
+
self.wx = nn.ParameterList()
|
| 39 |
+
self.wh = nn.ParameterList()
|
| 40 |
+
dims = [input_size] + [hidden_size] * num_layers
|
| 41 |
+
for l in range(num_layers):
|
| 42 |
+
self.wx.append(nn.Parameter(torch.zeros(dims[l], dims[l + 1] * 4)))
|
| 43 |
+
self.wh.append(nn.Parameter(torch.zeros(hidden_size, hidden_size * 4)))
|
| 44 |
+
self.bias = nn.Parameter(torch.zeros(num_layers, hidden_size * 4))
|
| 45 |
+
# Initialize the Dropout Layer.
|
| 46 |
+
self.use_dropout = dropout > 0.
|
| 47 |
+
if self.use_dropout:
|
| 48 |
+
self.dropout = nn.Dropout(dropout)
|
| 49 |
+
self._init()
|
| 50 |
+
|
| 51 |
+
# Dealing with different types of input and return preprocessed prev_state.
|
| 52 |
+
def _before_forward(self, inputs: torch.Tensor, prev_state: Union[None, List[Dict]]) -> torch.Tensor:
|
| 53 |
+
seq_len, batch_size = inputs.shape[:2]
|
| 54 |
+
# If prev_state is None, it indicates that this is the beginning of a sequence. In this case, prev_state will be initialized as zero.
|
| 55 |
+
if prev_state is None:
|
| 56 |
+
zeros = torch.zeros(self.num_layers, batch_size, self.hidden_size, dtype=inputs.dtype, device=inputs.device)
|
| 57 |
+
prev_state = (zeros, zeros)
|
| 58 |
+
# If prev_state is not None, then preprocess it into one batch.
|
| 59 |
+
else:
|
| 60 |
+
assert len(prev_state) == batch_size
|
| 61 |
+
state = [[v for v in prev.values()] for prev in prev_state]
|
| 62 |
+
state = list(zip(*state))
|
| 63 |
+
prev_state = [torch.cat(t, dim=1) for t in state]
|
| 64 |
+
|
| 65 |
+
return prev_state
|
| 66 |
+
|
| 67 |
+
def _init(self):
|
| 68 |
+
# Initialize parameters. Each parameter is initialized using a uniform distribution of: $$U(-\sqrt {\frac 1 {HiddenSize}}, -\sqrt {\frac 1 {HiddenSize}})$$
|
| 69 |
+
gain = math.sqrt(1. / self.hidden_size)
|
| 70 |
+
for l in range(self.num_layers):
|
| 71 |
+
torch.nn.init.uniform_(self.wx[l], -gain, gain)
|
| 72 |
+
torch.nn.init.uniform_(self.wh[l], -gain, gain)
|
| 73 |
+
if self.bias is not None:
|
| 74 |
+
torch.nn.init.uniform_(self.bias[l], -gain, gain)
|
| 75 |
+
|
| 76 |
+
def forward(
|
| 77 |
+
self,
|
| 78 |
+
inputs: torch.Tensor,
|
| 79 |
+
prev_state: torch.Tensor,
|
| 80 |
+
) -> Tuple[torch.Tensor, Union[torch.Tensor, list]]:
|
| 81 |
+
# The shape of input is: [sequence length, batch size, input size]
|
| 82 |
+
seq_len, batch_size = inputs.shape[:2]
|
| 83 |
+
prev_state = self._before_forward(inputs, prev_state)
|
| 84 |
+
|
| 85 |
+
H, C = prev_state
|
| 86 |
+
x = inputs
|
| 87 |
+
next_state = []
|
| 88 |
+
for l in range(self.num_layers):
|
| 89 |
+
h, c = H[l], C[l]
|
| 90 |
+
new_x = []
|
| 91 |
+
for s in range(seq_len):
|
| 92 |
+
# Calculate $$z, z^i, z^f, z^o$$ simultaneously.
|
| 93 |
+
gate = self.norm[l * 2](torch.matmul(x[s], self.wx[l])
|
| 94 |
+
) + self.norm[l * 2 + 1](torch.matmul(h, self.wh[l]))
|
| 95 |
+
if self.bias is not None:
|
| 96 |
+
gate += self.bias[l]
|
| 97 |
+
gate = list(torch.chunk(gate, 4, dim=1))
|
| 98 |
+
i, f, o, z = gate
|
| 99 |
+
# $$z^i = \sigma (Wx^ix^t + Wh^ih^{t-1})$$
|
| 100 |
+
i = torch.sigmoid(i)
|
| 101 |
+
# $$z^f = \sigma (Wx^fx^t + Wh^fh^{t-1})$$
|
| 102 |
+
f = torch.sigmoid(f)
|
| 103 |
+
# $$z^o = \sigma (Wx^ox^t + Wh^oh^{t-1})$$
|
| 104 |
+
o = torch.sigmoid(o)
|
| 105 |
+
# $$z = tanh(Wxx^t + Whh^{t-1})$$
|
| 106 |
+
z = torch.tanh(z)
|
| 107 |
+
# $$c^t = z^f \odot c^{t-1}+z^i \odot z$$
|
| 108 |
+
c = f * c + i * z
|
| 109 |
+
# $$h^t = z^o \odot tanh(c^t)$$
|
| 110 |
+
h = o * torch.tanh(c)
|
| 111 |
+
new_x.append(h)
|
| 112 |
+
next_state.append((h, c))
|
| 113 |
+
x = torch.stack(new_x, dim=0)
|
| 114 |
+
# Dropout layer.
|
| 115 |
+
if self.use_dropout and l != self.num_layers - 1:
|
| 116 |
+
x = self.dropout(x)
|
| 117 |
+
next_state = [torch.stack(t, dim=0) for t in zip(*next_state)]
|
| 118 |
+
# Return list type, split the next_state .
|
| 119 |
+
h, c = next_state
|
| 120 |
+
batch_size = h.shape[1]
|
| 121 |
+
# Split h with shape [num_layers, batch_size, hidden_size] to a list with length batch_size and each element is a tensor with shape [num_layers, 1, hidden_size]. The same operation is performed on c.
|
| 122 |
+
next_state = [torch.chunk(h, batch_size, dim=1), torch.chunk(c, batch_size, dim=1)]
|
| 123 |
+
next_state = list(zip(*next_state))
|
| 124 |
+
next_state = [{k: v for k, v in zip(['h', 'c'], item)} for item in next_state]
|
| 125 |
+
return x, next_state
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def pack_data(data: List[torch.Tensor], traj_len: int) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 129 |
+
"""
|
| 130 |
+
Overview:
|
| 131 |
+
You need to pack variable-length data to regular tensor, return tensor and corresponding mask.
|
| 132 |
+
If len(data_i) < traj_len, use `null_padding`,
|
| 133 |
+
else split the whole sequences info different trajectories.
|
| 134 |
+
Returns:
|
| 135 |
+
- tensor (:obj:`torch.Tensor`): dtype (torch.float32), shape (traj_len, B, N)
|
| 136 |
+
- mask (:obj:`torch.Tensor`): dtype (torch.float32), shape (traj_len, B)
|
| 137 |
+
"""
|
| 138 |
+
new_data = []
|
| 139 |
+
mask = []
|
| 140 |
+
for item in data:
|
| 141 |
+
D, N = item.shape
|
| 142 |
+
if D < traj_len:
|
| 143 |
+
null_padding = torch.zeros(traj_len - D, N)
|
| 144 |
+
new_item = torch.cat([item, null_padding])
|
| 145 |
+
new_data.append(new_item)
|
| 146 |
+
item_mask = torch.ones(traj_len)
|
| 147 |
+
item_mask[D:].zero_()
|
| 148 |
+
mask.append(item_mask)
|
| 149 |
+
else:
|
| 150 |
+
for i in range(0, D, traj_len):
|
| 151 |
+
item_mask = torch.ones(traj_len)
|
| 152 |
+
new_item = item[i:i + traj_len]
|
| 153 |
+
if new_item.shape[0] < traj_len:
|
| 154 |
+
new_item = item[-traj_len:]
|
| 155 |
+
new_data.append(new_item)
|
| 156 |
+
mask.append(torch.ones(traj_len))
|
| 157 |
+
new_data = torch.stack(new_data, dim=1)
|
| 158 |
+
mask = torch.stack(mask, dim=1)
|
| 159 |
+
|
| 160 |
+
return new_data, mask
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_lstm():
|
| 164 |
+
seq_len_list = [32, 49, 24, 78, 45]
|
| 165 |
+
traj_len = 32
|
| 166 |
+
N = 10
|
| 167 |
+
hidden_size = 32
|
| 168 |
+
num_layers = 2
|
| 169 |
+
|
| 170 |
+
variable_len_data = [torch.rand(s, N) for s in seq_len_list]
|
| 171 |
+
input_, mask = pack_data(variable_len_data, traj_len)
|
| 172 |
+
assert isinstance(input_, torch.Tensor), type(input_)
|
| 173 |
+
batch_size = input_.shape[1]
|
| 174 |
+
assert batch_size == 9, "packed data must have 9 trajectories"
|
| 175 |
+
lstm = LSTM(N, hidden_size=hidden_size, num_layers=num_layers, norm_type='LN', dropout=0.1)
|
| 176 |
+
|
| 177 |
+
prev_state = None
|
| 178 |
+
for s in range(traj_len):
|
| 179 |
+
input_step = input_[s:s + 1]
|
| 180 |
+
output, prev_state = lstm(input_step, prev_state)
|
| 181 |
+
|
| 182 |
+
assert output.shape == (1, batch_size, hidden_size)
|
| 183 |
+
assert len(prev_state) == batch_size
|
| 184 |
+
assert prev_state[0]['h'].shape == (num_layers, 1, hidden_size)
|
| 185 |
+
loss = (output * mask.unsqueeze(-1)).mean()
|
| 186 |
+
loss.backward()
|
| 187 |
+
for _, m in lstm.named_parameters():
|
| 188 |
+
assert isinstance(m.grad, torch.Tensor)
|
| 189 |
+
print('finished')
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
if __name__ == '__main__':
|
| 193 |
+
test_lstm()
|
ppof_ch6_code_p1.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def get_agent_id_feature(agent_id, agent_num):
|
| 6 |
+
agent_id_feature = torch.zeros(agent_num)
|
| 7 |
+
agent_id_feature[agent_id] = 1
|
| 8 |
+
return agent_id_feature
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_movement_feature():
|
| 12 |
+
# for simplicity, we use random movement feature here
|
| 13 |
+
movement_feature = torch.randint(0, 2, (8, ))
|
| 14 |
+
return movement_feature
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_own_feature():
|
| 18 |
+
# for simplicity, we use random own feature here
|
| 19 |
+
return torch.randn(10)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_ally_visible_feature():
|
| 23 |
+
# this function only return the visible feature of one ally
|
| 24 |
+
# for simplicity, we use random tensor as ally visible feature while zero tensor as ally invisible feature
|
| 25 |
+
if np.random.random() > 0.5:
|
| 26 |
+
ally_visible_feature = torch.randn(4)
|
| 27 |
+
else:
|
| 28 |
+
ally_visible_feature = torch.zeros(4)
|
| 29 |
+
return ally_visible_feature
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_enemy_visible_feature():
|
| 33 |
+
# this function only return the visible feature of one enemy
|
| 34 |
+
# for simplicity, we use random tensor as enemy visible feature while zero tensor as enemy invisible feature
|
| 35 |
+
if np.random.random() > 0.8:
|
| 36 |
+
enemy_visible_feature = torch.randn(4)
|
| 37 |
+
else:
|
| 38 |
+
enemy_visible_feature = torch.zeros(4)
|
| 39 |
+
return enemy_visible_feature
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_ind_global_state(agent_id, ally_agent_num, enemy_agent_num):
|
| 43 |
+
# You need to implement this function
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_ep_global_state(agent_id, ally_agent_num, enemy_agent_num):
|
| 48 |
+
# In many multi-agent environments such as SMAC, the global state is the simplified version of the combination
|
| 49 |
+
# of all the agent's independent state, and the concrete implementation depends on the characteris of environment.
|
| 50 |
+
# For simplicity, we use random feature here.
|
| 51 |
+
ally_center_feature = torch.randn(8)
|
| 52 |
+
enemy_center_feature = torch.randn(8)
|
| 53 |
+
return torch.cat([ally_center_feature, enemy_center_feature])
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_as_global_state(agent_id, ally_agent_num, enemy_agent_num):
|
| 57 |
+
# You need to implement this function
|
| 58 |
+
raise NotImplementedError
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_global_state():
|
| 62 |
+
ally_agent_num = 3
|
| 63 |
+
enemy_agent_num = 5
|
| 64 |
+
# get independent global state, which usually used in decentralized training
|
| 65 |
+
for agent_id in range(ally_agent_num):
|
| 66 |
+
ind_global_state = get_ind_global_state(agent_id, ally_agent_num, enemy_agent_num)
|
| 67 |
+
assert isinstance(ind_global_state, torch.Tensor)
|
| 68 |
+
# get environment provide global state, which is the same for all agents, used in centralized training
|
| 69 |
+
for agent_id in range(ally_agent_num):
|
| 70 |
+
ep_global_state = get_ep_global_state(agent_id, ally_agent_num, enemy_agent_num)
|
| 71 |
+
assert isinstance(ep_global_state, torch.Tensor)
|
| 72 |
+
# get naive agent-specific global state, which is the specific for each agent, used in centralized training
|
| 73 |
+
for agent_id in range(ally_agent_num):
|
| 74 |
+
as_global_state = get_as_global_state(agent_id, ally_agent_num, enemy_agent_num)
|
| 75 |
+
assert isinstance(as_global_state, torch.Tensor)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
test_global_state()
|
ppof_ch7_code_p1.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Tuple, List
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import treetensor.torch as ttorch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class PPOFModel(nn.Module):
|
| 8 |
+
mode = ['compute_actor', 'compute_critic', 'compute_actor_critic']
|
| 9 |
+
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
obs_shape: Tuple[int],
|
| 13 |
+
action_shape: int,
|
| 14 |
+
encoder_hidden_size_list: List = [128, 128, 64],
|
| 15 |
+
actor_head_hidden_size: int = 64,
|
| 16 |
+
actor_head_layer_num: int = 1,
|
| 17 |
+
critic_head_hidden_size: int = 64,
|
| 18 |
+
critic_head_layer_num: int = 1,
|
| 19 |
+
activation: Optional[nn.Module] = nn.ReLU(),
|
| 20 |
+
) -> None:
|
| 21 |
+
super(PPOFModel, self).__init__()
|
| 22 |
+
self.obs_shape, self.action_shape = obs_shape, action_shape
|
| 23 |
+
|
| 24 |
+
# encoder
|
| 25 |
+
layers = []
|
| 26 |
+
input_size = obs_shape[0]
|
| 27 |
+
kernel_size_list = [8, 4, 3]
|
| 28 |
+
stride_list = [4, 2, 1]
|
| 29 |
+
for i in range(len(encoder_hidden_size_list)):
|
| 30 |
+
output_size = encoder_hidden_size_list[i]
|
| 31 |
+
layers.append(nn.Conv2d(input_size, output_size, kernel_size_list[i], stride_list[i]))
|
| 32 |
+
layers.append(activation)
|
| 33 |
+
input_size = output_size
|
| 34 |
+
layers.append(nn.Flatten())
|
| 35 |
+
self.encoder = nn.Sequential(*layers)
|
| 36 |
+
|
| 37 |
+
flatten_size = input_size = self.get_flatten_size()
|
| 38 |
+
# critic
|
| 39 |
+
layers = []
|
| 40 |
+
for i in range(critic_head_layer_num):
|
| 41 |
+
layers.append(nn.Linear(input_size, critic_head_hidden_size))
|
| 42 |
+
layers.append(activation)
|
| 43 |
+
input_size = critic_head_hidden_size
|
| 44 |
+
layers.append(nn.Linear(critic_head_hidden_size, 1))
|
| 45 |
+
self.critic = nn.Sequential(*layers)
|
| 46 |
+
# actor
|
| 47 |
+
layers = []
|
| 48 |
+
input_size = flatten_size
|
| 49 |
+
for i in range(actor_head_layer_num):
|
| 50 |
+
layers.append(nn.Linear(input_size, actor_head_hidden_size))
|
| 51 |
+
layers.append(activation)
|
| 52 |
+
input_size = actor_head_hidden_size
|
| 53 |
+
self.actor = nn.Sequential(*layers)
|
| 54 |
+
self.mu = nn.Linear(actor_head_hidden_size, action_shape)
|
| 55 |
+
self.log_sigma = nn.Parameter(torch.zeros(1, action_shape))
|
| 56 |
+
|
| 57 |
+
# init weights
|
| 58 |
+
self.init_weights()
|
| 59 |
+
|
| 60 |
+
def init_weights(self) -> None:
|
| 61 |
+
# You need to implement this function
|
| 62 |
+
raise NotImplementedError
|
| 63 |
+
|
| 64 |
+
def get_flatten_size(self) -> int:
|
| 65 |
+
test_data = torch.randn(1, *self.obs_shape)
|
| 66 |
+
with torch.no_grad():
|
| 67 |
+
output = self.encoder(test_data)
|
| 68 |
+
return output.shape[1]
|
| 69 |
+
|
| 70 |
+
def forward(self, inputs: ttorch.Tensor, mode: str) -> ttorch.Tensor:
|
| 71 |
+
assert mode in self.mode, "not support forward mode: {}/{}".format(mode, self.mode)
|
| 72 |
+
return getattr(self, mode)(inputs)
|
| 73 |
+
|
| 74 |
+
def compute_actor(self, x: ttorch.Tensor) -> ttorch.Tensor:
|
| 75 |
+
x = self.encoder(x)
|
| 76 |
+
x = self.actor(x)
|
| 77 |
+
mu = self.mu(x)
|
| 78 |
+
log_sigma = self.log_sigma + torch.zeros_like(mu) # addition aims to broadcast shape
|
| 79 |
+
sigma = torch.exp(log_sigma)
|
| 80 |
+
return ttorch.as_tensor({'mu': mu, 'sigma': sigma})
|
| 81 |
+
|
| 82 |
+
def compute_critic(self, x: ttorch.Tensor) -> ttorch.Tensor:
|
| 83 |
+
x = self.encoder(x)
|
| 84 |
+
value = self.critic(x)
|
| 85 |
+
return value
|
| 86 |
+
|
| 87 |
+
def compute_actor_critic(self, x: ttorch.Tensor) -> ttorch.Tensor:
|
| 88 |
+
x = self.encoder(x)
|
| 89 |
+
value = self.critic(x)
|
| 90 |
+
x = self.actor(x)
|
| 91 |
+
mu = self.mu(x)
|
| 92 |
+
log_sigma = self.log_sigma + torch.zeros_like(mu) # addition aims to broadcast shape
|
| 93 |
+
sigma = torch.exp(log_sigma)
|
| 94 |
+
return ttorch.as_tensor({'logit': {'mu': mu, 'sigma': sigma}, 'value': value})
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_ppof_model() -> None:
|
| 98 |
+
model = PPOFModel((4, 84, 84), 5)
|
| 99 |
+
print(model)
|
| 100 |
+
data = torch.randn(3, 4, 84, 84)
|
| 101 |
+
output = model(data, mode='compute_critic')
|
| 102 |
+
assert output.shape == (3, 1)
|
| 103 |
+
output = model(data, mode='compute_actor')
|
| 104 |
+
assert output.mu.shape == (3, 5)
|
| 105 |
+
assert output.sigma.shape == (3, 5)
|
| 106 |
+
output = model(data, mode='compute_actor_critic')
|
| 107 |
+
assert output.value.shape == (3, 1)
|
| 108 |
+
assert output.logit.mu.shape == (3, 5)
|
| 109 |
+
assert output.logit.sigma.shape == (3, 5)
|
| 110 |
+
print('End...')
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
test_ppof_model()
|
ppof_logo.png
ADDED
|