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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Tokenize FineWeb-Edu parquet files to byte-level .bin format.
|
| 3 |
+
|
| 4 |
+
Spider-FLEXITOKENS uses byte-level vocab (272 tokens: 256 bytes + 16 specials).
|
| 5 |
+
This script converts raw text parquet files to uint16 .bin files ready for
|
| 6 |
+
fast loading by ByteLevelTokenizedDataset.
|
| 7 |
+
|
| 8 |
+
Output format:
|
| 9 |
+
- tokens.uint16: concatenated byte values (0-255) + special tokens (256-271)
|
| 10 |
+
- metadata.json: {num_tokens, num_samples, seq_len, etc.}
|
| 11 |
+
"""
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import json
|
| 15 |
+
import glob
|
| 16 |
+
import argparse
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pyarrow.parquet as pq
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
|
| 23 |
+
# Sentinel tokens
|
| 24 |
+
BOS_ID = 257
|
| 25 |
+
EOS_ID = 258
|
| 26 |
+
PAD_ID = 256
|
| 27 |
+
|
| 28 |
+
def tokenize_text(text: str, max_bytes: int = 2048) -> list:
|
| 29 |
+
"""Convert text to byte-level token sequence with BOS/EOS."""
|
| 30 |
+
byte_ids = list(text.encode('utf-8'))[:max_bytes]
|
| 31 |
+
return [BOS_ID] + byte_ids + [EOS_ID]
|
| 32 |
+
|
| 33 |
+
def process_parquet(parquet_path: str, output_dir: str, seq_len: int = 2048, max_samples: int = 0):
|
| 34 |
+
"""Process a single parquet file to tokenized .bin."""
|
| 35 |
+
print(f"Processing: {parquet_path}")
|
| 36 |
+
output_path = os.path.join(output_dir, os.path.basename(parquet_path).replace('.parquet', '.bin'))
|
| 37 |
+
|
| 38 |
+
tokens = []
|
| 39 |
+
num_samples = 0
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
pf = pq.ParquetFile(parquet_path)
|
| 43 |
+
for batch in tqdm(pf.iter_batches(batch_size=1000, columns=["text"]), desc=os.path.basename(parquet_path)):
|
| 44 |
+
texts = batch["text"].to_pylist()
|
| 45 |
+
for text in texts:
|
| 46 |
+
if not text:
|
| 47 |
+
continue
|
| 48 |
+
token_ids = tokenize_text(text, max_bytes=seq_len - 2) # -2 for BOS/EOS
|
| 49 |
+
tokens.extend(token_ids)
|
| 50 |
+
num_samples += 1
|
| 51 |
+
if max_samples > 0 and num_samples >= max_samples:
|
| 52 |
+
break
|
| 53 |
+
if max_samples > 0 and num_samples >= max_samples:
|
| 54 |
+
break
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"Error processing {parquet_path}: {e}")
|
| 57 |
+
return 0, 0
|
| 58 |
+
|
| 59 |
+
if tokens:
|
| 60 |
+
arr = np.array(tokens, dtype=np.uint16)
|
| 61 |
+
arr.tofile(output_path)
|
| 62 |
+
print(f" Saved: {output_path} ({arr.nbytes / 1024**2:.1f} MB, {len(tokens):,} tokens)")
|
| 63 |
+
return len(tokens), num_samples
|
| 64 |
+
return 0, 0
|
| 65 |
+
|
| 66 |
+
def stream_from_huggingface(output_dir, seq_len=2048, num_shards=50, samples_per_shard=50000):
|
| 67 |
+
"""Stream FineWeb-Edu from HuggingFace and tokenize to .bin shards."""
|
| 68 |
+
from datasets import load_dataset
|
| 69 |
+
from tqdm import tqdm
|
| 70 |
+
|
| 71 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 72 |
+
|
| 73 |
+
print(f"Streaming FineWeb-Edu from HuggingFace (10BT sample)")
|
| 74 |
+
print(f"Output: {output_dir}")
|
| 75 |
+
|
| 76 |
+
ds = load_dataset("HuggingFaceFW/fineweb-edu", "sample/10BT", split="train", streaming=True)
|
| 77 |
+
|
| 78 |
+
total_tokens = 0
|
| 79 |
+
total_samples = 0
|
| 80 |
+
shard_tokens = []
|
| 81 |
+
shard_count = 0
|
| 82 |
+
|
| 83 |
+
for sample in tqdm(ds, desc="Tokenizing"):
|
| 84 |
+
text = sample.get("text", "")
|
| 85 |
+
if not text:
|
| 86 |
+
continue
|
| 87 |
+
token_ids = tokenize_text(text, max_bytes=seq_len - 2)
|
| 88 |
+
shard_tokens.extend(token_ids)
|
| 89 |
+
total_samples += 1
|
| 90 |
+
|
| 91 |
+
if len(shard_tokens) >= samples_per_shard * seq_len:
|
| 92 |
+
shard_count += 1
|
| 93 |
+
arr = np.array(shard_tokens, dtype=np.uint16)
|
| 94 |
+
shard_path = os.path.join(output_dir, f"shard_{shard_count:04d}.bin")
|
| 95 |
+
arr.tofile(shard_path)
|
| 96 |
+
print(f" Shard {shard_count}: {shard_path} ({arr.nbytes / 1024**2:.1f} MB, {len(shard_tokens):,} tokens, {total_samples:,} samples)")
|
| 97 |
+
total_tokens += len(shard_tokens)
|
| 98 |
+
shard_tokens = []
|
| 99 |
+
|
| 100 |
+
if shard_count >= num_shards:
|
| 101 |
+
break
|
| 102 |
+
|
| 103 |
+
if shard_tokens:
|
| 104 |
+
shard_count += 1
|
| 105 |
+
arr = np.array(shard_tokens, dtype=np.uint16)
|
| 106 |
+
shard_path = os.path.join(output_dir, f"shard_{shard_count:04d}.bin")
|
| 107 |
+
arr.tofile(shard_path)
|
| 108 |
+
print(f" Shard {shard_count}: {shard_path} ({arr.nbytes / 1024**2:.1f} MB, {len(shard_tokens):,} tokens)")
|
| 109 |
+
total_tokens += len(shard_tokens)
|
| 110 |
+
|
| 111 |
+
metadata = {
|
| 112 |
+
"source": "HuggingFaceFW/fineweb-edu sample/10BT",
|
| 113 |
+
"seq_len": seq_len,
|
| 114 |
+
"vocab_size": 272,
|
| 115 |
+
"dtype": "uint16",
|
| 116 |
+
"total_samples": total_samples,
|
| 117 |
+
"total_tokens": total_tokens,
|
| 118 |
+
"num_shards": shard_count,
|
| 119 |
+
"token_format": "BOS + UTF-8 bytes + EOS (byte-level, 272 vocab)",
|
| 120 |
+
}
|
| 121 |
+
with open(os.path.join(output_dir, "metadata.json"), 'w') as f:
|
| 122 |
+
json.dump(metadata, f, indent=2)
|
| 123 |
+
|
| 124 |
+
print(f"\nDone! Total: {total_samples:,} samples, {total_tokens:,} tokens, {shard_count} shards")
|
| 125 |
+
print(f"Metadata saved to {output_dir}/metadata.json")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def main():
|
| 129 |
+
parser = argparse.ArgumentParser()
|
| 130 |
+
parser.add_argument("--input_dir", type=str, default="",
|
| 131 |
+
help="Input directory with parquet files (local mode)")
|
| 132 |
+
parser.add_argument("--output_dir", type=str, default="/home/lamcodealong/fineweb_bytelevel",
|
| 133 |
+
help="Output directory for tokenized .bin files")
|
| 134 |
+
parser.add_argument("--seq_len", type=int, default=2048,
|
| 135 |
+
help="Max sequence length (including BOS/EOS)")
|
| 136 |
+
parser.add_argument("--max_samples", type=int, default=0,
|
| 137 |
+
help="Max samples per file (0=all, local mode only)")
|
| 138 |
+
parser.add_argument("--max_files", type=int, default=0,
|
| 139 |
+
help="Max number of parquet files to process (0=all, local mode only)")
|
| 140 |
+
parser.add_argument("--num_shards", type=int, default=50,
|
| 141 |
+
help="Number of output shards (HuggingFace mode)")
|
| 142 |
+
parser.add_argument("--samples_per_shard", type=int, default=50000,
|
| 143 |
+
help="Approx samples per shard (HuggingFace mode)")
|
| 144 |
+
parser.add_argument("--from_hf", action="store_true",
|
| 145 |
+
help="Stream from HuggingFace instead of local parquet files")
|
| 146 |
+
args = parser.parse_args()
|
| 147 |
+
|
| 148 |
+
if args.from_hf or not args.input_dir:
|
| 149 |
+
stream_from_huggingface(args.output_dir, args.seq_len, args.num_shards, args.samples_per_shard)
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 153 |
+
|
| 154 |
+
parquet_files = sorted(glob.glob(os.path.join(args.input_dir, "*.parquet")))
|
| 155 |
+
if args.max_files > 0:
|
| 156 |
+
parquet_files = parquet_files[:args.max_files]
|
| 157 |
+
|
| 158 |
+
print(f"Found {len(parquet_files)} parquet files")
|
| 159 |
+
print(f"Output: {args.output_dir}")
|
| 160 |
+
|
| 161 |
+
total_tokens = 0
|
| 162 |
+
total_samples = 0
|
| 163 |
+
|
| 164 |
+
for pq_file in parquet_files:
|
| 165 |
+
n_tokens, n_samples = process_parquet(
|
| 166 |
+
pq_file, args.output_dir, args.seq_len, args.max_samples
|
| 167 |
+
)
|
| 168 |
+
total_tokens += n_tokens
|
| 169 |
+
total_samples += n_samples
|
| 170 |
+
|
| 171 |
+
metadata = {
|
| 172 |
+
"input_dir": args.input_dir,
|
| 173 |
+
"seq_len": args.seq_len,
|
| 174 |
+
"vocab_size": 272,
|
| 175 |
+
"dtype": "uint16",
|
| 176 |
+
"total_samples": total_samples,
|
| 177 |
+
"total_tokens": total_tokens,
|
| 178 |
+
"token_format": "BOS + UTF-8 bytes + EOS (byte-level, 272 vocab)",
|
| 179 |
+
}
|
| 180 |
+
with open(os.path.join(args.output_dir, "metadata.json"), 'w') as f:
|
| 181 |
+
json.dump(metadata, f, indent=2)
|
| 182 |
+
|
| 183 |
+
print(f"\nDone! Total: {total_samples:,} samples, {total_tokens:,} tokens")
|
| 184 |
+
print(f"Metadata saved to {args.output_dir}/metadata.json")
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
main()
|