Transformers
tobiges commited on
Commit
8ea8c8b
·
verified ·
1 Parent(s): 282a289

Upload processor

Browse files
Files changed (2) hide show
  1. processing_action_tokenizer.py +43 -41
  2. tokenizer.json +0 -0
processing_action_tokenizer.py CHANGED
@@ -4,11 +4,11 @@ from typing import ClassVar
4
 
5
  import numpy as np
6
  from scipy.fft import dct, idct
7
- from tokenizers import ByteLevelBPETokenizer, AddedToken, Tokenizer, decoders, pre_tokenizers, processors, trainers
 
8
  from tokenizers.trainers import BpeTrainer
9
- from transformers.processing_utils import ProcessorMixin
10
  from transformers import PreTrainedTokenizerFast
11
- from tokenizers.models import BPE
12
 
13
 
14
  class UniversalActionProcessor(ProcessorMixin):
@@ -42,7 +42,9 @@ class UniversalActionProcessor(ProcessorMixin):
42
  super().__init__(bpe_tokenizer)
43
 
44
  def __call__(self, action_chunk: np.array) -> np.array:
45
- assert action_chunk.ndim <= 3, "Only 3 dimensions supported: [batch, timesteps, action_dim]"
 
 
46
  if action_chunk.ndim == 2:
47
  action_chunk = action_chunk[None, ...]
48
 
@@ -54,7 +56,9 @@ class UniversalActionProcessor(ProcessorMixin):
54
  dct_coeff = np.around(dct_coeff * self.scale)
55
  tokens = []
56
  for elem in dct_coeff:
57
- token_str = "".join(map(chr, np.maximum(elem.flatten() - self.min_token, 0).astype(int)))
 
 
58
  tokens.append(self.bpe_tokenizer(token_str)["input_ids"])
59
  return tokens
60
 
@@ -65,35 +69,40 @@ class UniversalActionProcessor(ProcessorMixin):
65
  time_horizon: int | None = None,
66
  action_dim: int | None = None,
67
  ) -> np.array:
68
- self.time_horizon = time_horizon or self.time_horizon or self.called_time_horizon
 
 
69
  self.action_dim = action_dim or self.action_dim or self.called_action_dim
70
 
71
  # Cache the time horizon and action dimension for the next call
72
  self.called_time_horizon = self.time_horizon
73
  self.called_action_dim = self.action_dim
74
 
75
- assert (
76
- self.time_horizon is not None and self.action_dim is not None
77
- ), "Tokenizer not initialized, call encode() once or pass in time_horizon and action_dim."
78
 
79
  decoded_actions = []
80
  for token in tokens:
81
  try:
82
  decoded_tokens = self.bpe_tokenizer.decode(token)
83
- decoded_dct_coeff = np.array(list(map(ord, decoded_tokens))) + self.min_token
 
 
84
  decoded_dct_coeff = decoded_dct_coeff.reshape(-1, self.action_dim)
85
- assert (
86
- decoded_dct_coeff.shape
87
- == (
88
- self.time_horizon,
89
- self.action_dim,
90
- )
91
- ), f"Decoded DCT coefficients have shape {decoded_dct_coeff.shape}, expected ({self.time_horizon}, {self.action_dim})"
92
  except Exception as e:
93
  print(f"Error decoding tokens: {e}")
94
  print(f"Tokens: {token}")
95
  decoded_dct_coeff = np.zeros((self.time_horizon, self.action_dim))
96
- decoded_actions.append(idct(decoded_dct_coeff / self.scale, axis=0, norm="ortho"))
 
 
97
  return np.stack(decoded_actions)
98
 
99
  @classmethod
@@ -113,11 +122,13 @@ class UniversalActionProcessor(ProcessorMixin):
113
  max_token = int(np.around(np.concatenate(dct_tokens) * scale).max())
114
  min_token = int(np.around(np.concatenate(dct_tokens) * scale).min())
115
  min_vocab_size = max_token - min_token
116
- print(f"Min token: {min_token}, Max token: {max_token}, Min vocab size: {min_vocab_size}")
 
 
117
 
118
- assert (
119
- min_vocab_size <= vocab_size
120
- ), f"Vocab size {vocab_size} is too small for the range of tokens {min_vocab_size}"
121
  if min_vocab_size + 100 > vocab_size:
122
  logging.warning(
123
  f"Initial alphabet size {min_vocab_size} is almost as large as the vocab"
@@ -133,12 +144,11 @@ class UniversalActionProcessor(ProcessorMixin):
133
  yield string
134
 
135
  # Train BPE tokenizer
136
- # bpe = ByteLevelBPETokenizer()
137
  tokenizer = Tokenizer(BPE())
138
- tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel()
139
  tokenizer.decoder = decoders.ByteLevel()
140
- tokenizer.post_processor = processors.ByteLevel()
141
-
142
  # Set up the entire range of possible tokens as the initial alphabet
143
  # alphabet = [chr(i) for i in range(max_token - min_token + 1)]
144
  trainer = BpeTrainer(
@@ -147,24 +157,16 @@ class UniversalActionProcessor(ProcessorMixin):
147
  show_progress=True,
148
  special_tokens=[],
149
  initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
150
- max_token_length=64,
 
 
 
151
  )
152
- tokenizer.train_from_iterator(_token_iter(), trainer=trainer, length=len(dct_tokens))
153
-
154
- # Train the inner tokenizer (don't use ByteLevelBPETokenizer.train_from_iterator()
155
- # because it doesn't support custom alphabets)
156
- # bpe._tokenizer.train_from_iterator(_token_iter(), trainer=trainer, length=len(dct_tokens))
157
- # trainer.train_from_iterator(_token_iter(), trainer=trainer)
158
- # bpe.train_from_iterator(
159
- # _token_iter(),
160
- # vocab_size=vocab_size,
161
- # min_frequency=2,
162
- # special_tokens=[],
163
- # length=len(dct_tokens),
164
- # )
165
 
166
  return cls(
167
- PreTrainedTokenizerFast(tokenizer_object=tokenizer, clean_up_tokenization_spaces=False),
 
 
168
  scale=scale,
169
  vocab_size=vocab_size,
170
  min_token=min_token,
 
4
 
5
  import numpy as np
6
  from scipy.fft import dct, idct
7
+ from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
8
+ from tokenizers.models import BPE
9
  from tokenizers.trainers import BpeTrainer
 
10
  from transformers import PreTrainedTokenizerFast
11
+ from transformers.processing_utils import ProcessorMixin
12
 
13
 
14
  class UniversalActionProcessor(ProcessorMixin):
 
42
  super().__init__(bpe_tokenizer)
43
 
44
  def __call__(self, action_chunk: np.array) -> np.array:
45
+ assert action_chunk.ndim <= 3, (
46
+ "Only 3 dimensions supported: [batch, timesteps, action_dim]"
47
+ )
48
  if action_chunk.ndim == 2:
49
  action_chunk = action_chunk[None, ...]
50
 
 
56
  dct_coeff = np.around(dct_coeff * self.scale)
57
  tokens = []
58
  for elem in dct_coeff:
59
+ token_str = "".join(
60
+ map(chr, np.maximum(elem.flatten() - self.min_token, 0).astype(int))
61
+ )
62
  tokens.append(self.bpe_tokenizer(token_str)["input_ids"])
63
  return tokens
64
 
 
69
  time_horizon: int | None = None,
70
  action_dim: int | None = None,
71
  ) -> np.array:
72
+ self.time_horizon = (
73
+ time_horizon or self.time_horizon or self.called_time_horizon
74
+ )
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 self.time_horizon is not None and self.action_dim is not None, (
82
+ "Tokenizer not initialized, call encode() once or pass in time_horizon and action_dim."
83
+ )
84
 
85
  decoded_actions = []
86
  for token in tokens:
87
  try:
88
  decoded_tokens = self.bpe_tokenizer.decode(token)
89
+ decoded_dct_coeff = (
90
+ np.array(list(map(ord, decoded_tokens))) + self.min_token
91
+ )
92
  decoded_dct_coeff = decoded_dct_coeff.reshape(-1, self.action_dim)
93
+ assert decoded_dct_coeff.shape == (
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
+ )
 
99
  except Exception as e:
100
  print(f"Error decoding tokens: {e}")
101
  print(f"Tokens: {token}")
102
  decoded_dct_coeff = np.zeros((self.time_horizon, self.action_dim))
103
+ decoded_actions.append(
104
+ idct(decoded_dct_coeff / self.scale, axis=0, norm="ortho")
105
+ )
106
  return np.stack(decoded_actions)
107
 
108
  @classmethod
 
122
  max_token = int(np.around(np.concatenate(dct_tokens) * scale).max())
123
  min_token = int(np.around(np.concatenate(dct_tokens) * scale).min())
124
  min_vocab_size = max_token - min_token
125
+ print(
126
+ f"Min token: {min_token}, Max token: {max_token}, Min vocab size: {min_vocab_size}"
127
+ )
128
 
129
+ assert min_vocab_size <= vocab_size, (
130
+ f"Vocab size {vocab_size} is too small for the range of tokens {min_vocab_size}"
131
+ )
132
  if min_vocab_size + 100 > vocab_size:
133
  logging.warning(
134
  f"Initial alphabet size {min_vocab_size} is almost as large as the vocab"
 
144
  yield string
145
 
146
  # Train BPE tokenizer
 
147
  tokenizer = Tokenizer(BPE())
148
+ tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
149
  tokenizer.decoder = decoders.ByteLevel()
150
+ tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
151
+
152
  # Set up the entire range of possible tokens as the initial alphabet
153
  # alphabet = [chr(i) for i in range(max_token - min_token + 1)]
154
  trainer = BpeTrainer(
 
157
  show_progress=True,
158
  special_tokens=[],
159
  initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
160
+ max_token_length=22,
161
+ )
162
+ tokenizer.train_from_iterator(
163
+ _token_iter(), trainer=trainer, length=len(dct_tokens)
164
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
  return cls(
167
+ PreTrainedTokenizerFast(
168
+ tokenizer_object=tokenizer, clean_up_tokenization_spaces=False
169
+ ),
170
  scale=scale,
171
  vocab_size=vocab_size,
172
  min_token=min_token,
tokenizer.json CHANGED
The diff for this file is too large to render. See raw diff