File size: 2,984 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 | #!/usr/bin/env python3
"""B4 asset: fit a FAST tokenizer (DCT + BPE, vocab 1024, scale 10) on LIBERO 50-step action chunks, as the
authors' scripts/train_fast_tokenizer.py does for BEHAVIOR. Actions are renormalised with global q01/q99 to
[-1, 1] (their TokenizeFASTActions). Uses the local re-implementation in fast_tokenizer.py (no remote code).
Writes assets/fast_tokenizer/ and the token-length distribution that sets max_fast_tokens.
Usage: envs/lerobot/.venv/bin/python experiments/lerobot/prepare_fast_tokenizer.py [--n 20000]
"""
import argparse
import importlib.util
import json
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
HERE = Path(__file__).resolve().parent
def _load(name):
spec = importlib.util.spec_from_file_location(name, HERE / f"{name}.py")
mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
return mod
V, F = _load("variants"), _load("fast_tokenizer")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--horizon", type=int, default=50)
ap.add_argument("--n", type=int, default=20000)
ap.add_argument("--vocab", type=int, default=1024)
ap.add_argument("--scale", type=float, default=10.0)
a = ap.parse_args()
from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
root = Path(LeRobotDatasetMetadata("HuggingFaceVLA/libero").root)
st = json.loads((root / "meta/stats.json").read_text())["action"]
q01, q99 = np.asarray(st["q01"]), np.asarray(st["q99"])
acts, eps = [], []
for f in sorted((root / "data").rglob("*.parquet")):
t = pq.read_table(f, columns=["action", "episode_index"])
acts.append(np.stack(t.column("action").to_numpy(zero_copy_only=False)))
eps.append(t.column("episode_index").to_numpy())
A, E = V.fast_quantile_normalize(np.concatenate(acts), q01, q99), np.concatenate(eps)
episodes = [A[E == e] for e in np.unique(E)]
chunks = V.chunk_windows(episodes, a.horizon, a.n, np.random.default_rng(0))
tok = F.FastTokenizer.fit(chunks, scale=a.scale, vocab_size=a.vocab)
out = HERE / "assets/fast_tokenizer"
tok.save(out)
test = V.chunk_windows(episodes, a.horizon, 2000, np.random.default_rng(1)) # held-out draw
ids = tok.encode(test)
lens = np.array([len(t) for t in ids])
rmse = float(np.sqrt(((tok.decode(ids) - test) ** 2).mean()))
meta = {"vocab": tok.vocab_size, "scale": a.scale, "horizon": a.horizon, "action_dim": int(chunks.shape[2]),
"n_fit_chunks": a.n, "symbol_range": [tok.lo, tok.hi],
"token_len_quantiles": {str(q): float(np.quantile(lens, q)) for q in (0.5, 0.95, 0.99, 1.0)},
"symbols_per_chunk": a.horizon * int(chunks.shape[2]),
"roundtrip_rmse_quantile_units": rmse, "normalisation": "global q01/q99 -> [-1, 1], clipped"}
(out / "course_meta.json").write_text(json.dumps(meta, indent=2))
print(json.dumps(meta, indent=2))
if __name__ == "__main__":
main()
|