-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathred_irl_model.py
More file actions
executable file
·175 lines (160 loc) · 7.03 KB
/
Copy pathred_irl_model.py
File metadata and controls
executable file
·175 lines (160 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
from typing import Dict, List
import pickle
import random
import torch
import torch.nn as nn
import torch.optim as optim
from ding.utils import REWARD_MODEL_REGISTRY, one_time_warning
from .base_reward_model import BaseRewardModel
class SENet(nn.Module):
"""support estimation network"""
def __init__(self, input_size: int, hidden_size: int, output_dims: int) -> None:
super(SENet, self).__init__()
self.l_1 = nn.Linear(input_size, hidden_size)
self.l_2 = nn.Linear(hidden_size, output_dims)
self.act = nn.Tanh()
def forward(self, x: torch.Tensor) -> torch.Tensor:
out = self.l_1(x)
out = self.act(out)
out = self.l_2(out)
out = self.act(out)
return out
@REWARD_MODEL_REGISTRY.register('red')
class RedRewardModel(BaseRewardModel):
"""
Overview:
The implement of reward model in RED (https://arxiv.org/abs/1905.06750)
Interface:
``estimate``, ``train``, ``load_expert_data``, ``collect_data``, ``clear_date``, \
``__init__``, ``_train``
Properties:
- online_net (:obj: `SENet`): The reward model, in default initialized once as the training begins.
"""
config = dict(
type='red',
# input_size=4,
sample_size=1000,
hidden_size=128,
learning_rate=1e-3,
update_per_collect=100,
# expert_data_path='expert_data.pkl',
batch_size=64,
sigma=0.5,
)
def __init__(self, config: Dict, device: str, tb_logger: 'SummaryWriter') -> None: # noqa
"""
Overview:
Initialize ``self.`` See ``help(type(self))`` for accurate signature.
Arguments:
- cfg (:obj:`Dict`): Training config
- device (:obj:`str`): Device usage, i.e. "cpu" or "cuda"
- tb_logger (:obj:`str`): Logger, defaultly set as 'SummaryWriter' for model summary
"""
super(RedRewardModel, self).__init__()
self.cfg: Dict = config
self.expert_data: List[tuple] = []
self.device = device
assert device in ["cpu", "cuda"] or "cuda" in device
self.tb_logger = tb_logger
self.target_net: SENet = SENet(config.input_size, config.hidden_size, 1)
self.online_net: SENet = SENet(config.input_size, config.hidden_size, 1)
self.target_net.to(device)
self.online_net.to(device)
self.opt: optim.Adam = optim.Adam(self.online_net.parameters(), config.learning_rate)
self.train_once_flag = False
self.load_expert_data()
def load_expert_data(self) -> None:
"""
Overview:
Getting the expert data from ``config['expert_data_path']`` attribute in self.
Effects:
This is a side effect function which updates the expert data attribute (e.g. ``self.expert_data``)
"""
with open(self.cfg.expert_data_path, 'rb') as f:
self.expert_data = pickle.load(f)
sample_size = min(len(self.expert_data), self.cfg.sample_size)
self.expert_data = random.sample(self.expert_data, sample_size)
print('the expert data size is:', len(self.expert_data))
def _train(self, batch_data: torch.Tensor) -> float:
"""
Overview:
Helper function for ``train`` which caclulates loss for train data and expert data.
Arguments:
- batch_data (:obj:`torch.Tensor`): Data used for training
Returns:
- Combined loss calculated of reward model from using ``batch_data`` in both target and reward models.
"""
with torch.no_grad():
target = self.target_net(batch_data)
hat: torch.Tensor = self.online_net(batch_data)
loss: torch.Tensor = ((hat - target) ** 2).mean()
self.opt.zero_grad()
loss.backward()
self.opt.step()
return loss.item()
def train(self) -> None:
"""
Overview:
Training the RED reward model. In default, RED model should be trained once.
Effects:
- This is a side effect function which updates the reward model and increment the train iteration count.
"""
if self.train_once_flag:
one_time_warning('RED model should be trained once, we do not train it anymore')
else:
for i in range(self.cfg.update_per_collect):
sample_batch = random.sample(self.expert_data, self.cfg.batch_size)
states_data = []
actions_data = []
for item in sample_batch:
states_data.append(item['obs'])
actions_data.append(item['action'])
states_tensor: torch.Tensor = torch.stack(states_data).float()
actions_tensor: torch.Tensor = torch.stack(actions_data).float()
states_actions_tensor: torch.Tensor = torch.cat([states_tensor, actions_tensor], dim=1)
states_actions_tensor = states_actions_tensor.to(self.device)
loss = self._train(states_actions_tensor)
self.tb_logger.add_scalar('reward_model/red_loss', loss, i)
self.train_once_flag = True
def estimate(self, data: list) -> None:
"""
Overview:
Estimate reward by rewriting the reward key
Arguments:
- data (:obj:`list`): the list of data used for estimation, \
with at least ``obs`` and ``action`` keys.
Effects:
- This is a side effect function which updates the reward values in place.
"""
states_data = []
actions_data = []
for item in data:
states_data.append(item['obs'])
actions_data.append(item['action'])
states_tensor = torch.stack(states_data).float()
actions_tensor = torch.stack(actions_data).float()
states_actions_tensor = torch.cat([states_tensor, actions_tensor], dim=1)
states_actions_tensor = states_actions_tensor.to(self.device)
with torch.no_grad():
hat_1 = self.online_net(states_actions_tensor)
hat_2 = self.target_net(states_actions_tensor)
c = ((hat_1 - hat_2) ** 2).mean(dim=1)
r = torch.exp(-self.cfg.sigma * c)
for item, rew in zip(data, r):
item['reward'] = rew
def collect_data(self, data) -> None:
"""
Overview:
Collecting training data, not implemented if reward model (i.e. online_net) is only trained ones, \
if online_net is trained continuously, there should be some implementations in collect_data method
"""
# if online_net is trained continuously, there should be some implementations in collect_data method
pass
def clear_data(self):
"""
Overview:
Collecting clearing data, not implemented if reward model (i.e. online_net) is only trained ones, \
if online_net is trained continuously, there should be some implementations in clear_data method
"""
# if online_net is trained continuously, there should be some implementations in clear_data method
pass