File size: 9,609 Bytes
b4396f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build the ActionCodec2 token map for sera-vla-v4_1 (SPEC in WORKLOG).

Fits the official ActionCodec2 first-order EEF tokenizer
(variant paper-o1-5mm-4k-2bin-1p2ms: 5 mm / 0.02 rad tolerances,
binary gripper, Set-BPE vocab 4,096) on the TRAIN split of
lerobot/libero at native fps 10 — merges fit on train episodes
only — then encodes, for every (episode, frame), the token stream
of the 16-step action window starting at that frame in two
clamping variants:

  base: window clamped at the episode end;
  seg:  window clamped at the DATA V2 segment end (train frames;
        identical to base on eval episodes).

The v4_1 training forward picks the variant whose clamping matches
the batch item's action_is_pad pattern, so DATA V2 segment samples
get segment-pure token targets while base samples keep full-window
targets. Stored LIBERO commands are converted to physical units
(x0.05 m translation, x0.5 rad rotation-vector, gripper stored
-1=open/+1=closed -> codec open-command (1-g)/2) before encoding.
EEF token ids are remapped from the artifact's [4096, 8192) band
to [0, 4096); the policy adds the offset back before decode.

Outputs (in ~/sera_v4_experiments/quest_probe/):
  acodec2_tokenizer/      fitted AutoProcessor artifact
  acodec2_map.npz         tok_base_ids/len, tok_seg_ids/len
                          [1693, MAXFR, LMAX], ep_len, train/eval
                          episode lists, id_offset, vocab
  acodec2_map_summary.json  atoms, vocab used, tokens/step
  acodec2_fit_report.json   raw codec training report
"""
import glob
import json
import math
import os
import time
from collections import defaultdict

import numpy as np
import pandas as pd

SNAP = os.path.expanduser(
    "~/.cache/huggingface/hub/datasets--lerobot--libero/snapshots/"
    "a1aaacb7f6cd6ee5fb43120f673cebb0cfea7dd4"
)
OUT_DIR = os.path.expanduser("~/sera_v4_experiments/quest_probe")
FPS = 10
WIN = 16
LMAX_CAP = 160
CHUNK = 8192


def to_phys(a: np.ndarray) -> np.ndarray:
    out = np.empty_like(a)
    out[:, 0:3] = a[:, 0:3] * 0.05
    out[:, 3:6] = a[:, 3:6] * 0.5
    out[:, 6] = (1.0 - a[:, 6]) / 2.0
    return out


def main() -> None:
    os.makedirs(OUT_DIR, exist_ok=True)
    t00 = time.time()
    files = sorted(glob.glob(SNAP + "/data/chunk-000/*.parquet"))
    frames = pd.concat(
        [pd.read_parquet(f, columns=["episode_index", "frame_index", "task_index", "action"])
         for f in files],
        ignore_index=True,
    )
    frames = frames.sort_values(["episode_index", "frame_index"]).reset_index(drop=True)
    act = np.stack(frames["action"].to_numpy()).astype(np.float32)
    ep_arr = frames["episode_index"].to_numpy()
    starts = np.flatnonzero(np.r_[True, ep_arr[1:] != ep_arr[:-1]])
    ends = np.r_[starts[1:], len(ep_arr)]
    ep_rows = {}
    for s, e in zip(starts.tolist(), ends.tolist()):
        ep_rows[int(ep_arr[s])] = (int(s), int(e))
    all_eps = sorted(ep_rows)
    n_ep = max(all_eps) + 1
    ep_len = np.zeros(n_ep, dtype=np.int64)
    for ep, (s, e) in ep_rows.items():
        ep_len[ep] = e - s
    maxfr = int(ep_len.max())
    print(f"episodes={len(all_eps)} frames={len(frames)} maxfr={maxfr}", flush=True)

    seg = np.load(os.path.join(OUT_DIR, "segment_map.npz"))
    train_eps = [int(x) for x in seg["train_eps"].tolist()]
    train_set = set(train_eps)
    eval_eps = [ep for ep in all_eps if ep not in train_set]
    seg_end_of = {
        int(k): int(v)
        for k, v in zip(seg["frame_key"].tolist(), seg["frame_seg_end"].tolist())
    }
    print(f"split: {len(train_eps)} train / {len(eval_eps)} eval", flush=True)

    phys_eps = {}
    for ep in all_eps:
        s, e = ep_rows[ep]
        phys_eps[ep] = to_phys(act[s:e])

    from transformers import AutoProcessor

    codec = AutoProcessor.from_pretrained(
        "ZibinDong/ActionCodec2",
        variant="paper-o1-5mm-4k-2bin-1p2ms",
        action_space="single_eef_delta",
        trust_remote_code=True,
    )
    t0 = time.time()
    out = codec.fit([phys_eps[ep] for ep in train_eps], fps=FPS, progress=False)
    if out is not None:
        codec = out
    fit_s = time.time() - t0
    rep = getattr(codec, "training_report", {})
    with open(os.path.join(OUT_DIR, "acodec2_fit_report.json"), "w") as f:
        json.dump(rep, f, indent=1, default=str)
    eef_rep = rep.get("profiles", {}).get("eef", {}) if isinstance(rep, dict) else {}
    print(f"fit done in {fit_s:.1f}s; eef vocab={eef_rep.get('vocab_size')} "
          f"tokens/action(train, episode-level)={eef_rep.get('tokens_per_action')}", flush=True)
    codec.save_pretrained(os.path.join(OUT_DIR, "acodec2_tokenizer"))

    # ---- encode windows, grouped by window length ----
    def encode_group(windows):
        """windows: list of (L,7) arrays of equal L -> list of id lists."""
        res = []
        for i in range(0, len(windows), CHUNK):
            batch = np.stack(windows[i:i + CHUNK])
            res.extend(codec.encode(batch, fps=FPS))
        return res

    variants = {"base": {}, "seg": {}}
    for name in ("base", "seg"):
        by_len = defaultdict(list)
        keys_by_len = defaultdict(list)
        for ep in all_eps:
            s, e = ep_rows[ep]
            n = e - s
            arr = phys_eps[ep]
            for fr in range(n):
                if name == "base":
                    ln = min(WIN, n - fr)
                else:
                    se = seg_end_of.get(ep * 100000 + fr)
                    ln = min(WIN, n - fr) if se is None else min(WIN, se - fr + 1)
                by_len[ln].append(arr[fr:fr + ln])
                keys_by_len[ln].append((ep, fr))
        store = {}
        for ln in sorted(by_len):
            toks = encode_group(by_len[ln])
            assert len(toks) == len(keys_by_len[ln])
            for key, tk in zip(keys_by_len[ln], toks):
                store[key] = tk
        variants[name] = store
        tot_tok = sum(len(v) for v in store.values())
        tot_step = sum(min(WIN, ep_len[ep] - fr) for (ep, fr) in store)
        print(f"{name}: {len(store)} windows, {tot_tok} tokens, "
              f"window tokens/step={tot_tok / tot_step:.4f}", flush=True)

    all_ids = np.concatenate(
        [np.asarray(v, dtype=np.int64) for v in variants["base"].values() if v]
    )
    id_min, id_max = int(all_ids.min()), int(all_ids.max())
    print(f"base id range: [{id_min}, {id_max}]", flush=True)
    assert id_min >= 4096 and id_max < 8192, (
        f"EEF ids not confined to [4096, 8192): [{id_min}, {id_max}] — remap assumption broken"
    )
    OFFSET = 4096

    lens = [len(v) for v in variants["base"].values()] + [len(v) for v in variants["seg"].values()]
    lmax = int(max(lens))
    print(f"token length per window: mean={np.mean(lens):.2f} p50={np.percentile(lens, 50):.0f} "
          f"p95={np.percentile(lens, 95):.0f} p99={np.percentile(lens, 99):.0f} max={lmax}", flush=True)
    assert lmax <= LMAX_CAP, f"window token length {lmax} exceeds cap {LMAX_CAP}"

    arrays = {}
    for name in ("base", "seg"):
        ids = np.zeros((n_ep, maxfr, lmax), dtype=np.int32)
        ln_arr = np.zeros((n_ep, maxfr), dtype=np.int16)
        for (ep, fr), tk in variants[name].items():
            remapped = np.asarray(tk, dtype=np.int64) - OFFSET
            ids[ep, fr, :len(tk)] = remapped
            ln_arr[ep, fr] = len(tk)
        arrays[f"tok_{name}_ids"] = ids
        arrays[f"tok_{name}_len"] = ln_arr

    np.savez_compressed(
        os.path.join(OUT_DIR, "acodec2_map.npz"),
        ep_len=ep_len,
        train_eps=np.asarray(train_eps),
        eval_eps=np.asarray(eval_eps),
        id_offset=np.int64(OFFSET),
        vocab=np.int64(4096),
        **arrays,
    )

    # ---- episode-level tokens/step (paper-comparable) + vocab usage ----
    def episode_tokens_per_step(eps):
        tt = 0
        for ep in eps:
            tt += len(codec.encode(phys_eps[ep][None], fps=FPS)[0])
        ts = sum(int(ep_len[ep]) for ep in eps)
        return tt / ts, tt, ts

    tr_tps, tr_t, tr_s = episode_tokens_per_step(train_eps)
    ev_tps, ev_t, ev_s = episode_tokens_per_step(eval_eps)
    used = np.unique(
        np.concatenate([np.asarray(v) for v in variants["base"].values() if v])
    )
    summary = {
        "fit_seconds": fit_s,
        "fit_episodes": len(train_eps),
        "eef_vocab_size": eef_rep.get("vocab_size"),
        "primitive_atoms": eef_rep.get("primitive_atoms"),
        "physical_bins": eef_rep.get("physical_bins"),
        "eef_spatial_vocab_size": eef_rep.get("temporal", {}).get("spatial_vocab_size")
        if isinstance(eef_rep.get("temporal"), dict) else None,
        "vocab_used_train_windows": int(len(used)),
        "id_offset": OFFSET,
        "id_range_raw": [id_min, id_max],
        "tokens_per_step_episode_level": {"train": tr_tps, "eval": ev_tps},
        "tokens_per_step_window_level": {
            name: sum(len(v) for v in variants[name].values())
            / sum(min(WIN, ep_len[ep] - fr) for (ep, fr) in variants[name])
            for name in ("base", "seg")
        },
        "window_token_length": {
            "mean": float(np.mean(lens)), "p50": float(np.percentile(lens, 50)),
            "p95": float(np.percentile(lens, 95)), "p99": float(np.percentile(lens, 99)),
            "max": lmax,
        },
        "total_seconds": time.time() - t00,
    }
    with open(os.path.join(OUT_DIR, "acodec2_map_summary.json"), "w") as f:
        json.dump(summary, f, indent=1)
    print(json.dumps(summary, indent=1), flush=True)
    print("BUILD DONE", flush=True)


if __name__ == "__main__":
    main()