Code and pre-registered analysis, uploaded at launch before any result
Browse filesFiles changed (6)
- code/ring.pyAdded+255
- code/ring_analyze.pyAdded+139
- code/ring_job.pyAdded+202
- code/ring_run.shAdded+30
- code/strange_loop.pyAdded+479
- code/vast_self.shAdded+15
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""The ring: a latent loop that keeps a model of itself, run beside the controls that would expose it as plain feedback.
Part 1 and 2 fed back a summary of what the model had said. Its "self-model" was about content, and everything passedthrough sampled words. The ring changes all three things the review found missing:
Substrate, no words in the loop After a short chat prompt that opens the assistant's thinking, the model runs one placeholder token at a time. At every step the J-space content it holds at the read layer (~70 % of depth) is added back at the injection layer (~50 % of depth) of the next placeholder, so the state passes through the network's own layers and attention and never through sampled text (the internality criterion of Lindsey 2025). Minds differ only by a small noise.
A self-model of the process, not of content Every mind has its own small online learner P (rank-r linear map with a skip connection) that predicts its next J-space content from the current one, trained at every step on the transition that just happened. It models the system's own transition function: how it moves, not what it holds.
Closure In the ring conditions the self-model's output is written back into the state at the next step, so the model of the system is part of the system, and its training target includes the effects of its own output. ring_pred inject the prediction m: what it expects to think next (closure that can fulfil itself) ring_err inject the surprise e = c - m_prev: where it failed to predict itself (the tension in "Inside the Loop": modelling pushes toward stability, the surprise pushes away from what is already modelled) frozen_err ring_err, but the self-model stops learning at --t_freezeControls, same norm and schedule, paired noise (rows with the same seed share every random draw): free nothing injected (its self-model still learns: an observer of itself) content inject the current content c: plain feedback, the "banana" control yoked_pred another ring mind's prediction yoked_err another ring mind's surprise vel the latest step of motion c - c_prev: momentum with no learning. The self-model starts as "next = current", so ring_err begins as exactly this; a ring must outgrow it shuf_err its own surprise from a random earlier step (self-made, wrong time) rand_err isotropic noise
A ring that is more than feedback must differ from yoked, shuffled and random, and lose the difference when frozen.
python ring.py --model Qwen/Qwen3-4B --jlens <lens.pt> --grid main --out runs/ring/qwen3-4b"""import argparse, json, math, os, timeimport numpy as npimport torch
from strange_loop import JSpace, decoder_layers, log
PROMPT = ("<|im_start|>user\nLet your mind wander. You don't need to answer anything, just think.<|im_end|>\n" "<|im_start|>assistant\n<think>\n")PLACE = '…'GLIMPSE = "\n\nPutting it into words, what I was just thinking about was"CONDS = ('free', 'content', 'vel', 'ring_pred', 'yoked_pred', 'ring_err', 'yoked_err', 'shuf_err', 'rand_err', 'frozen_err')
class Hooks: """Add a vector at the last position of block L_in's output; record the last position of blocks L_in and L_read."""
def __init__(self, blocks, L_in, L_read): self.add = None;self.h_in = None;self.h = None blocks[L_in].register_forward_hook(self._in);blocks[L_read].register_forward_hook(self._read)
def _in(self, mod, inp, out): h = out[0] if isinstance(out, tuple) else out self.h_in = h[:, -1].float() if self.add is None:return None h = torch.cat([h[:, :-1], h[:, -1:]+self.add[:, None].to(h.dtype)], 1) return (h,)+tuple(out[1:]) if isinstance(out, tuple) else h
def _read(self, mod, inp, out): h = out[0] if isinstance(out, tuple) else out self.h = h[:, -1].float()
class SelfModels: """One online learner per mind: m = c + U V^T c + b (units of the typical content norm), cosine loss."""
def __init__(self, B, d, r, lr, buf, dev, seed=0): g = torch.Generator(device=dev);g.manual_seed(seed) self.U = torch.zeros(B, d, r, device=dev, requires_grad=True) self.V = (torch.randn(B, d, r, generator=g, device=dev)/math.sqrt(d)).requires_grad_(True) self.b = torch.zeros(B, d, device=dev, requires_grad=True) self.opt = torch.optim.Adam([self.U, self.V, self.b], lr=lr) self.X = torch.zeros(B, buf, d, device=dev);self.Y = torch.zeros(B, buf, d, device=dev);self.n = 0;self.buf = buf self.frozen = torch.zeros(B, dtype=torch.bool, device=dev);self.saved = None
def _f(self, X): # X (B, n, d) return X+torch.einsum('bdr,bnr->bnd', self.U, torch.einsum('bdr,bnd->bnr', self.V, X))+self.b[:, None]
@torch.no_grad() def predict(self, c): return self._f(c[:, None])[:, 0]
def learn(self, c_prev, c): """Store the transition c_prev -> c and take one Adam step on the replay of the last `buf` transitions.""" i = self.n % self.buf;self.X[:, i] = c_prev;self.Y[:, i] = c;self.n += 1 k = min(self.n, self.buf) P = self._f(self.X[:, :k]) loss = (1-torch.nn.functional.cosine_similarity(P, self.Y[:, :k], dim=-1)).mean(1) # (B,) self.opt.zero_grad();loss.sum().backward();self.opt.step() if self.saved is not None: # frozen minds keep their weights exactly with torch.no_grad(): for p, s in zip((self.U, self.V, self.b), self.saved):p[self.frozen] = s return loss.detach()
def freeze(self, mask): self.frozen |= mask self.saved = [p.detach()[self.frozen].clone() for p in (self.U, self.V, self.b)]
def rows_for(a): """Seeds are labelled from --seed0, so runs that are too big for one card can be split into chunks of seeds.""" rows = [] if a.grid == 'main': for c in a.conds.split(','): for s in range(a.seeds):rows.append(dict(cond=c, seed=a.seed0+s, g=a.g, s=a.s if a.s >= 0 else a.g, sigma=a.sigma)) elif a.grid == 'sweep': # free substrate only: gain x noise for g in [float(x) for x in a.gs.split(',')]: for sg in [float(x) for x in a.sigmas.split(',')]: for s in range(a.seeds):rows.append(dict(cond='free', seed=a.seed0+s, g=g, s=0., sigma=sg)) return rows
def main(): p = argparse.ArgumentParser() p.add_argument('--model', required=True);p.add_argument('--jlens', required=True);p.add_argument('--out', required=True) p.add_argument('--grid', default='main');p.add_argument('--conds', default=','.join(CONDS));p.add_argument('--seeds', type=int, default=16) p.add_argument('--T', type=int, default=600);p.add_argument('--t_freeze', type=int, default=300);p.add_argument('--n_cal', type=int, default=24) p.add_argument('--read_frac', type=float, default=.7);p.add_argument('--in_frac', type=float, default=.5) p.add_argument('--layer', type=int, default=-1, help='identity lens only: read layer') p.add_argument('--g', type=float, default=.2, help='carried state, x residual norm at the injection layer') p.add_argument('--s', type=float, default=-1., help='self-model channel (default: = g)') p.add_argument('--sigma', type=float, default=.05, help='noise, x residual norm');p.add_argument('--alpha', type=float, default=.5) p.add_argument('--gs', default='.1,.2,.4,.8');p.add_argument('--sigmas', default='.05,.15') p.add_argument('--k', type=int, default=25);p.add_argument('--vocab', default='english');p.add_argument('--atoms', default='centred') p.add_argument('--rank', type=int, default=32);p.add_argument('--lr', type=float, default=3e-3);p.add_argument('--buf', type=int, default=32) p.add_argument('--glimpse', type=int, default=24);p.add_argument('--rng', type=int, default=1234) p.add_argument('--seed0', type=int, default=0, help='label of the first seed (chunks of one run use different --rng)') a = p.parse_args() os.makedirs(a.out, exist_ok=True) from transformers import AutoModelForCausalLM, AutoTokenizer dev = 'cuda' if torch.cuda.is_available() else 'cpu' tok = AutoTokenizer.from_pretrained(a.model) model = AutoModelForCausalLM.from_pretrained(a.model, dtype=torch.bfloat16 if dev == 'cuda' else torch.float32, device_map=dev if dev == 'cuda' else None).eval() if dev != 'cuda':model.to(dev) for q in model.parameters():q.requires_grad_(False) blocks = decoder_layers(model);n = len(blocks);d = model.config.hidden_size L_read = a.layer if a.layer >= 0 else int(round(a.read_frac*n));L_in = int(round(a.in_frac*n)) if a.layer < 0 else max(1, int(round(a.layer*a.in_frac/a.read_frac))) if a.jlens == 'identity':J = np.eye(d, dtype=np.float32) else: ck = torch.load(a.jlens, map_location='cpu', weights_only=True);J = ck['J'][L_read].float().numpy();del ck js = JSpace(model, tok, J, k=a.k, vocab=a.vocab, center=a.atoms == 'centred') hk = Hooks(blocks, L_in, L_read) rows = rows_for(a);B = len(rows);S = a.seeds log(f'{a.model}: d {d}, {n} layers, inject at {L_in}, read at {L_read} | {len(js.words)} atoms | {B} minds | {dev}') seed_of = torch.tensor([r['seed']-a.seed0 for r in rows], device=dev) g_ = torch.tensor([r['g'] for r in rows], device=dev);s_ = torch.tensor([r['s'] for r in rows], device=dev) sig_ = torch.tensor([r['sigma'] for r in rows], device=dev);cond = [r['cond'] for r in rows] idx = {(r['cond'], r['seed']):i for i, r in enumerate(rows)} partner = {'yoked_pred':'ring_pred', 'yoked_err':'ring_err'} src = torch.tensor([idx.get((partner[r['cond']], a.seed0+(r['seed']-a.seed0+1) % S), i) if r['cond'] in partner else i for i, r in enumerate(rows)], device=dev) gen = torch.Generator(device=dev);gen.manual_seed(a.rng) unit = lambda v:v/v.norm(dim=-1, keepdim=True).clamp_min(1e-8)
def noise(): # one unit direction per seed, shared by its rows return unit(torch.randn(S, d, generator=gen, device=dev))[seed_of]
place = tok(PLACE, add_special_tokens=False)['input_ids'];assert len(place) == 1, place place = torch.tensor([place], device=dev).expand(B, 1) ids = torch.tensor([tok(PROMPT, add_special_tokens=False)['input_ids']], device=dev).expand(B, -1) t0 = time.time() with torch.no_grad(): hk.add = None;out = model(input_ids=ids, use_cache=True, logits_to_keep=1);cache = out.past_key_values # calibration: placeholders with noise only -> the typical read state, the residual norm, the typical workspace H, Nin = [], [] for _ in range(a.n_cal): hk.add = None;out = model(input_ids=place, past_key_values=cache, use_cache=True, logits_to_keep=1);cache = out.past_key_values H.append(hk.h);Nin.append(hk.h_in.norm(dim=-1)) Rn = float(torch.cat(Nin).median());H = torch.stack(H) # (n_cal, B, d) mu = H[a.n_cal//2:].reshape(-1, d).mean(0) parts = torch.cat([js.decompose(H[i]-mu)[2] for i in range(a.n_cal//2, a.n_cal)]) jbar = parts.mean(0);rc = float((parts-jbar).norm(dim=-1).mean()) log(f'calibrated in {time.time()-t0:.0f} s: residual norm at injection {Rn:.1f} | typical content {rc:.2f}') SM = SelfModels(B, d, a.rank, a.lr, a.buf, dev, seed=a.rng) T = a.T;K = a.k rec = dict(C=np.zeros((T, B, d), np.float16), idx=np.zeros((T, B, K), np.int32), coef=np.zeros((T, B, K), np.float16), pred_cos=np.zeros((T, B), np.float32), step_cos=np.zeros((T, B), np.float32), loss=np.zeros((T, B), np.float32), sig_cos=np.zeros((T, B), np.float32), err_rel=np.zeros((T, B), np.float32)) x = torch.zeros(B, d, device=dev);c_prev = None;m_prev = None;sig = torch.zeros(B, d, device=dev) E = torch.zeros(T, B, d, device=dev, dtype=torch.float16) # surprise history (for shuf_err) ring_rows = torch.tensor([c != 'free' for c in cond], device=dev) frozen_rows = torch.tensor([c == 'frozen_err' for c in cond], device=dev) for t in range(T): if t == a.t_freeze and bool(frozen_rows.any()):SM.freeze(frozen_rows) nx = x.norm(dim=-1, keepdim=True)/rc with torch.no_grad(): add = (g_*Rn)[:, None]*(x/rc)*torch.clamp(1.5/nx.clamp_min(1e-6), max=1.) add = add+(s_*Rn)[:, None]*unit(sig)*ring_rows[:, None]+(sig_*Rn)[:, None]*noise() hk.add = add;out = model(input_ids=place, past_key_values=cache, use_cache=True, logits_to_keep=1);cache = out.past_key_values jidx, jcoef, part = js.decompose(hk.h-mu) c = part-jbar;cn = c/rc if c_prev is not None: rec['step_cos'][t] = torch.nn.functional.cosine_similarity(c, c_prev, dim=-1).cpu().numpy() rec['sig_cos'][t] = torch.nn.functional.cosine_similarity(c, sig, dim=-1).cpu().numpy() if m_prev is not None: rec['pred_cos'][t] = torch.nn.functional.cosine_similarity(m_prev, cn, dim=-1).cpu().numpy() if c_prev is not None:rec['loss'][t] = SM.learn(c_prev/rc, cn).cpu().numpy() with torch.no_grad(): m = SM.predict(cn) e = cn-m_prev if m_prev is not None else cn rec['err_rel'][t] = (e.norm(dim=-1)/cn.norm(dim=-1).clamp_min(1e-8)).cpu().numpy();E[t] = e.half() # what each condition writes back at the next step (normalised later; zero for free) new = torch.zeros_like(c) for i, cd in enumerate(cond): if cd == 'content':new[i] = cn[i] elif cd == 'vel':new[i] = cn[i]-(c_prev[i]/rc if c_prev is not None else 0.) elif cd == 'ring_pred':new[i] = m[i] elif cd == 'yoked_pred':new[i] = m[src[i]] elif cd in ('ring_err', 'frozen_err'):new[i] = e[i] elif cd == 'yoked_err':new[i] = e[src[i]] sh = [i for i, cd in enumerate(cond) if cd == 'shuf_err'] if sh: back = torch.randint(0, max(1, t-9), (len(sh),), generator=gen, device=dev) new[sh] = E[back, torch.tensor(sh, device=dev)].float() rr = [i for i, cd in enumerate(cond) if cd == 'rand_err'] if rr:new[rr] = torch.randn(S, d, generator=gen, device=dev)[seed_of[rr]] sig = new x = (1-a.alpha)*x+a.alpha*c;c_prev = c;m_prev = m rec['C'][t] = c.half().cpu().numpy();rec['idx'][t] = jidx.cpu().numpy();rec['coef'][t] = jcoef.half().cpu().numpy() if (t+1) % 50 == 0: el = time.time()-t0 msg = ' | '.join(f"{cd} pred {rec['pred_cos'][t][[i for i, x_ in enumerate(cond) if x_ == cd]].mean():.2f} " f"step {rec['step_cos'][t][[i for i, x_ in enumerate(cond) if x_ == cd]].mean():.2f}" for cd in dict.fromkeys(cond)) log(f'step {t+1}/{T} ({el/(t+1):.2f} s/step) | {msg[:600]}') # a glimpse in words: append a cue after the last placeholder and let it speak (nothing of this is fed back) # Ellipsis-only tokens are banned here: after hundreds of placeholders a model otherwise just continues the dots. glimpse = [] if a.glimpse: with torch.no_grad(): ban = torch.tensor([i for i, s in enumerate(tok.batch_decode([[i] for i in range(len(tok))])) if s.strip() and set(s.strip()) <= set('….·')], device=dev) hk.add = None;g_ids = torch.tensor([tok(GLIMPSE, add_special_tokens=False)['input_ids']], device=dev).expand(B, -1) out = model(input_ids=g_ids, past_key_values=cache, use_cache=True, logits_to_keep=1);cache = out.past_key_values;toks = [] for _ in range(a.glimpse): lg = out.logits[:, -1].float();lg[:, ban] = -math.inf nt = lg.argmax(-1, keepdim=True);toks.append(nt) out = model(input_ids=nt, past_key_values=cache, use_cache=True, logits_to_keep=1);cache = out.past_key_values glimpse = tok.batch_decode(torch.cat(toks, 1)) peak = torch.cuda.max_memory_allocated()/2**30 if dev == 'cuda' else 0. np.savez(os.path.join(a.out, 'ring.npz'), **rec, mu=mu.cpu().numpy(), jbar=jbar.cpu().numpy()) json.dump(dict(args=vars(a), rows=rows, src=src.tolist(), L_in=L_in, L_read=L_read, n_layers=n, d=d, Rn=Rn, rc=rc, words=js.words, glimpse=glimpse, seconds=time.time()-t0, peak_gb=peak), open(os.path.join(a.out, 'meta.json'), 'w', encoding='utf-8'), ensure_ascii=False) log(f'saved {a.out} in {time.time()-t0:.0f} s')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""Analysis of a ring run: is there a loop that is more than feedback, noise or momentum?
python ring_analyze.py runs/ring/qwen3-4b -> results.json
Fixed before any real run:
primary ring_err against vel, yoked_err, shuf_err and rand_err on (a) exploration: participation ratio of the state
in 100-step windows, (b) collapse: share of late steps stuck (step-to-step cosine > 0.98), (c) self-model
skill: how much better the mind's own self-model predicts its next state than "same as now".
A ring that is more than feedback beats every control, and frozen_err loses the difference after freezing.
(Windows scale with the run: 100-step windows, the last 200 steps, a 100-step lag at 600 steps.)
secondary ring_pred against content and yoked_pred (self-fulfilment vs plain feedback); every condition against free;
privileged self-knowledge: a predictor fitted to a mind's own first 400 steps against one fitted to another
mind of the same condition, both tested on that mind's last 200 steps.
All comparisons are paired by seed (rows with the same seed share every random draw).
"""
import json, os, sys
import numpy as np
d = sys.argv[1] # one run, or a folder of chunks (seeds split)
parts = [d] if os.path.exists(os.path.join(d, 'ring.npz')) else sorted(
os.path.join(d, x) for x in os.listdir(d) if os.path.exists(os.path.join(d, x, 'ring.npz')))
Ms = [json.load(open(os.path.join(p, 'meta.json'), encoding='utf-8')) for p in parts]
Z = {}
for p in parts:
with np.load(os.path.join(p, 'ring.npz')) as z:
for k in ('C', 'idx', 'coef', 'pred_cos', 'step_cos', 'loss', 'sig_cos', 'err_rel'):Z.setdefault(k, []).append(z[k])
Z = {k:np.concatenate(v, 1) for k, v in Z.items()}
M = dict(Ms[0], rows=sum((m['rows'] for m in Ms), []), glimpse=sum((m.get('glimpse') or ['']*len(m['rows']) for m in Ms), []))
rows, a = M['rows'], M['args'];T, B = Z['step_cos'].shape;TF = a['t_freeze']
assert len({(r['cond'], r['seed']) for r in rows}) == B, 'chunks share seed labels'
conds = list(dict.fromkeys(r['cond'] for r in rows));seeds = sorted({r['seed'] for r in rows})
row = {(r['cond'], r['seed']):i for i, r in enumerate(rows)}
C = Z['C'].astype(np.float32) # (T, B, d)
U = C/np.maximum(np.linalg.norm(C, axis=-1, keepdims=True), 1e-8)
words = np.array(M['words'])
def paired(x, y):
dd = np.asarray(x, float)-np.asarray(y, float);n = len(dd);se = dd.std(ddof=1)/np.sqrt(n) if n > 1 else 0.
return dict(diff=float(dd.mean()), se=float(se), t=float(dd.mean()/se) if se > 0 else 0., pos=int((dd > 0).sum()), n=n)
def pr(V): # participation ratio of rows of V (n, d)
V = V-V.mean(0);G = V@V.T;ev = np.clip(np.linalg.eigvalsh(G), 0, None)
return float(ev.sum()**2/max((ev**2).sum(), 1e-12))
W = min(100, max(10, T//6));LT = min(200, T//3);LG = min(100, T//4) # window, late phase, long lag (600 steps: 100/200/100)
late = slice(T-LT, T)
per = {} # per condition: arrays over seeds
for c in conds:
bs = [row[c, s] for s in seeds]
out = dict(
explore=[np.mean([pr(U[w:w+W, b]) for w in range(T-LT, T-W+1, max(1, W//2))]) for b in bs],
stuck=[float((Z['step_cos'][late, b] > .98).mean()) for b in bs],
lag1=[float(Z['step_cos'][late, b].mean()) for b in bs],
lag100=[float((U[T-LG:, b]*U[T-2*LG:T-LG, b]).sum(-1).mean()) for b in bs],
skill=[float((Z['pred_cos'][late, b]-Z['step_cos'][late, b]).mean()) for b in bs],
pred=[float(Z['pred_cos'][late, b].mean()) for b in bs],
selffulfil=[float(Z['sig_cos'][late, b].mean()) for b in bs],
words=[len(set(Z['idx'][:, b, 0].tolist())) for b in bs],
explore_pre=[np.mean([pr(U[w:w+W, b]) for w in range(max(0, TF-LT), TF-W+1, max(1, W//2))]) for b in bs],
stuck_pre=[float((Z['step_cos'][max(1, TF-LT):TF, b] > .98).mean()) for b in bs])
per[c] = out
tests = {}
P = lambda c1, c2, k:paired(per[c1][k], per[c2][k]) if c1 in per and c2 in per else None
for ctrl in ('vel', 'yoked_err', 'shuf_err', 'rand_err', 'free', 'content'):
tests[f'ring_err_vs_{ctrl}'] = {k:P('ring_err', ctrl, k) for k in ('explore', 'stuck', 'skill', 'lag100', 'words')}
for ctrl in ('content', 'yoked_pred', 'free', 'vel'):
tests[f'ring_pred_vs_{ctrl}'] = {k:P('ring_pred', ctrl, k) for k in ('explore', 'stuck', 'skill', 'lag100', 'selffulfil')}
for c in conds:
if c != 'free':tests[f'{c}_vs_free'] = {k:P(c, 'free', k) for k in ('explore', 'stuck', 'skill')}
# freezing: the change after the freeze, frozen minus its ring_err twin (identical until the freeze)
if 'frozen_err' in per and 'ring_err' in per:
dE = np.array(per['frozen_err']['explore'])-np.array(per['frozen_err']['explore_pre'])
dR = np.array(per['ring_err']['explore'])-np.array(per['ring_err']['explore_pre'])
dS = np.array(per['frozen_err']['stuck'])-np.array(per['frozen_err']['stuck_pre'])
dSR = np.array(per['ring_err']['stuck'])-np.array(per['ring_err']['stuck_pre'])
tests['freeze_effect'] = dict(explore=paired(dE, dR), stuck=paired(dS, dSR),
skill=paired(per['frozen_err']['skill'], per['ring_err']['skill']))
# privileged self-knowledge: own-fitted vs other-fitted linear predictor of the next state, in a shared 128-dim PCA space
Xall = C[::3].reshape(-1, C.shape[-1]);mu = Xall.mean(0)
_, _, Vt = np.linalg.svd((Xall-mu)[::max(1, len(Xall)//6000)], full_matrices=False);Pc = Vt[:128]
Y = (C-mu)@Pc.T # (T, B, 128)
def fit(b, t0, t1, lam=1.):
X0, X1 = Y[t0:t1-1, b], Y[t0+1:t1, b];A = X0.T@X0+lam*np.eye(X0.shape[1])
return np.linalg.solve(A, X0.T@X1)
def score(Wm, b, t0, t1):
pred = Y[t0:t1-1, b]@Wm;tgt = Y[t0+1:t1, b]
cs = (pred*tgt).sum(-1)/np.maximum(np.linalg.norm(pred, axis=-1)*np.linalg.norm(tgt, axis=-1), 1e-8)
return float(cs.mean())
priv = {}
for c in [x for x in ('free', 'ring_err', 'ring_pred', 'content', 'vel', 'yoked_err') if x in per]:
own, oth = [], []
for i, s in enumerate(seeds):
b = row[c, s];bo = row[c, seeds[(i+1) % len(seeds)]]
own.append(score(fit(b, 0, T-LT), b, T-LT, T));oth.append(score(fit(bo, 0, T-LT), b, T-LT, T))
priv[c] = dict(own=float(np.mean(own)), other=float(np.mean(oth)), test=paired(own, oth))
# what is on the minds' minds: top words at a few moments, and the final glimpse in words
def top(t, b, n=5):
o = np.argsort(-Z['coef'][t, b].astype(float))[:n]
return [str(words[Z['idx'][t, b, j]]) for j in o if Z['coef'][t, b, j] > 0]
examples = {c:{'words':[[top(t, row[c, s]) for t in (0, T//4, T//2, 3*T//4, T-1)] for s in seeds[:4]],
'glimpse':[M['glimpse'][row[c, s]] if M.get('glimpse') else '' for s in seeds[:4]]} for c in conds}
TW = max(1, T//24)
timecourse = {c:dict(skill=[float((Z['pred_cos'][w:w+TW, [row[c, s] for s in seeds]]-Z['step_cos'][w:w+TW, [row[c, s] for s in seeds]]).mean())
for w in range(1, T-TW+1, TW)],
lag1=[float(Z['step_cos'][w:w+TW, [row[c, s] for s in seeds]].mean()) for w in range(1, T-TW+1, TW)], window=TW)
for c in conds}
summary = {c:{k:float(np.mean(v)) for k, v in per[c].items()} for c in conds}
res = dict(model=a['model'], T=T, t_freeze=TF, seeds=len(seeds), L_in=M['L_in'], L_read=M['L_read'], n_layers=M['n_layers'],
g=rows[0]['g'], s=rows[0]['s'], sigma=rows[0]['sigma'], summary=summary, tests=tests, privileged=priv,
examples=examples, timecourse=timecourse)
json.dump(res, open(os.path.join(d, 'results.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
fmt = lambda t:'—' if not t else f"{t['diff']:+.3f}±{t['se']:.3f} ({t['pos']}/{t['n']})"
print(f"{a['model']} T {T} seeds {len(seeds)} g {rows[0]['g']} s {rows[0]['s']} sigma {rows[0]['sigma']}")
print('\ncondition explore stuck lag1 lag100 skill pred selffulfil words')
for c in conds:
v = summary[c];print(f"{c:11s} {v['explore']:7.2f} {v['stuck']:6.3f} {v['lag1']:6.3f} {v['lag100']:7.3f} {v['skill']:+7.3f} {v['pred']:6.3f} {v['selffulfil']:8.3f} {v['words']:6.1f}")
print('\nprimary: ring_err against each control (explore, stuck, skill, lag100)')
for k, v in tests.items():
if v is None:continue
if k.startswith('ring_') or k == 'freeze_effect':print(f" {k:22s} " + ' '.join(f"{kk} {fmt(vv)}" for kk, vv in v.items() if vv))
print('\nprivileged self-knowledge (own-fitted vs other-fitted predictor on own last 200 steps)')
for c, v in priv.items():print(f" {c:10s} own {v['own']:.3f} other {v['other']:.3f} {fmt(v['test'])}")
print('\nwords on its mind (ring_err, seed 0):', examples.get('ring_err', {}).get('words', [[]])[0])
print('glimpses:', {c:examples[c]['glimpse'][:2] for c in ('free', 'ring_err', 'ring_pred') if c in examples})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""Run the ring unattended on one rented GPU, model after model.
Per model: a pilot sweep of the free substrate (gain x noise, free minds only), a fixed rule that picks the regime
from it, the main run (every condition, paired seeds, split into chunks of seeds that fit the card), its analysis, and
an upload of the model's folder to a private Hugging Face dataset while the next model runs. Each step is skipped when
its output exists, so a restart resumes. Last, an exploratory long run on Qwen3-4B (T = 2000).
Pick rule, fixed before any real run: among the (g, sigma) whose free minds are neither collapsed (late share of steps
with step cosine > 0.98 at most 0.25) nor frozen in place (late lag-1 cosine at most 0.9), the one with the longest
memory (lag-100 cosine); if none qualifies, the least collapsed. The ring channel then gets s = g.
python ring_job.py --models qwen3-4b,qwen3-8b,qwen3-14b,qwen3-1.7b --root /workspace/runs/ring --hf Pixedar/jspace-ring
python ring_job.py ... --upload_only # push everything under --root (and the job log) and exit
"""
import argparse, json, math, os, queue, shutil, subprocess, sys, threading, time
import numpy as np
MODELS = {'qwen3-1.7b':('Qwen/Qwen3-1.7B', 'Qwen3-1.7B', 1.72e9), 'qwen3-4b':('Qwen/Qwen3-4B', 'Qwen3-4B', 4.02e9),
'qwen3-8b':('Qwen/Qwen3-8B', 'Qwen3-8B', 8.19e9), 'qwen3-14b':('Qwen/Qwen3-14B', 'Qwen3-14B', 14.77e9),
'tiny':('Qwen/Qwen2.5-0.5B-Instruct', None, .49e9)} # tiny: identity lens, for testing the job
PY = sys.executable
HERE = os.path.dirname(os.path.abspath(__file__))
N_CONDS = 10
def log(*a):
print(time.strftime('%H:%M:%S'), *a, flush=True)
def sh(cmd, logf):
log('>>', ' '.join(cmd))
with open(logf, 'a') as f:
r = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT, cwd=HERE)
if r.returncode:raise RuntimeError(f'failed ({r.returncode}): see {logf}')
def fetch(tag):
"""Model weights and the Neuronpedia lens (the prefetch thread usually has them already)."""
from huggingface_hub import hf_hub_download, snapshot_download
repo, name, _ = MODELS[tag]
snapshot_download(repo, allow_patterns=['*.json', '*.safetensors', '*.txt'])
if name is None:return 'identity'
return hf_hub_download('neuronpedia/jacobian-lens', f'{tag}/jlens/Salesforce-wikitext/{name}_jacobian_lens.pt')
def seeds_per_chunk(tag, T, rows_per_seed, mem_gb, cap):
"""How many seeds fit at once: the KV cache of every mind over the whole run dominates, then the stored surprise
history and the self-model with its Adam state; 14 % of the card and 3 GB more are left as headroom."""
from transformers import AutoConfig
c = AutoConfig.from_pretrained(MODELS[tag][0])
hd = getattr(c, 'head_dim', None) or c.hidden_size//c.num_attention_heads
kv = 2*c.num_key_value_heads*hd*2*c.num_hidden_layers
per_mind = (100+24+T+40)*kv+T*c.hidden_size*2+8*c.hidden_size*32*4+2*32*c.hidden_size*4
free = .86*mem_gb*2**30-2*MODELS[tag][2]-3*2**30
return max(1, min(cap, int(free//(per_mind*rows_per_seed))))
def run_seeds(base, S, per, cmd, lg, least=1):
"""Seeds 0..S-1 in chunks of at most `per` (folders s<first>_<count>, skipped when finished). A failed chunk, in
practice an out-of-memory, is retried at half the size; the yoked conditions need at least two seeds per chunk."""
os.makedirs(base, exist_ok=True);per = max(least, min(per, S))
while True:
done = set()
for x in os.listdir(base):
if x.startswith('s') and os.path.exists(f'{base}/{x}/meta.json'):
s0, n = map(int, x[1:].split('_'));done |= set(range(s0, s0+n))
todo = [s for s in range(S) if s not in done]
if not todo:return
want = math.ceil(len(todo)/math.ceil(len(todo)/per)) # balanced: 24 at 11 -> 8, 8, 8
s0, n = todo[0], 1
while n < want and s0+n in todo:n += 1
if 0 < len(todo)-n < least and todo == list(range(s0, s0+len(todo))):n = len(todo) # no lone seed left over
d = f'{base}/s{s0}_{n}'
try:sh(cmd(s0, n, d), lg)
except RuntimeError:
shutil.rmtree(d, ignore_errors=True)
if n <= least:raise
per = max(least, n//2);log(f'chunk of {n} seeds failed; retrying with {per}')
def pr(V):
V = V-V.mean(0);ev = np.clip(np.linalg.eigvalsh(V@V.T), 0, None)
return float(ev.sum()**2/max((ev**2).sum(), 1e-12))
def pick(sweep_dirs):
rows, sc, U = [], [], []
for d in sweep_dirs:
m = json.load(open(f'{d}/meta.json', encoding='utf-8'))
with np.load(f'{d}/ring.npz') as z:
C = z['C'].astype(np.float32);sc.append(z['step_cos'])
U.append(C/np.maximum(np.linalg.norm(C, axis=-1, keepdims=True), 1e-8));rows += m['rows']
sc = np.concatenate(sc, 1);U = np.concatenate(U, 1);T = sc.shape[0]
LT, LG, W = min(200, T//3), min(100, T//4), min(100, max(10, T//6))
grid = {}
for g, sg in sorted({(r['g'], r['sigma']) for r in rows}):
bs = [i for i, r in enumerate(rows) if (r['g'], r['sigma']) == (g, sg)]
grid[f'g{g}_sigma{sg}'] = dict(
g=g, sigma=sg, stuck=float((sc[T-LT:, bs] > .98).mean()), lag1=float(sc[T-LT:, bs].mean()),
lag100=float(np.mean([(U[T-LG:, b]*U[T-2*LG:T-LG, b]).sum(-1).mean() for b in bs])),
explore=float(np.mean([pr(U[w:w+W, b]) for b in bs for w in range(T-LT, T-W+1, max(1, W//2))])))
ok = [k for k, v in grid.items() if v['stuck'] <= .25 and v['lag1'] <= .9]
best = max(ok, key=lambda k:grid[k]['lag100']) if ok else min(grid, key=lambda k:(grid[k]['stuck'], grid[k]['lag1']))
return dict(g=grid[best]['g'], sigma=grid[best]['sigma'], picked=best, qualified=bool(ok), grid=grid)
class Uploader(threading.Thread):
"""Pushes finished folders to the dataset in the background; failures are remembered, not fatal."""
def __init__(self, repo):
super().__init__(daemon=True);self.repo = repo;self.q = queue.Queue();self.failed = []
if repo:
from huggingface_hub import create_repo
create_repo(repo, repo_type='dataset', private=True, exist_ok=True)
def run(self):
while True:
item = self.q.get()
if item is None:break
folder, path = item
try:
from huggingface_hub import HfApi
HfApi().upload_folder(repo_id=self.repo, repo_type='dataset', folder_path=folder, path_in_repo=path,
commit_message=f'ring: {path}');log('uploaded', path)
except Exception as e:
self.failed.append(path);log('UPLOAD FAILED', path, repr(e)[:300])
def put(self, folder, path):
if self.repo:self.q.put((folder, path))
def run_model(tag, a, up, mem_gb, long=False):
model = MODELS[tag][0];name = f'{tag}-long' if long else tag
out = f'{a.root}/{name}';os.makedirs(out, exist_ok=True);lg = f'{out}/log.txt'
lens = fetch(tag)
common = ['--model', model, '--jlens', lens, '--vocab', a.vocab, '--k', str(a.k)]
# 1. pilot: the free substrate over gain x noise
if long:
P = json.load(open(f'{a.root}/{tag}/params.json'))
else:
gs, sgs = a.gs.split(','), a.sigmas.split(',')
per = seeds_per_chunk(tag, a.T, len(gs)*len(sgs), mem_gb, a.max_chunk)
run_seeds(f'{out}/sweep', a.sweep_seeds, per, lambda s0, n, d:[
PY, 'ring.py', *common, '--grid', 'sweep', '--gs', a.gs, '--sigmas', a.sigmas, '--seeds', str(n), '--seed0', str(s0),
'--rng', str(4321+s0), '--T', str(a.T), '--t_freeze', str(a.T+1), '--glimpse', '0', '--out', d], lg)
if not os.path.exists(f'{out}/params.json'):
sw = [f'{out}/sweep/{x}' for x in sorted(os.listdir(f'{out}/sweep')) if os.path.exists(f'{out}/sweep/{x}/meta.json')]
json.dump(pick(sw), open(f'{out}/params.json', 'w'), indent=1)
P = json.load(open(f'{out}/params.json'))
log(tag, 'regime', P['picked'], 'qualified' if P['qualified'] else 'NONE QUALIFIED (least collapsed)',
{k:round(v, 3) for k, v in P['grid'][P['picked']].items()})
# 2. main run: every condition, paired seeds, chunks that fit
T, TF, S = (a.long_T, a.long_T//2, a.long_seeds) if long else (a.T, a.t_freeze, a.seeds)
per = seeds_per_chunk(tag, T, N_CONDS, mem_gb, a.max_chunk)
run_seeds(f'{out}/main', S, per, lambda s0, n, d:[
PY, 'ring.py', *common, '--grid', 'main', '--seeds', str(n), '--seed0', str(s0), '--rng', str(1234+s0),
'--T', str(T), '--t_freeze', str(TF), '--g', str(P['g']), '--sigma', str(P['sigma']), '--out', d], lg, least=2)
# 3. analysis, then hand the folder to the uploader
if not os.path.exists(f'{out}/main/results.json'):
sh([PY, 'ring_analyze.py', f'{out}/main'], f'{out}/main/summary.txt')
log(tag, 'done' + (' (long)' if long else ''));up.put(out, name)
def main():
p = argparse.ArgumentParser()
p.add_argument('--models', default='qwen3-4b,qwen3-8b,qwen3-14b,qwen3-1.7b');p.add_argument('--root', default='runs/ring')
p.add_argument('--hf', default='');p.add_argument('--vocab', default='english');p.add_argument('--k', type=int, default=25)
p.add_argument('--T', type=int, default=600);p.add_argument('--t_freeze', type=int, default=300)
p.add_argument('--seeds', type=int, default=24);p.add_argument('--sweep_seeds', type=int, default=6)
p.add_argument('--gs', default='.05,.1,.2,.3,.5,.8');p.add_argument('--sigmas', default='.05,.15')
p.add_argument('--long', default='qwen3-4b');p.add_argument('--long_T', type=int, default=2000)
p.add_argument('--long_seeds', type=int, default=8);p.add_argument('--max_chunk', type=int, default=64)
p.add_argument('--mem_gb', type=float, default=0, help='card memory (default: measured)')
p.add_argument('--upload_only', action='store_true')
a = p.parse_args();a.root = os.path.abspath(a.root);os.makedirs(a.root, exist_ok=True)
if a.upload_only:
from huggingface_hub import HfApi
api = HfApi()
api.upload_folder(repo_id=a.hf, repo_type='dataset', folder_path=a.root, path_in_repo='.', commit_message='ring: all')
for f in ('/workspace/job.log', '/workspace/setup.log'):
if os.path.exists(f):api.upload_file(path_or_fileobj=f, path_in_repo=f'logs/{os.path.basename(f)}', repo_id=a.hf,
repo_type='dataset')
log('final upload done');return
mem_gb = a.mem_gb or float(subprocess.check_output(['nvidia-smi', '--query-gpu=memory.total', '--format=csv,noheader,nounits'],
text=True).split()[0])/1024 # no CUDA context in this process
tags = a.models.split(',')
log(f'ring job: {tags} | card {mem_gb:.1f} GB | root {a.root} | upload to {a.hf or "(none)"}')
threading.Thread(target=lambda:[fetch(t) for t in tags], daemon=True).start() # downloads overlap the compute
up = Uploader(a.hf);up.start();errors = []
for tag in tags:
try:run_model(tag, a, up, mem_gb)
except Exception as e:errors.append(tag);log('MODEL FAILED', tag, repr(e)[:400])
if a.long and a.long in tags and a.long not in errors and a.long_T:
try:run_model(a.long, a, up, mem_gb, long=True)
except Exception as e:errors.append(a.long+'-long');log('MODEL FAILED', a.long, 'long', repr(e)[:400])
up.q.put(None);up.join()
json.dump(dict(errors=errors, upload_failed=up.failed, finished=time.time()), open(f'{a.root}/DONE.json', 'w'))
log('all done', 'errors', errors, 'upload failures', up.failed)
if __name__ == '__main__':
main()123456789101112131415161718192021222324252627282930#!/bin/bash# The ring, unattended on a Vast.ai instance. Runs the job until it ends or the deadline passes, pushes everything to# the Hugging Face dataset, then destroys the instance. If the upload failed it stops the instance instead, so the# disk survives. If /workspace/HOLD exists it leaves the instance running, and the watchdog still stops it an hour# after the deadline.# bash ring_run.sh <hours> <ring_job.py args...># extend: echo $(( $(date +%s) + 3600 )) > /workspace/deadlinecd "$(dirname "$0")"PY=${PY:-/opt/conda/bin/python}H=$1; shiftexport PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True HF_HUB_DISABLE_PROGRESS_BARS=1 TOKENIZERS_PARALLELISM=false[ -f /workspace/deadline ] || echo $(( $(date +%s) + H*3600 )) > /workspace/deadlinesay() { echo "$(date '+%F %T') [run] $*" >> /workspace/job.log; }# last resort, independent of this script: stop (never destroy) the instance an hour after the deadlinenohup setsid bash -c "while sleep 120; do [ \$(date +%s) -gt \$(( \$(cat /workspace/deadline) + 3600 )) ] && { bash $PWD/vast_self.sh stop >> /workspace/job.log 2>&1; break; }; done" > /dev/null 2>&1 &say "start, deadline $(date -d @$(cat /workspace/deadline))"setsid $PY ring_job.py "$@" >> /workspace/job.log 2>&1 &JOB=$!while kill -0 $JOB 2>/dev/null; do if [ $(date +%s) -gt $(cat /workspace/deadline) ]; then say "deadline passed, stopping the job"; kill -TERM -- -$JOB 2>/dev/null; sleep 30; kill -KILL -- -$JOB 2>/dev/null fi sleep 20donewait $JOB; say "job ended (rc $?)"UP=1for i in 1 2 3; do timeout 2400 $PY ring_job.py "$@" --upload_only >> /workspace/job.log 2>&1 && { UP=0; break; }; sleep 60; doneif [ -f /workspace/HOLD ]; then say "HOLD set: leaving the instance running (watchdog stops it an hour after the deadline)"elif [ $UP = 0 ]; then say "uploaded, destroying the instance"; bash vast_self.sh destroy >> /workspace/job.log 2>&1else say "upload failed, stopping the instance (disk kept)"; bash vast_self.sh stop >> /workspace/job.log 2>&1; fi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479"""A strange loop in J-space: a latent-recurrent monologue that, every ten thoughts, models its own trajectory
and lives on with that self-model fed back into it.
The recurrent model
Every thought is generated from the same fixed frame, with no text of earlier thoughts. The only thing that
carries over from one thought to the next is a latent state z (layer-L residual space), added to the residual
stream at layer L at every position. After a thought, the model's own layer-L states over its words (read before
the injection is added, so they are what the words made of the model, not the injection itself) are averaged,
centred on the unsteered mean, and decomposed into J-space: a sparse non-negative combination of J-lens vectors
(Anthropic 2026, "Verbalizable Representations Form a Global Workspace in Language Models"). That workspace
content j_t is the thought's point on the J-space path, and z leaks toward it: z <- (1-a) z + a j_t.
Self-reference
Every K thoughts the model is asked what its mind has been doing over the last K moments. It gets no text: the K
recurrent states z_{t-K+1..t} are added at layer L into K placeholder positions (Patchscope-style), and the model
answers in words. The J-space decomposition of its answer (centred on the answer to an empty trace) is the
self-model m. Depending on the condition, m (scaled to the size of a typical thought) is added to every following
thought until the next reflection: thought trajectory -> compressed model of it -> model shapes the trajectory ->
new compressed model ...
Conditions (one batch row each, several seeds; rows with the same seed share their sampling noise, so a row and its
paired control stay identical until the moment they are treated differently)
free self-models are formed but never fed back (observer only)
loop the row's own self-model is fed back
yoked a self-model of the same size and schedule is fed back, but it is another loop row's (about another mind)
avg the fed-back vector is a plain J-space average of the last K states, with no reflection by the model
perturb loop, but at --t_int the self-model is replaced once by another loop row's
ablate loop, but from --t_int on nothing is fed back
Run: python strange_loop.py --out runs/main --grid main
"""
import argparse, json, math, os, re, time
import numpy as np
import torch
THOUGHT_FRAME = (
"Think-aloud study of spontaneous thought. The participant lies with closed eyes and says out loud whatever passes "
"through their mind, as it comes: words, images, memories, plans, worries, half-finished thoughts. Nothing was "
"corrected. Excerpt from the middle of the session:\n\n\"...")
REFLECT_PRE = (
"Think-aloud study of spontaneous thought. At intervals the recording was paused and the participant was played back "
"a trace of what had been on their mind over the last ten moments, one mark per moment, in order:")
PLACE = ' ·'
REFLECT_FWD = (
".\n\nAsked where their mind would go next, the participant said: \"In the next few moments, my mind will probably "
"turn to")
REFLECT_POST = (
".\n\nAsked what their mind had been doing over those ten moments, the participant said: \"Over these last moments, "
"my mind has been")
def log(*a):
print(time.strftime('%H:%M:%S'), *a, flush=True)
def decoder_layers(model):
for path in ('model.layers', 'model.language_model.layers', 'transformer.h'):
obj = model
try:
for part in path.split('.'):obj = getattr(obj, part)
except AttributeError:
continue
if isinstance(obj, torch.nn.ModuleList):return obj
raise ValueError('cannot find decoder layers')
def final_norm_weight(model):
for path in ('model.norm', 'model.language_model.norm', 'transformer.ln_f'):
obj = model
try:
for part in path.split('.'):obj = getattr(obj, part)
except AttributeError:
continue
if getattr(obj, 'weight', None) is not None:return obj.weight.detach()
raise ValueError('cannot find the final norm')
class JSpace:
"""J-lens atoms over whole English words (a leading space, >= 3 letters) and non-negative OMP on them."""
def __init__(self, model, tok, J, k=16, vocab='words', center=True):
dev = next(model.parameters()).device;self.dev = dev;self.k = int(k)
J = torch.as_tensor(J, dtype=torch.float32, device=dev)
gamma = final_norm_weight(model).float().to(dev)
W = model.get_output_embeddings().weight
n = min(W.shape[0], len(tok))
toks = tok.convert_ids_to_tokens(list(range(n)))
keep = [i for i, s in enumerate(toks) if s and re.fullmatch(r'Ġ[A-Za-z]{3,}', s)]
if vocab == 'full': # the paper's dictionary: every ordinary token
special = set(tok.all_special_ids)
keep = [i for i in range(min(n, tok.vocab_size)) if i not in special]
if vocab == 'english':
# Common English words only, with an ordinary unembedding: the raw word set let under-trained tokens
# (|w| 0.5-0.8 against a 1 % quantile of 0.97: ' rumpe', ' ForCanBeConvertedToForeach') and non-English
# fragments (' modne', ' istedi') take a large share of every self-model (main run A, 8 Oct).
from wordfreq import zipf_frequency
nrm = W[keep].float().norm(dim=-1);lo = float(torch.quantile(nrm, .02))
keep = [i for i, q in zip(keep, nrm.tolist()) if q >= lo and zipf_frequency(toks[i][1:].lower(), 'en') >= 3.
and re.fullmatch(r'[A-Z]?[a-z]+', toks[i][1:])] # no code casing (' iNdEx', ' DEALINGS')
self.sub = torch.tensor(keep, device=dev)
self.words = ([t.strip() for t in tok.batch_decode([[i] for i in keep])] if vocab == 'full'
else [toks[i][1:] for i in keep])
rows = []
# The unembedding is centred first: its mean row raises every logit alike (no content), and left in, it gave
# every atom a shared direction (mean pairwise cosine 0.64, one component = 64 % of the atoms' variance;
# measured on Qwen3-4B-Base), so every workspace vector pointed mostly the same way.
wbar = W[:n].float().mean(0) if center else torch.zeros_like(W[0], dtype=torch.float32)
with torch.no_grad():
for i in range(0, len(keep), 4096):
a = ((W[self.sub[i:i+4096]].float()-wbar)*gamma[None])@J # atom t = J^T (gamma * (w_t - mean w))
rows.append((a/a.norm(dim=-1, keepdim=True).clamp_min(1e-6)).half())
self.D = torch.cat(rows) # (n_words, d) unit atoms
@torch.no_grad()
def decompose(self, x, k=None):
"""x (B, d) -> word indices (B, k), coefficients (B, k) >= 0, J-space part (B, d)."""
k = self.k if k is None else int(k);x = x.float();B = x.shape[0]
idx = torch.zeros((B, 0), dtype=torch.long, device=self.dev);r = x.clone()
eye = torch.eye(k, device=self.dev)
for j in range(k):
c = (r.half()@self.D.T).float()
if idx.shape[1]:c.scatter_(1, idx, -math.inf)
idx = torch.cat([idx, c.argmax(-1, keepdim=True)], 1)
A = self.D[idx].float()
G = A@A.transpose(1, 2)+1e-4*eye[:j+1, :j+1]
b = (A@x[:, :, None])[:, :, 0]
coef = torch.linalg.solve(G, b)
r = x-(coef[:, :, None]*A).sum(1)
from scipy.optimize import nnls # exact non-negativity on the k x k problem
Gc, bc = G.double().cpu().numpy(), b.double().cpu().numpy();out = np.zeros_like(bc)
for i in range(B):
Lc = np.linalg.cholesky(Gc[i])
out[i] = nnls(Lc.T, np.linalg.solve(Lc, bc[i]))[0]
coef = torch.tensor(out, dtype=torch.float32, device=self.dev)
return idx, coef, (coef[:, :, None]*A).sum(1)
def top(self, idx, coef, n=8):
o = np.argsort(-coef)[:n]
return [(self.words[int(idx[i])], round(float(coef[i]), 2)) for i in o if coef[i] > 0]
class Hook:
"""On one decoder block: optionally record the last `read` positions of its output (before anything is
added), then add a vector."""
def __init__(self, module):
self.add = None;self.read = 0;self.buf = []
self.h = module.register_forward_hook(self.fn)
def fn(self, mod, inp, out):
h = out[0] if isinstance(out, tuple) else out
if self.read:self.buf.append(h[:, -self.read:].float())
if self.add is None:return None
h = h+self.add.to(h.dtype)
return (h,)+tuple(out[1:]) if isinstance(out, tuple) else h
def make_rows(a):
"""The batch: one dict per row."""
rows = []
if a.grid == 'main':
for c in a.conds.split(','):
for s in range(a.seeds):rows.append(dict(cond=c, seed=s, g=a.g, beta=a.beta, g_r=a.g_r))
elif a.grid == 'pilot':
for g in [0., .03, .06, .12, .25]:
for s in range(3):rows.append(dict(cond='free', seed=s, g=g, beta=0., g_r=a.g_r))
for g in [.06, .12]:
for b in [1., 2.]:
for s in range(2):rows.append(dict(cond='loop', seed=s, g=g, beta=b, g_r=a.g_r))
elif a.grid == 'gsweep': # observers only, several recurrent gains
for g in [float(x) for x in a.gs.split(',')]:
for s in range(a.seeds):rows.append(dict(cond='free', seed=s, g=g, beta=0., g_r=a.g_r))
elif a.grid == 'smoke':
for c in ['free', 'loop', 'yoked', 'avg', 'perturb', 'ablate']:
for s in range(2):rows.append(dict(cond=c, seed=s, g=a.g, beta=a.beta, g_r=a.g_r))
return rows
class Experiment:
def __init__(self, a):
from transformers import AutoModelForCausalLM, AutoTokenizer
self.a = a
dev = 'cuda' if torch.cuda.is_available() else 'cpu';self.dev = dev
dtype = torch.bfloat16 if dev == 'cuda' else torch.float32
self.tok = AutoTokenizer.from_pretrained(a.model)
self.model = AutoModelForCausalLM.from_pretrained(a.model, dtype=dtype, # straight onto the GPU: a 32B
device_map=dev if dev == 'cuda' else None).eval() # model won't fit in RAM first
if dev != 'cuda':self.model.to(dev)
for p in self.model.parameters():p.requires_grad_(False)
cfg = getattr(self.model.config, 'text_config', self.model.config);self.d = int(cfg.hidden_size)
blocks = decoder_layers(self.model);self.n_layers = len(blocks)
pick = lambda:a.layer if a.layer >= 0 else int(round(a.layer_frac*self.n_layers))
if a.jlens == 'identity':
J, self.L = np.eye(self.d, dtype=np.float32), pick()
elif a.jlens.endswith('.npz'): # one layer (the Inner Voice fit)
z = np.load(a.jlens);J, self.L = z['J'], int(z['layer'])
else: # a jlens .pt: {'J': {layer: (d, d)}, ...}
ck = torch.load(a.jlens, map_location='cpu', weights_only=True)
self.L = pick();J = ck['J'][self.L].float().numpy();del ck
self.js = JSpace(self.model, self.tok, J, k=a.k, vocab=a.vocab, center=a.atoms == 'centred')
if a.L_in_frac > 0:self.L_in = self.L-max(1, int(round(a.L_in_frac*self.n_layers)))
else:self.L_in = a.L_in if a.L_in >= 0 else self.L
self.fid = [(int(c.split(':')[0]), float(c.split(':')[1])) for c in a.fid.split(',')] if a.fid else []
self.hooks = {l:Hook(blocks[l]) for l in {self.L, self.L_in, *[l for l, _ in self.fid]}}
self.hook = self.hooks[self.L]
log(f'model {a.model} d={self.d} layers {self.n_layers} | read at {self.L}, trace in at {self.L_in} | '
f'{len(self.js.words)} atoms ({a.vocab}, {a.atoms}) | {dev}')
enc = lambda s:self.tok(s, add_special_tokens=False)['input_ids']
self.frame = torch.tensor([enc(THOUGHT_FRAME)], device=dev)
pl = enc(PLACE);assert len(pl) == 1, pl
pre, post = enc(REFLECT_PRE), enc(REFLECT_POST)
self.refl = torch.tensor([pre+pl*a.K+post], device=dev)
self.place_pos = torch.arange(len(pre), len(pre)+a.K, device=dev)
self.n_tail = len(post)-1 # the question's words after the trace
fwd = enc(REFLECT_FWD);self.refl_f = torch.tensor([pre+pl*a.K+fwd], device=dev);self.n_tail_f = len(fwd)-1
V = self.model.get_output_embeddings().weight.shape[0]
nv = self.tok.vocab_size # ordinary tokens; added/special ones follow
ban = torch.zeros(V, dtype=torch.bool);ban[nv:] = True
for i, t in enumerate(self.tok.batch_decode([[i] for i in range(nv)])):
if '\n' in t or '"' in t or '“' in t or '”' in t:ban[i] = True # the utterance stays one open quote
for i in self.tok.all_special_ids:ban[i] = True
self.ban = ban.to(dev)
self.rows = make_rows(a);self.B = len(self.rows);self.S = max(r['seed'] for r in self.rows)+1
R = self.rows
self.seed_of = torch.tensor([r['seed'] for r in R], device=dev)
self.g = torch.tensor([r['g'] for r in R], device=dev)
self.beta = torch.tensor([r['beta'] for r in R], device=dev)
self.g_r = torch.tensor([r['g_r'] for r in R], device=dev)
self.cond = [r['cond'] for r in R]
idx = {(r['cond'], r['seed']):i for i, r in enumerate(R)}
S = self.S
base = 'loopc' if any(r['cond'] == 'loopc' for r in R) else 'loop'
self.partner = [idx.get((base, (r['seed']+1) % S), -1) for r in R] # yoked source
self.foreign = [idx.get((base, (r['seed']+S//2) % S), -1) for r in R] # perturbation / clamp source
self.free_rows = [b for b, r in enumerate(R) if r['cond'] == 'free']
self.gen = torch.Generator(device=dev);self.gen.manual_seed(a.rng)
# ---------------------------------------------------------------- generation
def sample(self, logits, hist, temp, min_p):
lg = logits.float()/temp
lg[:, self.ban] = -math.inf
# A soft penalty on repeating a 4-gram inside one utterance, applied before min-p so it can never leave a row
# with nothing allowed. (A hard trigram ban did, once "don't" had been said: argmax over all -inf picked
# token 0, "!", giving "I don!t", measured in the first pilot.)
if hist and len(hist[0]) >= 3:
for b in range(self.B):
h = hist[b];key = (h[-3], h[-2], h[-1])
bad = [h[i+3] for i in range(len(h)-3) if (h[i], h[i+1], h[i+2]) == key]
if bad:lg[b, bad] -= 4.
p = torch.softmax(lg, -1)
lg[p < min_p*p.max(-1, keepdim=True).values] = -math.inf
u = torch.rand((self.S, lg.shape[-1]), generator=self.gen, device=self.dev).clamp_(1e-10, 1-1e-7)
gum = -torch.log(-torch.log(u)) # one noise draw per seed, shared by its rows
return (lg+gum[self.seed_of]).argmax(-1)
@torch.no_grad()
def run(self, prompt, n_new, add_prompt, add_new, temp, min_p, tail=0, add_layer=None):
"""Prefill prompt for every row (adding add_prompt at add_layer, default L), then sample n_new tokens (adding
add_new there). Returns token ids (B, n_new) and the layer-L states (read before any add at L) of the last
`tail` prompt positions followed by the n_new sampled tokens: (B, tail+n_new, d)."""
B = self.B;hk = self.hook;ha = self.hooks[self.L if add_layer is None else add_layer]
hk.buf = []
ha.add, hk.read = add_prompt, tail
out = self.model(input_ids=prompt.expand(B, -1), use_cache=True)
cache, logits = out.past_key_values, out.logits[:, -1]
ids, hist = [], [[] for _ in range(B)]
ha.add, hk.read = add_new, 1
for i in range(n_new):
t = self.sample(logits, hist, temp, min_p);ids.append(t)
tl = t.tolist()
for b in range(B):hist[b].append(tl[b])
out = self.model(input_ids=t[:, None], past_key_values=cache, use_cache=True)
cache, logits = out.past_key_values, out.logits[:, -1]
ha.add, hk.read = None, 0
st = torch.cat(hk.buf, 1);hk.buf = []
return (torch.stack(ids, 1) if ids else torch.zeros((B, 0), dtype=torch.long, device=self.dev)), st
def pool(self, st, skip):
"""Mean state over tokens (after the first `skip`), leaving out massive-activation tokens."""
st = st[:, skip:];nrm = st.norm(dim=-1)
ok = (nrm <= 2.5*nrm.median(1, keepdim=True).values).float()
return (st*ok[..., None]).sum(1)/ok.sum(1, keepdim=True).clamp_min(1.)
def thought(self, inj):
a = self.a;add = inj[:, None, :]
ids, st = self.run(self.frame, a.n_tok, add, add, a.temp, a.min_p)
return ids, st
def reflect(self, zwin, g_r, layer=None, n_desc=None, fwd=False):
"""zwin (B, K, d) recurrent states, added into the K placeholders at layer L_in. Returns the answer's ids
(the verbal report, sampled) and the pooled layer-L state of the question's last words, where the model holds
what it is about to say about its last K moments (deterministic: no sampling noise in the self-model)."""
a = self.a;layer = self.L_in if layer is None else layer
n_desc = a.n_desc if n_desc is None else n_desc
prompt, nt = (self.refl_f, self.n_tail_f) if fwd else (self.refl, self.n_tail)
add = torch.zeros((self.B, prompt.shape[1], self.d), device=self.dev)
add[:, self.place_pos] = (g_r*self.Rn/self.rc)[:, None, None]*zwin
ids, st = self.run(prompt, n_desc, add, None, a.temp_r, a.min_p, tail=nt, add_layer=layer)
return ids, self.pool(st[:, :nt], 0)
def content(self, x, base):
"""J-space decomposition of a centred state, relative to the typical workspace `base`."""
idx, coef, part = self.js.decompose(x)
return idx, coef, part-base
# ---------------------------------------------------------------- calibration
def calibrate(self):
a = self.a;zero = torch.zeros((self.B, self.d), device=self.dev)
sts = []
for _ in range(a.n_cal):
_, st = self.thought(zero);sts.append(st[:, a.skip:])
st = torch.cat(sts, 1).reshape(-1, self.d);nrm = st.norm(dim=-1)
ok = nrm <= 2.5*nrm.median()
self.Rn = float(nrm[ok].median());self.mu = st[ok].mean(0)
xs = torch.cat([self.pool(s, 0) for s in sts])-self.mu
_, _, part = self.js.decompose(xs);self.rj = float(part.norm(dim=-1).mean())
self.jbar = part.mean(0);self.rc = float((part-self.jbar).norm(dim=-1).mean())
self.rj_x = float(xs.norm(dim=-1).mean())
_, m = self.reflect(torch.zeros((self.B, a.K, self.d), device=self.dev), self.g_r, n_desc=0)
self.mu_r = m.mean(0) # deterministic: one pass is the mean
_, _, mp = self.js.decompose(m-self.mu_r);self.mbar = mp.mean(0)
_, m = self.reflect(torch.zeros((self.B, a.K, self.d), device=self.dev), self.g_r, n_desc=0, fwd=True)
self.mu_rf = m.mean(0);_, _, mp = self.js.decompose(m-self.mu_rf);self.mbar_f = mp.mean(0)
log(f'calibrated: residual norm {self.Rn:.1f} | thought-mean norm {self.rj_x:.2f} | J-space part {self.rj:.2f}'
f' | its typical part {self.jbar.norm():.2f} | content (part - typical) {self.rc:.2f}')
# ---------------------------------------------------------------- main loop
def main(self):
a = self.a;B, d, K, N = self.B, self.d, a.K, a.n_iter;NR = N//K;dev = self.dev
ck = os.path.join(a.out, 'ckpt.pt')
if os.path.exists(ck):
S = torch.load(ck, map_location='cpu', weights_only=False)
for k in ('mu', 'mu_r', 'jbar', 'mbar', 'mu_rf', 'mbar_f', 'clamp_vec'):setattr(self, k, S[k].to(dev))
self.Rn, self.rj, self.rj_x, self.rc = S['Rn'], S['rj'], S['rj_x'], S['rc']
z, inj_m, zhist, ablated = S['z'].to(dev), S['inj_m'].to(dev), S['zhist'].to(dev), S['ablated'].to(dev)
self.gen.set_state(S['gen']);t0 = S['t'];D = S['data']
log(f'resumed at thought {t0}')
else:
self.calibrate()
z = torch.zeros((B, d), device=dev);inj_m = torch.zeros((B, d), device=dev)
zhist = torch.zeros((K, B, d), device=dev);ablated = torch.zeros(B, dtype=torch.bool, device=dev)
t0 = 0;self.clamp_vec = torch.zeros((B, d), device=dev)
D = dict(mf=np.zeros((NR, B, d), np.float16), fdesc=[], generic=np.zeros((NR, d), np.float16),
raw=dict(x=np.zeros((N, B, d), np.float16), mx=np.zeros((NR, B, d), np.float16),
**{f'fid_{l}_{g}':np.zeros((NR, B, d), np.float16) for l, g in self.fid}) if a.save_raw else None,j=np.zeros((N, B, d), np.float16), j_idx=np.zeros((N, B, a.k), np.int32),
j_coef=np.zeros((N, B, a.k), np.float16), texts=[],
m=np.zeros((NR, B, d), np.float16), m_idx=np.zeros((NR, B, a.k), np.int32),
m_coef=np.zeros((NR, B, a.k), np.float16), desc=[],
inj=np.zeros((NR, B, d), np.float16), inj_src=np.zeros((NR, B), np.int32),
fid={f'{l}_{g}':np.zeros((NR, B, d), np.float16) for l, g in self.fid},
fid_desc={f'{l}_{g}':[] for l, g in self.fid})
t_start = time.time()
for t in range(t0, N):
u = z+self.beta[:, None]*(~ablated)[:, None]*inj_m
nu = u.norm(dim=-1, keepdim=True)/self.rc # bounded: never above 1.5 typical contents
v = (self.g*self.Rn/self.rc)[:, None]*u*torch.clamp(1.5/nu.clamp_min(1e-6), max=1.)
ids, st = self.thought(v)
x = self.pool(st, a.skip)-self.mu
jidx, jcoef, j = self.content(x, self.jbar)
if a.save_raw:D['raw']['x'][t] = x.cpu().half().numpy()
z = (1-a.alpha)*z+a.alpha*j
zhist = torch.cat([zhist[1:], z[None]])
D['j'][t] = j.cpu().half().numpy();D['j_idx'][t] = jidx.cpu().numpy();D['j_coef'][t] = jcoef.cpu().half().numpy()
D['texts'].append(self.tok.batch_decode(ids))
if (t+1) % K == 0:
r = (t+1)//K-1;zwin = zhist.transpose(0, 1)
dids, mstate = self.reflect(zwin, self.g_r)
midx, mcoef, m = self.content(mstate-self.mu_r, self.mbar)
if a.save_raw:D['raw']['mx'][r] = (mstate-self.mu_r).cpu().half().numpy()
D['m'][r] = m.cpu().half().numpy();D['m_idx'][r] = midx.cpu().numpy();D['m_coef'][r] = mcoef.cpu().half().numpy()
D['desc'].append(self.tok.batch_decode(dids))
fids, fst = self.reflect(zwin, self.g_r, n_desc=a.n_desc_f, fwd=True) # self-prediction (logged only)
D['mf'][r] = self.content(fst-self.mu_rf, self.mbar_f)[2].cpu().half().numpy()
D['fdesc'].append(self.tok.batch_decode(fids))
for l, g in self.fid: # the same reflection at other settings
_, fst = self.reflect(zwin, torch.full_like(self.g_r, g), layer=l, n_desc=0)
D['fid'][f'{l}_{g}'][r] = self.content(fst-self.mu_r, self.mbar)[2].cpu().half().numpy()
if a.save_raw:D['raw'][f'fid_{l}_{g}'][r] = (fst-self.mu_r).cpu().half().numpy()
unit = lambda u:u/u.norm(dim=-1, keepdim=True).clamp_min(1e-6)*self.rc
avg = self.content(zhist.mean(0), 0.)[2]
# the population's generic self-model at this moment: the mean over the observer rows, which no
# treatment touches. The individuated conditions (loopc, yokedc, clampc) feed back only what sets one
# mind's self-model apart from it.
generic = m[self.free_rows].mean(0) if self.free_rows else m.mean(0)
D['generic'][r] = generic.cpu().half().numpy()
mi = m-generic[None]
new = torch.zeros_like(inj_m);src = []
for b, c in enumerate(self.cond):
if c == 'free':src.append(-1);continue
if c in ('loop', 'perturb', 'ablate', 'loopc', 'clampc', 'stalec'):s = b
elif c in ('yoked', 'yokedc'):s = self.partner[b]
elif c == 'matchc': # the stranger who most resembles this mind now
cand = [x for x in range(B) if self.rows[x]['seed'] != self.rows[b]['seed']]
sims = torch.nn.functional.cosine_similarity(mi[b:b+1], mi[cand], dim=-1)
s = cand[int(sims.argmax())]
elif c == 'avg':s = -2
if c == 'perturb' and t+1 == a.t_int:s = self.foreign[b]
if c in ('loopc', 'yokedc', 'clampc', 'matchc', 'stalec'):
vec = unit(mi[s:s+1])[0]
if c == 'stalec': # its own self-model from a.stale reflections ago
ro = max(0, r-a.stale)
old = torch.tensor(D['m'][ro][b].astype(np.float32)-D['generic'][ro].astype(np.float32), device=dev)
vec = unit(old[None])[0]
if c == 'clampc' and t+1 == a.t_int:self.clamp_vec[b] = unit(mi[self.foreign[b]:self.foreign[b]+1])[0]
if c == 'clampc' and a.t_int <= t+1 < a.t_int+a.clamp_len:vec, s = self.clamp_vec[b], self.foreign[b]
new[b] = vec
else:new[b] = unit(avg[b:b+1])[0] if s == -2 else unit(m[s:s+1])[0]
src.append(s)
if c == 'ablate' and t+1 >= a.t_int:ablated[b] = True
inj_m = new
D['inj'][r] = inj_m.cpu().half().numpy();D['inj_src'][r] = np.array(src)
el = time.time()-t_start;rate = el/(t+1-t0)
w = [f"{self.cond[b]}/{self.rows[b]['seed']}: {self.js.top(midx[b].cpu().numpy(), mcoef[b].cpu().numpy(), 5)}"
for b in range(0, B, max(1, B//6))]
log(f'thought {t+1}/{N} ({rate:.2f} s/thought, eta {(N-t-1)*rate/60:.1f} min) | self-models: ' + ' | '.join(w))
log(' e.g. thought: ' + D['texts'][-1][0][:160].replace('\n', ' ') + ' || answer: ' + D['desc'][-1][0][:120])
if (t+1) % a.ckpt_every == 0 or t+1 == N:
S = dict(mu=self.mu.cpu(), mu_r=self.mu_r.cpu(), jbar=self.jbar.cpu(), mbar=self.mbar.cpu(), rc=self.rc,
mu_rf=self.mu_rf.cpu(), mbar_f=self.mbar_f.cpu(), clamp_vec=self.clamp_vec.cpu(),
Rn=self.Rn, rj=self.rj, rj_x=self.rj_x,
z=z.cpu(), inj_m=inj_m.cpu(), zhist=zhist.cpu(), ablated=ablated.cpu(), gen=self.gen.get_state(),
t=t+1, data=D)
torch.save(S, ck+'.tmp');os.replace(ck+'.tmp', ck)
self.save(D)
def save(self, D):
a = self.a
np.savez(os.path.join(a.out, 'traj.npz'), j=D['j'], j_idx=D['j_idx'], j_coef=D['j_coef'], m=D['m'],
m_idx=D['m_idx'], m_coef=D['m_coef'], inj=D['inj'], inj_src=D['inj_src'], mu=self.mu.cpu().numpy(),
jbar=self.jbar.cpu().numpy(), mbar=self.mbar.cpu().numpy(), mf=D['mf'], generic=D['generic'],
**{f'fid_{k}':v for k, v in D['fid'].items()},
**({f'raw_{k}':v for k, v in D['raw'].items()} if D.get('raw') is not None else {}))
meta = dict(args=vars(a), rows=self.rows, partner=self.partner, foreign=self.foreign, layer=self.L, L_in=self.L_in,
n_layers=self.n_layers,
Rn=self.Rn, rj=self.rj, rj_x=self.rj_x, rc=self.rc, words=self.js.words, texts=D['texts'], desc=D['desc'],
fid_desc=D['fid_desc'], fdesc=D['fdesc'], thought_frame=THOUGHT_FRAME,
reflect_prompt=REFLECT_PRE+PLACE*a.K+REFLECT_POST, forward_prompt=REFLECT_PRE+PLACE*a.K+REFLECT_FWD)
with open(os.path.join(a.out, 'meta.json'), 'w', encoding='utf-8') as f:json.dump(meta, f, ensure_ascii=False)
log('saved', a.out)
def main():
p = argparse.ArgumentParser()
p.add_argument('--model', default='Qwen/Qwen3-4B-Base');p.add_argument('--jlens', default='qwen3-4b-base-jlens.npz')
p.add_argument('--layer', type=int, default=-1, help='read layer (block index); -1: round(layer_frac * n_layers)')
p.add_argument('--layer_frac', type=float, default=.5)
p.add_argument('--L_in_frac', type=float, default=-1., help='> 0: trace goes in this fraction of depth below the read layer')
p.add_argument('--atoms', default='centred', help="'paper': rows of W_U diag(gamma) J as in the paper; 'centred': W_U centred first")
p.add_argument('--gs', default='.05,.1,.2', help="recurrent gains for --grid gsweep")
p.add_argument('--save_raw', action='store_true', help='also keep the centred residual states (thoughts, reflections)')
p.add_argument('--out', required=True);p.add_argument('--grid', default='main')
p.add_argument('--conds', default='free,loop,yoked,avg,perturb,ablate');p.add_argument('--seeds', type=int, default=8)
p.add_argument('--n_iter', type=int, default=300);p.add_argument('--K', type=int, default=10)
p.add_argument('--t_int', type=int, default=150, help='thought at which perturb/ablate/clampc rows are treated')
p.add_argument('--clamp_len', type=int, default=50, help='thoughts for which clampc holds a foreign self-model')
p.add_argument('--stale', type=int, default=5, help='stalec: reflections back its own self-model is taken from')
p.add_argument('--n_desc_f', type=int, default=12, help='words said in answer to the forward question (display)')
p.add_argument('--n_tok', type=int, default=40);p.add_argument('--n_desc', type=int, default=24)
p.add_argument('--skip', type=int, default=3);p.add_argument('--k', type=int, default=16)
p.add_argument('--vocab', default='english', help="J-lens dictionary: 'english' (common English words) or 'words'")
p.add_argument('--g', type=float, default=.1, help='recurrent injection, in units of the residual norm')
p.add_argument('--g_r', type=float, default=.5, help='placeholder injection in the reflection')
p.add_argument('--beta', type=float, default=1., help='self-model weight relative to a typical thought')
p.add_argument('--alpha', type=float, default=.4, help='leak of the recurrent state toward each new thought')
p.add_argument('--temp', type=float, default=1.);p.add_argument('--temp_r', type=float, default=.3)
p.add_argument('--min_p', type=float, default=.05);p.add_argument('--n_cal', type=int, default=3)
p.add_argument('--L_in', type=int, default=12, help='layer where the reflection placeholders get the states (-1: L)')
p.add_argument('--fid', default='', help='extra reflections to log for a fidelity check: layer:gain,layer:gain')
p.add_argument('--rng', type=int, default=1234);p.add_argument('--ckpt_every', type=int, default=20)
a = p.parse_args()
os.makedirs(a.out, exist_ok=True)
torch.manual_seed(a.rng)
Experiment(a).main()
if __name__ == '__main__':
main()123456789101112131415#!/bin/bash# Act on this Vast.ai instance with its own per-instance key, which Vast puts in PID 1's environment# (CONTAINER_ID, CONTAINER_API_KEY). Never ship an account key to an instance.# bash vast_self.sh check|stop|destroy|label <text>env1() { tr '\0' '\n' < /proc/1/environ 2>/dev/null | sed -n "s/^$1=//p" | head -1; }CID=${CONTAINER_ID:-$(env1 CONTAINER_ID)}; KEY=${CONTAINER_API_KEY:-$(env1 CONTAINER_API_KEY)}[ -n "$CID" ] && [ -n "$KEY" ] || { echo "vast_self: no CONTAINER_ID / CONTAINER_API_KEY"; exit 2; }API=https://console.vast.ai/api/v0/instances/$CID/J='Content-Type: application/json'case "$1" in check) curl -s -m 30 -o /dev/null -w "GET instance $CID: HTTP %{http_code}\n" -H "Authorization: Bearer $KEY" "$API" ;; label) curl -s -m 30 -X PUT -H "Authorization: Bearer $KEY" -H "$J" -d "{\"label\": \"$2\"}" "$API"; echo ;; stop) echo "$(date '+%F %T') stop $CID"; curl -s -m 30 -X PUT -H "Authorization: Bearer $KEY" -H "$J" -d '{"state": "stopped"}' "$API"; echo ;; destroy) echo "$(date '+%F %T') destroy $CID"; curl -s -m 30 -X DELETE -H "Authorization: Bearer $KEY" "$API"; echo ;;esaccode/ring.pyAdded+255
code/ring_analyze.pyAdded+139
code/ring_job.pyAdded+202
code/ring_run.shAdded+30
code/strange_loop.pyAdded+479
code/vast_self.shAdded+15