Sure! Below is a Python script tailored for a Google Colab environment that performs Byte Pair Encoding (BPE) to generate a vocabulary from a dataset.txt file. The script includes parameters to control the maximum vocabulary size and maximum token length, ensures all ASCII characters are included, and outputs the vocabulary sorted alphabetically into vocab.txt. Additionally, it includes print statements to trace the training process.
# BPE Vocabulary Generator for Google Colab
# This script reads 'dataset.txt' from the current directory,
# performs Byte Pair Encoding (BPE) to generate a vocabulary,
# and writes the sorted vocabulary to 'vocab.txt'.
# Parameters
MAX_VOCAB_SIZE = 10000 # Maximum vocabulary size (including base vocab)
MAX_TOKEN_LENGTH = 20 # Maximum length of any token
# Initialize base vocabulary with all ASCII characters and '</w>'
def initialize_vocab():
vocab = set()
for i in range(32, 127): # Printable ASCII characters
vocab.add(chr(i))
vocab.add('</w>') # End of word token
return vocab
# Read dataset and preprocess
def read_dataset(file_path):
words_freq = {}
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
words = line.strip().split()
for word in words:
# Append '</w>' to mark end of word
tokens = tuple(list(word) + ['</w>'])
if tokens in words_freq:
words_freq[tokens] += 1
else:
words_freq[tokens] = 1
return words_freq
# Get frequency of all adjacent pairs
def get_pair_freq(words_freq):
pairs = {}
for word, freq in words_freq.items():
symbols = word
for i in range(len(symbols)-1):
pair = (symbols[i], symbols[i+1])
if pair in pairs:
pairs[pair] += freq
else:
pairs[pair] = freq
return pairs
# Merge the most frequent pair in all words
def merge_pair(pair_to_merge, words_freq):
new_words_freq = {}
bigram = ''.join(pair_to_merge)
for word, freq in words_freq.items():
new_word = []
i = 0
while i < len(word):
# Check if the current and next symbols match the pair to merge
if i < len(word)-1 and word[i] == pair_to_merge[0] and word[i+1] == pair_to_merge[1]:
merged_token = ''.join(pair_to_merge)
new_word.append(merged_token)
i += 2 # Skip the next symbol as it's merged
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
if new_word in new_words_freq:
new_words_freq[new_word] += freq
else:
new_words_freq[new_word] = freq
return new_words_freq
# BPE Training
def train_bpe(words_freq, vocab, max_vocab_size, max_token_length):
print(f"Initial vocabulary size: {len(vocab)}")
iteration = 1
while len(vocab) < max_vocab_size:
pairs = get_pair_freq(words_freq)
if not pairs:
print("No more pairs to merge.")
break
# Find the most frequent pair
most_freq_pair = max(pairs, key=pairs.get)
freq = pairs[most_freq_pair]
print(f"Iteration {iteration}: Most frequent pair: {most_freq_pair} (Frequency: {freq})")
# Create the new token
new_token = ''.join(most_freq_pair)
if len(new_token) > max_token_length:
print(f"Skipping merge {most_freq_pair} as it exceeds max token length.")
break
if new_token in vocab:
print(f"Token {new_token} already in vocabulary.")
break
# Check if adding the new token exceeds the max vocab size
if len(vocab) + 1 > max_vocab_size:
print("Reached maximum vocabulary size.")
break
# Merge the pair in the dataset
words_freq = merge_pair(most_freq_pair, words_freq)
# Add the new token to the vocabulary
vocab.add(new_token)
print(f"Added '{new_token}' to vocabulary. New vocab size: {len(vocab)}")
iteration += 1
print("BPE training completed.")
return vocab
# Main function
def main():
import os
dataset_file = 'dataset.txt'
output_vocab_file = 'vocab.txt'
if not os.path.isfile(dataset_file):
print(f"Dataset file '{dataset_file}' not found in the current directory.")
return
print("Initializing vocabulary with ASCII characters and '</w>'.")
vocab = initialize_vocab()
print(f"Reading dataset from '{dataset_file}'.")
words_freq = read_dataset(dataset_file)
print(f"Total unique words: {len(words_freq)}")
vocab = train_bpe(words_freq, vocab, MAX_VOCAB_SIZE, MAX_TOKEN_LENGTH)
# Sort the vocabulary alphabetically
sorted_vocab = 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}'. Total tokens: {len(sorted_vocab)}")
# Execute the main function
if __name__ == "__main__":
main()
Explanation of the Script
-
Parameters:
MAX_VOCAB_SIZE: Sets the upper limit for the vocabulary size, including the base ASCII characters.
MAX_TOKEN_LENGTH: Sets the maximum allowable length for any token in the vocabulary.
-
Initialization:
- The
initialize_vocab function creates a set containing all printable ASCII characters (from space ' ' to '~') and the end-of-word token '</w>'.
-
Data Reading and Preprocessing:
- The
read_dataset function reads the dataset.txt file line by line.
- It splits each line into words, appends the
'</w>' token to signify the end of each word, and populates a dictionary words_freq that maps each unique word (as a tuple of tokens) to its frequency.
-
BPE Training:
- The
train_bpe function performs the BPE algorithm:
- It repeatedly identifies the most frequent pair of adjacent tokens across all words.
- It checks if merging this pair would exceed the
MAX_VOCAB_SIZE or MAX_TOKEN_LENGTH.
- If valid, it merges the pair in all words and adds the new token to the vocabulary.
- The process continues until the vocabulary size limit is reached or no more valid pairs are available.
- Print statements provide a trace of each iteration, including which pair is merged and the updated vocabulary size.
-
Output:
- After training, the vocabulary is sorted alphabetically.
- The sorted vocabulary is written to
vocab.txt, with each token on a new line.
-
Execution:
- The
main function orchestrates the overall process, ensuring that the dataset file exists, initializing the vocabulary, reading and processing the dataset, performing BPE training, and writing the final vocabulary to the output file.
- The script is executed by calling the
main function when the script runs.
How to Use in Google Colab
-
Upload dataset.txt:
- Ensure that your
dataset.txt file is uploaded to the current working directory in your Google Colab environment. You can use the following code snippet to upload files:
from google.colab import files
uploaded = files.upload()
-
Run the Script:
- Copy and paste the entire script into a Colab code cell and execute it. The script will process the dataset, perform BPE training, and generate
vocab.txt.
-
Download the Vocabulary:
- After execution, you can download the
vocab.txt file using:
from google.colab import files
files.download('vocab.txt')
Notes
Feel free to adjust the MAX_VOCAB_SIZE and MAX_TOKEN_LENGTH parameters to suit your specific needs.