To efficiently detect contamination between your training and benchmark datasets using 10-grams, we can implement an optimized Python script. Given the size of your training dataset (approximately 1 million prompts), it's crucial to manage memory and processing time effectively.
Here's a step-by-step approach:
-
Tokenization: Convert each prompt into tokens. For simplicity, we'll assume that tokens are separated by whitespace. If your data requires more sophisticated tokenization (e.g., handling punctuation), consider using libraries like nltk or spaCy.
-
Generating 10-grams: Extract all possible 10-grams from each tokenized prompt. A 10-gram is a sequence of 10 consecutive tokens.
-
Storing 10-grams: Since storing all 10-grams from the training set in memory might be memory-intensive, we can use a disk-based storage solution like SQLite. This allows us to store and query large amounts of data efficiently without exhausting memory.
-
Checking for Contamination: For each 10-gram in the benchmark dataset, check if it exists in the training set's 10-gram database.
Below is the optimized Python code implementing this approach:
import sqlite3
import itertools
from collections import deque
from tqdm import tqdm
import multiprocessing as mp
def tokenize(prompt):
"""Simple whitespace tokenizer. Modify if needed."""
return prompt.strip().split()
def generate_ngrams(tokens, n=10):
"""Generate n-grams from a list of tokens."""
if len(tokens) < n:
return
window = deque(maxlen=n)
for token in tokens:
window.append(token)
if len(window) == n:
yield tuple(window)
def create_database(db_path='training_ngrams.db'):
"""Create SQLite database and ngrams table."""
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS ngrams (
ngram TEXT PRIMARY KEY
)
''')
conn.commit()
return conn, cursor
def insert_ngrams(cursor, ngrams):
"""Insert n-grams into the database in batches."""
cursor.executemany('INSERT OR IGNORE INTO ngrams (ngram) VALUES (?)',
(( ' '.join(ngram),) for ngram in ngrams))
def build_training_ngrams_db(training_prompts, db_path='training_ngrams.db', batch_size=100000):
"""Build SQLite database of training n-grams."""
conn, cursor = create_database(db_path)
ngram_set = set()
count = 0
with tqdm(total=len(training_prompts), desc="Building Training 10-grams") as pbar:
for prompt in training_prompts:
tokens = tokenize(prompt)
for ngram in generate_ngrams(tokens):
ngram_set.add(ngram)
if len(ngram_set) >= batch_size:
insert_ngrams(cursor, ngram_set)
conn.commit()
ngram_set.clear()
count += batch_size
pbar.update(batch_size)
if ngram_set:
insert_ngrams(cursor, ngram_set)
conn.commit()
count += len(ngram_set)
pbar.update(len(ngram_set))
cursor.close()
conn.close()
print(f"Total 10-grams inserted: {count}")
def check_contamination(benchmark_prompts, db_path='training_ngrams.db'):
"""Check for contamination by comparing benchmark n-grams with training n-grams."""
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
contaminated = set()
with tqdm(total=len(benchmark_prompts), desc="Checking Contamination") as pbar:
for prompt in benchmark_prompts:
tokens = tokenize(prompt)
for ngram in generate_ngrams(tokens):
ngram_str = ' '.join(ngram)
cursor.execute('SELECT 1 FROM ngrams WHERE ngram = ?', (ngram_str,))
if cursor.fetchone():
contaminated.add(ngram_str)
# Optionally, you can break early if you just need to know if any contamination exists
# break
pbar.update(1)
cursor.close()
conn.close()
return contaminated
def main():
# Example usage:
# Assume you have two lists: training_prompts and benchmark_prompts
# For demonstration, replace these with your actual data loading mechanism
import sys
if len(sys.argv) != 3:
print("Usage: python contamination_check.py <training_prompts.txt> <benchmark_prompts.txt>")
sys.exit(1)
training_file = sys.argv[1]
benchmark_file = sys.argv[2]
# Load training prompts
print("Loading training prompts...")
with open(training_file, 'r', encoding='utf-8') as f:
training_prompts = f.readlines()
# Build the training n-grams database
build_training_ngrams_db(training_prompts)
# Load benchmark prompts
print("Loading benchmark prompts...")
with open(benchmark_file, 'r', encoding='utf-8') as f:
benchmark_prompts = f.readlines()
# Check for contamination
contaminated_ngrams = check_contamination(benchmark_prompts)
if contaminated_ngrams:
print(f"Found {len(contaminated_ngrams)} contaminated 10-grams:")
for ngram in contaminated_ngrams:
print(ngram)
else:
print("No contamination found.")
if __name__ == "__main__":
main()
Explanation of the Code:
-
Tokenization and N-gram Generation:
- The
tokenize function splits each prompt into tokens based on whitespace.
- The
generate_ngrams function uses a sliding window (deque) to efficiently generate 10-grams from the list of tokens.
-
SQLite Database for 10-grams:
- Using SQLite helps manage memory efficiently by storing 10-grams on disk.
- The
create_database function sets up the database with a table for storing unique 10-grams.
- The
insert_ngrams function batches the insertion of 10-grams to optimize database writes.
-
Building the Training 10-grams Database:
- The
build_training_ngrams_db function processes the training prompts, generates 10-grams, and inserts them into the SQLite database in batches to enhance performance.
- Progress is tracked using
tqdm for better visibility, especially with large datasets.
-
Checking for Contamination:
- The
check_contamination function iterates over the benchmark prompts, generates 10-grams, and checks each against the training 10-gram database.
- Contaminated 10-grams are collected in a set to avoid duplicates.
-
Main Function and Usage:
Optimizations Implemented:
-
Batch Insertion: Instead of inserting each 10-gram individually, the script batches insertions which significantly reduces the number of database transactions and speeds up the process.
-
Using SQLite: Leveraging a disk-based database like SQLite prevents memory exhaustion when dealing with millions of 10-grams.
-
Progress Tracking: The tqdm library provides real-time progress bars, which are helpful for monitoring the processing of large datasets.
-
Efficient N-gram Handling: Using deque with a fixed size ensures that sliding windows for n-grams are managed efficiently without unnecessary memory overhead.
Additional Considerations:
-
Indexing: SQLite automatically creates an index for primary keys. Since we're setting the ngram column as PRIMARY KEY, lookups are fast. However, if you modify the schema, ensure that appropriate indexes are in place.
-
Concurrency: For even larger datasets or faster processing, consider parallelizing parts of the code using Python's multiprocessing module. Be cautious with SQLite as it has limitations with concurrent writes.
-
Storage Space: Ensure you have sufficient disk space for the SQLite database, especially since 1 million prompts can generate tens of millions of 10-grams.
-
Error Handling: For production use, add error handling to manage potential issues like file I/O errors, database write failures, etc.
This script provides an efficient way to detect contamination between large datasets using 10-gram similarity. Adjust the tokenizer and other parameters as needed based on the specifics of your data.