File size: 7,184 Bytes
ae1ed83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Phase A - A03/A04/A05 spatial feature probe (TRACE-VLA v1.1).

Zero-training probe (closed-form ridge, dual form) of how much
spatial information the frozen TIPSv2 features carry. Target: the
end-effector position state[0:3] of the same frame. This is a proxy
target - the dataset carries no object poses - and the limitation is
recorded in the report.

Frames: every 10th frame of the 63 cached episodes (21 tasks x 3
episodes). Split by episode: episodes 0-1 of each task are train,
episode 2 is test. Images are the main camera with the rot180
orientation correction, as in the feature cache.

A05 (pooling, at 224 px): token grids 256 (raw), 64 (2x2), 16 (4x4).
A04 (resolution, pooled to 64 tokens): 224 (2x2), 336 (3x3), 448 (4x4).
Representation: tokens projected by one fixed random matrix
768 -> 64 (same matrix for every variant), flattened, ridge in dual
form. Differences therefore come from the tokenization, not the probe.
Metric: MAE in meters and R^2 on the test episodes.
"""
import json
import sys
from pathlib import Path

import numpy as np
import torch

sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))

EXP = Path.home() / "sera_v4_experiments"
OUT = EXP / "trace_validation" / "results" / "a03_probe.json"
FRAME_STRIDE = 10
RIDGE_LAMBDA = 1.0


def pool_tokens(patch_tokens: torch.Tensor, factor: int) -> torch.Tensor:
    """[N, G*G, 768] -> [N, (G/f)^2, 768] by mean over fxf groups."""
    n, p, d = patch_tokens.shape
    g = int(round(p ** 0.5))
    x = patch_tokens.view(n, g // factor, factor, g // factor, factor, d)
    return x.mean(dim=(2, 4)).reshape(n, (g // factor) ** 2, d)


def ridge_fit_predict(x_tr, y_tr, x_te, lam=RIDGE_LAMBDA):
    """Dual-form ridge with a fixed random projection to 64 dims/token."""
    n_tr = x_tr.shape[0]
    k_tr = x_tr @ x_tr.T
    eye = torch.eye(n_tr, device=x_tr.device, dtype=x_tr.dtype)
    alpha = torch.linalg.solve(k_tr + lam * eye, y_tr)
    return (x_te @ x_tr.T) @ alpha


def main():
    from lerobot.datasets.lerobot_dataset import LeRobotDataset

    device = "cuda"
    cache = torch.load(EXP / "trace_vla" / "feature_cache.pt",
                       weights_only=False)
    episodes = cache["episodes"]
    states = cache["states"]

    # Sample frames and group them by (task, episode ordinal).
    by_task = {}
    for ei, ep in enumerate(episodes):
        by_task.setdefault(ep["task_index"], []).append(ei)
    sample = []   # (cache_ep_idx, local_t, is_test)
    for task, eps in sorted(by_task.items()):
        for ordinal, ei in enumerate(eps):
            ep = episodes[ei]
            for t in range(0, ep["length"], FRAME_STRIDE):
                sample.append((ei, t, ordinal == 2))
    print(f"sampled {len(sample)} frames")

    ds = LeRobotDataset("lerobot/libero", revision="v3.0",
                        episodes=sorted({episodes[ei]["episode_id"]
                                         for ei, _, _ in sample}),
                        video_backend="pyav")
    # Map (episode_id, frame_index) -> image
    wanted = {}
    for ei, t, _ in sample:
        wanted.setdefault(episodes[ei]["episode_id"], set()).add(t)
    images = {}
    for i in range(len(ds)):
        item = ds[i]
        e, f = int(item["episode_index"]), int(item["frame_index"])
        if e in wanted and f in wanted[e]:
            img = torch.flip(item["observation.images.image"],
                             dims=(-2, -1))
            images[(e, f)] = img
    print(f"decoded {len(images)} images")

    from trace_vla.anchor import TipsAnchor
    anchor = TipsAnchor("google/tipsv2-b14").to(device)
    gen = torch.Generator().manual_seed(1234)
    proj = torch.randn(768, 64, generator=gen) / (768 ** 0.5)
    proj = proj.to(device)

    def encode(res: int):
        """Return {(ep_id, frame): patch tokens [P, 768] at resolution res}."""
        out = {}
        keys = sorted(images.keys())
        bs = 24
        for i in range(0, len(keys), bs):
            batch_keys = keys[i:i + bs]
            imgs = torch.stack([images[k] for k in batch_keys]).to(device)
            if res != 256:
                imgs = torch.nn.functional.interpolate(
                    imgs, size=(res, res), mode="bilinear",
                    align_corners=False)
            with torch.no_grad():
                tok = anchor.tips.encode_image(imgs.float()).patch_tokens
            if i == 0:
                report_patch_counts[res] = int(tok.shape[1])
                print(f"res {res}: patch tokens = {tok.shape[1]}")
            for j, k in enumerate(batch_keys):
                out[k] = tok[j].float().cpu()
        return out

    def build(tokens_by_key, factor):
        xs, ys, test_flags = [], [], []
        for ei, t, is_test in sample:
            ep = episodes[ei]
            key = (ep["episode_id"], t)
            tok = pool_tokens(tokens_by_key[key].unsqueeze(0).to(device),
                              factor)[0]
            rep = (tok @ proj).reshape(-1).cpu()
            xs.append(rep)
            ys.append(states[ep["start"] + t][:3])
            test_flags.append(is_test)
        return torch.stack(xs), torch.stack(ys), torch.tensor(test_flags)

    def evaluate(name, tokens_by_key, factor):
        x, y, is_test = build(tokens_by_key, factor)
        x_tr, y_tr = x[~is_test], y[~is_test]
        x_te, y_te = x[is_test], y[is_test]
        mu, sd = y_tr.mean(0), y_tr.std(0).clamp(min=1e-6)
        pred = ridge_fit_predict(x_tr.to(device),
                                 ((y_tr - mu) / sd).to(device),
                                 x_te.to(device)).cpu() * sd + mu
        err = (pred - y_te).abs()
        mae = err.mean(0)
        ss_res = ((pred - y_te) ** 2).sum(0)
        ss_tot = ((y_te - y_tr.mean(0)) ** 2).sum(0)
        r2 = 1 - ss_res / ss_tot.clamp(min=1e-9)
        res = {"mae_per_axis_m": [round(float(v), 4) for v in mae],
               "mae_mean_m": round(float(mae.mean()), 4),
               "r2_per_axis": [round(float(v), 3) for v in r2]}
        print(name, res)
        return res

    report = {"target": "EE position state[0:3] (proxy; no object poses "
                        "in dataset)",
              "n_frames": len(sample), "pooling_224": {}, "resolution": {}}
    report_patch_counts = {}
    tok224 = encode(224)
    report["pooling_224"]["tokens256"] = evaluate("224/256tok", tok224, 1)
    report["pooling_224"]["tokens64"] = evaluate("224/64tok", tok224, 2)
    report["pooling_224"]["tokens16"] = evaluate("224/16tok", tok224, 4)
    report["resolution"]["res224_64tok"] = report["pooling_224"]["tokens64"]
    tok336 = encode(336)
    report["resolution"]["res336_64tok"] = evaluate("336/64tok", tok336, 3)
    tok448 = encode(448)
    report["resolution"]["res448_64tok"] = evaluate("448/64tok", tok448, 4)
    report["patch_counts_observed"] = report_patch_counts
    report["resolution_valid"] = report_patch_counts == {224: 256, 336: 576,
                                                         448: 1024}
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(report, indent=1))
    print("saved", OUT)


if __name__ == "__main__":
    main()