Datasets:
File size: 10,308 Bytes
222d213 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | """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+-%=<!&?CPMDS" # also the (length, lexicographic) order of programs
NUM, BOOL = "N", "B" # a boolean is a number that is 0 or 1; it can be used wherever a number can
ATTENTION = frozenset("CPM")
ARITY = {**{s: 0 for s in "T0123"}, **{s: 1 for s in "!CP"}, **{s: 2 for s in "+-%=<&"}, **{s: 3 for s in "?M"}}
def result_type(sym, arg_types):
"""Type of sym applied to arg_types (in push order), or None when the types do not fit."""
if sym == "T" or sym in "23":
return NUM
if sym in "01":
return BOOL
if sym in "+-%":
return NUM
if sym in "=<":
return BOOL
if sym in "!&":
return BOOL if all(t == BOOL for t in arg_types) else None
if sym == "?":
c, a, b = arg_types
if c != BOOL:
return None
return BOOL if a == b == BOOL else NUM
if sym == "C":
return NUM if arg_types[0] == BOOL else None
if sym == "P":
return arg_types[0]
if sym == "M":
return arg_types[2]
raise ValueError(sym)
def compile_program(prog):
"""Program string -> (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]
|