"""Part B: toy training experiment on running parity (float32). Usage: python3 train.py [steps] Configs exactB{1,2,4,8,16}: block-coarsened recurrence with block length B, trained by exact forward substitution (n/B Jacobi sweeps = exact solution; gradient through all of them = exact gradient). B = 16 has a single block, i.e. no feedback: the standard-transformer baseline. jac2det, jac2, jac3: B = 1, FBT-style truncated training: pass 1 without feedback, each later pass reads the previous pass's states (shifted by one position); loss on every pass. jac2det detaches the fed-back state (K = 0); jac2 keeps the gradient (K = 1); jac3 has 3 passes (K = 2). jac2mix: like jac2, but a random 10% of the steps use 3 passes (FBT-style mixture; FBT uses 3%). Task (state tracking in the non-commutative group S3): each token is one of two generators (a swap and a 3-cycle); the target at every position t is the group element g_{x_t} ... g_{x_1} (6 classes). Evaluation always uses exact token-by-token decoding semantics (the fixed point), on fresh data.""" import json, sys, time import jax, jax.numpy as jnp, numpy as np, optax from model import init_params, one_pass, src_from_cut N, D, L = 16, 32, 2 name, seed = sys.argv[1], int(sys.argv[2]) steps = int(sys.argv[3]) if len(sys.argv) > 3 else 2000 BATCH, LR = 64, 2e-3 if name.startswith('exactB'): B = int(name[6:]); mode = 'exact' else: B = 1; mode = name src = jnp.array(src_from_cut(N, list(range(0, N, B)))); has = src >= 0 nblocks = N // B bpass = jax.vmap(one_pass, in_axes=(None, 0, 0, None)) # batched parallel pass def exact_forward(p, x, n_sweeps=nblocks): z = jnp.zeros(x.shape + (D,)); lg = None for _ in range(n_sweeps): z, lg = bpass(p, x, z[:, jnp.maximum(src, 0)], has) return lg def jacobi_forward(p, x, passes, detach): z, lg = bpass(p, x, jnp.zeros(x.shape + (D,)), jnp.zeros(N, bool)) # pass 1: feedback off outs = [lg] for _ in range(passes - 1): zin = z[:, jnp.maximum(src, 0)] if detach: zin = jax.lax.stop_gradient(zin) z, lg = bpass(p, x, zin, has); outs.append(lg) return outs def ce(lg, y): return -jnp.take_along_axis(jax.nn.log_softmax(lg), y[..., None], -1).mean() def loss_fn(p, x, y, passes=None): if mode == 'exact': return ce(exact_forward(p, x), y) if passes is None: passes = 3 if mode == 'jac3' else 2 outs = jacobi_forward(p, x, passes, mode == 'jac2det') return sum(ce(o, y) for o in outs) / len(outs) opt = optax.chain(optax.clip_by_global_norm(1.0), optax.adam(optax.warmup_cosine_decay_schedule(0.0, LR, min(100, steps // 5), steps, LR * 0.05))) @jax.jit def step(p, st, x, y): l, g = jax.value_and_grad(loss_fn)(p, x, y) up, st = opt.update(g, st, p) return optax.apply_updates(p, up), st, l @jax.jit def step3(p, st, x, y): l, g = jax.value_and_grad(lambda p_, x_, y_: loss_fn(p_, x_, y_, 3))(p, x, y) up, st = opt.update(g, st, p) return optax.apply_updates(p, up), st, l import itertools PERMS = list(itertools.permutations(range(3))) GEN = [(1, 0, 2), (1, 2, 0)] # token 0: swap, token 1: 3-cycle TRANS = jnp.array([[PERMS.index(tuple(GEN[t][PERMS[s][i]] for i in range(3))) for t in range(2)] for s in range(6)]) def _batch(key, n): x = jax.random.bernoulli(key, 0.5, (n, N)).astype(jnp.int32) def stepf(s, xt): s2 = TRANS[s, xt] return s2, s2 _, y = jax.lax.scan(stepf, jnp.zeros(n, jnp.int32), x.T) return x, y.T _train_batch = jax.jit(lambda key: _batch(key, BATCH)); _eval_batch = jax.jit(lambda key: _batch(key, 4000)) def batch(key, n=BATCH): return _train_batch(key) if n == BATCH else _eval_batch(key) @jax.jit def evaluate(p, x, y): acc_dec = (jnp.argmax(exact_forward(p, x, N // 1 if B == 1 else nblocks), -1) == y).mean(0) # exact decoding, per position if mode == 'exact': return acc_dec, acc_dec outs = jacobi_forward(p, x, 3 if mode == 'jac3' else 2, False) return acc_dec, (jnp.argmax(outs[-1], -1) == y).mean(0) # what the last training pass computes key = jax.random.PRNGKey(seed) p = init_params(jax.random.fold_in(key, 1), 2, D, L, N, 6, scale=0.5) st = opt.init(p); t0 = time.time(); losses = []; mix_rng = np.random.default_rng(seed); n3 = 0 for i in range(steps): x, y = batch(jax.random.fold_in(key, 1000 + i)) use3 = mode == 'jac2mix' and mix_rng.random() < 0.10 n3 += int(use3) p, st, l = (step3 if use3 else step)(p, st, x, y) if i % 100 == 0 or i == steps - 1: losses.append(round(float(l), 4)) xe, ye = batch(jax.random.fold_in(key, 7), 4000) acc_dec, acc_train_style = evaluate(p, xe, ye) rec = {'three_pass_steps': n3, 'task': 'S3', 'batch': BATCH, 'name': name, 'seed': seed, 'steps': steps, 'B': B, 'mode': mode, 'n': N, 'd': D, 'layers': L, 'final_loss': losses[-1], 'loss_curve': losses, 'acc_decode_by_pos': [round(float(a), 4) for a in acc_dec], 'acc_trainstyle_by_pos': [round(float(a), 4) for a in acc_train_style], 'acc_decode_mean': round(float(acc_dec.mean()), 4), 'acc_decode_last': round(float(acc_dec[-1]), 4), 'wall_s': round(time.time() - t0, 1)} with open('runs.jsonl', 'a') as f: f.write(json.dumps(rec) + '\n') print(name, seed, 'loss', losses[-1], 'decode mean/last', rec['acc_decode_mean'], rec['acc_decode_last'], 'wall', rec['wall_s'])