lzhts1 commited on
Commit
3b57d09
·
verified ·
1 Parent(s): 0c96924

Delete eval_hyperbolic.py

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