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)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a Python implementation of the Byte Pair Encoding (BPE) algorithm tailored for a Google Colab environment. This script:
Initializes the vocabulary with all ASCII characters (256 tokens).
Reads the dataset.txt file and processes it to count the frequency of each word.
Iteratively merges the most frequent pair of tokens to build the BPE vocabulary.
Stops when the maximum vocabulary size or maximum token length is reached.
Outputs the final vocabulary to vocab.txt, sorted alphabetically.
The script includes print statements to trace the training process and allows control over the maximum vocabulary size and maximum token length through parameters.
python
# BPE Implementation in Python for Google Colab
# Parameters
MAX_VOCAB_SIZE = 10000 # Adjust as needed
MAX_TOKEN_LENGTH = 30 # Adjust as needed
from collections import defaultdict
import re
def initialize_vocab():
"""Initialize the vocabulary with all ASCII characters."""
vocab = set()
for i in range(256):
vocab.add(chr(i))
return vocab
def get_stats(vocab, corpus):
"""Compute frequency of all adjacent pairs."""
pairs = defaultdict(int)
for word, freq in corpus.items():
symbols = word.split()
for i in range(len(symbols)-1):
pair = (symbols[i], symbols[i+1])
pairs[pair] += freq
return pairs
def merge_vocab(pair, vocab, corpus):
"""Merge the most frequent pair in the corpus."""
bigram = re.escape(' '.join(pair))
pattern = re.compile(r'(?<!\S)' + bigram + r'(?!\S)')
new_vocab = set()
new_corpus = {}
merged_token = ''.join(pair)
for word in corpus:
# Replace the pair with the merged token
new_word = pattern.sub(merged_token, word)
new_corpus[new_word] = corpus[word]
new_vocab.update(new_word.split())
vocab.add(merged_token)
return new_vocab, new_corpus
def train_bpe(dataset_path, output_path, max_vocab_size, max_token_length):
# Initialize vocabulary
vocab = initialize_vocab()
print(f"Initialized vocabulary with {len(vocab)} ASCII characters.")
# Read the dataset and count word frequencies
corpus = defaultdict(int)
with open(dataset_path, 'r', encoding='utf-8') as f:
for line in f:
words = line.strip().split()
for word in words:
# Append end of word token
word = ' '.join(list(word)) + ' </w>'
corpus[word] += 1
print(f"Processed dataset. Total unique words: {len(corpus)}")
while len(vocab) < max_vocab_size:
pairs = get_stats(vocab, corpus)
if not pairs:
print("No more pairs to merge.")
break
# Find the most frequent pair
best = max(pairs, key=pairs.get)
best_freq = pairs[best]
print(f"Merging pair: {best} with frequency {best_freq}")
# Merge the pair
vocab, corpus = merge_vocab(best, vocab, corpus)
print(f"Vocabulary size: {len(vocab)}")
# Check for maximum token length
if any(len(token) > max_token_length for token in vocab):
print("Maximum token length exceeded.")
vocab = vocab - set([token for token in vocab if len(token) > max_token_length])
break
# Sort the vocabulary alphabetically
sorted_vocab = sorted(vocab)
# Write to output file
with open(output_path, 'w', encoding='utf-8') as f:
for token in sorted_vocab:
f.write(token + '\n')
print(f"Training complete. Vocabulary written to {output_path}.")
# Run the training
train_bpe(
dataset_path='dataset.txt',
output_path='vocab.txt',
max_vocab_size=10000, # Set your desired max vocab size
max_token_length=30 # Set your desired max token length
)
Explanation of the Code:
Initialization:
The initialize_vocab function creates a set containing all 256 ASCII characters.
Corpus Preparation:
The dataset is read line by line.
Each word is split into its constituent characters with spaces and an end-of-word token </w> appended.
The frequency of each unique word representation is stored in the corpus dictionary.
BPE Training Loop:
The get_stats function calculates the frequency of all adjacent pairs of tokens in the corpus.
The most frequent pair is identified and merged using the merge_vocab function.
After each merge, the vocabulary size is updated and checked against the maximum allowed size.
The loop continues until the vocabulary reaches the max_vocab_size or no more pairs can be merged.
Additionally, it ensures that no token exceeds the max_token_length.
Output:
Once training is complete, the vocabulary is sorted alphabetically and written to vocab.txt with one token per line.
Parameters:
MAX_VOCAB_SIZE: Controls the maximum size of the vocabulary.
MAX_TOKEN_LENGTH: Ensures that no token exceeds this length.
Notes:
Performance: This implementation is suitable for smaller datasets and vocabularies. For larger datasets, optimizations may be necessary.
End-of-Word Token: The </w> token is used to signify the end of a word. This helps the algorithm understand word boundaries during merging.
Handling Non-ASCII Characters: Ensure that dataset.txt contains only ASCII characters or modify the initialization to include the required character set.
Running the Code in Google Colab:
Upload dataset.txt: Ensure that your dataset.txt file is uploaded to the Colab environment.
Execute the Script: Run the provided script in a Colab cell. Adjust the MAX_VOCAB_SIZE and MAX_TOKEN_LENGTH as needed.
Download vocab.txt: After training, vocab.txt will be available in the working directory. You can download it using the Colab file browser or with the following code:
python
from google.colab import files
files.download('vocab.txt')
This implementation provides a foundational BPE tokenizer without relying on external libraries, giving you full control over the training process and parameters.