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.
Assistant
python
# BPE Vocabulary Builder in Google Colab
# This script reads 'dataset.txt', trains a BPE vocabulary, and writes it to 'vocab.txt'.
# Parameters
max_vocab_size = 1000 # Maximum size of the vocabulary
max_token_length = 10 # Maximum length of any token
# Ensure all ASCII characters are included in the initial vocabulary
import string
ascii_chars = list(string.printable)
vocab = set(ascii_chars)
print("Initial vocabulary size (ASCII characters):", len(vocab))
# Read the dataset
with open('dataset.txt', 'r', encoding='utf-8') as f:
data = f.read()
print("Dataset loaded. Length:", len(data), "characters.")
# Initialize tokens as list of words with spaces as separators
# Each word is represented as a list of characters ending with a special end-of-word symbol
# Here, we use '</w>' to denote end of word
# For simplicity, we'll split by whitespace
words = data.strip().split()
tokens = [list(word) + ['</w>'] for word in words]
print("Number of words in dataset:", len(tokens))
from collections import defaultdict
def get_vocab(tokens):
"""Get frequency of each word."""
vocab = defaultdict(int)
for token in tokens:
vocab_tuple = tuple(token)
vocab[vocab_tuple] +=1
return vocab
def get_pair_counts(vocab):
"""Get frequency of each adjacent pair of symbols."""
pairs = defaultdict(int)
for word, freq in vocab.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, vocab):
"""Merge the most frequent pair in the vocabulary."""
new_vocab = {}
bigram = ''.join(pair)
for word, freq in vocab.items():
new_word = []
i = 0
while i < len(word):
# Check if the bigram matches
if i < len(word)-1 and word[i] == pair[0] and word[i+1] == pair[1]:
merged_symbol = bigram
# Check token length constraint
if len(merged_symbol) > max_token_length:
new_word.append(word[i])
i +=1
else:
new_word.append(merged_symbol)
i +=2
else:
new_word.append(word[i])
i +=1
new_vocab[tuple(new_word)] = freq
return new_vocab
# Initialize the vocabulary
current_vocab = get_vocab(tokens)
while len(vocab) < max_vocab_size:
pairs = get_pair_counts(current_vocab)
if not pairs:
print("No more pairs to merge.")
break
# Find the most frequent pair
most_freq_pair = max(pairs, key=pairs.get)
if pairs[most_freq_pair] <1:
print("No pair has frequency >=1 to merge.")
break
print(f"Merging pair: {most_freq_pair} with frequency {pairs[most_freq_pair]}")
# Merge the pair
current_vocab = merge_pair(most_freq_pair, current_vocab)
# Add the new merged symbol to the vocabulary
merged_symbol = ''.join(most_freq_pair)
if len(merged_symbol) <= max_token_length:
vocab.add(merged_symbol)
print(f"Added '{merged_symbol}' to vocabulary. Size now: {len(vocab)}")
else:
print(f"Skipped adding '{merged_symbol}' due to max token length constraint.")
# Check if reached max vocab size
if len(vocab) >= max_vocab_size:
print("Reached maximum vocabulary size.")
break
print("Training completed.")
# Save the vocabulary sorted alphabetically
sorted_vocab = sorted(vocab)
with open('vocab.txt', 'w', encoding='utf-8') as f:
for token in sorted_vocab:
f.write(token + '\n')
print("Vocabulary saved to 'vocab.txt'. Total tokens:", len(sorted_vocab))
Explanation:
Parameters:
max_vocab_size: Defines the maximum number of tokens in the vocabulary.
max_token_length: Sets the maximum permissible length for any token to ensure tokens aren't excessively long.
Initialization:
The script starts by importing necessary modules and ensuring that all ASCII characters are included in the initial vocabulary.
It reads the dataset.txt file and splits the text into words, adding an end-of-word marker </w> to each word to help the BPE algorithm recognize word boundaries.
Functions:
get_vocab(tokens): Builds a frequency dictionary of all unique words in the dataset.
get_pair_counts(vocab): Counts the frequency of each adjacent symbol pair across all words.
merge_pair(pair, vocab): Merges the most frequent pair into a single token, updating the vocabulary accordingly while respecting the max_token_length constraint.
BPE Training Loop:
Continuously identifies and merges the most frequent adjacent symbol pairs.
After each merge, the new token is added to the vocabulary if it doesn't exceed the max_token_length.
The loop terminates once the vocabulary reaches the desired size or no more valid pairs can be merged.
Output:
The final vocabulary is sorted alphabetically and written to vocab.txt, with each token on a new line.
Throughout the process, print statements provide insights into the training progress, such as which pairs are being merged and updates to the vocabulary size.
Usage:
Upload dataset.txt: Ensure that your dataset.txt file is uploaded to the Google Colab environment.
Run the Script: Execute the provided Python code in a Colab cell. The script will process the dataset, train the BPE vocabulary, and output vocab.txt in the working directory.
Adjust Parameters: Modify max_vocab_size and max_token_length as needed to suit your specific requirements.