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 from the working directory, processes it to build a vocabulary using BPE, and writes the sorted vocabulary to vocab.txt. The script includes print statements to trace the training process.
# BPE Implementation in Google Colab
import os
import re
from collections import defaultdict
# Ensure 'dataset.txt' exists in the working directory
if not os.path.isfile('dataset.txt'):
print("Error: 'dataset.txt' not found in the current directory.")
else:
# Step 1: Read the dataset and preprocess
print("Reading 'dataset.txt'...")
with open('dataset.txt', 'r', encoding='utf-8') as f:
data = f.read()
# Split data into words
words = data.strip().split()
print(f"Number of words in dataset: {len(words)}")
# Initialize the tokenized corpus with words as list of characters plus '</w>'
print("Tokenizing words...")
corpus = []
for word in words:
# Ensure all characters are ASCII
if not all(ord(c) < 128 for c in word):
print(f"Warning: Non-ASCII characters found in word '{word}'. They will be ignored.")
word = ''.join([c for c in word if ord(c) < 128])
symbols = list(word) + ['</w>']
corpus.append(symbols)
# Initialize vocabulary with all unique characters plus '</w>'
vocab = set()
for symbols in corpus:
vocab.update(symbols)
# Ensure all ASCII characters are included
ascii_chars = set(chr(i) for i in range(32, 127)) # Printable ASCII
vocab.update(ascii_chars)
vocab.add('</w>')
print(f"Initial vocabulary size: {len(vocab)}")
# Function to get pair frequencies
def get_pair_stats(corpus):
pairs = defaultdict(int)
for symbols in corpus:
for i in range(len(symbols)-1):
pair = (symbols[i], symbols[i+1])
pairs[pair] += 1
return pairs
# Function to merge the most frequent pair
def merge_corpus(corpus, pair_to_merge):
merged_symbol = ''.join(pair_to_merge)
new_corpus = []
for symbols in corpus:
new_symbols = []
i = 0
while i < len(symbols):
# Check if the pair matches
if i < len(symbols)-1 and (symbols[i], symbols[i+1]) == pair_to_merge:
new_symbols.append(merged_symbol)
i += 2 # Skip the next symbol
else:
new_symbols.append(symbols[i])
i += 1
new_corpus.append(new_symbols)
return new_corpus, merged_symbol
# BPE Training
print("Starting BPE training...")
merge_operations = []
max_merges = 10000 # Set a maximum number of merges to prevent infinite loops
for merge_iteration in range(max_merges):
pairs = get_pair_stats(corpus)
if not pairs:
print("No more pairs to merge.")
break
# Find the most frequent pair
most_frequent_pair = max(pairs, key=pairs.get)
frequency = pairs[most_frequent_pair]
if frequency < 1:
print("No pair has frequency >= 1. Stopping.")
break
# Merge the most frequent pair
corpus, merged_symbol = merge_corpus(corpus, most_frequent_pair)
vocab.add(merged_symbol)
merge_operations.append((most_frequent_pair, merged_symbol))
# Print the merge information
print(f"Merge #{merge_iteration + 1}: {most_frequent_pair} -> {merged_symbol}")
# Optionally, stop after a certain number of merges
# For example, uncomment the following lines to stop after 100 merges
# if merge_iteration >= 99:
# print("Reached 100 merge operations. Stopping.")
# break
print(f"Total merge operations: {len(merge_operations)}")
print(f"Final vocabulary size: {len(vocab)}")
# Ensure all ASCII characters are in the vocabulary
vocab.update(ascii_chars)
vocab.add('</w>')
# Sort the vocabulary alphabetically
sorted_vocab = sorted(vocab)
# Write the vocabulary to 'vocab.txt'
print("Writing vocabulary to 'vocab.txt'...")
with open('vocab.txt', 'w', encoding='utf-8') as f:
for token in sorted_vocab:
f.write(token + '\n')
print("Vocabulary successfully written to 'vocab.txt'.")
Explanation of the Script:
-
Reading and Preprocessing the Data:
- The script first checks if
dataset.txt exists in the current working directory.
- It reads the file and splits the content into words based on whitespace.
- Each word is tokenized into a list of its constituent ASCII characters with an end-of-word marker
</w>. Non-ASCII characters are ignored with a warning.
-
Initializing the Vocabulary:
- The initial vocabulary includes all unique characters from the corpus and all printable ASCII characters to ensure completeness.
- The end-of-word marker
</w> is also included.
-
BPE Training Process:
- The script iteratively merges the most frequent pair of symbols in the corpus.
- In each iteration:
- Pair Statistics: It counts the frequency of every adjacent pair of symbols in the corpus.
- Selecting the Most Frequent Pair: It identifies the pair with the highest frequency.
- Merging: The most frequent pair is merged into a new symbol, and the corpus is updated accordingly.
- The new symbol is added to the vocabulary.
- The merge operation is printed for tracking purposes.
- The training continues until no more pairs can be merged or until a maximum number of merges (
max_merges) is reached to prevent infinite loops.
-
Finalizing the Vocabulary:
- After training, the script ensures that all ASCII characters and the end-of-word marker are present in the vocabulary.
- The vocabulary is then sorted alphabetically.
-
Writing the Vocabulary to a File:
- The sorted vocabulary is written to
vocab.txt, with each token on a new line.
Notes:
-
Performance Considerations: BPE can be computationally intensive, especially with large datasets and a high number of merge operations. The max_merges variable is set to 10,000 to prevent excessive computation. You can adjust this number based on your specific needs and the size of your dataset.
-
Customization: If you wish to limit the number of merge operations (e.g., to 100), you can uncomment the provided lines in the script.
-
Non-ASCII Characters: The script currently ignores non-ASCII characters and issues a warning when they are encountered. You can modify this behavior based on how you want to handle such characters.
-
End-of-Word Marker (</w>): This marker helps the model understand word boundaries. It's a standard practice in BPE implementations.
Run this script in a Google Colab notebook cell to perform BPE training and generate the vocab.txt file in your working directory.