Stage 2 code (exploratory gain ladder), added after seeing the Qwen3-4B result; not pre-registered
Browse filesFiles changed (4)
- code/stage2/ring_gains.pyAdded+116
- code/stage2/ring_job.pyAdded+227
- code/stage2/ring_ladder.pyAdded+53
- code/stage2/ring_run2.shAdded+31
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Exploratory, added after the first results (not pre-registered): the ring across the substrate's transition fromwandering to collapse.
Complexity tends to peak near the edge between order and chaos, and an attractor is not bad in itself: what mattersis what it holds and whether it is trivial. So per gain (the main run is the x1 point) and condition: exploration, collapse and memory as in ring_analyze.py; beta, the spectral exponent of the trajectory (power ~ 1/f^beta over its top 10 components): about 0 for white noise, about 2 for a random walk, about 1 is the classic sign of a critical regime; an attractor census: the end state of every seed (mean of its last 50 steps), seeds grouped when their end states have cosine > 0.9, and for each group the words it holds and what the mind says about it (the glimpse); ring_err against its controls on exploration, and the freeze effect, at every gain.
python ring_gains.py runs/ring/qwen3-4b -> runs/ring/qwen3-4b/gains/gains.json"""import json, os, sysimport numpy as np
out = sys.argv[1]KEYS = ('C', 'idx', 'coef', 'step_cos', 'pred_cos')
def load(d): parts = [d] if os.path.exists(f'{d}/ring.npz') else sorted(f'{d}/{x}' for x in os.listdir(d) if os.path.exists(f'{d}/{x}/ring.npz')) Ms = [json.load(open(f'{p}/meta.json', encoding='utf-8')) for p in parts];Z = {} for p in parts: with np.load(f'{p}/ring.npz') as z: for k in KEYS:Z.setdefault(k, []).append(z[k]) Z = {k:np.concatenate(v, 1) for k, v in Z.items()} rows = sum((m['rows'] for m in Ms), []);glimpse = sum((m.get('glimpse') or ['']*len(m['rows']) for m in Ms), []) return Z, rows, glimpse, Ms[0]
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 beta(X, k=10): """Spectral exponent of one mind's trajectory X (n, d): top-k components via the Gram matrix, Hann window.""" X = X-X.mean(0);ev, ec = np.linalg.eigh(X@X.T);Y = ec[:, -k:]*np.sqrt(np.clip(ev[-k:], 0, None)) F = np.abs(np.fft.rfft(Y*np.hanning(len(Y))[:, None], axis=0))**2;f = np.fft.rfftfreq(len(Y)) m = (f > 2/len(Y)) & (f < .25) return float(-np.polyfit(np.log(f[m]), np.log(F[m].sum(1)+1e-20), 1)[0])
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 analyse(d, words): Z, rows, glimpse, M = load(d);T, B = Z['step_cos'].shape;TF = M['args']['t_freeze'] C = Z['C'].astype(np.float32);U = C/np.maximum(np.linalg.norm(C, axis=-1, keepdims=True), 1e-8) W, LT, LG = min(100, max(10, T//6)), min(200, T//3), min(100, T//4) 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)};res = {} for c in conds: bs = [row[c, s] for s in seeds] m = 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], 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=[float((Z['step_cos'][T-LT:, b] > .98).mean()) for b in bs], lag1=[float(Z['step_cos'][T-LT:, 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], beta=[beta(U[min(100, T//6):, b]) for b in bs], words=[len(set(Z['idx'][:, b, 0].tolist())) for b in bs]) # attractor census on the end states E = U[T-50:, bs].mean(0);E /= np.maximum(np.linalg.norm(E, axis=-1, keepdims=True), 1e-8) left, groups = list(range(len(bs))), [] while left: i = left[0];grp = [j for j in left if float(E[i]@E[j]) > .9];groups.append(grp);left = [j for j in left if j not in grp] census = [] for grp in sorted(groups, key=len, reverse=True): acc = np.zeros(len(words)) for j in grp:np.add.at(acc, Z['idx'][T-50:, bs[j]].ravel(), Z['coef'][T-50:, bs[j]].astype(np.float64).ravel()) census.append(dict(size=len(grp), seeds=[seeds[j] for j in grp], words=[words[i] for i in np.argsort(-acc)[:8]], glimpse=list(dict.fromkeys(glimpse[bs[j]].strip() for j in grp))[:3])) res[c] = dict(per_seed=m, mean={k:float(np.mean(v)) for k, v in m.items()}, n_attractors=len(groups), census=census) tests = {} if 'ring_err' in res: for ctrl in ('vel', 'yoked_err', 'shuf_err', 'rand_err', 'free', 'content'): if ctrl in res:tests[f'ring_err_vs_{ctrl}'] = {k:paired(res['ring_err']['per_seed'][k], res[ctrl]['per_seed'][k]) for k in ('explore', 'stuck', 'beta')} if 'frozen_err' in res: f, r = res['frozen_err']['per_seed'], res['ring_err']['per_seed'] tests['freeze_effect'] = dict(explore=paired(np.subtract(f['explore'], f['explore_pre']), np.subtract(r['explore'], r['explore_pre']))) return dict(g=rows[0]['g'], sigma=rows[0]['sigma'], seeds=len(seeds), T=T, conds=res, tests=tests)
runs = {}M0 = json.load(open(f'{out}/params.json'))words = Nonefor d in [f'{out}/main']+sorted(f'{out}/gains/{x}' for x in os.listdir(f'{out}/gains') if x.startswith('g')): if not any(os.path.exists(f'{p}/meta.json') for p in [d]+[f'{d}/{x}' for x in os.listdir(d)] if os.path.isdir(p)):continue if words is None: first = d if os.path.exists(f'{d}/meta.json') else [f'{d}/{x}' for x in sorted(os.listdir(d)) if os.path.exists(f'{d}/{x}/meta.json')][0] words = json.load(open(f'{first}/meta.json', encoding='utf-8'))['words'] r = analyse(d, words);runs[r['g']] = r;print(f'analysed g {r["g"]} ({d})', flush=True)gs = sorted(runs)json.dump(dict(picked_g=M0['g'], gains=[runs[g] for g in gs]), open(f'{out}/gains/gains.json', 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
conds = list(runs[gs[0]]['conds'])print(f'\n{out}: gains {gs} (picked {M0["g"]}), sigma {runs[gs[0]]["sigma"]}')for k, fmt in (('explore', '{:7.2f}'), ('stuck', '{:7.3f}'), ('lag100', '{:7.3f}'), ('beta', '{:7.2f}'), ('words', '{:7.1f}')): print(f'\n{k:11s}' + ''.join(f'{"g "+str(g):>9s}' for g in gs)) for c in conds:print(f'{c:11s}' + ''.join(f'{fmt.format(runs[g]["conds"][c]["mean"][k]):>9s}' for g in gs))print('\nring_err minus control, exploration (t over seeds)')for name in runs[gs[0]]['tests']: print(f'{name:22s}' + ''.join(f'{runs[g]["tests"][name]["explore"]["diff"]:+7.2f} t{runs[g]["tests"][name]["explore"]["t"]:+5.1f} ' for g in gs if name in runs[g]['tests']))print('\nattractors: number of distinct end states among the seeds; the biggest group, its words and what it says')for c in ('free', 'content', 'ring_pred', 'ring_err', 'yoked_err', 'rand_err'): if c not in conds:continue for g in gs: r = runs[g]['conds'][c];top = r['census'][0] print(f'{c:10s} g {g:<6} {r["n_attractors"]:2d} end states | biggest {top["size"]:2d}: {", ".join(top["words"][:6])} | {top["glimpse"][0][:90]!r}')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227"""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
python ring_job.py ... --gains .5,2,4 # stage 2, exploratory (added after the first results): every
# condition again at multiples of the picked gain (ring_gains.py)
"""
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 run_gains(tag, a, up, mem_gb):
"""Stage 2: the main grid at multiples of the picked gain (s = g as in the main run), then ring_gains.py."""
out = f'{a.root}/{tag}';P = json.load(open(f'{out}/params.json'));lg = f'{out}/log.txt'
common = ['--model', MODELS[tag][0], '--jlens', fetch(tag), '--vocab', a.vocab, '--k', str(a.k)]
per = seeds_per_chunk(tag, a.T, N_CONDS, mem_gb, a.max_chunk)
for mult in [float(x) for x in a.gains.split(',')]:
g = round(P['g']*mult, 4)
run_seeds(f'{out}/gains/g{g}', a.gain_seeds, per, lambda s0, n, d:[
PY, 'ring.py', *common, '--grid', 'main', '--seeds', str(n), '--seed0', str(s0), '--rng', str(2234+s0),
'--T', str(a.T), '--t_freeze', str(a.t_freeze), '--g', str(g), '--sigma', str(P['sigma']), '--out', d], lg, least=2)
if not os.path.exists(f'{out}/gains/gains.json'):
sh([PY, 'ring_gains.py', out], f'{out}/gains/summary.txt')
log(tag, 'gain ladder done');up.put(f'{out}/gains', f'{tag}/gains')
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')
p.add_argument('--gains', default='', help='stage 2: multiples of the picked gain');p.add_argument('--gain_seeds', type=int, default=16)
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/job2.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 = []
if a.gains:
for tag in tags:
try:run_gains(tag, a, up, mem_gb)
except Exception as e:errors.append(tag);log('GAINS FAILED', tag, 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}/DONE2.json', 'w'))
log('stage 2 done', 'errors', errors, 'upload failures', up.failed);return
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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Across models: the ring's pre-registered tests from each results.json, side by side, plus Stouffer's z over models.
python ring_ladder.py runs/ring -> runs/ring/ladder.json and a table on stdout"""import json, math, os, sys
root = sys.argv[1]ORDER = ['qwen3-1.7b', 'qwen3-4b', 'qwen3-8b', 'qwen3-14b', 'qwen3-4b-long']models = [m for m in ORDER if os.path.exists(f'{root}/{m}/main/results.json')]R = {m:json.load(open(f'{root}/{m}/main/results.json', encoding='utf-8')) for m in models}PRIMARY = [('ring_err_vs_vel', ('explore', 'stuck', 'skill', 'lag100')), ('ring_err_vs_yoked_err', ('explore', 'stuck', 'skill', 'lag100')), ('ring_err_vs_shuf_err', ('explore', 'stuck', 'skill', 'lag100')), ('ring_err_vs_rand_err', ('explore', 'stuck', 'skill', 'lag100')), ('freeze_effect', ('explore', 'stuck', 'skill'))]SECONDARY = [('ring_pred_vs_content', ('explore', 'stuck', 'skill', 'selffulfil')), ('ring_pred_vs_yoked_pred', ('explore', 'stuck', 'skill', 'selffulfil')), ('ring_err_vs_free', ('explore', 'stuck', 'skill')), ('ring_pred_vs_free', ('explore', 'stuck', 'skill'))]
def cell(t): return ' — ' if not t else f"{t['diff']:+7.3f} t{t['t']:+6.1f}"
def stouffer(ts): ts = [t['t'] for t in ts if t and t['se'] > 0] return (sum(ts)/math.sqrt(len(ts)), len(ts)) if ts else (0., 0)
out = dict(models=models, regimes={}, tests={}, privileged={})print('regime per model (pilot rule): g = s, sigma; free minds at that setting')for m in models: r = R[m];out['regimes'][m] = dict(g=r['g'], sigma=r['sigma'], seeds=r['seeds'], T=r['T'], L_in=r['L_in'], L_read=r['L_read']) print(f" {m:14s} g {r['g']:.2f} sigma {r['sigma']:.2f} | {r['seeds']} seeds, T {r['T']} | inject L{r['L_in']}, read L{r['L_read']} of {r['n_layers']}")for title, block in (('PRIMARY', PRIMARY), ('SECONDARY', SECONDARY)): print(f'\n{title}: paired difference (first minus second), t over seeds; last column Stouffer z over the main models') print(f"{'test':26s} {'metric':8s} " + ' '.join(f'{m:>15s}' for m in models) + ' pooled z') for name, metrics in block: for k in metrics: ts = [R[m]['tests'].get(name, {}).get(k) if R[m]['tests'].get(name) else None for m in models] z, n = stouffer([t for m, t in zip(models, ts) if not m.endswith('-long')]) out['tests'][f'{name}.{k}'] = dict(per_model=dict(zip(models, ts)), stouffer_z=z, n_models=n) print(f"{name:26s} {k:8s} " + ' '.join(f'{cell(t):>15s}' for t in ts) + f' {z:+6.1f} ({n})')print('\nprivileged self-knowledge: own-fitted minus other-fitted next-state predictor (cosine), t over seeds')for c in ('free', 'ring_err', 'ring_pred', 'content', 'vel', 'yoked_err'): ts = [R[m]['privileged'].get(c, {}).get('test') for m in models] z, n = stouffer([t for m, t in zip(models, ts) if not m.endswith('-long')]) out['privileged'][c] = dict(per_model=dict(zip(models, ts)), stouffer_z=z) print(f"{c:12s} " + ' '.join(f'{cell(t):>15s}' for t in ts) + f' {z:+6.1f} ({n})')print('\nper-condition means (explore / stuck / skill)')conds = list(R[models[0]]['summary']) if models else []for c in conds: print(f"{c:11s} " + ' '.join(f"{R[m]['summary'][c]['explore']:6.2f}/{R[m]['summary'][c]['stuck']:.2f}/{R[m]['summary'][c]['skill']:+.3f}" for m in models))json.dump(out, open(f'{root}/ladder.json', 'w', encoding='utf-8'), indent=1)12345678910111213141516171819202122232425262728293031#!/bin/bash# Stage 2 (the exploratory gain ladder), chained after ring_run.sh, which must have been told to leave the instance up# (/workspace/HOLD). Waits until stage 1 has finished and uploaded, runs ring_job.py --gains ..., pushes everything to# the dataset, then destroys the instance. It stops the instance instead if the upload failed, and leaves it# running if /workspace/HOLD2 exists.# bash ring_run2.sh <ring_job.py args...>cd "$(dirname "$0")"PY=${PY:-/opt/conda/bin/python}export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True HF_HUB_DISABLE_PROGRESS_BARS=1 TOKENIZERS_PARALLELISM=falsesay() { echo "$(date '+%F %T') [run2] $*" >> /workspace/job2.log; }say "waiting for stage 1"until grep -q "\[run\] HOLD set" /workspace/job.log 2>/dev/null; do # stage 1's wrapper died before its end: go on once its DONE.json is 45 min old [ -f /workspace/runs/ring/DONE.json ] && [ $(( $(date +%s) - $(stat -c %Y /workspace/runs/ring/DONE.json) )) -gt 2700 ] && break sleep 20donesay "stage 2 start"setsid $PY ring_job.py "$@" >> /workspace/job2.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 "stage 2 ended (rc $?)"UP=1for i in 1 2 3; do timeout 2400 $PY ring_job.py "$@" --upload_only >> /workspace/job2.log 2>&1 && { UP=0; break; }; sleep 60; doneif [ -f /workspace/HOLD2 ]; then say "HOLD2 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/job2.log 2>&1else say "upload failed, stopping the instance (disk kept)"; bash vast_self.sh stop >> /workspace/job2.log 2>&1; ficode/stage2/ring_gains.pyAdded+116
code/stage2/ring_job.pyAdded+227
code/stage2/ring_ladder.pyAdded+53
code/stage2/ring_run2.shAdded+31