hungchiayu commited on
Commit
11f7d9a
·
verified ·
1 Parent(s): 9851098

Create processing_action_tokenizer.py

Browse files
Files changed (1) hide show
  1. processing_action_tokenizer.py +158 -0
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
+ )