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.
Yes, you can check the length of the tokenized output by using the tokenizer's encode method to convert the string to a list of tokens, and then checking the length of that list.
Here's an example of how you could do this:
code
from tokenizers import BertTokenizer
# Load the tokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# Set a maximum length for the tokenized output
max_length = 512
# Define your input string
input_string = "This is a very long string that will be tokenized into many tokens"
# Tokenize the string
tokenized_string = tokenizer.encode(input_string, add_special_tokens=True)
# If the length of the tokenized output is greater than the maximum length,
# truncate the input string and try again
while len(tokenized_string) > max_length:
input_string = input_string[:-1] # Truncate the input string by one character
tokenized_string = tokenizer.encode(input_string, add_special_tokens=True)
# The tokenized string is now truncated to the maximum length
truncated_tokens = tokenized_string
This will truncate the input string character by character until the length of the tokenized output is less than or equal to the maximum length.
Alternatively, you could use the truncation parameter of the encode method to automatically truncate the input string for you. This parameter takes a string value that specifies where the truncation should occur. For example, you could use the value 'only_first' to truncate the string at the beginning, or 'only_second' to truncate it at the end. Here's an example of how you could use this parameter:
code
from tokenizers import BertTokenizer
# Load the tokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# Set a maximum length for the tokenized output
max_length = 512
# Define your input string
input_string = "This is a very long string that will be tokenized into many tokens"
# Tokenize the string and truncate it at the beginning if necessary
truncated_tokens = tokenizer.encode(input_string, add_special_tokens=True, max_length=max_length, truncation='only_first')
This will truncate the input string at the beginning if the length of the tokenized output is greater than the maximum length.
I hope this helps! Let me know if you have any other questions.