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, generates a vocabulary with specified constraints, and writes the sorted vocabulary to vocab.txt.
Overview:
-
Initialization:
- ASCII Characters: Ensures all printable ASCII characters are included in the initial vocabulary.
- Dataset Processing: Reads and tokenizes the dataset into words represented as lists of characters.
-
BPE Training:
- Iteratively merges the most frequent pair of tokens.
- Stops when the maximum vocabulary size is reached or no more valid merges can be performed.
-
Output:
- Sorts the final vocabulary alphabetically.
- Writes the vocabulary to
vocab.txt, with each token on a new line.
Parameters:
MAX_VOCAB_SIZE: Maximum number of tokens in the vocabulary.
MAX_TOKEN_LENGTH: Maximum allowed length for any token in the vocabulary.
Code Implementation:
# BPE Implementation in Google Colab
# Parameters
MAX_VOCAB_SIZE = 1000 # Maximum vocabulary size
MAX_TOKEN_LENGTH = 10 # Maximum length of any token
# Step 1: Initialize the environment
import os
import string
from collections import defaultdict, Counter
# Ensure 'dataset.txt' exists
if not os.path.isfile('dataset.txt'):
raise FileNotFoundError("The file 'dataset.txt' was not found in the working directory.")
# Step 2: Initialize the vocabulary with all printable ASCII characters
print("Initializing vocabulary with all printable ASCII characters...")
ascii_chars = list(string.printable) # Includes digits, letters, punctuation, whitespace
vocab = set(ascii_chars)
print(f"Initial vocabulary size (ASCII): {len(vocab)}")
# Step 3: Read and tokenize the dataset
print("Reading and tokenizing the dataset...")
with open('dataset.txt', 'r', encoding='utf-8') as f:
data = f.read()
# Split data into words and represent each word as a list of characters ending with '</w>'
# The '</w>' token signifies the end of a word
words = [list(word) + ['</w>'] for word in data.strip().split()]
print(f"Total words in dataset: {len(words)}")
# Add unique characters from the dataset to the initial vocab
dataset_chars = set(char for word in words for char in word if char != '</w>')
vocab.update(dataset_chars)
print(f"Vocabulary size after adding dataset characters: {len(vocab)}")
# Initialize word representations
word_freq = Counter(words)
# Step 4: BPE Training
def get_pair_freq(word_freq):
pairs = defaultdict(int)
for word, freq in word_freq.items():
symbols = word
for i in range(len(symbols)-1):
pair = (symbols[i], symbols[i+1])
pairs[pair] += freq
return pairs
def merge_pair(pair, word_freq):
new_word_freq = {}
bigram = ''.join(pair)
replacement = bigram
for word, freq in word_freq.items():
new_word = []
i = 0
while i < len(word):
# Check if the pair matches
if i < len(word) -1 and word[i] == pair[0] and word[i+1] == pair[1]:
new_word.append(replacement)
i += 2
else:
new_word.append(word[i])
i += 1
new_word_freq[tuple(new_word)] = freq
return new_word_freq
iteration = 0
while len(vocab) < MAX_VOCAB_SIZE:
iteration += 1
print(f"\nIteration {iteration}:")
pairs = get_pair_freq(word_freq)
if not pairs:
print("No more pairs to merge.")
break
# Find the most frequent pair
best_pair, best_freq = max(pairs.items(), key=lambda item: item[1])
print(f"Most frequent pair: {best_pair} with frequency {best_freq}")
# Check the length of the new token
merged_token = ''.join(best_pair)
if len(merged_token) > MAX_TOKEN_LENGTH:
print(f"Cannot merge pair {best_pair} as it exceeds max token length ({MAX_TOKEN_LENGTH}). Stopping.")
break
# Add the new token to the vocabulary
vocab.add(merged_token)
print(f"Added new token: '{merged_token}' to vocabulary. New vocab size: {len(vocab)}")
# Merge the pair in the dataset
word_freq = merge_pair(best_pair, word_freq)
# Check if vocab size has reached the maximum
if len(vocab) >= MAX_VOCAB_SIZE:
print(f"Reached maximum vocabulary size of {MAX_VOCAB_SIZE}. Stopping.")
break
print("\nBPE training completed.")
print(f"Final vocabulary size: {len(vocab)}")
# Step 5: Sort the vocabulary alphabetically
sorted_vocab = sorted(vocab)
print("Sorted the vocabulary alphabetically.")
# Step 6: Write the vocabulary to 'vocab.txt'
print("Writing the 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:
-
Initialization:
- ASCII Characters: The script starts by initializing the vocabulary with all printable ASCII characters using Python's
string.printable.
- Dataset Processing: It reads the
dataset.txt file, splits the text into words, and represents each word as a list of characters appended with a special end-of-word token </w>. This helps the BPE algorithm understand word boundaries.
-
BPE Training:
- Pair Frequency Counting: The
get_pair_freq function counts the frequency of each adjacent pair of tokens across all words in the dataset.
- Pair Merging: The most frequent pair is identified and merged into a new token. This new token is then added to the vocabulary.
- Constraints:
- Maximum Token Length: Before merging, the script checks if the new token exceeds the
MAX_TOKEN_LENGTH. If it does, the merging process stops.
- Maximum Vocabulary Size: The process continues until the vocabulary size reaches
MAX_VOCAB_SIZE or no more valid pairs can be merged.
-
Output:
- After training, the vocabulary is sorted alphabetically to ensure orderly storage.
- The sorted vocabulary is written to
vocab.txt, with each token on a new line.
-
Print Statements:
- Throughout the training process, the script prints informative statements to provide insights into each iteration, such as the most frequent pair being merged and updates to the vocabulary size.
Usage:
-
Setup:
- Ensure that you have a
dataset.txt file in your Google Colab working directory. You can upload it using the Colab interface or mount Google Drive as needed.
-
Execution:
- Run the above script in a Colab notebook cell. It will perform the BPE training and generate the
vocab.txt file in the working directory.
-
Customization:
- Adjust the
MAX_VOCAB_SIZE and MAX_TOKEN_LENGTH parameters at the beginning of the script to control the size and complexity of the generated vocabulary.
Notes:
- This implementation uses a simple version of BPE without handling more complex cases like empty merge results or different merge strategies.
- The
</w> token is used to denote the end of a word, which can be useful for certain applications like language modeling.
- The script ensures that all printable ASCII characters are included in the vocabulary, even if they don't appear in the
dataset.txt.
Feel free to modify and extend this script based on your specific requirements!