Certainly! Below is a comprehensive Python script tailored for a Google Colab environment. This script utilizes the tokenizers library from Hugging Face to implement a Byte Pair Encoding (BPE) algorithm. The script ensures that all byte values from 0 to 255 are included in the vocabulary and that the final vocabulary is sorted alphabetically, with each token separated by a newline in the output file vocab.txt.
Step-by-Step Explanation:
-
Install Necessary Libraries:
tokenizers: For implementing BPE.
byte handling and other utilities from Python's standard library.
-
Prepare the Dataset:
- Ensure that your
dataset.txt file is uploaded to the Colab environment. You can upload it manually or use other methods like mounting Google Drive.
-
Initialize and Train the BPE Tokenizer:
- The tokenizer is set up to handle byte-level encoding.
- The training process ensures that all byte values (0-255) are part of the initial vocabulary.
- The vocabulary size is adjustable based on your requirements.
-
Extract, Sort, and Save the Vocabulary:
- After training, the vocabulary is extracted from the tokenizer.
- It is then sorted alphabetically.
- The sorted vocabulary is saved to
vocab.txt with each token on a new line.
Complete Code:
# Install the required library
!pip install tokenizers
import os
from tokenizers import Tokenizer
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer
from tokenizers.pre_tokenizers import ByteLevel
from tokenizers.normalizers import NFD, Lowercase, StripAccents
import string
# Mount Google Drive if your dataset is stored there (optional)
# from google.colab import drive
# drive.mount('/content/drive')
# Ensure 'dataset.txt' is in the current directory.
# If not, you can upload it manually using the Colab interface or programmatically.
# Example to upload 'dataset.txt' manually:
from google.colab import files
uploaded = files.upload()
# Define the path to the dataset
dataset_path = "dataset.txt"
if not os.path.isfile(dataset_path):
raise FileNotFoundError(f"'{dataset_path}' not found. Please upload the file.")
# Initialize a BPE tokenizer with byte-level pre-tokenizer
tokenizer = Tokenizer(BPE())
tokenizer.pre_tokenizer = ByteLevel()
# Define the trainer with initial vocabulary containing all byte values (0-255)
# and set the vocab size accordingly. For example, vocab_size=10000 includes initial bytes plus merges.
# Adjust vocab_size as needed.
# Create a list of initial byte tokens (0-255)
initial_tokens = [chr(i) for i in range(256)]
# Initialize the BPE trainer
trainer = BpeTrainer(
vocab_size=10000, # Adjust vocab size as needed
initial_alphabet=initial_tokens,
special_tokens=[], # Add any special tokens if necessary
show_progress=True
)
# Train the tokenizer on the dataset
tokenizer.train([dataset_path], trainer)
# Get the vocabulary
vocab = tokenizer.get_vocab()
# Extract the tokens
tokens = list(vocab.keys())
# Ensure all byte values (0-255) are in the vocabulary
# Convert byte values to characters
byte_tokens = [chr(i) for i in range(256)]
missing_bytes = [token for token in byte_tokens if token not in tokens]
if missing_bytes:
print(f"Adding {len(missing_bytes)} missing byte tokens to the vocabulary.")
tokens.extend(missing_bytes)
# Remove duplicates if any
tokens = list(set(tokens))
# Sort the tokens alphabetically
tokens_sorted = sorted(tokens)
# Save the vocabulary to 'vocab.txt' with each token on a new line
with open("vocab.txt", "w", encoding="utf-8") as f:
for token in tokens_sorted:
# For non-printable characters, represent them using their byte values
if token in string.printable and token not in '\t\n\r\x0b\x0c':
f.write(token + "\n")
else:
# Represent non-printable characters using their byte integer value
f.write(f"<0x{ord(token):02x}>\n")
print("Vocabulary has been successfully saved to 'vocab.txt'.")
Detailed Breakdown:
-
Library Installation and Imports:
- The
tokenizers library is installed and imported along with necessary modules.
-
Dataset Handling:
- The script checks for the presence of
dataset.txt. If it's not found, it prompts the user to upload the file.
- You can upload the file manually via the Colab interface or mount Google Drive if your dataset resides there.
-
Tokenizer Initialization:
- A BPE tokenizer is initialized with a byte-level pre-tokenizer, ensuring that the tokenizer works at the byte level.
-
Trainer Configuration:
- The
BpeTrainer is configured with an initial_alphabet that includes all byte values from 0 to 255.
- The
vocab_size parameter can be adjusted based on the desired vocabulary size. It should be larger than 256 to accommodate merged tokens.
-
Training:
- The tokenizer is trained on the
dataset.txt file. Progress is displayed during training.
-
Vocabulary Extraction and Processing:
- After training, the vocabulary is extracted.
- The script ensures that all byte tokens (
0-255) are present. If any are missing, they are added.
- Duplicate tokens are removed to maintain uniqueness.
- The tokens are sorted alphabetically for easy readability and consistency.
-
Handling Non-printable Characters:
- Non-printable or special characters are represented in a readable format (e.g.,
<0x1a>) to avoid issues in the vocab.txt file.
-
Saving the Vocabulary:
- The final sorted vocabulary is saved to
vocab.txt, with each token on a new line.
-
Completion Message:
- Upon successful execution, a confirmation message is displayed.
Notes:
-
Vocabulary Size: The vocab_size parameter in the BpeTrainer determines the total number of tokens in the vocabulary. Ensure it's set according to your specific needs.
-
Special Tokens: If your application requires special tokens (like <PAD>, <UNK>, etc.), you can add them to the special_tokens list in the BpeTrainer.
-
Non-printable Characters: The script represents non-printable characters in a hexadecimal format for better readability and to prevent issues in downstream applications.
-
Dataset Size: Ensure that your dataset.txt is sufficiently large to train a meaningful BPE tokenizer. Very small datasets might not produce optimal results.
Feel free to adjust the parameters and configurations based on your specific requirements!