# BPE Vocabulary Builder in Google Colab
# This script reads 'dataset.txt', builds a BPE vocabulary, and writes it to 'vocab.txt'
# The vocabulary is initialized with all 256 ASCII characters and is sorted alphabetically.
# Parameters for max vocabulary size and max token length can be adjusted.
# Parameters
MAX_VOCAB_SIZE = 10000 # Set your desired maximum vocabulary size
MAX_TOKEN_LENGTH = 30 # Set your desired maximum token length
def initialize_vocab():
vocab = {chr(i): i for i in range(256)}
print(f"Initialized vocabulary with {len(vocab)} ASCII characters.")
return vocab
def read_dataset(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
data = f.read()
tokens = list(data)
print(f"Dataset loaded with {len(tokens)} characters.")
return tokens
def get_stats(tokens):
pairs = {}
prev_token = tokens[0]
for token in tokens[1:]:
pair = (prev_token, token)
pairs[pair] = pairs.get(pair, 0) + 1
prev_token = token
return pairs
def merge_tokens(tokens, pair):
merged_token = ''.join(pair)
new_tokens = []
i = 0
while i < len(tokens):
# Check if the current and next token form the pair
if i < len(tokens) - 1 and (tokens[i], tokens[i+1]) == pair:
new_tokens.append(merged_token)
i += 2
else:
new_tokens.append(tokens[i])
i += 1
return new_tokens
def build_vocab(tokens, max_vocab_size, max_token_length):
vocab = initialize_vocab()
while len(vocab) < max_vocab_size:
pairs = get_stats(tokens)
if not pairs:
print("No more pairs to merge.")
break
# Find the most frequent pair
most_frequent = max(pairs, key=pairs.get)
frequency = pairs[most_frequent]
print(f"Merging pair {most_frequent} with frequency {frequency}.")
merged_token = ''.join(most_frequent)
# Check if the new token exceeds the maximum token length
if len(merged_token) > max_token_length:
print(f"Cannot merge pair {most_frequent} as it exceeds max token length.")
break
# Merge the most frequent pair
tokens = merge_tokens(tokens, most_frequent)
# Add the new token to the vocabulary
if merged_token not in vocab:
vocab[merged_token] = len(vocab)
print(f"Added new token '{merged_token}' to the vocabulary. Size: {len(vocab)}")
else:
print(f"Token '{merged_token}' already exists in the vocabulary.")
# Check if we've reached the maximum vocabulary size
if len(vocab) >= max_vocab_size:
print(f"Reached maximum vocabulary size of {max_vocab_size}. Stopping.")
break
return vocab
def save_vocab(vocab, file_path):
sorted_vocab = sorted(vocab.keys())
with open(file_path, 'w', encoding='utf-8') as f:
for token in sorted_vocab:
f.write(token + '\n')
print(f"Vocabulary saved to {file_path} with {len(vocab)} tokens.")
def main():
dataset_path = 'dataset.txt'
output_vocab_path = 'vocab.txt'
tokens = read_dataset(dataset_path)
vocab = build_vocab(tokens, MAX_VOCAB_SIZE, MAX_TOKEN_LENGTH)
save_vocab(vocab, output_vocab_path)
if __name__ == "__main__":
main()
Explanation
-
Parameters:
MAX_VOCAB_SIZE: Maximum number of tokens in the vocabulary. Set this to control how large the vocabulary can grow.
MAX_TOKEN_LENGTH: Maximum allowed length for any token. This prevents the creation of excessively long tokens.
-
Functions:
initialize_vocab(): Initializes the vocabulary with all 256 ASCII characters.
read_dataset(file_path): Reads the dataset from dataset.txt and converts it into a list of characters.
get_stats(tokens): Counts the frequency of each adjacent pair of tokens in the current token list.
merge_tokens(tokens, pair): Merges all occurrences of the specified pair in the token list into a single new token.
build_vocab(tokens, max_vocab_size, max_token_length): Iteratively builds the vocabulary by merging the most frequent pairs until the maximum vocabulary size or other stopping conditions are met.
save_vocab(vocab, file_path): Saves the final vocabulary to vocab.txt, sorted alphabetically.
-
Main Workflow:
- The script initializes the vocabulary, reads the dataset, and then enters a loop where it repeatedly merges the most frequent pair of tokens.
- After each merge, it checks if the new token exceeds the maximum allowed length or if the vocabulary has reached the desired size.
- Progress and important actions are printed to the console for monitoring.
- Finally, the vocabulary is sorted alphabetically and saved to
vocab.txt.
-
Usage:
- Ensure that
dataset.txt is uploaded to your Google Colab instance.
- Adjust
MAX_VOCAB_SIZE and MAX_TOKEN_LENGTH as needed.
- Run the script to generate
vocab.txt with the desired BPE vocabulary.
Notes
- This implementation is a basic version of the BPE algorithm and may not be optimized for very large datasets.
- For large datasets, consider more efficient data structures or optimizations to handle memory and speed.
- The script ensures that all initial ASCII characters are included and that the vocabulary grows by merging the most frequent pairs.
- Sorting the vocabulary alphabetically at the end ensures that the tokens are ordered nicely in the output file.