Certainly! 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 based on BPE, and writes the resulting tokens to vocab.txt. The vocabulary generation respects parameters such as maximum vocabulary size and maximum token length. Additionally, it ensures all ASCII characters are included and the final vocabulary is sorted alphabetically.
# BPE Vocabulary Generator in Google Colab
# Author: OpenAI Assistant
# Date: 2023-10
import os
from collections import defaultdict, Counter
# Parameters
max_vocab_size = 1000 # Set your desired maximum vocabulary size
max_token_length = 10 # Set your desired maximum token length
# Initialize Vocabulary with all ASCII characters
def initialize_vocab():
vocab = set()
for i in range(32, 127): # Printable ASCII characters
vocab.add(chr(i))
print(f"Initialized vocabulary with {len(vocab)} ASCII characters.")
return vocab
# Read dataset and tokenize
def read_dataset(filepath):
if not os.path.isfile(filepath):
raise FileNotFoundError(f"Dataset file '{filepath}' not found in the working directory.")
with open(filepath, 'r', encoding='utf-8') as f:
lines = f.readlines()
# Tokenize each line into a list of characters
# Adding a special end-of-word token if needed
tokenized_data = [list(line.strip()) for line in lines if line.strip()]
print(f"Read and tokenized {len(tokenized_data)} lines from the dataset.")
return tokenized_data
# Get frequency of all words in the dataset
def get_word_frequencies(tokenized_data):
freq = defaultdict(int)
for word in tokenized_data:
word_tuple = tuple(word)
freq[word_tuple] += 1
print(f"Counted frequencies of {len(freq)} unique word types.")
return freq
# Get all symbol pairs and their frequencies
def get_pair_frequencies(freq):
pairs = defaultdict(int)
for word, count in freq.items():
symbols = word
for i in range(len(symbols)-1):
pair = (symbols[i], symbols[i+1])
pairs[pair] += count
return pairs
# Merge the most frequent pair in the dataset
def merge_pair(pair_to_merge, freq):
merged_token = ''.join(pair_to_merge)
new_freq = defaultdict(int)
for word, count in freq.items():
new_word = []
i = 0
while i < len(word):
# Check if the pair matches
if i < len(word) -1 and word[i] == pair_to_merge[0] and word[i+1] == pair_to_merge[1]:
new_word.append(merged_token)
i += 2
else:
new_word.append(word[i])
i += 1
new_freq[tuple(new_word)] += count
return new_freq, merged_token
# BPE Training Loop
def train_bpe(tokenized_data, initial_vocab, max_vocab_size, max_token_length):
vocab = set(initial_vocab)
freq = get_word_frequencies(tokenized_data)
while len(vocab) < max_vocab_size:
pairs = get_pair_frequencies(freq)
if not pairs:
print("No more pairs to merge.")
break
# Find the most frequent pair
most_frequent_pair = max(pairs, key=pairs.get)
pair_freq = pairs[most_frequent_pair]
print(f"Most frequent pair: {most_frequent_pair} with frequency {pair_freq}")
# Create the new token
merged_token = ''.join(most_frequent_pair)
# Check token length constraint
if len(merged_token) > max_token_length:
print(f"Skipping merge of {most_frequent_pair} as it exceeds max token length.")
break
# Add the new token to the vocabulary
if merged_token in vocab:
print(f"Token '{merged_token}' already in vocabulary. Skipping.")
break
vocab.add(merged_token)
print(f"Added token '{merged_token}' to the vocabulary. Vocabulary size: {len(vocab)}")
# Merge the pair in the dataset
freq, new_token = merge_pair(most_frequent_pair, freq)
print(f"Merged pair {most_frequent_pair} into '{new_token}'.")
# 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 training.")
break
return vocab
# Write the vocabulary to a file, sorted alphabetically
def write_vocab(vocab, filepath):
sorted_vocab = sorted(vocab)
with open(filepath, 'w', encoding='utf-8') as f:
for token in sorted_vocab:
f.write(f"{token}\n")
print(f"Vocabulary written to '{filepath}' with {len(sorted_vocab)} tokens.")
# Main Execution
def main():
dataset_path = 'dataset.txt'
output_vocab_path = 'vocab.txt'
print("Starting BPE Vocabulary Generation...")
# Initialize vocabulary
initial_vocab = initialize_vocab()
# Read and tokenize dataset
tokenized_data = read_dataset(dataset_path)
# Train BPE
final_vocab = train_bpe(tokenized_data, initial_vocab, max_vocab_size, max_token_length)
# Ensure all ASCII characters are in the final vocabulary
ascii_chars = set(chr(i) for i in range(32, 127))
missing_ascii = ascii_chars - final_vocab
if missing_ascii:
print(f"Adding missing ASCII characters to the vocabulary: {missing_ascii}")
final_vocab.update(missing_ascii)
# Write the vocabulary to a file
write_vocab(final_vocab, output_vocab_path)
print("BPE Vocabulary Generation Completed.")
# Run the main function
if __name__ == "__main__":
main()
Explanation of the Script
-
Parameters Setup:
max_vocab_size: Maximum number of tokens allowed in the vocabulary.
max_token_length: Maximum allowed length for any token.
-
Initialize Vocabulary:
- Start with all printable ASCII characters (from space
' ' to '~').
- This ensures that all ASCII characters are included in the final vocabulary.
-
Read and Tokenize Dataset:
- The script reads
dataset.txt from the working directory.
- Each line is stripped of leading/trailing whitespace and tokenized into a list of characters.
-
BPE Training Loop:
- Frequency Counting:
- Counts the frequency of each unique word (as a tuple of tokens).
- Pair Frequency Counting:
- Identifies all adjacent token pairs and counts their frequencies across the dataset.
- Pair Merging:
- Finds the most frequent pair.
- Checks if merging this pair would exceed the
max_token_length.
- If valid, merges the pair into a new token and updates the dataset accordingly.
- Adds the new token to the vocabulary.
- Continues this process until the vocabulary size reaches
max_vocab_size or no more valid pairs can be merged.
-
Finalizing Vocabulary:
- Ensures that all ASCII characters are present in the final vocabulary.
- Sorts the vocabulary alphabetically.
- Writes each token to
vocab.txt, one per line.
-
Execution:
- The
main() function orchestrates the entire process.
- It is called at the end of the script to start the BPE training.
Usage Instructions
-
Upload dataset.txt:
-
Set Parameters:
- Adjust
max_vocab_size and max_token_length as desired by modifying their values in the script.
-
Run the Script:
- Execute the entire script in a Colab cell. The script will print progress statements during the training process.
-
Retrieve vocab.txt:
-
After execution, download vocab.txt from the Colab environment using:
from google.colab import files
files.download('vocab.txt')
This script provides a foundational implementation of BPE for generating a sorted vocabulary from a dataset without relying on external libraries. It includes necessary safeguards and informative print statements to trace the training process effectively.