I'm using the python tokenizers library. My tokenizer throws a warning if it is used to encode more than 512 tokens at once. Is there a way to check how long a string is likely to be after tokenization and truncate it? I don't want to just truncate to 512 CHARACTERS since the tokenizer is subword-based and should easily tokenize 512 characters to far less than the maximum 512 tokens.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In the transformers library by Hugging Face, which includes the tokenizers functionality, you can use the tokenizer to estimate the number of tokens a string will be broken into without actually encoding it. This way, you can decide whether to truncate the string or not.
Here is an example of how you can do this:
python
from transformers import AutoTokenizer
# Load the tokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
# Your text
text = "Your long text goes here ..."
# Encode the text, but only up to the maximum length without adding special tokens
tokens = tokenizer.tokenize(text)
num_tokens = len(tokens)
# Check if the number of tokens is more than the maximum allowed
max_tokens = 512
if num_tokens > max_tokens:
# Truncate the tokens
tokens = tokens[:max_tokens]
# Convert back to a string if necessary
truncated_text = tokenizer.convert_tokens_to_string(tokens)
# Now you can encode the truncated text safely
inputs = tokenizer.encode_plus(truncated_text, add_special_tokens=True, max_length=max_tokens)
In the code above, tokenize method is used to split the text into tokens first, and then we can check the number of tokens and decide whether we need to truncate the list of tokens or not. After truncation (if needed), we convert the tokens back to a string and then use encode_plus method to encode it into the format suitable for a model, respecting the max_length of tokens.
Remember that the max_length parameter also accounts for special tokens (like [CLS], [SEP] for BERT-based models), so if you're truncating at exactly 512 tokens, you might want to truncate a few tokens less to leave room for these if they're added by the encoding process (encode_plus with add_special_tokens=True).