| 12 | ACTION_TOKEN = '<ACTION{:05d}>' |
| 13 | |
| 14 | class ActionTokenizer: |
| 15 | def __init__( |
| 16 | self, |
| 17 | tokenizer: PreTrainedTokenizerBase, |
| 18 | num_bins: int = 256, |
| 19 | min_action: int = -1, |
| 20 | max_action: int = 1, |
| 21 | ): |
| 22 | self._vocab_size = num_bins |
| 23 | self.tokenizer = tokenizer |
| 24 | self.min_action, self.max_action = min_action, max_action |
| 25 | self.bin_centers = np.linspace(min_action, max_action, num_bins) |
| 26 | |
| 27 | # add special action tokens to language tokenizer |
| 28 | token_list = [ACTION_TOKEN.format(i) for i in range(self._vocab_size)] |
| 29 | self.token_array = np.array(token_list) |
| 30 | |
| 31 | num_new_tokens = self.tokenizer.add_tokens(token_list, special_tokens=True) |
| 32 | print(f"Add {num_new_tokens} TRANSLATION TOKENS, tokenizer vocab size {self.tokenizer.vocab_size} / {len(tokenizer)}") |
| 33 | |
| 34 | self.action_token_begin_idx = self.token_start_idx = self.tokenizer.convert_tokens_to_ids(self.token_array[0]) |
| 35 | self.token_end_idx = self.tokenizer.convert_tokens_to_ids(self.token_array[-1]) |
| 36 | |
| 37 | def __call__(self, action: np.ndarray) -> List[str]: |
| 38 | """Discretize continuous actions to tokens. |
| 39 | action: np.ndarray, (n, 7), continuous actions in Cartesian or Spherical coordinates. |
| 40 | return: np.ndarray, (n, 7), tokens. |
| 41 | """ |
| 42 | action = np.clip(action, a_min=float(self.min_action), a_max=float(self.max_action)) |
| 43 | ids = np.digitize(action, self.bin_centers, right=True) # [0, 255] |
| 44 | return self.token_array[ids] |
| 45 | |
| 46 | def decode_token_ids_to_actions(self, action_token_id: np.ndarray) -> np.ndarray: |
| 47 | """decode token ids to continuous actions. |
| 48 | action_token_id: np.ndarray, (n, 7), token ids. |
| 49 | return: np.ndarray, (n, 7), continuous actions |
| 50 | """ |
| 51 | ids = action_token_id - self.action_token_begin_idx |
| 52 | ids = np.clip(ids, a_min=0, a_max=self._vocab_size - 1) |
| 53 | return self.bin_centers[ids] |
| 54 | |
| 55 | @property |
| 56 | def vocab_size(self) -> int: |
| 57 | return self._vocab_size |
| 58 | |
| 59 | class TranslationTokenizer: |
| 60 | def __init__( |
nothing calls this directly
no outgoing calls
no test coverage detected