Sure! Below is a Python script tailored for a Google Colab environment that implements the Byte Pair Encoding (BPE) algorithm from scratch. This script reads a dataset.txt file, builds a vocabulary by iteratively merging the most frequent pairs of tokens, and writes the final vocabulary to vocab.txt, ensuring all ASCII characters are included and the vocabulary is sorted alphabetically.
Python Code for BPE Vocabulary Generation
# BPE Vocabulary Generation Script
# Parameters (You can adjust these)
max_vocab_size = 1000 # Maximum size of the vocabulary
max_token_length = 10 # Maximum length of any token
# Initialize the base vocabulary with all 256 ASCII characters
def initialize_vocab():
vocab = set()
for i in range(256):
vocab.add(chr(i))
return vocab
# Read the dataset and preprocess it into a list of words (as lists of characters)
def read_dataset(file_path):
words = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
# Split the line into words based on whitespace
line = line.strip()
if line == '':
continue
for word in line.split():
# Convert each word into a list of characters
words.append(list(word))
return words
# Count frequency of all adjacent pairs in the dataset
def get_pair_frequencies(words):
pairs = {}
for word in words:
for i in range(len(word)-1):
pair = (word[i], word[i+1])
if pair in pairs:
pairs[pair] +=1
else:
pairs[pair] =1
return pairs
# Merge the specified pair in all words
def merge_pair(pair_to_merge, words):
merged_token = ''.join(pair_to_merge)
new_words = []
for word in words:
new_word = []
i = 0
while i < len(word):
# Check if the current pair matches the pair to merge
if i < len(word)-1 and word[i] == pair_to_merge[0] and word[i+1] == pair_to_merge[1]:
# Merge the pair
new_word.append(merged_token)
i += 2 # Skip the next character as it's part of the merged pair
else:
new_word.append(word[i])
i +=1
new_words.append(new_word)
return new_words
def main():
import os
dataset_file = 'dataset.txt'
output_vocab_file = 'vocab.txt'
if not os.path.isfile(dataset_file):
print(f"Error: {dataset_file} not found in the working directory.")
return
print("Initializing vocabulary with all 256 ASCII characters...")
vocab = initialize_vocab()
print(f"Initial vocabulary size: {len(vocab)}")
print("Reading and preprocessing the dataset...")
words = read_dataset(dataset_file)
print(f"Total number of words in dataset: {len(words)}")
step = 0
while len(vocab) < max_vocab_size:
pairs = get_pair_frequencies(words)
if not pairs:
print("No more pairs to merge. Stopping.")
break
# Find the most frequent pair
most_frequent_pair = max(pairs, key=pairs.get)
freq = pairs[most_frequent_pair]
print(f"Step {step}: Most frequent pair: {most_frequent_pair} with frequency {freq}")
# Check the length of the new token
merged_token = ''.join(most_frequent_pair)
if len(merged_token) > max_token_length:
print(f"Cannot merge pair {most_frequent_pair} as it exceeds max token length.")
break
# Add the merged token to the vocabulary
if merged_token in vocab:
print(f"Token '{merged_token}' already in vocabulary.")
break
vocab.add(merged_token)
print(f"Added '{merged_token}' to the vocabulary. New vocab size: {len(vocab)}")
# Merge the pair in the dataset
words = merge_pair(most_frequent_pair, words)
print(f"Step {step}: Merged pair {most_frequent_pair} into '{merged_token}'.")
step +=1
# Check if max_vocab_size is reached
if len(vocab) >= max_vocab_size:
print(f"Reached maximum vocabulary size of {max_vocab_size}. Stopping.")
break
# Sort the vocabulary alphabetically
sorted_vocab = sorted(vocab)
print(f"Final vocabulary size: {len(sorted_vocab)}")
# Write the vocabulary to the output file
with open(output_vocab_file, 'w', encoding='utf-8') as f:
for token in sorted_vocab:
f.write(token + '\n')
print(f"Vocabulary written to {output_vocab_file}.")
if __name__ == "__main__":
main()
Explanation of the Script
-
Parameters Setup:
max_vocab_size: The maximum number of tokens your vocabulary can contain. Adjust this based on your requirements.
max_token_length: The maximum allowed length for any token in the vocabulary.
-
Initializing the Vocabulary:
- The
initialize_vocab function creates a set containing all 256 ASCII characters. This ensures that all basic characters are included from the start.
-
Reading and Preprocessing the Dataset:
- The
read_dataset function reads the dataset.txt file line by line, splits each line into words based on whitespace, and converts each word into a list of characters.
-
Counting Pair Frequencies:
- The
get_pair_frequencies function traverses each word and counts the frequency of every adjacent pair of tokens.
-
Merging Pairs:
- The
merge_pair function replaces all occurrences of a specified pair with a new merged token in the entire dataset.
-
Main Loop for BPE Training:
- The script enters a loop where it continuously finds and merges the most frequent pair of tokens until the
max_vocab_size is reached or no more valid pairs are available.
- Before merging, it ensures that the new token does not exceed the
max_token_length.
- After each merge, the vocabulary is updated, and the dataset is modified accordingly.
-
Finalizing the Vocabulary:
- Once the loop concludes, the vocabulary is sorted in alphabetical order.
- The sorted vocabulary is then written to
vocab.txt, with each token on a new line.
-
Execution Check:
- The script includes a check to ensure that
dataset.txt exists in the working directory before proceeding.
How to Use This Script in Google Colab
-
Upload dataset.txt:
-
Ensure that your dataset.txt file is uploaded to the Google Colab session. You can use the following code snippet in a Colab cell to upload files:
from google.colab import files
uploaded = files.upload()
-
Run the Script:
- Copy and paste the above Python script into a Colab cell.
- Execute the cell. The script will process the
dataset.txt file and generate vocab.txt in the working directory.
-
Download the Vocabulary:
-
After execution, you can download the vocab.txt file using:
from google.colab import files
files.download('vocab.txt')
Notes
-
Efficiency Consideration: This script is designed for simplicity and clarity. For very large datasets, consider optimizing the data structures or using more efficient libraries.
-
ASCII Characters: The script includes all 256 ASCII characters by default. If your dataset contains characters outside the ASCII range, you might need to adjust the initialization step accordingly.
-
Customization: Feel free to adjust max_vocab_size and max_token_length based on the specific needs of your application.
I hope this helps you generate the desired BPE-based vocabulary for your project!