-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_module.py
More file actions
95 lines (80 loc) · 3.21 KB
/
data_module.py
File metadata and controls
95 lines (80 loc) · 3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from datasets import load_dataset
from transformers import AutoTokenizer
from dataclasses import dataclass
import os, random, numpy as np, torch
from tqdm import tqdm
@dataclass
class TokenizationConfig:
dataset_name: str = "roneneldan/TinyStories"
text_column: str = "text" # TinyStories uses "text" column
tokenizer_name: str = "openai-community/gpt2" # Use pretrained GPT-2 Tokenizer
block_size: int = 128
num_proc: int = 4 # Parallel CPU processes
output_dir: str = './tokenized_tinystories'
seed: int = 42
def set_seed(seed: int):
"""Ensure deterministic preprocessing."""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
print(f"Random seed set to {seed}")
def get_tokenizer(cfg: TokenizationConfig):
tokenizer = AutoTokenizer.from_pretrained(cfg.tokenizer_name, use_fast=True)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
return tokenizer
def tokenize_and_group(cfg: TokenizationConfig):
set_seed(cfg.seed)
print(f"Loading dataset: {cfg.dataset_name}")
raw = load_dataset(cfg.dataset_name)
# Ensure validation split exists
if "validation" not in raw.keys():
print("No validation split found, creating one manually (1% of train).")
raw = raw["train"].train_test_split(test_size=0.01, seed=cfg.seed)
raw["validation"] = raw["test"]
del raw["test"]
print(f"Loading tokenizer: {cfg.tokenizer_name}")
tokenizer = get_tokenizer(cfg)
# Step 1: Tokenize
def tokenize_function(examples):
return tokenizer(examples[cfg.text_column], return_attention_mask=False)
print(f"Tokenizing dataset (batched)")
tokenized = raw.map(
tokenize_function,
batched=True,
num_proc=cfg.num_proc,
remove_columns=[cfg.text_column]
)
# Step 2: group into fixed size blocks
def group_texts(examples):
all_ids = sum(examples['input_ids'], [])
total_length = (len(all_ids)//cfg.block_size) * cfg.block_size
result = {
'input_ids': [all_ids[i: i+cfg.block_size] for i in range(0, total_length, cfg.block_size)]
}
result['labels'] = result['input_ids'].copy()
return result
print(f"Group into {cfg.block_size}-token blocks...")
grouped = tokenized.map(
group_texts,
batched=True,
num_proc=cfg.num_proc
)
# Step 3: save both splits
os.makedirs(cfg.output_dir, exist_ok=True)
print(f"Saving tokenized dataset to {cfg.output_dir}")
for split in ["train", "validation"]:
split_path = os.path.join(cfg.output_dir, split)
os.makedirs(split_path, exist_ok=True)
print(f" → Saving {split} split ({len(grouped[split])} samples)")
grouped[split].save_to_disk(split_path)
# Save tokenizer too
tokenizer.save_pretrained(cfg.output_dir)
print("Done! Tokenized dataset (train + validation) saved.")
print(f"Each sample length: {cfg.block_size}")
return grouped
if __name__ == '__main__':
cfg = TokenizationConfig()
tokenize_and_group(cfg)