"""Build weights.npz directly from EXPLANATION.md (Fourier multiplication). No training.""" import numpy as np from forward import forward, all_inputs P, D_VOCAB, D_MODEL, N_HEADS, D_HEAD, D_MLP, N_CTX = 113, 114, 128, 4, 32, 512, 3 FREQS = [19, 31, 45, 47] NF = len(FREQS) NPER = D_MLP // NF # neurons per frequency B_BIAS = 0.0 A_AMP = 1.0 # neuron amplitude G = 11.0 # query/key gain: score ~ G^2/sqrt(32) to numbers, 0 to '=' S_U = 20.0 # unembedding scale t = np.arange(P) ws = [2 * np.pi * k / P for k in FREQS] # Residual layout: dims 2f,2f+1 = cos/sin(w_f t) embedding; 8 = number indicator; 9 = constant 1; # 10+2f,11+2f = attention-averaged cos/sin sums (a+b waves); 18+2f,19+2f = cos/sin(w(a+b)) from MLP. # 1. Embeddings W_E = np.zeros((D_MODEL, D_VOCAB)) for f, w in enumerate(ws): W_E[2 * f, :P] = np.cos(w * t) W_E[2 * f + 1, :P] = np.sin(w * t) W_E[8, :P] = 1.0 W_pos = np.zeros((N_CTX, D_MODEL)) W_pos[:, 9] = 1.0 # 2. Attention: each head attends to numbers (not '=') and copies its frequency's cos/sin. W_Q = np.zeros((N_HEADS, D_HEAD, D_MODEL)) W_K = np.zeros((N_HEADS, D_HEAD, D_MODEL)) W_V = np.zeros((N_HEADS, D_HEAD, D_MODEL)) W_O = np.zeros((D_MODEL, N_HEADS * D_HEAD)) for h in range(N_HEADS): W_Q[h, 0, 9] = G W_K[h, 0, 8] = G if h < NF: W_V[h, 0, 2 * h] = 1.0 W_V[h, 1, 2 * h + 1] = 1.0 # weights 1/2 each, so 2*z = cos(wa)+cos(wb), sin(wa)+sin(wb) W_O[10 + 2 * h, h * D_HEAD + 0] = 2.0 W_O[11 + 2 * h, h * D_HEAD + 1] = 2.0 # 3. MLP: neuron (f, m) pre = A[cos(wa+phi)+cos(wb+phi)] + B = A(cos(phi) C - sin(phi) S) + B W_in = np.zeros((D_MLP, D_MODEL)) b_in = np.full(D_MLP, B_BIAS) for f in range(NF): for m in range(NPER): j = f * NPER + m phi = 2 * np.pi * m / NPER W_in[j, 10 + 2 * f] = A_AMP * np.cos(phi) W_in[j, 11 + 2 * f] = -A_AMP * np.sin(phi) # W_out: closed-form least squares so MLP output equals cos/sin(w_k(a+b)) features. W_out = np.zeros((D_MODEL, D_MLP)) b_out = np.zeros(D_MODEL) W_U = np.zeros((D_MODEL, D_VOCAB)) base = dict(W_E=W_E, W_pos=W_pos, W_Q=W_Q, W_K=W_K, W_V=W_V, W_O=W_O, W_in=W_in, b_in=b_in, W_out=W_out, b_out=b_out, W_U=W_U) inp = all_inputs() acts = forward(base, inp) mlp_post = acts["mlp_post"][:, -1, :] # [N, 512] a, b = inp[:, 0], inp[:, 1] targets = [] for w in ws: targets += [np.cos(w * (a + b)), np.sin(w * (a + b))] T = np.stack(targets, axis=1) # [N, 8] coef, *_ = np.linalg.lstsq(mlp_post, T, rcond=None) # [512, 8] for f in range(NF): W_out[18 + 2 * f, :] = coef[:, 2 * f] W_out[19 + 2 * f, :] = coef[:, 2 * f + 1] # 4. Unembedding: logit_c = S_U * sum_k cos(w_k(a+b)) cos(w_k c) + sin sin. for f, w in enumerate(ws): W_U[18 + 2 * f, :P] = S_U * np.cos(w * t) W_U[19 + 2 * f, :P] = S_U * np.sin(w * t) np.savez("weights.npz", W_E=W_E, W_pos=W_pos, W_Q=W_Q, W_K=W_K, W_V=W_V, W_O=W_O, W_in=W_in, b_in=b_in, W_out=W_out, b_out=b_out, W_U=W_U) print("wrote weights.npz")