Transformers
tobiges commited on
Commit
c343f91
·
verified ·
1 Parent(s): 15817e5

Upload processor

Browse files
Files changed (2) hide show
  1. processing_action_tokenizer.py +53 -35
  2. tokenizer.json +0 -0
processing_action_tokenizer.py CHANGED
@@ -1,13 +1,6 @@
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
  import numpy as np
12
  from scipy.fft import dct, idct
13
  from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
@@ -15,7 +8,7 @@ from tokenizers.models import BPE
15
  from tokenizers.trainers import BpeTrainer
16
  from transformers import PreTrainedTokenizerFast
17
  from transformers.processing_utils import ProcessorMixin
18
- from tokenizers import Tokenizer
19
 
20
  class UniversalActionProcessor(ProcessorMixin):
21
  attributes: ClassVar[list[str]] = ["bpe_tokenizer"]
@@ -48,7 +41,9 @@ class UniversalActionProcessor(ProcessorMixin):
48
  super().__init__(bpe_tokenizer)
49
 
50
  def __call__(self, action_chunk: np.array) -> np.array:
51
- assert action_chunk.ndim <= 3, "Only 3 dimensions supported: [batch, timesteps, action_dim]"
 
 
52
  if action_chunk.ndim == 2:
53
  action_chunk = action_chunk[None, ...]
54
 
@@ -60,7 +55,9 @@ class UniversalActionProcessor(ProcessorMixin):
60
  dct_coeff = np.around(dct_coeff * self.scale)
61
  tokens = []
62
  for elem in dct_coeff:
63
- token_str = "".join(map(chr, np.maximum(elem.flatten() - self.min_token, 0).astype(int)))
 
 
64
  tokens.append(self.bpe_tokenizer(token_str)["input_ids"])
65
  return tokens
66
 
@@ -71,35 +68,40 @@ class UniversalActionProcessor(ProcessorMixin):
71
  time_horizon: int | None = None,
72
  action_dim: int | None = None,
73
  ) -> np.array:
74
- self.time_horizon = time_horizon or self.time_horizon or self.called_time_horizon
 
 
75
  self.action_dim = action_dim or self.action_dim or self.called_action_dim
76
 
77
  # Cache the time horizon and action dimension for the next call
78
  self.called_time_horizon = self.time_horizon
79
  self.called_action_dim = self.action_dim
80
 
81
- assert (
82
- self.time_horizon is not None and self.action_dim is not None
83
- ), "Tokenizer not initialized, call encode() once or pass in time_horizon and action_dim."
84
 
85
  decoded_actions = []
86
  for token in tokens:
87
  try:
88
  decoded_tokens = self.bpe_tokenizer.decode(token)
89
- decoded_dct_coeff = np.array(list(map(ord, decoded_tokens))) + self.min_token
 
 
90
  decoded_dct_coeff = decoded_dct_coeff.reshape(-1, self.action_dim)
91
- assert (
92
- decoded_dct_coeff.shape
93
- == (
94
- self.time_horizon,
95
- self.action_dim,
96
- )
97
- ), f"Decoded DCT coefficients have shape {decoded_dct_coeff.shape}, expected ({self.time_horizon}, {self.action_dim})"
98
  except Exception as e:
99
  print(f"Error decoding tokens: {e}")
100
  print(f"Tokens: {token}")
101
  decoded_dct_coeff = np.zeros((self.time_horizon, self.action_dim))
102
- decoded_actions.append(idct(decoded_dct_coeff / self.scale, axis=0, norm="ortho"))
 
 
103
  return np.stack(decoded_actions)
104
 
105
  @classmethod
@@ -119,19 +121,25 @@ class UniversalActionProcessor(ProcessorMixin):
119
  max_token = int(np.around(np.concatenate(dct_tokens) * scale).max())
120
  min_token = int(np.around(np.concatenate(dct_tokens) * scale).min())
121
  min_vocab_size = max_token - min_token
122
- print(f"Min token: {min_token}, Max token: {max_token}, Min vocab size: {min_vocab_size}")
 
 
123
 
124
- assert (
125
- min_vocab_size <= vocab_size
126
- ), f"Vocab size {vocab_size} is too small for the range of tokens {min_vocab_size}"
127
  if min_vocab_size + 100 > vocab_size:
128
  logging.warning(
129
  f"Initial alphabet size {min_vocab_size} is almost as large as the vocab"
130
  f"size {vocab_size}, consider increasing vocab size"
131
  )
132
 
133
- assert min_token >= -128 + 10, f"Min token {min_token} is less than -128 + 10 (for buffer space)"
134
- assert max_token < 128 - 10, f"Max token {max_token} is greater than 128 - 10 (for buffer space)"
 
 
 
 
135
  min_token = -128
136
 
137
  # Make token iterator for BPE training
@@ -163,9 +171,17 @@ class UniversalActionProcessor(ProcessorMixin):
163
 
164
  # Train BPE tokenizer
165
  tokenizer = Tokenizer(BPE())
166
- tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False)
167
- tokenizer.decoder = decoders.ByteLevel()
168
- tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
 
 
 
 
 
 
 
 
169
 
170
  # Set up the entire range of possible tokens as the initial alphabet
171
  alphabet = [chr(i) for i in range(256)]
@@ -176,15 +192,17 @@ class UniversalActionProcessor(ProcessorMixin):
176
  special_tokens=[],
177
  # initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
178
  initial_alphabet=alphabet,
179
- # max_token_length=256,
180
- max_token_length=10_000,
181
  )
182
  tokenizer.train_from_iterator(
183
  _token_iter(), trainer=trainer, length=len(dct_tokens)
184
  )
185
 
186
  return cls(
187
- PreTrainedTokenizerFast(tokenizer_object=tokenizer, clean_up_tokenization_spaces=False),
 
 
188
  scale=scale,
189
  vocab_size=vocab_size,
190
  min_token=min_token,
 
1
  import logging
2
  from typing import ClassVar
3
 
 
 
 
 
 
 
 
4
  import numpy as np
5
  from scipy.fft import dct, idct
6
  from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
 
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"]
 
41
  super().__init__(bpe_tokenizer)
42
 
43
  def __call__(self, action_chunk: np.array) -> np.array:
44
+ assert action_chunk.ndim <= 3, (
45
+ "Only 3 dimensions supported: [batch, timesteps, action_dim]"
46
+ )
47
  if action_chunk.ndim == 2:
48
  action_chunk = action_chunk[None, ...]
49
 
 
55
  dct_coeff = np.around(dct_coeff * self.scale)
56
  tokens = []
57
  for elem in dct_coeff:
58
+ token_str = "".join(
59
+ map(chr, np.maximum(elem.flatten() - self.min_token, 0).astype(int))
60
+ )
61
  tokens.append(self.bpe_tokenizer(token_str)["input_ids"])
62
  return tokens
63
 
 
68
  time_horizon: int | None = None,
69
  action_dim: int | None = None,
70
  ) -> np.array:
71
+ self.time_horizon = (
72
+ time_horizon or self.time_horizon or self.called_time_horizon
73
+ )
74
  self.action_dim = action_dim or self.action_dim or self.called_action_dim
75
 
76
  # Cache the time horizon and action dimension for the next call
77
  self.called_time_horizon = self.time_horizon
78
  self.called_action_dim = self.action_dim
79
 
80
+ assert self.time_horizon is not None and self.action_dim is not None, (
81
+ "Tokenizer not initialized, call encode() once or pass in time_horizon and action_dim."
82
+ )
83
 
84
  decoded_actions = []
85
  for token in tokens:
86
  try:
87
  decoded_tokens = self.bpe_tokenizer.decode(token)
88
+ decoded_dct_coeff = (
89
+ np.array(list(map(ord, decoded_tokens))) + self.min_token
90
+ )
91
  decoded_dct_coeff = decoded_dct_coeff.reshape(-1, self.action_dim)
92
+ assert decoded_dct_coeff.shape == (
93
+ self.time_horizon,
94
+ self.action_dim,
95
+ ), (
96
+ f"Decoded DCT coefficients have shape {decoded_dct_coeff.shape}, expected ({self.time_horizon}, {self.action_dim})"
97
+ )
 
98
  except Exception as e:
99
  print(f"Error decoding tokens: {e}")
100
  print(f"Tokens: {token}")
101
  decoded_dct_coeff = np.zeros((self.time_horizon, self.action_dim))
102
+ decoded_actions.append(
103
+ idct(decoded_dct_coeff / self.scale, axis=0, norm="ortho")
104
+ )
105
  return np.stack(decoded_actions)
106
 
107
  @classmethod
 
121
  max_token = int(np.around(np.concatenate(dct_tokens) * scale).max())
122
  min_token = int(np.around(np.concatenate(dct_tokens) * scale).min())
123
  min_vocab_size = max_token - min_token
124
+ print(
125
+ f"Min token: {min_token}, Max token: {max_token}, Min vocab size: {min_vocab_size}"
126
+ )
127
 
128
+ assert min_vocab_size <= vocab_size, (
129
+ f"Vocab size {vocab_size} is too small for the range of tokens {min_vocab_size}"
130
+ )
131
  if min_vocab_size + 100 > vocab_size:
132
  logging.warning(
133
  f"Initial alphabet size {min_vocab_size} is almost as large as the vocab"
134
  f"size {vocab_size}, consider increasing vocab size"
135
  )
136
 
137
+ assert min_token >= -128 + 10, (
138
+ f"Min token {min_token} is less than -128 + 10 (for buffer space)"
139
+ )
140
+ assert max_token < 128 - 10, (
141
+ f"Max token {max_token} is greater than 128 - 10 (for buffer space)"
142
+ )
143
  min_token = -128
144
 
145
  # Make token iterator for BPE training
 
171
 
172
  # Train BPE tokenizer
173
  tokenizer = Tokenizer(BPE())
174
+ tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(
175
+ add_prefix_space=False, use_regex=False, trim_offsets=False
176
+ )
177
+ tokenizer.pre_tokenizer.pre_tokenize_str
178
+ tokenizer.decoder = decoders.ByteLevel(
179
+ add_prefix_space=False, trim_offsets=False, use_regex=False
180
+ )
181
+ tokenizer.dec
182
+ tokenizer.post_processor = processors.ByteLevel(
183
+ add_prefix_space=False, trim_offsets=False, use_regex=False
184
+ )
185
 
186
  # Set up the entire range of possible tokens as the initial alphabet
187
  alphabet = [chr(i) for i in range(256)]
 
192
  special_tokens=[],
193
  # initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
194
  initial_alphabet=alphabet,
195
+ max_token_length=256,
196
+ # max_token_length=10_000,
197
  )
198
  tokenizer.train_from_iterator(
199
  _token_iter(), trainer=trainer, length=len(dct_tokens)
200
  )
201
 
202
  return cls(
203
+ PreTrainedTokenizerFast(
204
+ tokenizer_object=tokenizer, clean_up_tokenization_spaces=False
205
+ ),
206
  scale=scale,
207
  vocab_size=vocab_size,
208
  min_token=min_token,
tokenizer.json CHANGED
The diff for this file is too large to render. See raw diff