jgalego commited on
Commit
12fb5b1
·
verified ·
1 Parent(s): 2fa05eb

Add model and results

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. atari.py +580 -0
  3. config.json +21 -0
  4. model.safetensors +3 -0
  5. results/eval.json +27 -0
  6. results/rollout.gif +3 -0
  7. results/train.json +27 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ results/rollout.gif filter=lfs diff=lfs merge=lfs -text
atari.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = [
4
+ # "ale-py",
5
+ # "gradio",
6
+ # "gymnasium",
7
+ # "huggingface_hub",
8
+ # "jinja2",
9
+ # "numpy",
10
+ # "pillow",
11
+ # "safetensors",
12
+ # "torch",
13
+ # ]
14
+ # ///
15
+ """Train a diffusion world model of an Atari game (Space Invaders, Ms. Pac-Man) and play it.
16
+
17
+ After DIAMOND (https://arxiv.org/abs/2405.12399): a small U-Net denoises the next 64x64 frame
18
+ from the last four frames and actions, with EDM preconditioning and a few Euler steps at
19
+ inference. Fed its own frames, it generates a video that the actions steer.
20
+ """
21
+
22
+ # Torch modules only expose forward and keep one attribute per layer.
23
+ # pylint: disable=too-few-public-methods,too-many-instance-attributes
24
+
25
+ import argparse
26
+ import json
27
+ import math
28
+ import os
29
+ import shutil
30
+ import time
31
+ from dataclasses import asdict, dataclass
32
+ from functools import partial
33
+ from pathlib import Path
34
+
35
+ import ale_py
36
+ import gradio as gr
37
+ import gymnasium as gym
38
+ import numpy as np
39
+ import torch
40
+ import torch.nn.functional as F
41
+ from huggingface_hub import EvalResult, HfApi, ModelCard, ModelCardData, snapshot_download
42
+ from huggingface_hub.errors import RepositoryNotFoundError
43
+ from PIL import Image
44
+ from safetensors.torch import load_file, save_file
45
+ from torch import nn
46
+
47
+ # ALE name: (display name, slug for the model repo)
48
+ GAMES = {
49
+ "SpaceInvaders": ("Space Invaders", "space-invaders"),
50
+ "MsPacman": ("Ms. Pac-Man", "ms-pacman"),
51
+ }
52
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
53
+ HERE = Path(__file__).parent
54
+ SIZE = 64
55
+ EVAL_SEED = 1_000_000 # evaluation episodes never share a seed with training episodes
56
+ SIGMA_DATA = 0.5
57
+ HORIZONS = (1, 5, 15) # frames ahead; at frameskip 4, 15 frames is one second of play
58
+ GIF_FRAMES = 60
59
+
60
+ gym.register_envs(ale_py)
61
+
62
+
63
+ @dataclass
64
+ class Config:
65
+ """Architecture and sampler."""
66
+
67
+ game: str = "SpaceInvaders"
68
+ actions: tuple = () # action names, in ALE order
69
+ context: int = 4
70
+ channels: tuple = (64, 128, 256)
71
+ steps: int = 3 # Euler steps per frame
72
+ sigma_min: float = 2e-3
73
+ sigma_max: float = 5.0
74
+ rho: float = 7.0
75
+
76
+
77
+ # Data
78
+
79
+
80
+ def repo_for(game):
81
+ """The model repo of a game."""
82
+ return f"jgalego/{GAMES[game][1]}-world-model"
83
+
84
+
85
+ def make_env(game):
86
+ """The ALE environment of a game: minimal action set, frameskip 4, no sticky actions."""
87
+ return gym.make(f"ALE/{game}-v5", frameskip=4, repeat_action_probability=0.0)
88
+
89
+
90
+ def action_names(game):
91
+ """The game's action names, in ALE order."""
92
+ env = make_env(game)
93
+ names = tuple(env.unwrapped.get_action_meanings())
94
+ env.close()
95
+ return names
96
+
97
+
98
+ def collect(frames, seed, game):
99
+ """Frames (n, 3, 64, 64) uint8, actions (n,) and episode ids (n,) from a random policy.
100
+
101
+ The policy holds each uniformly random action for 1 to 6 steps. actions[i] turns frame i
102
+ into frame i + 1; the last frame of an episode gets a NOOP that no window uses.
103
+ """
104
+ env = make_env(game)
105
+ rng = np.random.default_rng(seed)
106
+ obs, episode, action, hold = env.reset(seed=seed)[0], 0, 0, 0
107
+ out = {"frames": [], "actions": [], "episodes": []}
108
+ while len(out["frames"]) < frames:
109
+ if hold == 0:
110
+ action, hold = int(rng.integers(env.action_space.n)), int(rng.integers(1, 7))
111
+ hold -= 1
112
+ for key, value in zip(out, (resize(obs), action, episode)):
113
+ out[key].append(value)
114
+ obs, _, terminated, truncated, _ = env.step(action)
115
+ if terminated or truncated:
116
+ for key, value in zip(out, (resize(obs), 0, episode)):
117
+ out[key].append(value)
118
+ obs, episode = env.reset()[0], episode + 1
119
+ env.close()
120
+ return (
121
+ torch.from_numpy(np.stack(out["frames"])),
122
+ torch.tensor(out["actions"]),
123
+ torch.tensor(out["episodes"]),
124
+ )
125
+
126
+
127
+ def resize(obs):
128
+ """A 210x160 RGB frame as a 3x64x64 uint8 array."""
129
+ return np.asarray(Image.fromarray(obs).resize((SIZE, SIZE), Image.BOX)).transpose(2, 0, 1)
130
+
131
+
132
+ def starts(episodes, length):
133
+ """Indices i where frames i to i + length - 1 belong to one episode."""
134
+ return torch.nonzero(episodes[: -length + 1] == episodes[length - 1 :])[:, 0]
135
+
136
+
137
+ def to_float(frames):
138
+ """uint8 frames to [-1, 1]."""
139
+ return frames.float() / 127.5 - 1
140
+
141
+
142
+ def window(frames, actions, index, context):
143
+ """Context frames (b, c, 3, 64, 64), their actions (b, c) and the next frame (b, 3, 64, 64)."""
144
+ rows = index[:, None] + torch.arange(context + 1, device=index.device)
145
+ clip = to_float(frames[rows])
146
+ return clip[:, :-1], actions[rows[:, :-1]], clip[:, -1]
147
+
148
+
149
+ # Model
150
+
151
+
152
+ class Block(nn.Module):
153
+ """Residual conv block with scale and shift from the conditioning vector."""
154
+
155
+ def __init__(self, inputs, outputs, cond):
156
+ super().__init__()
157
+ self.norm1, self.norm2 = nn.GroupNorm(32, inputs), nn.GroupNorm(32, outputs)
158
+ self.conv1 = nn.Conv2d(inputs, outputs, 3, padding=1)
159
+ self.conv2 = nn.Conv2d(outputs, outputs, 3, padding=1)
160
+ self.film = nn.Linear(cond, 2 * outputs)
161
+ self.skip = nn.Conv2d(inputs, outputs, 1) if inputs != outputs else nn.Identity()
162
+
163
+ def forward(self, x, cond):
164
+ """x (b, inputs, h, w) to (b, outputs, h, w)."""
165
+ hidden = self.conv1(F.silu(self.norm1(x)))
166
+ scale, shift = self.film(cond)[:, :, None, None].chunk(2, dim=1)
167
+ hidden = self.conv2(F.silu(self.norm2(hidden) * (1 + scale) + shift))
168
+ return self.skip(x) + hidden
169
+
170
+
171
+ class Denoiser(nn.Module):
172
+ """U-Net over the noisy next frame stacked with the context frames."""
173
+
174
+ def __init__(self, config, cond=256):
175
+ super().__init__()
176
+ self.config = config
177
+ width = list(config.channels)
178
+ self.action = nn.Embedding(len(config.actions), 64)
179
+ self.embed = nn.Sequential(
180
+ nn.Linear(64 * (config.context + 1), cond), nn.SiLU(), nn.Linear(cond, cond)
181
+ )
182
+ self.stem = nn.Conv2d(3 * (config.context + 1), width[0], 3, padding=1)
183
+ self.down = nn.ModuleList(Block(a, b, cond) for a, b in zip(width[:1] + width, width))
184
+ self.middle = Block(width[-1], width[-1], cond)
185
+ self.up = nn.ModuleList(
186
+ Block(2 * width[i], width[max(i - 1, 0)], cond) for i in range(len(width))
187
+ )
188
+ self.out = nn.Sequential(
189
+ nn.GroupNorm(32, width[0]), nn.SiLU(), nn.Conv2d(width[0], 3, 3, padding=1)
190
+ )
191
+
192
+ def forward(self, noisy, noise, context, actions):
193
+ """Raw network output for the preconditioned input; `noise` is log(sigma) / 4."""
194
+ freqs = torch.exp(torch.linspace(0, math.log(1000), 32, device=noise.device))
195
+ angles = noise[:, None] * freqs
196
+ cond = torch.cat([angles.sin(), angles.cos(), self.action(actions).flatten(1)], dim=1)
197
+ cond = self.embed(cond)
198
+ x = self.stem(torch.cat([noisy, context.flatten(1, 2)], dim=1))
199
+ skips = []
200
+ for level, block in enumerate(self.down):
201
+ x = block(x, cond)
202
+ skips.append(x)
203
+ if level < len(self.down) - 1:
204
+ x = F.avg_pool2d(x, 2)
205
+ x = self.middle(x, cond)
206
+ for block, skip in zip(reversed(self.up), reversed(skips)):
207
+ if x.shape[-1] != skip.shape[-1]:
208
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
209
+ x = block(torch.cat([x, skip], dim=1), cond)
210
+ return self.out(x)
211
+
212
+ def denoise(self, noisy, sigma, context, actions):
213
+ """EDM denoiser: the clean frame estimate at noise level sigma (b,)."""
214
+ c_skip, c_out, c_in = precondition(sigma)
215
+ return c_skip * noisy + c_out * self(c_in * noisy, sigma.log() / 4, context, actions)
216
+
217
+
218
+ def precondition(sigma):
219
+ """EDM skip, output and input scales for noise levels sigma (b,)."""
220
+ sigma = sigma[:, None, None, None]
221
+ total = sigma**2 + SIGMA_DATA**2
222
+ return SIGMA_DATA**2 / total, sigma * SIGMA_DATA / total.sqrt(), 1 / total.sqrt()
223
+
224
+
225
+ @torch.no_grad()
226
+ def sample(model, context, actions):
227
+ """The next frame in [-1, 1] by Euler steps on the Karras noise schedule."""
228
+ config = model.config
229
+ ramp = torch.linspace(0, 1, config.steps, device=context.device)
230
+ low, high = config.sigma_min ** (1 / config.rho), config.sigma_max ** (1 / config.rho)
231
+ sigmas = (high + ramp * (low - high)) ** config.rho
232
+ x = torch.randn_like(context[:, -1]) * sigmas[0]
233
+ for i, sigma in enumerate(sigmas):
234
+ denoised = model.denoise(x, sigma.expand(len(x)), context, actions)
235
+ following = sigmas[i + 1] if i + 1 < len(sigmas) else 0.0
236
+ x = denoised + (x - denoised) * following / sigma
237
+ return x.clamp(-1, 1)
238
+
239
+
240
+ @torch.no_grad()
241
+ def rollout(model, context, actions):
242
+ """Generate frames from context (b, c, 3, 64, 64) with actions (b, c - 1 + steps).
243
+
244
+ Returns (b, steps, 3, 64, 64) in [-1, 1].
245
+ """
246
+ size = model.config.context
247
+ frames = []
248
+ for step in range(actions.shape[1] - size + 1):
249
+ with torch.autocast(DEVICE, torch.bfloat16, enabled=DEVICE == "cuda"):
250
+ frame = sample(model, context, actions[:, step : step + size]).float()
251
+ frames.append(frame)
252
+ context = torch.cat([context[:, 1:], frame[:, None]], dim=1)
253
+ return torch.stack(frames, dim=1)
254
+
255
+
256
+ # Evaluation
257
+
258
+
259
+ def psnr(predicted, truth, mask):
260
+ """PSNR in dB per step for frames (b, t, 3, h, w) in [-1, 1], pooled over masked pixels."""
261
+ error = ((predicted - truth) / 2).pow(2) * mask
262
+ mse = error.sum((0, 2, 3, 4)) / mask.sum((0, 2, 3, 4)).clamp_min(1)
263
+ return 10 * torch.log10(1 / mse.clamp_min(1e-10))
264
+
265
+
266
+ def evaluate_model(model, frames, actions, episodes, count):
267
+ """PSNR of rollouts against real frames, with a repeat-the-last-frame baseline.
268
+
269
+ Much of an Atari frame is static, so PSNR is also given over changed pixels: those where
270
+ the real or the predicted frame differs from the last context frame.
271
+ """
272
+ size, horizon = model.config.context, max(HORIZONS)
273
+ valid = starts(episodes, size + horizon)
274
+ index = valid[torch.linspace(0, len(valid) - 1, min(count, len(valid))).long()]
275
+ rows = index[:, None] + torch.arange(size + horizon)
276
+ clip = to_float(frames[rows].to(DEVICE))
277
+ last = clip[:, size - 1 : size].expand_as(clip[:, size:])
278
+ guesses = {
279
+ "model": rollout(model, clip[:, :size], actions[rows[:, : size - 1 + horizon]].to(DEVICE)),
280
+ "repeat": last,
281
+ }
282
+ return {
283
+ "n": len(index),
284
+ **{name: score(guess, clip[:, size:], last) for name, guess in guesses.items()},
285
+ }
286
+
287
+
288
+ def score(guess, truth, last):
289
+ """PSNR over all pixels and over changed pixels at each horizon."""
290
+ changed = ((truth - last).abs() > 0.1) | ((guess - last).abs() > 0.1)
291
+ parts = {"all": torch.ones_like(truth), "changed": changed}
292
+ return {
293
+ part: {f"{h}": round(psnr(guess, truth, mask)[h - 1].item(), 2) for h in HORIZONS}
294
+ for part, mask in parts.items()
295
+ }
296
+
297
+
298
+ def gif(model, frames, actions, episodes, path):
299
+ """Real frames next to a rollout from the same start and actions, 4x upscaled."""
300
+ size = model.config.context
301
+ valid = starts(episodes, size + GIF_FRAMES)
302
+ index = valid[len(valid) // 2] # mid-play, past intros where nothing moves
303
+ clip = to_float(frames[index : index + size + GIF_FRAMES].to(DEVICE))
304
+ moves = actions[index : index + size - 1 + GIF_FRAMES].to(DEVICE)
305
+ predicted = rollout(model, clip[None, :size], moves[None])[0]
306
+ pairs = torch.cat([clip[size:], predicted], dim=-1)
307
+ images = [picture(pair, 4) for pair in pairs]
308
+ images[0].save(path, save_all=True, append_images=images[1:], duration=66, loop=0)
309
+
310
+
311
+ def picture(frame, scale):
312
+ """A [-1, 1] frame (3, h, w) as an upscaled PIL image."""
313
+ pixels = ((frame + 1) * 127.5).round().clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()
314
+ image = Image.fromarray(pixels)
315
+ return image.resize((image.width * scale, image.height * scale), Image.NEAREST)
316
+
317
+
318
+ # Training
319
+
320
+
321
+ def edm_loss(model, context, actions, clean, generator):
322
+ """EDM loss on the next frame, with noise levels from a log-normal."""
323
+ sigma = (torch.randn(len(clean), device=DEVICE, generator=generator) * 1.2 - 0.4).exp()
324
+ c_skip, c_out, c_in = precondition(sigma)
325
+ noisy = clean + sigma[:, None, None, None] * torch.randn_like(clean)
326
+ with torch.autocast(DEVICE, torch.bfloat16, enabled=DEVICE == "cuda"):
327
+ output = model(c_in * noisy, sigma.log() / 4, context, actions)
328
+ return (output.float() - (clean - c_skip * noisy) / c_out).pow(2).mean()
329
+
330
+
331
+ def save_state(folder, state):
332
+ """Write resumable training state to folder/state.pt, replacing it in one step."""
333
+ folder = Path(folder)
334
+ folder.mkdir(parents=True, exist_ok=True)
335
+ torch.save(state, folder / "state.pt.tmp")
336
+ os.replace(folder / "state.pt.tmp", folder / "state.pt")
337
+
338
+
339
+ def training_state(step, model, optimizer, generator):
340
+ """Everything needed to continue training exactly where it stopped."""
341
+ return {
342
+ "step": step,
343
+ "model": model.state_dict(),
344
+ "optimizer": optimizer.state_dict(),
345
+ "generator": generator.get_state(),
346
+ "rng": torch.get_rng_state(),
347
+ "cuda_rng": torch.cuda.get_rng_state() if DEVICE == "cuda" else None,
348
+ }
349
+
350
+
351
+ def resume(folder, model, optimizer, generator):
352
+ """Restore training state from folder/state.pt if there is one; return its step, else 0."""
353
+ if not folder or not (Path(folder) / "state.pt").exists():
354
+ return 0
355
+ state = torch.load(Path(folder) / "state.pt", map_location="cpu")
356
+ model.load_state_dict(state["model"])
357
+ optimizer.load_state_dict(state["optimizer"])
358
+ generator.set_state(state["generator"])
359
+ torch.set_rng_state(state["rng"])
360
+ if DEVICE == "cuda":
361
+ torch.cuda.set_rng_state(state["cuda_rng"])
362
+ print(f"resumed at step {state['step']}", flush=True)
363
+ return state["step"]
364
+
365
+
366
+ def fit(model, frames, actions, episodes, args):
367
+ """AdamW on random windows of the collected play, resuming from --checkpoint if set."""
368
+ optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-2)
369
+ valid = starts(episodes, model.config.context + 1).to(DEVICE)
370
+ generator = torch.Generator(DEVICE).manual_seed(args.seed)
371
+ first = resume(args.checkpoint, model, optimizer, generator)
372
+ start = time.time()
373
+ for step in range(first + 1, args.steps + 1):
374
+ pick = torch.randint(0, len(valid), (args.batch_size,), device=DEVICE, generator=generator)
375
+ batch = window(frames, actions, valid[pick], model.config.context)
376
+ loss = edm_loss(model, *batch, generator)
377
+ optimizer.zero_grad()
378
+ loss.backward()
379
+ nn.utils.clip_grad_norm_(model.parameters(), 1.0)
380
+ optimizer.step()
381
+ if step % args.log_every == 0:
382
+ log = {
383
+ "step": step,
384
+ "loss": round(loss.item(), 4),
385
+ "steps_s": round((step - first) / (time.time() - start), 1),
386
+ }
387
+ print(json.dumps(log), flush=True)
388
+ if args.checkpoint and (step % args.save_every == 0 or step == args.steps):
389
+ save_state(args.checkpoint, training_state(step, model, optimizer, generator))
390
+
391
+
392
+ def train(args):
393
+ """Collect random play, fit, score on held-out episodes, save and optionally push."""
394
+ torch.manual_seed(args.seed)
395
+ frames, actions, episodes = collect(args.frames, args.seed, args.game)
396
+ config = Config(
397
+ game=args.game,
398
+ actions=action_names(args.game),
399
+ context=args.context,
400
+ channels=tuple(args.channels),
401
+ steps=args.sample_steps,
402
+ )
403
+ model = Denoiser(config).to(DEVICE)
404
+ training = {
405
+ **{key: value for key, value in vars(args).items() if key not in ("run", "push")},
406
+ "episodes": int(episodes[-1]) + 1,
407
+ "params": sum(param.numel() for param in model.parameters()),
408
+ "device": torch.cuda.get_device_name() if DEVICE == "cuda" else "cpu",
409
+ }
410
+ print(json.dumps(training, indent=1), flush=True)
411
+
412
+ start = time.time()
413
+ fit(model, *(tensor.to(DEVICE) for tensor in (frames, actions, episodes)), args)
414
+ training["minutes"] = round((time.time() - start) / 60, 1)
415
+
416
+ model.eval()
417
+ test = collect(args.eval_frames, EVAL_SEED, args.game)
418
+ result = evaluate_model(model, *test, args.eval_windows)
419
+ print(json.dumps(result, indent=1))
420
+ folder = Path(args.output)
421
+ save(model, folder, training, result)
422
+ gif(model, *test, folder / "results" / "rollout.gif")
423
+ if args.push:
424
+ push(folder, args.repo)
425
+
426
+
427
+ def save(model, folder, training, result):
428
+ """Write weights, config, code and results to a folder."""
429
+ (folder / "results").mkdir(parents=True, exist_ok=True)
430
+ state = {key: value.cpu().contiguous() for key, value in model.state_dict().items()}
431
+ save_file(state, folder / "model.safetensors")
432
+ files = {
433
+ "config.json": asdict(model.config),
434
+ "results/train.json": training,
435
+ "results/eval.json": result,
436
+ }
437
+ for name, value in files.items():
438
+ (folder / name).write_text(json.dumps(value, indent=1) + "\n", encoding="utf-8")
439
+ if Path(__file__).resolve() != (folder / "atari.py").resolve():
440
+ shutil.copy(__file__, folder / "atari.py")
441
+
442
+
443
+ def push(folder, repo):
444
+ """Upload a folder to a private model repo, creating it if needed."""
445
+ api = HfApi()
446
+ api.create_repo(repo, private=True, exist_ok=True)
447
+ api.upload_folder(folder_path=folder, repo_id=repo, commit_message="Add model and results")
448
+
449
+
450
+ def load(name, device=DEVICE):
451
+ """Load a trained model from a Hub repo id or a local folder."""
452
+ folder = Path(name) if Path(name).is_dir() else Path(snapshot_download(name))
453
+ config = Config(**json.loads((folder / "config.json").read_text(encoding="utf-8")))
454
+ model = Denoiser(config)
455
+ model.load_state_dict(load_file(folder / "model.safetensors"))
456
+ return model.to(device).eval()
457
+
458
+
459
+ # Play
460
+
461
+
462
+ def play(args):
463
+ """A browser page with one button per action; every press generates the next frame."""
464
+ model = load(args.model)
465
+ size = model.config.context
466
+ frames, actions, _ = collect(size, args.seed, model.config.game)
467
+ first = (to_float(frames[:size]).to(DEVICE), actions[: size - 1].to(DEVICE))
468
+
469
+ def act(action, state):
470
+ context, past = state
471
+ moves = torch.cat([past, torch.tensor([action], device=DEVICE)])
472
+ frame = rollout(model, context[None], moves[None])[0, 0]
473
+ state = (torch.cat([context[1:], frame[None]]), moves[1:])
474
+ return picture(frame, 6), state
475
+
476
+ with gr.Blocks(title=f"{GAMES[model.config.game][0]} world model") as demo:
477
+ state = gr.State(first)
478
+ screen = gr.Image(picture(first[0][-1], 6), label="Generated frame")
479
+ with gr.Row():
480
+ for action, name in enumerate(model.config.actions):
481
+ button = gr.Button(name)
482
+ button.click(partial(act, action), state, [screen, state], api_name=name.lower())
483
+ start = picture(first[0][-1], 6)
484
+ gr.Button("Reset").click(lambda: (start, first), None, [screen, state], api_name="reset")
485
+ demo.launch()
486
+
487
+
488
+ def card(args):
489
+ """Render card.jinja into card/<slug>/README.md with the config and results in the repo."""
490
+ display, slug = GAMES[args.game]
491
+ files = {}
492
+ try:
493
+ folder = Path(snapshot_download(args.repo, allow_patterns=["config.json", "results/*"]))
494
+ files = {
495
+ path.relative_to(folder).as_posix(): json.loads(path.read_text(encoding="utf-8"))
496
+ for path in folder.glob("**/*.json")
497
+ }
498
+ except RepositoryNotFoundError:
499
+ pass
500
+ evaluation = files.get("results/eval.json")
501
+ data = ModelCardData(
502
+ model_name=args.repo.split("/")[1],
503
+ license="apache-2.0",
504
+ library_name="pytorch",
505
+ tags=["world-model", "diffusion", "atari", slug, "video-generation"],
506
+ eval_results=[
507
+ EvalResult(
508
+ task_type="other",
509
+ task_name="Next-frame rollout",
510
+ dataset_type=f"ale/{slug}",
511
+ dataset_name=f"{display}, held-out random play",
512
+ metric_type=f"psnr_changed_{h}",
513
+ metric_name=f"PSNR on changed pixels at {h} frames",
514
+ metric_value=evaluation["model"]["changed"][f"{h}"],
515
+ )
516
+ for h in HORIZONS
517
+ ]
518
+ if evaluation
519
+ else None,
520
+ )
521
+ rendered = ModelCard.from_template(
522
+ data,
523
+ template_path=HERE / "card.jinja",
524
+ repo=args.repo,
525
+ game=args.game,
526
+ display=display,
527
+ actions=action_names(args.game),
528
+ config=files.get("config.json"),
529
+ train=files.get("results/train.json"),
530
+ evaluation=evaluation,
531
+ horizons=[f"{h}" for h in HORIZONS],
532
+ )
533
+ (HERE / "card" / slug).mkdir(parents=True, exist_ok=True)
534
+ rendered.save(HERE / "card" / slug / "README.md")
535
+
536
+
537
+ def main():
538
+ """Parse arguments and run a command."""
539
+ parser = argparse.ArgumentParser(description=__doc__)
540
+ commands = parser.add_subparsers(dest="command", required=True)
541
+
542
+ train_parser = commands.add_parser("train")
543
+ train_parser.add_argument("--frames", type=int, default=200_000)
544
+ train_parser.add_argument("--eval-frames", type=int, default=5_000)
545
+ train_parser.add_argument("--eval-windows", type=int, default=256)
546
+ train_parser.add_argument("--context", type=int, default=4)
547
+ train_parser.add_argument("--channels", type=int, nargs="+", default=[64, 128, 256])
548
+ train_parser.add_argument("--sample-steps", type=int, default=3)
549
+ train_parser.add_argument("--steps", type=int, default=50_000)
550
+ train_parser.add_argument("--batch-size", type=int, default=64)
551
+ train_parser.add_argument("--lr", type=float, default=1e-4)
552
+ train_parser.add_argument("--seed", type=int, default=0)
553
+ train_parser.add_argument("--log-every", type=int, default=500)
554
+ train_parser.add_argument("--checkpoint", help="folder for resumable state, e.g. a bucket")
555
+ train_parser.add_argument("--save-every", type=int, default=2500)
556
+ train_parser.add_argument("--output", default="out")
557
+ train_parser.add_argument("--repo", help="defaults to the game's repo")
558
+ train_parser.add_argument("--push", action="store_true")
559
+ train_parser.set_defaults(run=train)
560
+
561
+ play_parser = commands.add_parser("play")
562
+ play_parser.add_argument("--model", help="repo id or folder; defaults to the game's repo")
563
+ play_parser.add_argument("--seed", type=int, default=EVAL_SEED)
564
+ play_parser.set_defaults(run=play)
565
+
566
+ card_parser = commands.add_parser("card")
567
+ card_parser.add_argument("--repo", help="defaults to the game's repo")
568
+ card_parser.set_defaults(run=card)
569
+
570
+ for command in (train_parser, play_parser, card_parser):
571
+ command.add_argument("--game", choices=GAMES, required=True)
572
+ args = parser.parse_args()
573
+ for name in ("repo", "model"):
574
+ if getattr(args, name, "") is None:
575
+ setattr(args, name, repo_for(args.game))
576
+ args.run(args)
577
+
578
+
579
+ if __name__ == "__main__":
580
+ main()
config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "game": "SpaceInvaders",
3
+ "actions": [
4
+ "NOOP",
5
+ "FIRE",
6
+ "RIGHT",
7
+ "LEFT",
8
+ "RIGHTFIRE",
9
+ "LEFTFIRE"
10
+ ],
11
+ "context": 4,
12
+ "channels": [
13
+ 64,
14
+ 128,
15
+ 256
16
+ ],
17
+ "steps": 3,
18
+ "sigma_min": 0.002,
19
+ "sigma_max": 5.0,
20
+ "rho": 7.0
21
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28b074bf310f7fba47144e9f06e22bbc5dd1af7693c7c3cea9f2055e8232a19c
3
+ size 16736556
results/eval.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "n": 256,
3
+ "model": {
4
+ "all": {
5
+ "1": 35.43,
6
+ "5": 31.07,
7
+ "15": 27.33
8
+ },
9
+ "changed": {
10
+ "1": 18.17,
11
+ "5": 18.35,
12
+ "15": 16.64
13
+ }
14
+ },
15
+ "repeat": {
16
+ "all": {
17
+ "1": 36.56,
18
+ "5": 30.94,
19
+ "15": 26.77
20
+ },
21
+ "changed": {
22
+ "1": 16.0,
23
+ "5": 15.9,
24
+ "15": 14.54
25
+ }
26
+ }
27
+ }
results/rollout.gif ADDED

Git LFS Details

  • SHA256: 9d7d0727e0dd5b47fa2c4f619471155883ed7b39d68b67382a4ea691d841ddde
  • Pointer size: 132 Bytes
  • Size of remote file: 1.9 MB
results/train.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "command": "train",
3
+ "frames": 200000,
4
+ "eval_frames": 5000,
5
+ "eval_windows": 256,
6
+ "context": 4,
7
+ "channels": [
8
+ 64,
9
+ 128,
10
+ 256
11
+ ],
12
+ "sample_steps": 3,
13
+ "steps": 50000,
14
+ "batch_size": 64,
15
+ "lr": 0.0001,
16
+ "seed": 0,
17
+ "log_every": 500,
18
+ "checkpoint": "/checkpoints/space-invaders",
19
+ "save_every": 2500,
20
+ "output": "out",
21
+ "repo": "jgalego/space-invaders-world-model",
22
+ "game": "SpaceInvaders",
23
+ "episodes": 382,
24
+ "params": 4182211,
25
+ "device": "NVIDIA A10G",
26
+ "minutes": 55.9
27
+ }