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

Upload 2 files

Browse files
Files changed (2) hide show
  1. probe_hyperbolic_mse.py +558 -0
  2. probe_lewm_mse.py +531 -0
probe_hyperbolic_mse.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Offline physical probing for HyperbolicJEPA checkpoints.
4
+
5
+ The world model is frozen. A linear/MLP probe is trained on top of one selected
6
+ representation and evaluated with raw MSE plus normalized MSE.
7
+
8
+ Example:
9
+ python probe_hyperbolic_mse.py \
10
+ --policy /data_nvme/user/zliu681/le-wm-main/lewm_cache/ogbench/Experiment/hyperbolic_exp_antmaze/lewm_hyperbolic_epoch_100 \
11
+ --dataset-name ogbench_antmaze_visual_h5/visual-antmaze-large-navigate-v0 \
12
+ --target-keys observation \
13
+ --representation tangent \
14
+ --device auto \
15
+ --num-samples 50000 \
16
+ --epochs 20
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ from pathlib import Path
24
+
25
+ import h5py
26
+ import numpy as np
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from omegaconf import OmegaConf
30
+ from torch import nn
31
+ from torch.utils.data import DataLoader
32
+
33
+ from module import ARPredictor, Embedder, MLP, SIGReg
34
+ from probe_lewm_mse import (
35
+ H5RowProbeDataset,
36
+ cache_dir_from_args,
37
+ collate_rows,
38
+ load_targets_for_stats,
39
+ make_probe,
40
+ progress_iter,
41
+ preprocess_pixels,
42
+ resolve_h5_path,
43
+ )
44
+ from train_hyperbolic import (
45
+ AdaptiveEntailmentConeLoss,
46
+ HyperbolicJEPA,
47
+ LorentzContrastiveLoss,
48
+ LorentzManifold,
49
+ build_hyperbolic_world_model,
50
+ ensure_hyperbolic_defaults,
51
+ )
52
+ from utils import resolve_runtime_device
53
+
54
+
55
+ def parse_args():
56
+ parser = argparse.ArgumentParser(description="Train a frozen HyperbolicJEPA physical probe.")
57
+ parser.add_argument("--policy", type=str, required=True, help="Checkpoint prefix, checkpoint file, or run dir.")
58
+ parser.add_argument("--dataset-name", type=str, required=True, help="H5 dataset name under STABLEWM_HOME, or full .h5 path.")
59
+ parser.add_argument(
60
+ "--target-keys",
61
+ type=str,
62
+ default="observation",
63
+ help="Comma-separated H5 columns to predict, e.g. observation or qpos,qvel.",
64
+ )
65
+ parser.add_argument(
66
+ "--representation",
67
+ type=str,
68
+ default="tangent",
69
+ choices=("tangent", "lorentz", "euclidean"),
70
+ help="Probe input: tangent=hyp_tangent, lorentz=hyp_emb, euclidean=pre-hyperbolic emb.",
71
+ )
72
+ parser.add_argument("--cache-dir", type=str, default="", help="Overrides stable_worldmodel cache dir lookup.")
73
+ parser.add_argument("--device", type=str, default="auto")
74
+ parser.add_argument("--img-size", type=int, default=224)
75
+ parser.add_argument("--num-samples", type=int, default=50000)
76
+ parser.add_argument("--batch-size", type=int, default=256)
77
+ parser.add_argument("--epochs", type=int, default=20)
78
+ parser.add_argument("--lr", type=float, default=1e-3)
79
+ parser.add_argument("--weight-decay", type=float, default=1e-4)
80
+ parser.add_argument("--hidden-dim", type=int, default=512, help="0 means linear probe.")
81
+ parser.add_argument("--num-layers", type=int, default=2, help="Number of hidden layers when hidden_dim > 0.")
82
+ parser.add_argument("--train-frac", type=float, default=0.8)
83
+ parser.add_argument("--val-frac", type=float, default=0.1)
84
+ parser.add_argument("--seed", type=int, default=3072)
85
+ parser.add_argument("--num-workers", type=int, default=0)
86
+ parser.add_argument("--strict", action=argparse.BooleanOptionalAction, default=True)
87
+ parser.add_argument("--output", type=str, default="", help="Optional JSON metrics path.")
88
+ return parser.parse_args()
89
+
90
+
91
+ def register_hyperbolic_checkpoint_aliases():
92
+ import __main__ as main_mod
93
+
94
+ objects = (
95
+ HyperbolicJEPA,
96
+ LorentzManifold,
97
+ LorentzContrastiveLoss,
98
+ AdaptiveEntailmentConeLoss,
99
+ ARPredictor,
100
+ Embedder,
101
+ MLP,
102
+ SIGReg,
103
+ )
104
+ for obj in objects:
105
+ setattr(main_mod, obj.__name__, obj)
106
+
107
+ if hasattr(torch.serialization, "add_safe_globals"):
108
+ torch.serialization.add_safe_globals(list(objects))
109
+
110
+
111
+ def _add_prefix_candidates(candidates: list[Path], prefix: Path) -> None:
112
+ text = str(prefix)
113
+ for suffix in ("_state.ckpt", "_object.ckpt", "_weights.ckpt"):
114
+ if text.endswith(suffix):
115
+ _add_prefix_candidates(candidates, Path(text[: -len(suffix)]))
116
+ return
117
+ if text.endswith(".ckpt"):
118
+ candidates.append(prefix)
119
+ return
120
+
121
+ candidates.append(Path(f"{text}_state.ckpt"))
122
+ candidates.append(Path(f"{text}_object.ckpt"))
123
+ candidates.append(Path(f"{text}_weights.ckpt"))
124
+
125
+
126
+ def policy_artifact_candidates(policy_name: str, cache_dir: Path) -> list[tuple[Path, Path]]:
127
+ raw = Path(policy_name)
128
+ candidates: list[Path] = []
129
+
130
+ _add_prefix_candidates(candidates, raw)
131
+ _add_prefix_candidates(candidates, cache_dir / raw)
132
+
133
+ for item in (raw, cache_dir / raw):
134
+ if item.is_file():
135
+ candidates.append(item)
136
+ if item.is_dir():
137
+ candidates.extend(sorted(item.glob("*_state.ckpt")))
138
+ candidates.extend(sorted(item.glob("*_object.ckpt")))
139
+ weights = sorted(item.glob("*_weights.ckpt"))
140
+ if len(weights) == 1:
141
+ candidates.append(weights[0])
142
+ parent = item.parent
143
+ if parent.is_dir():
144
+ weights = sorted(parent.glob("*_weights.ckpt"))
145
+ if len(weights) == 1:
146
+ candidates.append(weights[0])
147
+
148
+ seen = set()
149
+ resolved: list[tuple[Path, Path]] = []
150
+ for candidate in candidates:
151
+ candidate = Path(candidate)
152
+ if candidate in seen or not candidate.is_file():
153
+ continue
154
+ seen.add(candidate)
155
+ config_path = candidate.parent / "config.yaml"
156
+ if config_path.is_file():
157
+ resolved.append((candidate, config_path))
158
+
159
+ if resolved:
160
+ return resolved
161
+
162
+ raise FileNotFoundError(
163
+ f"Could not resolve checkpoint/config for policy '{policy_name}' under cache '{cache_dir}'."
164
+ )
165
+
166
+
167
+ def infer_action_dim(h5_path: Path, train_cfg) -> int:
168
+ cfg_value = getattr(train_cfg.wm, "action_dim", None)
169
+ if cfg_value is not None:
170
+ return int(cfg_value)
171
+
172
+ with h5py.File(h5_path, "r") as h5:
173
+ if "action" not in h5:
174
+ raise KeyError(f"Cannot infer action_dim because '{h5_path}' has no action column.")
175
+ shape = h5["action"].shape
176
+ if len(shape) <= 1:
177
+ return 1
178
+ return int(np.prod(shape[1:], dtype=np.int64))
179
+
180
+
181
+ def _state_dict_from_checkpoint(checkpoint, checkpoint_path: Path):
182
+ if isinstance(checkpoint, dict) and "state_dict" in checkpoint:
183
+ state_dict = checkpoint["state_dict"]
184
+ elif isinstance(checkpoint, dict):
185
+ state_dict = checkpoint
186
+ else:
187
+ raise TypeError(
188
+ f"Unsupported checkpoint type '{type(checkpoint).__name__}' for '{checkpoint_path}'."
189
+ )
190
+
191
+ if any(key.startswith("model.") for key in state_dict.keys()):
192
+ state_dict = {
193
+ key[len("model."):]: value
194
+ for key, value in state_dict.items()
195
+ if key.startswith("model.")
196
+ }
197
+ return state_dict
198
+
199
+
200
+ def load_hyperbolic_model(args, h5_path: Path, cache_dir: Path, device: str) -> nn.Module:
201
+ register_hyperbolic_checkpoint_aliases()
202
+ failures = []
203
+
204
+ for checkpoint_path, config_path in policy_artifact_candidates(args.policy, cache_dir):
205
+ print(f"[probe] trying checkpoint={checkpoint_path} config={config_path}", flush=True)
206
+ train_cfg = OmegaConf.load(config_path)
207
+ ensure_hyperbolic_defaults(train_cfg)
208
+ action_dim = infer_action_dim(h5_path, train_cfg)
209
+ model = build_hyperbolic_world_model(train_cfg, action_dim=action_dim)
210
+
211
+ try:
212
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
213
+ if isinstance(checkpoint, nn.Module):
214
+ model = checkpoint
215
+ else:
216
+ state_dict = _state_dict_from_checkpoint(checkpoint, checkpoint_path)
217
+ missing, unexpected = model.load_state_dict(state_dict, strict=bool(args.strict))
218
+ print(
219
+ f"[probe] loaded state checkpoint strict={bool(args.strict)} "
220
+ f"missing={len(missing)} unexpected={len(unexpected)}",
221
+ flush=True,
222
+ )
223
+ if missing:
224
+ print(f"[probe] missing keys: {missing}", flush=True)
225
+ if unexpected:
226
+ print(f"[probe] unexpected keys: {unexpected}", flush=True)
227
+ except ModuleNotFoundError as exc:
228
+ if exc.name == "torch_npu" or str(exc.name).startswith("torch_npu."):
229
+ failures.append(f"{checkpoint_path}: requires torch_npu during object deserialization")
230
+ print(
231
+ f"[probe] checkpoint {checkpoint_path} requires torch_npu; trying next candidate.",
232
+ flush=True,
233
+ )
234
+ continue
235
+ raise
236
+ except Exception as exc:
237
+ failures.append(f"{checkpoint_path}: {type(exc).__name__}: {exc}")
238
+ print(f"[probe] failed checkpoint {checkpoint_path}: {exc}", flush=True)
239
+ continue
240
+
241
+ if not hasattr(model, "encode") and hasattr(model, "model"):
242
+ model = model.model
243
+ if not hasattr(model, "encode"):
244
+ raise TypeError(f"Loaded model does not expose encode(info): {type(model).__name__}")
245
+ model = model.to(device).eval()
246
+ model.requires_grad_(False)
247
+ model.interpolate_pos_encoding = True
248
+ return model
249
+
250
+ failure_details = "\n".join(f" - {failure}" for failure in failures)
251
+ raise RuntimeError(f"Failed to load hyperbolic model. Tried:\n{failure_details}")
252
+
253
+
254
+ @torch.no_grad()
255
+ def encode_batch(
256
+ model: nn.Module,
257
+ pixels: torch.Tensor,
258
+ img_size: int,
259
+ device: str,
260
+ representation: str,
261
+ ) -> torch.Tensor:
262
+ pixels = preprocess_pixels(pixels, img_size=img_size, device=device)
263
+ output = model.encode({"pixels": pixels.unsqueeze(1)})
264
+ if representation == "tangent":
265
+ key = "hyp_tangent"
266
+ elif representation == "lorentz":
267
+ key = "hyp_emb"
268
+ elif representation == "euclidean":
269
+ key = "emb"
270
+ else:
271
+ raise ValueError(f"Unknown representation: {representation}")
272
+ return output[key][:, -1].detach().float()
273
+
274
+
275
+ def evaluate_probe(model, probe, loader, mean, std, args, device: str) -> dict[str, float]:
276
+ sq_error_sum = None
277
+ norm_sq_error_sum = None
278
+ pred_sum = None
279
+ target_sum = None
280
+ pred_sq_sum = None
281
+ target_sq_sum = None
282
+ pred_target_sum = None
283
+ sample_count = 0
284
+ with torch.no_grad():
285
+ for pixels, target in loader:
286
+ target = target.to(device, non_blocking=True)
287
+ target = torch.nan_to_num(target, nan=0.0, posinf=0.0, neginf=0.0)
288
+ emb = encode_batch(model, pixels, args.img_size, device, args.representation)
289
+ pred_norm = probe(emb)
290
+ target_norm = (target - mean) / std
291
+ pred = pred_norm * std + mean
292
+
293
+ sq_error = (pred - target).pow(2).sum(dim=0).detach()
294
+ norm_sq_error = (pred_norm - target_norm).pow(2).sum(dim=0).detach()
295
+ pred_batch_sum = pred.sum(dim=0).detach()
296
+ target_batch_sum = target.sum(dim=0).detach()
297
+ pred_batch_sq_sum = pred.pow(2).sum(dim=0).detach()
298
+ target_batch_sq_sum = target.pow(2).sum(dim=0).detach()
299
+ pred_target_batch_sum = (pred * target).sum(dim=0).detach()
300
+
301
+ if sq_error_sum is None:
302
+ sq_error_sum = torch.zeros_like(sq_error)
303
+ norm_sq_error_sum = torch.zeros_like(norm_sq_error)
304
+ pred_sum = torch.zeros_like(pred_batch_sum)
305
+ target_sum = torch.zeros_like(target_batch_sum)
306
+ pred_sq_sum = torch.zeros_like(pred_batch_sq_sum)
307
+ target_sq_sum = torch.zeros_like(target_batch_sq_sum)
308
+ pred_target_sum = torch.zeros_like(pred_target_batch_sum)
309
+
310
+ sq_error_sum += sq_error
311
+ norm_sq_error_sum += norm_sq_error
312
+ pred_sum += pred_batch_sum
313
+ target_sum += target_batch_sum
314
+ pred_sq_sum += pred_batch_sq_sum
315
+ target_sq_sum += target_batch_sq_sum
316
+ pred_target_sum += pred_target_batch_sum
317
+ sample_count += int(target.size(0))
318
+
319
+ sample_count = max(1, sample_count)
320
+ mse_per_dim = sq_error_sum / sample_count
321
+ norm_mse_per_dim = norm_sq_error_sum / sample_count
322
+
323
+ cov = pred_target_sum - pred_sum * target_sum / sample_count
324
+ pred_var = pred_sq_sum - pred_sum.pow(2) / sample_count
325
+ target_var = target_sq_sum - target_sum.pow(2) / sample_count
326
+ denom = pred_var.clamp_min(0).sqrt() * target_var.clamp_min(0).sqrt()
327
+ valid = denom > 1e-12
328
+ if bool(valid.any().item()):
329
+ pearson_per_dim = cov[valid] / denom[valid]
330
+ pearson_r = pearson_per_dim.mean()
331
+ pearson_r_std = pearson_per_dim.std(unbiased=False)
332
+ else:
333
+ pearson_r = torch.tensor(0.0, device=device)
334
+ pearson_r_std = torch.tensor(0.0, device=device)
335
+
336
+ return {
337
+ "mse": float(mse_per_dim.mean().item()),
338
+ "mse_std": float(mse_per_dim.std(unbiased=False).item()),
339
+ "normalized_mse": float(norm_mse_per_dim.mean().item()),
340
+ "normalized_mse_std": float(norm_mse_per_dim.std(unbiased=False).item()),
341
+ "pearson_r": float(pearson_r.item()),
342
+ "pearson_r_std": float(pearson_r_std.item()),
343
+ }
344
+
345
+
346
+ def train_one_probe(
347
+ *,
348
+ probe_name: str,
349
+ hidden_dim: int,
350
+ num_layers: int,
351
+ model,
352
+ train_loader,
353
+ val_loader,
354
+ test_loader,
355
+ target_dim: int,
356
+ mean,
357
+ std,
358
+ args,
359
+ device: str,
360
+ ) -> dict:
361
+ first_pixels, _ = next(iter(train_loader))
362
+ first_emb = encode_batch(model, first_pixels, args.img_size, device, args.representation)
363
+ probe = make_probe(
364
+ input_dim=int(first_emb.shape[-1]),
365
+ output_dim=target_dim,
366
+ hidden_dim=hidden_dim,
367
+ num_layers=num_layers,
368
+ ).to(device)
369
+ optimizer = torch.optim.AdamW(probe.parameters(), lr=args.lr, weight_decay=args.weight_decay)
370
+
371
+ best_state = None
372
+ best_val = float("inf")
373
+ for epoch in range(1, args.epochs + 1):
374
+ probe.train()
375
+ train_loss = 0.0
376
+ train_count = 0
377
+ batch_iter = progress_iter(
378
+ train_loader,
379
+ desc=f"probe:{probe_name}:epoch{epoch:03d}",
380
+ total=len(train_loader),
381
+ leave=False,
382
+ )
383
+ for pixels, target in batch_iter:
384
+ target = target.to(device, non_blocking=True)
385
+ target = torch.nan_to_num(target, nan=0.0, posinf=0.0, neginf=0.0)
386
+ with torch.no_grad():
387
+ emb = encode_batch(model, pixels, args.img_size, device, args.representation)
388
+ pred = probe(emb)
389
+ target_norm = (target - mean) / std
390
+ loss = F.mse_loss(pred, target_norm)
391
+
392
+ optimizer.zero_grad(set_to_none=True)
393
+ loss.backward()
394
+ optimizer.step()
395
+
396
+ train_loss += loss.item() * target.numel()
397
+ train_count += target.numel()
398
+ if hasattr(batch_iter, "set_postfix"):
399
+ batch_iter.set_postfix(norm_mse=f"{train_loss / max(1, train_count):.4f}")
400
+
401
+ probe.eval()
402
+ val_metrics = evaluate_probe(model, probe, val_loader, mean, std, args, device)
403
+ train_norm_mse = train_loss / max(1, train_count)
404
+ print(
405
+ f"[probe:{probe_name}] epoch={epoch:03d} train_norm_mse={train_norm_mse:.6f} "
406
+ f"val_mse={val_metrics['mse']:.6f} val_r={val_metrics['pearson_r']:.6f}",
407
+ flush=True,
408
+ )
409
+ if val_metrics["normalized_mse"] < best_val:
410
+ best_val = val_metrics["normalized_mse"]
411
+ best_state = {key: value.detach().cpu() for key, value in probe.state_dict().items()}
412
+
413
+ if best_state is not None:
414
+ probe.load_state_dict(best_state)
415
+ probe.eval()
416
+ return {
417
+ "hidden_dim": int(hidden_dim),
418
+ "num_layers": int(num_layers),
419
+ "val": evaluate_probe(model, probe, val_loader, mean, std, args, device),
420
+ "test": evaluate_probe(model, probe, test_loader, mean, std, args, device),
421
+ }
422
+
423
+
424
+ def main():
425
+ args = parse_args()
426
+ cache_dir = cache_dir_from_args(args)
427
+ h5_path = resolve_h5_path(args.dataset_name, cache_dir)
428
+ target_keys = [key.strip() for key in args.target_keys.split(",") if key.strip()]
429
+
430
+ with h5py.File(h5_path, "r") as h5:
431
+ missing = [key for key in ["pixels", *target_keys] if key not in h5]
432
+ if missing:
433
+ raise KeyError(f"{h5_path} missing required keys: {missing}. Available: {list(h5.keys())}")
434
+ row_count = min(int(h5["pixels"].shape[0]), *(int(h5[key].shape[0]) for key in target_keys))
435
+
436
+ rng = np.random.default_rng(args.seed)
437
+ sample_count = min(int(args.num_samples), row_count)
438
+ indices = rng.choice(row_count, size=sample_count, replace=False)
439
+ rng.shuffle(indices)
440
+
441
+ n_train = int(sample_count * args.train_frac)
442
+ n_val = int(sample_count * args.val_frac)
443
+ n_train = max(1, min(n_train, sample_count))
444
+ n_val = max(1, min(n_val, sample_count - n_train))
445
+ train_idx = np.sort(indices[:n_train])
446
+ val_idx = np.sort(indices[n_train : n_train + n_val])
447
+ test_idx = np.sort(indices[n_train + n_val :])
448
+ if len(test_idx) == 0:
449
+ test_idx = val_idx
450
+
451
+ train_targets = load_targets_for_stats(h5_path, train_idx, target_keys)
452
+ target_mean_np = np.nanmean(train_targets, axis=0, keepdims=True).astype(np.float32)
453
+ target_std_np = np.nanstd(train_targets, axis=0, keepdims=True).astype(np.float32)
454
+ target_std_np = np.maximum(target_std_np, 1e-6)
455
+ target_dim = int(train_targets.shape[1])
456
+
457
+ device = resolve_runtime_device(args.device, allow_fallback=True)
458
+ print(
459
+ f"[probe] dataset={h5_path} rows={row_count} sampled={sample_count} "
460
+ f"train={len(train_idx)} val={len(val_idx)} test={len(test_idx)} target_dim={target_dim}",
461
+ flush=True,
462
+ )
463
+ print(
464
+ f"[probe] target_keys={target_keys} representation={args.representation} device={device}",
465
+ flush=True,
466
+ )
467
+
468
+ model = load_hyperbolic_model(args, h5_path, cache_dir, device)
469
+
470
+ train_loader = DataLoader(
471
+ H5RowProbeDataset(h5_path, train_idx, target_keys),
472
+ batch_size=args.batch_size,
473
+ shuffle=True,
474
+ num_workers=args.num_workers,
475
+ collate_fn=collate_rows,
476
+ pin_memory=device.startswith("cuda"),
477
+ )
478
+ val_loader = DataLoader(
479
+ H5RowProbeDataset(h5_path, val_idx, target_keys),
480
+ batch_size=args.batch_size,
481
+ shuffle=False,
482
+ num_workers=args.num_workers,
483
+ collate_fn=collate_rows,
484
+ pin_memory=device.startswith("cuda"),
485
+ )
486
+ test_loader = DataLoader(
487
+ H5RowProbeDataset(h5_path, test_idx, target_keys),
488
+ batch_size=args.batch_size,
489
+ shuffle=False,
490
+ num_workers=args.num_workers,
491
+ collate_fn=collate_rows,
492
+ pin_memory=device.startswith("cuda"),
493
+ )
494
+
495
+ mean = torch.from_numpy(target_mean_np).to(device)
496
+ std = torch.from_numpy(target_std_np).to(device)
497
+
498
+ probe_results = {
499
+ "linear": train_one_probe(
500
+ probe_name="linear",
501
+ hidden_dim=0,
502
+ num_layers=0,
503
+ model=model,
504
+ train_loader=train_loader,
505
+ val_loader=val_loader,
506
+ test_loader=test_loader,
507
+ target_dim=target_dim,
508
+ mean=mean,
509
+ std=std,
510
+ args=args,
511
+ device=device,
512
+ ),
513
+ "mlp": train_one_probe(
514
+ probe_name="mlp",
515
+ hidden_dim=int(args.hidden_dim),
516
+ num_layers=int(args.num_layers),
517
+ model=model,
518
+ train_loader=train_loader,
519
+ val_loader=val_loader,
520
+ test_loader=test_loader,
521
+ target_dim=target_dim,
522
+ mean=mean,
523
+ std=std,
524
+ args=args,
525
+ device=device,
526
+ ),
527
+ }
528
+
529
+ metrics = {
530
+ "policy": args.policy,
531
+ "dataset": str(h5_path),
532
+ "target_keys": target_keys,
533
+ "representation": args.representation,
534
+ "num_samples": sample_count,
535
+ "train_samples": int(len(train_idx)),
536
+ "val_samples": int(len(val_idx)),
537
+ "test_samples": int(len(test_idx)),
538
+ "probes": probe_results,
539
+ }
540
+ for probe_name, result in probe_results.items():
541
+ test = result["test"]
542
+ print(
543
+ f"[probe:{probe_name}] test_mse={test['mse']:.6f} +/- {test['mse_std']:.6f} "
544
+ f"test_r={test['pearson_r']:.6f}",
545
+ flush=True,
546
+ )
547
+ print("[probe] final metrics:")
548
+ print(json.dumps(metrics, indent=2, sort_keys=True))
549
+
550
+ if args.output:
551
+ output_path = Path(args.output)
552
+ output_path.parent.mkdir(parents=True, exist_ok=True)
553
+ output_path.write_text(json.dumps(metrics, indent=2, sort_keys=True))
554
+ print(f"[probe] wrote {output_path}", flush=True)
555
+
556
+
557
+ if __name__ == "__main__":
558
+ main()
probe_lewm_mse.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Offline physical probing for the original Euclidean LeWM model.
4
+
5
+ Example:
6
+ python probe_lewm_mse.py \
7
+ --policy /data_nvme/user/zliu681/le-wm-main/lewm_cache/antmaze_hyperbolic/antmaze_lewm/lewm_antmaze_epoch_10 \
8
+ --dataset-name ogbench_antmaze_visual_h5/visual-antmaze-large-navigate-v0 \
9
+ --target-keys observation \
10
+ --device auto \
11
+ --num-samples 50000 \
12
+ --epochs 20
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+ from pathlib import Path
21
+
22
+ import h5py
23
+ import numpy as np
24
+ import stable_worldmodel as swm
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from torch import nn
28
+ from torch.utils.data import DataLoader, Dataset
29
+
30
+ from jepa import JEPA
31
+ from module import ARPredictor, Embedder, MLP, SIGReg
32
+ from utils import resolve_runtime_device
33
+
34
+ try:
35
+ from tqdm.auto import tqdm
36
+ except Exception:
37
+ tqdm = None
38
+
39
+
40
+ IMAGENET_MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
41
+ IMAGENET_STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
42
+
43
+
44
+ def parse_args():
45
+ parser = argparse.ArgumentParser(description="Train a frozen LeWM physical probe and report MSE.")
46
+ parser.add_argument("--policy", type=str, required=True, help="Checkpoint prefix or object checkpoint path.")
47
+ parser.add_argument("--dataset-name", type=str, required=True, help="H5 dataset name under STABLEWM_HOME, or a full .h5 path.")
48
+ parser.add_argument(
49
+ "--target-keys",
50
+ type=str,
51
+ default="observation",
52
+ help="Comma-separated H5 columns to predict, e.g. observation or qpos,qvel.",
53
+ )
54
+ parser.add_argument("--cache-dir", type=str, default="", help="Overrides stable_worldmodel cache dir lookup.")
55
+ parser.add_argument("--device", type=str, default="auto")
56
+ parser.add_argument("--img-size", type=int, default=224)
57
+ parser.add_argument("--num-samples", type=int, default=50000)
58
+ parser.add_argument("--batch-size", type=int, default=256)
59
+ parser.add_argument("--epochs", type=int, default=20)
60
+ parser.add_argument("--lr", type=float, default=1e-3)
61
+ parser.add_argument("--weight-decay", type=float, default=1e-4)
62
+ parser.add_argument("--hidden-dim", type=int, default=512, help="0 means linear probe.")
63
+ parser.add_argument("--num-layers", type=int, default=2, help="Number of hidden layers when hidden_dim > 0.")
64
+ parser.add_argument("--train-frac", type=float, default=0.8)
65
+ parser.add_argument("--val-frac", type=float, default=0.1)
66
+ parser.add_argument("--seed", type=int, default=3072)
67
+ parser.add_argument("--num-workers", type=int, default=0)
68
+ parser.add_argument("--output", type=str, default="", help="Optional JSON metrics path.")
69
+ return parser.parse_args()
70
+
71
+
72
+ def cache_dir_from_args(args) -> Path:
73
+ return Path(args.cache_dir) if args.cache_dir else Path(swm.data.utils.get_cache_dir())
74
+
75
+
76
+ def resolve_h5_path(dataset_name: str, cache_dir: Path) -> Path:
77
+ path = Path(dataset_name)
78
+ if path.is_file():
79
+ return path
80
+ if path.suffix == ".h5":
81
+ candidate = cache_dir / path
82
+ else:
83
+ candidate = cache_dir / f"{dataset_name}.h5"
84
+ if candidate.is_file():
85
+ return candidate
86
+ raise FileNotFoundError(f"Could not find H5 dataset: {dataset_name} under {cache_dir}")
87
+
88
+
89
+ def register_checkpoint_aliases():
90
+ import __main__ as main_mod
91
+
92
+ for obj in (JEPA, ARPredictor, Embedder, MLP, SIGReg):
93
+ setattr(main_mod, obj.__name__, obj)
94
+ if hasattr(torch.serialization, "add_safe_globals"):
95
+ torch.serialization.add_safe_globals([JEPA, ARPredictor, Embedder, MLP, SIGReg])
96
+
97
+
98
+ def policy_candidates(policy_name: str, cache_dir: Path) -> list[Path]:
99
+ raw = Path(policy_name)
100
+ prefixes = [raw, cache_dir / raw]
101
+ candidates: list[Path] = []
102
+ for prefix in prefixes:
103
+ text = str(prefix)
104
+ if text.endswith(".ckpt"):
105
+ candidates.append(prefix)
106
+ else:
107
+ candidates.append(Path(f"{text}_object.ckpt"))
108
+ candidates.append(Path(f"{text}_state.ckpt"))
109
+ candidates.append(Path(f"{text}_weights.ckpt"))
110
+ if prefix.is_dir():
111
+ candidates.extend(sorted(prefix.glob("*_object.ckpt")))
112
+ seen = set()
113
+ result = []
114
+ for item in candidates:
115
+ if item in seen:
116
+ continue
117
+ seen.add(item)
118
+ if item.is_file():
119
+ result.append(item)
120
+ return result
121
+
122
+
123
+ def load_lewm_model(policy_name: str, cache_dir: Path, device: str) -> nn.Module:
124
+ try:
125
+ model = swm.policy.AutoCostModel(policy_name)
126
+ print(f"[probe] loaded via AutoCostModel: {policy_name}", flush=True)
127
+ except Exception as exc:
128
+ print(f"[probe] AutoCostModel failed: {type(exc).__name__}: {exc}", flush=True)
129
+ register_checkpoint_aliases()
130
+ candidates = policy_candidates(policy_name, cache_dir)
131
+ if not candidates:
132
+ raise FileNotFoundError(f"No checkpoint candidates found for policy={policy_name}")
133
+
134
+ last_error = None
135
+ model = None
136
+ for checkpoint_path in candidates:
137
+ try:
138
+ print(f"[probe] trying checkpoint: {checkpoint_path}", flush=True)
139
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
140
+ if not isinstance(checkpoint, nn.Module):
141
+ raise TypeError(
142
+ f"{checkpoint_path} is not a saved model object. "
143
+ "For LeWM probing, pass an object checkpoint or export/load via AutoCostModel."
144
+ )
145
+ model = checkpoint
146
+ break
147
+ except Exception as ckpt_exc:
148
+ last_error = ckpt_exc
149
+ print(f"[probe] failed checkpoint {checkpoint_path}: {ckpt_exc}", flush=True)
150
+ if model is None:
151
+ raise RuntimeError(f"Failed to load LeWM model. Last error: {last_error}") from last_error
152
+
153
+ if not hasattr(model, "encode") and hasattr(model, "model"):
154
+ model = model.model
155
+ if not hasattr(model, "encode"):
156
+ raise TypeError(f"Loaded model does not expose encode(info): {type(model).__name__}")
157
+ model = model.to(device).eval()
158
+ model.requires_grad_(False)
159
+ return model
160
+
161
+
162
+ class H5RowProbeDataset(Dataset):
163
+ def __init__(self, h5_path: Path, indices: np.ndarray, target_keys: list[str]):
164
+ self.h5_path = Path(h5_path)
165
+ self.indices = np.asarray(indices, dtype=np.int64)
166
+ self.target_keys = tuple(target_keys)
167
+ self._h5 = None
168
+
169
+ def _open(self):
170
+ if self._h5 is None:
171
+ self._h5 = h5py.File(self.h5_path, "r")
172
+ return self._h5
173
+
174
+ def __len__(self):
175
+ return int(len(self.indices))
176
+
177
+ def __getitem__(self, item):
178
+ h5 = self._open()
179
+ idx = int(self.indices[item])
180
+ pixels = np.asarray(h5["pixels"][idx])
181
+ targets = []
182
+ for key in self.target_keys:
183
+ value = np.asarray(h5[key][idx], dtype=np.float32).reshape(-1)
184
+ targets.append(value)
185
+ target = np.concatenate(targets, axis=0).astype(np.float32)
186
+ return torch.from_numpy(np.ascontiguousarray(pixels)), torch.from_numpy(target)
187
+
188
+
189
+ def collate_rows(batch):
190
+ pixels, targets = zip(*batch)
191
+ return torch.stack(list(pixels), dim=0), torch.stack(list(targets), dim=0)
192
+
193
+
194
+ def progress_iter(iterable, *, desc: str, total: int | None = None, leave: bool = False):
195
+ if tqdm is None:
196
+ return iterable
197
+ return tqdm(iterable, desc=desc, total=total, leave=leave, dynamic_ncols=True)
198
+
199
+
200
+ def preprocess_pixels(pixels: torch.Tensor, img_size: int, device: str) -> torch.Tensor:
201
+ pixels = pixels.to(device, non_blocking=True)
202
+ if pixels.ndim != 4:
203
+ raise ValueError(f"Expected pixels shape (B,H,W,C) or (B,C,H,W), got {tuple(pixels.shape)}")
204
+ if pixels.shape[-1] in (1, 3):
205
+ pixels = pixels.permute(0, 3, 1, 2)
206
+ elif pixels.shape[1] in (1, 3):
207
+ pass
208
+ else:
209
+ raise ValueError(f"Could not infer pixel channel layout from {tuple(pixels.shape)}")
210
+ if pixels.shape[1] == 1:
211
+ pixels = pixels.repeat(1, 3, 1, 1)
212
+ pixels = pixels.float()
213
+ if pixels.max() > 2.0:
214
+ pixels = pixels / 255.0
215
+ if pixels.shape[-2:] != (img_size, img_size):
216
+ pixels = F.interpolate(pixels, size=(img_size, img_size), mode="bilinear", align_corners=False)
217
+ mean = IMAGENET_MEAN.to(device)
218
+ std = IMAGENET_STD.to(device)
219
+ return (pixels - mean) / std
220
+
221
+
222
+ @torch.no_grad()
223
+ def encode_batch(model: nn.Module, pixels: torch.Tensor, img_size: int, device: str) -> torch.Tensor:
224
+ pixels = preprocess_pixels(pixels, img_size=img_size, device=device)
225
+ info = {"pixels": pixels.unsqueeze(1)}
226
+ out = model.encode(info)
227
+ emb = out["emb"][:, -1]
228
+ return emb.detach()
229
+
230
+
231
+ def make_probe(input_dim: int, output_dim: int, hidden_dim: int, num_layers: int) -> nn.Module:
232
+ if hidden_dim <= 0:
233
+ return nn.Linear(input_dim, output_dim)
234
+ layers: list[nn.Module] = []
235
+ dim = input_dim
236
+ for _ in range(max(1, int(num_layers))):
237
+ layers.extend([nn.Linear(dim, hidden_dim), nn.GELU()])
238
+ dim = hidden_dim
239
+ layers.append(nn.Linear(dim, output_dim))
240
+ return nn.Sequential(*layers)
241
+
242
+
243
+ def load_targets_for_stats(h5_path: Path, indices: np.ndarray, target_keys: list[str]) -> np.ndarray:
244
+ parts = []
245
+ with h5py.File(h5_path, "r") as h5:
246
+ for key in target_keys:
247
+ values = np.asarray(h5[key][indices], dtype=np.float32).reshape(len(indices), -1)
248
+ parts.append(values)
249
+ return np.concatenate(parts, axis=1)
250
+
251
+
252
+ def evaluate_probe(model, probe, loader, mean, std, args, device: str) -> dict[str, float]:
253
+ sq_error_sum = None
254
+ norm_sq_error_sum = None
255
+ pred_sum = None
256
+ target_sum = None
257
+ pred_sq_sum = None
258
+ target_sq_sum = None
259
+ pred_target_sum = None
260
+ sample_count = 0
261
+ with torch.no_grad():
262
+ for pixels, target in loader:
263
+ target = target.to(device, non_blocking=True)
264
+ target = torch.nan_to_num(target, nan=0.0, posinf=0.0, neginf=0.0)
265
+ emb = encode_batch(model, pixels, args.img_size, device)
266
+ pred_norm = probe(emb)
267
+ target_norm = (target - mean) / std
268
+ pred = pred_norm * std + mean
269
+
270
+ sq_error = (pred - target).pow(2).sum(dim=0).detach()
271
+ norm_sq_error = (pred_norm - target_norm).pow(2).sum(dim=0).detach()
272
+ pred_batch_sum = pred.sum(dim=0).detach()
273
+ target_batch_sum = target.sum(dim=0).detach()
274
+ pred_batch_sq_sum = pred.pow(2).sum(dim=0).detach()
275
+ target_batch_sq_sum = target.pow(2).sum(dim=0).detach()
276
+ pred_target_batch_sum = (pred * target).sum(dim=0).detach()
277
+
278
+ if sq_error_sum is None:
279
+ sq_error_sum = torch.zeros_like(sq_error)
280
+ norm_sq_error_sum = torch.zeros_like(norm_sq_error)
281
+ pred_sum = torch.zeros_like(pred_batch_sum)
282
+ target_sum = torch.zeros_like(target_batch_sum)
283
+ pred_sq_sum = torch.zeros_like(pred_batch_sq_sum)
284
+ target_sq_sum = torch.zeros_like(target_batch_sq_sum)
285
+ pred_target_sum = torch.zeros_like(pred_target_batch_sum)
286
+
287
+ sq_error_sum += sq_error
288
+ norm_sq_error_sum += norm_sq_error
289
+ pred_sum += pred_batch_sum
290
+ target_sum += target_batch_sum
291
+ pred_sq_sum += pred_batch_sq_sum
292
+ target_sq_sum += target_batch_sq_sum
293
+ pred_target_sum += pred_target_batch_sum
294
+ sample_count += int(target.size(0))
295
+
296
+ sample_count = max(1, sample_count)
297
+ mse_per_dim = sq_error_sum / sample_count
298
+ norm_mse_per_dim = norm_sq_error_sum / sample_count
299
+
300
+ cov = pred_target_sum - pred_sum * target_sum / sample_count
301
+ pred_var = pred_sq_sum - pred_sum.pow(2) / sample_count
302
+ target_var = target_sq_sum - target_sum.pow(2) / sample_count
303
+ denom = pred_var.clamp_min(0).sqrt() * target_var.clamp_min(0).sqrt()
304
+ valid = denom > 1e-12
305
+ if bool(valid.any().item()):
306
+ pearson_per_dim = cov[valid] / denom[valid]
307
+ pearson_r = pearson_per_dim.mean()
308
+ pearson_r_std = pearson_per_dim.std(unbiased=False)
309
+ else:
310
+ pearson_r = torch.tensor(0.0, device=device)
311
+ pearson_r_std = torch.tensor(0.0, device=device)
312
+
313
+ return {
314
+ "mse": float(mse_per_dim.mean().item()),
315
+ "mse_std": float(mse_per_dim.std(unbiased=False).item()),
316
+ "normalized_mse": float(norm_mse_per_dim.mean().item()),
317
+ "normalized_mse_std": float(norm_mse_per_dim.std(unbiased=False).item()),
318
+ "pearson_r": float(pearson_r.item()),
319
+ "pearson_r_std": float(pearson_r_std.item()),
320
+ }
321
+
322
+
323
+ def train_one_probe(
324
+ *,
325
+ probe_name: str,
326
+ hidden_dim: int,
327
+ num_layers: int,
328
+ model,
329
+ train_loader,
330
+ val_loader,
331
+ test_loader,
332
+ target_dim: int,
333
+ mean,
334
+ std,
335
+ args,
336
+ device: str,
337
+ ) -> dict:
338
+ first_pixels, _ = next(iter(train_loader))
339
+ first_emb = encode_batch(model, first_pixels, args.img_size, device)
340
+ probe = make_probe(
341
+ input_dim=int(first_emb.shape[-1]),
342
+ output_dim=target_dim,
343
+ hidden_dim=hidden_dim,
344
+ num_layers=num_layers,
345
+ ).to(device)
346
+ optimizer = torch.optim.AdamW(probe.parameters(), lr=args.lr, weight_decay=args.weight_decay)
347
+
348
+ best_state = None
349
+ best_val = float("inf")
350
+ for epoch in range(1, args.epochs + 1):
351
+ probe.train()
352
+ train_loss = 0.0
353
+ train_count = 0
354
+ batch_iter = progress_iter(
355
+ train_loader,
356
+ desc=f"probe:{probe_name}:epoch{epoch:03d}",
357
+ total=len(train_loader),
358
+ leave=False,
359
+ )
360
+ for pixels, target in batch_iter:
361
+ target = target.to(device, non_blocking=True)
362
+ target = torch.nan_to_num(target, nan=0.0, posinf=0.0, neginf=0.0)
363
+ with torch.no_grad():
364
+ emb = encode_batch(model, pixels, args.img_size, device)
365
+ pred = probe(emb)
366
+ target_norm = (target - mean) / std
367
+ loss = F.mse_loss(pred, target_norm)
368
+
369
+ optimizer.zero_grad(set_to_none=True)
370
+ loss.backward()
371
+ optimizer.step()
372
+
373
+ train_loss += loss.item() * target.numel()
374
+ train_count += target.numel()
375
+ if tqdm is not None:
376
+ batch_iter.set_postfix(norm_mse=f"{train_loss / max(1, train_count):.4f}")
377
+
378
+ probe.eval()
379
+ val_metrics = evaluate_probe(model, probe, val_loader, mean, std, args, device)
380
+ train_norm_mse = train_loss / max(1, train_count)
381
+ print(
382
+ f"[probe:{probe_name}] epoch={epoch:03d} train_norm_mse={train_norm_mse:.6f} "
383
+ f"val_mse={val_metrics['mse']:.6f} val_r={val_metrics['pearson_r']:.6f}",
384
+ flush=True,
385
+ )
386
+ if val_metrics["normalized_mse"] < best_val:
387
+ best_val = val_metrics["normalized_mse"]
388
+ best_state = {key: value.detach().cpu() for key, value in probe.state_dict().items()}
389
+
390
+ if best_state is not None:
391
+ probe.load_state_dict(best_state)
392
+ probe.eval()
393
+ return {
394
+ "hidden_dim": int(hidden_dim),
395
+ "num_layers": int(num_layers),
396
+ "val": evaluate_probe(model, probe, val_loader, mean, std, args, device),
397
+ "test": evaluate_probe(model, probe, test_loader, mean, std, args, device),
398
+ }
399
+
400
+
401
+ def main():
402
+ args = parse_args()
403
+ cache_dir = cache_dir_from_args(args)
404
+ h5_path = resolve_h5_path(args.dataset_name, cache_dir)
405
+ target_keys = [key.strip() for key in args.target_keys.split(",") if key.strip()]
406
+
407
+ with h5py.File(h5_path, "r") as h5:
408
+ missing = [key for key in ["pixels", *target_keys] if key not in h5]
409
+ if missing:
410
+ raise KeyError(f"{h5_path} missing required keys: {missing}. Available: {list(h5.keys())}")
411
+ row_count = min(int(h5["pixels"].shape[0]), *(int(h5[key].shape[0]) for key in target_keys))
412
+
413
+ rng = np.random.default_rng(args.seed)
414
+ sample_count = min(int(args.num_samples), row_count)
415
+ indices = rng.choice(row_count, size=sample_count, replace=False)
416
+ rng.shuffle(indices)
417
+
418
+ n_train = int(sample_count * args.train_frac)
419
+ n_val = int(sample_count * args.val_frac)
420
+ n_train = max(1, min(n_train, sample_count))
421
+ n_val = max(1, min(n_val, sample_count - n_train))
422
+ train_idx = np.sort(indices[:n_train])
423
+ val_idx = np.sort(indices[n_train : n_train + n_val])
424
+ test_idx = np.sort(indices[n_train + n_val :])
425
+ if len(test_idx) == 0:
426
+ test_idx = val_idx
427
+
428
+ train_targets = load_targets_for_stats(h5_path, train_idx, target_keys)
429
+ target_mean_np = np.nanmean(train_targets, axis=0, keepdims=True).astype(np.float32)
430
+ target_std_np = np.nanstd(train_targets, axis=0, keepdims=True).astype(np.float32)
431
+ target_std_np = np.maximum(target_std_np, 1e-6)
432
+ target_dim = int(train_targets.shape[1])
433
+
434
+ device = resolve_runtime_device(args.device, allow_fallback=True)
435
+ print(
436
+ f"[probe] dataset={h5_path} rows={row_count} sampled={sample_count} "
437
+ f"train={len(train_idx)} val={len(val_idx)} test={len(test_idx)} target_dim={target_dim}",
438
+ flush=True,
439
+ )
440
+ print(f"[probe] target_keys={target_keys} device={device}", flush=True)
441
+
442
+ model = load_lewm_model(args.policy, cache_dir, device)
443
+
444
+ train_loader = DataLoader(
445
+ H5RowProbeDataset(h5_path, train_idx, target_keys),
446
+ batch_size=args.batch_size,
447
+ shuffle=True,
448
+ num_workers=args.num_workers,
449
+ collate_fn=collate_rows,
450
+ pin_memory=device.startswith("cuda"),
451
+ )
452
+ val_loader = DataLoader(
453
+ H5RowProbeDataset(h5_path, val_idx, target_keys),
454
+ batch_size=args.batch_size,
455
+ shuffle=False,
456
+ num_workers=args.num_workers,
457
+ collate_fn=collate_rows,
458
+ pin_memory=device.startswith("cuda"),
459
+ )
460
+ test_loader = DataLoader(
461
+ H5RowProbeDataset(h5_path, test_idx, target_keys),
462
+ batch_size=args.batch_size,
463
+ shuffle=False,
464
+ num_workers=args.num_workers,
465
+ collate_fn=collate_rows,
466
+ pin_memory=device.startswith("cuda"),
467
+ )
468
+
469
+ mean = torch.from_numpy(target_mean_np).to(device)
470
+ std = torch.from_numpy(target_std_np).to(device)
471
+
472
+ probe_results = {
473
+ "linear": train_one_probe(
474
+ probe_name="linear",
475
+ hidden_dim=0,
476
+ num_layers=0,
477
+ model=model,
478
+ train_loader=train_loader,
479
+ val_loader=val_loader,
480
+ test_loader=test_loader,
481
+ target_dim=target_dim,
482
+ mean=mean,
483
+ std=std,
484
+ args=args,
485
+ device=device,
486
+ ),
487
+ "mlp": train_one_probe(
488
+ probe_name="mlp",
489
+ hidden_dim=int(args.hidden_dim),
490
+ num_layers=int(args.num_layers),
491
+ model=model,
492
+ train_loader=train_loader,
493
+ val_loader=val_loader,
494
+ test_loader=test_loader,
495
+ target_dim=target_dim,
496
+ mean=mean,
497
+ std=std,
498
+ args=args,
499
+ device=device,
500
+ ),
501
+ }
502
+
503
+ metrics = {
504
+ "policy": args.policy,
505
+ "dataset": str(h5_path),
506
+ "target_keys": target_keys,
507
+ "num_samples": sample_count,
508
+ "train_samples": int(len(train_idx)),
509
+ "val_samples": int(len(val_idx)),
510
+ "test_samples": int(len(test_idx)),
511
+ "probes": probe_results,
512
+ }
513
+ for probe_name, result in probe_results.items():
514
+ test = result["test"]
515
+ print(
516
+ f"[probe:{probe_name}] test_mse={test['mse']:.6f} +/- {test['mse_std']:.6f} "
517
+ f"test_r={test['pearson_r']:.6f}",
518
+ flush=True,
519
+ )
520
+ print("[probe] final metrics:")
521
+ print(json.dumps(metrics, indent=2, sort_keys=True))
522
+
523
+ if args.output:
524
+ output_path = Path(args.output)
525
+ output_path.parent.mkdir(parents=True, exist_ok=True)
526
+ output_path.write_text(json.dumps(metrics, indent=2, sort_keys=True))
527
+ print(f"[probe] wrote {output_path}", flush=True)
528
+
529
+
530
+ if __name__ == "__main__":
531
+ main()