"""bf-rasp v0: a compact RASP variant written as stack (postfix) strings. Language reference: README.md. A program is a string over ALPHABET. Reading left to right, each symbol pops its inputs from a stack of columns (one value per position, bytes mod 256) and pushes its result. A valid program type-checks and leaves exactly one column; at each position its value is the next token. Generation starts from the single token 0 and has no input. This module holds the language definition and three evaluators that must agree: evaluate reference: whole columns from the definitions, plain lists, O(n^2) attention; obviously correct generate incremental: one position at a time with running state, O(length) per token (used for outputs) evaluate_np numpy over a batch of sequences (used by the enumerator to fingerprint columns) """ import numpy as np ALPHABET = "T0123+-%= (nodes, types, top). nodes[i] = (symbol, input node indices in push order); D and S only rewire the stack and make no node. Raises ValueError for an invalid program.""" nodes, types, stack = [], [], [] for pos, s in enumerate(prog): if s == "D": if not stack: raise ValueError(f"D on an empty stack at {pos}") stack.append(stack[-1]) elif s == "S": if len(stack) < 2: raise ValueError(f"S needs two columns at {pos}") stack[-1], stack[-2] = stack[-2], stack[-1] elif s in ARITY: k = ARITY[s] if len(stack) < k: raise ValueError(f"{s} needs {k} columns at {pos}") args = tuple(stack[len(stack) - k:]) if k else () del stack[len(stack) - k:] t = result_type(s, [types[a] for a in args]) if t is None: raise ValueError(f"{s} has the wrong input types at {pos}") nodes.append((s, args)); types.append(t); stack.append(len(nodes) - 1) else: raise ValueError(f"unknown symbol {s!r} at {pos}") if len(stack) != 1: raise ValueError(f"program leaves {len(stack)} columns") return nodes, types, stack[0] def is_valid(prog): try: compile_program(prog) return True except ValueError: return False def measures(prog): """length; depth = most attention symbols on any path to the output (transformer layers); n_attn = attention symbols; width = most attention symbols at one depth (heads per layer).""" nodes, _, top = compile_program(prog) depth = [] for s, args in nodes: d = max((depth[a] for a in args), default=0) depth.append(d + (s in ATTENTION)) per_layer = {} for (s, _), d in zip(nodes, depth): if s in ATTENTION: per_layer[d] = per_layer.get(d, 0) + 1 return {"length": len(prog), "depth": depth[top], "n_attn": sum(per_layer.values()), "width": max(per_layer.values(), default=0)} # ---------------------------------------------------------------- reference evaluator (definitions, plain lists) def evaluate(prog, seq): """Output column (one value per position) of prog on the token sequence seq.""" nodes, _, top = compile_program(prog) n, cols = len(seq), [] for s, args in nodes: x = [cols[a] for a in args] if s == "T": c = [int(v) % 256 for v in seq] elif s in "0123": c = [int(s)] * n elif s == "+": c = [(a + b) % 256 for a, b in zip(*x)] elif s == "-": c = [(a - b) % 256 for a, b in zip(*x)] elif s == "%": c = [a % b if b else a for a, b in zip(*x)] elif s == "=": c = [int(a == b) for a, b in zip(*x)] elif s == "<": c = [int(a < b) for a, b in zip(*x)] elif s == "!": c = [1 - a for a in x[0]] elif s == "&": c = [a & b for a, b in zip(*x)] elif s == "?": c = [a if t else b for t, a, b in zip(*x)] elif s == "C": # count of k <= q where b[k] is true c = [sum(x[0][:q + 1]) % 256 for q in range(n)] elif s == "P": # value one position back; 0 at position 0 c = [0] + x[0][:-1] elif s == "M": # V at the latest k < q with K[k] = Q[q]; 0 if there is none K, Q, V = x c = [] for q in range(n): v = 0 for k in range(q): if K[k] == Q[q]: v = V[k] c.append(v) cols.append(c) return cols[top] def generate_reference(prog, T): """The first T generated tokens, re-evaluating the whole sequence at every step (slow; for tests).""" seq = [0] for _ in range(T): seq.append(evaluate(prog, seq)[-1]) return seq[1:] def produces(prog, y): """Teacher forcing: prog generates y (as its first len(y) tokens) iff its column on 0, y[:-1] equals y.""" return evaluate(prog, [0] + list(y[:-1])) == list(y) # ---------------------------------------------------------------- incremental generator def generate(prog, T): """The first T generated tokens, as bytes. Keeps per-node running state: a count for C, the previous input value for P, and for M a table from key to the value at its latest position (updated after the lookup, so only k < q are visible).""" nodes, _, top = compile_program(prog) state = [0 if s in "CP" else ({} if s == "M" else None) for s, _ in nodes] out, x, v = bytearray(), 0, [0] * len(nodes) for _ in range(T): for i, (s, args) in enumerate(nodes): if s == "T": r = x elif s in "0123": r = ord(s) - 48 elif s == "+": r = (v[args[0]] + v[args[1]]) & 255 elif s == "-": r = (v[args[0]] - v[args[1]]) & 255 elif s == "%": b = v[args[1]] r = v[args[0]] % b if b else v[args[0]] elif s == "=": r = int(v[args[0]] == v[args[1]]) elif s == "<": r = int(v[args[0]] < v[args[1]]) elif s == "!": r = 1 - v[args[0]] elif s == "&": r = v[args[0]] & v[args[1]] elif s == "?": r = v[args[1]] if v[args[0]] else v[args[2]] elif s == "C": r = state[i] = (state[i] + v[args[0]]) & 255 elif s == "P": r = state[i]; state[i] = v[args[0]] else: # M table = state[i] r = table.get(v[args[1]], 0) table[v[args[0]]] = v[args[2]] v[i] = r x = v[top] out.append(x) return bytes(out) # ---------------------------------------------------------------- numpy evaluator over a batch of sequences def apply_np(sym, args, seqs): """Column of sym on numpy uint8 input columns args (each [batch, n]); seqs is the token batch (for T).""" shape = seqs.shape if sym == "T": return seqs if sym in "0123": return np.full(shape, int(sym), np.uint8) if sym == "+": return args[0] + args[1] # uint8 arithmetic wraps mod 256 if sym == "-": return args[0] - args[1] if sym == "%": a, b = args return np.where(b == 0, a, a % np.maximum(b, 1)).astype(np.uint8) if sym == "=": return (args[0] == args[1]).astype(np.uint8) if sym == "<": return (args[0] < args[1]).astype(np.uint8) if sym == "!": return 1 - args[0] if sym == "&": return args[0] & args[1] if sym == "?": return np.where(args[0] != 0, args[1], args[2]) if sym == "C": return (np.cumsum(args[0], axis=1, dtype=np.int64) & 255).astype(np.uint8) if sym == "P": out = np.zeros(shape, np.uint8) out[:, 1:] = args[0][:, :-1] return out if sym == "M": # Sort the keys by (row, value, position); a query (row, Q[q], q) lands just after the latest k < q with the # same row and value, if there is one. O(n log n) per row, so long sequences are fine. K, Q, V = args b, n = shape base = (np.arange(b, dtype=np.int64)[:, None] * 256 * n) pos = np.arange(n, dtype=np.int64)[None, :] keys = (base + K.astype(np.int64) * n + pos).ravel() order = np.argsort(keys, kind="stable") sk = keys[order] queries = (base + Q.astype(np.int64) * n + pos).ravel() j = np.searchsorted(sk, queries, side="left") - 1 # last key strictly below the query jj = np.maximum(j, 0) hit = (j >= 0) & (sk[jj] // n == queries // n) # same row and value, and position < q return np.where(hit, V.ravel()[order[jj]], 0).reshape(shape).astype(np.uint8) raise ValueError(sym) def evaluate_np(prog, seqs): nodes, _, top = compile_program(prog) cols = [] for s, args in nodes: cols.append(apply_np(s, [cols[a] for a in args], seqs)) return cols[top]