File size: 5,817 Bytes
e213b85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env python3
"""Generate the PNS corpus: train the tokenizer (train text only), then pack
all splits as npz shards with a hashed manifest.

Seed namespaces are disjoint by construction and cross-checked by content hash:
  train        0        .. n_train-1          L=256
  val          1_000_000 ..                    L=256
  val_1k       1_100_000 ..                    L=1024
  val_4k       1_200_000 ..                    L=4096
  test         2_000_000 ..                    L=256   (touched once, at the end)
  test_1k      2_100_000 ..                    L=1024
  test_4k      2_200_000 ..                    L=4096
"""
import argparse
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

from pns.common import PNS_ROOT, SCHEMA_VERSION, atomic_write_json, sha256_file, shards_root, tokenizer_path  # noqa: E402
from pns.data.pack import pack_lifetimes  # noqa: E402
from pns.data.tokenize import load_tokenizer, train_tokenizer  # noqa: E402
from pns.world.sim import generate_lifetime  # noqa: E402

SPLITS = {
    "train":   (0,          None, 256),
    "val":     (1_000_000,  2000, 256),
    "val_1k":  (1_100_000,  400, 1024),
    "val_4k":  (1_200_000,  120, 4096),
    "test":    (2_000_000,  2000, 256),
    "test_1k": (2_100_000,  400, 1024),
    "test_4k": (2_200_000,  120, 4096),
    # ---- E3 (fresh namespace; exp-1 test data motivated the E3 design, so it
    # is burned for confirmatory use). Confirmation split is single-use.
    "e3_train":   (3_000_000, None, 256),
    "e3_dev":     (3_500_000, 2000, 256),
    "e3_dev_1k":  (3_600_000,  400, 1024),
    "e3_conf":    (3_900_000, 2000, 256),
    "e3_conf_1k": (3_950_000,  400, 1024),
    # forensic relabel of the ORIGINAL val seeds: identical event streams,
    # corrected SEM golds (generate with PNS_GOLD=sem)
    "val_relabel": (1_000_000, 2000, 256),
    # forensic relabel of the ORIGINAL train seeds, same construction. Needed
    # so the Sigma-decode probe can be *trained* on corrected labels too; the
    # probe only ever reads the first ~1.5k train lifetimes (AUDIT.md 9).
    "train_relabel": (0, 2000, 256),
}
LT_PER_SHARD = {256: 1000, 1024: 250, 4096: 60}


def build_shard(args):
    split, base_seed, count, length, shard_idx, out = args
    lts = [generate_lifetime(base_seed + i, length) for i in range(count)]
    tok = load_tokenizer()
    info = pack_lifetimes(lts, tok, Path(out))
    info.update(split=split, shard=shard_idx, seed_lo=base_seed, seed_hi=base_seed + count - 1,
                length=length, path=str(out),
                dropped={k: v for lt in lts for k, v in lt["dropped"].items()},
                digests=[lt["digest"] for lt in lts])
    return info


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--n-train", type=int, default=120_000)
    ap.add_argument("--e3-train", type=int, default=120_000)
    ap.add_argument("--workers", type=int, default=64)
    ap.add_argument("--tokenizer-sample", type=int, default=1500)
    args = ap.parse_args()
    root = shards_root()
    root.mkdir(parents=True, exist_ok=True)

    if not tokenizer_path().exists():
        print("training tokenizer on train-split sample ...", flush=True)
        texts = []
        for s in range(args.tokenizer_sample):
            lt = generate_lifetime(s, 256)
            texts.extend(f"+{e.dt}m {e.text}" for e in lt["events"])
        t = train_tokenizer(texts)
        print("tokenizer:", t.get_vocab_size(), "->", tokenizer_path(), flush=True)

    jobs = []
    for split, (base, n, length) in SPLITS.items():
        n = (args.e3_train if split == "e3_train" else args.n_train) if n is None else n
        per = LT_PER_SHARD[length]
        for i in range(0, n, per):
            cnt = min(per, n - i)
            out = root / split / f"shard_{i // per:05d}.npz"
            if not out.exists():
                jobs.append((split, base + i, cnt, length, i // per, str(out)))
    print(f"{len(jobs)} shards to build", flush=True)
    t0 = time.time()
    infos = []
    with ProcessPoolExecutor(max_workers=args.workers) as ex:
        for k, info in enumerate(ex.map(build_shard, jobs)):
            infos.append(info)
            if k % 20 == 0:
                print(f"  {k + 1}/{len(jobs)} shards, {time.time() - t0:.0f}s", flush=True)

    # cross-split content-hash disjointness
    seen: dict[str, str] = {}
    dup = 0
    for info in infos:
        for d in info["digests"]:
            if d in seen and seen[d] != info["split"]:
                dup += 1
            seen[d] = info["split"]
    # merge with any existing manifest: rebuilding it from newly-built shards
    # alone once erased the original corpus's provenance (audit/AUDIT.md 5)
    prev = []
    mpath = root / "MANIFEST.json"
    if mpath.exists():
        import json as _json
        prev = _json.loads(mpath.read_text()).get("shards", [])
    have = {i["path"] for i in infos}
    infos = [p for p in prev if p.get("path") not in have] + infos
    manifest = dict(schema=SCHEMA_VERSION, n_train=args.n_train,
                    generator_sha=sha256_file(PNS_ROOT / "pns" / "world" / "sim.py"),
                    reducer_sha=sha256_file(PNS_ROOT / "pns" / "world" / "reducer.py"),
                    verbalizer_sha=sha256_file(PNS_ROOT / "pns" / "world" / "verbalize.py"),
                    tokenizer_sha=sha256_file(tokenizer_path()),
                    cross_split_digest_collisions=dup,
                    shards=[{k: v for k, v in i.items() if k != "digests"} for i in infos])
    atomic_write_json(root / "MANIFEST.json", manifest)
    print("cross-split digest collisions:", dup)
    print("manifest written:", root / "MANIFEST.json")


if __name__ == "__main__":
    main()