lzhts1 commited on
Commit
0c96924
·
verified ·
1 Parent(s): 74794c1

Delete eval.py

Browse files
Files changed (1) hide show
  1. eval.py +0 -937
eval.py DELETED
@@ -1,937 +0,0 @@
1
- import os
2
-
3
-
4
- def _configure_mujoco_backend() -> str:
5
- backend = os.environ.get("MUJOCO_GL", "egl").strip().lower() or "egl"
6
- os.environ["MUJOCO_GL"] = backend
7
- if backend in {"egl", "osmesa"}:
8
- os.environ.setdefault("PYOPENGL_PLATFORM", backend)
9
- return backend
10
-
11
-
12
- MUJOCO_GL_BACKEND = _configure_mujoco_backend()
13
-
14
- import time
15
- from collections import defaultdict
16
- from copy import deepcopy
17
- from pathlib import Path
18
- from typing import Any, Sequence
19
-
20
- import gymnasium as gym
21
- import hydra
22
- import numpy as np
23
- import stable_pretraining as spt
24
- import torch
25
- from omegaconf import DictConfig, OmegaConf, open_dict
26
- from sklearn import preprocessing
27
- from torchvision.transforms import v2 as transforms
28
- from tqdm.auto import tqdm
29
- import stable_worldmodel as swm
30
-
31
- from module import ARPredictor, Embedder, MLP, SIGReg
32
- from train_hyperbolic import (
33
- AdaptiveEntailmentConeLoss,
34
- HyperbolicJEPA,
35
- LorentzContrastiveLoss,
36
- LorentzManifold,
37
- build_hyperbolic_world_model,
38
- ensure_hyperbolic_defaults,
39
- )
40
- from utils import resolve_runtime_device
41
-
42
-
43
- def _maybe_register_ogbench_envs() -> None:
44
- try:
45
- import ogbench # noqa: F401
46
- print("[eval] imported ogbench to register Gym environments", flush=True)
47
- except Exception as exc:
48
- print(
49
- f"[eval] ogbench import skipped: {type(exc).__name__}: {exc}",
50
- flush=True,
51
- )
52
-
53
-
54
- def _build_env_candidates(env_name: str) -> list[str]:
55
- raw_candidates = [env_name]
56
-
57
- if env_name.startswith("visual-"):
58
- raw_candidates.append(env_name.removeprefix("visual-"))
59
-
60
- for suffix in ("-navigate-v0", "-oraclerep-v0"):
61
- expanded = []
62
- for candidate in raw_candidates:
63
- if candidate.endswith(suffix):
64
- expanded.append(candidate[: -len(suffix)] + "-v0")
65
- raw_candidates.extend(expanded)
66
-
67
- expanded = []
68
- for candidate in raw_candidates:
69
- if candidate.startswith("visual-"):
70
- expanded.append(candidate.removeprefix("visual-"))
71
- raw_candidates.extend(expanded)
72
-
73
- candidates = []
74
- seen = set()
75
- for candidate in raw_candidates:
76
- if candidate in seen:
77
- continue
78
- seen.add(candidate)
79
- candidates.append(candidate)
80
- return candidates
81
-
82
-
83
- def _resolve_world_env_name(env_name: str) -> str:
84
- _maybe_register_ogbench_envs()
85
-
86
- registry_keys = set(gym.registry.keys())
87
- if env_name in registry_keys:
88
- return env_name
89
-
90
- candidates = _build_env_candidates(env_name)
91
- for candidate in candidates:
92
- if candidate in registry_keys:
93
- print(
94
- f"[eval] resolved env_name '{env_name}' -> '{candidate}'",
95
- flush=True,
96
- )
97
- return candidate
98
-
99
- print(
100
- f"[eval] could not resolve env_name '{env_name}'. "
101
- f"Tried: {candidates}",
102
- flush=True,
103
- )
104
- return env_name
105
-
106
- def img_transform(cfg):
107
- transform = transforms.Compose(
108
- [
109
- transforms.ToImage(),
110
- transforms.ToDtype(torch.float32, scale=True),
111
- transforms.Normalize(**spt.data.dataset_stats.ImageNet),
112
- transforms.Resize(size=cfg.eval.img_size),
113
- ]
114
- )
115
- return transform
116
-
117
-
118
- def get_episodes_length(dataset, episodes):
119
- col_name = "episode_idx" if "episode_idx" in dataset.column_names else "ep_idx"
120
-
121
- episode_idx = dataset.get_col_data(col_name)
122
- step_idx = dataset.get_col_data("step_idx")
123
- lengths = []
124
- for ep_id in episodes:
125
- lengths.append(np.max(step_idx[episode_idx == ep_id]) + 1)
126
- return np.array(lengths)
127
-
128
-
129
- def get_dataset(cfg, dataset_name):
130
- dataset_path = Path(cfg.cache_dir or swm.data.utils.get_cache_dir())
131
- dataset = swm.data.HDF5Dataset(
132
- dataset_name,
133
- keys_to_cache=cfg.dataset.keys_to_cache,
134
- cache_dir=dataset_path,
135
- )
136
- return dataset
137
-
138
-
139
- def _get_column_row_count(dataset, col_name: str) -> int | None:
140
- h5_file = getattr(dataset, "h5_file", None)
141
- try:
142
- if h5_file is not None and col_name in h5_file:
143
- shape = getattr(h5_file[col_name], "shape", None)
144
- if shape:
145
- return int(shape[0])
146
- except Exception:
147
- pass
148
-
149
- try:
150
- return int(len(dataset.get_col_data(col_name)))
151
- except Exception:
152
- return None
153
-
154
-
155
- def _resolve_safe_row_limit(dataset, extra_columns: Sequence[str]) -> tuple[int, dict[str, int]]:
156
- counts: dict[str, int] = {"__len__": int(len(dataset))}
157
- episode_meta_columns = {"ep_len", "ep_offset", "episode_ends"}
158
- columns = [
159
- col for col in list(getattr(dataset, "_keys", [])) + list(extra_columns)
160
- if col not in episode_meta_columns
161
- ]
162
-
163
- seen = set()
164
- for col_name in columns:
165
- if col_name in seen:
166
- continue
167
- seen.add(col_name)
168
- count = _get_column_row_count(dataset, col_name)
169
- if count is not None:
170
- counts[col_name] = count
171
-
172
- safe_limit = min(counts.values())
173
- return safe_limit, counts
174
-
175
-
176
- def _chunk_has_content(episode_chunk: dict[str, Any]) -> tuple[bool, str | None]:
177
- for col_name, value in episode_chunk.items():
178
- if not isinstance(value, (torch.Tensor, np.ndarray)):
179
- continue
180
- shape = getattr(value, "shape", None)
181
- if shape is None or len(shape) < 1:
182
- continue
183
- if int(shape[0]) == 0:
184
- return False, col_name
185
- return True, None
186
-
187
-
188
- def _select_valid_eval_rows(
189
- dataset,
190
- candidate_indices: np.ndarray,
191
- episode_idx_col: np.ndarray,
192
- step_idx_col: np.ndarray,
193
- goal_offset_steps: int,
194
- num_eval: int,
195
- ) -> np.ndarray:
196
- selected: list[int] = []
197
- skipped_empty = 0
198
-
199
- for row_idx in candidate_indices.tolist():
200
- ep_id = int(episode_idx_col[row_idx])
201
- start_step = int(step_idx_col[row_idx])
202
- end_step = int(start_step + goal_offset_steps)
203
-
204
- try:
205
- chunk = dataset.load_chunk(
206
- np.array([ep_id]),
207
- np.array([start_step]),
208
- np.array([end_step]),
209
- )
210
- except Exception as exc:
211
- print(
212
- f"[eval] skipping candidate row={row_idx} episode={ep_id} start={start_step} "
213
- f"because load_chunk failed: {type(exc).__name__}: {exc}",
214
- flush=True,
215
- )
216
- continue
217
-
218
- if not chunk:
219
- skipped_empty += 1
220
- continue
221
-
222
- has_content, bad_col = _chunk_has_content(chunk[0])
223
- if not has_content:
224
- if skipped_empty < 5:
225
- print(
226
- f"[eval] skipping empty candidate row={row_idx} episode={ep_id} "
227
- f"start={start_step} bad_col={bad_col}",
228
- flush=True,
229
- )
230
- skipped_empty += 1
231
- continue
232
-
233
- selected.append(int(row_idx))
234
- if len(selected) >= num_eval:
235
- break
236
-
237
- if skipped_empty:
238
- print(f"[eval] skipped {skipped_empty} empty/invalid evaluation candidates.", flush=True)
239
-
240
- if len(selected) < num_eval:
241
- raise ValueError(
242
- f"Only found {len(selected)} valid evaluation starts after load_chunk validation, "
243
- f"but {num_eval} were requested."
244
- )
245
-
246
- return np.asarray(selected, dtype=np.int64)
247
-
248
-
249
- def _register_hyperbolic_main_aliases():
250
- import __main__ as main_mod
251
-
252
- for obj in (
253
- HyperbolicJEPA,
254
- LorentzManifold,
255
- LorentzContrastiveLoss,
256
- AdaptiveEntailmentConeLoss,
257
- ARPredictor,
258
- Embedder,
259
- MLP,
260
- SIGReg,
261
- ):
262
- setattr(main_mod, obj.__name__, obj)
263
-
264
- if hasattr(torch.serialization, "add_safe_globals"):
265
- torch.serialization.add_safe_globals(
266
- [
267
- HyperbolicJEPA,
268
- LorentzManifold,
269
- LorentzContrastiveLoss,
270
- AdaptiveEntailmentConeLoss,
271
- ARPredictor,
272
- Embedder,
273
- MLP,
274
- SIGReg,
275
- ]
276
- )
277
-
278
-
279
- def _resolve_policy_artifact_candidates(policy_name: str, cache_dir: Path) -> list[tuple[Path, Path]]:
280
- raw = Path(policy_name)
281
- candidates = []
282
-
283
- def add_exact_prefix_artifacts(path_like: Path):
284
- path_text = str(path_like)
285
- for suffix in ("_state.ckpt", "_object.ckpt", "_weights.ckpt"):
286
- if path_text.endswith(suffix):
287
- add_exact_prefix_artifacts(Path(path_text[: -len(suffix)]))
288
- return
289
- if path_text.endswith(".ckpt"):
290
- candidates.append(path_like)
291
- return
292
-
293
- # Prefer device-neutral epoch state dicts when they exist. Object
294
- # checkpoints saved on Ascend may require torch_npu to unpickle.
295
- candidates.append(Path(f"{path_like}_state.ckpt"))
296
- candidates.append(Path(f"{path_like}_object.ckpt"))
297
- candidates.append(Path(f"{path_like}_weights.ckpt"))
298
-
299
- add_exact_prefix_artifacts(raw)
300
- add_exact_prefix_artifacts(cache_dir / raw)
301
-
302
- if raw.is_file():
303
- candidates.append(raw)
304
- cache_raw = cache_dir / raw
305
- if cache_raw.is_file():
306
- candidates.append(cache_raw)
307
- if cache_raw.is_dir():
308
- weights = sorted(cache_raw.glob("*_weights.ckpt"))
309
- if len(weights) == 1:
310
- candidates.append(weights[0])
311
-
312
- seen = set()
313
- resolved = []
314
- for candidate in candidates:
315
- candidate = Path(candidate)
316
- if candidate in seen:
317
- continue
318
- seen.add(candidate)
319
- if candidate.is_file():
320
- config_path = candidate.parent / "config.yaml"
321
- if config_path.is_file():
322
- resolved.append((candidate, config_path))
323
-
324
- if resolved:
325
- return resolved
326
-
327
- raise FileNotFoundError(
328
- f"Could not resolve checkpoint/config for policy '{policy_name}' under cache '{cache_dir}'."
329
- )
330
-
331
-
332
- def _resolve_policy_artifacts(policy_name: str, cache_dir: Path) -> tuple[Path, Path]:
333
- return _resolve_policy_artifact_candidates(policy_name, cache_dir)[0]
334
-
335
-
336
- def _load_hyperbolic_policy_model(cfg: DictConfig, dataset, runtime_device: str):
337
- cache_dir = Path(cfg.cache_dir or swm.data.utils.get_cache_dir())
338
- checkpoint_candidates = _resolve_policy_artifact_candidates(cfg.policy, cache_dir)
339
- _register_hyperbolic_main_aliases()
340
- failures = []
341
-
342
- for checkpoint_path, config_path in checkpoint_candidates:
343
- print(
344
- f"[eval] trying hyperbolic checkpoint={checkpoint_path} config={config_path}",
345
- flush=True,
346
- )
347
- train_cfg = OmegaConf.load(config_path)
348
- ensure_hyperbolic_defaults(train_cfg)
349
- action_dim = int(getattr(train_cfg.wm, "action_dim", dataset.get_dim("action")))
350
- model = build_hyperbolic_world_model(train_cfg, action_dim=action_dim)
351
-
352
- try:
353
- checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
354
- if isinstance(checkpoint, torch.nn.Module):
355
- model = checkpoint
356
- else:
357
- if isinstance(checkpoint, dict) and "state_dict" in checkpoint:
358
- state_dict = checkpoint["state_dict"]
359
- elif isinstance(checkpoint, dict):
360
- state_dict = checkpoint
361
- else:
362
- raise TypeError(
363
- f"Unsupported checkpoint type '{type(checkpoint).__name__}' for '{checkpoint_path}'."
364
- )
365
-
366
- if any(key.startswith("model.") for key in state_dict.keys()):
367
- state_dict = {
368
- key[len("model."):]: value
369
- for key, value in state_dict.items()
370
- if key.startswith("model.")
371
- }
372
-
373
- strict = bool(getattr(cfg.get("checkpoint", {}), "strict", True))
374
- missing, unexpected = model.load_state_dict(state_dict, strict=strict)
375
- print(
376
- f"[eval] loaded hyperbolic checkpoint {checkpoint_path} "
377
- f"(strict={strict}, missing={len(missing)}, unexpected={len(unexpected)})",
378
- flush=True,
379
- )
380
- if missing:
381
- print(f"[eval] missing keys: {missing}", flush=True)
382
- if unexpected:
383
- print(f"[eval] unexpected keys: {unexpected}", flush=True)
384
- except ModuleNotFoundError as exc:
385
- if exc.name == "torch_npu" or str(exc.name).startswith("torch_npu."):
386
- failures.append(
387
- f"{checkpoint_path}: requires torch_npu during object deserialization"
388
- )
389
- print(
390
- f"[eval] checkpoint {checkpoint_path} requires torch_npu; "
391
- "trying the next portable/state checkpoint candidate.",
392
- flush=True,
393
- )
394
- continue
395
- raise
396
- except RuntimeError as exc:
397
- failures.append(f"{checkpoint_path}: {type(exc).__name__}: {exc}")
398
- print(
399
- f"[eval] checkpoint {checkpoint_path} did not match the rebuilt model; "
400
- "trying the next checkpoint candidate.",
401
- flush=True,
402
- )
403
- continue
404
-
405
- model = model.to(runtime_device)
406
- model = model.eval()
407
- model.requires_grad_(False)
408
- model.interpolate_pos_encoding = True
409
- return model
410
-
411
- failure_details = "\n".join(f" - {failure}" for failure in failures)
412
- raise RuntimeError(
413
- "Unable to load a hyperbolic policy checkpoint on this runtime. "
414
- "For an object checkpoint saved from NPU training, evaluate in a torch_npu "
415
- "environment once or train/export a matching '<prefix>_state.ckpt' portable state dict.\n"
416
- f"Tried:\n{failure_details}"
417
- )
418
-
419
-
420
- def load_policy_model(cfg: DictConfig, dataset, runtime_device: str):
421
- try:
422
- model = swm.policy.AutoCostModel(cfg.policy)
423
- model = model.to(runtime_device)
424
- model = model.eval()
425
- model.requires_grad_(False)
426
- model.interpolate_pos_encoding = True
427
- print(f"[eval] loaded policy via AutoCostModel: {cfg.policy}", flush=True)
428
- return model
429
- except Exception as exc:
430
- print(
431
- f"[eval] AutoCostModel failed for '{cfg.policy}': {type(exc).__name__}: {exc}",
432
- flush=True,
433
- )
434
- print("[eval] falling back to hyperbolic checkpoint loader", flush=True)
435
- return _load_hyperbolic_policy_model(cfg, dataset, runtime_device)
436
-
437
-
438
- def _wrap_step_with_static_info(env, static_info: dict[str, Any]) -> None:
439
- """Inject dataset goal info into env.step infos for envs that do not emit it."""
440
- env._lewm_static_step_info = static_info
441
- if getattr(env, "_lewm_static_step_info_wrapped", False):
442
- return
443
-
444
- original_step = env.step
445
-
446
- def step_with_static_info(action):
447
- result = original_step(action)
448
- if len(result) == 5:
449
- obs, reward, terminated, truncated, info = result
450
- info = {} if info is None else dict(info)
451
- for key, value in getattr(env, "_lewm_static_step_info", {}).items():
452
- info.setdefault(key, deepcopy(value))
453
- return obs, reward, terminated, truncated, info
454
-
455
- obs, reward, done, info = result
456
- info = {} if info is None else dict(info)
457
- for key, value in getattr(env, "_lewm_static_step_info", {}).items():
458
- info.setdefault(key, deepcopy(value))
459
- return obs, reward, done, info
460
-
461
- env.step = step_with_static_info
462
- env._lewm_static_step_info_wrapped = True
463
-
464
-
465
- def _iter_vector_env_lists(root) -> list:
466
- env_lists = []
467
- queue = [root]
468
- seen = set()
469
- while queue:
470
- obj = queue.pop(0)
471
- if obj is None or id(obj) in seen:
472
- continue
473
- seen.add(id(obj))
474
-
475
- envs = getattr(obj, "envs", None)
476
- if isinstance(envs, (list, tuple)) and envs:
477
- env_lists.append(envs)
478
-
479
- for attr in ("env", "unwrapped"):
480
- try:
481
- child = getattr(obj, attr, None)
482
- except Exception:
483
- child = None
484
- if child is not None and id(child) not in seen:
485
- queue.append(child)
486
- return env_lists
487
-
488
-
489
- def _inject_static_goal_info_into_envs(world, goal_step: dict[str, np.ndarray]) -> None:
490
- """Make dataset goals visible in per-step env info for wrappers that require them."""
491
- wrapped_count = 0
492
- for envs in _iter_vector_env_lists(world.envs):
493
- if len(envs) != world.num_envs:
494
- continue
495
- for env_index, env in enumerate(envs):
496
- static_info = _prepare_static_info_for_env(goal_step, env_index)
497
- if not static_info:
498
- continue
499
-
500
- current_env = env
501
- seen = set()
502
- while current_env is not None and id(current_env) not in seen:
503
- seen.add(id(current_env))
504
- _wrap_step_with_static_info(current_env, static_info)
505
- wrapped_count += 1
506
- current_env = getattr(current_env, "env", None)
507
-
508
- if wrapped_count == 0:
509
- print("[eval] warning: did not find env wrappers to inject static goal info", flush=True)
510
- else:
511
- print(f"[eval] injected static goal info into {wrapped_count} env wrapper(s)", flush=True)
512
-
513
-
514
- def _set_dataset_goal_xy(world, goal_step: dict[str, np.ndarray]) -> None:
515
- """Align OGBench MazeEnv success checks with the dataset goal state."""
516
- goal_qpos = goal_step.get("goal_qpos")
517
- if goal_qpos is None:
518
- return
519
-
520
- applied = 0
521
- for i, env in enumerate(_get_unwrapped_envs(world)):
522
- env_unwrapped = env.unwrapped
523
- set_goal = getattr(env_unwrapped, "set_goal", None)
524
- if not callable(set_goal):
525
- continue
526
- goal_xy = np.asarray(goal_qpos[i], dtype=np.float64).reshape(-1)[:2]
527
- if goal_xy.shape[0] != 2:
528
- continue
529
- try:
530
- set_goal(goal_xy=goal_xy)
531
- applied += 1
532
- except TypeError:
533
- continue
534
-
535
- if applied:
536
- print(f"[eval] set dataset goal_xy for {applied} env(s)", flush=True)
537
-
538
-
539
- def _get_unwrapped_envs(world):
540
- envs = getattr(getattr(world.envs, "unwrapped", world.envs), "envs", None)
541
- if isinstance(envs, (list, tuple)) and envs:
542
- return envs
543
- for envs in _iter_vector_env_lists(world.envs):
544
- if len(envs) == world.num_envs:
545
- return envs
546
- return []
547
-
548
-
549
- def _set_vector_autoreset_flags(world) -> None:
550
- for obj in (world.envs, getattr(world.envs, "unwrapped", None)):
551
- if obj is not None and hasattr(obj, "_autoreset_envs"):
552
- obj._autoreset_envs = np.zeros((world.num_envs,))
553
- return
554
-
555
-
556
- def _resize_hwc_frames(frames: np.ndarray, height: int, width: int) -> np.ndarray:
557
- if frames.shape[-3:-1] == (height, width):
558
- return frames.astype(np.uint8, copy=False)
559
-
560
- import torch.nn.functional as F
561
-
562
- tensor = torch.as_tensor(frames)
563
- original_shape = tensor.shape
564
- tensor = tensor.reshape(-1, *original_shape[-3:]).permute(0, 3, 1, 2).float()
565
- tensor = F.interpolate(tensor, size=(height, width), mode="bilinear", align_corners=False)
566
- tensor = tensor.clamp(0, 255).byte().permute(0, 2, 3, 1)
567
- return tensor.reshape(*original_shape[:-3], height, width, original_shape[-1]).cpu().numpy()
568
-
569
-
570
- def _prepare_static_info_for_env(goal_step: dict[str, np.ndarray], env_index: int) -> dict[str, Any]:
571
- static_info = {}
572
- for key, value in goal_step.items():
573
- if not isinstance(value, np.ndarray) or value.shape[0] <= env_index:
574
- continue
575
- env_value = value[env_index]
576
- if isinstance(env_value, np.ndarray) and env_value.ndim > 0:
577
- env_value = env_value[-1]
578
- static_info[key] = deepcopy(env_value)
579
- return static_info
580
-
581
-
582
- def evaluate_from_dataset_with_progress(
583
- world,
584
- dataset: Any,
585
- episodes_idx: Sequence[int],
586
- start_steps: Sequence[int],
587
- goal_offset_steps: int,
588
- eval_budget: int,
589
- callables: list[dict] | None = None,
590
- save_video: bool = True,
591
- video_path: str | Path = "./",
592
- ):
593
- """Copy of stable_worldmodel's dataset evaluation with tqdm progress bars."""
594
- assert (
595
- world.envs.envs[0].spec.max_episode_steps is None
596
- or world.envs.envs[0].spec.max_episode_steps >= goal_offset_steps
597
- ), "env max_episode_steps must be greater than eval_budget"
598
-
599
- ep_idx_arr = np.array(episodes_idx)
600
- start_steps_arr = np.array(start_steps)
601
- end_steps = start_steps_arr + goal_offset_steps
602
-
603
- if len(ep_idx_arr) != len(start_steps_arr):
604
- raise ValueError("episodes_idx and start_steps must have the same length")
605
- if len(ep_idx_arr) != world.num_envs:
606
- raise ValueError("Number of episodes to evaluate must match number of envs")
607
-
608
- data = dataset.load_chunk(ep_idx_arr, start_steps_arr, end_steps)
609
- columns = dataset.column_names
610
-
611
- init_step_per_env: dict[str, list[Any]] = defaultdict(list)
612
- goal_step_per_env: dict[str, list[Any]] = defaultdict(list)
613
- for ep in data:
614
- for col in columns:
615
- if col.startswith("goal"):
616
- continue
617
- if col.startswith("pixels"):
618
- ep[col] = ep[col].permute(0, 2, 3, 1)
619
- if not isinstance(ep[col], (torch.Tensor, np.ndarray)):
620
- continue
621
-
622
- init_data = ep[col][0]
623
- goal_data = ep[col][-1]
624
- if not isinstance(init_data, (np.ndarray, torch.Tensor)):
625
- continue
626
-
627
- init_data = init_data.numpy() if isinstance(init_data, torch.Tensor) else init_data
628
- goal_data = goal_data.numpy() if isinstance(goal_data, torch.Tensor) else goal_data
629
- init_step_per_env[col].append(init_data)
630
- goal_step_per_env[col].append(goal_data)
631
-
632
- init_step = {k: np.stack(v) for k, v in deepcopy(init_step_per_env).items()}
633
- goal_step = {}
634
- for key, value in goal_step_per_env.items():
635
- goal_key = "goal" if key == "pixels" else f"goal_{key}"
636
- goal_step[goal_key] = np.stack(value)
637
-
638
- seeds = init_step.get("seed")
639
- vkey = "variation."
640
- variations_dict = {
641
- k.removeprefix(vkey): v for k, v in init_step.items() if k.startswith(vkey)
642
- }
643
- options = [{} for _ in range(world.num_envs)]
644
- if variations_dict:
645
- for i in range(world.num_envs):
646
- options[i]["variation"] = list(variations_dict.keys())
647
- options[i]["variation_values"] = {k: v[i] for k, v in variations_dict.items()}
648
-
649
- init_step.update(deepcopy(goal_step))
650
- world.reset(seed=seeds, options=options)
651
-
652
- callables = callables or []
653
- for i, env in enumerate(_get_unwrapped_envs(world)):
654
- env_unwrapped = env.unwrapped
655
- for spec in callables:
656
- method_name = spec["method"]
657
- if not hasattr(env_unwrapped, method_name):
658
- continue
659
- method = getattr(env_unwrapped, method_name)
660
- args = spec.get("args", spec)
661
-
662
- prepared_args = {}
663
- for args_name, args_data in args.items():
664
- value = args_data.get("value", None)
665
- is_in_dataset = args_data.get("in_dataset", True)
666
- if is_in_dataset:
667
- if value not in init_step:
668
- continue
669
- prepared_args[args_name] = deepcopy(init_step[value][i])
670
- else:
671
- prepared_args[args_name] = value
672
-
673
- method(**prepared_args)
674
-
675
- for i, env in enumerate(_get_unwrapped_envs(world)):
676
- env_unwrapped = env.unwrapped
677
- if "goal_state" in init_step and "goal_state" in goal_step:
678
- assert np.array_equal(
679
- init_step["goal_state"][i], goal_step["goal_state"][i]
680
- ), f"Goal state info does not match at reset for env {env_unwrapped}"
681
-
682
- _set_dataset_goal_xy(world, goal_step)
683
-
684
- results: dict = {
685
- "success_rate": 0.0,
686
- "episode_successes": np.zeros(len(episodes_idx)),
687
- "seeds": seeds,
688
- }
689
-
690
- shape_prefix = world.infos["pixels"].shape[:2]
691
- init_step = {
692
- k: np.broadcast_to(v[:, None, ...], shape_prefix + v.shape[1:]) for k, v in init_step.items()
693
- }
694
- goal_step = {
695
- k: np.broadcast_to(v[:, None, ...], shape_prefix + v.shape[1:]) for k, v in goal_step.items()
696
- }
697
- _inject_static_goal_info_into_envs(world, goal_step)
698
-
699
- world.infos.update(deepcopy(init_step))
700
- world.infos.update(deepcopy(goal_step))
701
-
702
- if "goal" in goal_step and "goal" in world.infos:
703
- assert np.allclose(world.infos["goal"], goal_step["goal"]), "Goal info does not match"
704
-
705
- target_frames = torch.stack([ep["pixels"] for ep in data]).numpy()
706
- video_frames = None
707
- video_height = video_width = None
708
-
709
- env_label = getattr(world.envs.envs[0].spec, "id", "WorldModel Eval")
710
- with tqdm(total=eval_budget, desc=f"Evaluating {env_label}", unit="step") as pbar:
711
- for step_idx in range(eval_budget):
712
- current_frame = world.infos["pixels"][:, -1]
713
- if video_frames is None:
714
- video_height, video_width = map(int, current_frame.shape[-3:-1])
715
- video_frames = np.empty(
716
- (world.num_envs, eval_budget, *current_frame.shape[-3:]),
717
- dtype=np.uint8,
718
- )
719
- target_frames = _resize_hwc_frames(target_frames, video_height, video_width)
720
- video_frames[:, step_idx] = _resize_hwc_frames(current_frame, video_height, video_width)
721
- world.infos.update(deepcopy(goal_step))
722
- world.step()
723
- results["episode_successes"] = np.logical_or(
724
- results["episode_successes"], world.terminateds
725
- )
726
- _set_vector_autoreset_flags(world)
727
- success_count = int(np.sum(results["episode_successes"]))
728
- pbar.set_postfix(success=f"{success_count}/{len(episodes_idx)}")
729
- pbar.update(1)
730
-
731
- if video_frames is None:
732
- current_frame = world.infos["pixels"][:, -1]
733
- video_height, video_width = map(int, current_frame.shape[-3:-1])
734
- video_frames = np.empty(
735
- (world.num_envs, eval_budget, *current_frame.shape[-3:]),
736
- dtype=np.uint8,
737
- )
738
- target_frames = _resize_hwc_frames(target_frames, video_height, video_width)
739
- video_frames[:, -1] = _resize_hwc_frames(world.infos["pixels"][:, -1], video_height, video_width)
740
- n_episodes = len(episodes_idx)
741
- results["success_rate"] = float(np.sum(results["episode_successes"])) / n_episodes * 100.0
742
-
743
- if save_video:
744
- import imageio
745
-
746
- target_len = target_frames.shape[1]
747
- video_path_obj = Path(video_path)
748
- video_path_obj.mkdir(parents=True, exist_ok=True)
749
- for i in tqdm(range(world.num_envs), desc="Writing videos", unit="video"):
750
- out = imageio.get_writer(
751
- video_path_obj / f"rollout_{i}.mp4",
752
- fps=15,
753
- codec="libx264",
754
- )
755
- goals = np.vstack([target_frames[i, -1], target_frames[i, -1]])
756
- for t in range(eval_budget):
757
- stacked_frame = np.vstack([video_frames[i, t], target_frames[i, t % target_len]])
758
- frame = np.hstack([stacked_frame, goals])
759
- out.append_data(frame)
760
- out.close()
761
- print(f"Video saved to {video_path_obj}")
762
-
763
- if results["seeds"] is not None:
764
- assert np.unique(results["seeds"]).shape[0] == n_episodes, "Some episode seeds are identical!"
765
-
766
- return results
767
-
768
- @hydra.main(version_base=None, config_path="./config/eval", config_name="pusht")
769
- def run(cfg: DictConfig):
770
- """Run evaluation of dinowm vs random policy."""
771
- assert (
772
- cfg.plan_config.horizon * cfg.plan_config.action_block <= cfg.eval.eval_budget
773
- ), "Planning horizon must be smaller than or equal to eval_budget"
774
-
775
- runtime_device = resolve_runtime_device(
776
- cfg.solver.get("device", "auto"),
777
- allow_fallback=True,
778
- )
779
- with open_dict(cfg):
780
- cfg.solver.device = runtime_device
781
- cfg.world.env_name = _resolve_world_env_name(str(cfg.world.env_name))
782
-
783
- # create world environment
784
- cfg.world.max_episode_steps = 2 * cfg.eval.eval_budget
785
- world_image_shape = (
786
- int(cfg.world.get("height", cfg.eval.img_size)),
787
- int(cfg.world.get("width", cfg.eval.img_size)),
788
- )
789
- world = swm.World(**cfg.world, image_shape=world_image_shape)
790
-
791
- # create the transform
792
- transform = {
793
- "pixels": img_transform(cfg),
794
- "goal": img_transform(cfg),
795
- }
796
-
797
- dataset = get_dataset(cfg, cfg.eval.dataset_name)
798
- stats_dataset = dataset # get_dataset(cfg, cfg.dataset.stats)
799
- col_name = "episode_idx" if "episode_idx" in dataset.column_names else "ep_idx"
800
- ep_indices, _ = np.unique(stats_dataset.get_col_data(col_name), return_index=True)
801
-
802
- process = {}
803
- process_columns = cfg.dataset.get("keys_to_process", cfg.dataset.keys_to_cache)
804
- for col in process_columns:
805
- if col in ["pixels"]:
806
- continue
807
- processor = preprocessing.StandardScaler()
808
- col_data = stats_dataset.get_col_data(col)
809
- col_data = col_data[~np.isnan(col_data).any(axis=1)]
810
- processor.fit(col_data)
811
- process[col] = processor
812
-
813
- if col != "action":
814
- process[f"goal_{col}"] = process[col]
815
-
816
- # -- run evaluation
817
- policy = cfg.get("policy", "random")
818
-
819
- if policy != "random":
820
- model = load_policy_model(cfg, dataset, runtime_device)
821
- planning_node = cfg.get("planning")
822
- planning_cfg = (
823
- OmegaConf.to_container(planning_node, resolve=True)
824
- if planning_node is not None
825
- else {}
826
- )
827
- if hasattr(model, "set_planning_config"):
828
- model.set_planning_config(planning_cfg)
829
- config = swm.PlanConfig(**cfg.plan_config)
830
- solver = hydra.utils.instantiate(cfg.solver, model=model)
831
- policy = swm.policy.WorldModelPolicy(
832
- solver=solver, config=config, process=process, transform=transform
833
- )
834
-
835
- else:
836
- policy = swm.policy.RandomPolicy()
837
-
838
- results_path = (
839
- Path(swm.data.utils.get_cache_dir(), cfg.policy).parent
840
- if cfg.policy != "random"
841
- else Path(__file__).parent
842
- )
843
-
844
- # sample the episodes and the starting indices
845
- episode_len = get_episodes_length(dataset, ep_indices)
846
- max_start_idx = episode_len - cfg.eval.goal_offset_steps - 1
847
- max_start_idx_dict = {ep_id: max_start_idx[i] for i, ep_id in enumerate(ep_indices)}
848
- # Map each dataset row’s episode_idx to its max_start_idx
849
- col_name = "episode_idx" if "episode_idx" in dataset.column_names else "ep_idx"
850
- safe_row_limit, row_counts = _resolve_safe_row_limit(dataset, [col_name, "step_idx"])
851
- dataset_len = int(len(dataset))
852
- unique_counts = sorted(set(row_counts.values()))
853
- if len(unique_counts) > 1:
854
- print(
855
- f"[eval] warning: inconsistent row counts detected across dataset columns: "
856
- f"{row_counts}. Dataset length is {dataset_len}; row-wise safe limit is {safe_row_limit}.",
857
- flush=True,
858
- )
859
- episode_idx_col = np.asarray(dataset.get_col_data(col_name))
860
- step_idx_col = np.asarray(dataset.get_col_data("step_idx"))
861
- if len(episode_idx_col) != len(step_idx_col):
862
- raise ValueError(
863
- f"Dataset metadata is inconsistent: len({col_name})={len(episode_idx_col)} "
864
- f"but len(step_idx)={len(step_idx_col)}."
865
- )
866
- episode_idx_col = episode_idx_col[:safe_row_limit]
867
- step_idx_col = step_idx_col[:safe_row_limit]
868
- max_start_per_row = np.array([max_start_idx_dict[ep_id] for ep_id in episode_idx_col])
869
-
870
- # remove all the lines of dataset for which dataset['step_idx'] > max_start_per_row
871
- valid_mask = step_idx_col <= max_start_per_row
872
- valid_indices = np.nonzero(valid_mask)[0]
873
- valid_indices = valid_indices[valid_indices < safe_row_limit]
874
- print(valid_mask.sum(), "valid starting points found for evaluation.")
875
-
876
- if len(valid_indices) < cfg.eval.num_eval:
877
- raise ValueError(
878
- f"Not enough valid starting points for evaluation: requested {cfg.eval.num_eval}, "
879
- f"found {len(valid_indices)} after filtering against dataset length {dataset_len}."
880
- )
881
-
882
- g = np.random.default_rng(cfg.seed)
883
- candidate_indices = g.permutation(valid_indices)
884
- random_episode_indices = np.sort(
885
- _select_valid_eval_rows(
886
- dataset,
887
- candidate_indices=candidate_indices,
888
- episode_idx_col=episode_idx_col,
889
- step_idx_col=step_idx_col,
890
- goal_offset_steps=cfg.eval.goal_offset_steps,
891
- num_eval=cfg.eval.num_eval,
892
- )
893
- )
894
-
895
- print(random_episode_indices)
896
-
897
- eval_episodes = episode_idx_col[random_episode_indices]
898
- eval_start_idx = step_idx_col[random_episode_indices]
899
-
900
- if len(eval_episodes) < cfg.eval.num_eval:
901
- raise ValueError("Not enough episodes with sufficient length for evaluation.")
902
-
903
- world.set_policy(policy)
904
-
905
- start_time = time.time()
906
- metrics = evaluate_from_dataset_with_progress(
907
- world,
908
- dataset,
909
- start_steps=eval_start_idx.tolist(),
910
- goal_offset_steps=cfg.eval.goal_offset_steps,
911
- eval_budget=cfg.eval.eval_budget,
912
- episodes_idx=eval_episodes.tolist(),
913
- callables=OmegaConf.to_container(cfg.eval.get("callables"), resolve=True),
914
- save_video=bool(cfg.eval.get("save_video", True)),
915
- video_path=results_path,
916
- )
917
- end_time = time.time()
918
-
919
- print(metrics)
920
-
921
- results_path = results_path / cfg.output.filename
922
- results_path.parent.mkdir(parents=True, exist_ok=True)
923
-
924
- with results_path.open("a") as f:
925
- f.write("\n") # separate from previous runs
926
-
927
- f.write("==== CONFIG ====\n")
928
- f.write(OmegaConf.to_yaml(cfg))
929
- f.write("\n")
930
-
931
- f.write("==== RESULTS ====\n")
932
- f.write(f"metrics: {metrics}\n")
933
- f.write(f"evaluation_time: {end_time - start_time} seconds\n")
934
-
935
-
936
- if __name__ == "__main__":
937
- run()