Edward Beeching commited on
Commit
7978894
1 Parent(s): 8efa30f

added checkpoints and readme file

Browse files
README.md CHANGED
@@ -1,3 +1,26 @@
1
  ---
2
- license: apache-2.0
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ tags:
3
+ - deep-reinforcement-learning
4
+ - reinforcement-learning
5
+
6
  ---
7
+
8
+ Find here pretrained model weights for the [Decision Transformer] (https://github.com/kzl/decision-transformer).
9
+ Weights are available for 4 Atari games: Breakout, Pong, Qbert and Seaquest. Found in the checkpoints directory.
10
+ We share models trained for one seed (123), whereas the paper contained weights for 3 random seeds.
11
+
12
+
13
+ ### Usage
14
+
15
+ ```
16
+ conda env create -f conda_env.yml
17
+ ```
18
+
19
+ Then, you can use the model like this:
20
+
21
+ ```python
22
+
23
+
24
+
25
+
26
+ ```
checkpoints/Breakout_123.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d56f3a83f8d5092b44f8fa812a51a210084854f542d89eb268be943729afbf75
3
+ size 8329555
checkpoints/Qbert_123.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84683bb7fb5dae6d73c6b4cf97338af9a77dfb8c8c0d30b22f79b3358748eea4
3
+ size 8971091
checkpoints/Seaquest_123.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2691ccaef484e97d22b2b47e87721d57c29747084fc11c7e15028a19ea0c7048
3
+ size 8384339
conda_env.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: decision-transformer-atari
2
+ channels:
3
+ - pytorch
4
+ dependencies:
5
+ - python=3.7.9
6
+ - pytorch
7
+ - cudatoolkit=11.3
8
+ - numpy
9
+ - psutil
10
+ - opencv
11
+ - pip
12
+ - pip:
13
+ - atari-py
14
+ - pyprind
15
+ - tensorflow-gpu>=1.13
16
+ - absl-py
17
+ - atari-py
18
+ - gin-config
19
+ - gym
20
+ - tqdm
21
+ - blosc
22
+ - git+https://github.com/google/dopamine.git
decision_transformer_atari.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The MIT License (MIT) Copyright (c) 2020 Andrej Karpathy
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9
+ """
10
+
11
+ """
12
+ GPT model:
13
+ - the initial stem consists of a combination of token encoding and a positional encoding
14
+ - the meat of it is a uniform sequence of Transformer blocks
15
+ - each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block
16
+ - all blocks feed into a central residual pathway similar to resnets
17
+ - the final decoder is a linear projection into a vanilla Softmax classifier
18
+ """
19
+
20
+ import math
21
+ import logging
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+ from torch.nn import functional as F
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ import numpy as np
30
+
31
+
32
+ class GELU(nn.Module):
33
+ def forward(self, input):
34
+ return F.gelu(input)
35
+
36
+
37
+ class GPTConfig:
38
+ """ base GPT config, params common to all GPT versions """
39
+
40
+ embd_pdrop = 0.1
41
+ resid_pdrop = 0.1
42
+ attn_pdrop = 0.1
43
+
44
+ def __init__(self, vocab_size, block_size, **kwargs):
45
+ self.vocab_size = vocab_size
46
+ self.block_size = block_size
47
+ for k, v in kwargs.items():
48
+ setattr(self, k, v)
49
+
50
+
51
+ class GPT1Config(GPTConfig):
52
+ """ GPT-1 like network roughly 125M params """
53
+
54
+ n_layer = 12
55
+ n_head = 12
56
+ n_embd = 768
57
+
58
+
59
+ class CausalSelfAttention(nn.Module):
60
+ """
61
+ A vanilla multi-head masked self-attention layer with a projection at the end.
62
+ It is possible to use torch.nn.MultiheadAttention here but I am including an
63
+ explicit implementation here to show that there is nothing too scary here.
64
+ """
65
+
66
+ def __init__(self, config):
67
+ super().__init__()
68
+ assert config.n_embd % config.n_head == 0
69
+ # key, query, value projections for all heads
70
+ self.key = nn.Linear(config.n_embd, config.n_embd)
71
+ self.query = nn.Linear(config.n_embd, config.n_embd)
72
+ self.value = nn.Linear(config.n_embd, config.n_embd)
73
+ # regularization
74
+ self.attn_drop = nn.Dropout(config.attn_pdrop)
75
+ self.resid_drop = nn.Dropout(config.resid_pdrop)
76
+ # output projection
77
+ self.proj = nn.Linear(config.n_embd, config.n_embd)
78
+ # causal mask to ensure that attention is only applied to the left in the input sequence
79
+ # self.register_buffer("mask", torch.tril(torch.ones(config.block_size, config.block_size))
80
+ # .view(1, 1, config.block_size, config.block_size))
81
+ self.register_buffer(
82
+ "mask",
83
+ torch.tril(torch.ones(config.block_size + 1, config.block_size + 1)).view(
84
+ 1, 1, config.block_size + 1, config.block_size + 1
85
+ ),
86
+ )
87
+ self.n_head = config.n_head
88
+
89
+ def forward(self, x, layer_past=None):
90
+ B, T, C = x.size()
91
+
92
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
93
+ k = (
94
+ self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
95
+ ) # (B, nh, T, hs)
96
+ q = (
97
+ self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
98
+ ) # (B, nh, T, hs)
99
+ v = (
100
+ self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
101
+ ) # (B, nh, T, hs)
102
+
103
+ # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
104
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
105
+ att = att.masked_fill(self.mask[:, :, :T, :T] == 0, float("-inf"))
106
+ att = F.softmax(att, dim=-1)
107
+ att = self.attn_drop(att)
108
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
109
+ y = (
110
+ y.transpose(1, 2).contiguous().view(B, T, C)
111
+ ) # re-assemble all head outputs side by side
112
+
113
+ # output projection
114
+ y = self.resid_drop(self.proj(y))
115
+ return y
116
+
117
+
118
+ class Block(nn.Module):
119
+ """ an unassuming Transformer block """
120
+
121
+ def __init__(self, config):
122
+ super().__init__()
123
+ self.ln1 = nn.LayerNorm(config.n_embd)
124
+ self.ln2 = nn.LayerNorm(config.n_embd)
125
+ self.attn = CausalSelfAttention(config)
126
+ self.mlp = nn.Sequential(
127
+ nn.Linear(config.n_embd, 4 * config.n_embd),
128
+ GELU(),
129
+ nn.Linear(4 * config.n_embd, config.n_embd),
130
+ nn.Dropout(config.resid_pdrop),
131
+ )
132
+
133
+ def forward(self, x):
134
+ x = x + self.attn(self.ln1(x))
135
+ x = x + self.mlp(self.ln2(x))
136
+ return x
137
+
138
+
139
+ class GPT(nn.Module):
140
+ """ the full GPT language model, with a context size of block_size """
141
+
142
+ def __init__(self, config):
143
+ super().__init__()
144
+
145
+ self.config = config
146
+
147
+ self.model_type = config.model_type
148
+
149
+ # input embedding stem
150
+ self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
151
+ # self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size, config.n_embd))
152
+ self.pos_emb = nn.Parameter(
153
+ torch.zeros(1, config.block_size + 1, config.n_embd)
154
+ )
155
+ self.global_pos_emb = nn.Parameter(
156
+ torch.zeros(1, config.max_timestep + 1, config.n_embd)
157
+ )
158
+ self.drop = nn.Dropout(config.embd_pdrop)
159
+
160
+ # transformer
161
+ self.blocks = nn.Sequential(*[Block(config) for _ in range(config.n_layer)])
162
+ # decoder head
163
+ self.ln_f = nn.LayerNorm(config.n_embd)
164
+ self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
165
+
166
+ self.block_size = config.block_size
167
+ self.apply(self._init_weights)
168
+
169
+ logger.info(
170
+ "number of parameters: %e", sum(p.numel() for p in self.parameters())
171
+ )
172
+
173
+ self.state_encoder = nn.Sequential(
174
+ nn.Conv2d(4, 32, 8, stride=4, padding=0),
175
+ nn.ReLU(),
176
+ nn.Conv2d(32, 64, 4, stride=2, padding=0),
177
+ nn.ReLU(),
178
+ nn.Conv2d(64, 64, 3, stride=1, padding=0),
179
+ nn.ReLU(),
180
+ nn.Flatten(),
181
+ nn.Linear(3136, config.n_embd),
182
+ nn.Tanh(),
183
+ )
184
+
185
+ self.ret_emb = nn.Sequential(nn.Linear(1, config.n_embd), nn.Tanh())
186
+
187
+ self.action_embeddings = nn.Sequential(
188
+ nn.Embedding(config.vocab_size, config.n_embd), nn.Tanh()
189
+ )
190
+ nn.init.normal_(self.action_embeddings[0].weight, mean=0.0, std=0.02)
191
+
192
+ def get_block_size(self):
193
+ return self.block_size
194
+
195
+ def _init_weights(self, module):
196
+ if isinstance(module, (nn.Linear, nn.Embedding)):
197
+ module.weight.data.normal_(mean=0.0, std=0.02)
198
+ if isinstance(module, nn.Linear) and module.bias is not None:
199
+ module.bias.data.zero_()
200
+ elif isinstance(module, nn.LayerNorm):
201
+ module.bias.data.zero_()
202
+ module.weight.data.fill_(1.0)
203
+
204
+ def configure_optimizers(self, train_config):
205
+ """
206
+ This long function is unfortunately doing something very simple and is being very defensive:
207
+ We are separating out all parameters of the model into two buckets: those that will experience
208
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
209
+ We are then returning the PyTorch optimizer object.
210
+ """
211
+
212
+ # separate out all parameters to those that will and won't experience regularizing weight decay
213
+ decay = set()
214
+ no_decay = set()
215
+ # whitelist_weight_modules = (torch.nn.Linear, )
216
+ whitelist_weight_modules = (torch.nn.Linear, torch.nn.Conv2d)
217
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
218
+ for mn, m in self.named_modules():
219
+ for pn, p in m.named_parameters():
220
+ fpn = "%s.%s" % (mn, pn) if mn else pn # full param name
221
+
222
+ if pn.endswith("bias"):
223
+ # all biases will not be decayed
224
+ no_decay.add(fpn)
225
+ elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules):
226
+ # weights of whitelist modules will be weight decayed
227
+ decay.add(fpn)
228
+ elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules):
229
+ # weights of blacklist modules will NOT be weight decayed
230
+ no_decay.add(fpn)
231
+
232
+ # special case the position embedding parameter in the root GPT module as not decayed
233
+ no_decay.add("pos_emb")
234
+ no_decay.add("global_pos_emb")
235
+
236
+ # validate that we considered every parameter
237
+ param_dict = {pn: p for pn, p in self.named_parameters()}
238
+ inter_params = decay & no_decay
239
+ union_params = decay | no_decay
240
+ assert (
241
+ len(inter_params) == 0
242
+ ), "parameters %s made it into both decay/no_decay sets!" % (str(inter_params),)
243
+ assert len(param_dict.keys() - union_params) == 0, (
244
+ "parameters %s were not separated into either decay/no_decay set!"
245
+ % (str(param_dict.keys() - union_params),)
246
+ )
247
+
248
+ # create the pytorch optimizer object
249
+ optim_groups = [
250
+ {
251
+ "params": [param_dict[pn] for pn in sorted(list(decay))],
252
+ "weight_decay": train_config.weight_decay,
253
+ },
254
+ {
255
+ "params": [param_dict[pn] for pn in sorted(list(no_decay))],
256
+ "weight_decay": 0.0,
257
+ },
258
+ ]
259
+ optimizer = torch.optim.AdamW(
260
+ optim_groups, lr=train_config.learning_rate, betas=train_config.betas
261
+ )
262
+ return optimizer
263
+
264
+ # state, action, and return
265
+ def forward(self, states, actions, targets=None, rtgs=None, timesteps=None):
266
+ # states: (batch, block_size, 4*84*84)
267
+ # actions: (batch, block_size, 1)
268
+ # targets: (batch, block_size, 1)
269
+ # rtgs: (batch, block_size, 1)
270
+ # timesteps: (batch, 1, 1)
271
+
272
+ state_embeddings = self.state_encoder(
273
+ states.reshape(-1, 4, 84, 84).type(torch.float32).contiguous()
274
+ ) # (batch * block_size, n_embd)
275
+ state_embeddings = state_embeddings.reshape(
276
+ states.shape[0], states.shape[1], self.config.n_embd
277
+ ) # (batch, block_size, n_embd)
278
+
279
+ if actions is not None and self.model_type == "reward_conditioned":
280
+ rtg_embeddings = self.ret_emb(rtgs.type(torch.float32))
281
+ action_embeddings = self.action_embeddings(
282
+ actions.type(torch.long).squeeze(-1)
283
+ ) # (batch, block_size, n_embd)
284
+
285
+ token_embeddings = torch.zeros(
286
+ (
287
+ states.shape[0],
288
+ states.shape[1] * 3 - int(targets is None),
289
+ self.config.n_embd,
290
+ ),
291
+ dtype=torch.float32,
292
+ device=state_embeddings.device,
293
+ )
294
+ token_embeddings[:, ::3, :] = rtg_embeddings
295
+ token_embeddings[:, 1::3, :] = state_embeddings
296
+ token_embeddings[:, 2::3, :] = action_embeddings[
297
+ :, -states.shape[1] + int(targets is None) :, :
298
+ ]
299
+ elif (
300
+ actions is None and self.model_type == "reward_conditioned"
301
+ ): # only happens at very first timestep of evaluation
302
+ rtg_embeddings = self.ret_emb(rtgs.type(torch.float32))
303
+
304
+ token_embeddings = torch.zeros(
305
+ (states.shape[0], states.shape[1] * 2, self.config.n_embd),
306
+ dtype=torch.float32,
307
+ device=state_embeddings.device,
308
+ )
309
+ token_embeddings[:, ::2, :] = rtg_embeddings # really just [:,0,:]
310
+ token_embeddings[:, 1::2, :] = state_embeddings # really just [:,1,:]
311
+ elif actions is not None and self.model_type == "naive":
312
+ action_embeddings = self.action_embeddings(
313
+ actions.type(torch.long).squeeze(-1)
314
+ ) # (batch, block_size, n_embd)
315
+
316
+ token_embeddings = torch.zeros(
317
+ (
318
+ states.shape[0],
319
+ states.shape[1] * 2 - int(targets is None),
320
+ self.config.n_embd,
321
+ ),
322
+ dtype=torch.float32,
323
+ device=state_embeddings.device,
324
+ )
325
+ token_embeddings[:, ::2, :] = state_embeddings
326
+ token_embeddings[:, 1::2, :] = action_embeddings[
327
+ :, -states.shape[1] + int(targets is None) :, :
328
+ ]
329
+ elif (
330
+ actions is None and self.model_type == "naive"
331
+ ): # only happens at very first timestep of evaluation
332
+ token_embeddings = state_embeddings
333
+ else:
334
+ raise NotImplementedError()
335
+
336
+ batch_size = states.shape[0]
337
+ all_global_pos_emb = torch.repeat_interleave(
338
+ self.global_pos_emb, batch_size, dim=0
339
+ ) # batch_size, traj_length, n_embd
340
+
341
+ position_embeddings = (
342
+ torch.gather(
343
+ all_global_pos_emb,
344
+ 1,
345
+ torch.repeat_interleave(timesteps, self.config.n_embd, dim=-1),
346
+ )
347
+ + self.pos_emb[:, : token_embeddings.shape[1], :]
348
+ )
349
+
350
+ x = self.drop(token_embeddings + position_embeddings)
351
+ x = self.blocks(x)
352
+ x = self.ln_f(x)
353
+ logits = self.head(x)
354
+
355
+ if actions is not None and self.model_type == "reward_conditioned":
356
+ logits = logits[:, 1::3, :] # only keep predictions from state_embeddings
357
+ elif actions is None and self.model_type == "reward_conditioned":
358
+ logits = logits[:, 1:, :]
359
+ elif actions is not None and self.model_type == "naive":
360
+ logits = logits[:, ::2, :] # only keep predictions from state_embeddings
361
+ elif actions is None and self.model_type == "naive":
362
+ logits = logits # for completeness
363
+ else:
364
+ raise NotImplementedError()
365
+
366
+ # if we are given some desired targets also calculate the loss
367
+ loss = None
368
+ if targets is not None:
369
+ loss = F.cross_entropy(
370
+ logits.reshape(-1, logits.size(-1)), targets.reshape(-1)
371
+ )
372
+
373
+ return logits, loss
374
+
375
+
376
+ if __name__ == "__main__":
377
+ vocab_size = 4
378
+ block_size = 90
379
+ model_type = "reward_conditioned"
380
+ timesteps = 2654
381
+
382
+ mconf = GPTConfig(
383
+ vocab_size,
384
+ block_size,
385
+ n_layer=6,
386
+ n_head=8,
387
+ n_embd=128,
388
+ model_type=model_type,
389
+ max_timestep=timesteps,
390
+ )
391
+ model = GPT(mconf)
392
+
393
+ checkpoint_path = "checkpoints/Breakout_123.pth" # or Pong, Qbert, Seaquest
394
+ checkpoint = torch.load(checkpoint_path)
395
+ model.load_state_dict(checkpoint)
396
+