-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-place.py
More file actions
1957 lines (1760 loc) · 112 KB
/
test-place.py
File metadata and controls
1957 lines (1760 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import os, argparse, yaml, time, numpy as np, torch
import torch.nn.functional as F
import torch.distributed as dist
from pydrake.all import StartMeshcat
import imageio
from collections import deque
from drake_env.scenes import build_scene, sample_randomization
from drake_env.planners import compute_subgoals, plan_and_rollout
from ot_jepa.models.encoders import VisionEncoder, StateEncoder, LangEncoder
from ot_jepa.models.metric import MetricNet
from ot_jepa.models.jepa import TemporalPredictor, GoalDistributionHead
from ot_jepa.models.action_conditioned_predictor import ActionConditionedPredictor
from ot_jepa.models.flow_matching import FlowMatchingHead
from ot_jepa.models.mpc_planner import MPCPlanner
def parse():
ap = argparse.ArgumentParser()
ap.add_argument("--config", type=str, default="configs/default.yaml")
ap.add_argument("--episodes", type=int, default=1)
ap.add_argument("--randomize", type=float, default=0.5)
ap.add_argument("--ckpt", type=str, default="")
ap.add_argument("--hz", type=int, default=4)
ap.add_argument("--horizon_H", type=int, default=4)
ap.add_argument("--window_k", type=int, default=2)
ap.add_argument("--scene", type=str, default=None)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--task", type=str, default="pick_place")
ap.add_argument("--skip-planner-baseline", action="store_true", help="Skip planner baseline (faster)")
ap.add_argument("--no-meshcat", action="store_true", help="Disable Meshcat visualization (faster)")
ap.add_argument("--use-mpc", action="store_true", help="Use MPC planning instead of flow matching for action generation")
ap.add_argument("--mpc-horizon", type=int, default=2, help="MPC planning horizon (Meta default: 2)")
ap.add_argument("--mpc-samples", type=int, default=256, help="MPC number of samples per iteration (Meta default: 400)")
ap.add_argument("--mpc-iterations", type=int, default=5, help="MPC number of CEM iterations (Optimized with Warm Start: 5)")
ap.add_argument("--mpc-top-k", type=int, default=10, help="MPC top-k trajectories for updating (Meta default: 10)")
ap.add_argument("--ac-hidden-dim", type=int, default=1024, help="Action-conditioned predictor hidden dim (default: 1024)")
ap.add_argument("--eval-clip-seconds", type=float, default=10.0,
help="Evaluation clip length in seconds (default: 10.0)")
ap.add_argument("--ac-layers", type=int, default=24, help="Action-conditioned predictor layers (default: 24)")
ap.add_argument("--ac-heads", type=int, default=16, help="Action-conditioned predictor attention heads (default: 16)")
ap.add_argument("--position-guidance", type=float, default=0.0,
help="Position guidance weight for MPC (0.0=pure latent, 1.0=pure position, default: 0.5 for pg)")
ap.add_argument("--position-guidance-phases", type=str, default="all",
help="Phases to apply position guidance: 'all' or 'none' (default: all for test-place)")
# test-place.py: Placement-only evaluation (starts with letter grasped)
ap.add_argument("--near-fraction", type=float, default=0.70,
help="Fraction of trajectory to use NEAR goal (default: 0.70 = 70%%)")
ap.add_argument("--place-fraction", type=float, default=0.30,
help="Fraction of trajectory to use FINAL goal (default: 0.30 = 30%%)")
ap.add_argument("--start-height", type=float, default=0.40,
help="Starting height for gripper with grasped letter (default: 0.40m)")
return ap.parse_args()
class EvalOTJEPA(torch.nn.Module):
def __init__(
self,
state_dim: int,
d: int,
act_dim: int,
vision_backbone: str = "internal",
image_size=(256, 256),
patch_size: int = 16,
depth: int = 4,
heads: int = 4,
vjepa2_cfg: dict | None = None,
metric_rank: int = 64,
):
super().__init__()
if str(vision_backbone).lower() == "vjepa2":
from ot_jepa.models.vjepa2_backbone import VJEPA2VisionEncoder
self.E_v = VJEPA2VisionEncoder(
latent_dim=d,
img_size=tuple(image_size),
patch_size=int(patch_size),
depth=int(depth),
heads=int(heads),
)
elif str(vision_backbone).lower() == "vjepa2_hub":
from ot_jepa.models.vjepa2_backbone import VJEPA2HubEncoder
cfg = dict(vjepa2_cfg or {})
variant = str(cfg.get("variant", "vjepa2_ac_vit_giant"))
pretrained = bool(cfg.get("pretrained", True))
freeze = bool(cfg.get("freeze_encoder", True))
hub_repo = str(cfg.get("hub_repo", "facebookresearch/vjepa2"))
cache_dir = cfg.get("cache_dir")
self.E_v = VJEPA2HubEncoder(
latent_dim=d,
variant=variant,
pretrained=pretrained,
freeze=freeze,
hub_repo=hub_repo,
cache_dir=cache_dir,
img_size=tuple(image_size),
patch_size=int(patch_size),
)
else:
self.E_v = VisionEncoder(latent_dim=d)
self.E_s = StateEncoder(in_dim=state_dim, latent_dim=d)
self.E_l = LangEncoder(vocab_size=512, emb_dim=d, latent_dim=d)
# Multi-view fusion: front + wrist + state -> d
self.Fusion = torch.nn.Sequential(torch.nn.Linear(d * 3, d), torch.nn.ReLU(), torch.nn.Linear(d, d))
# Single-view fusion: vision + state -> d (for independent camera training)
self.Fusion_single = torch.nn.Sequential(torch.nn.Linear(d * 2, d), torch.nn.ReLU(), torch.nn.Linear(d, d))
# Placeholder for Pred - will be set based on architecture
self.Pred = None
self.use_action_conditioning = False
self.Metric = MetricNet(d, rank=metric_rank)
self.FM = FlowMatchingHead(d, act_dim)
self.GoalHead = GoalDistributionHead(latent_dim=d)
def _find_latest_checkpoint(arch: str, directory: str = "checkpoints") -> str | None:
prefix = f"{arch}_"
best_step = -1
best_path: str | None = None
if not os.path.isdir(directory):
return None
for fname in os.listdir(directory):
if not (fname.startswith(prefix) and fname.endswith(".pt")):
continue
step_str = fname[len(prefix) : -3]
try:
step = int(step_str)
except ValueError:
continue
if step > best_step:
best_step = step
best_path = os.path.join(directory, fname)
return best_path
def main():
args = parse()
cfg = yaml.safe_load(open(args.config))
# Initialize distributed for multi-GPU MPC inference
# torch.distributed.run sets RANK, WORLD_SIZE, LOCAL_RANK env vars
local_rank = int(os.environ.get("LOCAL_RANK", "0"))
rank = int(os.environ.get("RANK", "0"))
world_size = int(os.environ.get("WORLD_SIZE", "1"))
# For single episode evaluation, distributed overhead isn't worth it
# Force single-GPU mode for simplicity
if args.episodes >= 1 and world_size > 1:
if rank == 0:
print(f"Single episode evaluation detected")
print(f"Using single GPU (rank 0) only for simplicity")
print(f"For multi-episode evaluation, use --episodes > 1 to leverage distributed MPC")
# Non-rank-0 processes exit immediately
if rank != 0:
return
world_size = 1
# Initialize process group if not already initialized and world_size > 1
if world_size > 1 and not (dist.is_available() and dist.is_initialized()):
# Use NCCL backend for GPU communication
dist.init_process_group(backend="nccl", init_method="env://")
if rank == 0:
print(f"Initialized distributed process group: {world_size} GPUs")
is_main = (rank == 0)
# Verify CUDA availability (only rank 0 prints to avoid clutter)
if is_main:
print(f"torch.cuda.is_available() = {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"CUDA Device Count: {torch.cuda.device_count()}")
print(f"Device Name: {torch.cuda.get_device_name(0)}")
else:
print("CUDA NOT AVAILABLE. Running on CPU!")
if world_size > 1:
print(f"Distributed MPC: Each of {world_size} ranks will evaluate {args.mpc_samples // world_size} samples")
# Set device to this rank's GPU
if torch.cuda.is_available() and cfg["device"] == "cuda":
device = torch.device(f"cuda:{local_rank}")
torch.cuda.set_device(device)
else:
device = torch.device("cpu")
d = int(cfg["model"]["latent_dim"])
cfg_act_dim = int(cfg["model"].get("act_dim", 7))
state_dim = int(cfg["model"].get("state_dim", 7))
arch = cfg.get("model", {}).get("architecture", "ot-jepa").lower()
# Model selection (FM-only at eval for all architectures)
ckpt_path = args.ckpt
if not ckpt_path:
ckpt_path = _find_latest_checkpoint(arch)
if ckpt_path and is_main:
print(f"loading latest checkpoint: {ckpt_path}")
# Enforce strict checkpoint loading semantics
explicit_ckpt = bool(args.ckpt)
if explicit_ckpt and not ckpt_path:
if is_main:
print(f"--ckpt was provided but no checkpoint path could be resolved")
raise SystemExit(1)
if explicit_ckpt and not os.path.exists(ckpt_path):
if is_main:
print(f"Checkpoint file not found: {ckpt_path}")
raise SystemExit(1)
if not explicit_ckpt and not ckpt_path:
if is_main:
print(f"No checkpoint found in directory 'checkpoints' for arch='{arch}'")
raise SystemExit(1)
ckpt = None
ckpt_state_dim = None
ckpt_act_dim = None
ckpt_metric_rank = None
if ckpt_path and os.path.exists(ckpt_path):
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
model_state = ckpt.get("model", ckpt)
if isinstance(model_state, dict):
# Handle both compiled (_orig_mod. prefix) and non-compiled checkpoints
es_weight = model_state.get("E_s.net.0.weight") or model_state.get("_orig_mod.E_s.net.0.weight")
if isinstance(es_weight, torch.Tensor) and es_weight.ndim == 2:
ckpt_state_dim = int(es_weight.shape[1])
if ckpt_state_dim is None:
for key, tensor in model_state.items():
# Strip _orig_mod. prefix if present for matching
clean_key = key.replace("_orig_mod.", "")
if not (isinstance(tensor, torch.Tensor) and tensor.ndim == 2 and clean_key.startswith("E_s")):
continue
ckpt_state_dim = int(tensor.shape[1])
break
fm_weight = model_state.get("FM.net.4.weight") or model_state.get("_orig_mod.FM.net.4.weight")
if isinstance(fm_weight, torch.Tensor) and fm_weight.ndim == 2:
ckpt_act_dim = int(fm_weight.shape[0])
if ckpt_act_dim is None:
for key, tensor in model_state.items():
# Strip _orig_mod. prefix if present for matching
clean_key = key.replace("_orig_mod.", "")
if not (isinstance(tensor, torch.Tensor) and tensor.ndim == 2 and clean_key.startswith("FM")):
continue
ckpt_act_dim = int(tensor.shape[0])
break
# Infer metric_rank from Metric.backbone.4.weight shape
# Shape is [rank * latent_dim, hidden], where hidden=256, latent_dim=d
metric_weight = model_state.get("Metric.backbone.4.weight") or model_state.get("_orig_mod.Metric.backbone.4.weight")
if isinstance(metric_weight, torch.Tensor) and metric_weight.ndim == 2:
rank_times_d = int(metric_weight.shape[0])
# latent_dim (d) will be determined from config, typically 256
# So we need to defer this calculation until after d is known
ckpt_metric_rank = rank_times_d # Store the product for now
if ckpt_state_dim is not None:
state_dim = ckpt_state_dim
if is_main:
print(f"Inferred state_dim={state_dim} from checkpoint (was {cfg.get('model', {}).get('state_dim', 7)} in config)")
act_dim = ckpt_act_dim if ckpt_act_dim is not None else cfg_act_dim
if ckpt_act_dim is not None and act_dim != cfg_act_dim and is_main:
print(f"Inferred act_dim={act_dim} from checkpoint (was {cfg_act_dim} in config)")
# Infer metric_rank from checkpoint if available
metric_rank = 64 # Default
if ckpt_metric_rank is not None:
# ckpt_metric_rank is rank * latent_dim, so divide by d to get rank
metric_rank = int(ckpt_metric_rank // d)
if is_main:
print(f"Inferred metric_rank={metric_rank} from checkpoint (rank*d={ckpt_metric_rank}, d={d})")
results_dir = "results"
os.makedirs(results_dir, exist_ok=True)
# Multi-GPU inference handled via torch.distributed, not DataParallel
# Each rank has its own model copy on its own GPU
# Default backbone; override sensible defaults for convenience
vb = str(cfg.get("model", {}).get("vision_backbone", "internal")).lower()
if arch in ("vjepa", "ot-vjepa") and vb == "internal":
vb = "vjepa2_hub"
elif arch in ("vjepa2ac-baseline", "vjepa2ac-continued", "vjepa2ac-unfreeze", "vjepa2ac-ot") and vb == "internal":
vb = "vjepa2_hub"
ps = int(cfg.get("model", {}).get("patch_size", 16))
vd = int(cfg.get("model", {}).get("vision_depth", 4))
vh = int(cfg.get("model", {}).get("vision_heads", 4))
imsz = tuple(cfg.get("data", {}).get("image_size", (256, 256)))
vjepa2_cfg = cfg.get("vjepa2", {})
model = EvalOTJEPA(
state_dim,
d,
act_dim,
vision_backbone=vb,
image_size=imsz,
patch_size=ps,
depth=vd,
heads=vh,
vjepa2_cfg=vjepa2_cfg,
metric_rank=metric_rank,
).to(device).eval()
# No DataParallel wrapping needed - each rank has its own model copy in distributed mode
# Set predictor for eval
# MPC requires action-conditioned predictor for full rollout capability
# FM-only uses basic TemporalPredictor
model_unwrapped = model # No wrapping in distributed mode
if args.use_mpc:
# VJEPA2-AC MPC: Use hub predictor with patch-token-level planning (Meta's approach)
if hasattr(model_unwrapped.E_v, 'predictor') and model_unwrapped.E_v.predictor is not None:
model_unwrapped.Pred = model_unwrapped.E_v.predictor # Use continued-pretrained VJEPA2-AC predictor
model_unwrapped.use_action_conditioning = True
model_unwrapped.use_patch_token_mpc = True # Flag for patch-token-based MPC
if is_main:
print(f"MPC with hub predictor (VisionTransformerPredictorAC)")
print(f"Planning operates on patch tokens (Meta's VJEPA2-AC approach)")
if ckpt is not None:
print(f"Using continued-pretrained weights from checkpoint")
else:
print(f"Using hub pretrained weights only (no checkpoint loaded)")
else:
# custom predictor for non-VJEPA2-AC architectures
model_unwrapped.Pred = ActionConditionedPredictor(
latent_dim=d,
action_dim=act_dim,
state_dim=state_dim,
hidden_dim=args.ac_hidden_dim,
num_layers=args.ac_layers,
num_heads=args.ac_heads,
).to(device).eval()
model_unwrapped.use_action_conditioning = True
model_unwrapped.use_patch_token_mpc = False # Latent-space MPC
if is_main:
print(f"MPC with custom ActionConditionedPredictor (latent-space)")
print(f"Config: hidden_dim={args.ac_hidden_dim}, layers={args.ac_layers}, heads={args.ac_heads}")
print(f"Predictor will have random weights unless loaded from checkpoint")
else:
# Use basic temporal predictor for FM
model_unwrapped.Pred = TemporalPredictor(latent_dim=d).to(device).eval()
model_unwrapped.use_action_conditioning = False
model_unwrapped.use_patch_token_mpc = False
if ckpt and "model" in ckpt:
# Handle torch.compile() prefixes in checkpoint keys
ckpt_state = ckpt["model"]
if any(k.startswith("_orig_mod.") for k in ckpt_state.keys()):
# Checkpoint was saved with compiled model; strip _orig_mod. prefix
ckpt_state = {k.replace("_orig_mod.", ""): v for k, v in ckpt_state.items()}
if is_main:
print("Detected compiled checkpoint; stripped _orig_mod. prefixes")
# Check what keys are in checkpoint vs what model expects
if is_main:
ckpt_keys = set(ckpt_state.keys())
model_keys = set(model_unwrapped.state_dict().keys())
ev_pred_keys = [k for k in ckpt_keys if k.startswith("E_v.predictor")]
pred_keys = [k for k in ckpt_keys if k.startswith("Pred.")]
print(f"Checkpoint E_v.predictor.* keys: {len(ev_pred_keys)}")
print(f"Checkpoint Pred.* keys: {len(pred_keys)}")
if len(ev_pred_keys) > 0:
print(f"Sample E_v.predictor keys: {ev_pred_keys[:3]}")
ckpt_has_predictor = any(k.startswith("E_v.predictor") for k in ckpt_state.keys())
# Capture predictor weights before loading to verify they change
pred_hash_before = None
if args.use_mpc and hasattr(model_unwrapped, 'Pred') and model_unwrapped.Pred is not None:
pred_param = next(model_unwrapped.Pred.parameters())
pred_hash_before = pred_param.data.sum().item()
missing_keys, unexpected_keys = model_unwrapped.load_state_dict(ckpt_state, strict=False)
# Filter out Pred.* missing keys if they're duplicates of E_v.predictor (same module)
# This happens because we assign model.Pred = model.E_v.predictor
if missing_keys:
filtered_missing = [k for k in missing_keys if not k.startswith("Pred.")]
pred_missing = [k for k in missing_keys if k.startswith("Pred.")]
if is_main and pred_missing:
print(f"{len(pred_missing)} 'Pred.*' keys missing because Pred=E_v.predictor (same module)")
missing_keys = filtered_missing
if is_main and (missing_keys or unexpected_keys):
print(f"Checkpoint loading summary:")
if missing_keys:
print(f"Missing keys ({len(missing_keys)}): {missing_keys[:5]}..." if len(missing_keys) > 5 else f"Missing keys: {missing_keys}")
if unexpected_keys:
print(f"Unexpected keys ({len(unexpected_keys)}): {unexpected_keys[:5]}..." if len(unexpected_keys) > 5 else f"Unexpected keys: {unexpected_keys}")
# Verify predictor weights actually changed after loading (only when we expect them to)
if args.use_mpc and hasattr(model_unwrapped, 'Pred') and model_unwrapped.Pred is not None and pred_hash_before is not None:
pred_param = next(model_unwrapped.Pred.parameters())
pred_hash_after = pred_param.data.sum().item()
delta = abs(pred_hash_after - pred_hash_before)
# For continued / unfreeze / OT variants, we EXPECT predictor updates if the
# checkpoint actually contains predictor weights. For baseline, it's
# acceptable (and expected) that the predictor remains equal to the hub.
expect_predictor_change = (
explicit_ckpt
and ckpt_has_predictor
and arch in ("vjepa2ac-continued", "vjepa2ac-unfreeze", "vjepa2ac-ot")
)
if is_main:
if delta > 1e-6:
print(f"Predictor weights LOADED from checkpoint (param sum: {pred_hash_before:.4f} -> {pred_hash_after:.4f})")
else:
if expect_predictor_change:
print(f"Predictor weights UNCHANGED after loading checkpoint (expected updates for arch='{arch}')")
else:
print(f"Predictor weights unchanged after loading checkpoint (arch='{arch}', frozen hub predictor)")
if delta <= 1e-6 and expect_predictor_change:
raise SystemExit(1)
# Optimize model for inference
model.eval() # Ensure all modules in eval mode
# Compile for faster inference (PyTorch 2.0+)
if hasattr(torch, "compile") and not args.no_meshcat:
try:
model = torch.compile(model, mode="reduce-overhead")
if is_main:
print("Model compiled for faster inference")
except Exception as e:
if is_main:
print(f"torch.compile failed: {e}")
# Initialize MPC planner if requested (mutually exclusive with FM)
mpc_planner = None
if args.use_mpc:
# ACTION SCALE: The action encoder was trained with larger action magnitudes.
# Our actions are in [-0.05, 0.05] meters, but the action encoder expects
# inputs that produce embeddings comparable to visual token embeddings.
# Visual tokens after predictor_embed have std ≈ 4.6, while action tokens
# have std ≈ 0.03 with our current action magnitudes.
# With action_scale=20, visual/action ratio drops from ~160 to ~23.
# Try action_scale=35 to get ratio closer to ~13 for stronger action influence.
mpc_planner = MPCPlanner(
act_dim=act_dim,
planning_horizon=args.mpc_horizon,
num_samples=args.mpc_samples,
num_iterations=args.mpc_iterations,
top_k=args.mpc_top_k,
action_l1_max=0.08, # Larger box constraint for more exploration (8cm)
action_std_init=0.06, # Larger initial std for better coverage (6cm)
action_scale=20.0, # Scale actions to match training distribution
).to(device).eval()
# Enable verbose debug for first few MPC calls to diagnose energy landscape
mpc_planner._verbose_debug = True # Enable for diagnostics
# MPC planner uses distributed communication (not DataParallel)
# Each rank evaluates a subset of samples on its own GPU
if is_main:
print("Policy: Model Predictive Control (MPC)")
print(f"MPC uses predictor for planning (FM ignored)")
print(f"Horizon={args.mpc_horizon}, samples={args.mpc_samples}, "
f"iterations={args.mpc_iterations}, top_k={args.mpc_top_k}")
if world_size > 1:
print(f"Distributed MPC: {args.mpc_samples} samples split across {world_size} GPUs (~{args.mpc_samples // world_size} samples/GPU)")
else:
if is_main:
print("Policy: Flow Matching (FM)")
print("FM generates actions directly (predictor ignored)")
def render_rgb(port, root_context):
sys = port.get_system()
port_context = sys.GetMyContextFromRoot(root_context)
img = port.Eval(port_context).data
arr = np.asarray(img)
# Match EpisodeLogger._prepare_image EXACTLY to keep train/eval aligned
# NO FLIPS: Meta's pretrained VJEPA2 expects unflipped images
# Flipping would destroy the pretrained representations
if arr.ndim == 3 and arr.shape[0] in (3, 4):
# Drake camera format: (C, H, W) -> (H, W, C)
arr = np.transpose(arr[:3], (1, 2, 0))
elif arr.ndim == 3 and arr.shape[-1] == 4:
# Drop alpha channel for (H, W, 4) -> (H, W, 3)
arr = arr[..., :3]
arr = np.clip(arr, 0, 255)
if arr.dtype != np.uint8:
arr = arr.astype(np.uint8)
return arr
base_seed = args.seed if args.seed is not None else 4321
if args.scene:
scene_seed = abs(hash(args.scene)) % (2**32)
base_seed = (base_seed + scene_seed) % (2**32)
rng = np.random.default_rng(base_seed)
if is_main and args.scene:
print(f"scene={args.scene} seed={base_seed}")
elif is_main and args.seed is not None:
print(f"seed={base_seed}")
successes_policy, successes_planner = 0, 0
# Define all available scenes with their configurations
ALL_SCENES = {
"scene_a": {
"scene_type": "franka_reference",
"drake_task_name": "scene_a",
"language_eval": "Place the grasped letter P on the top shelf",
"letter": "P",
},
"scene_b": {
"scene_type": "franka_reference",
"drake_task_name": "scene_b",
"language_eval": "Place the grasped letter L on the top shelf",
"letter": "L",
},
"scene_c": {
"scene_type": "franka_reference",
"drake_task_name": "scene_c",
"language_eval": "Place the grasped letter A on the top shelf",
"letter": "A",
},
"scene_d": {
"scene_type": "franka_reference",
"drake_task_name": "scene_d",
"language_eval": "Place the grasped letter C on the top shelf",
"letter": "C",
},
}
# Determine which scenes to run
if args.scene:
scene_name = str(args.scene).lower()
# Normalize scene name
if scene_name in ("a",):
scene_name = "scene_a"
elif scene_name in ("b",):
scene_name = "scene_b"
elif scene_name in ("c",):
scene_name = "scene_c"
elif scene_name in ("d",):
scene_name = "scene_d"
if scene_name in ALL_SCENES:
scenes_to_run = [scene_name]
else:
if is_main:
print(f"unknown scene '{args.scene}', defaulting to all scenes")
scenes_to_run = list(ALL_SCENES.keys())
else:
# No scene specified: run all 4 scenes
scenes_to_run = list(ALL_SCENES.keys())
if is_main:
print(f"No --scene specified, running all {len(scenes_to_run)} scenes: {scenes_to_run}")
print(f"Total episodes: {len(scenes_to_run) * args.episodes} ({args.episodes} per scene)")
# Determine suffix for output files
if len(scenes_to_run) == 1:
suffix = f"{scenes_to_run[0]}_{'mpc' if args.use_mpc else 'fm'}"
else:
suffix = f"all_scenes_{'mpc' if args.use_mpc else 'fm'}"
html_path = os.path.join(results_dir, f"{arch}_{suffix}.html")
mp4_path = os.path.join(results_dir, f"{arch}_{suffix}.mp4")
# Global tracking across all scenes
all_episode_results = [] # All episodes from all scenes
global_successes_policy = 0
global_successes_planner = 0
global_total_episodes = 0
# Global best episode tracking (across all scenes)
global_best_episode_idx = -1
global_best_episode_scene = None
global_best_episode_min_dist = float('inf')
global_best_episode_frames: list[np.ndarray] | None = None
# Per-scene results for detailed reporting
per_scene_results = {}
meshcat = None
meshcat_can_record = False
# Only enable meshcat for single-scene evaluation (multi-scene would record all episodes which isn't useful)
single_scene_mode = len(scenes_to_run) == 1
if is_main and not args.no_meshcat and single_scene_mode:
try:
meshcat = StartMeshcat()
if hasattr(meshcat, "DeleteRecording"):
meshcat.DeleteRecording()
if all(hasattr(meshcat, attr) for attr in ("StartRecording", "StopRecording", "PublishRecording", "StaticHtml")):
meshcat.StartRecording(set_visualizations_while_recording=False)
meshcat_can_record = True
else:
print("Meshcat version lacks recording support; HTML will be static.")
except Exception as exc:
meshcat = None
print(f"Meshcat start failed: {exc}. Proceeding without HTML export.")
elif is_main and args.no_meshcat:
print("Meshcat disabled for faster evaluation")
elif is_main and not single_scene_mode:
print("Meshcat disabled for multi-scene evaluation (use --scene to enable)")
# Episode generation loop
# Only rank 0 runs Drake simulation; other ranks participate when MPC is called
if rank == 0:
# Outer loop over scenes
for scene_idx, current_scene_name in enumerate(scenes_to_run):
scene_config = ALL_SCENES[current_scene_name]
scene_type = scene_config["scene_type"]
drake_task_name = scene_config["drake_task_name"]
language_eval = scene_config["language_eval"]
if is_main:
print(f"\nScene {scene_idx+1}/{len(scenes_to_run)}: {current_scene_name}")
print(f"Task: {language_eval}")
# Per-scene tracking
scene_episode_results = []
scene_successes_policy = 0
scene_successes_planner = 0
scene_best_episode_idx = -1
scene_best_episode_min_dist = float('inf')
scene_best_episode_frames = None
for ep in range(args.episodes):
ep_start_time = time.time()
rand = sample_randomization(args.randomize, rng)
# Planner baseline (optional)
planner_success = None
planner_min_distance = None
if not args.skip_planner_baseline:
t_planner_start = time.time()
scene = build_scene(
drake_task_name,
rand,
image_size=(256, 256),
camera_fps=float(args.hz),
meshcat=meshcat,
scene_type=scene_type,
)
subgoals = compute_subgoals(scene, drake_task_name)
if scene_type != "franka_reference":
baseline = plan_and_rollout(scene, subgoals, episode_length_sec=10.0, hz=args.hz)
planner_success = baseline["contacts"][-1]["min_distance"] > 0.005
planner_min_distance = baseline["contacts"][-1]["min_distance"]
if planner_success:
scene_successes_planner += 1
if is_main:
if scene_type == "franka_reference":
print("Skipping planner baseline for franka_reference scene")
else:
print(f"Planner baseline took {time.time() - t_planner_start:.2f}s")
else:
scene = build_scene(
drake_task_name,
rand,
image_size=(256, 256),
camera_fps=float(args.hz),
meshcat=meshcat,
scene_type=scene_type,
)
subgoals = compute_subgoals(scene, drake_task_name)
# Track per-episode metrics
ep_data = {
"scene": current_scene_name,
"episode": ep,
"global_episode_idx": global_total_episodes,
"randomize_factor": args.randomize,
"randomization": {
"light_intensity": rand.light_intensity,
"camera_jitter": rand.camera_jitter,
"clutter_count": rand.clutter_count,
"friction": rand.friction,
"block_color": rand.block_color,
},
"planner_success": planner_success,
"planner_min_distance": planner_min_distance,
}
# Reset scene for policy rollout
scene = build_scene(
drake_task_name,
rand,
image_size=(256, 256),
camera_fps=float(args.hz),
meshcat=meshcat,
scene_type=scene_type,
)
plant = scene.plant
sim = scene.simulator
root_context = scene.context
plant_context = plant.GetMyMutableContextFromRoot(root_context)
# Reset per-episode frame collection
if is_main:
current_episode_frames = []
K = int(cfg["data"].get("window_k", args.window_k))
H = int(cfg["data"].get("horizon_H", args.horizon_H))
dt = 1.0 / float(args.hz)
steps = int(10.0 * args.hz) # Default: 40 timesteps (10.0 s at 4fps)
# Helper to access model attributes (handles DataParallel wrapping)
def get_model_attr(model, attr):
"""Access model attribute, handling DataParallel wrapping."""
if isinstance(model, torch.nn.DataParallel):
return getattr(model.module, attr)
return getattr(model, attr)
# Language/instruction -> token/embedding (for FM policy)
language = language_eval
token = torch.tensor([hash(language) % 512], dtype=torch.long, device=device)
z_l = get_model_attr(model, 'E_l')(token)
# Load goal image for both MPC and FM (Meta's VJEPA2-AC approach)
# Goal image is stored per scene (not per episode)
goal_img_front = None
goal_patches_front = None
z_goals = [] # List of goal encodings for multi-goal planning
goal_timesteps = [] # Timesteps per goal
multi_goal_mode = False
prev_mpc_mean = None # Warm start state for MPC
# Determine scene directory from current scene being evaluated
# Use current_scene_name (from scene loop) instead of args.scene
# This ensures correct goal loading in multi-scene mode
goal_dir = f"episodes/{current_scene_name}"
# test-place.py: Placement-only - skip GRASP goal, only load NEAR and FINAL
# Load both front and wrist goals for multi-view conditioning
multi_goal_files = [
# Skip grasp goal - letter is already grasped
(("front_goal_near.png", "wrist_goal_near.png"), "near target sub-goal"),
(("front_goal_final.png", "wrist_goal_final.png"), "final goal"),
]
import imageio
model_unwrapped = model.module if isinstance(model, torch.nn.DataParallel) else model
use_patch_mpc = getattr(model_unwrapped, 'use_patch_token_mpc', False)
# Try to load multi-goal images (both front and wrist views)
for (goal_file_front, goal_file_wrist), goal_desc in multi_goal_files:
goal_path_front = os.path.join(goal_dir, goal_file_front)
goal_path_wrist = os.path.join(goal_dir, goal_file_wrist)
z_goal_front = None
z_goal_wrist = None
# Load and encode front goal if available
if os.path.exists(goal_path_front):
goal_img = imageio.imread(goal_path_front)
if is_main:
print(f"Found front goal: {goal_path_front}, shape={goal_img.shape}")
if goal_img.shape[-1] == 4:
goal_img = goal_img[:, :, :3]
# ImageNet normalization is handled internally by VJEPA2HubEncoder
goal_img_tensor = torch.from_numpy(goal_img / 255.0).to(
device=device, dtype=torch.float32, non_blocking=True
).unsqueeze(0).permute(0, 3, 1, 2) # (1, C, H, W)
# Encode as patches or pooled latent based on model type
if use_patch_mpc and hasattr(get_model_attr(model, 'E_v'), 'encode_patches'):
goal_img_batch = goal_img_tensor.unsqueeze(1) # (1, 1, C, H, W)
z_goal_front = get_model_attr(model, 'E_v').encode_patches(goal_img_batch).squeeze(1)
# Apply layer_norm to encoder output (Meta's normalize_reps=True)
z_goal_front = F.layer_norm(z_goal_front, (z_goal_front.size(-1),))
else:
z_goal_front = get_model_attr(model, 'E_v')(goal_img_tensor)
elif is_main:
print(f"Missing front goal: {goal_path_front}")
# Load and encode wrist goal if available
if os.path.exists(goal_path_wrist):
goal_img = imageio.imread(goal_path_wrist)
if is_main:
print(f"Found wrist goal: {goal_path_wrist}, shape={goal_img.shape}")
if goal_img.shape[-1] == 4:
goal_img = goal_img[:, :, :3]
# ImageNet normalization is handled internally by VJEPA2HubEncoder
goal_img_tensor = torch.from_numpy(goal_img / 255.0).to(
device=device, dtype=torch.float32, non_blocking=True
).unsqueeze(0).permute(0, 3, 1, 2) # (1, C, H, W)
# Encode as patches or pooled latent based on model type
if use_patch_mpc and hasattr(get_model_attr(model, 'E_v'), 'encode_patches'):
goal_img_batch = goal_img_tensor.unsqueeze(1) # (1, 1, C, H, W)
z_goal_wrist = get_model_attr(model, 'E_v').encode_patches(goal_img_batch).squeeze(1)
# Apply layer_norm to encoder output (Meta's normalize_reps=True)
z_goal_wrist = F.layer_norm(z_goal_wrist, (z_goal_wrist.size(-1),))
else:
z_goal_wrist = get_model_attr(model, 'E_v')(goal_img_tensor)
elif is_main:
print(f"Missing wrist goal: {goal_path_wrist}")
# Use front goal if available, otherwise fall back to wrist
# At test time, front camera is typically the primary view
if z_goal_front is not None:
goal_encoded = z_goal_front
if is_main:
print(f"Loaded {goal_desc} from {goal_file_front}")
elif z_goal_wrist is not None:
goal_encoded = z_goal_wrist
if is_main:
print(f"Loaded {goal_desc} from {goal_file_wrist} (fallback)")
else:
continue # Skip this goal if neither view is available
z_goals.append(goal_encoded)
# test-place.py: If we loaded 2 goals (NEAR + FINAL), use multi-goal mode
if is_main:
print(f"Total goals loaded: {len(z_goals)}. Multi-goal mode: {len(z_goals) == 2}")
if len(z_goals) == 2:
multi_goal_mode = True
# test-place.py: Placement-only fractional goal conditioning
# NEAR goal: first 70% of episode (args.near_fraction)
# FINAL goal: last 30% of episode (args.place_fraction)
eval_clip_seconds = getattr(args, 'eval_clip_seconds', 10.0)
eval_episode_frames = int(eval_clip_seconds * args.hz)
# Use configurable fractions (default 70/30)
near_frames = int(args.near_fraction * eval_episode_frames)
place_frames = eval_episode_frames - near_frames
goal_timesteps = [near_frames, place_frames]
if is_main:
print(f"Placement-only multi-goal planning (letter starts grasped)")
print(f"Clip duration: {eval_clip_seconds:.1f}s ({eval_episode_frames} frames at {args.hz}fps)")
print(f"Goal fractions: [{args.near_fraction:.0%}, {args.place_fraction:.0%}] = {goal_timesteps} timesteps")
print(f"Phases: NEAR={near_frames/args.hz:.1f}s, FINAL={place_frames/args.hz:.1f}s")
else:
# Fallback to single goal (try both front and wrist)
goal_img_path_front = os.path.join(goal_dir, "front_goal.png")
goal_img_path_wrist = os.path.join(goal_dir, "wrist_goal.png")
z_goal_front = None
z_goal_wrist = None
# Load and encode front goal if available
if os.path.exists(goal_img_path_front):
goal_img_front = imageio.imread(goal_img_path_front)
# Ensure RGB (drop alpha if present)
if goal_img_front.shape[-1] == 4:
goal_img_front = goal_img_front[:, :, :3]
# Encode goal image as patch tokens or pooled latent
goal_img_tensor = torch.from_numpy(goal_img_front / 255.0).to(
device=device, dtype=torch.float32, non_blocking=True
).unsqueeze(0).permute(0, 3, 1, 2) # (1, C, H, W)
# For patch-token MPC: encode as patches
if use_patch_mpc and hasattr(get_model_attr(model, 'E_v'), 'encode_patches'):
goal_img_batch = goal_img_tensor.unsqueeze(1) # (1, 1, C, H, W)
z_goal_front = get_model_attr(model, 'E_v').encode_patches(goal_img_batch).squeeze(1)
# Apply layer_norm to encoder output (Meta's normalize_reps=True)
z_goal_front = F.layer_norm(z_goal_front, (z_goal_front.size(-1),))
else:
# For latent-space MPC or FM: encode as pooled latent
z_goal_front = get_model_attr(model, 'E_v')(goal_img_tensor)
# Load and encode wrist goal if available
if os.path.exists(goal_img_path_wrist):
goal_img_wrist = imageio.imread(goal_img_path_wrist)
# Ensure RGB (drop alpha if present)
if goal_img_wrist.shape[-1] == 4:
goal_img_wrist = goal_img_wrist[:, :, :3]
# Encode goal image as patch tokens or pooled latent
goal_img_tensor = torch.from_numpy(goal_img_wrist / 255.0).to(
device=device, dtype=torch.float32, non_blocking=True
).unsqueeze(0).permute(0, 3, 1, 2) # (1, C, H, W)
# For patch-token MPC: encode as patches
if use_patch_mpc and hasattr(get_model_attr(model, 'E_v'), 'encode_patches'):
goal_img_batch = goal_img_tensor.unsqueeze(1) # (1, 1, C, H, W)
z_goal_wrist = get_model_attr(model, 'E_v').encode_patches(goal_img_batch).squeeze(1)
# Apply layer_norm to encoder output (Meta's normalize_reps=True)
z_goal_wrist = F.layer_norm(z_goal_wrist, (z_goal_wrist.size(-1),))
else:
# For latent-space MPC or FM: encode as pooled latent
z_goal_wrist = get_model_attr(model, 'E_v')(goal_img_tensor)
# Use front goal if available, otherwise fall back to wrist
# At test time, front camera is typically the primary view
if z_goal_front is not None:
z_goals = [z_goal_front]
if is_main:
print(f"Loaded goal from {goal_img_path_front}")
print(f"Goal shape: {z_goal_front.shape}")
elif z_goal_wrist is not None:
z_goals = [z_goal_wrist]
if is_main:
print(f"Loaded goal from {goal_img_path_wrist} (fallback)")
print(f"Goal shape: {z_goal_wrist.shape}")
else:
if is_main:
print(f"No goal images found in {goal_dir}")
if not args.use_mpc:
print(f"FM will use language embedding as fallback")
else:
print(f"MPC will use language embedding as fallback (not recommended)")
if z_goals:
# Single goal: use configurable clip length (default: 10 seconds at 4fps)
eval_clip_seconds = getattr(args, 'eval_clip_seconds', 10.0)
goal_timesteps = [int(eval_clip_seconds * args.hz)]
# Adjust episode length based on goal mode
if multi_goal_mode:
# Use the planned duration for multi-goal tasks
steps = sum(goal_timesteps)
if is_main:
print(f"Adjusted episode length to {steps} timesteps ({steps/args.hz:.1f}s) for multi-goal task")
z_hist = deque(maxlen=K + 1)
# For action-conditioned variants: track end-effector states and actions
if get_model_attr(model, 'use_action_conditioning'):
ee_state_hist = deque(maxlen=K + 1)
ee_delta_hist = deque(maxlen=K + 1)
# Boot with the first observation
img_f = render_rgb(scene.ports["rgb_front"], root_context)
img_w = render_rgb(scene.ports["rgb_wrist"], root_context)
if current_episode_frames is not None:
current_episode_frames.append(img_f[:, :, :3].copy())
q0 = plant.GetPositions(plant_context).copy()
# Match evaluation state to checkpoint's expected state_dim (e.g., 9-DoF state_q)
if q0.shape[0] > state_dim:
q0_state = q0[:state_dim]
elif q0.shape[0] < state_dim:
q0_state = np.zeros(state_dim, dtype=q0.dtype)
q0_state[: q0.shape[0]] = q0
else:
q0_state = q0
# Encode front view only (test time uses front camera, no multi-view fusion)
# During training, each view is treated independently; at test time we use front
# ImageNet normalization is handled internally by VJEPA2HubEncoder
img_f_tensor = torch.from_numpy(img_f / 255.0).to(device=device, dtype=torch.float32, non_blocking=True).unsqueeze(0).permute(0, 3, 1, 2)
z_v0 = get_model_attr(model, 'E_v')(img_f_tensor)
z_s0 = get_model_attr(model, 'E_s')(torch.from_numpy(q0_state).float().to(device).unsqueeze(0))
# Fuse vision and state using single-view fusion (2*d -> d)
z_t = get_model_attr(model, 'Fusion_single')(torch.cat([z_v0, z_s0], dim=-1))
for _ in range(K + 1):
z_hist.append(z_t)
# Initialize end-effector tracking for action-conditioned variants
if get_model_attr(model, 'use_action_conditioning'):
from pydrake.all import JacobianWrtVariable, RotationMatrix, RigidTransform
if plant.HasBodyNamed("panda_hand"):
eeF = plant.GetBodyByName("panda_hand").body_frame()
elif plant.HasBodyNamed("body"):
eeF = plant.GetBodyByName("body").body_frame()
else:
eeF = plant.GetBodyByName("panda_link8").body_frame()
X_WE_0 = plant.CalcRelativeTransform(plant_context, plant.world_frame(), eeF)
ee_pos_0 = X_WE_0.translation()
ee_rot_0 = X_WE_0.rotation().ToRollPitchYaw().vector()
ee_gripper_0 = q0[7] if len(q0) >= 9 else 0.0
# Use World Frame directly - training data uses plant.world_frame()
# No coordinate transformation needed (verified in episode_generation.py)
ee_state_0 = np.concatenate([ee_pos_0, ee_rot_0, [ee_gripper_0]])
ee_state_0_t = torch.from_numpy(ee_state_0).float().to(device).unsqueeze(0) # (1, 7)
for _ in range(K + 1):
ee_state_hist.append(ee_state_0_t)
ee_delta_hist.append(torch.zeros(1, 7, device=device)) # Zero action initially
# Closed-loop control with simple safety fallback
from pydrake.all import JacobianWrtVariable, RotationMatrix, RigidTransform
if plant.HasBodyNamed("panda_hand"):
eeF = plant.GetBodyByName("panda_hand").body_frame()
elif plant.HasBodyNamed("body"):
eeF = plant.GetBodyByName("body").body_frame()
else:
eeF = plant.GetBodyByName("panda_link8").body_frame()
hazard_thresh = -0.005
inspector = scene.scene_graph.model_inspector()
def _is_manip_geom(geom_id):
name = inspector.GetName(geom_id)
return ("panda" in name) or ("wsg" in name) or ("hand" in name) or ("gripper" in name)
fallback_goal = None
panda_port = None
hand_port = None # Franka hand or WSG gripper
use_station_control = (scene_type == "franka_reference")
if use_station_control:
diagram = scene.diagram
try:
num_in_ports = diagram.num_input_ports()
except AttributeError:
num_in_ports = diagram.NumInputPorts()
for i in range(num_in_ports):
port = diagram.get_input_port(i)
port_name = port.get_name()
if "panda.position" in port_name:
panda_port = port
elif "hand.position" in port_name:
hand_port = port
elif "wsg.position" in port_name:
hand_port = port # Backward compatibility with WSG
if panda_port is None and hand_port is None:
use_station_control = False
# Track trajectory metrics
min_distances = []
actions_taken = []
fallback_activations = 0
t_rollout_start = time.time()
# Prepare final goal for distance checking
final_goal = subgoals[-1]