"""Tiny FBT-style feedback transformer in JAX, with an optional block-coarsened recurrence. Position t receives, at its bottom input, the top-layer state of a *source* position src[t] < t (src[t] = -1 means no feedback: plain embedding). Fusion follows FBT's Eq. (4): u_t = (W_h z_src) * sigmoid(W_g e_t) (token embedding only gates the state) B = 1 (FBT): src[t] = t - 1 block-coarsened: src[t] = last position of the previous block (feedback crosses block boundaries only) """ import jax import jax.numpy as jnp import numpy as np def init_params(key, vocab, d, n_layers, n_pos, n_out, scale=1.0): ks = jax.random.split(key, 8 + 6 * n_layers) g = lambda k, shape, s: jax.random.normal(k, shape) * s p = { 'emb': g(ks[0], (vocab, d), 1.0 * scale), 'pos': g(ks[1], (n_pos, d), 0.3 * scale), 'Wh': g(ks[2], (d, d), scale / np.sqrt(d)) + jnp.eye(d), 'Wg': g(ks[3], (d, d), scale / np.sqrt(d)), 'out': g(ks[4], (d, n_out), scale / np.sqrt(d)), 'layers': [], } for l in range(n_layers): k = ks[8 + 6 * l: 14 + 6 * l] p['layers'].append({ 'q': g(k[0], (d, d), scale / np.sqrt(d)), 'k': g(k[1], (d, d), scale / np.sqrt(d)), 'v': g(k[2], (d, d), scale / np.sqrt(d)), 'o': g(k[3], (d, d), scale / np.sqrt(d)), 'm1': g(k[4], (d, 4 * d), scale / np.sqrt(d)), 'm2': g(k[5], (4 * d, d), scale / np.sqrt(4 * d)), }) return p def ln(x): x = x - x.mean(-1, keepdims=True) return x / jnp.sqrt((x * x).mean(-1, keepdims=True) + 1e-6) def one_pass(p, x, zin, has_src, n_heads=2): """One parallel causal forward pass over a single sequence. x: [n] int tokens; zin: [n, d] fed-back state per position (already gathered by src); has_src: [n] bool. Returns (top states [n, d], logits [n, n_out]).""" n = x.shape[0] e = p['emb'][x] fused = (zin @ p['Wh']) * jax.nn.sigmoid(e @ p['Wg']) h = jnp.where(has_src[:, None], fused, e) + p['pos'][:n] d = h.shape[-1] mask = jnp.tril(jnp.ones((n, n), bool)) for lyr in p['layers']: a = ln(h) q = (a @ lyr['q']).reshape(n, n_heads, d // n_heads) k = (a @ lyr['k']).reshape(n, n_heads, d // n_heads) v = (a @ lyr['v']).reshape(n, n_heads, d // n_heads) att = jnp.einsum('ihd,jhd->hij', q, k) / jnp.sqrt(d // n_heads) att = jax.nn.softmax(jnp.where(mask[None], att, -1e30), axis=-1) h = h + jnp.einsum('hij,jhd->ihd', att, v).reshape(n, d) @ lyr['o'] h = h + jax.nn.gelu(ln(h) @ lyr['m1']) @ lyr['m2'] z = ln(h) return z, z @ p['out'] def src_from_cut(n, starts): """starts: sorted block start positions (first must be 0). Returns src [n] (int, -1 = none).""" starts = list(starts) src = np.full(n, -1, dtype=np.int32) for b in range(1, len(starts)): end = starts[b + 1] if b + 1 < len(starts) else n src[starts[b]:end] = starts[b] - 1 return src def sweep(p, x, z, src): """One Jacobi sweep: every position re-computed in parallel from the previous iterate z.""" has = src >= 0 zin = z[jnp.maximum(src, 0)] return one_pass(p, x, zin, has) def solve(p, x, src, n_sweeps, z0=None): """n_sweeps Jacobi sweeps from z0 (zeros by default). With n_sweeps >= number of blocks the result is the exact fixed point, i.e. what token-by-token decoding computes.""" z = jnp.zeros((x.shape[0], p['emb'].shape[1])) if z0 is None else z0 logits = None for _ in range(n_sweeps): z, logits = sweep(p, x, z, src) return z, logits