File size: 46,437 Bytes
6b11150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Reproduce and visualize episode-level progress probes.

The probe learns a scalar progress value from per-timestep concept features:

    X[t] = HDF5["concept"][t]          # default: all 960 dims
    y[t] = t / (T - 1)                 # generated from episode length

Cross-validation is split by episode, not by timestep.
"""

from __future__ import annotations

import argparse
import json
import subprocess
import tempfile
from dataclasses import dataclass
from pathlib import Path

import joblib
import numpy as np
from PIL import Image, ImageDraw
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import KFold
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

from probe_common import (
    DEFAULT_LABEL_ROOT,
    DEFAULT_OUTPUT_ROOT,
    DEFAULT_TASK_DIRS,
    DEFAULT_VIDEO_ROOT,
    concept_steps,
    concept_to_frame_index,
    concat_episode_data,
    dataset_entries,
    default_output_root,
    ensure_dir,
    episode_number,
    ffprobe_video,
    infer_alignment,
    label_files,
    label_root_search_paths,
    list_task_demos,
    load_concept,
    natural_key,
    pair_episodes_by_id,
    progress_labels,
    read_video_frame,
    remap_path,
    resolve_kind_label_dir,
    resolve_label_dir,
    resolve_video_dir,
    status_counts,
    video_files,
)


def make_progress_probe(probe: str, alpha: float, seed: int):
    """Build ridge or MLP regressor for progress probing."""
    name = (probe or "ridge").lower()
    if name == "ridge":
        return Ridge(alpha=alpha)
    if name == "mlp":
        return Pipeline(
            [
                ("scaler", StandardScaler()),
                (
                    "reg",
                    MLPRegressor(
                        hidden_layer_sizes=(256, 128),
                        early_stopping=True,
                        random_state=seed,
                        max_iter=500,
                    ),
                ),
            ]
        )
    raise ValueError(f"Unknown --probe={probe!r}; expected ridge|mlp")


def model_from_joblib(path: Path):
    obj = joblib.load(path)
    if isinstance(obj, dict) and "model" in obj:
        return obj["model"], obj
    return obj, {"model_path": str(path)}


def fit_cv(args: argparse.Namespace) -> None:
    task_dir = resolve_label_dir(args)
    files = label_files(task_dir)
    out_dir = ensure_dir(Path(args.output_dir))
    ckpt_dir = ensure_dir(out_dir / "checkpoints")
    metrics_dir = ensure_dir(out_dir / "metrics")
    probe_name = getattr(args, "probe", "ridge") or "ridge"

    kf = KFold(n_splits=args.n_splits, shuffle=True, random_state=args.seed)
    folds = []
    for fold, (train_idx, test_idx) in enumerate(kf.split(np.arange(len(files)))):
        x_train, y_train = concat_episode_data(files, train_idx, args.feature_start, args.feature_end)
        x_test, y_test = concat_episode_data(files, test_idx, args.feature_start, args.feature_end)

        model = make_progress_probe(probe_name, args.alpha, args.seed)
        model.fit(x_train, y_train)
        pred = np.clip(model.predict(x_test), args.clip_min, args.clip_max)

        fold_record = {
            "fold": fold,
            "checkpoint": str(ckpt_dir / f"fold_{fold}.joblib"),
            "mse": float(mean_squared_error(y_test, pred)),
            "mae": float(mean_absolute_error(y_test, pred)),
            "r2": float(r2_score(y_test, pred)),
            "train_episode_indices": train_idx.tolist(),
            "test_episode_indices": test_idx.tolist(),
            "train_episodes": int(len(train_idx)),
            "test_episodes": int(len(test_idx)),
        }
        payload = {
            "model": model,
            "probe": probe_name,
            "task": args.task,
            "demo": getattr(args, "demo", None),
            "label_kind": getattr(args, "label_kind", None),
            "label_dir": str(task_dir),
            "feature_slice": [args.feature_start, args.feature_end],
            "feature_dim": int(x_train.shape[1]),
            "fold": fold,
            "n_splits": args.n_splits,
            "seed": args.seed,
            "alpha": args.alpha,
            "train_episode_indices": train_idx.tolist(),
            "test_episode_indices": test_idx.tolist(),
            "train_episodes": int(len(train_idx)),
            "test_episodes": int(len(test_idx)),
        }
        joblib.dump(payload, fold_record["checkpoint"])
        folds.append(fold_record)
        print(
            f"fold={fold} probe={probe_name} mse={fold_record['mse']:.6f} "
            f"mae={fold_record['mae']:.6f} r2={fold_record['r2']:.4f}"
        )

    x_all, y_all = concat_episode_data(files, range(len(files)), args.feature_start, args.feature_end)
    full_model = make_progress_probe(probe_name, args.alpha, args.seed).fit(x_all, y_all)
    full_model_path = ckpt_dir / "model_all_episodes.joblib"
    joblib.dump(
        {
            "model": full_model,
            "probe": probe_name,
            "task": args.task,
            "demo": getattr(args, "demo", None),
            "label_kind": getattr(args, "label_kind", None),
            "label_dir": str(task_dir),
            "feature_slice": [args.feature_start, args.feature_end],
            "feature_dim": int(x_all.shape[1]),
            "n_episodes": len(files),
            "seed": args.seed,
            "alpha": args.alpha,
            "note": "trained on all episodes",
        },
        full_model_path,
    )

    summary = {
        "mse_mean": float(np.mean([fold["mse"] for fold in folds])),
        "mae_mean": float(np.mean([fold["mae"] for fold in folds])),
        "r2_mean": float(np.mean([fold["r2"] for fold in folds])),
    }
    report = {
        "task": args.task,
        "demo": getattr(args, "demo", None),
        "label_kind": getattr(args, "label_kind", None),
        "probe": probe_name,
        "task_dir": str(task_dir),
        "feature_slice": [args.feature_start, args.feature_end],
        "feature_dim": int(x_all.shape[1]),
        "n_splits": args.n_splits,
        "seed": args.seed,
        "alpha": args.alpha,
        "folds": folds,
        "summary": summary,
        "full_model_checkpoint": str(full_model_path),
    }
    (metrics_dir / "cv_metrics.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(json.dumps(summary, indent=2))


def evaluate_files(
    model,
    files: list[Path],
    feature_start: int,
    feature_end: int | None,
    clip_min: float,
    clip_max: float,
) -> dict:
    xs = []
    ys = []
    per_episode = []
    for episode_index, path in enumerate(files):
        x = load_concept(path, feature_start, feature_end)
        y = progress_labels(x.shape[0])
        pred_ep = np.clip(model.predict(x), clip_min, clip_max)
        xs.append(x)
        ys.append(y)
        if x.shape[0] < 2:
            ep_r2 = None
            ep_mae = float(mean_absolute_error(y, pred_ep)) if x.shape[0] else None
            ep_mse = float(mean_squared_error(y, pred_ep)) if x.shape[0] else None
        else:
            ep_r2 = float(r2_score(y, pred_ep))
            ep_mae = float(mean_absolute_error(y, pred_ep))
            ep_mse = float(mean_squared_error(y, pred_ep))
        per_episode.append(
            {
                "episode_index": int(episode_index),
                "label_stem": path.stem,
                "label_path": str(path),
                "n_steps": int(x.shape[0]),
                "r2": ep_r2,
                "mae": ep_mae,
                "mse": ep_mse,
            }
        )
    x_all = np.concatenate(xs, axis=0)
    y_all = np.concatenate(ys, axis=0)
    pred = np.clip(model.predict(x_all), clip_min, clip_max)
    return {
        "mse": float(mean_squared_error(y_all, pred)),
        "mae": float(mean_absolute_error(y_all, pred)),
        "r2": float(r2_score(y_all, pred)),
        "n_episodes": int(len(files)),
        "n_steps": int(x_all.shape[0]),
        "feature_dim": int(x_all.shape[1]),
        "per_episode": per_episode,
    }


def write_cross_robot_episode_tables(
    task: str,
    results: list[dict],
    metrics_dir: Path,
    topk: int,
) -> None:
    """Flatten per-episode metrics and write top-K cherry-pick table for target splits."""
    per_ep_csv = metrics_dir / "cross_robot_per_episode.csv"
    topk_csv = metrics_dir / "cross_robot_topk_episodes.csv"
    flat_cols = [
        "task",
        "train_demo",
        "train_label_kind",
        "eval_demo",
        "eval_label_kind",
        "eval_validation_index",
        "split",
        "episode_index",
        "label_stem",
        "label_path",
        "n_steps",
        "r2",
        "mae",
        "mse",
        "aggregate_r2",
        "checkpoint",
    ]
    topk_rows: list[dict] = []
    with per_ep_csv.open("w", encoding="utf-8") as handle:
        handle.write(",".join(flat_cols) + "\n")
        for row in results:
            for ep in row.get("per_episode") or []:
                flat = {
                    "task": task,
                    "train_demo": row["train_demo"],
                    "train_label_kind": row["train_label_kind"],
                    "eval_demo": row["eval_demo"],
                    "eval_label_kind": row["eval_label_kind"],
                    "eval_validation_index": row["eval_validation_index"],
                    "split": row["split"],
                    "episode_index": ep["episode_index"],
                    "label_stem": ep["label_stem"],
                    "label_path": ep["label_path"],
                    "n_steps": ep["n_steps"],
                    "r2": "" if ep["r2"] is None else f"{ep['r2']:.8f}",
                    "mae": "" if ep["mae"] is None else f"{ep['mae']:.8f}",
                    "mse": "" if ep["mse"] is None else f"{ep['mse']:.8f}",
                    "aggregate_r2": f"{row['r2']:.8f}",
                    "checkpoint": row["checkpoint"],
                }
                handle.write(",".join(str(flat[c]) for c in flat_cols) + "\n")
                if row["split"] == "target" and ep["r2"] is not None:
                    topk_rows.append(
                        {
                            "task": task,
                            "train_demo": row["train_demo"],
                            "eval_demo": row["eval_demo"],
                            "label_kind": row["eval_label_kind"],
                            "eval_validation_index": row["eval_validation_index"],
                            "episode_index": ep["episode_index"],
                            "label_stem": ep["label_stem"],
                            "label_path": ep["label_path"],
                            "n_steps": ep["n_steps"],
                            "episode_r2": ep["r2"],
                            "episode_mae": ep["mae"],
                            "episode_mse": ep["mse"],
                            "aggregate_r2": row["r2"],
                            "checkpoint": row["checkpoint"],
                        }
                    )

    # Per (train_demo, eval_demo, label_kind, val) keep top-K by episode_r2
    grouped: dict[tuple, list[dict]] = {}
    for item in topk_rows:
        key = (
            item["train_demo"],
            item["eval_demo"],
            item["label_kind"],
            int(item["eval_validation_index"]),
        )
        grouped.setdefault(key, []).append(item)

    selected: list[dict] = []
    for key in sorted(grouped.keys(), key=lambda k: (str(k[0]), str(k[1]), str(k[2]), k[3])):
        items = sorted(grouped[key], key=lambda x: x["episode_r2"], reverse=True)
        for rank, item in enumerate(items[: max(1, topk)], start=1):
            selected.append({**item, "rank_in_pair": rank})

    topk_cols = [
        "task",
        "train_demo",
        "eval_demo",
        "label_kind",
        "eval_validation_index",
        "rank_in_pair",
        "episode_index",
        "label_stem",
        "episode_r2",
        "episode_mae",
        "episode_mse",
        "aggregate_r2",
        "n_steps",
        "label_path",
        "checkpoint",
    ]
    with topk_csv.open("w", encoding="utf-8") as handle:
        handle.write(",".join(topk_cols) + "\n")
        for item in selected:
            handle.write(
                ",".join(
                    [
                        str(item[c])
                        if c
                        not in {
                            "episode_r2",
                            "episode_mae",
                            "episode_mse",
                            "aggregate_r2",
                        }
                        else f"{item[c]:.8f}"
                        for c in topk_cols
                    ]
                )
                + "\n"
            )
    print(f"wrote {per_ep_csv}")
    print(f"wrote {topk_csv}")


def fit_cross_robot(args: argparse.Namespace) -> None:
    """Cross-embodiment: train on one robot, eval on others, matched by label kind.

    Runs full_label->full_label then womae_label->womae_label. Source robots rotate.
    """
    label_root = Path(args.label_root)
    task = args.task
    demos = list_task_demos(label_root, task)
    if args.train_demos:
        train_demos = [d for d in args.train_demos if d in demos]
        missing = sorted(set(args.train_demos) - set(train_demos))
        if missing:
            raise ValueError(f"--train-demos not found for task={task}: {missing}; available={demos}")
    else:
        train_demos = demos

    label_kinds = list(args.label_kinds)
    out_dir = ensure_dir(Path(args.output_dir))
    ckpt_dir = ensure_dir(out_dir / "checkpoints")
    metrics_dir = ensure_dir(out_dir / "metrics")
    topk = int(getattr(args, "topk", 5) or 5)
    probe_name = getattr(args, "probe", "ridge") or "ridge"

    results = []
    for label_kind in label_kinds:
        print(f"\n===== probe={probe_name} label_kind={label_kind} (train->eval matched) =====", flush=True)
        for train_demo in train_demos:
            # For womae with multiple validation dirs, train on val0 by default.
            train_dir = resolve_kind_label_dir(
                label_root,
                task,
                train_demo,
                label_kind,
                args.validation_glob,
                args.train_validation_index,
            )
            if train_dir is None:
                print(f"skip train demo={train_demo} kind={label_kind}: not found")
                continue
            train_files = label_files(train_dir)
            x_train, y_train = concat_episode_data(
                train_files, range(len(train_files)), args.feature_start, args.feature_end
            )
            model = make_progress_probe(probe_name, args.alpha, args.seed).fit(x_train, y_train)
            ckpt_path = ckpt_dir / f"train_{train_demo}__{label_kind}.joblib"
            joblib.dump(
                {
                    "model": model,
                    "probe": probe_name,
                    "task": task,
                    "demo": train_demo,
                    "label_kind": label_kind,
                    "label_dir": str(train_dir),
                    "feature_slice": [args.feature_start, args.feature_end],
                    "feature_dim": int(x_train.shape[1]),
                    "n_episodes": len(train_files),
                    "seed": args.seed,
                    "alpha": args.alpha,
                    "note": f"cross-robot: train {label_kind} on one robot, eval same kind on others",
                },
                ckpt_path,
            )
            print(
                f"trained probe={probe_name} source={train_demo} {label_kind} episodes={len(train_files)} "
                f"steps={x_train.shape[0]} -> {ckpt_path}",
                flush=True,
            )

            for eval_demo in demos:
                # Resolve eval kind dir across primary + ALOHA overlays.
                eval_kind_dir = None
                for root in label_root_search_paths(label_root):
                    cand = root / task / eval_demo / label_kind
                    if cand.is_dir():
                        eval_kind_dir = cand
                        break
                if eval_kind_dir is None:
                    continue
                val_dirs = sorted(
                    [p for p in eval_kind_dir.glob(args.validation_glob) if p.is_dir()],
                    key=natural_key,
                )
                if not val_dirs:
                    continue
                # full: only val0; womae: all available validation dirs
                indices = range(len(val_dirs)) if label_kind == "womae_label" else [0]
                for val_idx in indices:
                    eval_dir = val_dirs[val_idx]
                    # matched train/eval dirs when same demo+kind+val
                    if eval_demo == train_demo and val_idx == args.train_validation_index:
                        eval_files = train_files
                        split = "source_self"
                    else:
                        eval_files = label_files(eval_dir)
                        split = "target" if eval_demo != train_demo else "source_other_val"
                    metrics = evaluate_files(
                        model,
                        eval_files,
                        args.feature_start,
                        args.feature_end,
                        args.clip_min,
                        args.clip_max,
                    )
                    row = {
                        "train_demo": train_demo,
                        "train_label_kind": label_kind,
                        "eval_demo": eval_demo,
                        "eval_label_kind": label_kind,
                        "eval_validation_index": val_idx,
                        "split": split,
                        "probe": probe_name,
                        "checkpoint": str(ckpt_path),
                        "train_label_dir": str(train_dir),
                        "eval_label_dir": str(eval_dir),
                        **metrics,
                    }
                    results.append(row)
                    print(
                        f"  {label_kind}: {train_demo} -> {eval_demo} val={val_idx} "
                        f"split={split} r2={metrics['r2']:.4f} mae={metrics['mae']:.4f}",
                        flush=True,
                    )

    report = {
        "task": task,
        "label_root": str(label_root),
        "protocol": "matched label_kind cross-embodiment (full->full, womae->womae)",
        "probe": probe_name,
        "label_kinds": label_kinds,
        "demos": demos,
        "train_demos": train_demos,
        "feature_slice": [args.feature_start, args.feature_end],
        "alpha": args.alpha,
        "seed": args.seed,
        "topk": topk,
        "results": results,
    }
    metrics_path = metrics_dir / "cross_robot_metrics.json"
    metrics_path.write_text(json.dumps(report, indent=2), encoding="utf-8")

    for label_kind in label_kinds:
        kind_rows = [
            r
            for r in results
            if r["train_label_kind"] == label_kind
            and r["eval_label_kind"] == label_kind
            and r["split"] in {"target", "source_self", "source_other_val"}
        ]
        matrix_demos = demos
        train_present = sorted({r["train_demo"] for r in kind_rows}, key=natural_key)
        # matrix uses val_index == 0 for display clarity
        matrix_rows = [r for r in kind_rows if int(r.get("eval_validation_index", 0)) == 0]
        csv_path = metrics_dir / f"cross_robot_{label_kind}_r2.csv"
        md_path = metrics_dir / f"cross_robot_{label_kind}_r2.md"
        with csv_path.open("w", encoding="utf-8") as handle:
            header = ["train_demo"] + [f"eval_{d}" for d in matrix_demos]
            handle.write(",".join(header) + "\n")
            for train_demo in train_present:
                vals = [train_demo]
                for eval_demo in matrix_demos:
                    hit = next(
                        (
                            r
                            for r in matrix_rows
                            if r["train_demo"] == train_demo and r["eval_demo"] == eval_demo
                        ),
                        None,
                    )
                    vals.append("" if hit is None else f"{hit['r2']:.6f}")
                handle.write(",".join(vals) + "\n")
        lines = [
            f"# Cross-embodiment R² — {task} / `{label_kind}` -> `{label_kind}`",
            "",
            "Train and eval use the same label kind. Cells are R² (val0).",
            "",
            "| train_demo \\ eval_demo | " + " | ".join(matrix_demos) + " |",
            "| --- | " + " | ".join(["---:" for _ in matrix_demos]) + " |",
        ]
        for train_demo in train_present:
            cells = [train_demo]
            for eval_demo in matrix_demos:
                hit = next(
                    (
                        r
                        for r in matrix_rows
                        if r["train_demo"] == train_demo and r["eval_demo"] == eval_demo
                    ),
                    None,
                )
                cells.append("" if hit is None else f"{hit['r2']:.4f}")
            lines.append("| " + " | ".join(cells) + " |")
        md_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
        print(f"wrote {csv_path}")
        print(f"wrote {md_path}")

    all_csv = metrics_dir / "cross_robot_all_results.csv"
    with all_csv.open("w", encoding="utf-8") as handle:
        cols = [
            "train_demo",
            "train_label_kind",
            "eval_demo",
            "eval_label_kind",
            "eval_validation_index",
            "split",
            "r2",
            "mae",
            "mse",
            "n_episodes",
            "n_steps",
        ]
        handle.write(",".join(cols) + "\n")
        for r in results:
            handle.write(
                ",".join(
                    [
                        str(r[c]) if c not in {"r2", "mae", "mse"} else f"{r[c]:.8f}"
                        for c in cols
                    ]
                )
                + "\n"
            )
    write_cross_robot_episode_tables(task, results, metrics_dir, topk=topk)
    print(f"wrote {metrics_path}")
    print(f"wrote {all_csv}")


def build_mapping(args: argparse.Namespace) -> None:
    task = args.task
    label_dir = resolve_label_dir(args)
    video_dir = resolve_video_dir(args)
    labels = label_files(label_dir)
    videos = video_files(video_dir)
    pairs = pair_episodes_by_id(labels, videos)
    label_ids = [episode_number(path) for path in labels]
    video_by_idx = {episode_number(path): path for path in videos}
    video_ids = sorted(video_by_idx)
    if len(labels) != len(videos):
        print(f"warning: labels={len(labels)} videos={len(videos)}")
    id_mismatches = sorted(set(label_ids).symmetric_difference(video_ids))
    if id_mismatches:
        print(
            f"warning: episode-id set differs between labels and videos; "
            f"example missing/extra ids={id_mismatches[:20]}"
        )
    # Show why alpha sort would be wrong for unpadded video names.
    alpha_videos = sorted(videos, key=lambda path: path.name)
    alpha_mismatch = sum(
        1
        for label_path, video_path in zip(labels, alpha_videos)
        if episode_number(label_path) != episode_number(video_path)
    )
    print(
        f"episode-id pairing: labels={len(labels)} videos={len(videos)} "
        f"shared_ids={len(set(label_ids) & set(video_ids))} "
        f"alpha_sort_would_mismatch={alpha_mismatch}"
    )

    out_dir = ensure_dir(Path(args.output_dir))
    rows = []
    for pos, label_path in enumerate(labels):
        label_idx = episode_number(label_path)
        _, video_path = pairs.get(label_idx, (label_path, None))
        row = {
            "task": task,
            "demo": getattr(args, "demo", None),
            "label_kind": getattr(args, "label_kind", None),
            "validation_index": getattr(args, "validation_index", 0),
            "position": pos,
            "label_idx": label_idx,
            "label_stem": label_path.stem,
            "label_path": str(label_path),
            "demo_idx": episode_number(video_path) if video_path else None,
            "demo_stem": video_path.stem if video_path else None,
            "video_path": str(video_path) if video_path else None,
            "mapping_source": "episode_id",
            "episode_id_match": bool(video_path is not None and episode_number(video_path) == label_idx),
        }
        try:
            if video_path is None:
                row["status"] = "bad"
                row["alignment"] = "missing_video"
                row["concept_steps"] = None
            elif getattr(args, "skip_video_probe", False):
                row["status"] = "ok" if row["episode_id_match"] else "bad"
                row["alignment"] = "episode_id_only"
                if getattr(args, "skip_concept_probe", False):
                    row["concept_steps"] = None
                else:
                    row["concept_steps"] = concept_steps(label_path)
            else:
                row["concept_steps"] = concept_steps(label_path)
                row.update(ffprobe_video(video_path))
                status, alignment = infer_alignment(row["concept_steps"], row["video_frames"])
                row["status"] = status
                row["alignment"] = alignment
                row["frame_per_concept"] = row["video_frames"] / row["concept_steps"]
        except Exception as exc:
            row["status"] = "bad"
            row["alignment"] = f"inspect_error: {exc}"
        rows.append(row)

    id_match_count = sum(1 for row in rows if row.get("episode_id_match"))
    output = {
        "task": task,
        "demo": getattr(args, "demo", None),
        "label_kind": getattr(args, "label_kind", None),
        "label_dir": str(label_dir),
        "video_dir": str(video_dir),
        "mapping_policy": "match by episode number (not alphabetical filename order)",
        "episode_id_match_count": id_match_count,
        "episode_id_total": len(rows),
        "items": rows,
    }
    val_idx = int(getattr(args, "validation_index", 0) or 0)
    suffix_parts = [
        part
        for part in [task, getattr(args, "demo", None), getattr(args, "label_kind", None), f"val{val_idx}"]
        if part
    ]
    suffix = "__".join(suffix_parts)
    mapping_path = out_dir / f"{suffix}_mapping.json"
    mapping_path.write_text(json.dumps(output, indent=2), encoding="utf-8")
    print(f"wrote {mapping_path}")
    print(f"episode_id_match={id_match_count}/{len(rows)}")
    print(f"status counts: {status_counts(rows)}")

    if args.check_images:
        check_dir = ensure_dir(out_dir / f"{suffix}_alignment_checks")
        for row in rows[: args.max_check_images]:
            if row.get("video_path"):
                write_alignment_check(row, check_dir)
        print(f"wrote alignment checks to {check_dir}")


def scan_dataset(args: argparse.Namespace) -> None:
    label_root = Path(args.label_root)
    video_root = Path(args.video_root)
    entries = dataset_entries(label_root, video_root, args.validation_glob)
    output = {
        "label_root": str(label_root),
        "video_root": str(video_root),
        "validation_glob": args.validation_glob,
        "entries": entries,
    }
    output_path = Path(args.output_json)
    ensure_dir(output_path.parent)
    output_path.write_text(json.dumps(output, indent=2), encoding="utf-8")
    print(f"wrote {output_path}")
    print(f"entries={len(entries)}")
    counts: dict[str, int] = {}
    for entry in entries:
        counts[entry["status"]] = counts.get(entry["status"], 0) + 1
    print(f"status counts: {counts}")
    for entry in entries[: args.print_limit]:
        print(
            f"{entry['status']} task={entry['task']} demo={entry['demo']} "
            f"kind={entry['label_kind']} labels={entry['label_count']} videos={entry['video_count']}"
        )


def existing_selection_to_mapping(args: argparse.Namespace) -> None:
    selection = json.loads(Path(args.selection_json).read_text(encoding="utf-8"))
    items = []
    for task, rows in selection.items():
        for row in rows:
            label_path = Path(row["episode"]["label_path"])
            old_video_path = Path(row["video_path"])
            video_path = remap_path(old_video_path, Path(args.old_video_root), Path(args.new_video_root))
            label_path = remap_path(label_path, Path(args.old_label_root), Path(args.new_label_root))
            item = {
                "task": task,
                "label_idx": row.get("label_idx"),
                "label_stem": row.get("label_stem"),
                "label_path": str(label_path),
                "demo_stem": row.get("demo_stem"),
                "video_path": str(video_path),
                "fold": row.get("fold"),
                "mapping_source": str(args.selection_json),
            }
            try:
                item["concept_steps"] = concept_steps(label_path)
                item.update(ffprobe_video(video_path))
                status, alignment = infer_alignment(item["concept_steps"], item["video_frames"])
                item["status"] = status
                item["alignment"] = alignment
                item["frame_per_concept"] = item["video_frames"] / item["concept_steps"]
            except Exception as exc:
                item["status"] = "bad"
                item["alignment"] = f"inspect_error: {exc}"
            items.append(item)
    out = {"items": items, "mapping_policy": "from existing selection.json with root remap"}
    output_path = Path(args.output_json)
    ensure_dir(output_path.parent)
    output_path.write_text(json.dumps(out, indent=2), encoding="utf-8")
    print(f"wrote {output_path}")
    print(f"status counts: {status_counts(items)}")


def write_alignment_check(row: dict, out_dir: Path) -> None:
    label = Path(row["label_path"])
    video = Path(row["video_path"])
    concept_count = int(row["concept_steps"])
    video_count = int(row["video_frames"])
    points = [0, concept_count // 2, max(0, concept_count - 1)]
    frames = []
    for t in points:
        frame_idx = concept_to_frame_index(t, concept_count, video_count)
        frame = read_video_frame(video, frame_idx).resize((320, 180))
        frames.append((t, frame_idx, frame))

    canvas = Image.new("RGB", (960, 240), "white")
    draw = ImageDraw.Draw(canvas)
    for i, (t, frame_idx, frame) in enumerate(frames):
        x = i * 320
        canvas.paste(frame, (x, 32))
        draw.text((x + 8, 8), f"concept t={t} -> video frame={frame_idx}", fill=(0, 0, 0))
    draw.text(
        (8, 216),
        f"{row['label_stem']} -> {row['demo_stem']} | {row.get('alignment')} | "
        f"T={concept_count}, frames={video_count}",
        fill=(0, 0, 0),
    )
    canvas.save(out_dir / f"{row['label_stem']}__{row['demo_stem']}.jpg", quality=92)


@dataclass
class PanelFrame:
    full: Image.Image
    video_only: Image.Image
    curve_panel: Image.Image
    progress_bar: Image.Image
    error_panel: Image.Image


def visualize_one(args: argparse.Namespace) -> None:
    mapping_item = load_mapping_item(args)
    label_path = Path(args.label_path or mapping_item["label_path"])
    video_path = Path(args.video_path or mapping_item["video_path"])
    model, model_meta = model_from_joblib(Path(args.model_path))
    x = load_concept(label_path, args.feature_start, args.feature_end)
    gt = progress_labels(x.shape[0])
    pred = np.clip(model.predict(x), args.clip_min, args.clip_max)
    errors = np.abs(pred - gt)

    video_meta = ffprobe_video(video_path)
    fps = args.output_fps or min(max(video_meta["video_fps"], 1.0), 30.0)
    out_dir = ensure_dir(Path(args.output_dir))

    metadata = {
        "label_path": str(label_path),
        "video_path": str(video_path),
        "model_path": str(args.model_path),
        "model_meta": model_meta,
        "concept_steps": int(x.shape[0]),
        "video": video_meta,
        "mse": float(mean_squared_error(gt, pred)),
        "mae": float(mean_absolute_error(gt, pred)),
        "r2": float(r2_score(gt, pred)),
        "feature_slice": [args.feature_start, args.feature_end],
    }
    (out_dir / "metadata.json").write_text(json.dumps(metadata, indent=2, default=str), encoding="utf-8")

    with tempfile.TemporaryDirectory() as tmp:
        tmp_dir = Path(tmp)
        panel_dirs = {
            "full": ensure_dir(tmp_dir / "full"),
            "video_only": ensure_dir(tmp_dir / "video_only"),
            "curve_panel": ensure_dir(tmp_dir / "curve_panel"),
            "progress_bar": ensure_dir(tmp_dir / "progress_bar"),
            "error_panel": ensure_dir(tmp_dir / "error_panel"),
        }
        for t in range(0, x.shape[0], args.step):
            frame_idx = concept_to_frame_index(t, x.shape[0], video_meta["video_frames"])
            video_frame = read_video_frame(video_path, frame_idx)
            panels = render_panels(
                video_frame,
                gt,
                pred,
                errors,
                t,
                frame_idx,
                metadata,
                width=args.width,
                height=args.height,
            )
            for name in panel_dirs:
                getattr(panels, name).save(panel_dirs[name] / f"{t:06d}.png")
            if t % max(1, args.progress_every) == 0:
                print(f"rendered t={t}/{x.shape[0] - 1}")

        for name, frames_dir in panel_dirs.items():
            write_video_from_frames(frames_dir, out_dir / f"{name}.mp4", fps=fps / args.step)
    print(f"wrote visualization outputs to {out_dir}")


def load_mapping_item(args: argparse.Namespace) -> dict:
    if not args.mapping_json:
        return {}
    data = json.loads(Path(args.mapping_json).read_text(encoding="utf-8"))
    items = data.get("items", data if isinstance(data, list) else [])
    if args.mapping_index is not None:
        return items[args.mapping_index]
    for item in items:
        if args.label_stem and item.get("label_stem") == args.label_stem:
            return item
        if args.demo_stem and item.get("demo_stem") == args.demo_stem:
            return item
    raise ValueError("No mapping item matched; pass --mapping-index, --label-stem, or --demo-stem")


def render_panels(
    video_frame: Image.Image,
    gt: np.ndarray,
    pred: np.ndarray,
    errors: np.ndarray,
    t: int,
    frame_idx: int,
    metadata: dict,
    width: int,
    height: int,
) -> PanelFrame:
    video_panel = fit_image(video_frame, width // 2, height)
    side_w = width - video_panel.width
    curve = draw_curve_panel(gt, pred, t, side_w, height // 2)
    progress = draw_progress_panel(gt[t], pred[t], side_w, height // 4)
    err = draw_error_panel(errors, t, metadata, frame_idx, side_w, height - curve.height - progress.height)

    full = Image.new("RGB", (video_panel.width + side_w, height), (245, 245, 245))
    full.paste(video_panel, (0, 0))
    full.paste(curve, (video_panel.width, 0))
    full.paste(progress, (video_panel.width, curve.height))
    full.paste(err, (video_panel.width, curve.height + progress.height))
    return PanelFrame(full=full, video_only=video_panel, curve_panel=curve, progress_bar=progress, error_panel=err)


def fit_image(image: Image.Image, max_w: int, max_h: int) -> Image.Image:
    image = image.convert("RGB")
    scale = min(max_w / image.width, max_h / image.height)
    new_size = (max(1, int(image.width * scale)), max(1, int(image.height * scale)))
    resized = image.resize(new_size)
    canvas = Image.new("RGB", (max_w, max_h), (0, 0, 0))
    canvas.paste(resized, ((max_w - new_size[0]) // 2, (max_h - new_size[1]) // 2))
    return canvas


def draw_curve_panel(gt: np.ndarray, pred: np.ndarray, t: int, width: int, height: int) -> Image.Image:
    img = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(img)
    pad_l, pad_r, pad_t, pad_b = 48, 16, 24, 36
    plot_w = width - pad_l - pad_r
    plot_h = height - pad_t - pad_b
    draw.rectangle((pad_l, pad_t, pad_l + plot_w, pad_t + plot_h), outline=(80, 80, 80))
    draw.text((pad_l, 6), "GT / Pred Progress", fill=(0, 0, 0))
    draw.text((pad_l + 8, pad_t + 8), "GT", fill=(20, 120, 60))
    draw.text((pad_l + 48, pad_t + 8), "Pred", fill=(40, 90, 200))

    upto = max(1, t + 1)
    draw_polyline(draw, gt[:upto], pad_l, pad_t, plot_w, plot_h, color=(20, 120, 60), total=len(gt))
    draw_polyline(draw, pred[:upto], pad_l, pad_t, plot_w, plot_h, color=(40, 90, 200), total=len(gt))
    x = pad_l + int(t / max(1, len(gt) - 1) * plot_w)
    draw.line((x, pad_t, x, pad_t + plot_h), fill=(180, 60, 60), width=1)
    draw.text((pad_l, height - 28), f"t={t}/{len(gt)-1}", fill=(0, 0, 0))
    return img


def draw_polyline(draw: ImageDraw.ImageDraw, values: np.ndarray, x0: int, y0: int, w: int, h: int, color, total: int) -> None:
    if len(values) < 2:
        return
    points = []
    for i, value in enumerate(values):
        x = x0 + int(i / max(1, total - 1) * w)
        y = y0 + h - int(float(value) * h)
        points.append((x, y))
    draw.line(points, fill=color, width=2)


def draw_progress_panel(gt_value: float, pred_value: float, width: int, height: int) -> Image.Image:
    img = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(img)
    draw.text((24, 14), "Current Progress", fill=(0, 0, 0))
    draw_bar(draw, 24, 48, width - 48, 24, gt_value, "GT", (20, 120, 60))
    draw_bar(draw, 24, 90, width - 48, 24, pred_value, "Pred", (40, 90, 200))
    return img


def draw_bar(draw: ImageDraw.ImageDraw, x: int, y: int, w: int, h: int, value: float, label: str, color) -> None:
    value = max(0.0, min(1.0, float(value)))
    draw.text((x, y - 18), f"{label}: {value:.3f}", fill=(0, 0, 0))
    draw.rectangle((x, y, x + w, y + h), outline=(80, 80, 80))
    draw.rectangle((x, y, x + int(w * value), y + h), fill=color)


def draw_error_panel(errors: np.ndarray, t: int, metadata: dict, frame_idx: int, width: int, height: int) -> Image.Image:
    img = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(img)
    lines = [
        f"video frame: {frame_idx}",
        f"current abs error: {errors[t]:.4f}",
        f"running MAE: {float(np.mean(errors[: t + 1])):.4f}",
        f"episode MAE: {metadata['mae']:.4f}",
        f"episode MSE: {metadata['mse']:.4f}",
        f"episode R2: {metadata['r2']:.4f}",
        f"steps: {metadata['concept_steps']} | frames: {metadata['video']['video_frames']}",
    ]
    y = 16
    for line in lines:
        draw.text((24, y), line, fill=(0, 0, 0))
        y += 24
    return img


def write_video_from_frames(frames_dir: Path, output_path: Path, fps: float) -> None:
    subprocess.run(
        [
            "ffmpeg",
            "-v",
            "error",
            "-y",
            "-framerate",
            f"{fps:.6f}",
            "-pattern_type",
            "glob",
            "-i",
            str(frames_dir / "*.png"),
            "-c:v",
            "libx264",
            "-pix_fmt",
            "yuv420p",
            "-movflags",
            "+faststart",
            str(output_path),
        ],
        check=True,
    )


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="command", required=True)

    fit = sub.add_parser("fit-cv", help="Fit episode-level Ridge CV probe")
    fit.add_argument("--task", required=True)
    fit.add_argument("--task-dir", default=None, help="Direct validation label directory")
    fit.add_argument("--label-root", default=str(DEFAULT_LABEL_ROOT), help="Root containing label directories")
    fit.add_argument("--demo", default=None, help="Example: demo_clean_100_arx")
    fit.add_argument("--label-kind", default=None, help="Example: full_label or womae_label")
    fit.add_argument("--validation-glob", default="validation-*-label")
    fit.add_argument("--validation-index", type=int, default=0)
    fit.add_argument("--allow-multiple-validation-dirs", action="store_true")
    fit.add_argument("--output-dir", required=True)
    fit.add_argument("--feature-start", type=int, default=0)
    fit.add_argument("--feature-end", type=int, default=None)
    fit.add_argument("--n-splits", type=int, default=10)
    fit.add_argument("--seed", type=int, default=42)
    fit.add_argument("--alpha", type=float, default=0.0)
    fit.add_argument("--clip-min", type=float, default=0.0)
    fit.add_argument("--clip-max", type=float, default=1.0)
    fit.add_argument("--probe", choices=["ridge", "mlp"], default="ridge")
    fit.set_defaults(func=fit_cv)

    cross = sub.add_parser(
        "fit-cross-robot",
        help="Cross-embodiment: full->full then womae->womae, rotate train robots",
    )
    cross.add_argument("--task", required=True)
    cross.add_argument("--label-root", default=str(DEFAULT_LABEL_ROOT))
    cross.add_argument(
        "--train-demos",
        nargs="*",
        default=None,
        help="Optional subset of source robots; default: rotate all demos",
    )
    cross.add_argument(
        "--label-kinds",
        nargs="+",
        default=["full_label", "womae_label"],
        help="Matched train/eval kinds in order (default: full_label then womae_label)",
    )
    cross.add_argument("--validation-glob", default="validation-*-label")
    cross.add_argument("--train-validation-index", type=int, default=0)
    cross.add_argument("--output-dir", required=True)
    cross.add_argument("--feature-start", type=int, default=0)
    cross.add_argument("--feature-end", type=int, default=None)
    cross.add_argument("--seed", type=int, default=42)
    cross.add_argument("--alpha", type=float, default=0.0)
    cross.add_argument("--clip-min", type=float, default=0.0)
    cross.add_argument("--clip-max", type=float, default=1.0)
    cross.add_argument(
        "--topk",
        type=int,
        default=5,
        help="Per target train→eval pair, keep top-K episodes by R² for cherry-pick",
    )
    cross.add_argument("--probe", choices=["ridge", "mlp"], default="ridge")
    cross.set_defaults(func=fit_cross_robot)

    scan = sub.add_parser("scan-dataset", help="Scan cross-embodiment label/video roots")
    scan.add_argument("--label-root", required=True, help="Example: /data/share/robotwin2.0-hard-cross-embodiment")
    scan.add_argument("--video-root", required=True, help="Example: /data/share/robotwin2.0-hard")
    scan.add_argument("--validation-glob", default="validation-*-label")
    scan.add_argument("--output-json", default=str(default_output_root() / "dataset_manifest.json"))
    scan.add_argument("--print-limit", type=int, default=30)
    scan.set_defaults(func=scan_dataset)

    mapping = sub.add_parser("build-mapping", help="Build candidate HDF5-to-video mapping for one task")
    mapping.add_argument("--task", required=True)
    mapping.add_argument("--label-root", default=str(DEFAULT_LABEL_ROOT))
    mapping.add_argument("--video-root", default=str(DEFAULT_VIDEO_ROOT))
    mapping.add_argument("--demo", default=None, help="Example: demo_clean_100_arx")
    mapping.add_argument("--label-kind", default=None, help="Example: full_label or womae_label")
    mapping.add_argument("--validation-glob", default="validation-*-label")
    mapping.add_argument("--validation-index", type=int, default=0)
    mapping.add_argument("--allow-multiple-validation-dirs", action="store_true")
    mapping.add_argument("--label-dir", default=None)
    mapping.add_argument("--video-dir", default=None)
    mapping.add_argument("--output-dir", default=str(DEFAULT_OUTPUT_ROOT / "mappings"))
    mapping.add_argument("--check-images", action="store_true")
    mapping.add_argument("--max-check-images", type=int, default=20)
    mapping.add_argument(
        "--skip-video-probe",
        action="store_true",
        help="Only match by episode id; skip ffprobe frame-count checks (much faster)",
    )
    mapping.add_argument(
        "--skip-concept-probe",
        action="store_true",
        help="With --skip-video-probe, also skip reading concept shapes from HDF5",
    )
    mapping.set_defaults(func=build_mapping)

    sel = sub.add_parser("selection-to-mapping", help="Convert existing selection.json to local mapping")
    sel.add_argument("--selection-json", required=True)
    sel.add_argument("--output-json", required=True)
    sel.add_argument("--old-label-root", default="/home/jianyuan/yidong/RoboTwin/policy/data/himaconplusplus_0.8B_labels")
    sel.add_argument("--new-label-root", default=str(DEFAULT_LABEL_ROOT))
    sel.add_argument("--old-video-root", default="/home/jianyuan/yidong/RoboTwin/policy/data/robotwin2.0-hard")
    sel.add_argument("--new-video-root", default=str(DEFAULT_VIDEO_ROOT))
    sel.set_defaults(func=existing_selection_to_mapping)

    viz = sub.add_parser("visualize-one", help="Render full and split-panel visualization for one episode")
    viz.add_argument("--mapping-json", default=None)
    viz.add_argument("--mapping-index", type=int, default=None)
    viz.add_argument("--label-stem", default=None)
    viz.add_argument("--demo-stem", default=None)
    viz.add_argument("--label-path", default=None)
    viz.add_argument("--video-path", default=None)
    viz.add_argument("--model-path", required=True)
    viz.add_argument("--output-dir", required=True)
    viz.add_argument("--feature-start", type=int, default=0)
    viz.add_argument("--feature-end", type=int, default=None)
    viz.add_argument("--clip-min", type=float, default=0.0)
    viz.add_argument("--clip-max", type=float, default=1.0)
    viz.add_argument("--width", type=int, default=1280)
    viz.add_argument("--height", type=int, default=720)
    viz.add_argument("--step", type=int, default=1, help="Render every Nth concept timestep")
    viz.add_argument("--output-fps", type=float, default=None)
    viz.add_argument("--progress-every", type=int, default=50)
    viz.set_defaults(func=visualize_one)

    return parser.parse_args()


def main() -> None:
    args = parse_args()
    args.func(args)


if __name__ == "__main__":
    main()