atharva-pantheon commited on
Commit
3a8e55e
·
verified ·
1 Parent(s): e9e2a68

Upload code/gate_success_fail.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/gate_success_fail.py +93 -0
code/gate_success_fail.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Definitive RLT encoder gate: do SUCCESS vs FAILURE z_rl separate?
3
+
4
+ The RL Token paper validates the token by showing success frames form a smooth
5
+ manifold while failures (failed grasps / tower collapses) cluster apart. This is
6
+ the real test (stronger than the success-only smoothness gate in tsne_gate.py).
7
+
8
+ success = the 44 teleop demos -> encoder_cache_prefix/
9
+ failure = frozen-baseline rollouts -> encoder_cache_fail/ (SR~0)
10
+
11
+ Reports: linear separability (LogisticRegression 5-fold CV accuracy on z_rl) and
12
+ silhouette score, plus a t-SNE colored by class. High CV-acc + clear visual
13
+ split = z_rl encodes task-success information => good RL state.
14
+
15
+ CPU-only (won't fight the GPU policy server). Run AFTER collecting failures:
16
+ ./lerobot/.venv/bin/python gate_success_fail.py --ckpt checkpoints/rl_token_encoder_FINAL.pt
17
+ """
18
+ from __future__ import annotations
19
+ import argparse, glob, os
20
+ import numpy as np, torch
21
+ import matplotlib; matplotlib.use("Agg")
22
+ import matplotlib.pyplot as plt
23
+ from sklearn.decomposition import PCA
24
+ from sklearn.manifold import TSNE
25
+ from sklearn.linear_model import LogisticRegression
26
+ from sklearn.model_selection import cross_val_score
27
+ from sklearn.metrics import silhouette_score
28
+ from rl_token_encoder import RLTokenAutoencoder, RLTokenConfig
29
+
30
+
31
+ def encode_dir(ae, d, cap):
32
+ fs = sorted(glob.glob(os.path.join(d, "*.npz")))
33
+ if not fs:
34
+ return np.zeros((0, 2560), np.float32)
35
+ if len(fs) > cap:
36
+ fs = fs[:: len(fs) // cap]
37
+ Z = []
38
+ with torch.no_grad():
39
+ for f in fs:
40
+ e = torch.from_numpy(np.load(f)["embeddings"].astype(np.float32))[None]
41
+ m = torch.ones(1, e.shape[1], dtype=torch.bool)
42
+ Z.append(ae.encode(e, m)[0].numpy())
43
+ return np.stack(Z)
44
+
45
+
46
+ def main():
47
+ p = argparse.ArgumentParser()
48
+ p.add_argument("--ckpt", default="checkpoints/rl_token_encoder_FINAL.pt")
49
+ p.add_argument("--success-dir", default="./encoder_cache_prefix")
50
+ p.add_argument("--fail-dir", default="./encoder_cache_fail")
51
+ p.add_argument("--weights", default="ema", choices=["ema", "model"])
52
+ p.add_argument("--cap", type=int, default=800, help="max points per class (balanced)")
53
+ p.add_argument("--out", default="outputs/gate_success_fail.png")
54
+ args = p.parse_args()
55
+
56
+ ck = torch.load(args.ckpt, map_location="cpu")
57
+ ae = RLTokenAutoencoder(RLTokenConfig(dim=2560)); ae.load_state_dict(ck[args.weights]); ae.eval()
58
+ print(f"loaded {args.ckpt} ({args.weights})")
59
+
60
+ Zs = encode_dir(ae, args.success_dir, args.cap)
61
+ Zf = encode_dir(ae, args.fail_dir, args.cap)
62
+ print(f"success z_rl: {len(Zs)} failure z_rl: {len(Zf)}")
63
+ if len(Zf) < 10:
64
+ print("⚠️ <10 failure shards — collect baseline rollouts into", args.fail_dir, "first."); return
65
+
66
+ n = min(len(Zs), len(Zf)) # balance
67
+ Zs, Zf = Zs[:n], Zf[:n]
68
+ X = np.concatenate([Zs, Zf]); y = np.array([0] * n + [1] * n)
69
+
70
+ # 1) linear separability (the quantitative verdict)
71
+ clf = LogisticRegression(max_iter=2000, C=1.0)
72
+ acc = cross_val_score(clf, X, y, cv=5, scoring="accuracy").mean()
73
+ sil = silhouette_score(X, y)
74
+ print(f"\nSEPARATION:")
75
+ print(f" LogReg 5-fold CV accuracy = {acc:.1%} (50%=indistinguishable, >80%=clearly separable)")
76
+ print(f" silhouette (by class) = {sil:.3f} (>0 = classes form distinct groups)")
77
+
78
+ # 2) t-SNE colored by class
79
+ Xp = PCA(n_components=min(50, X.shape[0])).fit_transform(X)
80
+ emb = TSNE(n_components=2, perplexity=30, init="pca", random_state=0).fit_transform(Xp)
81
+ plt.figure(figsize=(7, 6))
82
+ plt.scatter(emb[:n, 0], emb[:n, 1], c="tab:green", s=10, label="success (demos)", alpha=0.6)
83
+ plt.scatter(emb[n:, 0], emb[n:, 1], c="tab:red", s=10, label="failure (baseline)", alpha=0.6)
84
+ plt.legend(); plt.title(f"z_rl: success vs failure (LogReg CV acc {acc:.0%}, silhouette {sil:.2f})")
85
+ os.makedirs(os.path.dirname(args.out), exist_ok=True)
86
+ plt.tight_layout(); plt.savefig(args.out, dpi=120)
87
+ print(f"saved {args.out}")
88
+ print("\nGATE:", "✅ z_rl separates success from failure — good RL state" if acc > 0.8
89
+ else "⚠️ weak separation — z_rl may not capture task success cleanly")
90
+
91
+
92
+ if __name__ == "__main__":
93
+ main()