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 including all byte values from 0 to 255, performs BPE merges to create new tokens, and writes the sorted vocabulary to vocab.txt.
Overview of the Script
-
Initialization:
- Byte Handling: Since BPE operates on byte-level tokens, the script reads
dataset.txt in binary mode to correctly handle all byte values from 0 to 255.
- Vocabulary Setup: Initializes the vocabulary with all single-byte tokens (0-255).
-
Data Preparation:
- Word Separation: Splits the dataset into words based on whitespace. Each word is represented as a list of byte values, with a special end-of-word marker
</w> appended to each word to signify boundaries.
-
BPE Training Loop:
- Counting Pair Frequencies: For each word, counts the frequency of adjacent byte pairs.
- Pair Selection: Identifies the most frequent byte pair across all words.
- Merging: Merges the most frequent pair into a new token and updates all words accordingly.
- Vocabulary Update: Adds the newly merged token to the vocabulary.
- Termination Condition: Continues the process for a predefined number of merges (e.g., 1000) or until no more pairs can be merged.
-
Finalization:
- Sorting: Sorts the final vocabulary in alphabetical (lexicographical) order.
- Writing to File: Writes each token to
vocab.txt, one per line.
Important Considerations
- No External Libraries: The script is built without relying on external libraries, ensuring compatibility and adherence to the user’s requirements.
- Efficiency: While implemented in pure Python for simplicity, be aware that BPE can be computationally intensive for large datasets. Adjust the number of merge operations (
num_merges) based on available computational resources.
- Token Representation: Tokens are handled as byte strings and properly decoded to handle all possible byte values. Non-printable characters are managed to prevent issues during file writing.
Python Code
# BPE Implementation in Python for Google Colab
# Define the number of merge operations
num_merges = 1000 # You can adjust this number as needed
# Initialize vocabulary with all single-byte tokens (0-255)
vocab = {bytes([i]): 0 for i in range(256)}
# Read the dataset as bytes
with open('dataset.txt', 'rb') as f:
data = f.read()
# Split data into words based on whitespace
# You can adjust the split criteria as needed
words = data.split(b' ') # Simple split on space. Adjust if needed.
# Append a special end-of-word token
words = [word + b'</w>' for word in words]
# Initialize the corpus: list of words represented as tuples of bytes
corpus = [tuple(word) for word in words]
# Initialize the vocabulary frequency
vocab_freq = {}
for word in corpus:
vocab_freq[word] = vocab_freq.get(word, 0) + 1
# Function to get pair frequencies
def get_pair_freq(corpus):
pair_freq = {}
for word, freq in corpus.items():
symbols = word
for i in range(len(symbols)-1):
pair = (symbols[i], symbols[i+1])
pair_freq[pair] = pair_freq.get(pair, 0) + freq
return pair_freq
# Function to merge a pair in the corpus
def merge_pair(pair, corpus):
new_corpus = {}
bigram = b''.join(pair)
merged = b''.join(pair)
replacement = bytes([256 + merge_pair.counter]) # Assign a new byte value beyond 255
for word, freq in corpus.items():
new_word = []
i = 0
while i < len(word):
if i < len(word)-1 and word[i] == pair[0] and word[i+1] == pair[1]:
new_word.append(merged) # Replace pair with merged token
i += 2
else:
new_word.append(word[i:i+1])
i += 1
new_corpus[tuple(new_word)] = new_corpus.get(tuple(new_word), 0) + freq
return new_corpus
# BPE training loop
for merge in range(num_merges):
pair_freq = get_pair_freq(vocab_freq)
if not pair_freq:
break
# Find the most frequent pair
best_pair = max(pair_freq, key=pair_freq.get)
best_freq = pair_freq[best_pair]
if best_freq < 1:
break
print(f"Merge {merge+1}: {best_pair} with frequency {best_freq}")
# Merge the best pair
corpus = merge_pair(best_pair, vocab_freq)
# Update the vocabulary frequency
vocab_freq = corpus
# Add the merged pair to the vocab
merged_token = b''.join(best_pair)
vocab[merged_token] = 0 # Initialize frequency to 0 or set appropriately
# Collect all tokens from the vocabulary
all_tokens = set()
for word in corpus:
for byte in word:
all_tokens.add(byte)
# Convert all tokens to sorted list
# Sort tokens based on their byte values
sorted_tokens = sorted(all_tokens)
# Function to decode bytes to string, handling non-printable characters
def decode_token(token_bytes):
try:
return token_bytes.decode('utf-8')
except UnicodeDecodeError:
return ''.join(['<%d>' % b for b in token_bytes])
# Write the sorted vocabulary to 'vocab.txt'
with open('vocab.txt', 'w', encoding='utf-8') as f:
for token in sorted_tokens:
decoded = decode_token(token)
f.write(decoded + '\n')
print("Vocabulary has been written to 'vocab.txt'.")
Explanation of the Code
-
Parameters and Initialization:
num_merges: Specifies how many BPE merge operations to perform. You can adjust this based on your requirements and computational resources.
vocab: Initializes the vocabulary with all single-byte tokens (0-255).
-
Data Reading and Preprocessing:
- Reads
dataset.txt in binary mode to ensure all byte values are correctly handled.
- Splits the data into words based on spaces and appends an end-of-word marker (
</w>) to each word to help the BPE algorithm recognize word boundaries.
-
Corpus and Vocabulary Frequency:
corpus: A dictionary where keys are word tuples and values are their frequencies.
vocab_freq: Keeps track of how often each word appears in the corpus.
-
BPE Functions:
get_pair_freq: Calculates the frequency of each adjacent byte pair in the corpus.
merge_pair: Merges the most frequent pair in the corpus and updates the corpus accordingly.
-
BPE Training Loop:
- Iterates up to
num_merges times, each time finding and merging the most frequent byte pair.
- Prints out each merge operation for tracking purposes.
- Updates the corpus and vocabulary after each merge.
-
Final Vocabulary Compilation:
- Gathers all unique tokens from the corpus.
- Sorts the tokens lexicographically based on their byte values.
- Defines a
decode_token function to safely convert byte tokens to strings, handling non-printable characters by representing them in a readable format (e.g., <65> for byte 65).
-
Writing to vocab.txt:
- Writes each sorted token to
vocab.txt, one per line.
- Prints a confirmation message upon completion.
Notes
-
Handling Non-Printable Characters: The decode_token function ensures that non-printable byte values are represented in a readable format within vocab.txt. You can modify this function based on how you wish to represent such bytes.
-
Performance: Pure Python implementations can be slow for large datasets or a high number of merge operations. For improved performance, consider optimizing the code or using more efficient data structures.
-
Adjustments: Depending on your specific use case and the nature of dataset.txt, you might need to adjust how the data is split into words or how tokens are represented.
Feel free to adjust the parameters and functions according to your specific needs and the characteristics of your dataset.