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"""
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 _get_unwrapped_envs(world):
569
+ envs = getattr(getattr(world.envs, "unwrapped", world.envs), "envs", None)
570
+ if isinstance(envs, (list, tuple)) and envs:
571
+ return envs
572
+ for envs in _iter_vector_env_lists(world.envs):
573
+ if len(envs) == world.num_envs:
574
+ return envs
575
+ return []
576
+
577
+
578
+ def _set_vector_autoreset_flags(world) -> None:
579
+ for obj in (world.envs, getattr(world.envs, "unwrapped", None)):
580
+ if obj is not None and hasattr(obj, "_autoreset_envs"):
581
+ obj._autoreset_envs = np.zeros((world.num_envs,))
582
+ return
583
+
584
+
585
+ def _resize_hwc_frames(frames: np.ndarray, height: int, width: int) -> np.ndarray:
586
+ if frames.shape[-3:-1] == (height, width):
587
+ return frames.astype(np.uint8, copy=False)
588
+
589
+ import torch.nn.functional as F
590
+
591
+ tensor = torch.as_tensor(frames)
592
+ original_shape = tensor.shape
593
+ tensor = tensor.reshape(-1, *original_shape[-3:]).permute(0, 3, 1, 2).float()
594
+ tensor = F.interpolate(tensor, size=(height, width), mode="bilinear", align_corners=False)
595
+ tensor = tensor.clamp(0, 255).byte().permute(0, 2, 3, 1)
596
+ return tensor.reshape(*original_shape[:-3], height, width, original_shape[-1]).cpu().numpy()
597
+
598
+
599
+ def evaluate_from_dataset_with_progress(
600
+ world,
601
+ dataset: Any,
602
+ episodes_idx: Sequence[int],
603
+ start_steps: Sequence[int],
604
+ goal_offset_steps: int,
605
+ eval_budget: int,
606
+ callables: list[dict] | None = None,
607
+ save_video: bool = True,
608
+ video_path: str | Path = "./",
609
+ ):
610
+ """Copy of stable_worldmodel's dataset evaluation with tqdm progress bars."""
611
+ assert (
612
+ world.envs.envs[0].spec.max_episode_steps is None
613
+ or world.envs.envs[0].spec.max_episode_steps >= goal_offset_steps
614
+ ), "env max_episode_steps must be greater than eval_budget"
615
+
616
+ ep_idx_arr = np.array(episodes_idx)
617
+ start_steps_arr = np.array(start_steps)
618
+ end_steps = start_steps_arr + goal_offset_steps
619
+
620
+ if len(ep_idx_arr) != len(start_steps_arr):
621
+ raise ValueError("episodes_idx and start_steps must have the same length")
622
+ if len(ep_idx_arr) != world.num_envs:
623
+ raise ValueError("Number of episodes to evaluate must match number of envs")
624
+
625
+ data = dataset.load_chunk(ep_idx_arr, start_steps_arr, end_steps)
626
+ columns = dataset.column_names
627
+
628
+ init_step_per_env: dict[str, list[Any]] = defaultdict(list)
629
+ goal_step_per_env: dict[str, list[Any]] = defaultdict(list)
630
+ for ep in data:
631
+ for col in columns:
632
+ if col.startswith("goal"):
633
+ continue
634
+ if col.startswith("pixels"):
635
+ ep[col] = ep[col].permute(0, 2, 3, 1)
636
+ if not isinstance(ep[col], (torch.Tensor, np.ndarray)):
637
+ continue
638
+
639
+ init_data = ep[col][0]
640
+ goal_data = ep[col][-1]
641
+ if not isinstance(init_data, (np.ndarray, torch.Tensor)):
642
+ continue
643
+
644
+ init_data = init_data.numpy() if isinstance(init_data, torch.Tensor) else init_data
645
+ goal_data = goal_data.numpy() if isinstance(goal_data, torch.Tensor) else goal_data
646
+ init_step_per_env[col].append(init_data)
647
+ goal_step_per_env[col].append(goal_data)
648
+
649
+ init_step = {k: np.stack(v) for k, v in deepcopy(init_step_per_env).items()}
650
+ goal_step = {}
651
+ for key, value in goal_step_per_env.items():
652
+ goal_key = "goal" if key == "pixels" else f"goal_{key}"
653
+ goal_step[goal_key] = np.stack(value)
654
+
655
+ seeds = init_step.get("seed")
656
+ vkey = "variation."
657
+ variations_dict = {
658
+ k.removeprefix(vkey): v for k, v in init_step.items() if k.startswith(vkey)
659
+ }
660
+ options = [{} for _ in range(world.num_envs)]
661
+ if variations_dict:
662
+ for i in range(world.num_envs):
663
+ options[i]["variation"] = list(variations_dict.keys())
664
+ options[i]["variation_values"] = {k: v[i] for k, v in variations_dict.items()}
665
+
666
+ init_step.update(deepcopy(goal_step))
667
+ world.reset(seed=seeds, options=options)
668
+
669
+ callables = callables or []
670
+ for i, env in enumerate(_get_unwrapped_envs(world)):
671
+ env_unwrapped = env.unwrapped
672
+ for spec in callables:
673
+ method_name = spec["method"]
674
+ if not hasattr(env_unwrapped, method_name):
675
+ continue
676
+ method = getattr(env_unwrapped, method_name)
677
+ args = spec.get("args", spec)
678
+
679
+ prepared_args = {}
680
+ for args_name, args_data in args.items():
681
+ value = args_data.get("value", None)
682
+ is_in_dataset = args_data.get("in_dataset", True)
683
+ if is_in_dataset:
684
+ if value not in init_step:
685
+ continue
686
+ prepared_args[args_name] = deepcopy(init_step[value][i])
687
+ else:
688
+ prepared_args[args_name] = value
689
+
690
+ method(**prepared_args)
691
+
692
+ for i, env in enumerate(_get_unwrapped_envs(world)):
693
+ env_unwrapped = env.unwrapped
694
+ if "goal_state" in init_step and "goal_state" in goal_step:
695
+ assert np.array_equal(
696
+ init_step["goal_state"][i], goal_step["goal_state"][i]
697
+ ), f"Goal state info does not match at reset for env {env_unwrapped}"
698
+
699
+ results: dict = {
700
+ "success_rate": 0.0,
701
+ "episode_successes": np.zeros(len(episodes_idx)),
702
+ "seeds": seeds,
703
+ }
704
+
705
+ shape_prefix = world.infos["pixels"].shape[:2]
706
+ init_step = {
707
+ k: np.broadcast_to(v[:, None, ...], shape_prefix + v.shape[1:]) for k, v in init_step.items()
708
+ }
709
+ goal_step = {
710
+ k: np.broadcast_to(v[:, None, ...], shape_prefix + v.shape[1:]) for k, v in goal_step.items()
711
+ }
712
+ _inject_static_goal_info_into_envs(world, goal_step)
713
+
714
+ world.infos.update(deepcopy(init_step))
715
+ world.infos.update(deepcopy(goal_step))
716
+
717
+ if "goal" in goal_step and "goal" in world.infos:
718
+ assert np.allclose(world.infos["goal"], goal_step["goal"]), "Goal info does not match"
719
+
720
+ target_frames = torch.stack([ep["pixels"] for ep in data]).numpy()
721
+ video_frames = None
722
+ video_height = video_width = None
723
+
724
+ env_label = getattr(world.envs.envs[0].spec, "id", "WorldModel Eval")
725
+ with tqdm(total=eval_budget, desc=f"Evaluating {env_label}", unit="step") as pbar:
726
+ for step_idx in range(eval_budget):
727
+ current_frame = world.infos["pixels"][:, -1]
728
+ if video_frames is None:
729
+ video_height, video_width = map(int, current_frame.shape[-3:-1])
730
+ video_frames = np.empty(
731
+ (world.num_envs, eval_budget, *current_frame.shape[-3:]),
732
+ dtype=np.uint8,
733
+ )
734
+ target_frames = _resize_hwc_frames(target_frames, video_height, video_width)
735
+ video_frames[:, step_idx] = _resize_hwc_frames(current_frame, video_height, video_width)
736
+ world.infos.update(deepcopy(goal_step))
737
+ world.step()
738
+ results["episode_successes"] = np.logical_or(
739
+ results["episode_successes"], world.terminateds
740
+ )
741
+ _set_vector_autoreset_flags(world)
742
+ success_count = int(np.sum(results["episode_successes"]))
743
+ pbar.set_postfix(success=f"{success_count}/{len(episodes_idx)}")
744
+ pbar.update(1)
745
+
746
+ if video_frames is None:
747
+ current_frame = world.infos["pixels"][:, -1]
748
+ video_height, video_width = map(int, current_frame.shape[-3:-1])
749
+ video_frames = np.empty(
750
+ (world.num_envs, eval_budget, *current_frame.shape[-3:]),
751
+ dtype=np.uint8,
752
+ )
753
+ target_frames = _resize_hwc_frames(target_frames, video_height, video_width)
754
+ video_frames[:, -1] = _resize_hwc_frames(world.infos["pixels"][:, -1], video_height, video_width)
755
+ n_episodes = len(episodes_idx)
756
+ results["success_rate"] = float(np.sum(results["episode_successes"])) / n_episodes * 100.0
757
+
758
+ if save_video:
759
+ import imageio
760
+
761
+ target_len = target_frames.shape[1]
762
+ video_path_obj = Path(video_path)
763
+ video_path_obj.mkdir(parents=True, exist_ok=True)
764
+ for i in tqdm(range(world.num_envs), desc="Writing videos", unit="video"):
765
+ out = imageio.get_writer(
766
+ video_path_obj / f"rollout_{i}.mp4",
767
+ fps=15,
768
+ codec="libx264",
769
+ )
770
+ goals = np.vstack([target_frames[i, -1], target_frames[i, -1]])
771
+ for t in range(eval_budget):
772
+ stacked_frame = np.vstack([video_frames[i, t], target_frames[i, t % target_len]])
773
+ frame = np.hstack([stacked_frame, goals])
774
+ out.append_data(frame)
775
+ out.close()
776
+ print(f"Video saved to {video_path_obj}")
777
+
778
+ if results["seeds"] is not None:
779
+ assert np.unique(results["seeds"]).shape[0] == n_episodes, "Some episode seeds are identical!"
780
+
781
+ return results
782
+
783
+ @hydra.main(version_base=None, config_path="./config/eval", config_name="hyperbolic")
784
+ def run(cfg: DictConfig):
785
+ """Run evaluation of dinowm vs random policy."""
786
+ assert (
787
+ cfg.plan_config.horizon * cfg.plan_config.action_block <= cfg.eval.eval_budget
788
+ ), "Planning horizon must be smaller than or equal to eval_budget"
789
+ print(f"[eval] mujoco backend: {MUJOCO_GL_BACKEND}", flush=True)
790
+
791
+ runtime_device = resolve_runtime_device(
792
+ cfg.solver.get("device", "auto"),
793
+ allow_fallback=True,
794
+ )
795
+ with open_dict(cfg):
796
+ cfg.solver.device = runtime_device
797
+ cfg.world.env_name = _resolve_world_env_name(str(cfg.world.env_name))
798
+
799
+ # create world environment
800
+ cfg.world.max_episode_steps = 2 * cfg.eval.eval_budget
801
+ world = swm.World(**cfg.world, image_shape=(224, 224))
802
+
803
+ # create the transform
804
+ transform = {
805
+ "pixels": img_transform(cfg),
806
+ "goal": img_transform(cfg),
807
+ }
808
+
809
+ dataset = get_dataset(cfg, cfg.eval.dataset_name)
810
+ stats_dataset = dataset # get_dataset(cfg, cfg.dataset.stats)
811
+ col_name = "episode_idx" if "episode_idx" in dataset.column_names else "ep_idx"
812
+ ep_indices, _ = np.unique(stats_dataset.get_col_data(col_name), return_index=True)
813
+
814
+ process = {}
815
+ for col in cfg.dataset.keys_to_cache:
816
+ if col in ["pixels"]:
817
+ continue
818
+ processor = preprocessing.StandardScaler()
819
+ col_data = stats_dataset.get_col_data(col)
820
+ col_data = col_data[~np.isnan(col_data).any(axis=1)]
821
+ processor.fit(col_data)
822
+ process[col] = processor
823
+
824
+ if col != "action":
825
+ process[f"goal_{col}"] = process[col]
826
+
827
+ # -- run evaluation
828
+ policy = cfg.get("policy", "random")
829
+
830
+ if policy != "random":
831
+ model = load_policy_model(cfg, dataset, runtime_device)
832
+ planning_node = cfg.get("planning")
833
+ planning_cfg = (
834
+ OmegaConf.to_container(planning_node, resolve=True)
835
+ if planning_node is not None
836
+ else {}
837
+ )
838
+ if hasattr(model, "set_planning_config"):
839
+ model.set_planning_config(planning_cfg)
840
+ if isinstance(model, HyperbolicJEPA):
841
+ resolved_cfg = (
842
+ model._planning_hyperbolic_config()
843
+ if hasattr(model, "_planning_hyperbolic_config")
844
+ else planning_cfg.get("hyperbolic", "<defaults>")
845
+ )
846
+ print(
847
+ f"[eval] hyperbolic planning config: {resolved_cfg}",
848
+ flush=True,
849
+ )
850
+ config = swm.PlanConfig(**cfg.plan_config)
851
+ solver = hydra.utils.instantiate(cfg.solver, model=model)
852
+ policy = swm.policy.WorldModelPolicy(
853
+ solver=solver, config=config, process=process, transform=transform
854
+ )
855
+
856
+ else:
857
+ policy = swm.policy.RandomPolicy()
858
+
859
+ results_path = (
860
+ Path(swm.data.utils.get_cache_dir(), cfg.policy).parent
861
+ if cfg.policy != "random"
862
+ else Path(__file__).parent
863
+ )
864
+
865
+ # sample the episodes and the starting indices
866
+ episode_len = get_episodes_length(dataset, ep_indices)
867
+ max_start_idx = episode_len - cfg.eval.goal_offset_steps - 1
868
+ max_start_idx_dict = {ep_id: max_start_idx[i] for i, ep_id in enumerate(ep_indices)}
869
+ # Map each dataset row’s episode_idx to its max_start_idx
870
+ col_name = "episode_idx" if "episode_idx" in dataset.column_names else "ep_idx"
871
+ safe_row_limit, row_counts = _resolve_safe_row_limit(dataset, [col_name, "step_idx"])
872
+ dataset_len = int(len(dataset))
873
+ unique_counts = sorted(set(row_counts.values()))
874
+ if len(unique_counts) > 1:
875
+ print(
876
+ f"[eval] warning: inconsistent row counts detected across dataset columns: "
877
+ f"{row_counts}. Dataset length is {dataset_len}; row-wise safe limit is {safe_row_limit}.",
878
+ flush=True,
879
+ )
880
+ episode_idx_col = np.asarray(dataset.get_col_data(col_name))
881
+ step_idx_col = np.asarray(dataset.get_col_data("step_idx"))
882
+ if len(episode_idx_col) != len(step_idx_col):
883
+ raise ValueError(
884
+ f"Dataset metadata is inconsistent: len({col_name})={len(episode_idx_col)} "
885
+ f"but len(step_idx)={len(step_idx_col)}."
886
+ )
887
+ episode_idx_col = episode_idx_col[:safe_row_limit]
888
+ step_idx_col = step_idx_col[:safe_row_limit]
889
+ max_start_per_row = np.array([max_start_idx_dict[ep_id] for ep_id in episode_idx_col])
890
+
891
+ # remove all the lines of dataset for which dataset['step_idx'] > max_start_per_row
892
+ valid_mask = step_idx_col <= max_start_per_row
893
+ valid_indices = np.nonzero(valid_mask)[0]
894
+ valid_indices = valid_indices[valid_indices < safe_row_limit]
895
+ print(valid_mask.sum(), "valid starting points found for evaluation.")
896
+
897
+ if len(valid_indices) < cfg.eval.num_eval:
898
+ raise ValueError(
899
+ f"Not enough valid starting points for evaluation: requested {cfg.eval.num_eval}, "
900
+ f"found {len(valid_indices)} after filtering against dataset length {dataset_len}."
901
+ )
902
+
903
+ g = np.random.default_rng(cfg.seed)
904
+ candidate_indices = g.permutation(valid_indices)
905
+ random_episode_indices = np.sort(
906
+ _select_valid_eval_rows(
907
+ dataset,
908
+ candidate_indices=candidate_indices,
909
+ episode_idx_col=episode_idx_col,
910
+ step_idx_col=step_idx_col,
911
+ goal_offset_steps=cfg.eval.goal_offset_steps,
912
+ num_eval=cfg.eval.num_eval,
913
+ )
914
+ )
915
+
916
+ print(random_episode_indices)
917
+
918
+ eval_episodes = episode_idx_col[random_episode_indices]
919
+ eval_start_idx = step_idx_col[random_episode_indices]
920
+
921
+ if len(eval_episodes) < cfg.eval.num_eval:
922
+ raise ValueError("Not enough episodes with sufficient length for evaluation.")
923
+
924
+ world.set_policy(policy)
925
+
926
+ start_time = time.time()
927
+ metrics = evaluate_from_dataset_with_progress(
928
+ world,
929
+ dataset,
930
+ start_steps=eval_start_idx.tolist(),
931
+ goal_offset_steps=cfg.eval.goal_offset_steps,
932
+ eval_budget=cfg.eval.eval_budget,
933
+ episodes_idx=eval_episodes.tolist(),
934
+ callables=OmegaConf.to_container(cfg.eval.get("callables"), resolve=True),
935
+ save_video=bool(cfg.eval.get("save_video", True)),
936
+ video_path=results_path,
937
+ )
938
+ end_time = time.time()
939
+
940
+ print(metrics)
941
+
942
+ results_path = results_path / cfg.output.filename
943
+ results_path.parent.mkdir(parents=True, exist_ok=True)
944
+
945
+ with results_path.open("a") as f:
946
+ f.write("\n") # separate from previous runs
947
+
948
+ f.write("==== CONFIG ====\n")
949
+ f.write(OmegaConf.to_yaml(cfg))
950
+ f.write("\n")
951
+
952
+ f.write("==== RESULTS ====\n")
953
+ f.write(f"metrics: {metrics}\n")
954
+ f.write(f"evaluation_time: {end_time - start_time} seconds\n")
955
+
956
+
957
+ if __name__ == "__main__":
958
+ run()