Datasets:
File size: 7,194 Bytes
c7fac78 | 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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | #!/usr/bin/env python3
"""Tokenize FineWeb-Edu parquet files to byte-level .bin format.
Spider-FLEXITOKENS uses byte-level vocab (272 tokens: 256 bytes + 16 specials).
This script converts raw text parquet files to uint16 .bin files ready for
fast loading by ByteLevelTokenizedDataset.
Output format:
- tokens.uint16: concatenated byte values (0-255) + special tokens (256-271)
- metadata.json: {num_tokens, num_samples, seq_len, etc.}
"""
import os
import sys
import json
import glob
import argparse
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
from tqdm import tqdm
# Sentinel tokens
BOS_ID = 257
EOS_ID = 258
PAD_ID = 256
def tokenize_text(text: str, max_bytes: int = 2048) -> list:
"""Convert text to byte-level token sequence with BOS/EOS."""
byte_ids = list(text.encode('utf-8'))[:max_bytes]
return [BOS_ID] + byte_ids + [EOS_ID]
def process_parquet(parquet_path: str, output_dir: str, seq_len: int = 2048, max_samples: int = 0):
"""Process a single parquet file to tokenized .bin."""
print(f"Processing: {parquet_path}")
output_path = os.path.join(output_dir, os.path.basename(parquet_path).replace('.parquet', '.bin'))
tokens = []
num_samples = 0
try:
pf = pq.ParquetFile(parquet_path)
for batch in tqdm(pf.iter_batches(batch_size=1000, columns=["text"]), desc=os.path.basename(parquet_path)):
texts = batch["text"].to_pylist()
for text in texts:
if not text:
continue
token_ids = tokenize_text(text, max_bytes=seq_len - 2) # -2 for BOS/EOS
tokens.extend(token_ids)
num_samples += 1
if max_samples > 0 and num_samples >= max_samples:
break
if max_samples > 0 and num_samples >= max_samples:
break
except Exception as e:
print(f"Error processing {parquet_path}: {e}")
return 0, 0
if tokens:
arr = np.array(tokens, dtype=np.uint16)
arr.tofile(output_path)
print(f" Saved: {output_path} ({arr.nbytes / 1024**2:.1f} MB, {len(tokens):,} tokens)")
return len(tokens), num_samples
return 0, 0
def stream_from_huggingface(output_dir, seq_len=2048, num_shards=50, samples_per_shard=50000):
"""Stream FineWeb-Edu from HuggingFace and tokenize to .bin shards."""
from datasets import load_dataset
from tqdm import tqdm
os.makedirs(output_dir, exist_ok=True)
print(f"Streaming FineWeb-Edu from HuggingFace (10BT sample)")
print(f"Output: {output_dir}")
ds = load_dataset("HuggingFaceFW/fineweb-edu", "sample/10BT", split="train", streaming=True)
total_tokens = 0
total_samples = 0
shard_tokens = []
shard_count = 0
for sample in tqdm(ds, desc="Tokenizing"):
text = sample.get("text", "")
if not text:
continue
token_ids = tokenize_text(text, max_bytes=seq_len - 2)
shard_tokens.extend(token_ids)
total_samples += 1
if len(shard_tokens) >= samples_per_shard * seq_len:
shard_count += 1
arr = np.array(shard_tokens, dtype=np.uint16)
shard_path = os.path.join(output_dir, f"shard_{shard_count:04d}.bin")
arr.tofile(shard_path)
print(f" Shard {shard_count}: {shard_path} ({arr.nbytes / 1024**2:.1f} MB, {len(shard_tokens):,} tokens, {total_samples:,} samples)")
total_tokens += len(shard_tokens)
shard_tokens = []
if shard_count >= num_shards:
break
if shard_tokens:
shard_count += 1
arr = np.array(shard_tokens, dtype=np.uint16)
shard_path = os.path.join(output_dir, f"shard_{shard_count:04d}.bin")
arr.tofile(shard_path)
print(f" Shard {shard_count}: {shard_path} ({arr.nbytes / 1024**2:.1f} MB, {len(shard_tokens):,} tokens)")
total_tokens += len(shard_tokens)
metadata = {
"source": "HuggingFaceFW/fineweb-edu sample/10BT",
"seq_len": seq_len,
"vocab_size": 272,
"dtype": "uint16",
"total_samples": total_samples,
"total_tokens": total_tokens,
"num_shards": shard_count,
"token_format": "BOS + UTF-8 bytes + EOS (byte-level, 272 vocab)",
}
with open(os.path.join(output_dir, "metadata.json"), 'w') as f:
json.dump(metadata, f, indent=2)
print(f"\nDone! Total: {total_samples:,} samples, {total_tokens:,} tokens, {shard_count} shards")
print(f"Metadata saved to {output_dir}/metadata.json")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--input_dir", type=str, default="",
help="Input directory with parquet files (local mode)")
parser.add_argument("--output_dir", type=str, default="/home/lamcodealong/fineweb_bytelevel",
help="Output directory for tokenized .bin files")
parser.add_argument("--seq_len", type=int, default=2048,
help="Max sequence length (including BOS/EOS)")
parser.add_argument("--max_samples", type=int, default=0,
help="Max samples per file (0=all, local mode only)")
parser.add_argument("--max_files", type=int, default=0,
help="Max number of parquet files to process (0=all, local mode only)")
parser.add_argument("--num_shards", type=int, default=50,
help="Number of output shards (HuggingFace mode)")
parser.add_argument("--samples_per_shard", type=int, default=50000,
help="Approx samples per shard (HuggingFace mode)")
parser.add_argument("--from_hf", action="store_true",
help="Stream from HuggingFace instead of local parquet files")
args = parser.parse_args()
if args.from_hf or not args.input_dir:
stream_from_huggingface(args.output_dir, args.seq_len, args.num_shards, args.samples_per_shard)
return
os.makedirs(args.output_dir, exist_ok=True)
parquet_files = sorted(glob.glob(os.path.join(args.input_dir, "*.parquet")))
if args.max_files > 0:
parquet_files = parquet_files[:args.max_files]
print(f"Found {len(parquet_files)} parquet files")
print(f"Output: {args.output_dir}")
total_tokens = 0
total_samples = 0
for pq_file in parquet_files:
n_tokens, n_samples = process_parquet(
pq_file, args.output_dir, args.seq_len, args.max_samples
)
total_tokens += n_tokens
total_samples += n_samples
metadata = {
"input_dir": args.input_dir,
"seq_len": args.seq_len,
"vocab_size": 272,
"dtype": "uint16",
"total_samples": total_samples,
"total_tokens": total_tokens,
"token_format": "BOS + UTF-8 bytes + EOS (byte-level, 272 vocab)",
}
with open(os.path.join(args.output_dir, "metadata.json"), 'w') as f:
json.dump(metadata, f, indent=2)
print(f"\nDone! Total: {total_samples:,} samples, {total_tokens:,} tokens")
print(f"Metadata saved to {args.output_dir}/metadata.json")
if __name__ == "__main__":
main()
|