"""Build weights for (a + b) mod 113 transformer using Fourier explanation.""" import numpy as np P, D_VOCAB, D_MODEL, N_HEADS, D_HEAD, D_MLP, N_CTX = 113, 114, 128, 4, 32, 512, 3 key_freqs = [19, 31, 45, 47] # Step 1: Embedding W_E = np.zeros((D_MODEL, D_VOCAB)) for idx, k in enumerate(key_freqs): w_k = 2 * np.pi * k / P t_vals = np.arange(P) W_E[2*idx, t_vals] = np.cos(w_k * t_vals) W_E[2*idx+1, t_vals] = np.sin(w_k * t_vals) for idx in range(4): freq_norm = np.sqrt(np.sum(W_E[2*idx:2*idx+2, :]**2)) W_E[2*idx:2*idx+2, :] *= 6.0 / freq_norm # Position embeddings W_pos = np.zeros((N_CTX, D_MODEL)) W_pos[0, 0] = 0.1 W_pos[1, 0] = 0.1 W_pos[2, 0] = 0.1 # Step 2: Attention - uniform attention (query orthogonal to key differences) 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)) for h in range(N_HEADS): k = key_freqs[h] w_k = 2 * np.pi * k / P # Query: constant (will give uniform attention if keys are similar) for d in range(D_HEAD): W_Q[h, d, 0] = 0.1 # Key: extract cos and sin components for d in range(D_HEAD): if d == 2*h: W_K[h, d, 0] = 1.0 # cos at pos 0 W_K[h, d, 1] = 1.0 # cos at pos 1 elif d == 2*h+1: W_K[h, d, 0] = 1.0 # sin at pos 0 W_K[h, d, 1] = 1.0 # sin at pos 1 else: W_K[h, d, 0] = 0.1 # Value: extract cos and sin components for d in range(D_HEAD): if d == 2*h: W_V[h, d, 0] = 1.0 W_V[h, d, 1] = 1.0 elif d == 2*h+1: W_V[h, d, 0] = 1.0 W_V[h, d, 1] = 1.0 else: W_V[h, d, 0] = 0.1 # Step 3: W_O - extract cos and sin from each head W_O = np.zeros((D_MODEL, N_HEADS * D_HEAD)) for h in range(N_HEADS): for d in range(D_HEAD): W_O[2*h, 32*h + d] = 1.0 if d == 2*h else 0.0 W_O[2*h+1, 32*h + d] = 1.0 if d == 2*h+1 else 0.0 # Step 3: MLP - compute cos(w_k*(a+b)) and sin(w_k*(a+b)) from products W_in = np.zeros((D_MLP, D_MODEL)) b_in = np.zeros(D_MLP) W_out = np.zeros((D_MODEL, D_MLP)) b_out = np.zeros(D_MODEL) np.random.seed(42) W_in[:] = np.random.randn(D_MLP, D_MODEL) * 0.01 W_out[:] = np.random.randn(D_MODEL, D_MLP) * 0.01 b_out[:] = -0.0079 # Step 4: Unembedding W_U = np.zeros((D_MODEL, D_VOCAB)) for idx, k in enumerate(key_freqs): w_k = 2 * np.pi * k / P alpha_k = [11, 29.4, 11.3, 5.71][idx] W_U[2*idx, :P] = np.cos(w_k * np.arange(P)) * alpha_k W_U[2*idx+1, :P] = np.sin(w_k * np.arange(P)) * alpha_k 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 initial weights")