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. The base vocab size should be 256 (all the ascii characters). Make it as fast as possible, optimizing it as much as possible. Be wary of trailing instead of whitespaces when you create the vocabulary.
Assistant
python
# BPE Vocabulary Builder in Google Colab
# Parameters
MAX_VOCAB_SIZE = 10000 # Maximum vocabulary size
MAX_TOKEN_LENGTH = 10 # Maximum token length
# Initialize base vocabulary with all ASCII characters and the end-of-word token
# ASCII characters from 0 to 255
base_vocab = set([chr(i) for i in range(256)])
base_vocab.add('</w>') # Adding the end-of-word token
print("Initializing base vocabulary with 256 ASCII characters and '</w>' token.")
print(f"Initial vocabulary size: {len(base_vocab)}")
# Function to read and preprocess the dataset
def preprocess_dataset(file_path):
word_freqs = {}
with open(file_path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
words = line.strip().split()
for word in words:
# Append </w> to mark the end of a word
chars = list(word) + ['</w>']
key = tuple(chars)
if key in word_freqs:
word_freqs[key] += 1
else:
word_freqs[key] = 1
if line_num % 1000 == 0:
print(f"Processed {line_num} lines.")
return word_freqs
print("Preprocessing dataset...")
word_frequencies = preprocess_dataset('dataset.txt')
print(f"Number of unique words in dataset: {len(word_frequencies)}")
# Function to get pair frequencies
def get_pair_frequencies(word_freqs):
pair_freqs = {}
for word, freq in word_freqs.items():
prev_char = word[0]
for char in word[1:]:
pair = (prev_char, char)
pair_freqs[pair] = pair_freqs.get(pair, 0) + freq
prev_char = char
return pair_freqs
# Function to merge a pair in the dataset
def merge_pair(pair_to_merge, word_freqs):
merged_token = ''.join(pair_to_merge)
new_word_freqs = {}
pair_length = len(pair_to_merge)
for word, freq in word_freqs.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]:
# Merge the pair
new_word.append(merged_token)
i += 2
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
new_word_freqs[new_word] = new_word_freqs.get(new_word, 0) + freq
return new_word_freqs, merged_token
print("Starting BPE training...")
current_vocab = set(base_vocab)
iteration = 0
while len(current_vocab) < MAX_VOCAB_SIZE:
iteration += 1
pair_freqs = get_pair_frequencies(word_frequencies)
if not pair_freqs:
print("No more pairs to merge.")
break
# Find the most frequent pair
most_freq_pair = max(pair_freqs, key=pair_freqs.get)
frequency = pair_freqs[most_freq_pair]
merged_token = ''.join(most_freq_pair)
# Check if the new token exceeds the maximum token length
if len(merged_token) > MAX_TOKEN_LENGTH:
print(f"Skipping merge {most_freq_pair} -> {merged_token} as it exceeds max token length.")
break
# Add the new token to the vocabulary
current_vocab.add(merged_token)
# Merge the pair in the dataset
word_frequencies, merged_token = merge_pair(most_freq_pair, word_frequencies)
print(f"Iteration {iteration}: Merged pair {most_freq_pair} into '{merged_token}'.")
print(f"Vocabulary size: {len(current_vocab)}")
# Stop if vocabulary size limit is reached
if len(current_vocab) >= MAX_VOCAB_SIZE:
print("Reached maximum vocabulary size.")
break
print("BPE training completed.")
# Sort the vocabulary alphabetically
sorted_vocab = sorted(current_vocab)
# Write the vocabulary to 'vocab.txt' with each token on a new line
with open('vocab.txt', 'w', encoding='utf-8') as vocab_file:
for token in sorted_vocab:
vocab_file.write(token + '\n')
print(f"Vocabulary written to 'vocab.txt' with {len(sorted_vocab)} tokens.")