import math import os import torch from torch import nn from aio.interface import NCV, NMV, CF, MF, DV as DRIVEN, shape as shape_of, rows as rows_of from aio.actor import Actor, ExpertHead, History, STATE as BASE, TOKEN, MEMORY, pool, symlog, symexp, unpack, state_size as base_size from aio.sim import model as MD from aio.sim.model import NLAB, KNOTS from aio import formula as FM from aio import reader as RD WIDE = int(os.environ.get('AIO_WIDE', '1')) P = 32 * WIDE D = 48 * WIDE ROUNDS = 2 NPAIR = NCV * NMV POLES = (1.5, 4.0, 10.0, 25.0, 60.0, 150.0) NF = len(POLES) FORGET = 200.0 NEAR = 200 NX = NMV * NF NSTAT = 4 * NF + 1 E_CLIP, K_CLIP, K_UNIT, V_CLIP, V_UNIT = (6.0, 5.0, 0.001, 2.0, 0.06) UNSEEN, GAP_UNIT, RATE_UNIT = (2, 1.0, 0.05) SSTAT = 3 * NX + NX * NX + NCV * NX + NCV SSLOW = NX * NX + NCV * NX + NCV NARX = 2 * NF SROW = 3 * NCV * NF SARX = NCV * NF * NX + NCV * NF * NF + NCV * NF A_CLIP = 5.0 NDV = 2 NXD = NDV * NF SDVF = 3 * NXD SDV = NX * NXD + NXD * NXD + NCV * NXD + NCV * NF * NXD SPAIR = NPAIR * 2 * P STATE = BASE + SPAIR + SSTAT def sizes(ncv=NCV, nmv=NMV): nx = nmv * NF return (ncv * nmv, nx, 3 * nx + nx * nx + ncv * nx + ncv, nx * nx + ncv * nx + ncv, 3 * ncv * NF, ncv * NF * nx + ncv * NF * NF + ncv * NF, nx * NXD + NXD * NXD + ncv * NXD + ncv * NF * NXD, ncv * nmv * 2 * P) def _in(i, o): return nn.Sequential(nn.Linear(i, o), nn.LayerNorm(o), nn.SiLU()) def _up(i, o): return nn.Sequential(nn.Linear(i, o), nn.SiLU(), nn.Linear(o, o)) class Stats(nn.Module): def __init__(self, moves=False, slow=0.0, arx=False, dv=False): super().__init__() assert arx or not dv, "the measured disturbances go into the fits with the rows' own past" self.moves = moves self.slow = float(slow) self.arx, self.dv = (bool(arx), bool(dv)) self.rho2 = math.exp(-1 / self.slow) if self.slow > 0 else 0.0 self.sets = 2 if self.slow > 0 else 1 self.size = self.size_of() o = NSTAT + (NF if moves else 0) self.at_slow = slice(o, o + NSTAT) o += NSTAT if self.slow > 0 else 0 self.at_arx = slice(o, o + self.sets * NARX) a = torch.exp(-1 / torch.tensor(POLES)) self.register_buffer('a', a, persistent=False) self.register_buffer('g', torch.sqrt(1 - a * a), persistent=False) self.rho = math.exp(-1 / FORGET) def size_of(self, ncv=NCV, nmv=NMV): _, _, SSTAT, SSLOW, SROW, SARX, SDV, _ = sizes(ncv, nmv) return SSTAT + (SSLOW if self.slow > 0 else 0) + (SROW + self.sets * SARX if self.arx else 0) + (SDVF + self.sets * SDV if self.dv else 0) def bank(self, v, x, w, vp): xs, ws, vs = ([], [], []) for m in range(NF): xs.append(self.a[m] * x[..., m] + self.g[m] * v) ws.append(self.a[m] * w[..., m] + vp[..., m] - self.a[m] * v) vs.append(v) v = ws[-1] return (torch.stack(xs, -1), torch.stack(ws, -1), torch.stack(vs, -1)) @torch.no_grad() def forward(self, obs, state=None): cv, mv, _ = unpack(obs) dy, dp = ((x[..., 1] * x[..., -1]).float().nan_to_num(0.0, 0.0, 0.0).clamp(-1000.0, 1000.0) for x in (cv, mv)) b, T = dy.shape[:2] NCV, NMV = (cv.shape[-2], mv.shape[-2]) _, NX, SSTAT, SSLOW, SROW, SARX, SDV, _ = sizes(NCV, NMV) if state is None: state = dy.new_zeros(b, self.size_of(NCV, NMV)) state = state.float() x, w, vp = (state[:, i * NX:(i + 1) * NX].reshape(b, NMV, NF) for i in range(3)) R = state[:, 3 * NX:3 * NX + NX * NX].reshape(b, NX, NX) c = state[:, 3 * NX + NX * NX:SSTAT - NCV].reshape(b, NCV, NX) E = state[:, SSTAT - NCV:SSTAT] o = SSTAT if self.slow > 0: R2, c2, E2 = (state[:, o:o + NX * NX].reshape(b, NX, NX), state[:, o + NX * NX:o + SSLOW - NCV].reshape(b, NCV, NX), state[:, o + SSLOW - NCV:o + SSLOW]) o += SSLOW if self.arx: yx, yw, yvp = (state[:, o + i * NCV * NF:o + (i + 1) * NCV * NF].reshape(b, NCV, NF) for i in range(3)) o, own = (o + SROW, []) for _ in range(self.sets): own.append([state[:, o:o + NCV * NF * NX].reshape(b, NCV, NF, NX), state[:, o + NCV * NF * NX:o + SARX - NCV * NF].reshape(b, NCV, NF, NF), state[:, o + SARX - NCV * NF:o + SARX].reshape(b, NCV, NF)]) o += SARX ins = [(), ()] if self.dv: zx, zw, zvp = (state[:, o + i * NXD:o + (i + 1) * NXD].reshape(b, NDV, NF) for i in range(3)) o, ins = (o + SDVF, []) for _ in range(self.sets): cut = (0, NX * NXD, NX * NXD + NXD * NXD, NX * NXD + NXD * NXD + NCV * NXD, SDV) ins.append([state[:, o + i:o + j].reshape(b, *shape) for i, j, shape in zip(cut, cut[1:], ((NX, NXD), (NXD, NXD), (NCV, NXD), (NCV, NF, NXD)))]) o += SDV on, at = torch.sort(((cv[..., -1] > 0) & (cv[..., DRIVEN] < 0.5)).float(), dim=-1, descending=True, stable=True) dz = torch.gather(dy, 2, at[..., :NDV]) * on[..., :NDV] out = [] for t in range(T): x, w, vp = self.bank(dp[:, t], x, w, vp) X = x.reshape(b, NX) R = self.rho * R + X[:, :, None] * X[:, None, :] c = self.rho * c + dy[:, t][:, :, None] * X[:, None, :] E = self.rho * E + dy[:, t] ** 2 f = [self.features(R, c, E)] if self.moves: f.append(x[:, None].expand(b, NCV, NMV, NF)) if self.slow > 0: R2 = self.rho2 * R2 + X[:, :, None] * X[:, None, :] c2 = self.rho2 * c2 + dy[:, t][:, :, None] * X[:, None, :] E2 = self.rho2 * E2 + dy[:, t] ** 2 f.append(self.features(R2, c2, E2)) if self.arx: for q, rho in zip(own, (self.rho, self.rho2)): q[0] = rho * q[0] + yx[:, :, :, None] * X[:, None, None, :] q[1] = rho * q[1] + yx[:, :, :, None] * yx[:, :, None, :] q[2] = rho * q[2] + dy[:, t][:, :, None] * yx if self.dv: zx, zw, zvp = self.bank(dz[:, t], zx, zw, zvp) Z = zx.reshape(b, NXD) for q, rho in zip(ins, (self.rho, self.rho2)): q[0] = rho * q[0] + X[:, :, None] * Z[:, None, :] q[1] = rho * q[1] + Z[:, :, None] * Z[:, None, :] q[2] = rho * q[2] + dy[:, t][:, :, None] * Z[:, None, :] q[3] = rho * q[3] + yx[:, :, :, None] * Z[:, None, None, :] yx, yw, yvp = self.bank(dy[:, t], yx, yw, yvp) f.append(self.fit(R, c, *own[0], *ins[0])) if self.slow > 0: f.append(self.fit(R2, c2, *own[1], *ins[1])) out.append(torch.cat(f, -1) if len(f) > 1 else f[0]) state = [x.reshape(b, NX), w.reshape(b, NX), vp.reshape(b, NX), R.reshape(b, NX * NX), c.reshape(b, NCV * NX), E] if self.slow > 0: state += [R2.reshape(b, NX * NX), c2.reshape(b, NCV * NX), E2] if self.arx: state += [yx.reshape(b, NCV * NF), yw.reshape(b, NCV * NF), yvp.reshape(b, NCV * NF)] for P_, Q_, d_ in own: state += [P_.reshape(b, NCV * NF * NX), Q_.reshape(b, NCV * NF * NF), d_.reshape(b, NCV * NF)] if self.dv: state += [zx.reshape(b, NXD), zw.reshape(b, NXD), zvp.reshape(b, NXD)] for q in ins: state += [x_.reshape(b, -1) for x_ in q] return (torch.stack(out, 1), torch.cat(state, -1)) @staticmethod def features(R, c, E): b, NCV, NX = c.shape NMV = NX // NF d = R.diagonal(dim1=1, dim2=2) corr = (c / torch.sqrt(d[:, None, :] * E[:, :, None] + 1e-12)).reshape(b, NCV, NMV, NF) lam = (0.001 * d.mean(-1) + 1e-10).double()[:, None, None] R64, c64 = (R.double(), c.double()) solve = MD.spd_solve joint = solve(R64 + lam * torch.eye(NX, dtype=torch.float64, device=R.device), c64.transpose(1, 2)).transpose(1, 2).reshape(b, NCV, NMV, NF) Rb = R64.reshape(b, NMV, NF, NMV, NF).diagonal(dim1=1, dim2=3).permute(0, 3, 1, 2) alone = solve(Rb + lam[..., None] * torch.eye(NF, dtype=torch.float64, device=R.device), c64.reshape(b, NCV, NMV, NF).permute(0, 2, 3, 1)).permute(0, 3, 1, 2) ld = (torch.log(d + 1e-08) / 8).reshape(b, 1, NMV, NF).expand(b, NCV, NMV, NF) le = (torch.log(E + 1e-08) / 8)[:, :, None, None].expand(b, NCV, NMV, 1) return torch.cat((corr, torch.asinh(joint / 0.45).float(), torch.asinh(alone / 0.45).float(), ld, le), -1) @staticmethod def solve_own(R, c, P, Q, d, Rz=None, Rzz=None, cz=None, Pz=None): (b, NCV, NX), f = (c.shape, torch.float64) NMV, nx = (NX // NF, NX) solve = MD.spd_solve lam = (0.001 * R.diagonal(dim1=1, dim2=2).mean(-1) + 1e-10).to(f)[:, None, None] lam2 = (0.001 * Q.diagonal(dim1=2, dim2=3).mean(-1) + 1e-10).to(f)[:, :, None, None] P64, c64 = (P.to(f), c.to(f)) A = R.to(f) + lam * torch.eye(NX, dtype=f, device=R.device) if Rz is not None: lamz = (0.001 * Rzz.diagonal(dim1=1, dim2=2).mean(-1) + 1e-10).to(f)[:, None, None] A = torch.cat((torch.cat((A, Rz.to(f)), -1), torch.cat((Rz.to(f).transpose(1, 2), Rzz.to(f) + lamz * torch.eye(NXD, dtype=f, device=R.device)), -1)), 1) P64, c64, nx = (torch.cat((P64, Pz.to(f)), -1), torch.cat((c64, cz.to(f)), -1), NX + NXD) W = solve(A, torch.cat((c64.transpose(1, 2), P64.reshape(b, NCV * NF, nx).transpose(1, 2)), -1)) Wc, Wp = (W[..., :NCV].transpose(1, 2), W[..., NCV:].transpose(1, 2).reshape(b, NCV, NF, nx)) left = Q.to(f) + lam2 * torch.eye(NF, dtype=f, device=R.device) - torch.einsum('bimx,binx->bimn', P64, Wp) ta = solve(left, (d.to(f) - torch.einsum('bimx,bix->bim', P64, Wc))[..., None])[..., 0] tb = Wc - torch.einsum('bim,bimx->bix', ta, Wp) if Rz is not None: return (tb[..., :NX].reshape(b, NCV, NMV, NF), ta, tb[..., NX:].reshape(b, NCV, NDV, NF)) return (tb.reshape(b, NCV, NMV, NF), ta) @staticmethod def fit(R, c, P, Q, d, *dv): tb, ta = Stats.solve_own(R, c, P, Q, d, *dv)[:2] NMV = tb.shape[2] return torch.cat((torch.asinh(tb / 0.45).float(), ta.clamp(-A_CLIP, A_CLIP).float()[:, :, None, :].expand(-1, -1, NMV, -1)), -1) @staticmethod def response(tb, ta, lags): b, f = (tb.shape[0], torch.float64) a = torch.exp(-1 / torch.tensor(POLES, dtype=f, device=tb.device)) g = torch.sqrt(1 - a * a) def bank(v, x, w, vp): xs, ws, vs = ([], [], []) for m in range(NF): xs.append(a[m] * x[..., m] + g[m] * v) ws.append(a[m] * w[..., m] + vp[..., m] - a[m] * v) vs.append(v) v = ws[-1] return (torch.stack(xs, -1), torch.stack(ws, -1), torch.stack(vs, -1)) mvs = [torch.zeros(NF, dtype=f, device=tb.device) for _ in range(3)] own = [torch.zeros(tb.shape, dtype=f, device=tb.device) for _ in range(3)] y, out = (torch.zeros(tb.shape[:-1], dtype=f, device=tb.device), []) for t in range(max(lags)): mvs = bank(torch.tensor(1.0 if t == 0 else 0.0, dtype=f, device=tb.device), *mvs) dy = ((tb.to(f) * mvs[0]).sum(-1) + (own[0] * ta.to(f)[:, :, None, :]).sum(-1)).clamp(-1000.0, 1000.0) own = bank(dy, *own) y = (y + dy).clamp(-1000.0, 1000.0) if t + 1 in lags: out.append(y) return torch.stack(out, -1).float() / 0.45 def _grown_stat(module, keys): keys.missing_keys[:] = [k for k in keys.missing_keys if not {'stat', 'stat2', 'slow', 'stat3', 'arx', 'dvs', 'unseen', 'unseen_in', 'told_in'} & set(k.split('.'))] def has_stats(pairs): return any(('stat' in k.split('.') for k in pairs)) def slow_of(pairs): return float(pairs['slow']) if 'slow' in pairs else 0.0 def arx_of(pairs): return 'arx' in pairs def dv_of(pairs): return 'dvs' in pairs def unseen_of(pairs): return 'unseen.weight' in pairs def apart_of(pairs): return law_of(pairs) and 'law_in.weight' not in pairs def reader_of(pairs): if not any((k.startswith('reader.') for k in pairs)): return False asked = ['const'] * ('reader.A0' in pairs) + (['rounds%d' % int(pairs['reader.nround'])] if 'reader.nround' in pairs else []) k, v, w = (pairs['reader.pole'].shape[0], pairs['reader.val0.weight'].shape[0], pairs['reader.key.0.weight'].shape[0]) asked += ['k%d' % k] * (k != RD.K) + ['v%d' % v] * (v != RD.V) + ['w%d' % w] * (w != 48) return ','.join(asked) or True def told_of(pairs): return 'told_in.weight' in pairs def law_of(pairs): return any((k.startswith('heading.') for k in pairs)) def knots_of(pairs): return int(pairs['read.2.weight'].shape[0]) def worked_of(pairs): return (law_of(pairs) and (not given_of(pairs)) and (pairs['heading.2.weight'].shape[0] == NLAB + 1), law_of(pairs) and (not any((k.startswith('gain.') for k in pairs)))) def hybrid_of(pairs): return worked_of(pairs)[0] and any((k.startswith('kern.') for k in pairs)) def given_of(pairs): return any((k.startswith('adjust.') for k in pairs)) def tied_of(pairs): return int(pairs['rounds']) if 'rounds' in pairs else 0 def diff_of(pairs): return ''.join((q for q in 'SE' if 'diff_' + q in pairs)) def values_of(d, clip): top = math.asinh(2 * math.sinh(clip)) return torch.asinh(torch.cumsum(torch.sinh(d.float().clamp(-top, top)), -1)) class PairNet(nn.Module): def __init__(self, stats=True, tied=0, law=False, knots=NLAB, formula=False, solve=False, given=False, slow=0.0, arx=False, dv=False, diff='', unseen=False, told=False, reader=False, apart=None, hybrid=False): super().__init__() assert stats or not (slow or arx), "the slow sums are a second set of the running sums, the rows' own past a second fit of them" assert not reader or not (stats or formula or solve or given), 'the learned reader (aio.reader) is in place of the running sums and of every formula' self.apart = bool(law and (reader if apart is None else apart)) assert arx or not dv, "the measured disturbances go into the fits with the rows' own past" given = law and given self.reader = None formula, solve = (formula and (not given), solve and (not given)) self.hybrid = hybrid = bool(law and formula and hybrid) self.nk = NK = len(KNOTS[knots]) self.inp = _in(CF + MF + 2, P) self.gru1 = nn.GRU(P, P, batch_first=True) self.gru2 = nn.GRU(3 * P, P, batch_first=True) self.read = nn.Sequential(nn.Linear(P, 2 * P), nn.SiLU(), nn.Linear(2 * P, NK)) self.edge = _in(NK + 1 + P, D) self.row0, self.mv0 = (_in(TOKEN, D), _in(TOKEN, D)) self.tied = tied if tied: self.register_buffer('rounds', torch.tensor(tied)) self.gate_row, self.gate_mv = (nn.Linear(D + NK + 1, D), nn.Linear(D + NK + 1, D)) self.say_row, self.say_mv = (nn.Linear(D, D), nn.Linear(D, D)) self.up_row, self.up_mv = (_up(2 * D, D), _up(2 * D, D)) for q in (self.up_row, self.up_mv): q[-1].weight.data.mul_(0.1) q[-1].bias.data.zero_() else: self.to_row = nn.ModuleList([_in(2 * D, D) for _ in range(ROUNDS)]) self.to_mv = nn.ModuleList([_in(2 * D, D) for _ in range(ROUNDS)]) self.up_row = nn.ModuleList([_up(2 * D, D) for _ in range(ROUNDS)]) self.up_mv = nn.ModuleList([_up(2 * D, D) for _ in range(ROUNDS)]) self.out = nn.Linear(D, TOKEN) nn.init.zeros_(self.out.weight) nn.init.zeros_(self.out.bias) self.stats = None if stats: self.stats, self.stat = (Stats(moves=law and (not formula or hybrid), slow=slow, arx=arx, dv=dv), _up(NSTAT, P)) nn.init.zeros_(self.stat[-1].weight) nn.init.zeros_(self.stat[-1].bias) self.register_load_state_dict_post_hook(_grown_stat) self.law, self.read_law, self.read_given = (law, None, None) self.worked, self.solve, self.given = (law and (formula or given), law and (solve or given), given) self.fm = FM.Formula(KNOTS[knots]) if self.worked or self.solve else None self.size = self.size_of() if law: assert stats or formula or reader, 'the law reads the filtered moves of the running sums' if formula: self.heading = nn.Sequential(nn.Linear(D + NLAB + 2 + (NLAB if hybrid else 0), 2 * D), nn.SiLU(), nn.Linear(2 * D, NLAB + 1)) nn.init.zeros_(self.heading[-1].weight) nn.init.zeros_(self.heading[-1].bias) if hybrid: assert stats, 'the learned kernel reads the filtered moves of the running sums' self.nf = NF self.kern = nn.Sequential(nn.Linear(NK + 1 + P, 2 * P), nn.SiLU(), nn.Linear(2 * P, NLAB * self.nf)) else: self.nf = RD.spec(reader).get('k', RD.K) if reader else NF self.kern = nn.Sequential(nn.Linear(NK + 1 + P, 2 * P), nn.SiLU(), nn.Linear(2 * P, NLAB * self.nf)) self.heading = nn.Sequential(nn.Linear(D + NLAB, 2 * D), nn.SiLU(), nn.Linear(2 * D, NLAB)) if given: self.adjust = nn.Sequential(nn.Linear(D + NLAB + 2, 2 * D), nn.SiLU(), nn.Linear(2 * D, NLAB + 1)) nn.init.zeros_(self.adjust[-1].weight) nn.init.zeros_(self.adjust[-1].bias) if not solve: self.gain = nn.Sequential(nn.Linear(3 * D, 2 * D), nn.SiLU(), nn.Linear(2 * D, NLAB)) self.valve = nn.Sequential(nn.Linear(D, D), nn.SiLU(), nn.Linear(D, 1)) if not self.apart: self.law_in = nn.Linear(2, TOKEN) nn.init.zeros_(self.law_in.weight) nn.init.zeros_(self.law_in.bias) if slow: self.register_buffer('slow', torch.tensor(float(slow))) self.stat2 = _up(NSTAT, P) nn.init.zeros_(self.stat2[-1].weight) nn.init.zeros_(self.stat2[-1].bias) if arx: self.register_buffer('arx', torch.tensor(1.0)) self.stat3 = _up(2 * NARX, P) nn.init.zeros_(self.stat3[-1].weight) nn.init.zeros_(self.stat3[-1].bias) if dv: self.register_buffer('dvs', torch.tensor(1.0)) assert not set(diff) - set('SE') and ('E' not in diff or (law and (not self.worked))), 'diff: S (the responses), E (the E read-out that learns, with law)' self.diff = ''.join((q for q in 'SE' if q in diff)) for q in self.diff: self.register_buffer('diff_' + q, torch.tensor(1.0)) self.unseen, self.read_unseen = (None, None) if unseen: assert law and (not self.worked), 'unseen: beside the E read-out that learns (with law)' self.unseen, self.unseen_in = (nn.Linear(D, UNSEEN), nn.Linear(UNSEEN, 2 * D, bias=False)) nn.init.zeros_(self.unseen_in.weight) if reader: self.reader = RD.Reader(out=P, **RD.spec(reader)) self.size = self.size_of() if WIDE > 1: self.register_buffer('wide', torch.tensor(WIDE)) self.told_in = None if told: self.told_in = nn.Linear(1, D, bias=False) nn.init.zeros_(self.told_in.weight) def size_of(self, ncv=NCV, nmv=NMV): s = sizes(ncv, nmv) return s[7] + (self.reader.size_of(ncv, nmv) if self.reader is not None else s[2] if self.stats is None else self.stats.size_of(ncv, nmv)) + (FM.SMEM if self.fm is not None else 0) def forward(self, obs, previous, ce, me, state, code=None, feats=None): cv, mv, links = unpack(obs) b, T, NK = (obs.shape[0], obs.shape[1], self.nk) NCV, NMV = (cv.shape[-2], mv.shape[-2]) NPAIR, _, SSTAT, _, _, _, _, SPAIR = sizes(NCV, NMV) assert self.fm is None or NPAIR == sizes()[0], 'the formula (aio.formula) is written for the default size alone' ns = self.reader.size_of(NCV, NMV) if self.reader is not None else SSTAT if self.stats is None else self.stats.size_of(NCV, NMV) hp, hs, hf = (state[:, :SPAIR].reshape(b, NPAIR, 2 * P), state[:, SPAIR:SPAIR + ns], state[:, SPAIR + ns:]) seen = None if self.reader is not None: seen, hs = self.reader(obs, previous, hs) hs = hs.to(state.dtype) if self.stats is None: feats = None elif feats is None: feats, hs = self.stats(obs, hs) hs = hs.to(state.dtype) cm, mm = (cv[..., -1], mv[..., -1]) alive = cm[..., :, None] * mm[..., None, :] there = alive.amax(1) > 0 bi, ci, mi = there.nonzero(as_tuple=True) if bi.numel() == 0: return (obs.new_zeros(b, T, NMV, TOKEN), obs.new_zeros(b, T, NCV, NMV, NK), torch.cat((hp.reshape(b, SPAIR), hs, hf), -1)) on = alive[bi, :, ci, mi][..., None] link = links[bi, :, ci, mi][..., None] x = torch.cat((symlog(cv * cm[..., None])[bi, :, ci], symlog(mv * mm[..., None])[bi, :, mi], previous[bi, :, mi][..., None], link), -1) pi = ci * NMV + mi h = hp[bi, pi] xin = self.inp(x) if seen is not None: xin = xin + seen[bi, :, ci, mi].to(xin.dtype) if feats is not None: xin = xin + self.stat(feats[bi, :, ci, mi][..., :NSTAT].to(xin.dtype)) if self.stats.slow > 0: xin = xin + self.stat2(feats[bi, :, ci, mi][..., self.stats.at_slow].to(xin.dtype)) if self.stats.arx: fa = feats[bi, :, ci, mi][..., self.stats.at_arx].to(xin.dtype) xin = xin + self.stat3(fa if self.stats.sets == 2 else torch.cat((fa, torch.zeros_like(fa)), -1)) o1, h1 = self.gru1(xin, h[None, :, :P].contiguous()) o1 = o1 * on dense = o1.new_zeros(b, NCV, NMV, T, P).index_put((bi, ci, mi), o1) cnt = there.to(o1.dtype) rmean = dense.sum(2) / cnt.sum(2).clamp_min(1)[..., None, None] cmean = dense.sum(1) / cnt.sum(1).clamp_min(1)[..., None, None] o2, h2 = self.gru2(torch.cat((o1, rmean[bi, ci], cmean[bi, mi]), -1), h[None, :, P:].contiguous()) est = self.read(o2) if 'S' in self.diff: est = values_of(est, FM.S_CLIP).to(est.dtype) lab = est.new_zeros(b, NCV, NMV, T, NK).index_put((bi, ci, mi), est * on).permute(0, 3, 1, 2, 4) if code is not None: w = code[1].to(est.dtype)[bi][:, None, None] est = w * code[0].permute(0, 2, 3, 1, 4)[bi, ci, mi].to(est.dtype) + (1 - w) * est e = self.edge(torch.cat((est, link, o2), -1)) * on if self.told_in is not None and code is not None: e = e + self.told_in(w) * on cmT, mmT = (cm.transpose(1, 2)[..., None], mm.transpose(1, 2)[..., None]) r, m = (self.row0(ce).transpose(1, 2) * cmT, self.mv0(me).transpose(1, 2) * mmT) nr, nc = (cnt.sum(2).clamp_min(1).sqrt()[..., None, None], cnt.sum(1).clamp_min(1).sqrt()[..., None, None]) if self.tied: ge = torch.cat((e, est, link), -1) gr, gm = (self.gate_row(ge) * on, self.gate_mv(ge) * on) for k in range(self.tied): agg = torch.zeros_like(r).index_put((bi, ci), gr * self.say_mv(m)[bi, mi], accumulate=True) / nr ** 2 r = r + self.up_row(torch.cat((r, agg), -1)) * cmT agg = torch.zeros_like(m).index_put((bi, mi), gm * self.say_row(r)[bi, ci], accumulate=True) / nc ** 2 m = m + self.up_mv(torch.cat((m, agg), -1)) * mmT for k in range(0 if self.tied else ROUNDS): msg = self.to_row[k](torch.cat((e, m[bi, mi]), -1)) * on agg = torch.zeros_like(r).index_put((bi, ci), msg, accumulate=True) / nr r = r + self.up_row[k](torch.cat((r, agg), -1)) * cmT msg = self.to_mv[k](torch.cat((e, r[bi, ci]), -1)) * on agg = torch.zeros_like(m).index_put((bi, mi), msg, accumulate=True) / nc m = m + self.up_mv[k](torch.cat((m, agg), -1)) * mmT hp = hp.index_put((bi, pi), torch.cat((h1[0], h2[0]), -1)) dj = self.out(m) if self.law: told = code is not None and len(code) > 2 and (not self.given) wb = code[1].to(dj.dtype)[:, None, None] if code is not None else None sel = (code[1] > 0).nonzero()[:, 0] if self.given and code is not None else None sel = None if sel is None or sel.numel() == 0 else sel g = wb.float() if sel is not None else None work = self.fm is not None and (sel is not None or not self.given) if self.fm is not None: mem, hf = self.fm.memory(obs, hf) hf = hf.to(state.dtype) if work: Sd = torch.sinh(est.float().clamp(-FM.S_CLIP, FM.S_CLIP)) * on Sd = Sd.new_zeros(b, NCV, NMV, T, NK).index_put((bi, ci, mi), Sd).permute(0, 3, 1, 2, 4) of = (lambda x: x) if sel is None else lambda x: None if x is None else x[sel] back = (lambda x: x) if sel is None else lambda x: x.new_zeros((b,) + x.shape[1:]).index_copy(0, sel, x) ob, Sd, mem = (of(obs), of(Sd), tuple((of(x) for x in mem))) Ef = El = None if self.worked and work: Ew, rate, lev = (x.transpose(1, 2) for x in self.fm.heading(ob, Sd, mem)) rs, also = (of(r), ()) if self.hybrid: xf = feats[bi, :, ci, mi][..., NSTAT:NSTAT + NF].to(e.dtype) pk = (self.kern(torch.cat((est, link, o2), -1)).unflatten(-1, (NLAB, self.nf)) * xf[..., None, :]).sum(-1) * on also = (torch.asinh(of(torch.zeros_like(r[..., :NLAB]).index_put((bi, ci), pk, accumulate=True))),) h = (self.adjust if self.given else self.heading)(torch.cat((rs,) + also + (torch.asinh(Ew).to(r.dtype), torch.asinh(rate)[..., None].to(r.dtype), lev[..., None].to(r.dtype)), -1)).float() Ef = back(torch.asinh(2 * torch.sigmoid(h[..., -1:]) * Ew + torch.sinh(h[..., :-1].clamp(-E_CLIP, E_CLIP))) * of(cmT)) if not self.worked or self.given: xf = (self.reader.keys[bi, :, mi] if self.reader is not None else feats[bi, :, ci, mi][..., NSTAT:NSTAT + NF]).to(e.dtype) pend = (self.kern(torch.cat((est, link, o2), -1)).unflatten(-1, (NLAB, self.nf)) * xf[..., None, :]).sum(-1) * on pend = torch.zeros_like(r[..., :NLAB]).index_put((bi, ci), pend, accumulate=True) if self.unseen is None: El = self.heading(torch.cat((r, torch.asinh(pend)), -1)) else: uh = self.unseen(r) * cmT U = uh.detach() if told and len(code) > 5: U = wb[..., None] * code[5].transpose(1, 2).to(uh.dtype) + (1 - wb[..., None]) * U El = self.heading[2](self.heading[1](self.heading[0](torch.cat((r, torch.asinh(pend)), -1)) + self.unseen_in(torch.asinh(U)))) self.read_unseen = uh.transpose(1, 2) if 'E' in self.diff: El = values_of(El, E_CLIP).to(El.dtype) El = El * cmT eh = E = Ef if El is None else El if told and (not self.worked): E = wb[..., None] * code[2].transpose(1, 2).to(eh.dtype) + (1 - wb[..., None]) * eh elif Ef is not None and El is not None: E = g[..., None] * Ef + (1 - g[..., None]) * El.float() Es = torch.sinh(E.float().clamp(-E_CLIP, E_CLIP)) kh = vh = ms = ml = None if self.solve and work: ms = back(self.fm.move(ob, Sd, of(Es).transpose(1, 2), mem).transpose(1, 2)) if not self.solve or self.given: kh = self.gain(torch.cat((e, r[bi, ci], m[bi, mi]), -1)) * on vh = self.valve(m)[..., 0] * mmT[..., 0] K, V = (kh, vh) if told: K = w * code[3].permute(0, 2, 3, 1, 4)[bi, ci, mi].to(kh.dtype) + (1 - w) * kh V = wb * code[4].transpose(1, 2).to(vh.dtype) + (1 - wb) * vh prod = (K_UNIT * torch.sinh(K.float().clamp(-K_CLIP, K_CLIP)) * Es[bi, ci]).sum(-1) * on[..., 0] ml = torch.zeros_like(m[..., 0], dtype=prod.dtype).index_put((bi, mi), prod, accumulate=True) ml = ml / (V_UNIT * torch.exp(V.float().clamp(-V_CLIP, V_CLIP))) kh, vh = (kh.new_zeros(b, NCV, NMV, T, NLAB).index_put((bi, ci, mi), kh).permute(0, 3, 1, 2, 4), vh.transpose(1, 2)) mv = ml if ms is None else ms if ml is None else g * ms + (1 - g) * ml self.read_given = Ef.transpose(1, 2) if self.given and Ef is not None else None if not self.apart: dj = dj + self.law_in(torch.stack((torch.asinh(mv), mv.clamp(-1.0, 1.0)), -1).to(dj.dtype)) * mmT self.read_law = (eh.transpose(1, 2), kh, vh, mv.transpose(1, 2)) return (dj.transpose(1, 2), lab, torch.cat((hp.reshape(b, SPAIR), hs, hf), -1)) def trunk(hist, pairs, obs, previous, hidden=None, code=None, feats=None): ncv, nmv = shape_of(obs.shape[-1]) BASE = base_size(ncv, nmv) b, size = (obs.shape[0], BASE + pairs.size_of(ncv, nmv)) if hidden is None: hidden = obs.new_zeros(1, b, size) elif hidden.shape[-1] < size: hidden = torch.cat((hidden, hidden.new_zeros(1, b, size - hidden.shape[-1])), -1) hg, ht = (hidden[..., :MEMORY].contiguous(), hidden[..., MEMORY:BASE].contiguous()) ce, me, cm, mm, links = hist.channels.embed(obs, previous) ce, me, _, ht = hist.tokens(ce, me, cm, mm, links, ht) joint, x, mask = hist.channels.combine(ce, me, cm, mm, links) memory, hg = hist.gru(x, hg) dj, lab, hp = pairs(obs, previous, ce, me, hidden[0, :, BASE:], code, feats) return (joint + dj * mm[..., None], memory, mask, lab, torch.cat((hg, ht, hp[None]), -1)) class AIO(nn.Module): canonical = True def __init__(self, stats=True, tied=0, law=False, knots=NLAB, formula=False, solve=False, given=False, slow=0.0, arx=False, dv=False, diff='', unseen=False, told=False, reader=False, apart=None, hybrid=False): super().__init__() self.actor = Actor() self.pairs = PairNet(stats, tied, law, knots, formula, solve, given, slow, arx, dv, diff, unseen, told, reader, apart, hybrid) def steps(self, obs, previous, hidden=None, code=None, feats=None): joint, memory, mask, lab, hidden = trunk(self.actor.history, self.pairs, obs, previous, hidden, code, feats) out = self.actor.head(self.actor.head_input(joint, memory))[0].float() return (out[..., 0] * mask, out[..., 1], mask, lab, hidden) def state_size(self, ncv=NCV, nmv=NMV): return base_size(ncv, nmv) + self.pairs.size_of(ncv, nmv) def legacy(self): return _Legacy(self) class _Legacy: canonical = True def __init__(self, net): self.net = net def history(self, obs, previous, hidden): mean, _, mask, _, hidden = self.net.steps(obs, previous, hidden) return (mean[..., None], None, mask, hidden) def distribution(self, joint, memory, mask): return (joint[..., 0] * mask, torch.zeros_like(joint[..., 0]), None) def eval(self): self.net.eval() return self def train(self, mode=True): self.net.train(mode) return self PRIV_CV, PRIV_MV, PRIV_EDGE, PRIV_G = (25, 10, 4, 2) _PRIV_P_KEYS = ('K', 'dead', 'p1r', 'c0r', 'c1r', 'c0i', 'c1i') _PRIV_T_KEYS = ('cvw', 'ulo', 'uhi') _PRIV_C_KEYS = ('bandf', 'rowm', 'prc', 'trk', 'zon', 'mvm', 'integ', 'rst', 'tint', 'lam', 'vc', 'slew', 'link', 'jload', 'uref', 'kap', 'warp') _PRIV_ST_KEYS = ('yt', 'v', 'fl', 'l1', 'l2', 'sr', 'si', 'buf', 'target', 'u', 'ua', 'xv', 'prev_u', 'd', 'fail', 'thist', 'alo', 'ahi', 'lo', 'hi', 'rhist') _PRIV_COMPILE = None _PRIV_COMPILE_CPU = False _PRIV_COMPILED_PROG = None _PRIV_COMPILED_CTX = None def probing(second): return second - 2.0 class Controller: def __init__(self, net): self.net, self.probe, self.unpaired = (net, float(getattr(net, 'probe', 0.0)), blind_main(net)) self.reset() def reset(self): self.h, self.prev = (None, None) self.g = torch.Generator().manual_seed(0) @torch.no_grad() def step(self, packet): from aio.frame import canonical o, s = canonical(torch.as_tensor(packet, dtype=torch.float32)[None], torch.ones(1, dtype=torch.bool) if self.unpaired else None) if self.prev is None: self.prev = torch.zeros(1, shape_of(o.shape[-1])[1]) mean, second, mask, _, self.h = self.net.steps(o[:, None], self.prev[:, None], self.h) z = mean[:, 0] if self.probe and (self.unpaired or not getattr(self.net, 'unpaired', 0.0)): z = z + self.probe * (probing(second[:, 0]) > 0) * torch.randn(z.shape, generator=self.g) self.prev = torch.tanh(z) * mask[:, 0] return (self.prev * s)[0].numpy() def blind_main(net): return float(getattr(net, 'unpaired', 0.0)) >= 0.5 def of_state(actor, pairs=None, config=None, device='cpu'): if pairs is not None and 'seq' in pairs: from aio import seqnet as SQ asked, w = SQ.of_buffer(pairs['seq']) net = SQ.SeqAIO(asked, w, actor['read.2.weight'].shape[0]) net.actor.load_state_dict(actor) net.probe, net.unpaired = (float((config or {}).get('probe') or 0.0), float((config or {}).get('unpaired') or 0.0)) net.meter = bool((config or {}).get('meter', False)) return net.to(device).eval() kw = dict(zip(('formula', 'solve'), worked_of(pairs)), knots=knots_of(pairs), law=law_of(pairs), tied=tied_of(pairs), given=given_of(pairs), slow=slow_of(pairs), arx=arx_of(pairs), dv=dv_of(pairs), diff=diff_of(pairs), unseen=unseen_of(pairs), told=told_of(pairs), reader=reader_of(pairs), apart=apart_of(pairs), hybrid=hybrid_of(pairs)) if pairs is not None else {} wide = int(pairs['wide']) if pairs is not None and 'wide' in pairs else 1 assert wide == WIDE, f'these weights have the pair pathway {wide} times as wide: run with AIO_WIDE={wide} in the environment' net = AIO(stats=pairs is not None and has_stats(pairs), **kw) net.actor.load_state_dict(actor) if pairs is not None: net.pairs.load_state_dict(pairs) net.probe = float((config or {}).get('probe') or 0.0) net.unpaired = float((config or {}).get('unpaired') or 0.0) net.meter = bool((config or {}).get('meter', False)) return net.to(device).eval() def released(path, device='cpu'): import json from pathlib import Path from safetensors.torch import load_file state = load_file(str(Path(path) / 'model.safetensors')) def part(prefix): return {k[len(prefix):]: v for k, v in state.items() if k.startswith(prefix)} return of_state(part('actor.'), part('pairs.') or None, json.loads((Path(path) / 'config.json').read_text(encoding='utf-8')), device)