File size: 4,497 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
"""FAST action tokenizer, re-implemented from the paper (Pertsch et al. 2025, "FAST: Efficient Action
Tokenization for Vision-Language-Action Models"): DCT over time per action dim, scale and round, flatten
low-frequency first, then byte-pair encoding over the integer symbols.

Written locally instead of loading `physical-intelligence/fast` with trust_remote_code. Same pipeline as that
processor (dct(norm="ortho") along time, round(coeff * scale), row-major flatten of [T, D] so all dims of
frequency 0 come first, BPE over one character per integer). PiBehavior fits its own tokenizer with vocab 1024,
scale 10 (scripts/train_fast_tokenizer.py); B4 does the same on LIBERO.

The DCT/quantise half is pure numpy/scipy (tested in the course env). BPE uses the `tokenizers` library
(Rust; installed in the LeRobot env with transformers).
"""
from __future__ import annotations

import json
from pathlib import Path

import numpy as np
from scipy.fft import dct, idct

OFFSET = 0x4E00  # map integers into the CJK block: no whitespace/control characters reach the BPE model


def quantize(chunks: np.ndarray, scale: float) -> np.ndarray:
    """[N, T, D] actions (≈[-1, 1]) -> integer DCT coefficients [N, T*D], frequency-major."""
    c = dct(np.asarray(chunks, float), axis=1, norm="ortho")
    return np.rint(c * scale).astype(np.int64).reshape(len(c), -1)


def dequantize(coeffs: np.ndarray, scale: float, T: int, D: int) -> np.ndarray:
    return idct(np.asarray(coeffs, float).reshape(-1, T, D) / scale, axis=1, norm="ortho")


class FastTokenizer:
    def __init__(self, scale: float, T: int, D: int, lo: int, hi: int, bpe=None):
        self.scale, self.T, self.D, self.lo, self.hi, self.bpe = scale, T, D, lo, hi, bpe

    # ---------------------------------------------------------------- symbols <-> text
    def _to_text(self, q: np.ndarray) -> list[str]:
        q = np.clip(q, self.lo, self.hi) - self.lo  # unseen extremes are clipped to the fitted range
        return ["".join(chr(OFFSET + int(v)) for v in row) for row in q]

    def _from_text(self, s: str) -> np.ndarray:
        q = np.array([ord(ch) - OFFSET + self.lo for ch in s], np.int64)
        n = self.T * self.D
        return np.pad(q[:n], (0, max(0, n - len(q))))  # truncated token streams decode with zeros

    # ---------------------------------------------------------------- fit / encode / decode
    @classmethod
    def fit(cls, chunks: np.ndarray, scale: float = 10.0, vocab_size: int = 1024) -> FastTokenizer:
        from tokenizers import Tokenizer, models, trainers
        N, T, D = chunks.shape
        q = quantize(chunks, scale)
        tok = cls(scale, T, D, int(q.min()), int(q.max()))
        alphabet = [chr(OFFSET + i) for i in range(tok.hi - tok.lo + 1)]
        if vocab_size < len(alphabet):
            raise ValueError(f"vocab_size {vocab_size} < alphabet {len(alphabet)}: raise vocab or lower scale")
        bpe = Tokenizer(models.BPE())
        trainer = trainers.BpeTrainer(vocab_size=vocab_size, initial_alphabet=alphabet, show_progress=False,
                                      special_tokens=[], limit_alphabet=len(alphabet))
        bpe.train_from_iterator(tok._to_text(q), trainer=trainer)
        tok.bpe = bpe
        return tok

    def encode(self, chunks: np.ndarray) -> list[list[int]]:
        return [e.ids for e in self.bpe.encode_batch(self._to_text(quantize(chunks, self.scale)))]

    def decode(self, token_lists) -> np.ndarray:
        rows = ["".join(self.bpe.id_to_token(int(i)) or "" for i in ids) for ids in token_lists]
        return dequantize(np.stack([self._from_text(s) for s in rows]), self.scale, self.T, self.D)

    @property
    def vocab_size(self) -> int:
        return self.bpe.get_vocab_size()

    # ---------------------------------------------------------------- persistence
    def save(self, d: str | Path):
        d = Path(d); d.mkdir(parents=True, exist_ok=True)
        self.bpe.save(str(d / "bpe.json"))
        (d / "fast.json").write_text(json.dumps({"scale": self.scale, "T": self.T, "D": self.D, "lo": self.lo,
                                                 "hi": self.hi, "offset": OFFSET}))

    @classmethod
    def load(cls, d: str | Path) -> FastTokenizer:
        from tokenizers import Tokenizer
        d = Path(d)
        m = json.loads((d / "fast.json").read_text())
        assert m["offset"] == OFFSET
        return cls(m["scale"], m["T"], m["D"], m["lo"], m["hi"], Tokenizer.from_file(str(d / "bpe.json")))