Spaces:
Runtime error
Runtime error
Upload prepare_code_dataset.py with huggingface_hub
Browse files- prepare_code_dataset.py +122 -0
prepare_code_dataset.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Data preparation script for training nanoGPT on the flytech/python-codes-25k dataset.
|
| 3 |
+
This script downloads the dataset, tokenizes it, and creates the binary files needed for training.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import pickle
|
| 8 |
+
import numpy as np
|
| 9 |
+
from datasets import load_dataset
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
|
| 12 |
+
def download_and_prepare_code_dataset():
|
| 13 |
+
"""Download and prepare the flytech/python-codes-25k dataset for nanoGPT training."""
|
| 14 |
+
|
| 15 |
+
print("Loading flytech/python-codes-25k dataset...")
|
| 16 |
+
dataset = load_dataset("flytech/python-codes-25k")
|
| 17 |
+
|
| 18 |
+
print(f"Dataset structure: {dataset}")
|
| 19 |
+
print(f"Available splits: {list(dataset.keys())}")
|
| 20 |
+
print(f"Train split size: {len(dataset['train'])}")
|
| 21 |
+
|
| 22 |
+
# Debug: Check the first few examples to understand the structure
|
| 23 |
+
print("\nFirst example structure:")
|
| 24 |
+
first_example = dataset['train'][0]
|
| 25 |
+
for key, value in first_example.items():
|
| 26 |
+
print(f" {key}: {repr(value[:200])}...") # Show first 200 chars
|
| 27 |
+
|
| 28 |
+
# Create data directory
|
| 29 |
+
data_dir = os.path.join('data', 'python-codes-25k')
|
| 30 |
+
os.makedirs(data_dir, exist_ok=True)
|
| 31 |
+
|
| 32 |
+
# Extract code content from the dataset
|
| 33 |
+
print("Extracting code content...")
|
| 34 |
+
train_texts = []
|
| 35 |
+
test_texts = []
|
| 36 |
+
|
| 37 |
+
# Process training data
|
| 38 |
+
for item in tqdm(dataset['train'], desc="Processing train split"):
|
| 39 |
+
# Try different possible field names for code content
|
| 40 |
+
code = item.get('text', '') or item.get('output', '') or item.get('code', '')
|
| 41 |
+
if code and isinstance(code, str) and len(code.strip()) > 0:
|
| 42 |
+
train_texts.append(code)
|
| 43 |
+
|
| 44 |
+
# Split training data into train and validation sets (90/10 split)
|
| 45 |
+
print("Splitting data into train and validation sets...")
|
| 46 |
+
total_samples = len(train_texts)
|
| 47 |
+
split_idx = int(0.9 * total_samples)
|
| 48 |
+
|
| 49 |
+
train_texts_final = train_texts[:split_idx]
|
| 50 |
+
test_texts = train_texts[split_idx:] # Use last 10% as validation
|
| 51 |
+
|
| 52 |
+
print(f"Final train samples: {len(train_texts_final)}")
|
| 53 |
+
print(f"Validation samples: {len(test_texts)}")
|
| 54 |
+
|
| 55 |
+
print(f"Extracted {len(train_texts)} total samples")
|
| 56 |
+
|
| 57 |
+
# Combine all texts for vocabulary building
|
| 58 |
+
all_text = '\n'.join(train_texts_final + test_texts)
|
| 59 |
+
print(f"Total characters: {len(all_text):,}")
|
| 60 |
+
|
| 61 |
+
# Create vocabulary from the text
|
| 62 |
+
print("Creating vocabulary...")
|
| 63 |
+
chars = sorted(list(set(all_text)))
|
| 64 |
+
vocab_size = len(chars)
|
| 65 |
+
print(f"Vocabulary size: {vocab_size}")
|
| 66 |
+
|
| 67 |
+
# Create character to integer mapping
|
| 68 |
+
stoi = {ch: i for i, ch in enumerate(chars)}
|
| 69 |
+
itos = {i: ch for i, ch in enumerate(chars)}
|
| 70 |
+
|
| 71 |
+
# Save vocabulary metadata
|
| 72 |
+
meta = {
|
| 73 |
+
'vocab_size': vocab_size,
|
| 74 |
+
'itos': itos,
|
| 75 |
+
'stoi': stoi,
|
| 76 |
+
}
|
| 77 |
+
with open(os.path.join(data_dir, 'meta.pkl'), 'wb') as f:
|
| 78 |
+
pickle.dump(meta, f)
|
| 79 |
+
print(f"Saved vocabulary to {os.path.join(data_dir, 'meta.pkl')}")
|
| 80 |
+
|
| 81 |
+
# Tokenize and save training data
|
| 82 |
+
print("Tokenizing training data...")
|
| 83 |
+
train_ids = []
|
| 84 |
+
for text in tqdm(train_texts_final, desc="Tokenizing train"):
|
| 85 |
+
ids = [stoi[c] for c in text]
|
| 86 |
+
train_ids.extend(ids)
|
| 87 |
+
|
| 88 |
+
# Tokenize and save test data
|
| 89 |
+
print("Tokenizing test data...")
|
| 90 |
+
test_ids = []
|
| 91 |
+
for text in tqdm(test_texts, desc="Tokenizing test"):
|
| 92 |
+
ids = [stoi[c] for c in text]
|
| 93 |
+
test_ids.extend(ids)
|
| 94 |
+
|
| 95 |
+
# Save as binary files
|
| 96 |
+
train_ids = np.array(train_ids, dtype=np.uint16)
|
| 97 |
+
test_ids = np.array(test_ids, dtype=np.uint16)
|
| 98 |
+
|
| 99 |
+
train_path = os.path.join(data_dir, 'train.bin')
|
| 100 |
+
test_path = os.path.join(data_dir, 'val.bin') # nanoGPT expects 'val.bin'
|
| 101 |
+
|
| 102 |
+
train_ids.tofile(train_path)
|
| 103 |
+
test_ids.tofile(test_path)
|
| 104 |
+
|
| 105 |
+
print(f"Saved training data to {train_path} ({len(train_ids):,} tokens)")
|
| 106 |
+
print(f"Saved validation data to {test_path} ({len(test_ids):,} tokens)")
|
| 107 |
+
|
| 108 |
+
# Print some statistics
|
| 109 |
+
print(f"\nDataset statistics:")
|
| 110 |
+
print(f"Vocabulary size: {vocab_size}")
|
| 111 |
+
print(f"Training tokens: {len(train_ids):,}")
|
| 112 |
+
print(f"Validation tokens: {len(test_ids):,}")
|
| 113 |
+
print(f"Total tokens: {len(train_ids) + len(test_ids):,}")
|
| 114 |
+
|
| 115 |
+
# Show some example characters
|
| 116 |
+
print(f"\nFirst 100 characters in vocabulary:")
|
| 117 |
+
print(''.join(chars[:100]))
|
| 118 |
+
|
| 119 |
+
return data_dir
|
| 120 |
+
|
| 121 |
+
if __name__ == '__main__':
|
| 122 |
+
download_and_prepare_code_dataset()
|