Write Python code for a Google Colab instance, that will produce a vocabulary of tokens, each separated by newlines into a file. The training file would be "dataset.txt" and output file "vocab.txt". You can use a BPE algorithm to train this vocabulary. It should at least contain all the ASCII characters. The vocab should also be sorted in alphabetical order. Do not use any library, instead writing the training code yourself.. The dataset file is already stored in the working directory of the colab session. Include printing statements while training. We should have parameters to control the generation of vocabulary, like max vocab size and max token length. Once the vocab size is exceeded, stop trying to merge and write the vocabulary.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! Below is a complete 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, trains a vocabulary with customizable parameters, and writes the resulting vocabulary to vocab.txt with tokens sorted alphabetically. The script includes print statements to provide insights during the training process.
python
# BPE Vocabulary Training from Scratch
import os
import sys
from collections import defaultdict
# Parameters
MAX_VOCAB_SIZE = 1000 # Maximum size of the vocabulary
MAX_TOKEN_LENGTH = 10 # Maximum length of a token
DATASET_FILE = 'dataset.txt'
VOCAB_FILE = 'vocab.txt'
# Initialize the vocabulary with all ASCII printable characters
def initialize_vocab():
ascii_chars = [chr(i) for i in range(32, 127)] # ASCII 32 to 126
print(f"Initializing vocabulary with {len(ascii_chars)} ASCII characters.")
return set(ascii_chars)
# Read the dataset and initialize tokens
def read_dataset():
if not os.path.exists(DATASET_FILE):
print(f"Error: {DATASET_FILE} not found in the working directory.")
sys.exit(1)
with open(DATASET_FILE, 'r', encoding='utf-8') as f:
lines = f.read().strip().split('\n')
# Split each line into a list of characters
tokens = [list(line) for line in lines]
print(f"Loaded dataset with {len(tokens)} lines.")
return tokens
# Count frequency of all adjacent pairs
def get_pair_frequencies(tokens):
pair_freq = defaultdict(int)
for token_list in tokens:
for i in range(len(token_list)-1):
pair = (token_list[i], token_list[i+1])
pair_freq[pair] += 1
return pair_freq
# Merge the most frequent pair in the tokens
def merge_pair(pair, tokens):
merged_token = ''.join(pair)
new_tokens = []
for token_list in tokens:
new_token_list = []
i = 0
while i < len(token_list):
# Check if the current and next token form the pair
if i < len(token_list)-1 and token_list[i] == pair[0] and token_list[i+1] == pair[1]:
# Merge them
new_token_list.append(merged_token)
i += 2 # Skip the next token as it's merged
else:
new_token_list.append(token_list[i])
i += 1
new_tokens.append(new_token_list)
return new_tokens, merged_token
# Main BPE Training Function
def train_bpe(tokens, vocab, max_vocab_size, max_token_length):
iteration = 0
while len(vocab) < max_vocab_size:
iteration += 1
pair_freq = get_pair_frequencies(tokens)
if not pair_freq:
print("No more pairs to merge.")
break
# Find the most frequent pair
most_freq_pair = max(pair_freq, key=pair_freq.get)
frequency = pair_freq[most_freq_pair]
print(f"Iteration {iteration}: Most frequent pair {most_freq_pair} with frequency {frequency}")
# Check if the merged token exceeds max token length
new_token = ''.join(most_freq_pair)
if len(new_token) > max_token_length:
print(f"Skipping pair {most_freq_pair} as merged token '{new_token}' exceeds max token length {max_token_length}.")
break
if new_token in vocab:
print(f"Token '{new_token}' already in vocabulary.")
break
# Merge the pair
tokens, merged_token = merge_pair(most_freq_pair, tokens)
vocab.add(merged_token)
print(f"Added new token '{merged_token}' to vocabulary. Vocabulary size: {len(vocab)}")
# Check if adding the new token exceeds max vocab 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, vocab_file):
sorted_vocab = sorted(vocab)
with open(vocab_file, 'w', encoding='utf-8') as f:
for token in sorted_vocab:
f.write(token + '\n')
print(f"Vocabulary written to {vocab_file} with {len(sorted_vocab)} tokens.")
# Ensure all ASCII characters are in the vocabulary
def ensure_ascii(vocab):
ascii_chars = set([chr(i) for i in range(32, 127)])
missing = ascii_chars - vocab
if missing:
print(f"Adding missing ASCII characters to vocabulary: {missing}")
vocab.update(missing)
else:
print("All ASCII characters are present in the vocabulary.")
return vocab
# Main Execution
def main():
# Initialize vocabulary with ASCII characters
vocab = initialize_vocab()
# Read dataset and initialize tokens
tokens = read_dataset()
# Ensure all ASCII characters are in the vocabulary
vocab = ensure_ascii(vocab)
print("Starting BPE training...")
# Train BPE to build the vocabulary
vocab = train_bpe(tokens, vocab, MAX_VOCAB_SIZE, MAX_TOKEN_LENGTH)
# Write the final vocabulary to file
write_vocab(vocab, VOCAB_FILE)
print("BPE vocabulary training completed.")
# Run the main function
if __name__ == "__main__":
main()
Explanation of the Script
Parameters Setup:
MAX_VOCAB_SIZE: Defines the maximum number of tokens in the vocabulary. You can adjust this based on your needs.
MAX_TOKEN_LENGTH: Sets the upper limit on the length of any token in the vocabulary to ensure tokens don't become too long.
DATASET_FILE and VOCAB_FILE: Specify the input dataset and output vocabulary filenames.
Initialization:
The vocabulary is initialized with all printable ASCII characters (from space ' ' to tilde '~'), ensuring that the basic character set is always included.
Dataset Reading:
The script reads the dataset.txt file, expecting one sentence or word per line.
Each line is split into a list of characters, which serves as the initial tokens.
BPE Training Process:
Pair Frequency Counting: For each iteration, the script counts how frequently each adjacent pair of tokens appears across the entire dataset.
Pair Selection and Merging: The most frequent pair is selected and merged into a new token, provided it doesn't exceed the maximum token length and the vocabulary size limit.
Vocabulary Update: The new token is added to the vocabulary, and all occurrences of the pair in the dataset are replaced with the new token.
Termination Conditions: The training stops when the vocabulary reaches the maximum size, no more pairs can be merged, or merging a pair would result in a token that is too long.
Final Steps:
After training, the vocabulary is sorted alphabetically and written to vocab.txt, with one token per line.
Print Statements:
Throughout the training process, the script prints informative messages about the current iteration, the most frequent pair being merged, any tokens being skipped, and updates to the vocabulary size. This helps in tracking the progress and understanding the internal workings of the algorithm.
Usage Instructions
Upload dataset.txt:
Ensure that your dataset.txt file is uploaded to the working directory of your Google Colab session. You can upload files by using the file upload interface in Colab (Files pane on the left sidebar).
Run the Script:
Copy and paste the entire script into a cell in your Colab notebook.
Modify the MAX_VOCAB_SIZE and MAX_TOKEN_LENGTH parameters at the beginning of the script if needed.
Execute the cell. The script will process the dataset, train the BPE model, and generate vocab.txt in the working directory.
Download vocab.txt:
After the script finishes, you can download the vocab.txt file from the Files pane in Colab for further use.
Notes
Performance Considerations:
This implementation is straightforward and suitable for smaller datasets. For very large datasets, performance optimizations might be necessary.
Extensibility:
You can further enhance this script by adding more features, such as handling different encodings, adding special tokens, or integrating with other preprocessing steps.
Error Handling:
The script includes basic error handling, such as checking for the existence of the dataset.txt file. You can expand on this based on your specific requirements.
Feel free to adjust the parameters and extend the functionality as needed for your specific use case!