Datasets:
File size: 7,566 Bytes
58d2bd8 | 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | # -*- coding: utf-8 -*-
"""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) # 2,388,787,200
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)) # s, sec, reg, st, ins, frm, it, hz
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}"}}')
# ──────────────────────── worker ────────────────────────
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
# 日志写文件(避免stdout管道背压死锁)
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
# 双射性抽查:前100万索引无碰撞
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__)
|