"""Parallel re-implementation of data_io/tokenizer (Rust) with INTRA-file parallelism, producing byte-identical outputs. The Rust tool parallelizes only across files, so one 16.9GB parquet becomes a multi-hour single-threaded critical path. Here, each worker process streams a file in row batches and uses tokenizers' rayon-parallel encode_batch_fast, so even a single giant file uses RAYON_NUM_THREADS cores. Output per source file (identical to Rust): //{tokens.npy(u32), inst_start,inst_len,resp_start,resp_len (u64), metadata.json} Row stream per row: [BOQ, cond_ids..., inst_ids..., EOQ, resp_ids..., EOA] Skip logic (metadata.json source_mtime/source_size) is compatible both ways. Usage: python py_tokenize.py DIR [DIR...] --tokenizer-path X.json -o OUT \ [--workers 8] [--rayon-threads 16] [--batch-rows 32768] """ import argparse import json import os import sys import time from itertools import chain from multiprocessing import get_context from pathlib import Path import numpy as np BOQ, EOQ, EOA = "<|im_start|>", "<|im_end|>", "<|box_end|>" CONDITIONS = {"direct": "<|object_ref_start|>", "cot": "<|object_ref_end|>", "noisy": "<|quad_start|>", "synth": "<|quad_end|>"} def scan_inputs(dirs): files = [] for d in dirs: d = Path(d) for p in sorted(d.rglob("*")): if p.is_file() and p.suffix in (".parquet", ".jsonl"): files.append((p, str(p.relative_to(d)).replace("/", "__").replace("\\", "__"))) return files def should_process(input_path: Path, out_subdir: Path) -> bool: meta = out_subdir / "metadata.json" if not meta.exists(): return True try: cached = json.loads(meta.read_text()) st = input_path.stat() return cached.get("source_size") != st.st_size or cached.get("source_mtime") != int(st.st_mtime) except Exception: return True def iter_row_batches(path: Path, batch_rows: int): """Yield (conditions, instructions, responses) lists preserving row order.""" if path.suffix == ".parquet": import pyarrow.parquet as pq pf = pq.ParquetFile(path) for rb in pf.iter_batches(batch_size=batch_rows, columns=["condition", "instruction", "response"]): yield (rb.column("condition").to_pylist(), rb.column("instruction").to_pylist(), rb.column("response").to_pylist()) else: conds, insts, resps = [], [], [] with open(path, "rb") as f: for line in f: if not line.strip(): continue row = json.loads(line) conds.append(row["condition"]); insts.append(row["instruction"]); resps.append(row["response"]) if len(conds) >= batch_rows: yield conds, insts, resps conds, insts, resps = [], [], [] if conds: yield conds, insts, resps def process_file(tok, input_path: Path, out_subdir: Path, batch_rows: int): boq = tok.token_to_id(BOQ); eoq = tok.token_to_id(EOQ); eoa = tok.token_to_id(EOA) cond_tok_ids = {k: tok.token_to_id(v) for k, v in CONDITIONS.items()} assert None not in (boq, eoq, eoa) and None not in cond_tok_ids.values() prefix_cache = {} # raw condition string -> tuple of ids (BOQ + condition ids) token_chunks, il_chunks, rl_chunks = [], [], [] n_rows = 0 for conds, insts, resps in iter_row_batches(input_path, batch_rows): n = len(conds) ie = tok.encode_batch_fast(insts, add_special_tokens=False) re_ = tok.encode_batch_fast(resps, add_special_tokens=False) prefixes = [] for c in conds: p = prefix_cache.get(c) if p is None: p = prefix_cache[c] = (boq,) + tuple(cond_tok_ids[x] for x in c.split(",")) prefixes.append(p) p_lens = np.fromiter((len(p) for p in prefixes), np.int64, n) i_core = np.fromiter((len(e.ids) for e in ie), np.int64, n) r_core = np.fromiter((len(e.ids) for e in re_), np.int64, n) inst_lens = p_lens + i_core + 1 # + EOQ resp_lens = r_core + 1 # + EOA total = int((inst_lens + resp_lens).sum()) def gen(): for j in range(n): yield prefixes[j]; yield ie[j].ids; yield (eoq,) yield re_[j].ids; yield (eoa,) flat = np.fromiter(chain.from_iterable(gen()), np.uint32, total) token_chunks.append(flat) il_chunks.append(inst_lens) rl_chunks.append(resp_lens) n_rows += n tokens = np.concatenate(token_chunks) if token_chunks else np.empty(0, np.uint32) del token_chunks inst_len = np.concatenate(il_chunks) if il_chunks else np.empty(0, np.int64) resp_len = np.concatenate(rl_chunks) if rl_chunks else np.empty(0, np.int64) row_tot = inst_len + resp_len row_start = np.concatenate(([0], np.cumsum(row_tot)[:-1])) if n_rows else np.empty(0, np.int64) inst_start = row_start resp_start = row_start + inst_len out_subdir.mkdir(parents=True, exist_ok=True) np.save(out_subdir / "tokens.npy", tokens) np.save(out_subdir / "inst_start.npy", inst_start.astype(np.uint64)) np.save(out_subdir / "inst_len.npy", inst_len.astype(np.uint64)) np.save(out_subdir / "resp_start.npy", resp_start.astype(np.uint64)) np.save(out_subdir / "resp_len.npy", resp_len.astype(np.uint64)) st = input_path.stat() (out_subdir / "metadata.json").write_text( json.dumps({"source_mtime": int(st.st_mtime), "source_size": st.st_size})) return n_rows, len(tokens) def worker(wid, queue, args): os.environ["TOKENIZERS_PARALLELISM"] = "true" os.environ["RAYON_NUM_THREADS"] = str(args.rayon_threads) from tokenizers import Tokenizer tok = Tokenizer.from_file(args.tokenizer_path) tok.encode_special_tokens = True while True: item = queue.get() if item is None: return path, safe_name = item out_subdir = Path(args.output_dir) / safe_name t0 = time.time() try: n_rows, n_tok = process_file(tok, Path(path), out_subdir, args.batch_rows) print(f"[w{wid}] {safe_name}: {n_rows:,} rows, {n_tok:,} tokens, {time.time()-t0:.0f}s", flush=True) except Exception as e: print(f"[w{wid}] FAILED {safe_name}: {e!r}", flush=True) def main(): ap = argparse.ArgumentParser() ap.add_argument("dirs", nargs="+") ap.add_argument("-o", "--output-dir", required=True) ap.add_argument("-t", "--tokenizer-path", required=True) ap.add_argument("--workers", type=int, default=8) ap.add_argument("--rayon-threads", type=int, default=16) ap.add_argument("--batch-rows", type=int, default=32768) args = ap.parse_args() out = Path(args.output_dir) out.mkdir(parents=True, exist_ok=True) # tokenizer_info.json — same content as the Rust tool os.environ["TOKENIZERS_PARALLELISM"] = "false" from tokenizers import Tokenizer tok = Tokenizer.from_file(args.tokenizer_path) (out / "tokenizer_info.json").write_text(json.dumps({ "tokenizer_path": args.tokenizer_path, "boq": BOQ, "eoq": EOQ, "eoa": EOA, "condition_mapping": CONDITIONS, "vocab_size": tok.get_vocab_size(True), })) del tok files = scan_inputs(args.dirs) pending = [(p, s) for p, s in files if should_process(p, out / s)] # LPT: largest first pending.sort(key=lambda x: -x[0].stat().st_size) print(f"{len(files)} files found, {len(pending)} to process, " f"{args.workers} workers x {args.rayon_threads} rayon threads", flush=True) ctx = get_context("spawn") queue = ctx.Queue() for p, s in pending: queue.put((str(p), s)) for _ in range(args.workers): queue.put(None) procs = [ctx.Process(target=worker, args=(i, queue, args)) for i in range(args.workers)] for p in procs: p.start() for p in procs: p.join() failed = any(p.exitcode != 0 for p in procs) print("PY_TOKENIZE_DONE" if not failed else "PY_TOKENIZE_WORKER_CRASH", flush=True) sys.exit(1 if failed else 0) if __name__ == "__main__": main()