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
Sure! Below is a Python script tailored to run in a Google Colab environment. This script reads a dataset.txt file, generates a vocabulary of subwords based on specified parameters, and saves the resulting vocabulary to vocab.txt. The script is written using pure Python without any external libraries and includes ample print statements to help you track its progress and debug if necessary.
Explanation:
Initialization:
ASCII Characters: The vocabulary begins with all ASCII characters (0-255) to ensure a fallback mechanism.
Parameters: You can control the vocabulary size and the maximum length of subwords using VOCAB_SIZE and MAX_SUBWORD_LENGTH.
Processing Steps:
Reading Data: The script reads the entire content of dataset.txt.
Counting Substrings: It counts the frequency of all possible substrings within the specified length constraints.
Selecting Subwords: Substrings are sorted by frequency and then alphabetically. The script iteratively adds the most frequent substrings to the vocabulary, ensuring that no subword is a part of another subword already in the vocabulary.
Final Sorting: The vocabulary is sorted first by frequency and then alphabetically before being written to vocab.txt.
Debugging and Progress Tracking:
The script includes print statements at each significant step to help you understand the internal state and progress of the vocabulary generation process.
Python Code:
python
# Parameters
VOCAB_SIZE = 1000 # Total vocabulary size including ASCII characters
MAX_SUBWORD_LENGTH = 10 # Maximum length of subwords
def load_data(file_path):
print(f"Loading data from {file_path}...")
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = f.read()
print(f"Loaded data length: {len(data)} characters.")
return data
except FileNotFoundError:
print(f"File {file_path} not found.")
return ""
def initialize_vocab():
print("Initializing vocabulary with ASCII characters (0-255)...")
vocab = [chr(i) for i in range(256)]
print(f"Initialized vocabulary with {len(vocab)} ASCII characters.")
return vocab
def count_substrings(data, max_length):
print(f"Counting substrings up to length {max_length}...")
substring_freq = {}
data_length = len(data)
for length in range(2, max_length + 1):
print(f"Counting substrings of length {length}...")
for i in range(data_length - length + 1):
substr = data[i:i+length]
if substr in substring_freq:
substring_freq[substr] += 1
else:
substring_freq[substr] = 1
print(f"Found {len(substring_freq)} unique substrings.")
return substring_freq
def sort_substrings(substring_freq):
print("Sorting substrings by frequency and alphabetically...")
# Create a list of tuples (substring, frequency)
substrings = list(substring_freq.items())
# Sort by frequency descending, then alphabetically
substrings.sort(key=lambda x: (-x[1], x[0]))
print(f"Top 10 substrings after sorting:")
for substr, freq in substrings[:10]:
print(f"'{substr}': {freq}")
return substrings
def select_subwords(sorted_substrings, existing_vocab, vocab_size, max_length):
print("Selecting subwords for the vocabulary...")
vocab = existing_vocab.copy()
existing_subwords = set(existing_vocab)
count = len(vocab)
print(f"Current vocabulary size: {count}")
for substr, freq in sorted_substrings:
if count >= vocab_size:
print(f"Reached desired vocabulary size: {vocab_size}")
break
# Check if substr is not part of any existing subword and vice versa
conflict = False
for sub in existing_subwords:
if substr in sub or sub in substr:
conflict = True
break
if not conflict:
vocab.append(substr)
existing_subwords.add(substr)
count += 1
if count % 100 == 0 or count == vocab_size:
print(f"Added '{substr}' to vocabulary. Current size: {count}")
print(f"Final vocabulary size after selection: {len(vocab)}")
return vocab
def save_vocab(vocab, file_path):
print(f"Saving vocabulary to {file_path}...")
try:
with open(file_path, 'w', encoding='utf-8') as f:
for subword in vocab:
# To handle non-printable ASCII characters, we can write their integer values
if len(subword) == 1 and ord(subword) < 256:
f.write(str(ord(subword)) + '\n')
else:
f.write(subword + '\n')
print(f"Vocabulary successfully saved to {file_path}.")
except Exception as e:
print(f"Error saving vocabulary: {e}")
def main():
data = load_data("dataset.txt")
if not data:
print("No data to process. Exiting.")
return
initial_vocab = initialize_vocab()
substring_freq = count_substrings(data, MAX_SUBWORD_LENGTH)
sorted_substrings = sort_substrings(substring_freq)
# Adjust vocab size to account for ASCII characters
desired_vocab_size = VOCAB_SIZE
if desired_vocab_size < 256:
print("Warning: VOCAB_SIZE is less than 256. All ASCII characters will be included, possibly exceeding VOCAB_SIZE.")
vocab = select_subwords(sorted_substrings, initial_vocab, desired_vocab_size, MAX_SUBWORD_LENGTH)
# Sort the final vocabulary: ASCII first sorted by code, then subwords sorted by frequency and alphabetically
ascii_vocab = [chr(i) for i in range(256)]
subword_vocab = [sub for sub in vocab if sub not in ascii_vocab]
# To sort subwords, we need their frequencies. Re-sort sorted_substrings to maintain frequency order
subword_freq = {substr: freq for substr, freq in substring_freq.items() if substr in subword_vocab}
# Sort subwords again by frequency descending, then alphabetically
sorted_subword_vocab = sorted(subword_vocab, key=lambda x: (-subword_freq.get(x,0), x))
final_vocab = ascii_vocab + sorted_subword_vocab
print("Final vocabulary sorted. Preparing to save.")
save_vocab(final_vocab, "vocab.txt")
if __name__ == "__main__":
main()
Usage Instructions:
Upload dataset.txt:
Before running the script, ensure that your dataset.txt file is uploaded to the Google Colab environment. You can upload files by clicking the folder icon on the left sidebar in Colab and then clicking the upload button.
Set Parameters:
You can adjust the VOCAB_SIZE and MAX_SUBWORD_LENGTH at the beginning of the script to suit your needs.
Run the Script:
Execute the script in a Colab cell. It will process the dataset.txt and generate a vocab.txt file in the same directory.
Download vocab.txt:
After the script finishes, you can download the vocab.txt file by clicking the three dots next to the file in the Colab file explorer and selecting "Download".
Notes:
ASCII Handling: The script writes ASCII characters as their integer values to ensure that non-printable characters are correctly represented in vocab.txt.
Performance Considerations: Counting all possible substrings can be computationally intensive for large datasets. Adjust MAX_SUBWORD_LENGTH and VOCAB_SIZE accordingly to balance performance and vocabulary comprehensiveness.
Conflict Resolution: The script ensures that no subword is a substring of another by checking for conflicts before adding a new subword to the vocabulary.
Feel free to modify and extend the script based on your specific requirements. Happy coding!