|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +from collections.abc import Sequence |
| 10 | +from pathlib import Path |
| 11 | +from typing import final |
| 12 | + |
| 13 | +import torch |
| 14 | +from torch import Tensor |
| 15 | +from typing_extensions import override |
| 16 | + |
| 17 | +from fairseq2.data import VocabularyInfo |
| 18 | +from fairseq2.data.text.tokenizers import ( |
| 19 | + TextTokenDecoder, |
| 20 | + TextTokenEncoder, |
| 21 | +) |
| 22 | +from fairseq2.typing import Device |
| 23 | +from transformers import AutoTokenizer |
| 24 | + |
| 25 | + |
| 26 | +@final |
| 27 | +class HuggingfaceTokenizerEncoder(TextTokenEncoder): |
| 28 | + """Represents a tiktoken decoder.""" |
| 29 | + |
| 30 | + _tokenizer: AutoTokenizer |
| 31 | + _prefix_indices: list[int] |
| 32 | + _suffix_indices: list[int] |
| 33 | + _prefix_index_tensor: Tensor | None |
| 34 | + _suffix_index_tensor: Tensor | None |
| 35 | + _device: Device | None |
| 36 | + _pin_memory: bool |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + tokenizer: AutoTokenizer, |
| 41 | + *, |
| 42 | + prefix_tokens: Sequence[str] | None = None, |
| 43 | + suffix_tokens: Sequence[str] | None = None, |
| 44 | + device: Device | None = None, |
| 45 | + pin_memory: bool = False, |
| 46 | + ) -> None: |
| 47 | + """ |
| 48 | + :param tokenizer: |
| 49 | + The huggingface :class:`AutoTokenizer` object. |
| 50 | + :param prefix_tokens: |
| 51 | + The prefix tokens to encode with input text. |
| 52 | + :param suffix_tokens: |
| 53 | + The suffix tokens to encode with input text. |
| 54 | + :param device: |
| 55 | + The device on which to construct tensors. |
| 56 | + :param pin_memory: |
| 57 | + If ``True``, uses pinned memory while constructing tensors. |
| 58 | + """ |
| 59 | + self._tokenizer = tokenizer |
| 60 | + |
| 61 | + # Prefix |
| 62 | + if prefix_tokens: |
| 63 | + self._prefix_indices = self._tokenizer.convert_tokens_to_ids(prefix_tokens) |
| 64 | + |
| 65 | + self._prefix_index_tensor = torch.tensor( |
| 66 | + self._prefix_indices, dtype=torch.int64, device=device |
| 67 | + ) |
| 68 | + else: |
| 69 | + self._prefix_indices = [] |
| 70 | + |
| 71 | + self._prefix_index_tensor = None |
| 72 | + |
| 73 | + # Suffix |
| 74 | + if suffix_tokens: |
| 75 | + self._suffix_indices = self._tokenizer.convert_tokens_to_ids(suffix_tokens) |
| 76 | + |
| 77 | + self._suffix_index_tensor = torch.tensor( |
| 78 | + self._suffix_indices, dtype=torch.int64, device=device |
| 79 | + ) |
| 80 | + else: |
| 81 | + self._suffix_indices = [] |
| 82 | + |
| 83 | + self._suffix_index_tensor = None |
| 84 | + |
| 85 | + self._device = device |
| 86 | + self._pin_memory = pin_memory |
| 87 | + |
| 88 | + @override |
| 89 | + def __call__(self, text: str) -> Tensor: |
| 90 | + # fairseq2 tokenizer adds special tokens on its own |
| 91 | + indices = self._tokenizer.encode(text, add_special_tokens=False) |
| 92 | + |
| 93 | + if self._prefix_indices: |
| 94 | + indices = self._prefix_indices + indices |
| 95 | + |
| 96 | + if self._suffix_indices: |
| 97 | + indices.extend(self._suffix_indices) |
| 98 | + |
| 99 | + return torch.tensor( |
| 100 | + indices, dtype=torch.int64, device=self._device, pin_memory=self._pin_memory |
| 101 | + ) |
| 102 | + |
| 103 | + @override |
| 104 | + def encode_as_tokens(self, text: str) -> list[str]: |
| 105 | + indices = self(text).tolist() |
| 106 | + |
| 107 | + tokens = self._tokenizer.convert_tds_to_tokens(indices) |
| 108 | + |
| 109 | + return tokens |
| 110 | + |
| 111 | + @property |
| 112 | + @override |
| 113 | + def prefix_indices(self) -> Tensor | None: |
| 114 | + return self._prefix_index_tensor |
| 115 | + |
| 116 | + @property |
| 117 | + @override |
| 118 | + def suffix_indices(self) -> Tensor | None: |
| 119 | + return self._suffix_index_tensor |
| 120 | + |
| 121 | + |
| 122 | +@final |
| 123 | +class HuggingfaceTokenizerDecoder(TextTokenDecoder): |
| 124 | + """Represents a tiktoken decoder.""" |
| 125 | + |
| 126 | + _tokenizer: AutoTokenizer |
| 127 | + |
| 128 | + def __init__(self, tokenizer: AutoTokenizer) -> None: |
| 129 | + self._tokenizer = tokenizer |
| 130 | + |
| 131 | + @override |
| 132 | + def __call__(self, token_indices: Tensor) -> str: |
| 133 | + if token_indices.dim() != 1: |
| 134 | + raise ValueError( |
| 135 | + f"`token_indices` must be one dimensional, but has {token_indices.dim()} dimensions instead." |
| 136 | + ) |
| 137 | + |
| 138 | + return self._tokenizer.decode(token_indices) |
| 139 | + |
| 140 | + @override |
| 141 | + def decode_from_tokens(self, tokens: Sequence[str]) -> str: |
| 142 | + indices = self._tokenizer.convert_tokens_to_ids(tokens) |
| 143 | + |
| 144 | + return self._tokenizer.decode(indices) |
0 commit comments