og2_small / scripts /og2subset.py
AutomatedScientist's picture
Add files using upload-large-folder tool
6f32cc3 verified
Raw History Blame Contribute Delete
19.7 kB
"""Build a small subset of OpenGenome2 (the Evo 2 training data) with the full dataset's variety.
Standalone: needs only numpy, requests and huggingface_hub (see requirements.txt).
Deterministic: the output depends only on (--revision, --seed, --rate or target, --window, --holdout, --rule):
each shard's generator is seeded by blake2b(seed, shard path) and each record's by (that, record index), so
worker count and completion order do not matter; held-out species are a seed-independent hash of the species
name; the source is pinned to an OpenGenome2 Hub commit (REVISION) and every plan/.done file records it.
python og2subset.py sample --split train --target-tokens 10e9 --holdout 0.01 [--workers 14] [--window 16384]
python og2subset.py sample --split valid --target-tokens 100e6
python og2subset.py finalize --split train [--target-tokens N] # keep all, or trim to N tokens
python og2subset.py finalize --split heldout
python og2subset.py report --split train
How a window is chosen (`sample`)
Every json/<phase>/<subset>/*_<split>_*.jsonl.gz shard of arcinstitute/opengenome2 is streamed over HTTP and
decompressed in memory; nothing but the sample is written, so the 2.8 TB of JSONL never touches the disk. Each
record's "text" is cut into segments at phylogenetic tags (|D__...;S__...|), contig separators (#) and window
separators (@); a segment is tiled into windows of --window bases on a fixed grid (the last one shorter), and a
window is kept iff u < rate, u ~ U(0, 1) from a generator seeded by (seed, shard, record index), whatever its
length. So every base has the same inclusion probability `rate` (short sequences such as promoters and ncRNA
included): the sample reproduces the composition of the full dataset (subsets, taxa, GC, repeats) in expectation,
and the same seed gives the same sample.
rate = target * oversample / (compressed bytes * tokens per byte). OpenGenome2's train JSONL holds ~9.24T
characters in 2.787 TB of gzip, i.e. ~3.32 tokens per compressed byte (the default).
Held-out species (`--holdout h`)
Records whose species (tag S__) hashes (blake2b, independent of the seed) below h go to <out>/heldout instead of
<out>/train, at the same rate; untagged records (metagenomes, transcripts, ...) are held out record by record. All
records of a species go the same way across shards and subsets, so heldout shares no species with train.
Output, per source shard: <out>/<split>/<subset>/<shard>.npy (uint8 codes of the kept windows, concatenated),
<shard>.jsonl (one line per window: offset, len, u, tag, rec) and <shard>.done (stats; makes `sample` resumable).
`finalize` writes <out>/<split>/selected.json (kept window ids per shard) and manifest.json (composition).
Encoding: one uint8 per base, low 3 bits A=0 C=1 G=2 T=3 N/other=4, bit 7 (0x80) set for lowercase (soft-masked).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
import time
import zlib
from collections import Counter, defaultdict
from collections.abc import Iterator
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
import numpy as np
HF_REPO = "arcinstitute/opengenome2"
# Pinned OpenGenome2 revision (Hub commit, last modified 2026-09-02) that this dataset was built from.
REVISION = "84d2a7e690c8bb395d1f4868822dfa031ea561c6"
BASE = f"https://huggingface.co/datasets/{HF_REPO}/resolve/"
TAG = re.compile(r"\|[^|]*\|")
SPLIT = re.compile(r"[#@]+")
TOKENS_PER_BYTE = 3.316 # measured: 9.242T characters in 2.787 TB of train JSONL gzip
# ---------------------------------------------------------------- encoding (same as acgt.data.tokenize)
N_ID, LOWER_BIT, BASE_MASK = 4, 0x80, 0x07
ENC = np.full(256, N_ID, dtype=np.uint8)
for _i, _c in enumerate(b"ACGT"):
ENC[_c] = _i
ENC[_c + 32] = _i | LOWER_BIT
for _c in range(ord("a"), ord("z") + 1):
if ENC[_c] == N_ID:
ENC[_c] = N_ID | LOWER_BIT
def encode(seq: str) -> np.ndarray:
return ENC[np.frombuffer(seq.encode(), dtype=np.uint8)]
def decode(arr: np.ndarray) -> str:
up, low = np.frombuffer(b"ACGTN", dtype=np.uint8), np.frombuffer(b"acgtn", dtype=np.uint8)
b = arr & BASE_MASK
return np.where((arr & LOWER_BIT) != 0, low[b], up[b]).astype(np.uint8).tobytes().decode()
# ---------------------------------------------------------------- records -> windows
@dataclass
class Window:
seq: str
u: float
tag: str
def shard_seed(seed: int, shard: str) -> int:
return int.from_bytes(hashlib.blake2b(f"{seed}:{shard}".encode(), digest_size=8).digest(), "little")
def record_tag(text: str) -> str:
"""The first taxonomy tag of a record ('' if untagged); it also labels the sequence before that tag."""
m = TAG.search(text)
return m.group(0)[1:-1] if m else ""
def species_of(tag: str) -> str:
m = re.search(r"S__([^;|]*)", tag)
return m.group(1) if m else ""
def unit_hash(key: str) -> float:
"""Deterministic U(0, 1) from a string (blake2b), independent of the sampling seed."""
return int.from_bytes(hashlib.blake2b(key.encode(), digest_size=8).digest(), "little") / 2**64
def holdout_key(text: str, shard: str, rec_idx: int) -> str:
"""Held-out unit of a record: its species when tagged, else the record itself."""
sp = species_of(record_tag(text))
return f"S:{sp}" if sp else f"R:{shard}:{rec_idx}"
def segments(text: str, tag: str = "") -> Iterator[tuple[str, str]]:
"""(sequence segment, taxonomy tag in force) pairs: tags and #/@ separators are boundaries, never content.
`tag` labels the sequence before the first tag."""
pos = 0
for m in TAG.finditer(text):
yield from ((s, tag) for s in SPLIT.split(text[pos:m.start()]) if s)
tag = m.group(0)[1:-1]
pos = m.end()
yield from ((s, tag) for s in SPLIT.split(text[pos:]) if s)
def sample_record(text: str, rng: np.random.Generator, rate: float, window: int,
rule: str = "per_base") -> list[Window]:
"""Windows of one record, each kept with probability `rate` whatever its length: every base has inclusion
probability `rate`. (Keeping a window with probability rate * len / window would under-sample short sequences
by len / window; that rule is kept as rule="length_weighted" only to reproduce data sampled with it.)"""
if rule not in ("per_base", "length_weighted"):
raise ValueError(f"unknown rule {rule!r}")
out = []
for seg, tag in segments(text, record_tag(text)):
n = len(seg)
starts = range(0, n, window)
u = rng.random(len(starts))
for k, s in enumerate(starts):
L = min(window, n - s)
if u[k] < (rate if rule == "per_base" else rate * L / window):
out.append(Window(seg[s:s + L], float(u[k]), tag))
return out
# ---------------------------------------------------------------- streaming
def iter_lines(chunks: Iterator[bytes]) -> Iterator[bytes]:
"""Lines of a gzip stream given as byte chunks; one split per chunk (records range from 100 b to ~20 Mb)."""
dec = zlib.decompressobj(16 + zlib.MAX_WBITS)
parts: list[bytes] = []
for chunk in chunks:
data = dec.decompress(chunk)
if not data:
continue
pieces = data.split(b"\n")
if len(pieces) == 1:
parts.append(data)
continue
parts.append(pieces[0])
yield b"".join(parts)
yield from pieces[1:-1]
parts = [pieces[-1]] if pieces[-1] else []
tail = dec.flush()
if tail:
parts.append(tail)
if parts and b"".join(parts).strip():
yield b"".join(parts)
def http_chunks(path: str, revision: str = REVISION, chunk_size: int = 1 << 20) -> Iterator[bytes]:
import requests
with requests.get(f"{BASE}{revision}/{path}", stream=True, timeout=120) as r:
r.raise_for_status()
yield from r.iter_content(chunk_size=chunk_size)
def file_chunks(path: Path, chunk_size: int = 1 << 20) -> Iterator[bytes]:
with open(path, "rb") as f:
while chunk := f.read(chunk_size):
yield chunk
def shard_out(out_dir: Path, split: str, shard: str) -> Path:
"""<out>/<split>/<subset>/<shard file stem>; the subset is the directory under json/<phase>/."""
parts = shard.split("/")
subset = parts[2] if len(parts) > 3 else "misc"
return out_dir / split / subset / Path(parts[-1]).name.removesuffix(".jsonl.gz")
class _Writer:
def __init__(self) -> None:
self.codes: list[np.ndarray] = []
self.index: list[dict] = []
self.offset = self.records = self.chars = 0
def add(self, w: Window, rec_idx: int) -> None:
self.codes.append(encode(w.seq))
self.index.append({"offset": self.offset, "len": len(w.seq), "u": round(w.u, 9), "tag": w.tag, "rec": rec_idx})
self.offset += len(w.seq)
def save(self, base: Path, stats: dict) -> dict:
base.parent.mkdir(parents=True, exist_ok=True)
arr = np.concatenate(self.codes) if self.codes else np.zeros(0, dtype=np.uint8)
np.save(base.with_suffix(".npy"), arr)
base.with_suffix(".jsonl").write_text("".join(json.dumps(r) + "\n" for r in self.index))
stats = {**stats, "records": self.records, "chars_seen": self.chars, "kept_windows": len(self.index),
"kept_bases": int(self.offset)}
base.with_suffix(".done").write_text(json.dumps(stats))
return stats
def sample_shard(shard: str, out_dir: Path, split: str, rate: float, window: int, seed: int,
chunks: Iterator[bytes] | None = None, holdout: float = 0.0, holdout_split: str = "heldout",
rule: str = "per_base", revision: str = REVISION) -> dict:
"""Stream one shard and write its kept windows (and held-out records'). Returns stats; skips shards done."""
base = shard_out(out_dir, split, shard)
done = base.with_suffix(".done")
if done.exists():
return json.loads(done.read_text())
t0 = time.time()
root = shard_seed(seed, shard)
main, held = _Writer(), _Writer()
for rec_idx, line in enumerate(iter_lines(chunks if chunks is not None else http_chunks(shard, revision))):
text = json.loads(line)["text"]
wr = held if holdout > 0 and unit_hash(holdout_key(text, shard, rec_idx)) < holdout else main
wr.records += 1
wr.chars += len(text) # incl. tag characters; an upper bound on bases
rng = np.random.default_rng([root, rec_idx])
for w in sample_record(text, rng, rate, window, rule):
wr.add(w, rec_idx)
common = {"shard": shard, "rate": rate, "window": window, "seed": seed, "holdout": holdout, "rule": rule,
"revision": revision}
if holdout > 0:
held.save(shard_out(out_dir, holdout_split, shard), {**common, "split": holdout_split})
return main.save(base, {**common, "split": split, "seconds": round(time.time() - t0, 1)})
# ---------------------------------------------------------------- CLI
def list_shards(split: str, subsets: list[str] | None, revision: str = REVISION) -> list[tuple[str, int]]:
from huggingface_hub import HfApi
out = []
for f in HfApi().list_repo_tree(HF_REPO, repo_type="dataset", recursive=True, revision=revision):
p, size = f.path, getattr(f, "size", None)
if size is None or not p.startswith("json/") or not p.endswith(".jsonl.gz"):
continue
if not re.search(rf"[_/]{split}[_.]", p.rsplit("/", 1)[-1]):
continue
if subsets and p.split("/")[2] not in subsets:
continue
out.append((p, int(size)))
return sorted(out, key=lambda x: -x[1])
def run_one(shard: str, out: str, split: str, rate: float, window: int, seed: int, holdout: float, rule: str,
revision: str, retries: int = 4) -> dict:
for attempt in range(retries):
try:
return sample_shard(shard, Path(out), split, rate, window, seed, holdout=holdout, rule=rule,
revision=revision)
except Exception as e: # noqa: BLE001 network hiccup mid-stream (any error): start the shard again
if attempt == retries - 1:
return {"shard": shard, "error": repr(e)}
time.sleep(10 * (attempt + 1))
raise AssertionError
def cmd_sample(a) -> None:
shards = list_shards(a.split, a.subsets, a.revision)
if a.limit:
shards = shards[-a.limit:]
total_bytes = sum(s for _, s in shards)
target = a.target_tokens or 10e9
rate = a.rate if a.rate else min(1.0, target * a.oversample / (total_bytes * a.tokens_per_byte))
root = Path(a.out)
root.mkdir(parents=True, exist_ok=True)
plan = {"split": a.split, "target_tokens": target, "oversample": a.oversample, "rate": rate, "window": a.window,
"seed": a.seed, "holdout": a.holdout, "shards": len(shards), "compressed_bytes": total_bytes,
"tokens_per_byte_assumed": a.tokens_per_byte}
plan |= {"rule": a.rule, "subsets": a.subsets or "all", "revision": a.revision, "source": HF_REPO}
(root / (a.plan or f"plan_{a.split}.json")).write_text(json.dumps(plan, indent=1))
print(json.dumps(plan), flush=True)
t0, done_bytes, kept = time.time(), 0, 0
sizes = dict(shards)
with ProcessPoolExecutor(a.workers) as ex:
futs = [ex.submit(run_one, p, a.out, a.split, rate, a.window, a.seed, a.holdout, a.rule, a.revision) for p, _ in shards]
for i, fut in enumerate(as_completed(futs), 1):
st = fut.result()
done_bytes += sizes[st["shard"]]
kept += st.get("kept_bases", 0)
el = time.time() - t0
print(f"[{i}/{len(shards)}] {done_bytes / 1e9:.0f}/{total_bytes / 1e9:.0f} GB kept {kept / 1e9:.3f}B "
f"{el / 3600:.2f} h {st['shard'].rsplit('/', 1)[-1]}" + (f" ERROR {st['error']}" if "error" in st else ""),
flush=True)
def load_index(root: Path, split: str) -> list[tuple[Path, list[dict], dict]]:
out = []
for done in sorted((root / split).glob("*/*.done")):
rows = [json.loads(line) for line in done.with_suffix(".jsonl").read_text().splitlines()]
out.append((done.with_suffix(""), rows, json.loads(done.read_text())))
return out
def cmd_finalize(a) -> None:
root = Path(a.out)
idx = load_index(root, a.split)
kept = sum(r["len"] for _, rows, _ in idx for r in rows)
rate, window = idx[0][2]["rate"], idx[0][2]["window"]
final_rate = rate * (min(1.0, a.target_tokens / kept) if a.target_tokens and kept else 1.0)
selected, total = {}, 0
for base, rows, _ in idx:
ids = [i for i, r in enumerate(rows) if r["u"] < final_rate]
selected[str(base.relative_to(root))] = ids
total += sum(rows[i]["len"] for i in ids)
(root / a.split / "selected.json").write_text(json.dumps({"rate": final_rate, "window": window, "tokens": total,
"shards": selected}))
print(f"{a.split}: kept {kept / 1e9:.3f}B -> selected {total / 1e9:.3f}B tokens (rate {final_rate:.3e})")
cmd_report(a)
def taxon(tag: str, rank: str) -> str:
m = re.search(rf"{rank}__([^;|]*)", tag)
return m.group(1) if m else "(untagged)"
def cmd_report(a) -> None:
root = Path(a.out)
idx = load_index(root, a.split)
sel_path = root / a.split / "selected.json"
sel = json.loads(sel_path.read_text())["shards"] if sel_path.exists() else None
by_subset, by_domain, by_phylum, windows = Counter(), Counter(), Counter(), Counter()
species: dict[str, set] = defaultdict(set)
seen_chars, records = Counter(), Counter()
for base, rows, st in idx:
subset = base.parent.name
seen_chars[subset] += st["chars_seen"]
records[subset] += st["records"]
ids = sel[str(base.relative_to(root))] if sel is not None else range(len(rows))
for i in ids:
r = rows[i]
by_subset[subset] += r["len"]
windows[subset] += 1
by_domain[taxon(r["tag"], "D")] += r["len"]
by_phylum[taxon(r["tag"], "P")] += r["len"]
if r["tag"]:
species[subset].add(taxon(r["tag"], "S"))
total = sum(by_subset.values())
seen = sum(seen_chars.values())
rep = {"split": a.split, "tokens": total, "windows": sum(windows.values()), "selected": sel is not None,
"subsets": {k: {"tokens": v, "windows": windows[k], "share": v / total, "full_share": seen_chars[k] / seen,
"records_seen": records[k], "chars_seen": seen_chars[k], "species": len(species[k])}
for k, v in by_subset.most_common()},
"domains": {k: v / total for k, v in by_domain.most_common()},
"phyla_top30": {k: v / total for k, v in by_phylum.most_common(30)},
"n_phyla": len(by_phylum), "n_species": len(set().union(*species.values())) if species else 0,
"chars_seen": seen, "records_seen": sum(records.values())}
(root / a.split / "manifest.json").write_text(json.dumps(rep, indent=1))
print(f"{a.split}: {total / 1e9:.3f}B tokens in {rep['windows']} windows, from {seen / 1e12:.3f}T characters "
f"seen; {rep['n_species']} species, {rep['n_phyla']} phyla")
for k, v in rep["subsets"].items():
print(f" {k:<28} {v['tokens'] / 1e9:8.3f}B share {v['share']:.4f} full {v['full_share']:.4f} "
f"species {v['species']}")
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("cmd", choices=["sample", "finalize", "report"])
ap.add_argument("--split", default="train", choices=["train", "valid", "test", "heldout"],
help="sample: the source split to stream; finalize/report: an output split (incl. heldout)")
ap.add_argument("--holdout", type=float, default=0.0, help="sample: fraction of species sent to <out>/heldout")
ap.add_argument("--target-tokens", type=float, default=None,
help="sample: size target (default 10e9); finalize: trim to this many tokens (default: keep all)")
ap.add_argument("--oversample", type=float, default=1.0, help="sample this much extra (trim with finalize)")
ap.add_argument("--rate", type=float, default=None, help="sample: inclusion rate per base (overrides the target)")
ap.add_argument("--rule", default="per_base", choices=["per_base", "length_weighted"],
help="sample: per_base (correct); length_weighted only to reproduce data sampled with it")
ap.add_argument("--plan", default=None, help="sample: plan file name (default plan_<split>.json)")
ap.add_argument("--revision", default=REVISION, help="OpenGenome2 Hub revision (commit) to read; pinned by default")
ap.add_argument("--tokens-per-byte", type=float, default=TOKENS_PER_BYTE)
ap.add_argument("--window", type=int, default=16384)
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--subsets", nargs="*", default=None, help="restrict to these subsets (directory names)")
ap.add_argument("--limit", type=int, default=0, help="sample: only the N smallest shards (trial)")
ap.add_argument("--out", default=".", help="dataset root (default: current directory)")
a = ap.parse_args()
{"sample": cmd_sample, "finalize": cmd_finalize, "report": cmd_report}[a.cmd](a)
if __name__ == "__main__":
sys.exit(main())