Write some python code, that will be running in a Google Colab instance, to generate a vocabulary based on a given dataset. You will load a file, named "dataset.txt" and generate a vocabulary of subwords and save it to "vocab.txt". Do not use any library, instead writing clean and pure python code. Here is how the vocabulary should be formed:
At first we should have all the possible ASCII characters, including the extension table. That means that the vocab will contain ASCII values from 0 to 255 as a fallback, if a text cannot be encoded afterwards
You find the best algorithm to create a list of words and subwords that will encode the text, creating a vocabulary. We should have control parameters, such as the vocabulary size and max length of words in the vocab.
No subword should be part of any other subword. That means that if "some" is a possible subword, "something" shouldn't be one, only: "thing". Apply this principle retroactively
Words and subwords will be sorted by frequencies (keeping only the first vocab_size subwords) and then sorting them alphabetically to store them into the final "vocab.txt" file. Each subword will be separated by a newline in the final file
What I recommend doing is:
Create an algorithm for finding the most common substrings in the main string, with a size greater than the max word size
Repeatedly trying to cut these most frequent substrings into subwords, with as much sense as possible for these cuts.
Iteratively repeat the cutting mechanism for even the subwords created from previous cuts, if they exceed the max word size themselves. A word like: "something" could be split into subwords like: "some", "thing", for example.
Subwords of length 1 or less should be discarded.
Add as much printing statements as possible, trying small arguments to your functions to see if they function correctly
Before exporting the vocabulary, make sure to include the base ASCII values and sort the vocab.
Assistant
Certainly! Below is a Python script designed to be run in a Google Colab environment. This script reads a dataset.txt file, generates a vocabulary based on the specified parameters, and saves the vocabulary to vocab.txt. The vocabulary includes all ASCII characters (0-255) as a base and adds the most frequent subwords based on the dataset while ensuring that no subword is part of another subword.
python
# Define control parameters
VOCAB_SIZE = 1000 # Maximum number of subwords to add to the vocabulary
MAX_WORD_LENGTH = 10 # Maximum length of subwords
def load_dataset(file_path):
"""
Load the dataset from a text file.
"""
print(f"Loading dataset from '{file_path}'...")
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = f.read()
print(f"Dataset loaded successfully. Length: {len(data)} characters.")
return data
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return ""
def initialize_base_vocab():
"""
Initialize the base vocabulary with all ASCII characters (0-255).
"""
print("Initializing base vocabulary with ASCII characters (0-255)...")
base_vocab = [chr(i) for i in range(256)]
print(f"Base vocabulary initialized with {len(base_vocab)} ASCII characters.")
return base_vocab
def count_subword_frequencies(data, max_length):
"""
Count the frequency of all substrings in the data with length >=2 and <= max_length.
"""
print(f"Counting frequencies of all substrings with length >=2 and <= {max_length}...")
freq_dict = {}
data_length = len(data)
for i in range(data_length):
for l in range(2, max_length + 1):
if i + l <= data_length:
substr = data[i:i+l]
freq_dict[substr] = freq_dict.get(substr, 0) + 1
if i % 100000 == 0 and i > 0:
print(f"Processed {i} characters...")
print(f"Total unique substrings counted: {len(freq_dict)}")
return freq_dict
def sort_subwords(freq_dict):
"""
Sort the substrings first by descending frequency and then alphabetically.
"""
print("Sorting substrings by frequency and alphabetically...")
sorted_subwords = sorted(freq_dict.items(), key=lambda x: (-x[1], x[0]))
print(f"Top 10 most frequent substrings:")
for subword, freq in sorted_subwords[:10]:
print(f"'{subword}': {freq}")
return sorted_subwords
def is_subword_conflict(candidate, vocab):
"""
Check if the candidate subword is a substring of any existing vocab subword
or any existing vocab subword is a substring of the candidate.
"""
for word in vocab:
if word in candidate or candidate in word:
return True
return False
def select_subwords(sorted_subwords, vocab_size, max_length):
"""
Select subwords ensuring no subword is part of another subword.
"""
print(f"Selecting top {vocab_size} subwords without substring conflicts...")
selected_subwords = []
count = 0
for subword, freq in sorted_subwords:
if len(subword) > max_length:
continue # Skip if subword exceeds max_length
if is_subword_conflict(subword, selected_subwords):
continue # Skip if there's a conflict
selected_subwords.append(subword)
count += 1
if count % 100 == 0:
print(f"Selected {count} subwords so far...")
if count >= vocab_size:
break
print(f"Total subwords selected: {len(selected_subwords)}")
return selected_subwords
def save_vocab(base_vocab, subword_vocab, output_file):
"""
Save the final vocabulary to a file, each subword on a new line.
"""
print(f"Saving vocabulary to '{output_file}'...")
try:
with open(output_file, 'w', encoding='utf-8') as f:
for word in base_vocab:
f.write(word + '\n')
for word in subword_vocab:
f.write(word + '\n')
print(f"Vocabulary saved successfully with {len(base_vocab) + len(subword_vocab)} total entries.")
except Exception as e:
print(f"Error saving vocabulary: {e}")
def main():
# File paths
dataset_path = "dataset.txt"
vocab_output_path = "vocab.txt"
# Load dataset
data = load_dataset(dataset_path)
if not data:
return
# Initialize base vocabulary
base_vocab = initialize_base_vocab()
# Count substring frequencies
freq_dict = count_subword_frequencies(data, MAX_WORD_LENGTH)
# Sort substrings by frequency and alphabetically
sorted_subwords = sort_subwords(freq_dict)
# Select subwords without conflicts
subword_vocab = select_subwords(sorted_subwords, VOCAB_SIZE, MAX_WORD_LENGTH)
# Sort subword_vocab by frequency descending and then alphabetically
# Re-sort based on original sorted_subwords to maintain frequency order
subword_vocab_sorted = sorted(subword_vocab, key=lambda x: (-freq_dict[x], x))
# Save the final vocabulary
save_vocab(base_vocab, subword_vocab_sorted, vocab_output_path)
print("Vocabulary generation complete.")
# Run the main function
if __name__ == "__main__":
main()
Explanation of the Code
Control Parameters:
VOCAB_SIZE: Specifies the maximum number of subwords to be added to the vocabulary besides the base ASCII characters.
MAX_WORD_LENGTH: Defines the maximum length for the subwords.
Function Definitions:
load_dataset: Reads the dataset.txt file and loads its content into a string.
initialize_base_vocab: Creates a list of all ASCII characters (from chr(0) to chr(255)).
count_subword_frequencies: Iterates through the dataset to count the frequency of all possible substrings with lengths ranging from 2 to MAX_WORD_LENGTH.
sort_subwords: Sorts the substrings first by descending frequency and then alphabetically.
is_subword_conflict: Checks whether a candidate subword conflicts with any already selected subword (i.e., one is a substring of the other).
select_subwords: Selects the top VOCAB_SIZE subwords ensuring no substring conflicts.
save_vocab: Writes the final vocabulary to vocab.txt, with each subword on a new line.
Main Execution Flow:
Loads the dataset from dataset.txt.
Initializes the base vocabulary with all ASCII characters.
Counts the frequencies of all relevant substrings in the dataset.
Sorts these substrings based on frequency and alphabetical order.
Selects the top subwords while ensuring no conflicts.
Saves the combined vocabulary (base ASCII + subwords) to vocab.txt.
How to Use
Prepare the Dataset:
Ensure that the dataset.txt file is uploaded to your Google Colab environment. You can do this by using the upload feature in Colab:
python
from google.colab import files
uploaded = files.upload()
Then select the dataset.txt file from your local machine.
Set Control Parameters(Optional):
You can modify the VOCAB_SIZE and MAX_WORD_LENGTH variables at the top of the script to suit your requirements.
Run the Script:
Execute the entire script in a Colab cell. It will process the dataset and generate the vocab.txt file.
Download the Vocabulary:
After execution, download the vocab.txt file to your local machine using:
python
files.download('vocab.txt')
Notes
Performance: Counting all possible substrings can be computationally intensive for large datasets. The script includes print statements to monitor progress, especially useful for large files.
Conflict Resolution: The select_subwords function ensures that no subword is a substring of another, adhering to the user's specifications.
Sorting: Subwords are sorted primarily by frequency (descending) and secondarily alphabetically to resolve ties.
Feel free to adjust the VOCAB_SIZE and MAX_WORD_LENGTH to better fit the specifics of your dataset and requirements.