VertexAIco's picture
Archive copy: build_scripts/assemble.py
b90dbca verified
Raw History Blame Contribute Delete
6.23 kB
#!/usr/bin/env python3
"""Stage 3: build the final Medium (25,000) and Large (65,000) files.
* per stream: the first N VALID rows by plan rank -> Large; the first M of those -> Medium (so Medium is nested in Large)
* Small's 15,000 rows come straight from its raw file (unchanged) and sit in every tier; Small's own validation rows stay validation
* new rows are validation with probability 8% by id hash (same share as Small); everything else is train
* rows are sharded by id hash, then each shard is shuffled so every shard mixes all sources
Outputs (plain JSONL, {"messages": [...]} per line, like Small): out/<tier>/train-0000i-of-0000N.jsonl, valid.jsonl, row_index.csv, stats.json"""
import csv, gzip, hashlib, json, os, random, re, shutil, sys, time, collections
import huggingface_hub as hf
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import *
t0 = time.time()
plan = json.load(open(os.path.join(SCRATCH, "plan.json")))
small = json.load(open(os.path.join(HERE, "..", "scan", "small_ids.json")))
small_valid = set(small["valid_ids"])
head = re.compile(r'^\{"rk": (\d+), "id": "((?:[^"\\]|\\.)*)"')
STAGE = os.path.join(SCRATCH, "stage"); shutil.rmtree(STAGE, ignore_errors=True); os.makedirs(STAGE)
shutil.rmtree(OUTDIR, ignore_errors=True)
# ---- pass 1: which new rows does each tier take? ---------------------------------------------------------------------------------
sel = {} # id -> (stream, in_medium)
for stream, s in plan["streams"].items():
fn = os.path.join(SCRATCH, "rows_" + stream.replace("/", "_").replace(":", "_") + ".jsonl.gz")
ranks = []
with gzip.open(fn, "rt", encoding="utf-8") as f:
for line in f:
m = head.match(line[:300]); ranks.append((int(m.group(1)), json.loads('"' + m.group(2) + '"')))
ranks.sort()
assert len(ranks) >= s["new_large"], (stream, len(ranks), s["new_large"])
for i, (_, rid) in enumerate(ranks[: s["new_large"]]):
assert rid not in sel
sel[rid] = (stream, i < s["new_medium"])
print(f"selected {len(sel)} new rows (medium-new {sum(1 for v in sel.values() if v[1])}) {time.time()-t0:.0f}s", flush=True)
# ---- writers ---------------------------------------------------------------------------------------------------------------------
W, INDEX = {}, {"medium": [], "large": []}
def w(tier, name):
k = (tier, name)
if k not in W:
os.makedirs(os.path.join(STAGE, tier), exist_ok=True)
W[k] = gzip.open(os.path.join(STAGE, tier, name + ".jsonl.gz"), "wt", encoding="utf-8", compresslevel=3)
return W[k]
def emit(rid, source_key, msgs, valid, in_small, in_medium):
line = json.dumps({"messages": msgs}, ensure_ascii=False) + "\n"
for tier in (("medium", "large") if in_medium else ("large",)):
name = "valid" if valid else f"train_{shard_of(rid, N_TRAIN_SHARDS[tier])}"
w(tier, name).write(line)
INDEX[tier].append((rid, source_key, "valid" if valid else "train", int(in_small)))
# ---- pass 2a: Small's rows, untouched ---------------------------------------------------------------------------------------------
rp = hf.hf_hub_download("VertexAGI/cyberdata-1", "raw_examples.jsonl", repo_type="dataset")
n_small = 0
for line in open(rp, encoding="utf-8"):
r = json.loads(line)
emit(r["id"], SRC_KEY[r["source"]], r["messages"], r["id"] in small_valid, True, True)
n_small += 1
for p in {rp, os.path.realpath(rp)}:
try: os.remove(p)
except OSError: pass
assert n_small == 15000
print(f"small rows written {n_small} {time.time()-t0:.0f}s", flush=True)
# ---- pass 2b: the new rows --------------------------------------------------------------------------------------------------------
seen = collections.Counter()
for stream in plan["streams"]:
fn = os.path.join(SCRATCH, "rows_" + stream.replace("/", "_").replace(":", "_") + ".jsonl.gz")
with gzip.open(fn, "rt", encoding="utf-8") as f:
for line in f:
m = head.match(line[:300]); rid = json.loads('"' + m.group(2) + '"')
if rid not in sel or seen[rid]: continue
seen[rid] = 1
r = json.loads(line)
emit(rid, SRC_KEY[r["source"]], r["messages"], is_valid_new(rid), False, sel[rid][1])
assert len(seen) == len(sel), (len(seen), len(sel))
for h in W.values(): h.close()
print(f"new rows written {len(seen)} {time.time()-t0:.0f}s", flush=True)
# ---- pass 3: shuffle each shard, write plain files + index + stats ------------------------------------------------------------------
stats = {}
for tier in ("medium", "large"):
od = os.path.join(OUTDIR, tier); os.makedirs(od)
nshard = N_TRAIN_SHARDS[tier]; total = {"train": 0, "valid": 0}; bytes_ = 0
for k in list(range(nshard)) + ["valid"]:
name = "valid" if k == "valid" else f"train_{k}"
with gzip.open(os.path.join(STAGE, tier, name + ".jsonl.gz"), "rt", encoding="utf-8") as f:
lines = f.readlines()
random.Random(f"{SALT}{tier}:{name}").shuffle(lines)
out = os.path.join(od, "valid.jsonl" if k == "valid" else f"train-{k:05d}-of-{nshard:05d}.jsonl")
with open(out, "w", encoding="utf-8") as g: g.writelines(lines)
total["valid" if k == "valid" else "train"] += len(lines); bytes_ += os.path.getsize(out)
os.remove(os.path.join(STAGE, tier, name + ".jsonl.gz"))
with open(os.path.join(od, "row_index.csv"), "w", newline="") as f:
cw = csv.writer(f); cw.writerow(["id", "source", "split", "in_small"]); cw.writerows(sorted(INDEX[tier]))
by_src = collections.Counter(r[1] for r in INDEX[tier]); by_split = collections.Counter((r[1], r[2]) for r in INDEX[tier])
stats[tier] = {"rows": len(INDEX[tier]), "train": total["train"], "valid": total["valid"], "bytes": bytes_, "by_source": dict(by_src),
"by_source_split": {f"{a}/{b}": v for (a, b), v in by_split.items()}, "unique_ids": len({r[0] for r in INDEX[tier]})}
print(tier, {k: v for k, v in stats[tier].items() if k not in ("by_source_split",)}, flush=True)
json.dump(stats[tier], open(os.path.join(od, "stats.json"), "w"), indent=1)
shutil.rmtree(STAGE, ignore_errors=True)
print("ASSEMBLE_DONE", f"{time.time()-t0:.0f}s")