-
Notifications
You must be signed in to change notification settings - Fork 15
/
gridworld_models.py
276 lines (234 loc) · 6.87 KB
/
gridworld_models.py
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""
Copyright (c) Meta Platforms, Inc. and affiliates.
All rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
"""
from typing import Tuple
import numpy as np
import jax
import jax.numpy as jnp
import flax.linen as nn
import chex
from tensorflow_probability.substrates import jax as tfp
from minimax.models import common
from minimax.models import s5
from minimax.models.registration import register
class GridWorldBasicModel(nn.Module):
"""Split Actor-Critic Architecture for PPO."""
output_dim: int = 7
n_hidden_layers: int = 1
hidden_dim: int = 32
n_conv_filters: int = 16
conv_kernel_size: int = 3
n_scalar_embeddings: int = 4
max_scalar: int = 4
scalar_embed_dim: int = 5
recurrent_arch: str = None
recurrent_hidden_dim: int = 256
base_activation: str = 'relu'
head_activation: str = 'tanh'
s5_n_blocks: int = 2
s5_n_layers: int = 4
s5_layernorm_pos: str = None
s5_activation: str = "half_glu1"
value_ensemble_size: int = 1
def setup(self):
self.conv = nn.Sequential([
nn.Conv(
features=self.n_conv_filters,
kernel_size=[self.conv_kernel_size,]*2,
strides=1,
kernel_init=common.init_orth(
scale=common.calc_gain(self.base_activation)
),
padding='VALID',
name='cnn'),
common.get_activation(self.base_activation)
])
if self.n_scalar_embeddings > 0:
self.fc_scalar = nn.Embed(
num_embeddings=self.n_scalar_embeddings,
features=self.scalar_embed_dim,
embedding_init=common.init_orth(
common.calc_gain('linear')
),
name=f'fc_scalar'
)
elif self.scalar_embed_dim > 0:
self.fc_scalar = nn.Dense(
self.scalar_embed_dim,
kernel_init=common.init_orth(
common.calc_gain('linear')
),
name=f'fc_scalar'
)
else:
self.fc_scalar = None
if self.recurrent_arch is not None:
if self.recurrent_arch == 's5':
self.embed_pre_s5 = nn.Sequential([
nn.Dense(
self.recurrent_hidden_dim,
kernel_init=common.init_orth(
common.calc_gain('linear')
),
name=f'fc_pre_s5'
)
])
self.rnn = s5.make_s5_encoder_stack(
input_dim=self.recurrent_hidden_dim,
ssm_state_dim=self.recurrent_hidden_dim,
n_blocks=self.s5_n_blocks,
n_layers=self.s5_n_layers,
activation=self.s5_activation,
layernorm_pos=self.s5_layernorm_pos
)
else:
self.rnn = common.ScannedRNN(
recurrent_arch=self.recurrent_arch,
recurrent_hidden_dim=self.recurrent_hidden_dim,
kernel_init=common.init_orth(),
recurrent_kernel_init=common.init_orth()
)
else:
self.rnn = None
self.pi_head = nn.Sequential([
common.make_fc_layers(
'fc_pi',
n_layers=self.n_hidden_layers,
hidden_dim=self.hidden_dim,
activation=common.get_activation(self.head_activation),
kernel_init=common.init_orth(
common.calc_gain(self.head_activation)
)
),
nn.Dense(
self.output_dim,
kernel_init=nn.initializers.constant(0.01),
name=f'fc_pi_final'
)
])
value_head_kwargs = dict(
n_hidden_layers=self.n_hidden_layers,
hidden_dim=self.hidden_dim,
activation=nn.tanh,
kernel_init=common.init_orth(
common.calc_gain('tanh')
),
last_layer_kernel_init=common.init_orth(
common.calc_gain('linear')
)
)
if self.value_ensemble_size > 1:
self.v_head = common.EnsembleValueHead(
n=self.value_ensemble_size, **value_head_kwargs)
else:
self.v_head = common.ValueHead(**value_head_kwargs)
def __call__(self, x, carry=None):
raise NotImplementedError
def initialize_carry(
self,
rng: chex.PRNGKey,
batch_dims: Tuple[int] = ()) -> Tuple[chex.ArrayTree, chex.ArrayTree]:
"""Initialize hidden state of LSTM."""
if self.recurrent_arch is not None:
if self.recurrent_arch == 's5':
return s5.S5EncoderStack.initialize_carry( # Since conj_sym=True
rng, batch_dims, self.recurrent_hidden_dim//2, self.s5_n_layers
)
else:
return common.ScannedRNN.initialize_carry(
rng, batch_dims, self.recurrent_hidden_dim, self.recurrent_arch)
else:
raise ValueError('Model is not recurrent.')
@property
def is_recurrent(self):
return self.recurrent_arch is not None
class GridWorldACStudentModel(GridWorldBasicModel):
def __call__(self, x, carry=None, reset=None):
"""
Inputs:
x: B x h x w observations
hxs: B x hx_dim hidden states
masks: B length vector of done masks
"""
old_x = x
img = x['image']
agent_dir = x['agent_dir']
aux = x.get('aux')
if self.rnn is not None:
batch_dims = img.shape[:2]
x = self.conv(img).reshape(*batch_dims, -1)
else:
batch_dims = img.shape[:1]
x = self.conv(img).reshape(*batch_dims, -1)
if self.fc_scalar is not None:
if self.n_scalar_embeddings == 0:
agent_dir /= self.max_scalar
scalar_emb = self.fc_scalar(agent_dir).reshape(*batch_dims, -1)
x = jnp.concatenate([x, scalar_emb], axis=-1)
if aux is not None:
x = jnp.concatenate([x, aux], axis=-1)
if self.rnn is not None:
if self.recurrent_arch == 's5':
x = self.embed_pre_s5(x)
carry, x = self.rnn(carry, x, reset)
else:
carry, x = self.rnn(carry, (x, reset))
logits = self.pi_head(x)
v = self.v_head(x)
return v, logits, carry
class GridWorldACTeacherModel(GridWorldBasicModel):
"""
Original teacher model from Dennis et al, 2020. It is identical ins
high-level spec to the student model, but with the additional fwd logic
of concatenating a noise vector.
"""
def __call__(self, x, carry=None, reset=None):
"""
Inputs:
x: B x h x w observations
hxs: B x hx_dim hidden states
masks: B length vector of done masks
"""
img = x['image']
time = x['time']
noise = x.get('noise')
aux = x.get('aux')
if self.rnn is not None:
batch_dims = img.shape[:2]
x = self.conv(img).reshape(*batch_dims, -1)
else:
batch_dims = img.shape[:1]
x = self.conv(img).reshape(*batch_dims, -1)
if self.fc_scalar is not None:
if self.n_scalar_embeddings == 0:
time /= self.max_scalar
scalar_emb = self.fc_scalar(time).reshape(*batch_dims, -1)
x = jnp.concatenate([x, scalar_emb], axis=-1)
if noise is not None:
noise = noise.reshape(*batch_dims, -1)
x = jnp.concatenate([x, noise], axis=-1)
if aux is not None:
x = jnp.concatenate([x, aux], axis=-1)
if self.rnn is not None:
if self.recurrent_arch == 's5':
x = self.embed_pre_s5(x)
carry, x = self.rnn(carry, x, reset)
else:
carry, x = self.rnn(carry, (x, reset))
logits = self.pi_head(x)
v = self.v_head(x)
return v, logits, carry
# Register models
if hasattr(__loader__, 'name'):
module_path = __loader__.name
elif hasattr(__loader__, 'fullname'):
module_path = __loader__.fullname
register(
env_group_id='Maze', model_id='default_student_cnn',
entry_point=module_path + ':GridWorldACStudentModel')
register(
env_group_id='Maze', model_id='default_teacher_cnn',
entry_point=module_path + ':GridWorldACTeacherModel')