Datasets:
Download tokenize_fineweb.py from CLIWorks/Spider-FLEXITOKENS-FP8: direct link, hf CLI and curl.
- Browser
- Download file 7.19 kB
-
https://huggingface.co/datasets/CLIWorks/Spider-FLEXITOKENS-FP8/resolve/245020bbdb83d9594903680ef56b1a94e9de1769/tokenize_fineweb.py
- Command line
-
hf download hf://datasets/CLIWorks/Spider-FLEXITOKENS-FP8@245020bbdb83d9594903680ef56b1a94e9de1769/tokenize_fineweb.py
-
curl -L -o tokenize_fineweb.py https://huggingface.co/datasets/CLIWorks/Spider-FLEXITOKENS-FP8/resolve/245020bbdb83d9594903680ef56b1a94e9de1769/tokenize_fineweb.py
7.19 kB
| #!/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() | |