File size: 7,549 Bytes
b26bdfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Linear probes: what does each part of a VLA know? (Phase 2, Part C)

For a SmolVLA checkpoint, extract mean-pooled features at three depths on held-out LIBERO frames:
  vision   = SigLIP patch features after the connector (what the 'eyes' report)
  prefix   = VLM output over [images, language, state] (what the 'reasoning' part holds)
  expert   = action-expert output at flow time t=1 (pure noise input, so it reflects only the context)
and fit ridge / logistic probes for:
  ee_pos (state[0:3], R虏) 路 commanded gripper close/open (action[6] sign, accuracy) 路 task id (40-way, accuracy) 路
  progress = frame_index / episode_length (R虏)
Probes are fit on train episodes and scored on held-out episodes (never the same episode in both).

Usage: envs/lerobot/.venv/bin/python experiments/lerobot/probe_features.py --policy lerobot/smolvla_base --n 3000
       (--policy may be a run's train/checkpoints/last/pretrained_model). Writes <out>/probes.json.
"""
import argparse
import json
from pathlib import Path

import numpy as np
import torch

# smolvla_base's camera names; see experiments/lerobot/run.py
RENAME = {"observation.images.image": "observation.images.camera1", "observation.images.image2": "observation.images.camera2"}


def ridge_r2(Xtr, ytr, Xte, yte, lam=1.0):
    mu, sd = Xtr.mean(0), Xtr.std(0) + 1e-6
    Xtr, Xte = (Xtr - mu) / sd, (Xte - mu) / sd
    Xtr1 = np.c_[Xtr, np.ones(len(Xtr))]
    W = np.linalg.solve(Xtr1.T @ Xtr1 + lam * np.eye(Xtr1.shape[1]), Xtr1.T @ ytr)
    pred = np.c_[Xte, np.ones(len(Xte))] @ W
    ss = ((yte - yte.mean(0)) ** 2).sum()
    return float(1 - ((yte - pred) ** 2).sum() / ss)


def logistic_acc(Xtr, ytr, Xte, yte):
    if len(np.unique(ytr)) < 2 or len(yte) == 0:
        return float("nan")  # too few samples/classes to fit (use a larger --n)
    from sklearn.linear_model import LogisticRegression
    from sklearn.preprocessing import StandardScaler
    sc = StandardScaler().fit(Xtr)
    clf = LogisticRegression(max_iter=2000, C=1.0).fit(sc.transform(Xtr), ytr)
    return float(clf.score(sc.transform(Xte), yte))


@torch.no_grad()
def extract(policy, pre, ds, idx, device, rename=None):
    from lerobot.policies.common.flow_matching import FlowConvention, make_flow_matching_inputs  # noqa: F401
    from lerobot.policies.smolvla.modeling_smolvla import make_att_2d_masks
    m = policy.model
    feats = {"vision": [], "prefix": [], "expert": []}
    for i in idx:
        item = {(rename or {}).get(k, k): v for k, v in ds[int(i)].items()}
        batch = pre({k: (v.unsqueeze(0) if torch.is_tensor(v) else v) for k, v in item.items()})
        batch = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in batch.items()}
        images, img_masks = policy.prepare_images(batch)
        state = policy.prepare_state(batch)
        lang, lmask = batch["observation.language.tokens"], batch["observation.language.attention_mask"]
        vis = torch.cat([m.vlm_with_expert.embed_image(im) for im in images], 1)
        feats["vision"].append(vis.float().mean(1).cpu().numpy()[0])
        pe, pp, pa = m.embed_prefix(images, img_masks, lang, lmask, state=state)
        att = make_att_2d_masks(pp, pa)
        pos = torch.cumsum(pp, 1) - 1
        (pout, _), pkv = m.vlm_with_expert.forward(attention_mask=att, position_ids=pos, past_key_values=None,
                                                   inputs_embeds=[pe, None], use_cache=True)
        feats["prefix"].append(pout.float().mean(1).cpu().numpy()[0])
        x1 = torch.zeros(1, m.config.chunk_size, m.config.max_action_dim, device=device)
        t = torch.ones(1, device=device)
        se, sp, sa = m.embed_suffix(x1, t)
        L = sp.shape[1]
        full = torch.cat([pp[:, None, :].expand(1, L, pp.shape[1]), make_att_2d_masks(sp, sa)], 2)
        spos = pp.sum(-1)[:, None] + torch.cumsum(sp, 1) - 1
        (_, sout), _ = m.vlm_with_expert.forward(attention_mask=full, position_ids=spos, past_key_values=pkv,
                                                 inputs_embeds=[None, se], use_cache=True)
        feats["expert"].append(sout.float().mean(1).cpu().numpy()[0])
    return {k: np.stack(v) for k, v in feats.items()}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--policy", default="lerobot/smolvla_base")
    ap.add_argument("--n", type=int, default=3000)
    ap.add_argument("--out", default=None)
    ap.add_argument("--seed", type=int, default=0)
    a = ap.parse_args()
    from lerobot.configs.policies import PreTrainedConfig
    from lerobot.datasets.lerobot_dataset import LeRobotDataset
    from lerobot.policies.factory import make_policy, make_pre_post_processors
    device = "cuda" if torch.cuda.is_available() else "cpu"
    ds = LeRobotDataset("HuggingFaceVLA/libero")
    # Build exactly as lerobot-train does: features come from the LIBERO dataset, weights from a.policy.
    cfg = PreTrainedConfig.from_pretrained(a.policy)
    cfg.pretrained_path, cfg.device = a.policy, device
    rename = {} if cfg.input_features and "observation.images.image" in cfg.input_features else RENAME
    policy = make_policy(cfg, ds_meta=ds.meta, rename_map=rename or None).to(device).eval()
    # Local fine-tuned checkpoints carry LIBERO processors; the Hub base model's processors hold its own
    # pre-training stats, so for it build fresh processors from the LIBERO statistics.
    local = Path(a.policy).exists()
    pre, _ = make_pre_post_processors(cfg, pretrained_path=a.policy if local else None, dataset_stats=ds.meta.stats,
                                      preprocessor_overrides={"device_processor": {"device": device},
                                                              "rename_observations_processor": {"rename_map": rename}})
    rng = np.random.default_rng(a.seed)
    ep_of = np.asarray(ds.hf_dataset["episode_index"])
    eps = np.unique(ep_of)
    test_eps = set(rng.choice(eps, size=len(eps) // 5, replace=False).tolist())
    idx = rng.choice(len(ds), size=a.n, replace=False)
    F = extract(policy, pre, ds, idx, device, rename)
    st = np.stack([np.asarray(ds[int(i)]["observation.state"]) for i in idx])
    # LIBERO state = [eef pos(3), axis-angle(3), finger qpos(2)]: finger 1 is always > 0, so use the COMMANDED
    # gripper (action[6], +1 close / -1 open) as the binary target instead.
    grip = np.array([float(np.asarray(ds[int(i)]["action"])[6]) > 0 for i in idx])
    task = np.array([int(ds[int(i)]["task_index"]) for i in idx])
    fi = np.array([int(ds[int(i)]["frame_index"]) for i in idx])
    ep_len = {int(e): int((ep_of == e).sum()) for e in np.unique(ep_of[idx])}
    prog = fi / np.array([ep_len[int(ep_of[i])] for i in idx])
    te = np.array([int(ep_of[i]) in test_eps for i in idx])
    res = {}
    for k, X in F.items():
        res[k] = {"ee_pos_r2": ridge_r2(X[~te], st[~te, :3], X[te], st[te, :3]),
                  "gripper_cmd_acc": logistic_acc(X[~te], grip[~te], X[te], grip[te]),
                  "task_acc": logistic_acc(X[~te], task[~te], X[te], task[te]),
                  "progress_r2": ridge_r2(X[~te], prog[~te], X[te], prog[te]), "dim": int(X.shape[1])}
        print(k, json.dumps(res[k]), flush=True)
    out = Path(a.out or (Path(a.policy).parent.parent.parent.parent if Path(a.policy).exists() else Path("probes_base")))
    out.mkdir(parents=True, exist_ok=True)
    (out / "probes.json").write_text(json.dumps({"policy": a.policy, "n": a.n, "results": res}, indent=2))
    print("wrote", out / "probes.json")


if __name__ == "__main__":
    main()