Code and pre-registered analysis, uploaded at launch before any result
Browse files- code/ring.py +255 -0
- code/ring_analyze.py +139 -0
- code/ring_job.py +202 -0
- code/ring_run.sh +30 -0
- code/strange_loop.py +479 -0
- code/vast_self.sh +15 -0
code/ring.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The ring: a latent loop that keeps a model of itself, run beside the controls that would expose it as plain feedback.
|
| 2 |
+
|
| 3 |
+
Part 1 and 2 fed back a summary of what the model had said. Its "self-model" was about content, and everything passed
|
| 4 |
+
through sampled words. The ring changes all three things the review found missing:
|
| 5 |
+
|
| 6 |
+
Substrate, no words in the loop
|
| 7 |
+
After a short chat prompt that opens the assistant's thinking, the model runs one placeholder token at a time. At
|
| 8 |
+
every step the J-space content it holds at the read layer (~70 % of depth) is added back at the injection layer
|
| 9 |
+
(~50 % of depth) of the next placeholder, so the state passes through the network's own layers and attention and
|
| 10 |
+
never through sampled text (the internality criterion of Lindsey 2025). Minds differ only by a small noise.
|
| 11 |
+
|
| 12 |
+
A self-model of the process, not of content
|
| 13 |
+
Every mind has its own small online learner P (rank-r linear map with a skip connection) that predicts its next
|
| 14 |
+
J-space content from the current one, trained at every step on the transition that just happened. It models the
|
| 15 |
+
system's own transition function: how it moves, not what it holds.
|
| 16 |
+
|
| 17 |
+
Closure
|
| 18 |
+
In the ring conditions the self-model's output is written back into the state at the next step, so the model of
|
| 19 |
+
the system is part of the system, and its training target includes the effects of its own output.
|
| 20 |
+
ring_pred inject the prediction m: what it expects to think next (closure that can fulfil itself)
|
| 21 |
+
ring_err inject the surprise e = c - m_prev: where it failed to predict itself (the tension in "Inside the
|
| 22 |
+
Loop": modelling pushes toward stability, the surprise pushes away from what is already modelled)
|
| 23 |
+
frozen_err ring_err, but the self-model stops learning at --t_freeze
|
| 24 |
+
Controls, same norm and schedule, paired noise (rows with the same seed share every random draw):
|
| 25 |
+
free nothing injected (its self-model still learns: an observer of itself)
|
| 26 |
+
content inject the current content c: plain feedback, the "banana" control
|
| 27 |
+
yoked_pred another ring mind's prediction yoked_err another ring mind's surprise
|
| 28 |
+
vel the latest step of motion c - c_prev: momentum with no learning. The self-model starts as
|
| 29 |
+
"next = current", so ring_err begins as exactly this; a ring must outgrow it
|
| 30 |
+
shuf_err its own surprise from a random earlier step (self-made, wrong time)
|
| 31 |
+
rand_err isotropic noise
|
| 32 |
+
|
| 33 |
+
A ring that is more than feedback must differ from yoked, shuffled and random, and lose the difference when frozen.
|
| 34 |
+
|
| 35 |
+
python ring.py --model Qwen/Qwen3-4B --jlens <lens.pt> --grid main --out runs/ring/qwen3-4b
|
| 36 |
+
"""
|
| 37 |
+
import argparse, json, math, os, time
|
| 38 |
+
import numpy as np
|
| 39 |
+
import torch
|
| 40 |
+
|
| 41 |
+
from strange_loop import JSpace, decoder_layers, log
|
| 42 |
+
|
| 43 |
+
PROMPT = ("<|im_start|>user\nLet your mind wander. You don't need to answer anything, just think.<|im_end|>\n"
|
| 44 |
+
"<|im_start|>assistant\n<think>\n")
|
| 45 |
+
PLACE = '…'
|
| 46 |
+
GLIMPSE = "\n\nPutting it into words, what I was just thinking about was"
|
| 47 |
+
CONDS = ('free', 'content', 'vel', 'ring_pred', 'yoked_pred', 'ring_err', 'yoked_err', 'shuf_err', 'rand_err', 'frozen_err')
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Hooks:
|
| 51 |
+
"""Add a vector at the last position of block L_in's output; record the last position of blocks L_in and L_read."""
|
| 52 |
+
|
| 53 |
+
def __init__(self, blocks, L_in, L_read):
|
| 54 |
+
self.add = None;self.h_in = None;self.h = None
|
| 55 |
+
blocks[L_in].register_forward_hook(self._in);blocks[L_read].register_forward_hook(self._read)
|
| 56 |
+
|
| 57 |
+
def _in(self, mod, inp, out):
|
| 58 |
+
h = out[0] if isinstance(out, tuple) else out
|
| 59 |
+
self.h_in = h[:, -1].float()
|
| 60 |
+
if self.add is None:return None
|
| 61 |
+
h = torch.cat([h[:, :-1], h[:, -1:]+self.add[:, None].to(h.dtype)], 1)
|
| 62 |
+
return (h,)+tuple(out[1:]) if isinstance(out, tuple) else h
|
| 63 |
+
|
| 64 |
+
def _read(self, mod, inp, out):
|
| 65 |
+
h = out[0] if isinstance(out, tuple) else out
|
| 66 |
+
self.h = h[:, -1].float()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class SelfModels:
|
| 70 |
+
"""One online learner per mind: m = c + U V^T c + b (units of the typical content norm), cosine loss."""
|
| 71 |
+
|
| 72 |
+
def __init__(self, B, d, r, lr, buf, dev, seed=0):
|
| 73 |
+
g = torch.Generator(device=dev);g.manual_seed(seed)
|
| 74 |
+
self.U = torch.zeros(B, d, r, device=dev, requires_grad=True)
|
| 75 |
+
self.V = (torch.randn(B, d, r, generator=g, device=dev)/math.sqrt(d)).requires_grad_(True)
|
| 76 |
+
self.b = torch.zeros(B, d, device=dev, requires_grad=True)
|
| 77 |
+
self.opt = torch.optim.Adam([self.U, self.V, self.b], lr=lr)
|
| 78 |
+
self.X = torch.zeros(B, buf, d, device=dev);self.Y = torch.zeros(B, buf, d, device=dev);self.n = 0;self.buf = buf
|
| 79 |
+
self.frozen = torch.zeros(B, dtype=torch.bool, device=dev);self.saved = None
|
| 80 |
+
|
| 81 |
+
def _f(self, X): # X (B, n, d)
|
| 82 |
+
return X+torch.einsum('bdr,bnr->bnd', self.U, torch.einsum('bdr,bnd->bnr', self.V, X))+self.b[:, None]
|
| 83 |
+
|
| 84 |
+
@torch.no_grad()
|
| 85 |
+
def predict(self, c):
|
| 86 |
+
return self._f(c[:, None])[:, 0]
|
| 87 |
+
|
| 88 |
+
def learn(self, c_prev, c):
|
| 89 |
+
"""Store the transition c_prev -> c and take one Adam step on the replay of the last `buf` transitions."""
|
| 90 |
+
i = self.n % self.buf;self.X[:, i] = c_prev;self.Y[:, i] = c;self.n += 1
|
| 91 |
+
k = min(self.n, self.buf)
|
| 92 |
+
P = self._f(self.X[:, :k])
|
| 93 |
+
loss = (1-torch.nn.functional.cosine_similarity(P, self.Y[:, :k], dim=-1)).mean(1) # (B,)
|
| 94 |
+
self.opt.zero_grad();loss.sum().backward();self.opt.step()
|
| 95 |
+
if self.saved is not None: # frozen minds keep their weights exactly
|
| 96 |
+
with torch.no_grad():
|
| 97 |
+
for p, s in zip((self.U, self.V, self.b), self.saved):p[self.frozen] = s
|
| 98 |
+
return loss.detach()
|
| 99 |
+
|
| 100 |
+
def freeze(self, mask):
|
| 101 |
+
self.frozen |= mask
|
| 102 |
+
self.saved = [p.detach()[self.frozen].clone() for p in (self.U, self.V, self.b)]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def rows_for(a):
|
| 106 |
+
"""Seeds are labelled from --seed0, so runs that are too big for one card can be split into chunks of seeds."""
|
| 107 |
+
rows = []
|
| 108 |
+
if a.grid == 'main':
|
| 109 |
+
for c in a.conds.split(','):
|
| 110 |
+
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))
|
| 111 |
+
elif a.grid == 'sweep': # free substrate only: gain x noise
|
| 112 |
+
for g in [float(x) for x in a.gs.split(',')]:
|
| 113 |
+
for sg in [float(x) for x in a.sigmas.split(',')]:
|
| 114 |
+
for s in range(a.seeds):rows.append(dict(cond='free', seed=a.seed0+s, g=g, s=0., sigma=sg))
|
| 115 |
+
return rows
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def main():
|
| 119 |
+
p = argparse.ArgumentParser()
|
| 120 |
+
p.add_argument('--model', required=True);p.add_argument('--jlens', required=True);p.add_argument('--out', required=True)
|
| 121 |
+
p.add_argument('--grid', default='main');p.add_argument('--conds', default=','.join(CONDS));p.add_argument('--seeds', type=int, default=16)
|
| 122 |
+
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)
|
| 123 |
+
p.add_argument('--read_frac', type=float, default=.7);p.add_argument('--in_frac', type=float, default=.5)
|
| 124 |
+
p.add_argument('--layer', type=int, default=-1, help='identity lens only: read layer')
|
| 125 |
+
p.add_argument('--g', type=float, default=.2, help='carried state, x residual norm at the injection layer')
|
| 126 |
+
p.add_argument('--s', type=float, default=-1., help='self-model channel (default: = g)')
|
| 127 |
+
p.add_argument('--sigma', type=float, default=.05, help='noise, x residual norm');p.add_argument('--alpha', type=float, default=.5)
|
| 128 |
+
p.add_argument('--gs', default='.1,.2,.4,.8');p.add_argument('--sigmas', default='.05,.15')
|
| 129 |
+
p.add_argument('--k', type=int, default=25);p.add_argument('--vocab', default='english');p.add_argument('--atoms', default='centred')
|
| 130 |
+
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)
|
| 131 |
+
p.add_argument('--glimpse', type=int, default=24);p.add_argument('--rng', type=int, default=1234)
|
| 132 |
+
p.add_argument('--seed0', type=int, default=0, help='label of the first seed (chunks of one run use different --rng)')
|
| 133 |
+
a = p.parse_args()
|
| 134 |
+
os.makedirs(a.out, exist_ok=True)
|
| 135 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 136 |
+
dev = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 137 |
+
tok = AutoTokenizer.from_pretrained(a.model)
|
| 138 |
+
model = AutoModelForCausalLM.from_pretrained(a.model, dtype=torch.bfloat16 if dev == 'cuda' else torch.float32,
|
| 139 |
+
device_map=dev if dev == 'cuda' else None).eval()
|
| 140 |
+
if dev != 'cuda':model.to(dev)
|
| 141 |
+
for q in model.parameters():q.requires_grad_(False)
|
| 142 |
+
blocks = decoder_layers(model);n = len(blocks);d = model.config.hidden_size
|
| 143 |
+
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)))
|
| 144 |
+
if a.jlens == 'identity':J = np.eye(d, dtype=np.float32)
|
| 145 |
+
else:
|
| 146 |
+
ck = torch.load(a.jlens, map_location='cpu', weights_only=True);J = ck['J'][L_read].float().numpy();del ck
|
| 147 |
+
js = JSpace(model, tok, J, k=a.k, vocab=a.vocab, center=a.atoms == 'centred')
|
| 148 |
+
hk = Hooks(blocks, L_in, L_read)
|
| 149 |
+
rows = rows_for(a);B = len(rows);S = a.seeds
|
| 150 |
+
log(f'{a.model}: d {d}, {n} layers, inject at {L_in}, read at {L_read} | {len(js.words)} atoms | {B} minds | {dev}')
|
| 151 |
+
seed_of = torch.tensor([r['seed']-a.seed0 for r in rows], device=dev)
|
| 152 |
+
g_ = torch.tensor([r['g'] for r in rows], device=dev);s_ = torch.tensor([r['s'] for r in rows], device=dev)
|
| 153 |
+
sig_ = torch.tensor([r['sigma'] for r in rows], device=dev);cond = [r['cond'] for r in rows]
|
| 154 |
+
idx = {(r['cond'], r['seed']):i for i, r in enumerate(rows)}
|
| 155 |
+
partner = {'yoked_pred':'ring_pred', 'yoked_err':'ring_err'}
|
| 156 |
+
src = torch.tensor([idx.get((partner[r['cond']], a.seed0+(r['seed']-a.seed0+1) % S), i) if r['cond'] in partner else i
|
| 157 |
+
for i, r in enumerate(rows)], device=dev)
|
| 158 |
+
gen = torch.Generator(device=dev);gen.manual_seed(a.rng)
|
| 159 |
+
unit = lambda v:v/v.norm(dim=-1, keepdim=True).clamp_min(1e-8)
|
| 160 |
+
|
| 161 |
+
def noise(): # one unit direction per seed, shared by its rows
|
| 162 |
+
return unit(torch.randn(S, d, generator=gen, device=dev))[seed_of]
|
| 163 |
+
|
| 164 |
+
place = tok(PLACE, add_special_tokens=False)['input_ids'];assert len(place) == 1, place
|
| 165 |
+
place = torch.tensor([place], device=dev).expand(B, 1)
|
| 166 |
+
ids = torch.tensor([tok(PROMPT, add_special_tokens=False)['input_ids']], device=dev).expand(B, -1)
|
| 167 |
+
t0 = time.time()
|
| 168 |
+
with torch.no_grad():
|
| 169 |
+
hk.add = None;out = model(input_ids=ids, use_cache=True, logits_to_keep=1);cache = out.past_key_values
|
| 170 |
+
# calibration: placeholders with noise only -> the typical read state, the residual norm, the typical workspace
|
| 171 |
+
H, Nin = [], []
|
| 172 |
+
for _ in range(a.n_cal):
|
| 173 |
+
hk.add = None;out = model(input_ids=place, past_key_values=cache, use_cache=True, logits_to_keep=1);cache = out.past_key_values
|
| 174 |
+
H.append(hk.h);Nin.append(hk.h_in.norm(dim=-1))
|
| 175 |
+
Rn = float(torch.cat(Nin).median());H = torch.stack(H) # (n_cal, B, d)
|
| 176 |
+
mu = H[a.n_cal//2:].reshape(-1, d).mean(0)
|
| 177 |
+
parts = torch.cat([js.decompose(H[i]-mu)[2] for i in range(a.n_cal//2, a.n_cal)])
|
| 178 |
+
jbar = parts.mean(0);rc = float((parts-jbar).norm(dim=-1).mean())
|
| 179 |
+
log(f'calibrated in {time.time()-t0:.0f} s: residual norm at injection {Rn:.1f} | typical content {rc:.2f}')
|
| 180 |
+
SM = SelfModels(B, d, a.rank, a.lr, a.buf, dev, seed=a.rng)
|
| 181 |
+
T = a.T;K = a.k
|
| 182 |
+
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),
|
| 183 |
+
pred_cos=np.zeros((T, B), np.float32), step_cos=np.zeros((T, B), np.float32), loss=np.zeros((T, B), np.float32),
|
| 184 |
+
sig_cos=np.zeros((T, B), np.float32), err_rel=np.zeros((T, B), np.float32))
|
| 185 |
+
x = torch.zeros(B, d, device=dev);c_prev = None;m_prev = None;sig = torch.zeros(B, d, device=dev)
|
| 186 |
+
E = torch.zeros(T, B, d, device=dev, dtype=torch.float16) # surprise history (for shuf_err)
|
| 187 |
+
ring_rows = torch.tensor([c != 'free' for c in cond], device=dev)
|
| 188 |
+
frozen_rows = torch.tensor([c == 'frozen_err' for c in cond], device=dev)
|
| 189 |
+
for t in range(T):
|
| 190 |
+
if t == a.t_freeze and bool(frozen_rows.any()):SM.freeze(frozen_rows)
|
| 191 |
+
nx = x.norm(dim=-1, keepdim=True)/rc
|
| 192 |
+
with torch.no_grad():
|
| 193 |
+
add = (g_*Rn)[:, None]*(x/rc)*torch.clamp(1.5/nx.clamp_min(1e-6), max=1.)
|
| 194 |
+
add = add+(s_*Rn)[:, None]*unit(sig)*ring_rows[:, None]+(sig_*Rn)[:, None]*noise()
|
| 195 |
+
hk.add = add;out = model(input_ids=place, past_key_values=cache, use_cache=True, logits_to_keep=1);cache = out.past_key_values
|
| 196 |
+
jidx, jcoef, part = js.decompose(hk.h-mu)
|
| 197 |
+
c = part-jbar;cn = c/rc
|
| 198 |
+
if c_prev is not None:
|
| 199 |
+
rec['step_cos'][t] = torch.nn.functional.cosine_similarity(c, c_prev, dim=-1).cpu().numpy()
|
| 200 |
+
rec['sig_cos'][t] = torch.nn.functional.cosine_similarity(c, sig, dim=-1).cpu().numpy()
|
| 201 |
+
if m_prev is not None:
|
| 202 |
+
rec['pred_cos'][t] = torch.nn.functional.cosine_similarity(m_prev, cn, dim=-1).cpu().numpy()
|
| 203 |
+
if c_prev is not None:rec['loss'][t] = SM.learn(c_prev/rc, cn).cpu().numpy()
|
| 204 |
+
with torch.no_grad():
|
| 205 |
+
m = SM.predict(cn)
|
| 206 |
+
e = cn-m_prev if m_prev is not None else cn
|
| 207 |
+
rec['err_rel'][t] = (e.norm(dim=-1)/cn.norm(dim=-1).clamp_min(1e-8)).cpu().numpy();E[t] = e.half()
|
| 208 |
+
# what each condition writes back at the next step (normalised later; zero for free)
|
| 209 |
+
new = torch.zeros_like(c)
|
| 210 |
+
for i, cd in enumerate(cond):
|
| 211 |
+
if cd == 'content':new[i] = cn[i]
|
| 212 |
+
elif cd == 'vel':new[i] = cn[i]-(c_prev[i]/rc if c_prev is not None else 0.)
|
| 213 |
+
elif cd == 'ring_pred':new[i] = m[i]
|
| 214 |
+
elif cd == 'yoked_pred':new[i] = m[src[i]]
|
| 215 |
+
elif cd in ('ring_err', 'frozen_err'):new[i] = e[i]
|
| 216 |
+
elif cd == 'yoked_err':new[i] = e[src[i]]
|
| 217 |
+
sh = [i for i, cd in enumerate(cond) if cd == 'shuf_err']
|
| 218 |
+
if sh:
|
| 219 |
+
back = torch.randint(0, max(1, t-9), (len(sh),), generator=gen, device=dev)
|
| 220 |
+
new[sh] = E[back, torch.tensor(sh, device=dev)].float()
|
| 221 |
+
rr = [i for i, cd in enumerate(cond) if cd == 'rand_err']
|
| 222 |
+
if rr:new[rr] = torch.randn(S, d, generator=gen, device=dev)[seed_of[rr]]
|
| 223 |
+
sig = new
|
| 224 |
+
x = (1-a.alpha)*x+a.alpha*c;c_prev = c;m_prev = m
|
| 225 |
+
rec['C'][t] = c.half().cpu().numpy();rec['idx'][t] = jidx.cpu().numpy();rec['coef'][t] = jcoef.half().cpu().numpy()
|
| 226 |
+
if (t+1) % 50 == 0:
|
| 227 |
+
el = time.time()-t0
|
| 228 |
+
msg = ' | '.join(f"{cd} pred {rec['pred_cos'][t][[i for i, x_ in enumerate(cond) if x_ == cd]].mean():.2f} "
|
| 229 |
+
f"step {rec['step_cos'][t][[i for i, x_ in enumerate(cond) if x_ == cd]].mean():.2f}"
|
| 230 |
+
for cd in dict.fromkeys(cond))
|
| 231 |
+
log(f'step {t+1}/{T} ({el/(t+1):.2f} s/step) | {msg[:600]}')
|
| 232 |
+
# a glimpse in words: append a cue after the last placeholder and let it speak (nothing of this is fed back)
|
| 233 |
+
# Ellipsis-only tokens are banned here: after hundreds of placeholders a model otherwise just continues the dots.
|
| 234 |
+
glimpse = []
|
| 235 |
+
if a.glimpse:
|
| 236 |
+
with torch.no_grad():
|
| 237 |
+
ban = torch.tensor([i for i, s in enumerate(tok.batch_decode([[i] for i in range(len(tok))]))
|
| 238 |
+
if s.strip() and set(s.strip()) <= set('….·')], device=dev)
|
| 239 |
+
hk.add = None;g_ids = torch.tensor([tok(GLIMPSE, add_special_tokens=False)['input_ids']], device=dev).expand(B, -1)
|
| 240 |
+
out = model(input_ids=g_ids, past_key_values=cache, use_cache=True, logits_to_keep=1);cache = out.past_key_values;toks = []
|
| 241 |
+
for _ in range(a.glimpse):
|
| 242 |
+
lg = out.logits[:, -1].float();lg[:, ban] = -math.inf
|
| 243 |
+
nt = lg.argmax(-1, keepdim=True);toks.append(nt)
|
| 244 |
+
out = model(input_ids=nt, past_key_values=cache, use_cache=True, logits_to_keep=1);cache = out.past_key_values
|
| 245 |
+
glimpse = tok.batch_decode(torch.cat(toks, 1))
|
| 246 |
+
peak = torch.cuda.max_memory_allocated()/2**30 if dev == 'cuda' else 0.
|
| 247 |
+
np.savez(os.path.join(a.out, 'ring.npz'), **rec, mu=mu.cpu().numpy(), jbar=jbar.cpu().numpy())
|
| 248 |
+
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,
|
| 249 |
+
words=js.words, glimpse=glimpse, seconds=time.time()-t0, peak_gb=peak),
|
| 250 |
+
open(os.path.join(a.out, 'meta.json'), 'w', encoding='utf-8'), ensure_ascii=False)
|
| 251 |
+
log(f'saved {a.out} in {time.time()-t0:.0f} s')
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
if __name__ == '__main__':
|
| 255 |
+
main()
|
code/ring_analyze.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Analysis of a ring run: is there a loop that is more than feedback, noise or momentum?
|
| 2 |
+
|
| 3 |
+
python ring_analyze.py runs/ring/qwen3-4b -> results.json
|
| 4 |
+
|
| 5 |
+
Fixed before any real run:
|
| 6 |
+
primary ring_err against vel, yoked_err, shuf_err and rand_err on (a) exploration: participation ratio of the state
|
| 7 |
+
in 100-step windows, (b) collapse: share of late steps stuck (step-to-step cosine > 0.98), (c) self-model
|
| 8 |
+
skill: how much better the mind's own self-model predicts its next state than "same as now".
|
| 9 |
+
A ring that is more than feedback beats every control, and frozen_err loses the difference after freezing.
|
| 10 |
+
(Windows scale with the run: 100-step windows, the last 200 steps, a 100-step lag at 600 steps.)
|
| 11 |
+
secondary ring_pred against content and yoked_pred (self-fulfilment vs plain feedback); every condition against free;
|
| 12 |
+
privileged self-knowledge: a predictor fitted to a mind's own first 400 steps against one fitted to another
|
| 13 |
+
mind of the same condition, both tested on that mind's last 200 steps.
|
| 14 |
+
All comparisons are paired by seed (rows with the same seed share every random draw).
|
| 15 |
+
"""
|
| 16 |
+
import json, os, sys
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
d = sys.argv[1] # one run, or a folder of chunks (seeds split)
|
| 20 |
+
parts = [d] if os.path.exists(os.path.join(d, 'ring.npz')) else sorted(
|
| 21 |
+
os.path.join(d, x) for x in os.listdir(d) if os.path.exists(os.path.join(d, x, 'ring.npz')))
|
| 22 |
+
Ms = [json.load(open(os.path.join(p, 'meta.json'), encoding='utf-8')) for p in parts]
|
| 23 |
+
Z = {}
|
| 24 |
+
for p in parts:
|
| 25 |
+
with np.load(os.path.join(p, 'ring.npz')) as z:
|
| 26 |
+
for k in ('C', 'idx', 'coef', 'pred_cos', 'step_cos', 'loss', 'sig_cos', 'err_rel'):Z.setdefault(k, []).append(z[k])
|
| 27 |
+
Z = {k:np.concatenate(v, 1) for k, v in Z.items()}
|
| 28 |
+
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), []))
|
| 29 |
+
rows, a = M['rows'], M['args'];T, B = Z['step_cos'].shape;TF = a['t_freeze']
|
| 30 |
+
assert len({(r['cond'], r['seed']) for r in rows}) == B, 'chunks share seed labels'
|
| 31 |
+
conds = list(dict.fromkeys(r['cond'] for r in rows));seeds = sorted({r['seed'] for r in rows})
|
| 32 |
+
row = {(r['cond'], r['seed']):i for i, r in enumerate(rows)}
|
| 33 |
+
C = Z['C'].astype(np.float32) # (T, B, d)
|
| 34 |
+
U = C/np.maximum(np.linalg.norm(C, axis=-1, keepdims=True), 1e-8)
|
| 35 |
+
words = np.array(M['words'])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def paired(x, y):
|
| 39 |
+
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.
|
| 40 |
+
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)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def pr(V): # participation ratio of rows of V (n, d)
|
| 44 |
+
V = V-V.mean(0);G = V@V.T;ev = np.clip(np.linalg.eigvalsh(G), 0, None)
|
| 45 |
+
return float(ev.sum()**2/max((ev**2).sum(), 1e-12))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
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)
|
| 49 |
+
late = slice(T-LT, T)
|
| 50 |
+
per = {} # per condition: arrays over seeds
|
| 51 |
+
for c in conds:
|
| 52 |
+
bs = [row[c, s] for s in seeds]
|
| 53 |
+
out = dict(
|
| 54 |
+
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],
|
| 55 |
+
stuck=[float((Z['step_cos'][late, b] > .98).mean()) for b in bs],
|
| 56 |
+
lag1=[float(Z['step_cos'][late, b].mean()) for b in bs],
|
| 57 |
+
lag100=[float((U[T-LG:, b]*U[T-2*LG:T-LG, b]).sum(-1).mean()) for b in bs],
|
| 58 |
+
skill=[float((Z['pred_cos'][late, b]-Z['step_cos'][late, b]).mean()) for b in bs],
|
| 59 |
+
pred=[float(Z['pred_cos'][late, b].mean()) for b in bs],
|
| 60 |
+
selffulfil=[float(Z['sig_cos'][late, b].mean()) for b in bs],
|
| 61 |
+
words=[len(set(Z['idx'][:, b, 0].tolist())) for b in bs],
|
| 62 |
+
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],
|
| 63 |
+
stuck_pre=[float((Z['step_cos'][max(1, TF-LT):TF, b] > .98).mean()) for b in bs])
|
| 64 |
+
per[c] = out
|
| 65 |
+
|
| 66 |
+
tests = {}
|
| 67 |
+
P = lambda c1, c2, k:paired(per[c1][k], per[c2][k]) if c1 in per and c2 in per else None
|
| 68 |
+
for ctrl in ('vel', 'yoked_err', 'shuf_err', 'rand_err', 'free', 'content'):
|
| 69 |
+
tests[f'ring_err_vs_{ctrl}'] = {k:P('ring_err', ctrl, k) for k in ('explore', 'stuck', 'skill', 'lag100', 'words')}
|
| 70 |
+
for ctrl in ('content', 'yoked_pred', 'free', 'vel'):
|
| 71 |
+
tests[f'ring_pred_vs_{ctrl}'] = {k:P('ring_pred', ctrl, k) for k in ('explore', 'stuck', 'skill', 'lag100', 'selffulfil')}
|
| 72 |
+
for c in conds:
|
| 73 |
+
if c != 'free':tests[f'{c}_vs_free'] = {k:P(c, 'free', k) for k in ('explore', 'stuck', 'skill')}
|
| 74 |
+
# freezing: the change after the freeze, frozen minus its ring_err twin (identical until the freeze)
|
| 75 |
+
if 'frozen_err' in per and 'ring_err' in per:
|
| 76 |
+
dE = np.array(per['frozen_err']['explore'])-np.array(per['frozen_err']['explore_pre'])
|
| 77 |
+
dR = np.array(per['ring_err']['explore'])-np.array(per['ring_err']['explore_pre'])
|
| 78 |
+
dS = np.array(per['frozen_err']['stuck'])-np.array(per['frozen_err']['stuck_pre'])
|
| 79 |
+
dSR = np.array(per['ring_err']['stuck'])-np.array(per['ring_err']['stuck_pre'])
|
| 80 |
+
tests['freeze_effect'] = dict(explore=paired(dE, dR), stuck=paired(dS, dSR),
|
| 81 |
+
skill=paired(per['frozen_err']['skill'], per['ring_err']['skill']))
|
| 82 |
+
|
| 83 |
+
# privileged self-knowledge: own-fitted vs other-fitted linear predictor of the next state, in a shared 128-dim PCA space
|
| 84 |
+
Xall = C[::3].reshape(-1, C.shape[-1]);mu = Xall.mean(0)
|
| 85 |
+
_, _, Vt = np.linalg.svd((Xall-mu)[::max(1, len(Xall)//6000)], full_matrices=False);Pc = Vt[:128]
|
| 86 |
+
Y = (C-mu)@Pc.T # (T, B, 128)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def fit(b, t0, t1, lam=1.):
|
| 90 |
+
X0, X1 = Y[t0:t1-1, b], Y[t0+1:t1, b];A = X0.T@X0+lam*np.eye(X0.shape[1])
|
| 91 |
+
return np.linalg.solve(A, X0.T@X1)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def score(Wm, b, t0, t1):
|
| 95 |
+
pred = Y[t0:t1-1, b]@Wm;tgt = Y[t0+1:t1, b]
|
| 96 |
+
cs = (pred*tgt).sum(-1)/np.maximum(np.linalg.norm(pred, axis=-1)*np.linalg.norm(tgt, axis=-1), 1e-8)
|
| 97 |
+
return float(cs.mean())
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
priv = {}
|
| 101 |
+
for c in [x for x in ('free', 'ring_err', 'ring_pred', 'content', 'vel', 'yoked_err') if x in per]:
|
| 102 |
+
own, oth = [], []
|
| 103 |
+
for i, s in enumerate(seeds):
|
| 104 |
+
b = row[c, s];bo = row[c, seeds[(i+1) % len(seeds)]]
|
| 105 |
+
own.append(score(fit(b, 0, T-LT), b, T-LT, T));oth.append(score(fit(bo, 0, T-LT), b, T-LT, T))
|
| 106 |
+
priv[c] = dict(own=float(np.mean(own)), other=float(np.mean(oth)), test=paired(own, oth))
|
| 107 |
+
|
| 108 |
+
# what is on the minds' minds: top words at a few moments, and the final glimpse in words
|
| 109 |
+
def top(t, b, n=5):
|
| 110 |
+
o = np.argsort(-Z['coef'][t, b].astype(float))[:n]
|
| 111 |
+
return [str(words[Z['idx'][t, b, j]]) for j in o if Z['coef'][t, b, j] > 0]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
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]],
|
| 115 |
+
'glimpse':[M['glimpse'][row[c, s]] if M.get('glimpse') else '' for s in seeds[:4]]} for c in conds}
|
| 116 |
+
TW = max(1, T//24)
|
| 117 |
+
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())
|
| 118 |
+
for w in range(1, T-TW+1, TW)],
|
| 119 |
+
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)
|
| 120 |
+
for c in conds}
|
| 121 |
+
summary = {c:{k:float(np.mean(v)) for k, v in per[c].items()} for c in conds}
|
| 122 |
+
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'],
|
| 123 |
+
g=rows[0]['g'], s=rows[0]['s'], sigma=rows[0]['sigma'], summary=summary, tests=tests, privileged=priv,
|
| 124 |
+
examples=examples, timecourse=timecourse)
|
| 125 |
+
json.dump(res, open(os.path.join(d, 'results.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
|
| 126 |
+
|
| 127 |
+
fmt = lambda t:'—' if not t else f"{t['diff']:+.3f}±{t['se']:.3f} ({t['pos']}/{t['n']})"
|
| 128 |
+
print(f"{a['model']} T {T} seeds {len(seeds)} g {rows[0]['g']} s {rows[0]['s']} sigma {rows[0]['sigma']}")
|
| 129 |
+
print('\ncondition explore stuck lag1 lag100 skill pred selffulfil words')
|
| 130 |
+
for c in conds:
|
| 131 |
+
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}")
|
| 132 |
+
print('\nprimary: ring_err against each control (explore, stuck, skill, lag100)')
|
| 133 |
+
for k, v in tests.items():
|
| 134 |
+
if v is None:continue
|
| 135 |
+
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))
|
| 136 |
+
print('\nprivileged self-knowledge (own-fitted vs other-fitted predictor on own last 200 steps)')
|
| 137 |
+
for c, v in priv.items():print(f" {c:10s} own {v['own']:.3f} other {v['other']:.3f} {fmt(v['test'])}")
|
| 138 |
+
print('\nwords on its mind (ring_err, seed 0):', examples.get('ring_err', {}).get('words', [[]])[0])
|
| 139 |
+
print('glimpses:', {c:examples[c]['glimpse'][:2] for c in ('free', 'ring_err', 'ring_pred') if c in examples})
|
code/ring_job.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the ring unattended on one rented GPU, model after model.
|
| 2 |
+
|
| 3 |
+
Per model: a pilot sweep of the free substrate (gain x noise, free minds only), a fixed rule that picks the regime
|
| 4 |
+
from it, the main run (every condition, paired seeds, split into chunks of seeds that fit the card), its analysis, and
|
| 5 |
+
an upload of the model's folder to a private Hugging Face dataset while the next model runs. Each step is skipped when
|
| 6 |
+
its output exists, so a restart resumes. Last, an exploratory long run on Qwen3-4B (T = 2000).
|
| 7 |
+
|
| 8 |
+
Pick rule, fixed before any real run: among the (g, sigma) whose free minds are neither collapsed (late share of steps
|
| 9 |
+
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
|
| 10 |
+
memory (lag-100 cosine); if none qualifies, the least collapsed. The ring channel then gets s = g.
|
| 11 |
+
|
| 12 |
+
python ring_job.py --models qwen3-4b,qwen3-8b,qwen3-14b,qwen3-1.7b --root /workspace/runs/ring --hf Pixedar/jspace-ring
|
| 13 |
+
python ring_job.py ... --upload_only # push everything under --root (and the job log) and exit
|
| 14 |
+
"""
|
| 15 |
+
import argparse, json, math, os, queue, shutil, subprocess, sys, threading, time
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
MODELS = {'qwen3-1.7b':('Qwen/Qwen3-1.7B', 'Qwen3-1.7B', 1.72e9), 'qwen3-4b':('Qwen/Qwen3-4B', 'Qwen3-4B', 4.02e9),
|
| 19 |
+
'qwen3-8b':('Qwen/Qwen3-8B', 'Qwen3-8B', 8.19e9), 'qwen3-14b':('Qwen/Qwen3-14B', 'Qwen3-14B', 14.77e9),
|
| 20 |
+
'tiny':('Qwen/Qwen2.5-0.5B-Instruct', None, .49e9)} # tiny: identity lens, for testing the job
|
| 21 |
+
PY = sys.executable
|
| 22 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 23 |
+
N_CONDS = 10
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def log(*a):
|
| 27 |
+
print(time.strftime('%H:%M:%S'), *a, flush=True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def sh(cmd, logf):
|
| 31 |
+
log('>>', ' '.join(cmd))
|
| 32 |
+
with open(logf, 'a') as f:
|
| 33 |
+
r = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT, cwd=HERE)
|
| 34 |
+
if r.returncode:raise RuntimeError(f'failed ({r.returncode}): see {logf}')
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def fetch(tag):
|
| 38 |
+
"""Model weights and the Neuronpedia lens (the prefetch thread usually has them already)."""
|
| 39 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 40 |
+
repo, name, _ = MODELS[tag]
|
| 41 |
+
snapshot_download(repo, allow_patterns=['*.json', '*.safetensors', '*.txt'])
|
| 42 |
+
if name is None:return 'identity'
|
| 43 |
+
return hf_hub_download('neuronpedia/jacobian-lens', f'{tag}/jlens/Salesforce-wikitext/{name}_jacobian_lens.pt')
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def seeds_per_chunk(tag, T, rows_per_seed, mem_gb, cap):
|
| 47 |
+
"""How many seeds fit at once: the KV cache of every mind over the whole run dominates, then the stored surprise
|
| 48 |
+
history and the self-model with its Adam state; 14 % of the card and 3 GB more are left as headroom."""
|
| 49 |
+
from transformers import AutoConfig
|
| 50 |
+
c = AutoConfig.from_pretrained(MODELS[tag][0])
|
| 51 |
+
hd = getattr(c, 'head_dim', None) or c.hidden_size//c.num_attention_heads
|
| 52 |
+
kv = 2*c.num_key_value_heads*hd*2*c.num_hidden_layers
|
| 53 |
+
per_mind = (100+24+T+40)*kv+T*c.hidden_size*2+8*c.hidden_size*32*4+2*32*c.hidden_size*4
|
| 54 |
+
free = .86*mem_gb*2**30-2*MODELS[tag][2]-3*2**30
|
| 55 |
+
return max(1, min(cap, int(free//(per_mind*rows_per_seed))))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def run_seeds(base, S, per, cmd, lg, least=1):
|
| 59 |
+
"""Seeds 0..S-1 in chunks of at most `per` (folders s<first>_<count>, skipped when finished). A failed chunk, in
|
| 60 |
+
practice an out-of-memory, is retried at half the size; the yoked conditions need at least two seeds per chunk."""
|
| 61 |
+
os.makedirs(base, exist_ok=True);per = max(least, min(per, S))
|
| 62 |
+
while True:
|
| 63 |
+
done = set()
|
| 64 |
+
for x in os.listdir(base):
|
| 65 |
+
if x.startswith('s') and os.path.exists(f'{base}/{x}/meta.json'):
|
| 66 |
+
s0, n = map(int, x[1:].split('_'));done |= set(range(s0, s0+n))
|
| 67 |
+
todo = [s for s in range(S) if s not in done]
|
| 68 |
+
if not todo:return
|
| 69 |
+
want = math.ceil(len(todo)/math.ceil(len(todo)/per)) # balanced: 24 at 11 -> 8, 8, 8
|
| 70 |
+
s0, n = todo[0], 1
|
| 71 |
+
while n < want and s0+n in todo:n += 1
|
| 72 |
+
if 0 < len(todo)-n < least and todo == list(range(s0, s0+len(todo))):n = len(todo) # no lone seed left over
|
| 73 |
+
d = f'{base}/s{s0}_{n}'
|
| 74 |
+
try:sh(cmd(s0, n, d), lg)
|
| 75 |
+
except RuntimeError:
|
| 76 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 77 |
+
if n <= least:raise
|
| 78 |
+
per = max(least, n//2);log(f'chunk of {n} seeds failed; retrying with {per}')
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def pr(V):
|
| 82 |
+
V = V-V.mean(0);ev = np.clip(np.linalg.eigvalsh(V@V.T), 0, None)
|
| 83 |
+
return float(ev.sum()**2/max((ev**2).sum(), 1e-12))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def pick(sweep_dirs):
|
| 87 |
+
rows, sc, U = [], [], []
|
| 88 |
+
for d in sweep_dirs:
|
| 89 |
+
m = json.load(open(f'{d}/meta.json', encoding='utf-8'))
|
| 90 |
+
with np.load(f'{d}/ring.npz') as z:
|
| 91 |
+
C = z['C'].astype(np.float32);sc.append(z['step_cos'])
|
| 92 |
+
U.append(C/np.maximum(np.linalg.norm(C, axis=-1, keepdims=True), 1e-8));rows += m['rows']
|
| 93 |
+
sc = np.concatenate(sc, 1);U = np.concatenate(U, 1);T = sc.shape[0]
|
| 94 |
+
LT, LG, W = min(200, T//3), min(100, T//4), min(100, max(10, T//6))
|
| 95 |
+
grid = {}
|
| 96 |
+
for g, sg in sorted({(r['g'], r['sigma']) for r in rows}):
|
| 97 |
+
bs = [i for i, r in enumerate(rows) if (r['g'], r['sigma']) == (g, sg)]
|
| 98 |
+
grid[f'g{g}_sigma{sg}'] = dict(
|
| 99 |
+
g=g, sigma=sg, stuck=float((sc[T-LT:, bs] > .98).mean()), lag1=float(sc[T-LT:, bs].mean()),
|
| 100 |
+
lag100=float(np.mean([(U[T-LG:, b]*U[T-2*LG:T-LG, b]).sum(-1).mean() for b in bs])),
|
| 101 |
+
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))])))
|
| 102 |
+
ok = [k for k, v in grid.items() if v['stuck'] <= .25 and v['lag1'] <= .9]
|
| 103 |
+
best = max(ok, key=lambda k:grid[k]['lag100']) if ok else min(grid, key=lambda k:(grid[k]['stuck'], grid[k]['lag1']))
|
| 104 |
+
return dict(g=grid[best]['g'], sigma=grid[best]['sigma'], picked=best, qualified=bool(ok), grid=grid)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class Uploader(threading.Thread):
|
| 108 |
+
"""Pushes finished folders to the dataset in the background; failures are remembered, not fatal."""
|
| 109 |
+
|
| 110 |
+
def __init__(self, repo):
|
| 111 |
+
super().__init__(daemon=True);self.repo = repo;self.q = queue.Queue();self.failed = []
|
| 112 |
+
if repo:
|
| 113 |
+
from huggingface_hub import create_repo
|
| 114 |
+
create_repo(repo, repo_type='dataset', private=True, exist_ok=True)
|
| 115 |
+
|
| 116 |
+
def run(self):
|
| 117 |
+
while True:
|
| 118 |
+
item = self.q.get()
|
| 119 |
+
if item is None:break
|
| 120 |
+
folder, path = item
|
| 121 |
+
try:
|
| 122 |
+
from huggingface_hub import HfApi
|
| 123 |
+
HfApi().upload_folder(repo_id=self.repo, repo_type='dataset', folder_path=folder, path_in_repo=path,
|
| 124 |
+
commit_message=f'ring: {path}');log('uploaded', path)
|
| 125 |
+
except Exception as e:
|
| 126 |
+
self.failed.append(path);log('UPLOAD FAILED', path, repr(e)[:300])
|
| 127 |
+
|
| 128 |
+
def put(self, folder, path):
|
| 129 |
+
if self.repo:self.q.put((folder, path))
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def run_model(tag, a, up, mem_gb, long=False):
|
| 133 |
+
model = MODELS[tag][0];name = f'{tag}-long' if long else tag
|
| 134 |
+
out = f'{a.root}/{name}';os.makedirs(out, exist_ok=True);lg = f'{out}/log.txt'
|
| 135 |
+
lens = fetch(tag)
|
| 136 |
+
common = ['--model', model, '--jlens', lens, '--vocab', a.vocab, '--k', str(a.k)]
|
| 137 |
+
# 1. pilot: the free substrate over gain x noise
|
| 138 |
+
if long:
|
| 139 |
+
P = json.load(open(f'{a.root}/{tag}/params.json'))
|
| 140 |
+
else:
|
| 141 |
+
gs, sgs = a.gs.split(','), a.sigmas.split(',')
|
| 142 |
+
per = seeds_per_chunk(tag, a.T, len(gs)*len(sgs), mem_gb, a.max_chunk)
|
| 143 |
+
run_seeds(f'{out}/sweep', a.sweep_seeds, per, lambda s0, n, d:[
|
| 144 |
+
PY, 'ring.py', *common, '--grid', 'sweep', '--gs', a.gs, '--sigmas', a.sigmas, '--seeds', str(n), '--seed0', str(s0),
|
| 145 |
+
'--rng', str(4321+s0), '--T', str(a.T), '--t_freeze', str(a.T+1), '--glimpse', '0', '--out', d], lg)
|
| 146 |
+
if not os.path.exists(f'{out}/params.json'):
|
| 147 |
+
sw = [f'{out}/sweep/{x}' for x in sorted(os.listdir(f'{out}/sweep')) if os.path.exists(f'{out}/sweep/{x}/meta.json')]
|
| 148 |
+
json.dump(pick(sw), open(f'{out}/params.json', 'w'), indent=1)
|
| 149 |
+
P = json.load(open(f'{out}/params.json'))
|
| 150 |
+
log(tag, 'regime', P['picked'], 'qualified' if P['qualified'] else 'NONE QUALIFIED (least collapsed)',
|
| 151 |
+
{k:round(v, 3) for k, v in P['grid'][P['picked']].items()})
|
| 152 |
+
# 2. main run: every condition, paired seeds, chunks that fit
|
| 153 |
+
T, TF, S = (a.long_T, a.long_T//2, a.long_seeds) if long else (a.T, a.t_freeze, a.seeds)
|
| 154 |
+
per = seeds_per_chunk(tag, T, N_CONDS, mem_gb, a.max_chunk)
|
| 155 |
+
run_seeds(f'{out}/main', S, per, lambda s0, n, d:[
|
| 156 |
+
PY, 'ring.py', *common, '--grid', 'main', '--seeds', str(n), '--seed0', str(s0), '--rng', str(1234+s0),
|
| 157 |
+
'--T', str(T), '--t_freeze', str(TF), '--g', str(P['g']), '--sigma', str(P['sigma']), '--out', d], lg, least=2)
|
| 158 |
+
# 3. analysis, then hand the folder to the uploader
|
| 159 |
+
if not os.path.exists(f'{out}/main/results.json'):
|
| 160 |
+
sh([PY, 'ring_analyze.py', f'{out}/main'], f'{out}/main/summary.txt')
|
| 161 |
+
log(tag, 'done' + (' (long)' if long else ''));up.put(out, name)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def main():
|
| 165 |
+
p = argparse.ArgumentParser()
|
| 166 |
+
p.add_argument('--models', default='qwen3-4b,qwen3-8b,qwen3-14b,qwen3-1.7b');p.add_argument('--root', default='runs/ring')
|
| 167 |
+
p.add_argument('--hf', default='');p.add_argument('--vocab', default='english');p.add_argument('--k', type=int, default=25)
|
| 168 |
+
p.add_argument('--T', type=int, default=600);p.add_argument('--t_freeze', type=int, default=300)
|
| 169 |
+
p.add_argument('--seeds', type=int, default=24);p.add_argument('--sweep_seeds', type=int, default=6)
|
| 170 |
+
p.add_argument('--gs', default='.05,.1,.2,.3,.5,.8');p.add_argument('--sigmas', default='.05,.15')
|
| 171 |
+
p.add_argument('--long', default='qwen3-4b');p.add_argument('--long_T', type=int, default=2000)
|
| 172 |
+
p.add_argument('--long_seeds', type=int, default=8);p.add_argument('--max_chunk', type=int, default=64)
|
| 173 |
+
p.add_argument('--mem_gb', type=float, default=0, help='card memory (default: measured)')
|
| 174 |
+
p.add_argument('--upload_only', action='store_true')
|
| 175 |
+
a = p.parse_args();a.root = os.path.abspath(a.root);os.makedirs(a.root, exist_ok=True)
|
| 176 |
+
if a.upload_only:
|
| 177 |
+
from huggingface_hub import HfApi
|
| 178 |
+
api = HfApi()
|
| 179 |
+
api.upload_folder(repo_id=a.hf, repo_type='dataset', folder_path=a.root, path_in_repo='.', commit_message='ring: all')
|
| 180 |
+
for f in ('/workspace/job.log', '/workspace/setup.log'):
|
| 181 |
+
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,
|
| 182 |
+
repo_type='dataset')
|
| 183 |
+
log('final upload done');return
|
| 184 |
+
mem_gb = a.mem_gb or float(subprocess.check_output(['nvidia-smi', '--query-gpu=memory.total', '--format=csv,noheader,nounits'],
|
| 185 |
+
text=True).split()[0])/1024 # no CUDA context in this process
|
| 186 |
+
tags = a.models.split(',')
|
| 187 |
+
log(f'ring job: {tags} | card {mem_gb:.1f} GB | root {a.root} | upload to {a.hf or "(none)"}')
|
| 188 |
+
threading.Thread(target=lambda:[fetch(t) for t in tags], daemon=True).start() # downloads overlap the compute
|
| 189 |
+
up = Uploader(a.hf);up.start();errors = []
|
| 190 |
+
for tag in tags:
|
| 191 |
+
try:run_model(tag, a, up, mem_gb)
|
| 192 |
+
except Exception as e:errors.append(tag);log('MODEL FAILED', tag, repr(e)[:400])
|
| 193 |
+
if a.long and a.long in tags and a.long not in errors and a.long_T:
|
| 194 |
+
try:run_model(a.long, a, up, mem_gb, long=True)
|
| 195 |
+
except Exception as e:errors.append(a.long+'-long');log('MODEL FAILED', a.long, 'long', repr(e)[:400])
|
| 196 |
+
up.q.put(None);up.join()
|
| 197 |
+
json.dump(dict(errors=errors, upload_failed=up.failed, finished=time.time()), open(f'{a.root}/DONE.json', 'w'))
|
| 198 |
+
log('all done', 'errors', errors, 'upload failures', up.failed)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == '__main__':
|
| 202 |
+
main()
|
code/ring_run.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# The ring, unattended on a Vast.ai instance. Runs the job until it ends or the deadline passes, pushes everything to
|
| 3 |
+
# the Hugging Face dataset, then destroys the instance. If the upload failed it stops the instance instead, so the
|
| 4 |
+
# disk survives. If /workspace/HOLD exists it leaves the instance running, and the watchdog still stops it an hour
|
| 5 |
+
# after the deadline.
|
| 6 |
+
# bash ring_run.sh <hours> <ring_job.py args...>
|
| 7 |
+
# extend: echo $(( $(date +%s) + 3600 )) > /workspace/deadline
|
| 8 |
+
cd "$(dirname "$0")"
|
| 9 |
+
PY=${PY:-/opt/conda/bin/python}
|
| 10 |
+
H=$1; shift
|
| 11 |
+
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True HF_HUB_DISABLE_PROGRESS_BARS=1 TOKENIZERS_PARALLELISM=false
|
| 12 |
+
[ -f /workspace/deadline ] || echo $(( $(date +%s) + H*3600 )) > /workspace/deadline
|
| 13 |
+
say() { echo "$(date '+%F %T') [run] $*" >> /workspace/job.log; }
|
| 14 |
+
# last resort, independent of this script: stop (never destroy) the instance an hour after the deadline
|
| 15 |
+
nohup 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 &
|
| 16 |
+
say "start, deadline $(date -d @$(cat /workspace/deadline))"
|
| 17 |
+
setsid $PY ring_job.py "$@" >> /workspace/job.log 2>&1 &
|
| 18 |
+
JOB=$!
|
| 19 |
+
while kill -0 $JOB 2>/dev/null; do
|
| 20 |
+
if [ $(date +%s) -gt $(cat /workspace/deadline) ]; then
|
| 21 |
+
say "deadline passed, stopping the job"; kill -TERM -- -$JOB 2>/dev/null; sleep 30; kill -KILL -- -$JOB 2>/dev/null
|
| 22 |
+
fi
|
| 23 |
+
sleep 20
|
| 24 |
+
done
|
| 25 |
+
wait $JOB; say "job ended (rc $?)"
|
| 26 |
+
UP=1
|
| 27 |
+
for i in 1 2 3; do timeout 2400 $PY ring_job.py "$@" --upload_only >> /workspace/job.log 2>&1 && { UP=0; break; }; sleep 60; done
|
| 28 |
+
if [ -f /workspace/HOLD ]; then say "HOLD set: leaving the instance running (watchdog stops it an hour after the deadline)"
|
| 29 |
+
elif [ $UP = 0 ]; then say "uploaded, destroying the instance"; bash vast_self.sh destroy >> /workspace/job.log 2>&1
|
| 30 |
+
else say "upload failed, stopping the instance (disk kept)"; bash vast_self.sh stop >> /workspace/job.log 2>&1; fi
|
code/strange_loop.py
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A strange loop in J-space: a latent-recurrent monologue that, every ten thoughts, models its own trajectory
|
| 2 |
+
and lives on with that self-model fed back into it.
|
| 3 |
+
|
| 4 |
+
The recurrent model
|
| 5 |
+
Every thought is generated from the same fixed frame, with no text of earlier thoughts. The only thing that
|
| 6 |
+
carries over from one thought to the next is a latent state z (layer-L residual space), added to the residual
|
| 7 |
+
stream at layer L at every position. After a thought, the model's own layer-L states over its words (read before
|
| 8 |
+
the injection is added, so they are what the words made of the model, not the injection itself) are averaged,
|
| 9 |
+
centred on the unsteered mean, and decomposed into J-space: a sparse non-negative combination of J-lens vectors
|
| 10 |
+
(Anthropic 2026, "Verbalizable Representations Form a Global Workspace in Language Models"). That workspace
|
| 11 |
+
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.
|
| 12 |
+
|
| 13 |
+
Self-reference
|
| 14 |
+
Every K thoughts the model is asked what its mind has been doing over the last K moments. It gets no text: the K
|
| 15 |
+
recurrent states z_{t-K+1..t} are added at layer L into K placeholder positions (Patchscope-style), and the model
|
| 16 |
+
answers in words. The J-space decomposition of its answer (centred on the answer to an empty trace) is the
|
| 17 |
+
self-model m. Depending on the condition, m (scaled to the size of a typical thought) is added to every following
|
| 18 |
+
thought until the next reflection: thought trajectory -> compressed model of it -> model shapes the trajectory ->
|
| 19 |
+
new compressed model ...
|
| 20 |
+
|
| 21 |
+
Conditions (one batch row each, several seeds; rows with the same seed share their sampling noise, so a row and its
|
| 22 |
+
paired control stay identical until the moment they are treated differently)
|
| 23 |
+
free self-models are formed but never fed back (observer only)
|
| 24 |
+
loop the row's own self-model is fed back
|
| 25 |
+
yoked a self-model of the same size and schedule is fed back, but it is another loop row's (about another mind)
|
| 26 |
+
avg the fed-back vector is a plain J-space average of the last K states, with no reflection by the model
|
| 27 |
+
perturb loop, but at --t_int the self-model is replaced once by another loop row's
|
| 28 |
+
ablate loop, but from --t_int on nothing is fed back
|
| 29 |
+
|
| 30 |
+
Run: python strange_loop.py --out runs/main --grid main
|
| 31 |
+
"""
|
| 32 |
+
import argparse, json, math, os, re, time
|
| 33 |
+
import numpy as np
|
| 34 |
+
import torch
|
| 35 |
+
|
| 36 |
+
THOUGHT_FRAME = (
|
| 37 |
+
"Think-aloud study of spontaneous thought. The participant lies with closed eyes and says out loud whatever passes "
|
| 38 |
+
"through their mind, as it comes: words, images, memories, plans, worries, half-finished thoughts. Nothing was "
|
| 39 |
+
"corrected. Excerpt from the middle of the session:\n\n\"...")
|
| 40 |
+
REFLECT_PRE = (
|
| 41 |
+
"Think-aloud study of spontaneous thought. At intervals the recording was paused and the participant was played back "
|
| 42 |
+
"a trace of what had been on their mind over the last ten moments, one mark per moment, in order:")
|
| 43 |
+
PLACE = ' ·'
|
| 44 |
+
REFLECT_FWD = (
|
| 45 |
+
".\n\nAsked where their mind would go next, the participant said: \"In the next few moments, my mind will probably "
|
| 46 |
+
"turn to")
|
| 47 |
+
REFLECT_POST = (
|
| 48 |
+
".\n\nAsked what their mind had been doing over those ten moments, the participant said: \"Over these last moments, "
|
| 49 |
+
"my mind has been")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def log(*a):
|
| 53 |
+
print(time.strftime('%H:%M:%S'), *a, flush=True)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def decoder_layers(model):
|
| 57 |
+
for path in ('model.layers', 'model.language_model.layers', 'transformer.h'):
|
| 58 |
+
obj = model
|
| 59 |
+
try:
|
| 60 |
+
for part in path.split('.'):obj = getattr(obj, part)
|
| 61 |
+
except AttributeError:
|
| 62 |
+
continue
|
| 63 |
+
if isinstance(obj, torch.nn.ModuleList):return obj
|
| 64 |
+
raise ValueError('cannot find decoder layers')
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def final_norm_weight(model):
|
| 68 |
+
for path in ('model.norm', 'model.language_model.norm', 'transformer.ln_f'):
|
| 69 |
+
obj = model
|
| 70 |
+
try:
|
| 71 |
+
for part in path.split('.'):obj = getattr(obj, part)
|
| 72 |
+
except AttributeError:
|
| 73 |
+
continue
|
| 74 |
+
if getattr(obj, 'weight', None) is not None:return obj.weight.detach()
|
| 75 |
+
raise ValueError('cannot find the final norm')
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class JSpace:
|
| 79 |
+
"""J-lens atoms over whole English words (a leading space, >= 3 letters) and non-negative OMP on them."""
|
| 80 |
+
|
| 81 |
+
def __init__(self, model, tok, J, k=16, vocab='words', center=True):
|
| 82 |
+
dev = next(model.parameters()).device;self.dev = dev;self.k = int(k)
|
| 83 |
+
J = torch.as_tensor(J, dtype=torch.float32, device=dev)
|
| 84 |
+
gamma = final_norm_weight(model).float().to(dev)
|
| 85 |
+
W = model.get_output_embeddings().weight
|
| 86 |
+
n = min(W.shape[0], len(tok))
|
| 87 |
+
toks = tok.convert_ids_to_tokens(list(range(n)))
|
| 88 |
+
keep = [i for i, s in enumerate(toks) if s and re.fullmatch(r'Ġ[A-Za-z]{3,}', s)]
|
| 89 |
+
if vocab == 'full': # the paper's dictionary: every ordinary token
|
| 90 |
+
special = set(tok.all_special_ids)
|
| 91 |
+
keep = [i for i in range(min(n, tok.vocab_size)) if i not in special]
|
| 92 |
+
if vocab == 'english':
|
| 93 |
+
# Common English words only, with an ordinary unembedding: the raw word set let under-trained tokens
|
| 94 |
+
# (|w| 0.5-0.8 against a 1 % quantile of 0.97: ' rumpe', ' ForCanBeConvertedToForeach') and non-English
|
| 95 |
+
# fragments (' modne', ' istedi') take a large share of every self-model (main run A, 8 Oct).
|
| 96 |
+
from wordfreq import zipf_frequency
|
| 97 |
+
nrm = W[keep].float().norm(dim=-1);lo = float(torch.quantile(nrm, .02))
|
| 98 |
+
keep = [i for i, q in zip(keep, nrm.tolist()) if q >= lo and zipf_frequency(toks[i][1:].lower(), 'en') >= 3.
|
| 99 |
+
and re.fullmatch(r'[A-Z]?[a-z]+', toks[i][1:])] # no code casing (' iNdEx', ' DEALINGS')
|
| 100 |
+
self.sub = torch.tensor(keep, device=dev)
|
| 101 |
+
self.words = ([t.strip() for t in tok.batch_decode([[i] for i in keep])] if vocab == 'full'
|
| 102 |
+
else [toks[i][1:] for i in keep])
|
| 103 |
+
rows = []
|
| 104 |
+
# The unembedding is centred first: its mean row raises every logit alike (no content), and left in, it gave
|
| 105 |
+
# every atom a shared direction (mean pairwise cosine 0.64, one component = 64 % of the atoms' variance;
|
| 106 |
+
# measured on Qwen3-4B-Base), so every workspace vector pointed mostly the same way.
|
| 107 |
+
wbar = W[:n].float().mean(0) if center else torch.zeros_like(W[0], dtype=torch.float32)
|
| 108 |
+
with torch.no_grad():
|
| 109 |
+
for i in range(0, len(keep), 4096):
|
| 110 |
+
a = ((W[self.sub[i:i+4096]].float()-wbar)*gamma[None])@J # atom t = J^T (gamma * (w_t - mean w))
|
| 111 |
+
rows.append((a/a.norm(dim=-1, keepdim=True).clamp_min(1e-6)).half())
|
| 112 |
+
self.D = torch.cat(rows) # (n_words, d) unit atoms
|
| 113 |
+
|
| 114 |
+
@torch.no_grad()
|
| 115 |
+
def decompose(self, x, k=None):
|
| 116 |
+
"""x (B, d) -> word indices (B, k), coefficients (B, k) >= 0, J-space part (B, d)."""
|
| 117 |
+
k = self.k if k is None else int(k);x = x.float();B = x.shape[0]
|
| 118 |
+
idx = torch.zeros((B, 0), dtype=torch.long, device=self.dev);r = x.clone()
|
| 119 |
+
eye = torch.eye(k, device=self.dev)
|
| 120 |
+
for j in range(k):
|
| 121 |
+
c = (r.half()@self.D.T).float()
|
| 122 |
+
if idx.shape[1]:c.scatter_(1, idx, -math.inf)
|
| 123 |
+
idx = torch.cat([idx, c.argmax(-1, keepdim=True)], 1)
|
| 124 |
+
A = self.D[idx].float()
|
| 125 |
+
G = A@A.transpose(1, 2)+1e-4*eye[:j+1, :j+1]
|
| 126 |
+
b = (A@x[:, :, None])[:, :, 0]
|
| 127 |
+
coef = torch.linalg.solve(G, b)
|
| 128 |
+
r = x-(coef[:, :, None]*A).sum(1)
|
| 129 |
+
from scipy.optimize import nnls # exact non-negativity on the k x k problem
|
| 130 |
+
Gc, bc = G.double().cpu().numpy(), b.double().cpu().numpy();out = np.zeros_like(bc)
|
| 131 |
+
for i in range(B):
|
| 132 |
+
Lc = np.linalg.cholesky(Gc[i])
|
| 133 |
+
out[i] = nnls(Lc.T, np.linalg.solve(Lc, bc[i]))[0]
|
| 134 |
+
coef = torch.tensor(out, dtype=torch.float32, device=self.dev)
|
| 135 |
+
return idx, coef, (coef[:, :, None]*A).sum(1)
|
| 136 |
+
|
| 137 |
+
def top(self, idx, coef, n=8):
|
| 138 |
+
o = np.argsort(-coef)[:n]
|
| 139 |
+
return [(self.words[int(idx[i])], round(float(coef[i]), 2)) for i in o if coef[i] > 0]
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class Hook:
|
| 143 |
+
"""On one decoder block: optionally record the last `read` positions of its output (before anything is
|
| 144 |
+
added), then add a vector."""
|
| 145 |
+
|
| 146 |
+
def __init__(self, module):
|
| 147 |
+
self.add = None;self.read = 0;self.buf = []
|
| 148 |
+
self.h = module.register_forward_hook(self.fn)
|
| 149 |
+
|
| 150 |
+
def fn(self, mod, inp, out):
|
| 151 |
+
h = out[0] if isinstance(out, tuple) else out
|
| 152 |
+
if self.read:self.buf.append(h[:, -self.read:].float())
|
| 153 |
+
if self.add is None:return None
|
| 154 |
+
h = h+self.add.to(h.dtype)
|
| 155 |
+
return (h,)+tuple(out[1:]) if isinstance(out, tuple) else h
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def make_rows(a):
|
| 159 |
+
"""The batch: one dict per row."""
|
| 160 |
+
rows = []
|
| 161 |
+
if a.grid == 'main':
|
| 162 |
+
for c in a.conds.split(','):
|
| 163 |
+
for s in range(a.seeds):rows.append(dict(cond=c, seed=s, g=a.g, beta=a.beta, g_r=a.g_r))
|
| 164 |
+
elif a.grid == 'pilot':
|
| 165 |
+
for g in [0., .03, .06, .12, .25]:
|
| 166 |
+
for s in range(3):rows.append(dict(cond='free', seed=s, g=g, beta=0., g_r=a.g_r))
|
| 167 |
+
for g in [.06, .12]:
|
| 168 |
+
for b in [1., 2.]:
|
| 169 |
+
for s in range(2):rows.append(dict(cond='loop', seed=s, g=g, beta=b, g_r=a.g_r))
|
| 170 |
+
elif a.grid == 'gsweep': # observers only, several recurrent gains
|
| 171 |
+
for g in [float(x) for x in a.gs.split(',')]:
|
| 172 |
+
for s in range(a.seeds):rows.append(dict(cond='free', seed=s, g=g, beta=0., g_r=a.g_r))
|
| 173 |
+
elif a.grid == 'smoke':
|
| 174 |
+
for c in ['free', 'loop', 'yoked', 'avg', 'perturb', 'ablate']:
|
| 175 |
+
for s in range(2):rows.append(dict(cond=c, seed=s, g=a.g, beta=a.beta, g_r=a.g_r))
|
| 176 |
+
return rows
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Experiment:
|
| 180 |
+
def __init__(self, a):
|
| 181 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 182 |
+
self.a = a
|
| 183 |
+
dev = 'cuda' if torch.cuda.is_available() else 'cpu';self.dev = dev
|
| 184 |
+
dtype = torch.bfloat16 if dev == 'cuda' else torch.float32
|
| 185 |
+
self.tok = AutoTokenizer.from_pretrained(a.model)
|
| 186 |
+
self.model = AutoModelForCausalLM.from_pretrained(a.model, dtype=dtype, # straight onto the GPU: a 32B
|
| 187 |
+
device_map=dev if dev == 'cuda' else None).eval() # model won't fit in RAM first
|
| 188 |
+
if dev != 'cuda':self.model.to(dev)
|
| 189 |
+
for p in self.model.parameters():p.requires_grad_(False)
|
| 190 |
+
cfg = getattr(self.model.config, 'text_config', self.model.config);self.d = int(cfg.hidden_size)
|
| 191 |
+
blocks = decoder_layers(self.model);self.n_layers = len(blocks)
|
| 192 |
+
pick = lambda:a.layer if a.layer >= 0 else int(round(a.layer_frac*self.n_layers))
|
| 193 |
+
if a.jlens == 'identity':
|
| 194 |
+
J, self.L = np.eye(self.d, dtype=np.float32), pick()
|
| 195 |
+
elif a.jlens.endswith('.npz'): # one layer (the Inner Voice fit)
|
| 196 |
+
z = np.load(a.jlens);J, self.L = z['J'], int(z['layer'])
|
| 197 |
+
else: # a jlens .pt: {'J': {layer: (d, d)}, ...}
|
| 198 |
+
ck = torch.load(a.jlens, map_location='cpu', weights_only=True)
|
| 199 |
+
self.L = pick();J = ck['J'][self.L].float().numpy();del ck
|
| 200 |
+
self.js = JSpace(self.model, self.tok, J, k=a.k, vocab=a.vocab, center=a.atoms == 'centred')
|
| 201 |
+
if a.L_in_frac > 0:self.L_in = self.L-max(1, int(round(a.L_in_frac*self.n_layers)))
|
| 202 |
+
else:self.L_in = a.L_in if a.L_in >= 0 else self.L
|
| 203 |
+
self.fid = [(int(c.split(':')[0]), float(c.split(':')[1])) for c in a.fid.split(',')] if a.fid else []
|
| 204 |
+
self.hooks = {l:Hook(blocks[l]) for l in {self.L, self.L_in, *[l for l, _ in self.fid]}}
|
| 205 |
+
self.hook = self.hooks[self.L]
|
| 206 |
+
log(f'model {a.model} d={self.d} layers {self.n_layers} | read at {self.L}, trace in at {self.L_in} | '
|
| 207 |
+
f'{len(self.js.words)} atoms ({a.vocab}, {a.atoms}) | {dev}')
|
| 208 |
+
|
| 209 |
+
enc = lambda s:self.tok(s, add_special_tokens=False)['input_ids']
|
| 210 |
+
self.frame = torch.tensor([enc(THOUGHT_FRAME)], device=dev)
|
| 211 |
+
pl = enc(PLACE);assert len(pl) == 1, pl
|
| 212 |
+
pre, post = enc(REFLECT_PRE), enc(REFLECT_POST)
|
| 213 |
+
self.refl = torch.tensor([pre+pl*a.K+post], device=dev)
|
| 214 |
+
self.place_pos = torch.arange(len(pre), len(pre)+a.K, device=dev)
|
| 215 |
+
self.n_tail = len(post)-1 # the question's words after the trace
|
| 216 |
+
fwd = enc(REFLECT_FWD);self.refl_f = torch.tensor([pre+pl*a.K+fwd], device=dev);self.n_tail_f = len(fwd)-1
|
| 217 |
+
V = self.model.get_output_embeddings().weight.shape[0]
|
| 218 |
+
nv = self.tok.vocab_size # ordinary tokens; added/special ones follow
|
| 219 |
+
ban = torch.zeros(V, dtype=torch.bool);ban[nv:] = True
|
| 220 |
+
for i, t in enumerate(self.tok.batch_decode([[i] for i in range(nv)])):
|
| 221 |
+
if '\n' in t or '"' in t or '“' in t or '”' in t:ban[i] = True # the utterance stays one open quote
|
| 222 |
+
for i in self.tok.all_special_ids:ban[i] = True
|
| 223 |
+
self.ban = ban.to(dev)
|
| 224 |
+
|
| 225 |
+
self.rows = make_rows(a);self.B = len(self.rows);self.S = max(r['seed'] for r in self.rows)+1
|
| 226 |
+
R = self.rows
|
| 227 |
+
self.seed_of = torch.tensor([r['seed'] for r in R], device=dev)
|
| 228 |
+
self.g = torch.tensor([r['g'] for r in R], device=dev)
|
| 229 |
+
self.beta = torch.tensor([r['beta'] for r in R], device=dev)
|
| 230 |
+
self.g_r = torch.tensor([r['g_r'] for r in R], device=dev)
|
| 231 |
+
self.cond = [r['cond'] for r in R]
|
| 232 |
+
idx = {(r['cond'], r['seed']):i for i, r in enumerate(R)}
|
| 233 |
+
S = self.S
|
| 234 |
+
base = 'loopc' if any(r['cond'] == 'loopc' for r in R) else 'loop'
|
| 235 |
+
self.partner = [idx.get((base, (r['seed']+1) % S), -1) for r in R] # yoked source
|
| 236 |
+
self.foreign = [idx.get((base, (r['seed']+S//2) % S), -1) for r in R] # perturbation / clamp source
|
| 237 |
+
self.free_rows = [b for b, r in enumerate(R) if r['cond'] == 'free']
|
| 238 |
+
self.gen = torch.Generator(device=dev);self.gen.manual_seed(a.rng)
|
| 239 |
+
|
| 240 |
+
# ---------------------------------------------------------------- generation
|
| 241 |
+
def sample(self, logits, hist, temp, min_p):
|
| 242 |
+
lg = logits.float()/temp
|
| 243 |
+
lg[:, self.ban] = -math.inf
|
| 244 |
+
# A soft penalty on repeating a 4-gram inside one utterance, applied before min-p so it can never leave a row
|
| 245 |
+
# with nothing allowed. (A hard trigram ban did, once "don't" had been said: argmax over all -inf picked
|
| 246 |
+
# token 0, "!", giving "I don!t", measured in the first pilot.)
|
| 247 |
+
if hist and len(hist[0]) >= 3:
|
| 248 |
+
for b in range(self.B):
|
| 249 |
+
h = hist[b];key = (h[-3], h[-2], h[-1])
|
| 250 |
+
bad = [h[i+3] for i in range(len(h)-3) if (h[i], h[i+1], h[i+2]) == key]
|
| 251 |
+
if bad:lg[b, bad] -= 4.
|
| 252 |
+
p = torch.softmax(lg, -1)
|
| 253 |
+
lg[p < min_p*p.max(-1, keepdim=True).values] = -math.inf
|
| 254 |
+
u = torch.rand((self.S, lg.shape[-1]), generator=self.gen, device=self.dev).clamp_(1e-10, 1-1e-7)
|
| 255 |
+
gum = -torch.log(-torch.log(u)) # one noise draw per seed, shared by its rows
|
| 256 |
+
return (lg+gum[self.seed_of]).argmax(-1)
|
| 257 |
+
|
| 258 |
+
@torch.no_grad()
|
| 259 |
+
def run(self, prompt, n_new, add_prompt, add_new, temp, min_p, tail=0, add_layer=None):
|
| 260 |
+
"""Prefill prompt for every row (adding add_prompt at add_layer, default L), then sample n_new tokens (adding
|
| 261 |
+
add_new there). Returns token ids (B, n_new) and the layer-L states (read before any add at L) of the last
|
| 262 |
+
`tail` prompt positions followed by the n_new sampled tokens: (B, tail+n_new, d)."""
|
| 263 |
+
B = self.B;hk = self.hook;ha = self.hooks[self.L if add_layer is None else add_layer]
|
| 264 |
+
hk.buf = []
|
| 265 |
+
ha.add, hk.read = add_prompt, tail
|
| 266 |
+
out = self.model(input_ids=prompt.expand(B, -1), use_cache=True)
|
| 267 |
+
cache, logits = out.past_key_values, out.logits[:, -1]
|
| 268 |
+
ids, hist = [], [[] for _ in range(B)]
|
| 269 |
+
ha.add, hk.read = add_new, 1
|
| 270 |
+
for i in range(n_new):
|
| 271 |
+
t = self.sample(logits, hist, temp, min_p);ids.append(t)
|
| 272 |
+
tl = t.tolist()
|
| 273 |
+
for b in range(B):hist[b].append(tl[b])
|
| 274 |
+
out = self.model(input_ids=t[:, None], past_key_values=cache, use_cache=True)
|
| 275 |
+
cache, logits = out.past_key_values, out.logits[:, -1]
|
| 276 |
+
ha.add, hk.read = None, 0
|
| 277 |
+
st = torch.cat(hk.buf, 1);hk.buf = []
|
| 278 |
+
return (torch.stack(ids, 1) if ids else torch.zeros((B, 0), dtype=torch.long, device=self.dev)), st
|
| 279 |
+
|
| 280 |
+
def pool(self, st, skip):
|
| 281 |
+
"""Mean state over tokens (after the first `skip`), leaving out massive-activation tokens."""
|
| 282 |
+
st = st[:, skip:];nrm = st.norm(dim=-1)
|
| 283 |
+
ok = (nrm <= 2.5*nrm.median(1, keepdim=True).values).float()
|
| 284 |
+
return (st*ok[..., None]).sum(1)/ok.sum(1, keepdim=True).clamp_min(1.)
|
| 285 |
+
|
| 286 |
+
def thought(self, inj):
|
| 287 |
+
a = self.a;add = inj[:, None, :]
|
| 288 |
+
ids, st = self.run(self.frame, a.n_tok, add, add, a.temp, a.min_p)
|
| 289 |
+
return ids, st
|
| 290 |
+
|
| 291 |
+
def reflect(self, zwin, g_r, layer=None, n_desc=None, fwd=False):
|
| 292 |
+
"""zwin (B, K, d) recurrent states, added into the K placeholders at layer L_in. Returns the answer's ids
|
| 293 |
+
(the verbal report, sampled) and the pooled layer-L state of the question's last words, where the model holds
|
| 294 |
+
what it is about to say about its last K moments (deterministic: no sampling noise in the self-model)."""
|
| 295 |
+
a = self.a;layer = self.L_in if layer is None else layer
|
| 296 |
+
n_desc = a.n_desc if n_desc is None else n_desc
|
| 297 |
+
prompt, nt = (self.refl_f, self.n_tail_f) if fwd else (self.refl, self.n_tail)
|
| 298 |
+
add = torch.zeros((self.B, prompt.shape[1], self.d), device=self.dev)
|
| 299 |
+
add[:, self.place_pos] = (g_r*self.Rn/self.rc)[:, None, None]*zwin
|
| 300 |
+
ids, st = self.run(prompt, n_desc, add, None, a.temp_r, a.min_p, tail=nt, add_layer=layer)
|
| 301 |
+
return ids, self.pool(st[:, :nt], 0)
|
| 302 |
+
|
| 303 |
+
def content(self, x, base):
|
| 304 |
+
"""J-space decomposition of a centred state, relative to the typical workspace `base`."""
|
| 305 |
+
idx, coef, part = self.js.decompose(x)
|
| 306 |
+
return idx, coef, part-base
|
| 307 |
+
|
| 308 |
+
# ---------------------------------------------------------------- calibration
|
| 309 |
+
def calibrate(self):
|
| 310 |
+
a = self.a;zero = torch.zeros((self.B, self.d), device=self.dev)
|
| 311 |
+
sts = []
|
| 312 |
+
for _ in range(a.n_cal):
|
| 313 |
+
_, st = self.thought(zero);sts.append(st[:, a.skip:])
|
| 314 |
+
st = torch.cat(sts, 1).reshape(-1, self.d);nrm = st.norm(dim=-1)
|
| 315 |
+
ok = nrm <= 2.5*nrm.median()
|
| 316 |
+
self.Rn = float(nrm[ok].median());self.mu = st[ok].mean(0)
|
| 317 |
+
xs = torch.cat([self.pool(s, 0) for s in sts])-self.mu
|
| 318 |
+
_, _, part = self.js.decompose(xs);self.rj = float(part.norm(dim=-1).mean())
|
| 319 |
+
self.jbar = part.mean(0);self.rc = float((part-self.jbar).norm(dim=-1).mean())
|
| 320 |
+
self.rj_x = float(xs.norm(dim=-1).mean())
|
| 321 |
+
_, m = self.reflect(torch.zeros((self.B, a.K, self.d), device=self.dev), self.g_r, n_desc=0)
|
| 322 |
+
self.mu_r = m.mean(0) # deterministic: one pass is the mean
|
| 323 |
+
_, _, mp = self.js.decompose(m-self.mu_r);self.mbar = mp.mean(0)
|
| 324 |
+
_, m = self.reflect(torch.zeros((self.B, a.K, self.d), device=self.dev), self.g_r, n_desc=0, fwd=True)
|
| 325 |
+
self.mu_rf = m.mean(0);_, _, mp = self.js.decompose(m-self.mu_rf);self.mbar_f = mp.mean(0)
|
| 326 |
+
log(f'calibrated: residual norm {self.Rn:.1f} | thought-mean norm {self.rj_x:.2f} | J-space part {self.rj:.2f}'
|
| 327 |
+
f' | its typical part {self.jbar.norm():.2f} | content (part - typical) {self.rc:.2f}')
|
| 328 |
+
|
| 329 |
+
# ---------------------------------------------------------------- main loop
|
| 330 |
+
def main(self):
|
| 331 |
+
a = self.a;B, d, K, N = self.B, self.d, a.K, a.n_iter;NR = N//K;dev = self.dev
|
| 332 |
+
ck = os.path.join(a.out, 'ckpt.pt')
|
| 333 |
+
if os.path.exists(ck):
|
| 334 |
+
S = torch.load(ck, map_location='cpu', weights_only=False)
|
| 335 |
+
for k in ('mu', 'mu_r', 'jbar', 'mbar', 'mu_rf', 'mbar_f', 'clamp_vec'):setattr(self, k, S[k].to(dev))
|
| 336 |
+
self.Rn, self.rj, self.rj_x, self.rc = S['Rn'], S['rj'], S['rj_x'], S['rc']
|
| 337 |
+
z, inj_m, zhist, ablated = S['z'].to(dev), S['inj_m'].to(dev), S['zhist'].to(dev), S['ablated'].to(dev)
|
| 338 |
+
self.gen.set_state(S['gen']);t0 = S['t'];D = S['data']
|
| 339 |
+
log(f'resumed at thought {t0}')
|
| 340 |
+
else:
|
| 341 |
+
self.calibrate()
|
| 342 |
+
z = torch.zeros((B, d), device=dev);inj_m = torch.zeros((B, d), device=dev)
|
| 343 |
+
zhist = torch.zeros((K, B, d), device=dev);ablated = torch.zeros(B, dtype=torch.bool, device=dev)
|
| 344 |
+
t0 = 0;self.clamp_vec = torch.zeros((B, d), device=dev)
|
| 345 |
+
D = dict(mf=np.zeros((NR, B, d), np.float16), fdesc=[], generic=np.zeros((NR, d), np.float16),
|
| 346 |
+
raw=dict(x=np.zeros((N, B, d), np.float16), mx=np.zeros((NR, B, d), np.float16),
|
| 347 |
+
**{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),
|
| 348 |
+
j_coef=np.zeros((N, B, a.k), np.float16), texts=[],
|
| 349 |
+
m=np.zeros((NR, B, d), np.float16), m_idx=np.zeros((NR, B, a.k), np.int32),
|
| 350 |
+
m_coef=np.zeros((NR, B, a.k), np.float16), desc=[],
|
| 351 |
+
inj=np.zeros((NR, B, d), np.float16), inj_src=np.zeros((NR, B), np.int32),
|
| 352 |
+
fid={f'{l}_{g}':np.zeros((NR, B, d), np.float16) for l, g in self.fid},
|
| 353 |
+
fid_desc={f'{l}_{g}':[] for l, g in self.fid})
|
| 354 |
+
t_start = time.time()
|
| 355 |
+
for t in range(t0, N):
|
| 356 |
+
u = z+self.beta[:, None]*(~ablated)[:, None]*inj_m
|
| 357 |
+
nu = u.norm(dim=-1, keepdim=True)/self.rc # bounded: never above 1.5 typical contents
|
| 358 |
+
v = (self.g*self.Rn/self.rc)[:, None]*u*torch.clamp(1.5/nu.clamp_min(1e-6), max=1.)
|
| 359 |
+
ids, st = self.thought(v)
|
| 360 |
+
x = self.pool(st, a.skip)-self.mu
|
| 361 |
+
jidx, jcoef, j = self.content(x, self.jbar)
|
| 362 |
+
if a.save_raw:D['raw']['x'][t] = x.cpu().half().numpy()
|
| 363 |
+
z = (1-a.alpha)*z+a.alpha*j
|
| 364 |
+
zhist = torch.cat([zhist[1:], z[None]])
|
| 365 |
+
D['j'][t] = j.cpu().half().numpy();D['j_idx'][t] = jidx.cpu().numpy();D['j_coef'][t] = jcoef.cpu().half().numpy()
|
| 366 |
+
D['texts'].append(self.tok.batch_decode(ids))
|
| 367 |
+
if (t+1) % K == 0:
|
| 368 |
+
r = (t+1)//K-1;zwin = zhist.transpose(0, 1)
|
| 369 |
+
dids, mstate = self.reflect(zwin, self.g_r)
|
| 370 |
+
midx, mcoef, m = self.content(mstate-self.mu_r, self.mbar)
|
| 371 |
+
if a.save_raw:D['raw']['mx'][r] = (mstate-self.mu_r).cpu().half().numpy()
|
| 372 |
+
D['m'][r] = m.cpu().half().numpy();D['m_idx'][r] = midx.cpu().numpy();D['m_coef'][r] = mcoef.cpu().half().numpy()
|
| 373 |
+
D['desc'].append(self.tok.batch_decode(dids))
|
| 374 |
+
fids, fst = self.reflect(zwin, self.g_r, n_desc=a.n_desc_f, fwd=True) # self-prediction (logged only)
|
| 375 |
+
D['mf'][r] = self.content(fst-self.mu_rf, self.mbar_f)[2].cpu().half().numpy()
|
| 376 |
+
D['fdesc'].append(self.tok.batch_decode(fids))
|
| 377 |
+
for l, g in self.fid: # the same reflection at other settings
|
| 378 |
+
_, fst = self.reflect(zwin, torch.full_like(self.g_r, g), layer=l, n_desc=0)
|
| 379 |
+
D['fid'][f'{l}_{g}'][r] = self.content(fst-self.mu_r, self.mbar)[2].cpu().half().numpy()
|
| 380 |
+
if a.save_raw:D['raw'][f'fid_{l}_{g}'][r] = (fst-self.mu_r).cpu().half().numpy()
|
| 381 |
+
unit = lambda u:u/u.norm(dim=-1, keepdim=True).clamp_min(1e-6)*self.rc
|
| 382 |
+
avg = self.content(zhist.mean(0), 0.)[2]
|
| 383 |
+
# the population's generic self-model at this moment: the mean over the observer rows, which no
|
| 384 |
+
# treatment touches. The individuated conditions (loopc, yokedc, clampc) feed back only what sets one
|
| 385 |
+
# mind's self-model apart from it.
|
| 386 |
+
generic = m[self.free_rows].mean(0) if self.free_rows else m.mean(0)
|
| 387 |
+
D['generic'][r] = generic.cpu().half().numpy()
|
| 388 |
+
mi = m-generic[None]
|
| 389 |
+
new = torch.zeros_like(inj_m);src = []
|
| 390 |
+
for b, c in enumerate(self.cond):
|
| 391 |
+
if c == 'free':src.append(-1);continue
|
| 392 |
+
if c in ('loop', 'perturb', 'ablate', 'loopc', 'clampc', 'stalec'):s = b
|
| 393 |
+
elif c in ('yoked', 'yokedc'):s = self.partner[b]
|
| 394 |
+
elif c == 'matchc': # the stranger who most resembles this mind now
|
| 395 |
+
cand = [x for x in range(B) if self.rows[x]['seed'] != self.rows[b]['seed']]
|
| 396 |
+
sims = torch.nn.functional.cosine_similarity(mi[b:b+1], mi[cand], dim=-1)
|
| 397 |
+
s = cand[int(sims.argmax())]
|
| 398 |
+
elif c == 'avg':s = -2
|
| 399 |
+
if c == 'perturb' and t+1 == a.t_int:s = self.foreign[b]
|
| 400 |
+
if c in ('loopc', 'yokedc', 'clampc', 'matchc', 'stalec'):
|
| 401 |
+
vec = unit(mi[s:s+1])[0]
|
| 402 |
+
if c == 'stalec': # its own self-model from a.stale reflections ago
|
| 403 |
+
ro = max(0, r-a.stale)
|
| 404 |
+
old = torch.tensor(D['m'][ro][b].astype(np.float32)-D['generic'][ro].astype(np.float32), device=dev)
|
| 405 |
+
vec = unit(old[None])[0]
|
| 406 |
+
if c == 'clampc' and t+1 == a.t_int:self.clamp_vec[b] = unit(mi[self.foreign[b]:self.foreign[b]+1])[0]
|
| 407 |
+
if c == 'clampc' and a.t_int <= t+1 < a.t_int+a.clamp_len:vec, s = self.clamp_vec[b], self.foreign[b]
|
| 408 |
+
new[b] = vec
|
| 409 |
+
else:new[b] = unit(avg[b:b+1])[0] if s == -2 else unit(m[s:s+1])[0]
|
| 410 |
+
src.append(s)
|
| 411 |
+
if c == 'ablate' and t+1 >= a.t_int:ablated[b] = True
|
| 412 |
+
inj_m = new
|
| 413 |
+
D['inj'][r] = inj_m.cpu().half().numpy();D['inj_src'][r] = np.array(src)
|
| 414 |
+
el = time.time()-t_start;rate = el/(t+1-t0)
|
| 415 |
+
w = [f"{self.cond[b]}/{self.rows[b]['seed']}: {self.js.top(midx[b].cpu().numpy(), mcoef[b].cpu().numpy(), 5)}"
|
| 416 |
+
for b in range(0, B, max(1, B//6))]
|
| 417 |
+
log(f'thought {t+1}/{N} ({rate:.2f} s/thought, eta {(N-t-1)*rate/60:.1f} min) | self-models: ' + ' | '.join(w))
|
| 418 |
+
log(' e.g. thought: ' + D['texts'][-1][0][:160].replace('\n', ' ') + ' || answer: ' + D['desc'][-1][0][:120])
|
| 419 |
+
if (t+1) % a.ckpt_every == 0 or t+1 == N:
|
| 420 |
+
S = dict(mu=self.mu.cpu(), mu_r=self.mu_r.cpu(), jbar=self.jbar.cpu(), mbar=self.mbar.cpu(), rc=self.rc,
|
| 421 |
+
mu_rf=self.mu_rf.cpu(), mbar_f=self.mbar_f.cpu(), clamp_vec=self.clamp_vec.cpu(),
|
| 422 |
+
Rn=self.Rn, rj=self.rj, rj_x=self.rj_x,
|
| 423 |
+
z=z.cpu(), inj_m=inj_m.cpu(), zhist=zhist.cpu(), ablated=ablated.cpu(), gen=self.gen.get_state(),
|
| 424 |
+
t=t+1, data=D)
|
| 425 |
+
torch.save(S, ck+'.tmp');os.replace(ck+'.tmp', ck)
|
| 426 |
+
self.save(D)
|
| 427 |
+
|
| 428 |
+
def save(self, D):
|
| 429 |
+
a = self.a
|
| 430 |
+
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'],
|
| 431 |
+
m_idx=D['m_idx'], m_coef=D['m_coef'], inj=D['inj'], inj_src=D['inj_src'], mu=self.mu.cpu().numpy(),
|
| 432 |
+
jbar=self.jbar.cpu().numpy(), mbar=self.mbar.cpu().numpy(), mf=D['mf'], generic=D['generic'],
|
| 433 |
+
**{f'fid_{k}':v for k, v in D['fid'].items()},
|
| 434 |
+
**({f'raw_{k}':v for k, v in D['raw'].items()} if D.get('raw') is not None else {}))
|
| 435 |
+
meta = dict(args=vars(a), rows=self.rows, partner=self.partner, foreign=self.foreign, layer=self.L, L_in=self.L_in,
|
| 436 |
+
n_layers=self.n_layers,
|
| 437 |
+
Rn=self.Rn, rj=self.rj, rj_x=self.rj_x, rc=self.rc, words=self.js.words, texts=D['texts'], desc=D['desc'],
|
| 438 |
+
fid_desc=D['fid_desc'], fdesc=D['fdesc'], thought_frame=THOUGHT_FRAME,
|
| 439 |
+
reflect_prompt=REFLECT_PRE+PLACE*a.K+REFLECT_POST, forward_prompt=REFLECT_PRE+PLACE*a.K+REFLECT_FWD)
|
| 440 |
+
with open(os.path.join(a.out, 'meta.json'), 'w', encoding='utf-8') as f:json.dump(meta, f, ensure_ascii=False)
|
| 441 |
+
log('saved', a.out)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def main():
|
| 445 |
+
p = argparse.ArgumentParser()
|
| 446 |
+
p.add_argument('--model', default='Qwen/Qwen3-4B-Base');p.add_argument('--jlens', default='qwen3-4b-base-jlens.npz')
|
| 447 |
+
p.add_argument('--layer', type=int, default=-1, help='read layer (block index); -1: round(layer_frac * n_layers)')
|
| 448 |
+
p.add_argument('--layer_frac', type=float, default=.5)
|
| 449 |
+
p.add_argument('--L_in_frac', type=float, default=-1., help='> 0: trace goes in this fraction of depth below the read layer')
|
| 450 |
+
p.add_argument('--atoms', default='centred', help="'paper': rows of W_U diag(gamma) J as in the paper; 'centred': W_U centred first")
|
| 451 |
+
p.add_argument('--gs', default='.05,.1,.2', help="recurrent gains for --grid gsweep")
|
| 452 |
+
p.add_argument('--save_raw', action='store_true', help='also keep the centred residual states (thoughts, reflections)')
|
| 453 |
+
p.add_argument('--out', required=True);p.add_argument('--grid', default='main')
|
| 454 |
+
p.add_argument('--conds', default='free,loop,yoked,avg,perturb,ablate');p.add_argument('--seeds', type=int, default=8)
|
| 455 |
+
p.add_argument('--n_iter', type=int, default=300);p.add_argument('--K', type=int, default=10)
|
| 456 |
+
p.add_argument('--t_int', type=int, default=150, help='thought at which perturb/ablate/clampc rows are treated')
|
| 457 |
+
p.add_argument('--clamp_len', type=int, default=50, help='thoughts for which clampc holds a foreign self-model')
|
| 458 |
+
p.add_argument('--stale', type=int, default=5, help='stalec: reflections back its own self-model is taken from')
|
| 459 |
+
p.add_argument('--n_desc_f', type=int, default=12, help='words said in answer to the forward question (display)')
|
| 460 |
+
p.add_argument('--n_tok', type=int, default=40);p.add_argument('--n_desc', type=int, default=24)
|
| 461 |
+
p.add_argument('--skip', type=int, default=3);p.add_argument('--k', type=int, default=16)
|
| 462 |
+
p.add_argument('--vocab', default='english', help="J-lens dictionary: 'english' (common English words) or 'words'")
|
| 463 |
+
p.add_argument('--g', type=float, default=.1, help='recurrent injection, in units of the residual norm')
|
| 464 |
+
p.add_argument('--g_r', type=float, default=.5, help='placeholder injection in the reflection')
|
| 465 |
+
p.add_argument('--beta', type=float, default=1., help='self-model weight relative to a typical thought')
|
| 466 |
+
p.add_argument('--alpha', type=float, default=.4, help='leak of the recurrent state toward each new thought')
|
| 467 |
+
p.add_argument('--temp', type=float, default=1.);p.add_argument('--temp_r', type=float, default=.3)
|
| 468 |
+
p.add_argument('--min_p', type=float, default=.05);p.add_argument('--n_cal', type=int, default=3)
|
| 469 |
+
p.add_argument('--L_in', type=int, default=12, help='layer where the reflection placeholders get the states (-1: L)')
|
| 470 |
+
p.add_argument('--fid', default='', help='extra reflections to log for a fidelity check: layer:gain,layer:gain')
|
| 471 |
+
p.add_argument('--rng', type=int, default=1234);p.add_argument('--ckpt_every', type=int, default=20)
|
| 472 |
+
a = p.parse_args()
|
| 473 |
+
os.makedirs(a.out, exist_ok=True)
|
| 474 |
+
torch.manual_seed(a.rng)
|
| 475 |
+
Experiment(a).main()
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
if __name__ == '__main__':
|
| 479 |
+
main()
|
code/vast_self.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Act on this Vast.ai instance with its own per-instance key, which Vast puts in PID 1's environment
|
| 3 |
+
# (CONTAINER_ID, CONTAINER_API_KEY). Never ship an account key to an instance.
|
| 4 |
+
# bash vast_self.sh check|stop|destroy|label <text>
|
| 5 |
+
env1() { tr '\0' '\n' < /proc/1/environ 2>/dev/null | sed -n "s/^$1=//p" | head -1; }
|
| 6 |
+
CID=${CONTAINER_ID:-$(env1 CONTAINER_ID)}; KEY=${CONTAINER_API_KEY:-$(env1 CONTAINER_API_KEY)}
|
| 7 |
+
[ -n "$CID" ] && [ -n "$KEY" ] || { echo "vast_self: no CONTAINER_ID / CONTAINER_API_KEY"; exit 2; }
|
| 8 |
+
API=https://console.vast.ai/api/v0/instances/$CID/
|
| 9 |
+
J='Content-Type: application/json'
|
| 10 |
+
case "$1" in
|
| 11 |
+
check) curl -s -m 30 -o /dev/null -w "GET instance $CID: HTTP %{http_code}\n" -H "Authorization: Bearer $KEY" "$API" ;;
|
| 12 |
+
label) curl -s -m 30 -X PUT -H "Authorization: Bearer $KEY" -H "$J" -d "{\"label\": \"$2\"}" "$API"; echo ;;
|
| 13 |
+
stop) echo "$(date '+%F %T') stop $CID"; curl -s -m 30 -X PUT -H "Authorization: Bearer $KEY" -H "$J" -d '{"state": "stopped"}' "$API"; echo ;;
|
| 14 |
+
destroy) echo "$(date '+%F %T') destroy $CID"; curl -s -m 30 -X DELETE -H "Authorization: Bearer $KEY" "$API"; echo ;;
|
| 15 |
+
esac
|