jadechoghari commited on
Commit
f88b070
·
verified ·
1 Parent(s): 723831c

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ tags:
5
+ - robotics
6
+ - tokenizer
7
+ ---
8
+
9
+ # FAST: Efficient Action Tokenization for Vision-Language-Action Models
10
+
11
+ This is the official repo for the [FAST action tokenizer](https://www.pi.website/research/fast).
12
+
13
+ The action tokenizer maps any sequence of robot actions into a sequence of dense, discrete **action tokens** for training autoregressive VLA models.
14
+
15
+ Here, we provide:
16
+ 1. FAST+, our *universal* action tokenizer, trained on 1M real robot action sequences.
17
+ 2. Code for quickly training *new* action tokenizers on your custom dataset.
18
+
19
+ ## Installation
20
+
21
+ FAST can be used as a convenient HuggingFace AutoProcessor. To use it, simply install the `transformers` package (and `scipy` for the underlying DCT algorithm).
22
+
23
+ ```
24
+ pip install transformers scipy
25
+ ```
26
+
27
+ ## Using the Universal Action Tokenizer
28
+
29
+ We recommend applying the tokenizer to 1-second action "chunks" that have been pre-normalized to a range of [-1...1]
30
+ (we use quantile normalization for this step -- check our paper). Encoding and decoding support batched inference.
31
+
32
+ ```
33
+ import numpy as np
34
+ from transformers import AutoProcessor
35
+
36
+ # Load the tokenizer from the Hugging Face hub
37
+ tokenizer = AutoProcessor.from_pretrained("physical-intelligence/fast", trust_remote_code=True)
38
+
39
+ # Tokenize & decode action chunks (we use dummy data here)
40
+ action_data = np.random.rand(256, 50, 14) # one batch of action chunks
41
+ tokens = tokenizer(action_data) # tokens = list[int]
42
+ decoded_actions = tokenizer.decode(tokens)
43
+ ```
44
+
45
+ **Note**: During decoding, the tokenizer needs to map the decoded sequence of actions back into a `[time_horizon, action_dim]` matrix.
46
+ There are multiple ways to provide the necessary dimensions to the tokenizer: (1) they automatically get saved on the first `forward()` call, (2) you can set them manually as arguments to the `decode()` call
47
+
48
+
49
+ ## Training a new Action Tokenizer on Your Own Data
50
+
51
+ In our experiments, we found the FAST+ universal tokenizer to work well across a wide range of robot setups, action dimensions, and control frequencies.
52
+ If you, however, want to train a custom FAST tokenizer for your dataset at hand, it is very easy using the `.fit()` convenience function we provide.
53
+ When called on a dataset of action chunks (of the same or different lengths), it returns a new tokenizer instance, which you can save and optionally push
54
+ to the HuggingFace hub. Training should typically only take a few seconds to minutes.
55
+
56
+ ```
57
+ # First, we download the tokenizer from the Hugging Face model hub
58
+ # Here, we will not use the pre-trained tokenizer weights, but only the source code
59
+ # to train a new tokenizer on our own data.
60
+ tokenizer = AutoProcessor.from_pretrained("physical-intelligence/fast", trust_remote_code=True)
61
+
62
+ # Load your action data for tokenizer training
63
+ # Chunks do not need to be of the same length, we will use dummy data
64
+ action_data = np.random.rand(4000, 50, 14)
65
+
66
+ # Train the new tokenizer, depending on your dataset size this can take a few minutes
67
+ tokenizer = tokenizer.fit(action_data)
68
+
69
+ # Save the new tokenizer, optionally push it to the Hugging Face model hub
70
+ tokenizer.save_pretrained("<your_local_path>")
71
+ tokenizer.push_to_hub("YourUsername/my_new_tokenizer")
72
+ ```
processing_action_tokenizer.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import ClassVar
3
+
4
+ import numpy as np
5
+ from scipy.fft import dct
6
+ from scipy.fft import idct
7
+ from tokenizers import ByteLevelBPETokenizer
8
+ from tokenizers.trainers import BpeTrainer
9
+ from transformers import PreTrainedTokenizerFast
10
+ from transformers.processing_utils import ProcessorMixin
11
+
12
+
13
+ class UniversalActionProcessor(ProcessorMixin):
14
+ attributes: ClassVar[list[str]] = ["bpe_tokenizer"]
15
+ bpe_tokenizer_class: str = "AutoTokenizer"
16
+
17
+ def __init__(
18
+ self,
19
+ bpe_tokenizer: PreTrainedTokenizerFast,
20
+ scale: float = 10,
21
+ vocab_size: int = 1024,
22
+ min_token: int = 0,
23
+ *,
24
+ action_dim: int | None = None,
25
+ time_horizon: int | None = None,
26
+ ):
27
+ self.scale = scale
28
+ self.vocab_size = vocab_size
29
+ self.min_token = min_token
30
+
31
+ # Action horizon and dimension needed during decoding. These can be specified
32
+ # in three ways (in order of priority):
33
+ # 1. passed in as kwargs to decode()
34
+ # 2. in the constructor
35
+ # 3. cached from the last time decode() was called
36
+ self.time_horizon = time_horizon
37
+ self.action_dim = action_dim
38
+ self.called_time_horizon = time_horizon
39
+ self.called_action_dim = action_dim
40
+
41
+ super().__init__(bpe_tokenizer)
42
+
43
+ def __call__(self, action_chunk: np.array) -> np.array:
44
+ assert action_chunk.ndim <= 3, "Only 3 dimensions supported: [batch, timesteps, action_dim]"
45
+ if action_chunk.ndim == 2:
46
+ action_chunk = action_chunk[None, ...]
47
+
48
+ # Cache the time horizon and action dimension for decoding
49
+ self.called_time_horizon = action_chunk.shape[-2]
50
+ self.called_action_dim = action_chunk.shape[-1]
51
+
52
+ dct_coeff = dct(action_chunk, axis=1, norm="ortho")
53
+ dct_coeff = np.around(dct_coeff * self.scale)
54
+ tokens = []
55
+ for elem in dct_coeff:
56
+ token_str = "".join(map(chr, np.maximum(elem.flatten() - self.min_token, 0).astype(int)))
57
+ tokens.append(self.bpe_tokenizer(token_str)["input_ids"])
58
+ return tokens
59
+
60
+ def decode(
61
+ self,
62
+ tokens: list[list[int]],
63
+ *,
64
+ time_horizon: int | None = None,
65
+ action_dim: int | None = None,
66
+ ) -> np.array:
67
+ self.time_horizon = time_horizon or self.time_horizon or self.called_time_horizon
68
+ self.action_dim = action_dim or self.action_dim or self.called_action_dim
69
+
70
+ # Cache the time horizon and action dimension for the next call
71
+ self.called_time_horizon = self.time_horizon
72
+ self.called_action_dim = self.action_dim
73
+
74
+ assert (
75
+ self.time_horizon is not None and self.action_dim is not None
76
+ ), "Tokenizer not initialized, call encode() once or pass in time_horizon and action_dim."
77
+
78
+ decoded_actions = []
79
+ for token in tokens:
80
+ try:
81
+ decoded_tokens = self.bpe_tokenizer.decode(token)
82
+ decoded_dct_coeff = np.array(list(map(ord, decoded_tokens))) + self.min_token
83
+ decoded_dct_coeff = decoded_dct_coeff.reshape(-1, self.action_dim)
84
+ assert (
85
+ decoded_dct_coeff.shape
86
+ == (
87
+ self.time_horizon,
88
+ self.action_dim,
89
+ )
90
+ ), f"Decoded DCT coefficients have shape {decoded_dct_coeff.shape}, expected ({self.time_horizon}, {self.action_dim})"
91
+ except Exception as e:
92
+ print(f"Error decoding tokens: {e}")
93
+ print(f"Tokens: {token}")
94
+ decoded_dct_coeff = np.zeros((self.time_horizon, self.action_dim))
95
+ decoded_actions.append(idct(decoded_dct_coeff / self.scale, axis=0, norm="ortho"))
96
+ return np.stack(decoded_actions)
97
+
98
+ @classmethod
99
+ def fit(
100
+ cls,
101
+ action_data: list[np.array],
102
+ scale: float = 10,
103
+ vocab_size: int = 1024,
104
+ *,
105
+ time_horizon: int | None = None,
106
+ action_dim: int | None = None,
107
+ ) -> "UniversalActionProcessor":
108
+ # Run DCT over all inputs
109
+ dct_tokens = [dct(a, axis=0, norm="ortho").flatten() for a in action_data]
110
+
111
+ # Quantize and find min token
112
+ max_token = int(np.around(np.concatenate(dct_tokens) * scale).max())
113
+ min_token = int(np.around(np.concatenate(dct_tokens) * scale).min())
114
+ min_vocab_size = max_token - min_token
115
+
116
+ assert (
117
+ min_vocab_size <= vocab_size
118
+ ), f"Vocab size {vocab_size} is too small for the range of tokens {min_vocab_size}"
119
+ if min_vocab_size + 100 > vocab_size:
120
+ logging.warning(
121
+ f"Initial alphabet size {min_vocab_size} is almost as large as the vocab"
122
+ f"size {vocab_size}, consider increasing vocab size"
123
+ )
124
+
125
+ # Make token iterator for BPE training
126
+ def _token_iter():
127
+ for tokens in dct_tokens:
128
+ rounded_tokens = np.around(tokens * scale) - min_token
129
+ rounded_tokens = rounded_tokens.astype(int)
130
+ string = "".join(map(chr, rounded_tokens))
131
+ yield string
132
+
133
+ # Train BPE tokenizer
134
+ bpe = ByteLevelBPETokenizer()
135
+
136
+ # Set up the entire range of possible tokens as the initial alphabet
137
+ alphabet = [chr(i) for i in range(max_token - min_token + 1)]
138
+ trainer = BpeTrainer(
139
+ vocab_size=vocab_size,
140
+ min_frequency=2,
141
+ show_progress=True,
142
+ special_tokens=[],
143
+ initial_alphabet=alphabet,
144
+ max_token_length=10000,
145
+ )
146
+
147
+ # Train the inner tokenizer (don't use ByteLevelBPETokenizer.train_from_iterator()
148
+ # because it doesn't support custom alphabets)
149
+ bpe._tokenizer.train_from_iterator(_token_iter(), trainer=trainer)
150
+
151
+ return cls(
152
+ PreTrainedTokenizerFast(tokenizer_object=bpe, clean_up_tokenization_spaces=False),
153
+ scale=scale,
154
+ vocab_size=vocab_size,
155
+ min_token=min_token,
156
+ time_horizon=time_horizon,
157
+ action_dim=action_dim,
158
+ )
processor_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "action_dim": null,
3
+ "auto_map": {
4
+ "AutoProcessor": "processing_action_tokenizer.UniversalActionProcessor"
5
+ },
6
+ "min_token": -354,
7
+ "processor_class": "UniversalActionProcessor",
8
+ "scale": 10,
9
+ "time_horizon": null,
10
+ "vocab_size": 2048
11
+ }
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {},
3
+ "auto_map": {
4
+ "AutoProcessor": "processing_action_tokenizer.UniversalActionProcessor"
5
+ },
6
+ "clean_up_tokenization_spaces": true,
7
+ "model_max_length": 1000000000000000019884624838656,
8
+ "processor_class": "UniversalActionProcessor",
9
+ "tokenizer_class": "PreTrainedTokenizerFast"
10
+ }