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 and extensions, ranging from integer value 0 to 255. The vocab should also be sorted in alphabetical order. Do not use any library, instead writing the training code yourself.
Assistant
Sure! Below is a Python script tailored for a Google Colab environment that performs Byte Pair Encoding (BPE) on a dataset.txt file to generate a vocabulary (vocab.txt). This implementation ensures that all ASCII characters (ranging from integer values 0 to 255) are included in the vocabulary and that the final vocabulary is sorted alphabetically. The script does not rely on any external libraries for the BPE algorithm.
Steps Overview:
Upload the Dataset: Prompt the user to upload the dataset.txt file to the Colab environment.
Initialize Vocabulary: Start with all ASCII characters (0-255) in the vocabulary.
Perform BPE Merges: Iteratively merge the most frequent pair of tokens to build the vocabulary.
Sort and Save Vocabulary: Sort the final vocabulary alphabetically and save it to vocab.txt.
Complete Code:
python
# Import necessary modules
from collections import defaultdict
from google.colab import files
import os
# Step 1: Upload 'dataset.txt' to the Colab instance
print("Please upload your 'dataset.txt' file.")
uploaded = files.upload()
# Ensure 'dataset.txt' has been uploaded
if 'dataset.txt' not in uploaded:
raise FileNotFoundError("The file 'dataset.txt' was not uploaded. Please upload it and run the cell again.")
# Step 2: Read the dataset using 'latin1' encoding to preserve byte values 0-255
with open('dataset.txt', 'r', encoding='latin1') as f:
text = f.read()
print("Dataset successfully loaded.")
# Step 3: Initialize tokens as a list of characters
tokens = list(text)
# Step 4: Initialize vocabulary with all byte characters (0-255)
vocab = set([chr(i) for i in range(256)])
# Step 5: Define the number of merges
# You can adjust 'num_merges' based on the desired vocabulary size
num_merges = 1000 # Example: perform 1000 BPE merges
for merge_iteration in range(1, num_merges + 1):
# Step 5a: Count frequency of all adjacent pairs
pair_freq = defaultdict(int)
for i in range(len(tokens) - 1):
pair = (tokens[i], tokens[i + 1])
pair_freq[pair] += 1
if not pair_freq:
print("No more pairs to merge. Ending BPE training.")
break
# Step 5b: Identify the most frequent pair
most_freq_pair = max(pair_freq, key=pair_freq.get)
frequency = pair_freq[most_freq_pair]
# If the most frequent pair occurs only once, optionally stop early
if frequency < 2:
print(f"Most frequent pair '{most_freq_pair}' occurs only once. Ending BPE training.")
break
# Step 5c: Merge the most frequent pair into a new token
merged_token = ''.join(most_freq_pair)
vocab.add(merged_token)
# Step 5d: Replace all occurrences of the pair with the merged token
new_tokens = []
i = 0
while i < len(tokens):
# Check if the current and next token form the most frequent pair
if i < len(tokens) - 1 and (tokens[i], tokens[i + 1]) == most_freq_pair:
new_tokens.append(merged_token)
i += 2 # Skip the next token as it's part of the merged pair
else:
new_tokens.append(tokens[i])
i += 1
tokens = new_tokens
# Optional: Print progress every 100 merges
if merge_iteration % 100 == 0 or merge_iteration == 1:
print(f"Merge {merge_iteration}: {most_freq_pair} -> {merged_token} | Frequency: {frequency}")
print(f"BPE training completed after {merge_iteration} merges.")
# Step 6: Sort the vocabulary alphabetically
sorted_vocab = sorted(vocab)
# Step 7: Write the sorted vocabulary to 'vocab.txt', each token on a new line
with open('vocab.txt', 'w', encoding='latin1') as f:
for token in sorted_vocab:
f.write(token + '\n')
print(f"Vocabulary size: {len(sorted_vocab)}")
print("Vocabulary has been written to 'vocab.txt'.")
How to Use This Script in Google Colab:
Open Google Colab: Go to Google Colab and create a new notebook.
Upload the Code: Copy and paste the above script into a code cell in the notebook.
Run the Cell: Execute the cell. It will prompt you to upload the dataset.txt file. Select the file from your local machine.
Monitor Progress: The script will print progress messages, especially every 100 merges, so you can monitor the BPE training process.
Retrieve vocab.txt: After completion, you can download the vocab.txt file by running the following code in a new cell:
python
from google.colab import files
files.download('vocab.txt')
Notes:
Adjusting num_merges: The num_merges variable determines how many BPE merge operations are performed. Increasing this number allows the model to capture more complex tokens but will result in a larger vocabulary. You can adjust this based on your specific needs and the size of your dataset.
Early Stopping: The script includes checks to stop early if no more frequent pairs are available to merge, which can save computation time.
Encoding: The 'latin1' encoding is used to ensure that all byte values from 0 to 255 are correctly handled without data loss.
This implementation provides a fundamental BPE training mechanism suitable for educational purposes or small-scale projects. For large-scale applications or more optimized performance, consider using specialized libraries like sentencepiece or subword-nmt.