import json import random import numpy import pickle n = 17 # 长度改为 13 k_offset = 5 # 步长 (与 13 互质) num_train = 5000000 num_test = 1000 # 一个固定的、按位置变化的常量,扩展到 13 位 # (来自圆周率,只是为了固定且看起来随机) pos_const = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2] # 扩展了一位 import random from typing import List, Tuple, Set, Optional Latin = List[List[int]] def cyclic_latin_square(n: int = 10) -> Latin: return [[(i + j) % n for j in range(n)] for i in range(n)] def is_latin_square(L: Latin) -> bool: n = len(L) target = set(range(n)) for i in range(n): if set(L[i]) != target: return False for j in range(n): col = {L[i][j] for i in range(n)} if col != target: return False return True def _try_random_intercalate_move(L: Latin, rng: random.Random) -> bool: """ Try one random 2x2 intercalate flip. Return True if moved, else False. """ n = len(L) r1, r2 = rng.sample(range(n), 2) c1, c2 = rng.sample(range(n), 2) a = L[r1][c1] b = L[r1][c2] if a == b: return False # Need the 2x2 pattern: # L[r1,c1]=a, L[r1,c2]=b # L[r2,c1]=b, L[r2,c2]=a if L[r2][c1] != b or L[r2][c2] != a: return False # Flip to: # b a # a b L[r1][c1], L[r1][c2] = b, a L[r2][c1], L[r2][c2] = a, b return True def mcmc_step(L: Latin, rng: random.Random, lazy_p: float = 0.1, max_trials: int = 200) -> None: """ One Markov step: - with probability lazy_p: do nothing (aperiodicity) - else: attempt up to max_trials random intercalate moves; if none found, do nothing """ if rng.random() < lazy_p: return for _ in range(max_trials): if _try_random_intercalate_move(L, rng): return # No valid move found in trials -> stay def sample_latin_square_10( rng: random.Random, burn_in: int = 50_000, steps_after: int = 20_000, lazy_p: float = 0.1, max_trials_per_step: int = 200 ) -> Latin: """ Start from cyclic Latin square and run MCMC. Return one approximately-uniform sample. """ L = cyclic_latin_square(10) # Burn-in for _ in range(burn_in): mcmc_step(L, rng, lazy_p=lazy_p, max_trials=max_trials_per_step) # Extra steps (thinning / further mixing) for _ in range(steps_after): mcmc_step(L, rng, lazy_p=lazy_p, max_trials=max_trials_per_step) return [row[:] for row in L] def make_functions( n: int, seed: Optional[int] = None, burn_in: int = 500000, steps_between_samples: int = 500000, lazy_p: float = 0.1, max_trials_per_step: int = 200 ) -> List[Latin]: """ Generate n distinct 10x10 Latin squares via MCMC (approx uniform). Distinctness is enforced by hashing full matrices. """ rng = random.Random(seed) out: List[Latin] = [] seen: Set[Tuple[Tuple[int, ...], ...]] = set() # We keep one chain running and take samples separated by steps_between_samples. L = cyclic_latin_square(10) # burn-in on the running chain for _ in range(burn_in): mcmc_step(L, rng, lazy_p=lazy_p, max_trials=max_trials_per_step) while len(out) < n: # advance chain for _ in range(steps_between_samples): mcmc_step(L, rng, lazy_p=lazy_p, max_trials=max_trials_per_step) sample = [row[:] for row in L] key = tuple(tuple(row) for row in sample) if key in seen: continue # Safety check (can be removed for speed) if not is_latin_square(sample): raise RuntimeError("Internal error: produced a non-Latin square (should not happen).") seen.add(key) out.append(sample) return out functions = make_functions(n=n) print(functions) #print(xxx) def generate_samples_anchored_global(num_samples): samples = [] vocab = '0123456789' for _ in range(num_samples): # 1. 随机明文 (数字列表) plain_digits = [random.randint(0, 9) for _ in range(n)] cipher_digits = [0] * n # 2. 设置“锚点” # cipher[0] = plain[0] cipher_digits[0] = plain_digits[0] # 3. 生成全局依赖 for i in range(1, n): # cipher[i] = (plain[i] + plain[(i + k) % n] + C[i]) % 10 j = (i + k_offset) % n val = functions[i][plain_digits[i]][plain_digits[j]] #(plain_digits[i] + plain_digits[j] + pos_const[i]) % 10 cipher_digits[i] = val # 转换回字符串 #plain_str = ''.join(map(str, plain_digits)) #cipher_str = ''.join(map(str, cipher_digits)) #samples.append({"input": cipher_str, "output": plain_str}) samples.append(cipher_digits+plain_digits) #test_samples.append(cipher_digits+plain_digits) return numpy.array(samples,dtype=numpy.uint16) # --- 生成文件 --- train_samples = generate_samples_anchored_global(num_train) print(train_samples[0]) #print(xxx) train_samples.tofile('train.bin') #with open(f'{n}_anchored_global_mod10_train.jsonl', 'w') as f: # for s in train_samples: # f.write(json.dumps(s) + '\n') test_samples = generate_samples_anchored_global(num_test) test_samples.tofile('test.bin') #with open(f'{n}_anchored_global_mod10_test.jsonl', 'w') as f: # for s in test_samples: # f.write(json.dumps(s) + '\n') print(f"Generated {num_train} train samples and {num_test} test samples for ANCHORED GLOBAL (mod 10) task.") print(f"n={n}, k_offset={k_offset}") meta = { 'vocab_size': 11, 'block_size': n * 2, 'functions': functions } with open('meta.pkl', 'wb') as f: pickle.dump(meta, f) # --- 验证逻辑 --- # 打印一个样本的解密过程,用于验证 print("\n--- Verification Sample ---") if test_samples is None: print("No test samples generated for verification.") else: for t in range(len(test_samples)): c_str = test_samples[0,0:n] p_str = test_samples[0,n:2*n] #print(f"Cipher: {c_str}") #print(f"Plain: {p_str}") # 手动验证解密链 c = [int(x) for x in c_str] p_actual = [int(x) for x in p_str] p_solved = [-1] * n # -1 表示未知 #print("\nSolving sequence (MDM's perspective):") p_solved[0] = c[0] #print(f"Step 0: Solved p[0] = c[0] = {p_solved[0]}") # (n=13, k=5) 的求解顺序 # 求解 p[i] 需要 p[(i+k)%n] # 反过来看,p[0] -> p[i] s.t. (i+5)%13 = 0 => i = 8 # p[8] -> p[i] s.t. (i+5)%13 = 8 => i = 3 # p[3] -> p[i] s.t. (i+5)%13 = 3 => i = -2 % 13 = 11 # 链条: 0 -> 8 -> 3 -> 11 -> 6 -> 1 -> 9 -> 4 -> 12 -> 7 -> 2 -> 10 -> 5 solve_order = [12, 7, 2, 14, 9, 4, 16, 11, 6, 1, 13, 8, 3, 15, 10, 5] for i_solve in solve_order: # 找到它依赖谁 i_depend_on = (i_solve + k_offset) % n # plain[i] = (cipher[i] - plain[j] - C[i]) % 10 val = -1 for j in range(10): if functions[i_solve][j][p_solved[i_depend_on]] == c[i_solve]: val = j break if(val == -1): print("Oh no, what happens!") #(c[i_solve] - p_solved[i_depend_on] - pos_const[i_solve]) % 10 p_solved[i_solve] = val #print(f"Step N: Solved p[{i_solve}] = (c[{i_solve}] - p[{i_depend_on}] - C[{i_solve}]) % 10 = {val}") #print("\nSolved Plain:", numpy.array(p_solved)) #print("Actual Plain:", p_str) if (p_str == numpy.array(p_solved)).all(): #print("Verification SUCCESSFUL.") continue else: print("Verification FAILED.") print(xxxxx)