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.
Assistant
Sure! Below is a Python script designed to run in a Google Colab environment. This script performs Byte Pair Encoding (BPE) on a dataset.txt file to generate a vocabulary of tokens, ensuring that all ASCII characters are included. The resulting vocabulary is sorted alphabetically and saved to vocab.txt.
Overview of the Steps:
Initialize ASCII Symbols: Begin with all 128 ASCII characters to ensure they're included in the vocabulary.
Read and Preprocess the Dataset: Load dataset.txt, split it into words, and count the frequency of each word.
Build the Initial Vocabulary: Represent each word as a list of symbols (initially individual characters).
Perform BPE Merges: Iteratively merge the most frequent pair of symbols to form new tokens.
Compile the Final Vocabulary: Collect all unique symbols after merging, sort them alphabetically, and save to vocab.txt.
Python Code:
python
# BPE Vocabulary Builder in Google Colab
# This script reads 'dataset.txt', performs BPE, and writes 'vocab.txt'
# Step 1: Initialize all ASCII characters
import string
# Generate all 128 ASCII characters
ascii_chars = [chr(i) for i in range(128)]
# Step 2: Read the dataset and build word frequencies
from collections import defaultdict
vocab = defaultdict(int)
with open('dataset.txt', 'r', encoding='utf-8') as f:
for line in f:
words = line.strip().split()
for word in words:
# Represent each word as a tuple of characters
tokens = tuple(word)
vocab[tokens] += 1
# Ensure all ASCII characters are in the initial vocabulary
for char in ascii_chars:
if (char,) not in vocab:
vocab[(char,)] = 1
# Step 3: Define helper functions for BPE
def get_pair_frequencies(vocab):
"""Count frequency of symbol pairs in the vocabulary."""
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_vocab(pair, vocab):
"""Merge the most frequent pair in the vocabulary."""
merged_vocab = {}
bigram = ''.join(pair)
for word, freq in vocab.items():
new_word = []
i = 0
while i < len(word):
# Find the pair in the word
if i < len(word)-1 and word[i] == pair[0] and word[i+1] == pair[1]:
new_word.append(bigram)
i += 2
else:
new_word.append(word[i])
i += 1
merged_vocab[tuple(new_word)] = freq
return merged_vocab
# Step 4: Perform BPE merges
num_merges = 1000 # You can adjust this number based on desired vocab size
for merge_iteration in range(num_merges):
pairs = get_pair_frequencies(vocab)
if not pairs:
break
# Find the most frequent pair
most_freq_pair = max(pairs, key=pairs.get)
if pairs[most_freq_pair] < 1:
break
# Merge the most frequent pair
vocab = merge_vocab(most_freq_pair, vocab)
# Optional: print merge information
# print(f"Merge {merge_iteration+1}: {most_freq_pair} -> {''.join(most_freq_pair)}")
# Step 5: Extract the final vocabulary
final_tokens = set()
for word in vocab:
for symbol in word:
final_tokens.add(symbol)
# Ensure all ASCII characters are included
for char in ascii_chars:
final_tokens.add(char)
# Sort the tokens alphabetically
sorted_tokens = sorted(final_tokens)
# Step 6: Write the vocabulary to 'vocab.txt'
with open('vocab.txt', 'w', encoding='utf-8') as f:
for token in sorted_tokens:
f.write(token + '\n')
print("Vocabulary has been written to 'vocab.txt'.")
How to Use This Script in Google Colab:
Upload dataset.txt: Ensure that your dataset.txt file is uploaded to the current working directory in your Colab environment. You can upload files by clicking the folder icon on the left sidebar and then clicking the upload button.
Run the Script: Copy and paste the above Python code into a Colab notebook cell and execute it. The script will process the dataset and generate vocab.txt in the same directory.
Download vocab.txt: After the script completes, you can download the vocab.txt file by clicking on the file in the sidebar and selecting the download option.
Notes:
Number of Merges (num_merges): The variable num_merges controls how many BPE merge operations are performed. Increasing this number results in a larger vocabulary with more merged tokens, while decreasing it will generate a smaller vocabulary. You can adjust this based on your specific requirements.
Performance Considerations: For very large datasets or a high number of merges, the script might take longer to execute. Ensure that the Colab runtime has sufficient resources or consider optimizing the code further if needed.
ASCII Characters: The script explicitly initializes the vocabulary with all 128 ASCII characters to guarantee their inclusion, even if some of them do not appear in the dataset.
This script provides a foundational implementation of BPE without relying on external libraries, making it suitable for educational purposes or scenarios where dependencies need to be minimized.