jgalego commited on
Commit
cd6f7b2
·
verified ·
1 Parent(s): 8225c1b

Add model and results

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

Git LFS Details

  • SHA256: b91354c1ecd54ce19ee0f464323ea32987fc52740c387c5e86b126d8ad0a5732
  • Pointer size: 132 Bytes
  • Size of remote file: 1.62 MB
results/train.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/breakout",
19
+ "save_every": 2500,
20
+ "output": "out",
21
+ "repo": "jgalego/breakout-world-model",
22
+ "episodes": 600,
23
+ "params": 4182083,
24
+ "device": "NVIDIA A10G",
25
+ "minutes": 55.9
26
+ }