Download scripts/check_token_len.py from simpk/single_pickplace: direct link, hf CLI and curl.
- Browser
- Download file 4.16 kB
-
https://huggingface.co/datasets/simpk/single_pickplace/resolve/main/scripts/check_token_len.py
- Command line
-
hf download hf://datasets/simpk/single_pickplace/scripts/check_token_len.py
-
curl -L -o check_token_len.py https://huggingface.co/datasets/simpk/single_pickplace/resolve/main/scripts/check_token_len.py
4.16 kB
| """Verify pi0.5's discrete-state prompt fits inside max_token_len for this dataset. | |
| uv run python scripts/check_token_len.py [DATASET_ROOT] [--action-dim 32] [--max-token-len 200] | |
| Why this check exists: with `pi05=True`, openpi's `Pi0.embed_suffix()` skips the continuous state | |
| token (`if not self.pi05:`) and `state_proj` is never constructed, so pi0.5's ONLY proprioception | |
| path is the discretised state string that `PaligemmaTokenizer` packs into the prompt: | |
| "Task: <prompt>, State: <action_dim ints>;\nAction: " | |
| The pi0 default of 48 truncates that after ~9 of 32 state values -- keeping the left arm and | |
| dropping the entire right arm and hand -- while emitting only a `logging.warning`. pi0.5's own | |
| default is 200. | |
| Self-contained: pulls the same PaliGemma tokenizer openpi uses and reads the parquets directly, | |
| so it runs before openpi is installed. | |
| """ | |
| import argparse | |
| import glob | |
| import json | |
| import pathlib | |
| import sys | |
| import urllib.request | |
| import numpy as np | |
| TOKENIZER_URL = "https://storage.googleapis.com/big_vision/paligemma_tokenizer.model" | |
| UPPER = slice(15, 43) # the 28 trained dims of the 43-dim whole-body vector | |
| def main() -> int: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("root", nargs="?", default=str(pathlib.Path(__file__).resolve().parent.parent)) | |
| ap.add_argument("--action-dim", type=int, default=32) | |
| ap.add_argument("--max-token-len", type=int, default=200) | |
| ap.add_argument("--sample-frames", type=int, default=4000) | |
| a = ap.parse_args() | |
| root = pathlib.Path(a.root) | |
| try: | |
| import pandas as pd | |
| import sentencepiece | |
| except ImportError as e: | |
| print(f"needs pandas + sentencepiece + pyarrow: {e}") | |
| return 2 | |
| prompt = json.loads(next(open(root / "meta/tasks.jsonl")))["task"] | |
| cache = pathlib.Path.home() / ".cache" / "paligemma_tokenizer.model" | |
| if not cache.exists(): | |
| cache.parent.mkdir(parents=True, exist_ok=True) | |
| print(f"fetching tokenizer -> {cache}") | |
| urllib.request.urlretrieve(TOKENIZER_URL, cache) # noqa: S310 - fixed GCS URL | |
| sp = sentencepiece.SentencePieceProcessor(model_file=str(cache)) | |
| files = sorted(glob.glob(str(root / "data/chunk-000/episode_*.parquet"))) | |
| if not files: | |
| print(f"no parquet files under {root}/data/chunk-000") | |
| return 2 | |
| # Sample across the whole dataset, not just the first episode: state range drives digit count. | |
| step = max(1, len(files) // 40) | |
| S = np.concatenate([ | |
| np.stack([np.asarray(v, float) for v in pd.read_parquet(f, columns=["observation.state"])["observation.state"]]) | |
| for f in files[::step] | |
| ])[:, UPPER] | |
| # pi0.5 normalises state with q01/q99 quantiles, then pads to action_dim, then discretises. | |
| q01, q99 = np.percentile(S, 1, axis=0), np.percentile(S, 99, axis=0) | |
| N = (S - q01) / (q99 - q01 + 1e-6) * 2.0 - 1.0 | |
| N = np.pad(N, ((0, 0), (0, max(0, a.action_dim - N.shape[1])))) | |
| idx = np.linspace(0, len(N) - 1, min(a.sample_frames, len(N))).astype(int) | |
| lens = [] | |
| for i in idx: | |
| d = np.digitize(N[i], bins=np.linspace(-1, 1, 257)[:-1]) - 1 | |
| full = f"Task: {prompt.strip()}, State: {' '.join(map(str, d))};\nAction: " | |
| lens.append(len(sp.encode(full, add_bos=True))) | |
| lens = np.array(lens) | |
| print(f"task {prompt!r}") | |
| print(f"action_dim {a.action_dim} frames sampled {len(lens)}") | |
| print(f"token length min={lens.min()} median={int(np.median(lens))} " | |
| f"p99={int(np.percentile(lens,99))} max={lens.max()}") | |
| print() | |
| for L in (48, 64, 128, 200, 256): | |
| over = 100 * (lens > L).mean() | |
| mark = " <-- your setting" if L == a.max_token_len else "" | |
| print(f" max_token_len={L:>4}: {'OK' if over == 0 else f'TRUNCATES {over:.1f}% of frames'}{mark}") | |
| ok = int(lens.max()) <= a.max_token_len | |
| print(f"\nmax_token_len={a.max_token_len}: {'PASS' if ok else 'FAIL'}" | |
| f" (needs >= {int(lens.max())})") | |
| if not ok: | |
| print("Leave max_token_len unset in Pi0Config so the pi05 default of 200 applies.") | |
| return 0 if ok else 1 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |