| |
| """sephirot_gen.py v2 — 十六质点世界修复合成数据引擎(全量重建版) |
| 枚举空间 N = 16×64×32×4×27×27×5×5 = 2,388,787,200(与论文一致) |
| 核心:Feistel 双射 + 同置换游走(cycle-walking)→ 索引空间均匀洗牌 |
| 每行由索引确定性重建(断点安全、可验证) |
| 用法: |
| python sephirot_gen.py --smoke # 100万行快速验证 |
| python sephirot_gen.py --full # 全量23亿,16 workers |
| python sephirot_gen.py --verify 50000 # 抽样重生成一致性校验 |
| """ |
| import os, sys, json, gzip, time, math, hashlib, random, multiprocessing as mp |
|
|
| BASE = os.path.dirname(os.path.abspath(__file__)) |
| SEEDS = os.path.join(BASE, "seeds.json") |
| DATA = os.path.join(BASE, "data") |
| WORKERS = 16 |
| SHARD_ROWS = 2_000_000 |
| DIMS = [16, 64, 32, 4, 27, 27, 5, 5] |
| N = math.prod(DIMS) |
|
|
| with open(SEEDS, encoding="utf-8") as f: |
| S = json.load(f) |
| SECTOR = S["sector"]; REGION = S["region"] |
| INSTR = S["instrument"]; FRAME = S["frame"] |
| LEXK = S["sephirot_keys"]; LEX = S["sephirot_lex"] |
| TOP = S["top_terms"] |
|
|
| MASTER_KEY = int.from_bytes(hashlib.sha256( |
| b"worldfix-v2|corpus=61562415|sephirot=16").digest()[:8], "big") |
|
|
| STANCES = ["预防", "缓解", "修复", "再生"] |
| INTENS = ["微调", "常规", "强化", "集中", "极限"] |
| HORIZON = ["即时", "季度", "年度", "五年", "世代"] |
|
|
| def feistel(x: int) -> int: |
| """4轮 Feistel on 2^32(L=R=16bit),固定网络→双射""" |
| l, r = (x >> 16) & 0xFFFF, x & 0xFFFF |
| for rnd in range(4): |
| f = ((r * 2654435761 + MASTER_KEY + rnd * 0x9E3779B9) ^ (r << 7)) & 0xFFFF |
| l, r = r, (l ^ f) & 0xFFFF |
| return (l << 16) | r |
|
|
| def shuffle_index(i: int) -> int: |
| """同置换游走:i<N 映射到 [0,N) 的双射(修正版:单一定义网络)""" |
| x = i |
| while True: |
| x = feistel(x) |
| if x < N: |
| return x |
|
|
| def decode(idx: int): |
| """混合基解码 → 8字段""" |
| out = [] |
| for d in reversed(DIMS): |
| out.append(idx % d) |
| idx //= d |
| return tuple(reversed(out)) |
|
|
| VERD = ("ALLOW", "REPAIR", "FALLBACK") |
|
|
| def make_row(order: int): |
| """order=原始序号 → 确定性生成一行(任何进程任何时候结果一致)""" |
| idx = shuffle_index(order) |
| s, sec, reg, st, ins, frm, it, hz = decode(idx) |
| rng = random.Random(idx ^ MASTER_KEY) |
| k = LEXK[s % 16] |
| lex = LEX[k] |
| actor = lex[rng.randrange(len(lex))] |
| term1 = TOP[(idx * 31 + order) % len(TOP)] |
| term2 = INSTR[ins] |
| term3 = FRAME[frm] |
| rx = (f"[{k}] 面向{REGION[reg]}的{SECTOR[sec]}问题,以「{actor}」为核心姿态," |
| f"采用{term2}与{term3},在{HORIZON[hz]}视野内以{INTENS[it]}强度推进" |
| f"{STANCES[st]}型干预;配套十六质点审计回路与有界回滚预算(≤3)。") |
| |
| roll = rng.random() |
| if roll < 0.86: v, kk = "ALLOW", 0 |
| elif roll < 0.97: v, kk = "REPAIR", 1 + rng.randrange(3) |
| else: v, kk = "FALLBACK", 3 |
| aid = f"{(idx * 2654435761) & 0xFFFFFFFFFFFF:012x}" |
| return (f'{{"i":{order},"h":{idx},"s":{s},"sec":{sec},"reg":{reg},"st":{st},' |
| f'"ins":{ins},"frm":{frm},"it":{it},"hz":{hz},' |
| f'"key":"{k}","sector":"{SECTOR[sec]}","region":"{REGION[reg]}",' |
| f'"stance":"{STANCES[st]}","instrument":"{term2}","frame":"{term3}",' |
| f'"intensity":"{INTENS[it]}","horizon":"{HORIZON[hz]}",' |
| f'"prescription":"{rx}","verdict":"{v}","strikes":{kk},"audit":"{aid}"}}') |
|
|
| |
| def worker(wid: int, lo: int, hi: int): |
| wdir = os.path.join(DATA, f"w{wid:02d}") |
| os.makedirs(wdir, exist_ok=True) |
| mani = os.path.join(wdir, "manifest.json") |
| pos = lo |
| if os.path.exists(mani): |
| try: |
| p = int(json.load(open(mani))["pos"]) |
| if lo <= p <= hi: |
| pos = max(pos, p) |
| except Exception: |
| pass |
| |
| for fn in os.listdir(wdir): |
| m = fn.endswith(".jsonl.gz") and fn.split("_")[2:] |
| if fn.endswith(".part"): |
| os.remove(os.path.join(wdir, fn)) |
| t0 = time.time(); cnt_since = 0 |
| while pos < hi: |
| end = min(pos + SHARD_ROWS, hi) |
| tmp = os.path.join(wdir, f"s{pos:012d}.jsonl.gz.part") |
| fin = os.path.join(wdir, f"s{pos:012d}.jsonl.gz") |
| with gzip.open(tmp, "wb", compresslevel=1) as gz: |
| buf = [] |
| ap = buf.append |
| for o in range(pos, end): |
| ap(make_row(o)) |
| if len(buf) >= 20000: |
| gz.write(("\n".join(buf) + "\n").encode()) |
| buf.clear() |
| if buf: |
| gz.write(("\n".join(buf) + "\n").encode()) |
| os.replace(tmp, fin) |
| pos = end |
| json.dump({"pos": pos, "hi": hi}, open(mani, "w")) |
| cnt_since += SHARD_ROWS |
| el = time.time() - t0 |
| |
| with open(os.path.join(wdir, "gen.log"), "a", encoding="utf-8") as lf: |
| lf.write(f"[w{wid:02d}] {pos-lo}/{hi-lo} ({(pos-lo)/(hi-lo)*100:.2f}%) " |
| f"{cnt_since/max(el,1e-9):,.0f} r/s t+{el:.0f}s\n") |
| json.dump({"pos": pos, "hi": hi, "done": True}, open(mani, "w")) |
|
|
| def full(): |
| os.makedirs(DATA, exist_ok=True) |
| chunk = N // WORKERS |
| jobs = [(w, w * chunk, (w + 1) * chunk if w < WORKERS - 1 else N) |
| for w in range(WORKERS)] |
| t0 = time.time() |
| with mp.Pool(WORKERS) as pool: |
| pool.starmap(worker, jobs) |
| print(f"FULL DONE {N:,} rows in {(time.time()-t0)/60:.1f} min") |
|
|
| def smoke(total=1_000_000): |
| os.makedirs(DATA, exist_ok=True) |
| chunk = total // WORKERS |
| jobs = [(w, w * chunk, (w + 1) * chunk if w < WORKERS - 1 else total) |
| for w in range(WORKERS)] |
| t0 = time.time() |
| with mp.Pool(WORKERS) as pool: |
| pool.starmap(worker, jobs) |
| print(f"SMOKE DONE {total:,} rows in {time.time()-t0:.1f}s") |
|
|
| def verify(n=50000): |
| import itertools |
| bad = 0 |
| rng = random.Random(7) |
| samples = [rng.randrange(N) for _ in range(min(n, 5000))] + list(range(10)) |
| for o in samples: |
| r1 = make_row(o) |
| |
| if r1 != make_row(o): |
| bad += 1 |
| |
| seen = set() |
| dup = 0 |
| for o in range(1_000_000): |
| h = shuffle_index(o) |
| if h in seen: |
| dup += 1 |
| seen.add(h) |
| print(f"verify: 一致性坏行={bad}/{len(samples)} 百万抽样碰撞={dup}") |
| print("VERIFY PASS" if bad == 0 and dup == 0 else "VERIFY FAIL") |
| |
| o = 123456789 |
| s, sec, reg, st, ins, frm, it, hz = decode(shuffle_index(o)) |
| assert 0 <= s < 16 and 0 <= sec < 64 and 0 <= reg < 32 and 0 <= st < 4 \ |
| and 0 <= ins < 27 and 0 <= frm < 27 and 0 <= it < 5 and 0 <= hz < 5 |
| print("decode ranges OK; N =", f"{N:,}") |
|
|
| if __name__ == "__main__": |
| a = sys.argv[1] if len(sys.argv) > 1 else "--verify" |
| if a == "--full": |
| full() |
| elif a == "--smoke": |
| smoke(int(sys.argv[2]) if len(sys.argv) > 2 else 1_000_000) |
| elif a == "--verify": |
| verify(int(sys.argv[2]) if len(sys.argv) > 2 else 50000) |
| else: |
| print(__doc__) |
|
|