File size: 77,914 Bytes
d18db74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
import os
import socket
import numpy as np
import hydra
import torch
import cv2
import h5py
import uuid
import json
import dill

import robomimic.utils.file_utils as FileUtils
from omegaconf import open_dict, OmegaConf
from contextlib import nullcontext
from pathlib import Path
from hydra.core.hydra_config import HydraConfig
from hydra import compose

from gym.vector.vector_env import VectorEnv
from stable_baselines3.common.vec_env import VecEnv

import robomimic.utils.obs_utils as ObsUtils

from sim_pipeline.eval.rollout_env import PossibleVecEnv
from sim_pipeline.eval.rollout_policies import *
from sim_pipeline.eval.rollout import rollout
from sim_pipeline.configs._evaluation.eval_base import EvaluationConfig
from sim_pipeline.configs.constants import PolicyType, CombinedPolicyType, ImitationAlgorithm, ROLLOUT_DATA_DIR
from sim_pipeline.envs.robosuite_wrapper import RobomimicObsWrapper
from sim_pipeline.envs.make_env import make_env, make_vec_env
from sim_pipeline.eval.rollout_stats import RolloutStats
from sim_pipeline.utils.rollout_utils import add_trajectory_to_dataset, merge_obs_specs
from sim_pipeline.utils.train_utils import get_latest_sb_policy, get_latest_robomimic_policy, get_latest_diffusion_policy, get_latest_ogbench_policy
from sim_pipeline.utils.experiment import setup_experiment
from sim_pipeline.utils.video_writer import video_writer_manager
from sim_pipeline.utils.diffusion_utils import get_policy_class, get_workspace
from sim_pipeline.data_manager.modify_dataset import fill_metadata
from sim_pipeline.data_manager.dataset_metadata_enums import *
from sim_pipeline.data_manager.edit_dataset_description import edit_dataset_description
from sim_pipeline.model_manager.get_model import get_model
from sim_pipeline.data_manager.get_dataset import get_dataset

def get_env(policy_type: PolicyType, config: EvaluationConfig, obs_modality_specs=None, n_envs_override: int = None) -> RobomimicObsWrapper | VecEnv | VectorEnv:
    if n_envs_override is not None:
        n_envs = n_envs_override
    else:
        n_envs = config.exp.num_workers
    if policy_type == PolicyType.ROBOMIMIC:
        if n_envs > 1:
            env: VectorEnv = make_vec_env(
                env_config=config.env,
                num_workers=n_envs,
                seed=config.exp.eval_seed,
                device_id=config.exp.device_id,
                flatten_obs=False,
                use_gym_vec_env=True,
                gymnasium_api=False,
            )
        else:
            env: RobomimicObsWrapper = make_env(
                env_config=config.env,
                seed=config.exp.eval_seed,
                device_id=config.exp.device_id,
                flatten_obs=False,
            )
    elif policy_type == PolicyType.STABLE_BASELINES:
        if n_envs > 1:
            env: VecEnv = make_vec_env(
                env_config=config.env,
                num_workers=n_envs,
                seed=config.exp.eval_seed,
                device_id=config.exp.device_id,
                flatten_obs=True,
                use_gym_vec_env=False,
                mp_context='forkserver',
                obs_modality_specs=obs_modality_specs,
                gymnasium_api=False,
            )
        else:
            env: RobomimicObsWrapper = make_env(
                env_config=config.env,
                seed=config.exp.eval_seed,
                device_id=config.exp.device_id,
                flatten_obs=True,
            )
    elif policy_type == PolicyType.DIFFUSION or policy_type == PolicyType.COMPOSITE or policy_type == PolicyType.OGBENCH:
        if n_envs > 1:
            env: VectorEnv = make_vec_env(
                env_config=config.env,
                num_workers=n_envs,
                seed=config.exp.eval_seed,
                device_id=config.exp.device_id,
                flatten_obs=False,
                use_gym_vec_env=True,
                mp_context='forkserver',
                obs_modality_specs=obs_modality_specs,
                gymnasium_api=False,
            )
        else:
            env: RobomimicObsWrapper = make_env(
                env_config=config.env,
                seed=config.exp.eval_seed,
                device_id=config.exp.device_id,
                flatten_obs=False,
            )
    elif policy_type == PolicyType.PD:
        if n_envs > 1:
            env: VectorEnv = make_vec_env(
                env_config=config.env,
                num_workers=n_envs,
                seed=config.exp.eval_seed,
                device_id=config.exp.device_id,
                flatten_obs=False,
                use_gym_vec_env=True,
                mp_context='forkserver',
                obs_modality_specs=obs_modality_specs,
                gymnasium_api=False,
            )
        else:
            env: RobomimicObsWrapper = make_env(
                env_config=config.env,
                seed=config.exp.eval_seed,
                device_id=config.exp.device_id,
                flatten_obs=False,
            )
    else:
        raise NotImplementedError
    return env


def get_policy_dir(policy_type: PolicyType, config: EvaluationConfig) -> Path | None:
    if config.exp.use_model_manager and not policy_type in [PolicyType.PD, PolicyType.COMPOSITE, PolicyType.STABLE_BASELINES, PolicyType.OGBENCH]:
        identifier = config.exp.date_string
        if identifier:
            model_path = get_model(config.name, identifier)
        else:
            model_path = get_model(config.name)
        return Path(model_path)
    
    if config.exp.model_path:
        return Path(config.exp.model_path)
    
    log_path = config.exp.logdir
    match policy_type:
        case PolicyType.STABLE_BASELINES:
            logdir = Path(log_path) / f'{config.name}' / f'{config.exp.seed}'
        case PolicyType.ROBOMIMIC | PolicyType.DISCRIMINATOR:
            logdir: Path = Path(log_path) / f'{config.name}' / config.exp.date_string
        case PolicyType.DIFFUSION:
            logdir: Path = Path(log_path) / f'{config.name}' / config.exp.date_string
        case PolicyType.OGBENCH:
            logdir: Path = Path(log_path) / f'{config.name}'
        case PolicyType.PD:
            logdir = None
        case PolicyType.COMPOSITE:
            logdir: Path = Path(log_path) / config.name
            if not logdir.exists():
                logdir.mkdir()
        case _:
            raise NotImplementedError
    return logdir


def load_policy(policy_type: PolicyType, config: EvaluationConfig, policy_dir: Path, env, device: torch.device):
    match policy_type:
        case PolicyType.STABLE_BASELINES:
            algo = config.training.algo.get_algo()
            ckpt_path = get_latest_sb_policy(policy_dir / 'policy' / '_step_')
            model = algo.load(ckpt_path, device=device, env=env)
            
            return model
        case PolicyType.ROBOMIMIC | PolicyType.DISCRIMINATOR:
            if policy_dir.suffix == '.pth' and policy_dir.is_file():     # rsm_rise: a checkpoint file directly
                ckpt_path = policy_dir
            else:
                ckpt_path = get_latest_robomimic_policy(policy_dir / 'models')
            
            policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=ckpt_path, device=device, verbose=True,
                                                                 discriminator=policy_type == PolicyType.DISCRIMINATOR)
            # rsm_rise (stream D): the eval config's planner keys (training.plan_* / rsm_*) override the
            # checkpoint's algo config -> best-of-N over the diffusion sampler with the RSM scorer.
            algo = getattr(policy, 'policy', None)
            if hasattr(algo, 'configure_planner'):
                from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import planner_kwargs
                kw = planner_kwargs(config.training)
                if kw:
                    algo.configure_planner(**kw)
                    print(f"[rsm_rise] planner configured: plan_n={kw.get('plan_n')} rule={kw.get('plan_rule')} "
                          f"backend={kw.get('rsm_backend')} mode={kw.get('plan_mode')} depth={kw.get('plan_depth')} "
                          f"beta={kw.get('plan_beta')} rsm_ckpt={kw.get('rsm_ckpt')!r}")

            # rsm_rise gen_q#274 (stream NEW_BASELINES): Diffusion Forcing run AS A PLANNER.
            # Driven by ENV VARS, not by a config key, deliberately: the training-config schema is
            # being edited concurrently by the gen_q#273 stream and an additive env-var hook cannot
            # collide with it.  Default off -- with RR_DF_CKPT unset this block is a no-op and every
            # existing cell takes byte-identical code paths.
            # DF is not a scorer backend: it proposes its OWN actions (see code/df_rise/df_policy.py),
            # so it REPLACES get_action rather than ranking the proposer's candidates, and its
            # candidate count is reported separately and never compared silently against a
            # 128-candidate value column.
            import os as _os
            if _os.environ.get("RR_DF_CKPT"):
                import sys as _sys
                _sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/df_rise")
                # $ROOT/env does not ship rotary_embedding_torch, which upstream's
                # models/diffusion.py imports unconditionally via unet3d.  Vendored pure-python copy
                # (code/df_rise/_deps/PROVENANCE.txt); appended INSIDE this block so a non-DF cell is
                # untouched, and APPENDED (not inserted) so it can never shadow an env package.
                _sys.path.append("/proj/dmfexp/zwhong/rsm_rise/code/df_rise/_deps")
                # gen_q#274, measured LSF 1881480 13:35Z: a cell that leaves `training.plan_n` unset
                # gets RobomimicSamplingRolloutPolicy (eval.py:493-501, chosen for IDQL when plan_n is
                # None).  That class duplicates the observation 128x, calls get_action on the batch and
                # then picks the best candidate WITH THE RISE CRITIC (:94-111).  A DF cell run that way
                # would be "DF proposes, the RISE value function selects" while the caption said DF
                # selects its own -- the exact silent substitution #274 forbids.  Setting plan_n (any
                # value; 1 keeps the RSM planner itself off) selects the PLAIN RobomimicRolloutPolicy,
                # whose predict() calls get_action once and executes the returned chunk.  Refuse
                # rather than measure the wrong thing.
                _pn_df = config.training.get("plan_n", None) if hasattr(config.training, "get") else None
                if _pn_df is None:
                    raise RuntimeError(
                        "RR_DF_CKPT is set but training.plan_n is unset, so this cell would run "
                        "RobomimicSamplingRolloutPolicy: DF's actions would be RANKED BY THE RISE "
                        "CRITIC instead of by DF's own guidance, and the row would not be a DF row.  "
                        "Pass training.plan_n=1 (the RSM planner stays off; this only selects the "
                        "plain rollout policy).")
                import df_policy as _dfp
                _df = _dfp.install(
                    policy,
                    ckpt=_os.environ["RR_DF_CKPT"],
                    feat_stats=_os.environ["RR_DF_FEAT_STATS"],
                    horizon_frames=int(_os.environ.get("RR_DF_HORIZON", "20")),
                    guidance_scale=float(_os.environ.get("RR_DF_GUIDANCE", "1.0")),
                    gamma=float(_os.environ.get("RR_DF_GAMMA", "0.95")),
                    n_plans=int(_os.environ.get("RR_DF_NPLANS", "128")),
                    execute_frames=int(_os.environ.get("RR_DF_EXECUTE", "8")),
                    device=str(device),
                    seed=int(_os.environ.get("RR_DF_SEED", "0")),
                    diag_path=_os.environ.get("RR_DF_DIAG", ""),
                    # RR_DF_SELECT=random -> the random-of-N control on IDENTICAL candidates.
                    select=_os.environ.get("RR_DF_SELECT", "argmax"),
                )
                print(f"[gen_q#274] Diffusion Forcing PLANNER installed: ckpt={_os.environ['RR_DF_CKPT']} "
                      f"H={_df.H} guidance={_df.guidance_scale} gamma={_df.gamma} "
                      f"n_plans={_df.n_plans} execute={_df.execute_frames} select={_df.select} "
                      f"train_step={_df.step}")

            # rsm_rise gen_q#274 (stream NEW_BASELINES): TD-MPC2, BOTH reported configurations.
            # Same env-var discipline as the DF block above and for the same reason (gen_q#273 is
            # editing the training-config schema concurrently).  Default off -- with RR_TD_CKPT
            # unset this block is a no-op and every existing cell takes byte-identical code paths.
            #   RR_TD_MODE=score  -> configuration (a), the SHARED-CANDIDATE column.  The proposer,
            #       the candidate set (plan_n, unchanged), the selection rule and the harness are all
            #       untouched; only the function that ranks the 128 candidates is swapped, by
            #       pre-populating the planner's scorer cache.  This is close to DINO-WM plus a value
            #       head and the cell JSON's describe() says exactly that.
            #   RR_TD_MODE=plan   -> configuration (b), TD-MPC2's own MPPI/CEM planner seeded by the
            #       RISE actor as policy prior.  It PROPOSES its own actions, so like DF it replaces
            #       get_action, and its sample count / horizon / iterations are disclosed in the cell
            #       JSON.  Its budget is NOT 128 candidates and must never be printed as if it were.
            if _os.environ.get("RR_TD_CKPT"):
                import sys as _sys
                _sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/tdmpc2_rise")
                _td_mode = _os.environ.get("RR_TD_MODE", "score")
                _algo = getattr(policy, "policy", None)
                if _td_mode == "score":
                    import td_scorer as _tds
                    if _algo is None or not hasattr(_algo, "_get_scorer"):
                        raise RuntimeError("RR_TD_MODE=score needs a policy with the RSM planner "
                                           "(rsm_planner.PlannerMixin); got %r" % type(_algo))
                    # gen_q#274 run 5: pre-populating `_planner_scorer` only has an effect if the
                    # planner actually RANKS candidates.  `PlannerMixin.planning_enabled` is
                    # `plan_n is not None and plan_n > 1` (rsm_planner.py:267-269) and
                    # `plan_get_action` short-circuits to a single unranked sample when N <= 1
                    # (:341-345).  So a cell whose config left plan_n unset would run the PLAIN RISE
                    # policy, print the banner below, write a TD-MPC2-labelled cell JSON and never
                    # once call TD-MPC2.  That is the silent no-op #274 forbids -- refuse instead.
                    _pn = _algo.planner_cfg().get("plan_n")
                    if not _algo.planning_enabled:
                        raise RuntimeError(
                            "RR_TD_MODE=score requires the cell's own planner to be ON "
                            f"(training.plan_n > 1); got plan_n={_pn!r}, so plan_get_action would "
                            "return an unranked sample and the TD-MPC2 scorer would never be "
                            "called.  Set plan_n (128 for the shared-candidate column).")
                    _sc = _tds.make_td_scorer(
                        _os.environ["RR_TD_CKPT"], _os.environ["RR_TD_FEAT_STATS"],
                        device=str(device),
                        mode=_os.environ.get("RR_TD_PLAN_MODE", "d1"),
                        depth=int(_os.environ.get("RR_TD_DEPTH", "1")),
                        n_particles=int(_os.environ.get("RR_TD_PARTICLES", "1")),
                        chunk=int(_os.environ.get("RR_TD_CHUNK", "8")),
                        adim=int(_os.environ.get("RR_TD_ADIM", "7")),
                        score_kind=_os.environ.get("RR_TD_SCORE", "prob"))
                    # gen_q#274 blocker item 3 (owner, 2026-09-23 19:45Z): RR_TD_DUAL_DWM=<dinowm ckpt>
                    # additionally scores THE SAME 128 candidates at THE SAME anchor with the published
                    # DINO-WM read-out and writes the rank correlation to RR_TD_DUAL_OUT.  The cell's own
                    # selection is untouched -- the wrapper returns TD-MPC2's scores -- but it costs the
                    # second read-out's forward passes per decision, so a dual run is a DIAGNOSTIC and its
                    # payload writes it to td274smoke/, never into a published column.
                    if _os.environ.get("RR_TD_DUAL_DWM"):
                        import dual_scorer as _dual
                        _sec = _dual.build_dwm_secondary(
                            _os.environ["RR_TD_DUAL_DWM"], _os.environ["RR_TD_FEAT_STATS"],
                            hop_ckpt=_os.environ.get("RR_TD_DUAL_HOP") or None, device=str(device),
                            depth=int(_os.environ.get("RR_TD_DUAL_DEPTH", "4")),
                            beta=float(_os.environ.get("RR_TD_DUAL_BETA", "0.95")),
                            gamma=float(_os.environ.get("RR_TD_DUAL_GAMMA", "0.99")),
                            n_particles=int(_os.environ.get("RR_TD_DUAL_PARTICLES", "16")),
                            flow_steps=int(_os.environ.get("RR_TD_DUAL_FLOW", "8")))
                        # gen_q#274 run 38 -- RR_TD_DUAL_SWAP=1 exchanges WHICH read-out drives the
                        # selection.  Nothing about either estimator changes: both are built exactly
                        # as above, from the same checkpoints with the same knobs, and DualScorer
                        # still returns the PRIMARY's scores and records the other's ranks.  Only the
                        # argument order is swapped.
                        #
                        # WHY IT IS THE INSTRUMENT THAT LOCALISES THE DEFECT.  status/nb/td_dwm_rho.txt
                        # carries its own caveat: every anchor in the un-swapped run lies on cfg(a)'s
                        # OWN trajectory, and that trajectory fails, so agreement there is agreement
                        # about states cfg(a) already lost.  With DINO-WM driving, the anchors are the
                        # states the PUBLISHED column actually visits, and two things are read at once:
                        #   (i) the matched-anchor rank correlation the un-swapped table says is missing;
                        #   (ii) a WITHIN-HARNESS reproduction -- this cell's success rate should come
                        #        out near DINO-WM's published 31.6 / 21.1.  If it does, the eval
                        #        harness and the candidate pool are exonerated and the defect is
                        #        cfg(a)'s ordering; if it does not, the published comparison has a
                        #        confound and NO cfg(a) number may be set beside a DINO-WM number
                        #        until it is found.  Either outcome is a result.
                        #
                        # LABELLING.  A swapped run is NOT a TD-MPC2 score: DINO-WM chooses every
                        # action.  Its payload sets RR_TD_SMOKE=1 and a -DUALSWAP suffix, so it lands
                        # in td274smoke/ under a name no table reads and can never be pooled into the
                        # cfg(a) column.
                        _swap = _os.environ.get("RR_TD_DUAL_SWAP", "0") == "1"
                        if _swap:
                            _sc = _dual.DualScorer(
                                _sec, _sc, _os.environ.get("RR_TD_DUAL_OUT", ""),
                                "dinowm_published", "tdmpc2_cfg_a",
                                meta={"td_ckpt": _os.environ["RR_TD_CKPT"],
                                      "dwm_ckpt": _os.environ["RR_TD_DUAL_DWM"],
                                      "swapped": True,
                                      "acting_readout": "dinowm_published",
                                      "cell": _os.environ.get("RR_TD_DUAL_CELL", "")})
                            print("[gen_q#274] DUAL READ-OUT SWAPPED: DINO-WM SELECTS, TD-MPC2 cfg(a) "
                                  "observes the same candidates at DINO-WM's own anchors -> "
                                  f"{_os.environ.get('RR_TD_DUAL_OUT','<no out path>')}  "
                                  "(this cell's success rate is DINO-WM's, NOT TD-MPC2's)")
                        else:
                            _sc = _dual.DualScorer(
                                _sc, _sec, _os.environ.get("RR_TD_DUAL_OUT", ""),
                                "tdmpc2_cfg_a", "dinowm_published",
                                meta={"td_ckpt": _os.environ["RR_TD_CKPT"],
                                      "dwm_ckpt": _os.environ["RR_TD_DUAL_DWM"],
                                      "swapped": False,
                                      "acting_readout": "tdmpc2_cfg_a",
                                      "cell": _os.environ.get("RR_TD_DUAL_CELL", "")})
                            print("[gen_q#274] DUAL READ-OUT on: TD-MPC2 selects, DINO-WM observes the same "
                                  f"candidates -> {_os.environ.get('RR_TD_DUAL_OUT','<no out path>')}")
                    # the planner's own cache slot: `_get_scorer` returns this instead of building an
                    # RSMScorer, and `plan_get_action` is otherwise untouched.
                    _algo._planner_scorer = _sc
                    print(f"[gen_q#274] TD-MPC2 SCORER installed (configuration (a), shared candidates): "
                          f"plan_n={_pn} (the SAME candidate set the RSM/DINO-WM columns rank) "
                          f"ckpt={_os.environ['RR_TD_CKPT']} gamma={_sc.gamma} "
                          f"H={1.0/(1.0-_sc.gamma):.1f} chunk={_sc.chunk} "
                          f"train_step={_sc.backend.step} -- n_particles/flow_steps/beta have no "
                          f"TD-MPC2 counterpart (td_backend.py N1-N3)")
                elif _td_mode == "plan":
                    import td_policy as _tdp
                    _tdpol = _tdp.install(
                        policy,
                        ckpt=_os.environ["RR_TD_CKPT"],
                        feat_stats=_os.environ["RR_TD_FEAT_STATS"],
                        plan_horizon=int(_os.environ.get("RR_TD_HP", "3")),
                        num_samples=int(_os.environ.get("RR_TD_SAMPLES", "512")),
                        num_elites=int(_os.environ.get("RR_TD_ELITES", "64")),
                        iterations=int(_os.environ.get("RR_TD_ITERS", "6")),
                        num_pi_trajs=int(_os.environ.get("RR_TD_PI_TRAJS", "24")),
                        temperature=float(_os.environ.get("RR_TD_TEMP", "0.5")),
                        select=_os.environ.get("RR_TD_SELECT", "mean"),
                        execute_frames=int(_os.environ.get("RR_TD_EXECUTE", "3")),
                        device=str(device),
                        seed=int(_os.environ.get("RR_TD_SEED", "0")),
                        prior_src=_os.environ.get("RR_TD_PRIOR", "rise_actor"),
                        diag_path=_os.environ.get("RR_TD_DIAG", ""))
                    _d = _tdpol.planner
                    # run 31: the banner must name the prior that ACTUALLY ran.  cfg(b) as gen_q#274
                    # defines it is "rise_actor"; "tdmpc2" is upstream's own published prior and
                    # "none" is pure CEM, both used only where our actor's 8-frame executed chunk
                    # cannot cover the planner horizon.  Reading a tdmpc2/none cell as cfg(b) would
                    # credit our actor with a row it never touched.
                    _ps = _tdpol.prior_src
                    _lbl = {"rise_actor": "MPPI/CEM with the RISE actor as policy prior",
                            "tdmpc2": "MPPI/CEM with TD-MPC2's OWN published prior (model.pi) -- NOT "
                                      "the RISE actor; run because the actor's executed chunk is 8 "
                                      "frames and cannot cover this horizon",
                            "none": "MPPI/CEM with NO policy prior (pure CEM) -- the prior ablation"}[_ps]
                    print(f"[gen_q#274] TD-MPC2 PLANNER installed (configuration (b), {_lbl}): "
                          f"prior_src={_ps} ckpt={_os.environ['RR_TD_CKPT']} "
                          f"Hp={_d.Hp} samples={_d.num_samples} elites={_d.num_elites} "
                          f"iters={_d.iterations} pi_trajs={_d.num_pi_trajs} "
                          f"execute={_tdpol.execute_frames} gamma={_d.gamma} "
                          f"H_terminal_q={1.0/(1.0-_d.gamma):.1f} "
                          f"rollouts_per_plan={_d.num_samples*_d.iterations} train_step={_tdpol.step}")
                else:
                    raise RuntimeError(f"RR_TD_MODE={_td_mode!r} is not score|plan")

            return policy
        case PolicyType.DIFFUSION:
            ckpt_path = get_latest_diffusion_policy(policy_dir / 'checkpoints')
            payload = torch.load(open(ckpt_path, 'rb'), pickle_module=dill)
            diffusion_cfg = payload['cfg']
            
            lowdim_keys = config.training.low_dim_keys
            rgb_keys = config.training.rgb_keys
            depth_keys = config.training.depth_keys
            
            # adapt old diffusion library configs
            with open_dict(diffusion_cfg):
                diffusion_cfg.debug = False
            
            workspace_cls = get_workspace(rgb_keys, lowdim_keys, depth_keys)
            workspace = workspace_cls(diffusion_cfg, output_dir=policy_dir)
            workspace.load_payload(payload)

            policy = workspace.model
            if diffusion_cfg.training.use_ema:
                policy = workspace.ema_model
            policy.to(device)
            policy.eval()
        case PolicyType.OGBENCH:
            from impls.utils.flax_utils import restore_agent
            from diffusion_policy.dataset.robomimic_replay_image_dataset import RobomimicReplayImageDataset
            from diffusion_policy.dataset.robomimic_replay_lowdim_dataset import RobomimicReplayLowdimDataset
            from torch.utils.data import DataLoader

            dataset_path = get_dataset(config.data)
            
            if config.training.rgb_keys:
                with h5py.File(dataset_path, 'r') as f:
                    data = f['data']
                    ep_keys = list(data.keys())
                    ep = data[ep_keys[0]]
                    action_shape = ep['actions'].shape[1:]
                    obs_shapes = {}
                    for key in config.training.low_dim_keys:
                        if key not in ep['obs'].keys():
                            raise ValueError(f"Key {key} not found in dataset")
                        obs_shapes[key] = {'shape': ep['obs'][key].shape[1:]}
                    for key in config.training.rgb_keys:
                        if key not in ep['obs'].keys():
                            raise ValueError(f"Key {key} not found in dataset")
                        # switch to channels first
                        obs_shapes[key] = ep['obs'][key].shape[1:]
                        obs_shapes[key] = {
                            'shape': (obs_shapes[key][2], obs_shapes[key][0], obs_shapes[key][1]),
                            'type': 'rgb',
                        }
                        
                    shape_meta = {
                        'obs': obs_shapes,
                        'action': {
                            'shape': action_shape,
                        }
                    }

                dataset = RobomimicReplayImageDataset(
                    shape_meta=shape_meta,
                    dataset_path=dataset_path,
                    horizon=1,
                    pad_before=0,
                    pad_after=0,
                    n_obs_steps=1,
                    abs_action=False,
                    use_cache=True,
                    seed=config.exp.seed,
                    val_ratio=0.0,
                    extra_info=True,
                    sample_goals=True,
                    p_currgoal=config.training.p_currgoal,
                    squeeze=True,
                )
            else:
                dataset = RobomimicReplayLowdimDataset(
                    obs_keys=config.training.low_dim_keys,
                    dataset_path=dataset_path,
                    horizon=1,
                    pad_before=0,
                    pad_after=0,
                    abs_action=False,
                    seed=config.exp.seed,
                    val_ratio=0.0,
                    extra_info=True,
                    sample_goals=True,
                    p_currgoal=config.training.p_currgoal,
                    squeeze=True,
                )

            train_dataloader = DataLoader(
                dataset,
                batch_size=config.training.batch_size,
                num_workers=0,
                shuffle=True,
                generator=torch.Generator(device=device),
            )
                
            example_batch = next(iter(train_dataloader))
            example_batch_np = {
                'observations': example_batch['obs'].numpy(),
                'actions': example_batch['action'].numpy(),
            }
            agent_class = config.training.algo.get_agent()
            agent = agent_class.create(
                seed=config.exp.seed,
                ex_observations=example_batch_np['observations'],
                ex_actions=example_batch_np['actions'],
                config=OmegaConf.to_container(config.training),
            )
            latest_epoch = get_latest_ogbench_policy(policy_dir / 'checkpoints', find_epoch=True)
            policy = restore_agent(agent, str(policy_dir / 'checkpoints'), latest_epoch)
        case PolicyType.PD:
            policy = None
        case _:
            raise NotImplementedError
    return policy
    
    
def create_combined_policy(
    policies,
    combined_policy_type: CombinedPolicyType,
    n_envs: int,
):
    match combined_policy_type:
        case CombinedPolicyType.HEURISTIC_RESET:
            policy = HeuristicResetPolicy(
                policies=policies,
                n_envs=n_envs
            )
        case CombinedPolicyType.HEURISTIC_RESET_SPLIT:
            policy = HeuristicResetSplitPolicy(
                policies=policies,
                n_envs=n_envs
            )
        case _:
            raise NotImplementedError
    return policy

    
def create_rollout_policy(
        policy, 
        policy_type: PolicyType,
        config: EvaluationConfig,
        n_obs_steps: int | None = None,
        action_chunking: bool = False,
        obs_keys: list[str] | None = None,
        lowdim: bool = False,
        manual_lookahead: bool = False,
        opex: bool = False,
        discriminator = None,
        expert_policy = None,
    ) -> RolloutPolicy:
    match policy_type:
        case PolicyType.STABLE_BASELINES:
            return StableBaselinesRolloutPolicy(
                policy, 
            )
        case PolicyType.ROBOMIMIC:
            if opex:
                return RobomimicOpexRolloutPolicy(
                    policy, 
                    action_chunking=action_chunking, 
                    n_obs_steps=n_obs_steps,
                    is_diffusion=config.training.algo.is_diffusion()
                )
            if manual_lookahead:
                return ManualLookaheadRolloutPolicy(
                    policy, 
                    action_chunking=action_chunking, 
                    n_obs_steps=n_obs_steps,
                    is_diffusion=config.training.algo.is_diffusion()
                )
            # rsm_rise gen_q#289 (worker WM_NATIVE) -- the APPENDIX row.  Placed BEFORE the plan_n
            # branch on purpose: this route has no proposer and no actor at all (CEM over the full
            # open-loop action sequence, the published DINO-WM / LeWM planner), so it must never fall
            # through into the shared-candidate path even if a cell also carries a stale plan_n.
            # Nothing below this branch is reachable from it and nothing in rsm_planner/rsm_scorer is
            # modified by it; the arm key starts with 'CEM' so it cannot pool with a shared arm.
            if str(config.exp.get('policy_mode', 'idql')) == 'wm_cem':
                # imported HERE, not in rollout_policies/__init__: the module pulls in rsm_scorer
                # (and through it rsm_libero), and an eager package-level import would put that on
                # the import path of every eval cell in the project, sibling streams included.
                from sim_pipeline.eval.rollout_policies.wm_native_cem_rollout_policy import (
                    WMNativeCEMRolloutPolicy)
                spec = str(config.exp.get('wm_cem_json', '') or '')
                if not spec:
                    raise ValueError("exp.policy_mode='wm_cem' needs exp.wm_cem_json "
                                     "(a JSON string, or a path to a .json, with at least "
                                     "{family, ckpt, feat_stats})")
                if os.path.exists(spec):
                    with open(spec) as f:
                        cem_cfg = json.load(f)
                else:
                    cem_cfg = json.loads(spec)
                if int(config.exp.num_workers) != 1:
                    raise ValueError("policy_mode='wm_cem' is single-env (the CEM state is "
                                     f"per-episode); got exp.num_workers={config.exp.num_workers}")
                cem_cfg.setdefault('seed', int(config.exp.eval_seed))
                return WMNativeCEMRolloutPolicy(
                    policy,
                    cfg=cem_cfg,
                    n_obs_steps=n_obs_steps,
                    is_diffusion=config.training.algo.is_diffusion(),
                )
            plan_n = config.training.get('plan_n', None) if hasattr(config.training, 'get') else None
            if plan_n is not None:
                # rsm_rise (stream D): the planner lives in the algo's get_action; plain rollout policy
                return RobomimicRolloutPolicy(
                    policy, 
                    action_chunking=action_chunking,
                    n_obs_steps=n_obs_steps,
                    is_diffusion=config.training.algo.is_diffusion()
                )
            if config.training.algo == ImitationAlgorithm.IDQL and config.exp.get('policy_mode', 'idql') != 'bc':
                return RobomimicSamplingRolloutPolicy(
                    policy, 
                    action_chunking=action_chunking, 
                    n_obs_steps=n_obs_steps,
                    is_diffusion=config.training.algo.is_diffusion(),
                    discriminator=discriminator,
                    expert_policy=expert_policy,
                )
            return RobomimicRolloutPolicy(
                policy, 
                action_chunking=action_chunking,
                n_obs_steps=n_obs_steps,
                is_diffusion=config.training.algo.is_diffusion()
            )
        case PolicyType.DIFFUSION:
            return DiffusionRolloutPolicy(
                policy, 
                action_chunking=action_chunking, 
                n_obs_steps=n_obs_steps, 
                obs_keys=obs_keys, 
                lowdim=lowdim
            )
        case PolicyType.OGBENCH:
            return OGBenchRolloutPolicy(
                policy,
                action_chunking=action_chunking,
                n_obs_steps=n_obs_steps,
                obs_keys=obs_keys,
                lowdim=lowdim,
            )
        case PolicyType.PD:
            return PDRolloutPolicy(
                policy=None,
                target_pos=config.exp.target_pos,
            )
        case _:
            raise NotImplementedError


def get_policy_info(policy_type: PolicyType, config: EvaluationConfig) -> tuple:
    action_chunking = True if policy_type in [PolicyType.DIFFUSION] else False
    n_obs_steps = config.training.obs_horizon if policy_type in [PolicyType.DIFFUSION] else None
    all_obs_keys = None
    only_lowdim = False
    obs_modality_specs = None
    if policy_type == PolicyType.DIFFUSION or policy_type == PolicyType.OGBENCH:
        lowdim_keys = OmegaConf.to_container(config.training.low_dim_keys)
        rgb_keys = OmegaConf.to_container(config.training.rgb_keys)
        depth_keys = OmegaConf.to_container(config.training.depth_keys)
        all_obs_keys = []
        for key in lowdim_keys + rgb_keys + depth_keys:
            if key in all_obs_keys:
                raise ValueError(f"Duplicate obs key {key}")
            all_obs_keys.append(key)
        only_lowdim = lowdim_keys and not rgb_keys and not depth_keys
        obs_modality_specs = RobomimicObsWrapper.get_specs_from_obs_keys(lowdim_keys, rgb_keys, depth_keys)
    elif policy_type == PolicyType.ROBOMIMIC:
        if config.training.algo in [ImitationAlgorithm.IQL_DIFFUSION, ImitationAlgorithm.IDQL, ImitationAlgorithm.IDQL_QSM]:
            action_chunking = True
            n_obs_steps = config.training.observation_horizon
    elif policy_type == PolicyType.PD:
        obs_modality_specs = {}
    return action_chunking, n_obs_steps, all_obs_keys, only_lowdim, obs_modality_specs


def get_policy(policy_type: PolicyType, config: EvaluationConfig, device: torch.device, discriminator=None, expert_policy=None) -> tuple[RolloutPolicy, dict | None]:
    if policy_type == PolicyType.COMPOSITE:
        all_policies = []
        all_obs_modality_specs = []
        for policy_cfg_str in config.exp.policy_configs:
            policy_cfg: EvaluationConfig = compose(policy_cfg_str)
            rollout_policy, obs_modality_specs = get_policy(policy_cfg.exp.policy_type, policy_cfg, device)
            if obs_modality_specs is not None:
                all_obs_modality_specs.append(obs_modality_specs)
            all_policies.append(rollout_policy)
                
        obs_modality_specs = merge_obs_specs(all_obs_modality_specs)
        
        rollout_policy = create_combined_policy(
            policies=all_policies,
            combined_policy_type=config.exp.combined_policy_type,
            n_envs=config.exp.num_workers,
        )
        
        return rollout_policy, obs_modality_specs

    # rsm_rise gen_q#264 -- IFQL AS PUBLISHED (column (a) of the flagship's IFQL pair).  IFQL is not a
    # robomimic algo and is trained in JAX, so it is loaded from its exported torch bundle
    # (exp.eval_ckpt, written by code/ifql/train_ifql.py) rather than through policy_from_checkpoint.
    # Because nothing initialises ObsUtils on this path, the obs specs are built here and returned, which
    # is what makes setup_eval call initialize_obs_utils_with_obs_specs before the env is created -- the
    # env's observation dict must be the processed one (images float CHW in [0, 1]) that the frozen-DINO
    # state expects.  Column (b) does not come through here at all: it is the ordinary robomimic path
    # with training.rsm_backend=ifql.
    if bool(config.exp.get('ifql_policy', False)):
        from sim_pipeline.eval.rollout_policies.ifql_rollout_policy import IFQLRolloutPolicy
        from robomimic.algo.rsm_scorer import CAMS, PROPRIO_KEYS
        ckpt = str(config.exp.get('eval_ckpt', '') or '')
        if not ckpt:
            raise ValueError('exp.ifql_policy=True needs exp.eval_ckpt = the ifql_bundle.pt')
        specs = RobomimicObsWrapper.get_specs_from_obs_keys(list(PROPRIO_KEYS), list(CAMS), [])
        rollout_policy = IFQLRolloutPolicy(
            ckpt=ckpt,
            feat_stats=str(config.exp.get('ifql_feat_stats', '') or ''),
            device=device,
            num_samples=int(config.exp.get('ifql_num_samples', 128)),
            eval_seed=int(config.exp.eval_seed),
        )
        print(f'[rsm_rise] IFQL policy (as published): ckpt={ckpt} '
              f'N={config.exp.get("ifql_num_samples", 128)} eval_seed={config.exp.eval_seed}')
        return rollout_policy, specs

    policy_dir = get_policy_dir(config.exp.policy_type, config)
    action_chunking, n_obs_steps, all_obs_keys, lowdim, obs_modality_specs = get_policy_info(config.exp.policy_type, config)

    if policy_type == PolicyType.STABLE_BASELINES:
        # we need env in order to load sb policy
        temp_env = get_env(config.exp.policy_type, config, obs_modality_specs, n_envs_override=1)
    else:
        temp_env = None
        
    policy = load_policy(
        policy_type=config.exp.policy_type, 
        config=config, 
        policy_dir=policy_dir, 
        env=temp_env, 
        device=device
    )
    if policy_type == PolicyType.DISCRIMINATOR:
        return policy, None
    
    if config.exp.use_discriminator:
        assert discriminator is not None, "Discriminator policy not found"
    
    rollout_policy = create_rollout_policy(
        policy, 
        policy_type=config.exp.policy_type,
        config=config,
        obs_keys=all_obs_keys,
        lowdim=lowdim,
        action_chunking=action_chunking,
        n_obs_steps=n_obs_steps,
        manual_lookahead=config.exp.manual_lookahead,
        opex=config.exp.opex,
        discriminator=discriminator,
        expert_policy=expert_policy,
    )
    
    return rollout_policy, obs_modality_specs
    

def setup_eval(config: EvaluationConfig):    
    device = setup_experiment(config.exp, eval=True)

    log_video = config.exp.log_video
    render = config.env.render
    
    policy_dir = get_policy_dir(config.exp.policy_type, config)
    
    if config.exp.use_discriminator:
        import copy
        discriminator_config = copy.deepcopy(config)
        discriminator_config.exp.policy_type = PolicyType.DISCRIMINATOR
        discriminator_config.name = config.exp.discriminator_name
        discriminator, _ = get_policy(PolicyType.DISCRIMINATOR, discriminator_config, device)
        
        expert_config = copy.deepcopy(config)
        expert_config.exp.policy_type = PolicyType.DIFFUSION
        expert_config.exp.use_discriminator = False
        expert_config.exp.discriminator_name = None
        expert_policy, _ = get_policy(PolicyType.DIFFUSION, expert_config, device)
    else:
        discriminator = None

    policy, obs_modality_specs = get_policy(config.exp.policy_type, config, device, discriminator=discriminator)

    if obs_modality_specs is not None:
        ObsUtils.initialize_obs_utils_with_obs_specs(obs_modality_specs)
    env = get_env(config.exp.policy_type, config, obs_modality_specs)
    env = PossibleVecEnv(env)

    # human render takes precedence over video recording
    if log_video and not render:
        video_dir: Path = policy_dir / 'videos_eval'
    
        if not video_dir.exists():
            video_dir.mkdir()
            
        default_size = tuple((s[0] if not env.is_vec_env else s[0][0]) for s in env.get_camera_sizes())
        size = default_size if config.exp.video_dims is None else config.exp.video_dims
        fps = 20
        video_writers = []
        for i in range(config.exp.num_workers):
            video_writer = cv2.VideoWriter(str(video_dir / f'rollout_video_{i}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
            video_writers.append(video_writer)
            
        render_mode = 'rgb_array'
    elif render:
        render_mode = 'human'
        video_writers = None
    else:
        render_mode = None
        video_writers = None
        
    return env, policy, render_mode, video_writers
        
        
def _plan_summary(plan_log):
    """Per-episode summary of the planner's per-step logs (rsm_planner.RSMPlannerMixin.pop_plan_log)."""
    if not plan_log:
        return None
    if isinstance(plan_log, dict):
        return plan_log          # rsm_rise: a summary restored from a .partial on resume -- pass it through
    import numpy as _np
    def _flat(key):
        return [float(v) for st in plan_log for v in (st[key] if isinstance(st[key], list) else [st[key]])]
    chosen, smax, smean, sstd = _flat('score_chosen'), _flat('score_max'), _flat('score_mean'), _flat('score_std')
    return {
        'steps': len(plan_log), 'n': plan_log[0]['n'], 'rule': plan_log[0]['rule'],
        'score_chosen_mean': float(_np.mean(chosen)), 'score_max_mean': float(_np.mean(smax)),
        'score_mean_mean': float(_np.mean(smean)), 'score_std_mean': float(_np.mean(sstd)),
        'gap_chosen_minus_mean': float(_np.mean(_np.array(chosen) - _np.array(smean))),
        'ties_at_max_mean': float(_np.mean(_flat('ties_at_max'))) if 'ties_at_max' in plan_log[0] else None,
        'frac_saturated_mean': float(_np.mean(_flat('frac_saturated'))) if 'frac_saturated' in plan_log[0] else None,
        # rsm_rise (stream E): both read-outs of the RSM scorer, whichever one ranks (plan_score)
        'score_kind': plan_log[0].get('score_kind'),
        'prob_chosen_mean': float(_np.mean(_flat('prob_chosen'))) if 'prob_chosen' in plan_log[0] else None,
        'prob_max_mean': float(_np.mean(_flat('prob_max'))) if 'prob_max' in plan_log[0] else None,
        # ties of the PROBABILITY array itself (gen_q#266), which `ties_at_max_mean` does not give when
        # another read-out ranks -- this is what makes the prob-vs-prob_log tie claim a within-cell one.
        'prob_ties_at_max_mean': float(_np.mean(_flat('prob_ties_at_max'))) if 'prob_ties_at_max' in plan_log[0] else None,
        'prob_ties_at_max_exact_mean': float(_np.mean(_flat('prob_ties_at_max_exact'))) if 'prob_ties_at_max_exact' in plan_log[0] else None,
        'prob_distinct_mean': float(_np.mean(_flat('prob_distinct'))) if 'prob_distinct' in plan_log[0] else None,
        'logit_chosen_mean': float(_np.mean(_flat('logit_chosen'))) if 'logit_chosen' in plan_log[0] else None,
        'logit_max_mean': float(_np.mean(_flat('logit_max'))) if 'logit_max' in plan_log[0] else None,
        'logit_mean_mean': float(_np.mean(_flat('logit_mean'))) if 'logit_mean' in plan_log[0] else None,
        'logit_std_mean': float(_np.mean(_flat('logit_std'))) if 'logit_std' in plan_log[0] else None,
        'logit_ties_at_max_mean': float(_np.mean(_flat('logit_ties_at_max'))) if 'logit_ties_at_max' in plan_log[0] else None,
        # log-complement read-out (gen_q#266, plan_score=prob_log): `prob` folded in log space.  The tie
        # count is the health number for it -- the claim is that it orders all N where prob ties ~half of
        # them, and `prob_log_ties_at_max_mean` next to `ties_at_max_mean` makes that checkable from this
        # JSON with no re-scoring.
        'prob_log_chosen_mean': float(_np.mean(_flat('prob_log_chosen'))) if 'prob_log_chosen' in plan_log[0] else None,
        'prob_log_max_mean': float(_np.mean(_flat('prob_log_max'))) if 'prob_log_max' in plan_log[0] else None,
        'prob_log_mean_mean': float(_np.mean(_flat('prob_log_mean'))) if 'prob_log_mean' in plan_log[0] else None,
        'prob_log_std_mean': float(_np.mean(_flat('prob_log_std'))) if 'prob_log_std' in plan_log[0] else None,
        'prob_log_ties_at_max_mean': float(_np.mean(_flat('prob_log_ties_at_max'))) if 'prob_log_ties_at_max' in plan_log[0] else None,
        # tolerance-free versions: prob_log spans 40+ orders of magnitude, so an absolute 1e-6 tie
        # tolerance is meaningless in the hopeless (all-logits-very-negative) regime.  These are what the
        # "orders all N" claim must be read off.
        'prob_log_ties_at_max_exact_mean': float(_np.mean(_flat('prob_log_ties_at_max_exact'))) if 'prob_log_ties_at_max_exact' in plan_log[0] else None,
        'prob_log_distinct_mean': float(_np.mean(_flat('prob_log_distinct'))) if 'prob_log_distinct' in plan_log[0] else None,
        # conformal read-out (plan_score=conformal_lcb): the per-particle lower quantile that ranks
        'lcb_quantile': plan_log[0].get('lcb_quantile'),
        'lcb_chosen_mean': float(_np.mean(_flat('lcb_chosen'))) if 'lcb_chosen' in plan_log[0] else None,
        'lcb_max_mean': float(_np.mean(_flat('lcb_max'))) if 'lcb_max' in plan_log[0] else None,
        'lcb_mean_mean': float(_np.mean(_flat('lcb_mean'))) if 'lcb_mean' in plan_log[0] else None,
        'lcb_ties_at_max_mean': float(_np.mean(_flat('lcb_ties_at_max'))) if 'lcb_ties_at_max' in plan_log[0] else None,
        't_sample_s': float(sum(st['t_sample'] for st in plan_log)),
        't_score_s': float(sum(st['t_score'] for st in plan_log)),
        'idx': [int(v) for st in plan_log for v in st['idx']],
    }


# ---- rsm_rise (orchestrator 15:51): episode-level resume -----------------------------------------------------
# A preempted eval cell used to restart at episode 0, so on `preemptable` a long cell could never finish.
# eval.py writes "<results_json>.partial" after EVERY episode and eval_cell.sh keeps the furthest attempt as
# "<results_json>.partial_best"; on start we reload whichever of the two got furthest and continue from the next
# episode index.  Resume is refused unless the run is the SAME cell (seed / horizon / policy / planner config),
# so a partial can never be blended into a different recipe.
_RESUME_N = 0          # episodes restored from a partial in this process (recorded in the results JSON)
# NOTE: exp.model_path is the per-attempt mktemp symlink dir of eval_cell.sh, so it is NOT an identity key;
# the checkpoint is compared through exp.eval_ckpt (the real model_epoch_*.pth), which eval_cell.sh passes.
_RESUME_KEYS = ('eval_seed', 'rollout_horizon', 'end_on_success', 'policy_mode', 'success_criterion', 'cell',
                'reset_states_file', 'eval_ckpt')


def _resume_fingerprint(config: EvaluationConfig):
    fp = {
        'eval_seed': int(config.exp.eval_seed),
        'rollout_horizon': int(config.exp.rollout_horizon),
        'end_on_success': bool(config.exp.get('end_on_success', False)),
        'policy_mode': str(config.exp.get('policy_mode', 'idql')),
        'success_criterion': {'mug': os.environ.get('RSM_RISE_MUG_SUCCESS', 'stock') or 'stock', 'thread': os.environ.get('RSM_RISE_THREAD_SUCCESS', 'stock') or 'stock', 'piece_dz_tol': os.environ.get('RSM_RISE_PIECE_DZ_TOL', '') or None},  # rsm_rise: which env success rule this cell used (#267: 'thread' defaults to stock)
        'cell': str(config.exp.get('eval_cell', '') or ''),
        'eval_ckpt': str(config.exp.get('eval_ckpt', '') or ''),
        'reset_states_file': getattr(config.env, 'reset_states_file', None),
    }
    try:
        from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import planner_kwargs
        fp['planner_overrides'] = {k: (v if isinstance(v, (int, float, str, bool)) or v is None else str(v))
                                   for k, v in planner_kwargs(config.training).items()}
    except Exception:
        fp['planner_overrides'] = None
    return fp


def _rng_state_dump():
    """Serialize the GLOBAL numpy RNG state (robosuite's placement samplers draw from np.random)."""
    try:
        st = np.random.get_state()
        return {'name': str(st[0]), 'keys': [int(x) for x in st[1]], 'pos': int(st[2]),
                'has_gauss': int(st[3]), 'cached_gaussian': float(st[4])}
    except Exception as ex:
        print(f'[rsm_rise] resume: cannot snapshot the numpy RNG state ({ex!r})')
        return None


def _rng_state_load(d):
    """Restore a state written by _rng_state_dump.  True on success."""
    try:
        if not isinstance(d, dict) or d.get('name') != 'MT19937' or len(d.get('keys') or []) != 624:
            return False
        np.random.set_state((d['name'], np.array(d['keys'], dtype=np.uint32), int(d['pos']),
                            int(d['has_gauss']), float(d['cached_gaussian'])))
        return True
    except Exception as ex:
        print(f'[rsm_rise] resume: cannot restore the numpy RNG state ({ex!r})')
        return False


def _df_planner(policy):
    """The installed DF planner (code/df_rise/df_policy.py `install`), or None for every other cell.

    rsm_rise FINDING AJ (stream DF_MAKEITWORK, 2026-09-24): the DF planner keeps state that the
    episode-level resume must carry -- the plan sampler's torch.Generator and the health
    accumulators -- exactly as it already carries the env's numpy MT19937 state.  df_policy.install
    registers itself on the algo, which is where `planner_describe` / `pop_plan_log` are read from.
    Returns None (so every non-DF cell is untouched) when no DF planner is installed.
    """
    inner = getattr(getattr(policy, 'policy', None), 'policy', None)
    # rsm_rise FINDING AK (gen_q#274 run 49-main, 2026-09-24): configuration (b) of #274 installs
    # TD-MPC2's MPPI/CEM planner the same way df_policy.install does, and it owns the SAME two kinds
    # of resume state (a per-cell torch.Generator for the MPPI noise, and the per-plan health records
    # diagnostics() averages).  Reaching only `_rr_df_planner` left every cfg(b) cell on the old,
    # non-reproducing behaviour: four landed cells published 38%-96% health coverage beside an
    # all-episodes success rate (status/nb/resume_audit.json).  Both handles expose the same
    # state_dump()/state_load() contract, so nothing else in this file changes.  A cell is never
    # both, and DF keeps precedence if a future cell somehow were.
    for attr in ('_rr_df_planner', '_rr_td_planner'):
        p = getattr(inner, attr, None)
        if p is not None:
            return p
    return None


def _df_state_dump(dfp):
    """dfp.state_dump(), but a failure degrades the RESUME rather than killing the running cell."""
    if dfp is None:
        return None
    try:
        return dfp.state_dump()
    except Exception as ex:
        print(f'[rsm_rise] resume: cannot snapshot the DF planner state ({ex!r}) -- this partial will '
              f'resume with the OLD (non-reproducing) behaviour')
        return None


def _resume_load(config: EvaluationConfig):
    """(n_done, episodes, np_rng_state, planner_state) of the furthest COMPATIBLE partial of this cell.

    `planner_state` is the DF planner's state_dump() as of the same episode boundary, or None for a
    non-DF cell and for any partial written before FINDING AJ landed.
    """
    import os
    path = config.exp.get('results_json', None)
    if not path or not bool(config.exp.get('resume_partial', True)):
        return 0, [], None, None
    fp = _resume_fingerprint(config)
    best = (0, [], None, None, None)
    for cand in (str(path) + '.partial', str(path) + '.partial_best'):
        if not os.path.exists(cand):
            continue
        try:
            with open(cand) as f:
                d = json.load(f)
        except Exception as ex:
            print(f'[rsm_rise] resume: cannot read {cand} ({ex!r}) -- ignored')
            continue
        # a key missing from the partial = written before that key existed -> not a mismatch, just unverifiable
        # rsm_rise #267: `success_criterion` is a DICT that gains sub-keys over time (mug 2026-09-21,
        # thread 2026-09-21), so it is compared SUB-KEY-WISE over the sub-keys the partial actually has.
        # Comparing the whole dict would declare every partial written before a new sub-key existed "a
        # different cell" and silently throw away its finished episodes.
        bad = []
        for k in _RESUME_KEYS:
            if k not in d:
                continue
            if k == 'success_criterion' and isinstance(d.get(k), dict) and isinstance(fp[k], dict):
                if any(d[k].get(sk) != fp[k].get(sk) for sk in d[k]):
                    bad.append(k)
                continue
            if d.get(k) != fp[k]:
                bad.append(k)
        missing = [k for k in _RESUME_KEYS if k not in d]
        if missing:
            print(f'[rsm_rise] resume: {cand} predates {",".join(missing)} -- identity taken from its path')
        if fp['planner_overrides'] is not None and d.get('planner_overrides') != fp['planner_overrides']:
            bad.append('planner_overrides')
        if bad:
            print(f'[rsm_rise] resume: {cand} is a DIFFERENT cell ({",".join(bad)} differ) -- ignored')
            continue
        eps = d.get('episodes') or []
        n = min(int(d.get('num_episodes', 0)), len(eps))
        if n > best[0]:
            best = (n, eps[:n], cand, d.get('np_rng_state'), d.get('df_planner_state'))
    if best[0]:
        print(f'[rsm_rise] resume: {best[2]} has {best[0]} finished episodes -> continuing at episode {best[0]}')
    return best[0], best[1], best[3], best[4]


def _resume_restore(rollout_stats: RolloutStats, episodes):
    """Replay finished episodes into a fresh RolloutStats (+ their wall times and planner summaries)."""
    ep_times, ep_plans = [], []
    for e in episodes:
        rollout_stats.all_reward.append(float(e.get('return', 0.0)))
        rollout_stats.all_successes.append(1.0 if e.get('success') else 0.0)
        rollout_stats.all_final_successes.append(1.0 if e.get('final_success') else 0.0)
        rollout_stats.all_lengths.append(int(e.get('length', 0)))
        rollout_stats.all_first_success.append(int(e.get('first_success_step', -1)))
        rollout_stats.num_episodes += 1
        ep_times.append(float(e.get('wall_time_s', 0.0)))
        ep_plans.append(e.get('plan') or [])
    rollout_stats.compute_statistics()
    return ep_times, ep_plans


def _write_results_json(config: EvaluationConfig, rollout_stats: RolloutStats, policy=None, ep_times=None,
                        ep_plans=None, t_start=None, partial=False, np_rng_state=None,
                        df_planner_state=None):
    # rsm_rise: per-episode results for the planning grid (stream A) + planner config / timing (stream D)
    import os, time as _time
    n = rollout_stats.num_episodes
    episodes = [
        {
            'episode': i,
            'success': bool(rollout_stats.all_successes[i] > 0.5),
            'final_success': bool(rollout_stats.all_final_successes[i] > 0.5),
            'return': float(rollout_stats.all_reward[i]),
            'length': int(rollout_stats.all_lengths[i]),
            'first_success_step': int(rollout_stats.all_first_success[i]),
        }
        for i in range(n)
    ]
    out = {
        'num_episodes': n,
        'success_rate': float(np.mean([e['success'] for e in episodes])) if n else None,
        'final_success_rate': float(np.mean([e['final_success'] for e in episodes])) if n else None,
        'mean_length': float(np.mean([e['length'] for e in episodes])) if n else None,
        'mean_return': float(np.mean([e['return'] for e in episodes])) if n else None,
        'model_path': str(config.exp.model_path),
        'env': OmegaConf.to_container(config.env, resolve=True, enum_to_str=True),
        'rollout_horizon': int(config.exp.rollout_horizon),
        'end_on_success': bool(config.exp.get('end_on_success', False)),
        'policy_mode': str(config.exp.get('policy_mode', 'idql')),
        'success_criterion': {'mug': os.environ.get('RSM_RISE_MUG_SUCCESS', 'stock') or 'stock', 'thread': os.environ.get('RSM_RISE_THREAD_SUCCESS', 'stock') or 'stock', 'piece_dz_tol': os.environ.get('RSM_RISE_PIECE_DZ_TOL', '') or None},  # rsm_rise: which env success rule this cell used (#267: 'thread' defaults to stock)
        'eval_seed': int(config.exp.eval_seed),
        'eval_ckpt': str(config.exp.get('eval_ckpt', '') or ''),
        'reset_states_file': getattr(config.env, 'reset_states_file', None),
        'episodes': episodes,
    }
    # ---- stream D: planner config, per-episode planner summary, timing, Wilson CI ------------------
    if ep_times is not None:
        for i, e in enumerate(episodes[:len(ep_times)]):
            e['wall_time_s'] = float(ep_times[i])
    if ep_plans is not None:
        for i, e in enumerate(episodes[:len(ep_plans)]):
            e['plan'] = _plan_summary(ep_plans[i])
    algo = getattr(getattr(policy, 'policy', None), 'policy', None)
    if hasattr(algo, 'planner_describe'):
        try:
            out['planner'] = algo.planner_describe()
        except Exception as ex:
            out['planner'] = {'error': repr(ex)}
    try:
        from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import planner_kwargs
        out['planner_overrides'] = {k: (v if isinstance(v, (int, float, str, bool)) or v is None else str(v))
                                    for k, v in planner_kwargs(config.training).items()}
    except Exception:
        pass
    # rsm_rise gen_q#289 (WM_NATIVE) -- PROVENANCE, and it was wrong before this block existed.
    # On the native-CEM route there is no robomimic planner: `algo` above is the loaded policy, whose
    # planner_describe() reports the SHARED planner's DEFAULTS (plan_mode=fold, rsm_backend=mlp,
    # plan_n=None) -- a planner this cell never ran and never built.  Measured on the first smoke
    # cells: every CEM JSON claimed `rsm_backend: mlp, plan_mode: fold`.  Anyone reading the archive
    # later would have attributed a CEM result to the shared read-out.
    # The native planner lives on the ROLLOUT POLICY (it has no algo), so it is read from there.
    # Gated on policy_mode == 'wm_cem', which nothing but this route sets, so every other cell's JSON
    # is byte-identical.  `planner_overrides` is deliberately left alone: it is the training config's
    # kwargs (all defaults here, and unread), and it is part of the resume identity key at :1020.
    if str(config.exp.get('policy_mode', 'idql')) == 'wm_cem':
        try:
            out['planner'] = policy.planner_describe()
        except Exception as ex:
            out['planner'] = {'error': repr(ex)}
    out['cell'] = str(config.exp.get('eval_cell', '') or '')
    out['task'] = str(config.exp.get('eval_task', '') or config.exp.get('task', '') or '')
    out['algo_name'] = getattr(algo, 'algo_name', None) if algo is not None else None
    out['num_rollouts_requested'] = int(config.exp.num_rollouts)
    out['partial'] = bool(partial)
    out['resumed_from_episode'] = int(_RESUME_N)
    if np_rng_state is not None:
        out['np_rng_state'] = np_rng_state
    # rsm_rise FINDING AJ: the DF planner's sampler state + health accumulators, so a preempted cell
    # resumes the SAME noise stream (see _df_planner / df_policy.state_dump).  PARTIAL FILES ONLY --
    # it is resume scaffolding, not a result, and the published cell JSON stays byte-for-byte the
    # shape every landed cell and every table loader already reads.
    if partial and df_planner_state is not None:
        out['df_planner_state'] = df_planner_state
    if n:
        p_hat = out['success_rate']; z = 1.96
        den = 1 + z * z / n
        centre = (p_hat + z * z / (2 * n)) / den
        half = z * np.sqrt(p_hat * (1 - p_hat) / n + z * z / (4 * n * n)) / den
        out['success_ci95'] = [float(centre - half), float(centre + half)]
    if t_start is not None:
        out['wall_time_s'] = float(_time.time() - t_start)
        out['wall_time_per_episode_s'] = float(out['wall_time_s'] / max(n, 1))
    plans = [e.get('plan') for e in episodes if e.get('plan')]
    if plans:
        out['planner_time'] = {
            'steps_total': int(sum(p['steps'] for p in plans)),
            't_sample_s': float(sum(p['t_sample_s'] for p in plans)),
            't_score_s': float(sum(p['t_score_s'] for p in plans)),
            'score_chosen_mean': float(np.mean([p['score_chosen_mean'] for p in plans])),
            'score_max_mean': float(np.mean([p['score_max_mean'] for p in plans])),
            'score_mean_mean': float(np.mean([p['score_mean_mean'] for p in plans])),
            'gap_chosen_minus_mean': float(np.mean([p['gap_chosen_minus_mean'] for p in plans])),
            'ties_at_max_mean': float(np.mean([p['ties_at_max_mean'] for p in plans if p.get('ties_at_max_mean') is not None] or [np.nan])),
            'frac_saturated_mean': float(np.mean([p['frac_saturated_mean'] for p in plans if p.get('frac_saturated_mean') is not None] or [np.nan])),
            # gen_q#266: the log-space read-out's tie count, rolled up to the cell so the table can print
            # it beside the score without opening the per-episode plans.
            'prob_log_ties_at_max_mean': float(np.mean([p['prob_log_ties_at_max_mean'] for p in plans if p.get('prob_log_ties_at_max_mean') is not None] or [np.nan])),
            'prob_log_std_mean': float(np.mean([p['prob_log_std_mean'] for p in plans if p.get('prob_log_std_mean') is not None] or [np.nan])),
            'prob_ties_at_max_mean': float(np.mean([p['prob_ties_at_max_mean'] for p in plans if p.get('prob_ties_at_max_mean') is not None] or [np.nan])),
            'prob_log_ties_at_max_exact_mean': float(np.mean([p['prob_log_ties_at_max_exact_mean'] for p in plans if p.get('prob_log_ties_at_max_exact_mean') is not None] or [np.nan])),
            'prob_log_distinct_mean': float(np.mean([p['prob_log_distinct_mean'] for p in plans if p.get('prob_log_distinct_mean') is not None] or [np.nan])),
            'prob_ties_at_max_exact_mean': float(np.mean([p['prob_ties_at_max_exact_mean'] for p in plans if p.get('prob_ties_at_max_exact_mean') is not None] or [np.nan])),
            'prob_distinct_mean': float(np.mean([p['prob_distinct_mean'] for p in plans if p.get('prob_distinct_mean') is not None] or [np.nan])),
        }
    path = str(config.exp.results_json)
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    target = path + '.partial' if partial else path
    # PER-PROCESS TMP (GAMMA_FAIR run 20, 2026-09-24, measured).  `os.replace` makes the PUBLISH atomic, but
    # a single shared `<target>.tmp` is not: if two evaluators are on the same cell at once -- which happens
    # whenever a drain queue carries the same payload at two indices (measured on q_gf11_tdflow_foldgamma,
    # idx 99 and 113 were one file, both running) -- they open, truncate and write that ONE tmp
    # concurrently, and whichever calls replace second can publish a truncated or interleaved JSON as the
    # cell's result.  A pid+host-unique tmp makes the pair last-writer-wins over two independently VALID
    # files instead, which is the worst a duplicate should ever cost.  Single-writer behaviour is unchanged.
    tmp = f"{target}.tmp.{socket.gethostname()}.{os.getpid()}"
    try:
        with open(tmp, 'w') as f:
            json.dump(out, f, indent=2)
        os.replace(tmp, target)
    finally:
        if os.path.exists(tmp):
            try:
                os.remove(tmp)          # write failed partway: never leave a stray tmp behind
            except OSError:
                pass
    if not partial:
        for stale in (path + '.partial', path + '.partial_best'):
            try:
                os.remove(stale)
            except OSError:
                pass
        print(f'[rsm_rise] wrote {path}: success_rate={out["success_rate"]} over {n} episodes')


@hydra.main(version_base=None, config_path='../configs', config_name="eval_robomimic")
def eval(config: EvaluationConfig): 
    config.env.horizon = config.exp.rollout_horizon
    env, policy, render_mode, video_writers = setup_eval(config)
            
    save_dataset = config.exp.save_to_dataset
    rollout_stats = RolloutStats()
    # rsm_rise: episode-level resume -- reload the furthest compatible partial of THIS cell and continue
    global _RESUME_N
    _RESUME_N, _resume_eps, _resume_rng, _resume_dfp = _resume_load(config)
    _resume_times, _resume_plans = _resume_restore(rollout_stats, _resume_eps)
    
    if save_dataset:
        dataset_name = f'{config.exp.dataset_name}.hdf5'
        if not ROLLOUT_DATA_DIR.exists():
            ROLLOUT_DATA_DIR.mkdir()
        dataset_path = ROLLOUT_DATA_DIR / dataset_name
        total_samples = 0
        demo_num = 0
        
    if config.exp.reset_to_data:
        ref_dataset_path = get_dataset(config.data)
    else:
        ref_dataset_path = None
    # rsm_rise: fixed initial-state pool (env.reset_states_file), one state per episode drawn with the eval seed
    _reset_pool = None
    if getattr(config.env, 'reset_states_file', None):
        with open(config.env.reset_states_file) as _f:
            _reset_pool = [np.array(e['state0'], dtype=np.float64) for e in json.load(_f)['episodes']]
        _reset_rng = np.random.RandomState(int(config.exp.eval_seed))
        _reset_idx = [int(_reset_rng.randint(len(_reset_pool))) for _ in range(int(config.exp.num_rollouts))]
        print(f"[rsm_rise] resetting every episode to one of {len(_reset_pool)} pooled initial states from {config.env.reset_states_file}")
        
    try:
        with (
            video_writer_manager(video_writers) as video_writers, 
            (h5py.File(dataset_path, 'w') if save_dataset else nullcontext()) as dataset_file,
            (h5py.File(ref_dataset_path, 'r') if ref_dataset_path is not None else nullcontext()) as ref_dataset_file
        ):
            if save_dataset:
                data_grp = dataset_file.create_group('data')                
            
            import time as _time
            # rsm_rise: wall time and planner log per episode (pre-filled by an episode-level resume)
            _ep_times, _ep_plans = list(_resume_times), list(_resume_plans)
            _t_eval0 = _time.time()
            # rsm_rise FINDING AJ (stream DF_MAKEITWORK, 2026-09-24) -- the DF planner half of the
            # resume.  The env half above restores the numpy MT19937 state exactly; the DF plan
            # sampler's torch.Generator was NOT carried, so a resumed cell ran the right initial
            # states with the wrong noise (measured: threading idmk8 As0-s0 resumed at 44 scored
            # 0/6 on its tail against 3/6 fresh, and published 300 plans of health instead of
            # 2500).  Carrying it makes a resumed cell reproduce a fresh one; a FRESH run never
            # reaches state_load, so every landed cell's numbers are untouched.
            _dfp = _df_planner(policy)
            if _RESUME_N and _dfp is not None:
                if _resume_dfp is None:
                    print(f'[rsm_rise] resume: WARNING -- cell '
                          f'{str(config.exp.get("eval_cell", "") or config.exp.results_json)!r} is a '
                          f'PLANNER cell (DF or TD-MPC2) resuming at episode {_RESUME_N} from a partial that carries NO '
                          f'df_planner_state (written before FINDING AJ landed).  Falling back to the OLD '
                          f'behaviour: the plan sampler restarts from its seed, so this cell will NOT '
                          f'reproduce a fresh run and its planner health covers only episodes '
                          f'{_RESUME_N}.. -- discard it and re-run fresh.')
                elif _dfp.state_load(_resume_dfp):
                    print(f'[rsm_rise] resume: restored the DF plan sampler + planner health of episode '
                          f'{_RESUME_N} ({len(_dfp._diag)} plans carried forward)')
                else:
                    print(f'[rsm_rise] resume: WARNING -- cell '
                          f'{str(config.exp.get("eval_cell", "") or config.exp.results_json)!r} carries a '
                          f'df_planner_state that could NOT be restored; falling back to the OLD behaviour '
                          f'(the plan sampler restarts from its seed).  Discard this cell and re-run fresh.')
            if _RESUME_N and _reset_pool is None and _rng_state_load(_resume_rng):
                # rsm_rise 23:20 UTC: the partial carries the exact global-numpy RNG state as of the reset of
                # episode _RESUME_N, so the resumed tail gets the SAME initial states a fresh run would have
                # given it without replaying _RESUME_N env.reset() calls (~1 s each -> up to 100 s per attempt
                # on a crashy cell, which is what made the 100-rollout TEST evals of a degenerate job miss the
                # deadline).  Strictly more faithful than the replay: the replay only matched a fresh run if
                # nothing inside a rollout drew from np.random.
                print(f'[rsm_rise] resume: restored the numpy RNG state of episode {_RESUME_N} '
                      f'(no reset replay needed)')
            elif _RESUME_N and _reset_pool is None:
                # No fixed init-state pool: episode i's initial state is the i-th draw of the env RNG (seeded with
                # eval_seed at creation).  Burn _RESUME_N resets so the resumed episodes get the SAME initial states
                # a fresh run would have given them -- otherwise the resumed tail would repeat the init states of
                # the finished head and the estimate would be built on duplicated inits.
                _t_warm = _time.time()
                for _ in range(_RESUME_N):
                    env.reset()
                print(f'[rsm_rise] resume: advanced the env RNG by {_RESUME_N} resets '
                      f'in {_time.time() - _t_warm:.1f}s')
            for i in range(_RESUME_N, config.exp.num_rollouts):
                _t_ep0 = _time.time()
                if ref_dataset_file is not None:
                    ind = 9
                    
                    eef_pos = ref_dataset_file['data'][f'demo_{ind}']['obs']['robot0_eef_pos'] 
                    # find first index where z < 0.5
                    try:
                        idx = np.where(eef_pos[:, 2] < 0.835)[0][0]
                    except IndexError:
                        idx = 0
                    
                    reset_state = ref_dataset_file['data'][f'demo_{ind}']['states'][idx]
                elif _reset_pool is not None:
                    reset_state = _reset_pool[_reset_idx[i]]
                else:
                    reset_state = None
                                        
                traj = rollout(
                    policy=policy,
                    eval_envs=env,
                    rollout_stats=rollout_stats,
                    reset_state=reset_state,
                    logger=None,
                    total_steps=config.exp.rollout_horizon,
                    render_mode=render_mode,
                    log_video=config.exp.log_video,
                    video_writers=video_writers,
                    render_dims=config.exp.video_dims,
                    video_skip=config.exp.video_skip,
                    return_trajectory=save_dataset,
                    end_on_success=bool(config.exp.get('end_on_success', False)),
                )
                if save_dataset:
                    # save traj
                    demo_num, added_samples = add_trajectory_to_dataset(
                        demo_num,
                        traj,
                        dataset_file
                    )
                    total_samples += added_samples
                
                rollout_stats.compute_statistics()
                _ep_times.append(_time.time() - _t_ep0)
                _algo = getattr(getattr(policy, 'policy', None), 'policy', None)
                _ep_plans.append(_algo.pop_plan_log() if hasattr(_algo, 'pop_plan_log') else [])
                if config.exp.get('results_json', None):
                    # snapshot taken here = the RNG state the NEXT episode's env.reset() will consume,
                    # and (FINDING AJ) the DF plan sampler + planner health as of the same boundary
                    _write_results_json(config, rollout_stats, policy=policy, ep_times=_ep_times,
                                        ep_plans=_ep_plans, t_start=_t_eval0, partial=True,
                                        np_rng_state=_rng_state_dump(),
                                        df_planner_state=_df_state_dump(_dfp))

                if config.exp.verbose:
                    rollout_stats.print_stats(i, total=config.exp.num_rollouts)
        
            if save_dataset:
                data_grp.attrs['total'] = total_samples
                
                hydra_config = HydraConfig.get()
                config_name = hydra_config.job.config_name
                data_grp.attrs['config_name'] = config_name
                
                env_args = env.serialize()
                if "placement_initializer" in env_args['env_kwargs']:
                    env_args['env_kwargs']["placement_initializer"] = None
                data_grp.attrs['env_args'] = json.dumps(env_args, indent=4)

                fill_metadata(
                    dataset_file,
                    dataset_id=str(uuid.uuid4()),
                    dataset_type=DatasetType.RL,
                    action_type=ActionType.RELATIVE,
                    env_type=EnvType.ROBOMIMIC,
                    env_name=config.env.env_name.value,
                    is_real=False,
                    include_date=True,
                    include_creator=True,
                )
                
                print(f"Dataset saved to {dataset_path}")
                print(f"Total samples added to dataset: {total_samples}")
        if save_dataset:
            edit_dataset_description(dataset_path)
        if config.exp.get('results_json', None):
            _write_results_json(config, rollout_stats, policy=policy, ep_times=_ep_times,
                                ep_plans=_ep_plans, t_start=_t_eval0, partial=False)
    except Exception as e:
        # remove partially completed dataset if it was created
        if save_dataset:
            dataset_path.unlink()
        raise e