AngelWarmSmile123 commited on
Commit
58d2bd8
·
verified ·
1 Parent(s): 82face0

add sephirot_gen.py

Browse files
Files changed (1) hide show
  1. sephirot_gen.py +188 -0
sephirot_gen.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """sephirot_gen.py v2 — 十六质点世界修复合成数据引擎(全量重建版)
3
+ 枚举空间 N = 16×64×32×4×27×27×5×5 = 2,388,787,200(与论文一致)
4
+ 核心:Feistel 双射 + 同置换游走(cycle-walking)→ 索引空间均匀洗牌
5
+ 每行由索引确定性重建(断点安全、可验证)
6
+ 用法:
7
+ python sephirot_gen.py --smoke # 100万行快速验证
8
+ python sephirot_gen.py --full # 全量23亿,16 workers
9
+ python sephirot_gen.py --verify 50000 # 抽样重生成一致性校验
10
+ """
11
+ import os, sys, json, gzip, time, math, hashlib, random, multiprocessing as mp
12
+
13
+ BASE = os.path.dirname(os.path.abspath(__file__))
14
+ SEEDS = os.path.join(BASE, "seeds.json")
15
+ DATA = os.path.join(BASE, "data")
16
+ WORKERS = 16
17
+ SHARD_ROWS = 2_000_000 # 每分片行数
18
+ DIMS = [16, 64, 32, 4, 27, 27, 5, 5]
19
+ N = math.prod(DIMS) # 2,388,787,200
20
+
21
+ with open(SEEDS, encoding="utf-8") as f:
22
+ S = json.load(f)
23
+ SECTOR = S["sector"]; REGION = S["region"]
24
+ INSTR = S["instrument"]; FRAME = S["frame"]
25
+ LEXK = S["sephirot_keys"]; LEX = S["sephirot_lex"]
26
+ TOP = S["top_terms"]
27
+
28
+ MASTER_KEY = int.from_bytes(hashlib.sha256(
29
+ b"worldfix-v2|corpus=61562415|sephirot=16").digest()[:8], "big")
30
+
31
+ STANCES = ["预防", "缓解", "修复", "再生"]
32
+ INTENS = ["微调", "常规", "强化", "集中", "极限"]
33
+ HORIZON = ["即时", "季度", "年度", "五年", "世代"]
34
+
35
+ def feistel(x: int) -> int:
36
+ """4轮 Feistel on 2^32(L=R=16bit),固定网络→双射"""
37
+ l, r = (x >> 16) & 0xFFFF, x & 0xFFFF
38
+ for rnd in range(4):
39
+ f = ((r * 2654435761 + MASTER_KEY + rnd * 0x9E3779B9) ^ (r << 7)) & 0xFFFF
40
+ l, r = r, (l ^ f) & 0xFFFF
41
+ return (l << 16) | r
42
+
43
+ def shuffle_index(i: int) -> int:
44
+ """同置换游走:i<N 映射到 [0,N) 的双射(修正版:单一定义网络)"""
45
+ x = i
46
+ while True:
47
+ x = feistel(x)
48
+ if x < N:
49
+ return x
50
+
51
+ def decode(idx: int):
52
+ """混合基解码 → 8字段"""
53
+ out = []
54
+ for d in reversed(DIMS):
55
+ out.append(idx % d)
56
+ idx //= d
57
+ return tuple(reversed(out)) # s, sec, reg, st, ins, frm, it, hz
58
+
59
+ VERD = ("ALLOW", "REPAIR", "FALLBACK")
60
+
61
+ def make_row(order: int):
62
+ """order=原始序号 → 确定性生成一行(任何进程任何时候结果一致)"""
63
+ idx = shuffle_index(order)
64
+ s, sec, reg, st, ins, frm, it, hz = decode(idx)
65
+ rng = random.Random(idx ^ MASTER_KEY)
66
+ k = LEXK[s % 16]
67
+ lex = LEX[k]
68
+ actor = lex[rng.randrange(len(lex))]
69
+ term1 = TOP[(idx * 31 + order) % len(TOP)]
70
+ term2 = INSTR[ins]
71
+ term3 = FRAME[frm]
72
+ rx = (f"[{k}] 面向{REGION[reg]}的{SECTOR[sec]}问题,以「{actor}」为核心姿态,"
73
+ f"采用{term2}与{term3},在{HORIZON[hz]}视野内以{INTENS[it]}强度推进"
74
+ f"{STANCES[st]}型干预;配套十六质点审计回路与有界回滚预算(≤3)。")
75
+ # 治理模拟块
76
+ roll = rng.random()
77
+ if roll < 0.86: v, kk = "ALLOW", 0
78
+ elif roll < 0.97: v, kk = "REPAIR", 1 + rng.randrange(3)
79
+ else: v, kk = "FALLBACK", 3
80
+ aid = f"{(idx * 2654435761) & 0xFFFFFFFFFFFF:012x}"
81
+ return (f'{{"i":{order},"h":{idx},"s":{s},"sec":{sec},"reg":{reg},"st":{st},'
82
+ f'"ins":{ins},"frm":{frm},"it":{it},"hz":{hz},'
83
+ f'"key":"{k}","sector":"{SECTOR[sec]}","region":"{REGION[reg]}",'
84
+ f'"stance":"{STANCES[st]}","instrument":"{term2}","frame":"{term3}",'
85
+ f'"intensity":"{INTENS[it]}","horizon":"{HORIZON[hz]}",'
86
+ f'"prescription":"{rx}","verdict":"{v}","strikes":{kk},"audit":"{aid}"}}')
87
+
88
+ # ──────────────────────── worker ────────────────────────
89
+ def worker(wid: int, lo: int, hi: int):
90
+ wdir = os.path.join(DATA, f"w{wid:02d}")
91
+ os.makedirs(wdir, exist_ok=True)
92
+ mani = os.path.join(wdir, "manifest.json")
93
+ pos = lo
94
+ if os.path.exists(mani):
95
+ try:
96
+ p = int(json.load(open(mani))["pos"])
97
+ if lo <= p <= hi: # 越界/损坏清单不可信,静默丢弃
98
+ pos = max(pos, p)
99
+ except Exception:
100
+ pass
101
+ # 清理尾部未登记分片
102
+ for fn in os.listdir(wdir):
103
+ m = fn.endswith(".jsonl.gz") and fn.split("_")[2:]
104
+ if fn.endswith(".part"):
105
+ os.remove(os.path.join(wdir, fn))
106
+ t0 = time.time(); cnt_since = 0
107
+ while pos < hi:
108
+ end = min(pos + SHARD_ROWS, hi)
109
+ tmp = os.path.join(wdir, f"s{pos:012d}.jsonl.gz.part")
110
+ fin = os.path.join(wdir, f"s{pos:012d}.jsonl.gz")
111
+ with gzip.open(tmp, "wb", compresslevel=1) as gz:
112
+ buf = []
113
+ ap = buf.append
114
+ for o in range(pos, end):
115
+ ap(make_row(o))
116
+ if len(buf) >= 20000:
117
+ gz.write(("\n".join(buf) + "\n").encode())
118
+ buf.clear()
119
+ if buf:
120
+ gz.write(("\n".join(buf) + "\n").encode())
121
+ os.replace(tmp, fin)
122
+ pos = end
123
+ json.dump({"pos": pos, "hi": hi}, open(mani, "w"))
124
+ cnt_since += SHARD_ROWS
125
+ el = time.time() - t0
126
+ # 日志写文件(避免stdout管道背压死锁)
127
+ with open(os.path.join(wdir, "gen.log"), "a", encoding="utf-8") as lf:
128
+ lf.write(f"[w{wid:02d}] {pos-lo}/{hi-lo} ({(pos-lo)/(hi-lo)*100:.2f}%) "
129
+ f"{cnt_since/max(el,1e-9):,.0f} r/s t+{el:.0f}s\n")
130
+ json.dump({"pos": pos, "hi": hi, "done": True}, open(mani, "w")) # 收尾覆写,清掉陈旧/越界清单
131
+
132
+ def full():
133
+ os.makedirs(DATA, exist_ok=True)
134
+ chunk = N // WORKERS
135
+ jobs = [(w, w * chunk, (w + 1) * chunk if w < WORKERS - 1 else N)
136
+ for w in range(WORKERS)]
137
+ t0 = time.time()
138
+ with mp.Pool(WORKERS) as pool:
139
+ pool.starmap(worker, jobs)
140
+ print(f"FULL DONE {N:,} rows in {(time.time()-t0)/60:.1f} min")
141
+
142
+ def smoke(total=1_000_000):
143
+ os.makedirs(DATA, exist_ok=True)
144
+ chunk = total // WORKERS
145
+ jobs = [(w, w * chunk, (w + 1) * chunk if w < WORKERS - 1 else total)
146
+ for w in range(WORKERS)]
147
+ t0 = time.time()
148
+ with mp.Pool(WORKERS) as pool:
149
+ pool.starmap(worker, jobs)
150
+ print(f"SMOKE DONE {total:,} rows in {time.time()-t0:.1f}s")
151
+
152
+ def verify(n=50000):
153
+ import itertools
154
+ bad = 0
155
+ rng = random.Random(7)
156
+ samples = [rng.randrange(N) for _ in range(min(n, 5000))] + list(range(10))
157
+ for o in samples:
158
+ r1 = make_row(o)
159
+ # 重算两次一致性
160
+ if r1 != make_row(o):
161
+ bad += 1
162
+ # 双射性抽查:前100万索引无碰撞
163
+ seen = set()
164
+ dup = 0
165
+ for o in range(1_000_000):
166
+ h = shuffle_index(o)
167
+ if h in seen:
168
+ dup += 1
169
+ seen.add(h)
170
+ print(f"verify: 一致性坏行={bad}/{len(samples)} 百万抽样碰撞={dup}")
171
+ print("VERIFY PASS" if bad == 0 and dup == 0 else "VERIFY FAIL")
172
+ # 字段范围校验
173
+ o = 123456789
174
+ s, sec, reg, st, ins, frm, it, hz = decode(shuffle_index(o))
175
+ assert 0 <= s < 16 and 0 <= sec < 64 and 0 <= reg < 32 and 0 <= st < 4 \
176
+ and 0 <= ins < 27 and 0 <= frm < 27 and 0 <= it < 5 and 0 <= hz < 5
177
+ print("decode ranges OK; N =", f"{N:,}")
178
+
179
+ if __name__ == "__main__":
180
+ a = sys.argv[1] if len(sys.argv) > 1 else "--verify"
181
+ if a == "--full":
182
+ full()
183
+ elif a == "--smoke":
184
+ smoke(int(sys.argv[2]) if len(sys.argv) > 2 else 1_000_000)
185
+ elif a == "--verify":
186
+ verify(int(sys.argv[2]) if len(sys.argv) > 2 else 50000)
187
+ else:
188
+ print(__doc__)