Stage 2 code (exploratory gain ladder), added after seeing the Qwen3-4B result; not pre-registered
Browse files- code/stage2/ring_gains.py +116 -0
- code/stage2/ring_job.py +227 -0
- code/stage2/ring_ladder.py +53 -0
- code/stage2/ring_run2.sh +31 -0
code/stage2/ring_gains.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exploratory, added after the first results (not pre-registered): the ring across the substrate's transition from
|
| 2 |
+
wandering to collapse.
|
| 3 |
+
|
| 4 |
+
Complexity tends to peak near the edge between order and chaos, and an attractor is not bad in itself: what matters
|
| 5 |
+
is what it holds and whether it is trivial. So per gain (the main run is the x1 point) and condition:
|
| 6 |
+
exploration, collapse and memory as in ring_analyze.py;
|
| 7 |
+
beta, the spectral exponent of the trajectory (power ~ 1/f^beta over its top 10 components): about 0 for white
|
| 8 |
+
noise, about 2 for a random walk, about 1 is the classic sign of a critical regime;
|
| 9 |
+
an attractor census: the end state of every seed (mean of its last 50 steps), seeds grouped when their end states
|
| 10 |
+
have cosine > 0.9, and for each group the words it holds and what the mind says about it (the glimpse);
|
| 11 |
+
ring_err against its controls on exploration, and the freeze effect, at every gain.
|
| 12 |
+
|
| 13 |
+
python ring_gains.py runs/ring/qwen3-4b -> runs/ring/qwen3-4b/gains/gains.json
|
| 14 |
+
"""
|
| 15 |
+
import json, os, sys
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
out = sys.argv[1]
|
| 19 |
+
KEYS = ('C', 'idx', 'coef', 'step_cos', 'pred_cos')
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load(d):
|
| 23 |
+
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'))
|
| 24 |
+
Ms = [json.load(open(f'{p}/meta.json', encoding='utf-8')) for p in parts];Z = {}
|
| 25 |
+
for p in parts:
|
| 26 |
+
with np.load(f'{p}/ring.npz') as z:
|
| 27 |
+
for k in KEYS:Z.setdefault(k, []).append(z[k])
|
| 28 |
+
Z = {k:np.concatenate(v, 1) for k, v in Z.items()}
|
| 29 |
+
rows = sum((m['rows'] for m in Ms), []);glimpse = sum((m.get('glimpse') or ['']*len(m['rows']) for m in Ms), [])
|
| 30 |
+
return Z, rows, glimpse, Ms[0]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def pr(V):
|
| 34 |
+
V = V-V.mean(0);ev = np.clip(np.linalg.eigvalsh(V@V.T), 0, None)
|
| 35 |
+
return float(ev.sum()**2/max((ev**2).sum(), 1e-12))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def beta(X, k=10):
|
| 39 |
+
"""Spectral exponent of one mind's trajectory X (n, d): top-k components via the Gram matrix, Hann window."""
|
| 40 |
+
X = X-X.mean(0);ev, ec = np.linalg.eigh(X@X.T);Y = ec[:, -k:]*np.sqrt(np.clip(ev[-k:], 0, None))
|
| 41 |
+
F = np.abs(np.fft.rfft(Y*np.hanning(len(Y))[:, None], axis=0))**2;f = np.fft.rfftfreq(len(Y))
|
| 42 |
+
m = (f > 2/len(Y)) & (f < .25)
|
| 43 |
+
return float(-np.polyfit(np.log(f[m]), np.log(F[m].sum(1)+1e-20), 1)[0])
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def paired(x, y):
|
| 47 |
+
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.
|
| 48 |
+
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)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def analyse(d, words):
|
| 52 |
+
Z, rows, glimpse, M = load(d);T, B = Z['step_cos'].shape;TF = M['args']['t_freeze']
|
| 53 |
+
C = Z['C'].astype(np.float32);U = C/np.maximum(np.linalg.norm(C, axis=-1, keepdims=True), 1e-8)
|
| 54 |
+
W, LT, LG = min(100, max(10, T//6)), min(200, T//3), min(100, T//4)
|
| 55 |
+
conds = list(dict.fromkeys(r['cond'] for r in rows));seeds = sorted({r['seed'] for r in rows})
|
| 56 |
+
row = {(r['cond'], r['seed']):i for i, r in enumerate(rows)};res = {}
|
| 57 |
+
for c in conds:
|
| 58 |
+
bs = [row[c, s] for s in seeds]
|
| 59 |
+
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],
|
| 60 |
+
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],
|
| 61 |
+
stuck=[float((Z['step_cos'][T-LT:, b] > .98).mean()) for b in bs],
|
| 62 |
+
lag1=[float(Z['step_cos'][T-LT:, b].mean()) for b in bs],
|
| 63 |
+
lag100=[float((U[T-LG:, b]*U[T-2*LG:T-LG, b]).sum(-1).mean()) for b in bs],
|
| 64 |
+
beta=[beta(U[min(100, T//6):, b]) for b in bs],
|
| 65 |
+
words=[len(set(Z['idx'][:, b, 0].tolist())) for b in bs])
|
| 66 |
+
# attractor census on the end states
|
| 67 |
+
E = U[T-50:, bs].mean(0);E /= np.maximum(np.linalg.norm(E, axis=-1, keepdims=True), 1e-8)
|
| 68 |
+
left, groups = list(range(len(bs))), []
|
| 69 |
+
while left:
|
| 70 |
+
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]
|
| 71 |
+
census = []
|
| 72 |
+
for grp in sorted(groups, key=len, reverse=True):
|
| 73 |
+
acc = np.zeros(len(words))
|
| 74 |
+
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())
|
| 75 |
+
census.append(dict(size=len(grp), seeds=[seeds[j] for j in grp], words=[words[i] for i in np.argsort(-acc)[:8]],
|
| 76 |
+
glimpse=list(dict.fromkeys(glimpse[bs[j]].strip() for j in grp))[:3]))
|
| 77 |
+
res[c] = dict(per_seed=m, mean={k:float(np.mean(v)) for k, v in m.items()}, n_attractors=len(groups), census=census)
|
| 78 |
+
tests = {}
|
| 79 |
+
if 'ring_err' in res:
|
| 80 |
+
for ctrl in ('vel', 'yoked_err', 'shuf_err', 'rand_err', 'free', 'content'):
|
| 81 |
+
if ctrl in res:tests[f'ring_err_vs_{ctrl}'] = {k:paired(res['ring_err']['per_seed'][k], res[ctrl]['per_seed'][k])
|
| 82 |
+
for k in ('explore', 'stuck', 'beta')}
|
| 83 |
+
if 'frozen_err' in res:
|
| 84 |
+
f, r = res['frozen_err']['per_seed'], res['ring_err']['per_seed']
|
| 85 |
+
tests['freeze_effect'] = dict(explore=paired(np.subtract(f['explore'], f['explore_pre']), np.subtract(r['explore'], r['explore_pre'])))
|
| 86 |
+
return dict(g=rows[0]['g'], sigma=rows[0]['sigma'], seeds=len(seeds), T=T, conds=res, tests=tests)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
runs = {}
|
| 90 |
+
M0 = json.load(open(f'{out}/params.json'))
|
| 91 |
+
words = None
|
| 92 |
+
for d in [f'{out}/main']+sorted(f'{out}/gains/{x}' for x in os.listdir(f'{out}/gains') if x.startswith('g')):
|
| 93 |
+
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
|
| 94 |
+
if words is None:
|
| 95 |
+
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]
|
| 96 |
+
words = json.load(open(f'{first}/meta.json', encoding='utf-8'))['words']
|
| 97 |
+
r = analyse(d, words);runs[r['g']] = r;print(f'analysed g {r["g"]} ({d})', flush=True)
|
| 98 |
+
gs = sorted(runs)
|
| 99 |
+
json.dump(dict(picked_g=M0['g'], gains=[runs[g] for g in gs]), open(f'{out}/gains/gains.json', 'w', encoding='utf-8'),
|
| 100 |
+
ensure_ascii=False, indent=1)
|
| 101 |
+
|
| 102 |
+
conds = list(runs[gs[0]]['conds'])
|
| 103 |
+
print(f'\n{out}: gains {gs} (picked {M0["g"]}), sigma {runs[gs[0]]["sigma"]}')
|
| 104 |
+
for k, fmt in (('explore', '{:7.2f}'), ('stuck', '{:7.3f}'), ('lag100', '{:7.3f}'), ('beta', '{:7.2f}'), ('words', '{:7.1f}')):
|
| 105 |
+
print(f'\n{k:11s}' + ''.join(f'{"g "+str(g):>9s}' for g in gs))
|
| 106 |
+
for c in conds:print(f'{c:11s}' + ''.join(f'{fmt.format(runs[g]["conds"][c]["mean"][k]):>9s}' for g in gs))
|
| 107 |
+
print('\nring_err minus control, exploration (t over seeds)')
|
| 108 |
+
for name in runs[gs[0]]['tests']:
|
| 109 |
+
print(f'{name:22s}' + ''.join(f'{runs[g]["tests"][name]["explore"]["diff"]:+7.2f} t{runs[g]["tests"][name]["explore"]["t"]:+5.1f} '
|
| 110 |
+
for g in gs if name in runs[g]['tests']))
|
| 111 |
+
print('\nattractors: number of distinct end states among the seeds; the biggest group, its words and what it says')
|
| 112 |
+
for c in ('free', 'content', 'ring_pred', 'ring_err', 'yoked_err', 'rand_err'):
|
| 113 |
+
if c not in conds:continue
|
| 114 |
+
for g in gs:
|
| 115 |
+
r = runs[g]['conds'][c];top = r['census'][0]
|
| 116 |
+
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}')
|
code/stage2/ring_job.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
python ring_job.py ... --gains .5,2,4 # stage 2, exploratory (added after the first results): every
|
| 15 |
+
# condition again at multiples of the picked gain (ring_gains.py)
|
| 16 |
+
"""
|
| 17 |
+
import argparse, json, math, os, queue, shutil, subprocess, sys, threading, time
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
MODELS = {'qwen3-1.7b':('Qwen/Qwen3-1.7B', 'Qwen3-1.7B', 1.72e9), 'qwen3-4b':('Qwen/Qwen3-4B', 'Qwen3-4B', 4.02e9),
|
| 21 |
+
'qwen3-8b':('Qwen/Qwen3-8B', 'Qwen3-8B', 8.19e9), 'qwen3-14b':('Qwen/Qwen3-14B', 'Qwen3-14B', 14.77e9),
|
| 22 |
+
'tiny':('Qwen/Qwen2.5-0.5B-Instruct', None, .49e9)} # tiny: identity lens, for testing the job
|
| 23 |
+
PY = sys.executable
|
| 24 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 25 |
+
N_CONDS = 10
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def log(*a):
|
| 29 |
+
print(time.strftime('%H:%M:%S'), *a, flush=True)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def sh(cmd, logf):
|
| 33 |
+
log('>>', ' '.join(cmd))
|
| 34 |
+
with open(logf, 'a') as f:
|
| 35 |
+
r = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT, cwd=HERE)
|
| 36 |
+
if r.returncode:raise RuntimeError(f'failed ({r.returncode}): see {logf}')
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def fetch(tag):
|
| 40 |
+
"""Model weights and the Neuronpedia lens (the prefetch thread usually has them already)."""
|
| 41 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 42 |
+
repo, name, _ = MODELS[tag]
|
| 43 |
+
snapshot_download(repo, allow_patterns=['*.json', '*.safetensors', '*.txt'])
|
| 44 |
+
if name is None:return 'identity'
|
| 45 |
+
return hf_hub_download('neuronpedia/jacobian-lens', f'{tag}/jlens/Salesforce-wikitext/{name}_jacobian_lens.pt')
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def seeds_per_chunk(tag, T, rows_per_seed, mem_gb, cap):
|
| 49 |
+
"""How many seeds fit at once: the KV cache of every mind over the whole run dominates, then the stored surprise
|
| 50 |
+
history and the self-model with its Adam state; 14 % of the card and 3 GB more are left as headroom."""
|
| 51 |
+
from transformers import AutoConfig
|
| 52 |
+
c = AutoConfig.from_pretrained(MODELS[tag][0])
|
| 53 |
+
hd = getattr(c, 'head_dim', None) or c.hidden_size//c.num_attention_heads
|
| 54 |
+
kv = 2*c.num_key_value_heads*hd*2*c.num_hidden_layers
|
| 55 |
+
per_mind = (100+24+T+40)*kv+T*c.hidden_size*2+8*c.hidden_size*32*4+2*32*c.hidden_size*4
|
| 56 |
+
free = .86*mem_gb*2**30-2*MODELS[tag][2]-3*2**30
|
| 57 |
+
return max(1, min(cap, int(free//(per_mind*rows_per_seed))))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def run_seeds(base, S, per, cmd, lg, least=1):
|
| 61 |
+
"""Seeds 0..S-1 in chunks of at most `per` (folders s<first>_<count>, skipped when finished). A failed chunk, in
|
| 62 |
+
practice an out-of-memory, is retried at half the size; the yoked conditions need at least two seeds per chunk."""
|
| 63 |
+
os.makedirs(base, exist_ok=True);per = max(least, min(per, S))
|
| 64 |
+
while True:
|
| 65 |
+
done = set()
|
| 66 |
+
for x in os.listdir(base):
|
| 67 |
+
if x.startswith('s') and os.path.exists(f'{base}/{x}/meta.json'):
|
| 68 |
+
s0, n = map(int, x[1:].split('_'));done |= set(range(s0, s0+n))
|
| 69 |
+
todo = [s for s in range(S) if s not in done]
|
| 70 |
+
if not todo:return
|
| 71 |
+
want = math.ceil(len(todo)/math.ceil(len(todo)/per)) # balanced: 24 at 11 -> 8, 8, 8
|
| 72 |
+
s0, n = todo[0], 1
|
| 73 |
+
while n < want and s0+n in todo:n += 1
|
| 74 |
+
if 0 < len(todo)-n < least and todo == list(range(s0, s0+len(todo))):n = len(todo) # no lone seed left over
|
| 75 |
+
d = f'{base}/s{s0}_{n}'
|
| 76 |
+
try:sh(cmd(s0, n, d), lg)
|
| 77 |
+
except RuntimeError:
|
| 78 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 79 |
+
if n <= least:raise
|
| 80 |
+
per = max(least, n//2);log(f'chunk of {n} seeds failed; retrying with {per}')
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def pr(V):
|
| 84 |
+
V = V-V.mean(0);ev = np.clip(np.linalg.eigvalsh(V@V.T), 0, None)
|
| 85 |
+
return float(ev.sum()**2/max((ev**2).sum(), 1e-12))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def pick(sweep_dirs):
|
| 89 |
+
rows, sc, U = [], [], []
|
| 90 |
+
for d in sweep_dirs:
|
| 91 |
+
m = json.load(open(f'{d}/meta.json', encoding='utf-8'))
|
| 92 |
+
with np.load(f'{d}/ring.npz') as z:
|
| 93 |
+
C = z['C'].astype(np.float32);sc.append(z['step_cos'])
|
| 94 |
+
U.append(C/np.maximum(np.linalg.norm(C, axis=-1, keepdims=True), 1e-8));rows += m['rows']
|
| 95 |
+
sc = np.concatenate(sc, 1);U = np.concatenate(U, 1);T = sc.shape[0]
|
| 96 |
+
LT, LG, W = min(200, T//3), min(100, T//4), min(100, max(10, T//6))
|
| 97 |
+
grid = {}
|
| 98 |
+
for g, sg in sorted({(r['g'], r['sigma']) for r in rows}):
|
| 99 |
+
bs = [i for i, r in enumerate(rows) if (r['g'], r['sigma']) == (g, sg)]
|
| 100 |
+
grid[f'g{g}_sigma{sg}'] = dict(
|
| 101 |
+
g=g, sigma=sg, stuck=float((sc[T-LT:, bs] > .98).mean()), lag1=float(sc[T-LT:, bs].mean()),
|
| 102 |
+
lag100=float(np.mean([(U[T-LG:, b]*U[T-2*LG:T-LG, b]).sum(-1).mean() for b in bs])),
|
| 103 |
+
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))])))
|
| 104 |
+
ok = [k for k, v in grid.items() if v['stuck'] <= .25 and v['lag1'] <= .9]
|
| 105 |
+
best = max(ok, key=lambda k:grid[k]['lag100']) if ok else min(grid, key=lambda k:(grid[k]['stuck'], grid[k]['lag1']))
|
| 106 |
+
return dict(g=grid[best]['g'], sigma=grid[best]['sigma'], picked=best, qualified=bool(ok), grid=grid)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class Uploader(threading.Thread):
|
| 110 |
+
"""Pushes finished folders to the dataset in the background; failures are remembered, not fatal."""
|
| 111 |
+
|
| 112 |
+
def __init__(self, repo):
|
| 113 |
+
super().__init__(daemon=True);self.repo = repo;self.q = queue.Queue();self.failed = []
|
| 114 |
+
if repo:
|
| 115 |
+
from huggingface_hub import create_repo
|
| 116 |
+
create_repo(repo, repo_type='dataset', private=True, exist_ok=True)
|
| 117 |
+
|
| 118 |
+
def run(self):
|
| 119 |
+
while True:
|
| 120 |
+
item = self.q.get()
|
| 121 |
+
if item is None:break
|
| 122 |
+
folder, path = item
|
| 123 |
+
try:
|
| 124 |
+
from huggingface_hub import HfApi
|
| 125 |
+
HfApi().upload_folder(repo_id=self.repo, repo_type='dataset', folder_path=folder, path_in_repo=path,
|
| 126 |
+
commit_message=f'ring: {path}');log('uploaded', path)
|
| 127 |
+
except Exception as e:
|
| 128 |
+
self.failed.append(path);log('UPLOAD FAILED', path, repr(e)[:300])
|
| 129 |
+
|
| 130 |
+
def put(self, folder, path):
|
| 131 |
+
if self.repo:self.q.put((folder, path))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def run_model(tag, a, up, mem_gb, long=False):
|
| 135 |
+
model = MODELS[tag][0];name = f'{tag}-long' if long else tag
|
| 136 |
+
out = f'{a.root}/{name}';os.makedirs(out, exist_ok=True);lg = f'{out}/log.txt'
|
| 137 |
+
lens = fetch(tag)
|
| 138 |
+
common = ['--model', model, '--jlens', lens, '--vocab', a.vocab, '--k', str(a.k)]
|
| 139 |
+
# 1. pilot: the free substrate over gain x noise
|
| 140 |
+
if long:
|
| 141 |
+
P = json.load(open(f'{a.root}/{tag}/params.json'))
|
| 142 |
+
else:
|
| 143 |
+
gs, sgs = a.gs.split(','), a.sigmas.split(',')
|
| 144 |
+
per = seeds_per_chunk(tag, a.T, len(gs)*len(sgs), mem_gb, a.max_chunk)
|
| 145 |
+
run_seeds(f'{out}/sweep', a.sweep_seeds, per, lambda s0, n, d:[
|
| 146 |
+
PY, 'ring.py', *common, '--grid', 'sweep', '--gs', a.gs, '--sigmas', a.sigmas, '--seeds', str(n), '--seed0', str(s0),
|
| 147 |
+
'--rng', str(4321+s0), '--T', str(a.T), '--t_freeze', str(a.T+1), '--glimpse', '0', '--out', d], lg)
|
| 148 |
+
if not os.path.exists(f'{out}/params.json'):
|
| 149 |
+
sw = [f'{out}/sweep/{x}' for x in sorted(os.listdir(f'{out}/sweep')) if os.path.exists(f'{out}/sweep/{x}/meta.json')]
|
| 150 |
+
json.dump(pick(sw), open(f'{out}/params.json', 'w'), indent=1)
|
| 151 |
+
P = json.load(open(f'{out}/params.json'))
|
| 152 |
+
log(tag, 'regime', P['picked'], 'qualified' if P['qualified'] else 'NONE QUALIFIED (least collapsed)',
|
| 153 |
+
{k:round(v, 3) for k, v in P['grid'][P['picked']].items()})
|
| 154 |
+
# 2. main run: every condition, paired seeds, chunks that fit
|
| 155 |
+
T, TF, S = (a.long_T, a.long_T//2, a.long_seeds) if long else (a.T, a.t_freeze, a.seeds)
|
| 156 |
+
per = seeds_per_chunk(tag, T, N_CONDS, mem_gb, a.max_chunk)
|
| 157 |
+
run_seeds(f'{out}/main', S, per, lambda s0, n, d:[
|
| 158 |
+
PY, 'ring.py', *common, '--grid', 'main', '--seeds', str(n), '--seed0', str(s0), '--rng', str(1234+s0),
|
| 159 |
+
'--T', str(T), '--t_freeze', str(TF), '--g', str(P['g']), '--sigma', str(P['sigma']), '--out', d], lg, least=2)
|
| 160 |
+
# 3. analysis, then hand the folder to the uploader
|
| 161 |
+
if not os.path.exists(f'{out}/main/results.json'):
|
| 162 |
+
sh([PY, 'ring_analyze.py', f'{out}/main'], f'{out}/main/summary.txt')
|
| 163 |
+
log(tag, 'done' + (' (long)' if long else ''));up.put(out, name)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def run_gains(tag, a, up, mem_gb):
|
| 167 |
+
"""Stage 2: the main grid at multiples of the picked gain (s = g as in the main run), then ring_gains.py."""
|
| 168 |
+
out = f'{a.root}/{tag}';P = json.load(open(f'{out}/params.json'));lg = f'{out}/log.txt'
|
| 169 |
+
common = ['--model', MODELS[tag][0], '--jlens', fetch(tag), '--vocab', a.vocab, '--k', str(a.k)]
|
| 170 |
+
per = seeds_per_chunk(tag, a.T, N_CONDS, mem_gb, a.max_chunk)
|
| 171 |
+
for mult in [float(x) for x in a.gains.split(',')]:
|
| 172 |
+
g = round(P['g']*mult, 4)
|
| 173 |
+
run_seeds(f'{out}/gains/g{g}', a.gain_seeds, per, lambda s0, n, d:[
|
| 174 |
+
PY, 'ring.py', *common, '--grid', 'main', '--seeds', str(n), '--seed0', str(s0), '--rng', str(2234+s0),
|
| 175 |
+
'--T', str(a.T), '--t_freeze', str(a.t_freeze), '--g', str(g), '--sigma', str(P['sigma']), '--out', d], lg, least=2)
|
| 176 |
+
if not os.path.exists(f'{out}/gains/gains.json'):
|
| 177 |
+
sh([PY, 'ring_gains.py', out], f'{out}/gains/summary.txt')
|
| 178 |
+
log(tag, 'gain ladder done');up.put(f'{out}/gains', f'{tag}/gains')
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def main():
|
| 182 |
+
p = argparse.ArgumentParser()
|
| 183 |
+
p.add_argument('--models', default='qwen3-4b,qwen3-8b,qwen3-14b,qwen3-1.7b');p.add_argument('--root', default='runs/ring')
|
| 184 |
+
p.add_argument('--hf', default='');p.add_argument('--vocab', default='english');p.add_argument('--k', type=int, default=25)
|
| 185 |
+
p.add_argument('--T', type=int, default=600);p.add_argument('--t_freeze', type=int, default=300)
|
| 186 |
+
p.add_argument('--seeds', type=int, default=24);p.add_argument('--sweep_seeds', type=int, default=6)
|
| 187 |
+
p.add_argument('--gs', default='.05,.1,.2,.3,.5,.8');p.add_argument('--sigmas', default='.05,.15')
|
| 188 |
+
p.add_argument('--long', default='qwen3-4b');p.add_argument('--long_T', type=int, default=2000)
|
| 189 |
+
p.add_argument('--long_seeds', type=int, default=8);p.add_argument('--max_chunk', type=int, default=64)
|
| 190 |
+
p.add_argument('--mem_gb', type=float, default=0, help='card memory (default: measured)')
|
| 191 |
+
p.add_argument('--upload_only', action='store_true')
|
| 192 |
+
p.add_argument('--gains', default='', help='stage 2: multiples of the picked gain');p.add_argument('--gain_seeds', type=int, default=16)
|
| 193 |
+
a = p.parse_args();a.root = os.path.abspath(a.root);os.makedirs(a.root, exist_ok=True)
|
| 194 |
+
if a.upload_only:
|
| 195 |
+
from huggingface_hub import HfApi
|
| 196 |
+
api = HfApi()
|
| 197 |
+
api.upload_folder(repo_id=a.hf, repo_type='dataset', folder_path=a.root, path_in_repo='.', commit_message='ring: all')
|
| 198 |
+
for f in ('/workspace/job.log', '/workspace/job2.log', '/workspace/setup.log'):
|
| 199 |
+
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,
|
| 200 |
+
repo_type='dataset')
|
| 201 |
+
log('final upload done');return
|
| 202 |
+
mem_gb = a.mem_gb or float(subprocess.check_output(['nvidia-smi', '--query-gpu=memory.total', '--format=csv,noheader,nounits'],
|
| 203 |
+
text=True).split()[0])/1024 # no CUDA context in this process
|
| 204 |
+
tags = a.models.split(',')
|
| 205 |
+
log(f'ring job: {tags} | card {mem_gb:.1f} GB | root {a.root} | upload to {a.hf or "(none)"}')
|
| 206 |
+
threading.Thread(target=lambda:[fetch(t) for t in tags], daemon=True).start() # downloads overlap the compute
|
| 207 |
+
up = Uploader(a.hf);up.start();errors = []
|
| 208 |
+
if a.gains:
|
| 209 |
+
for tag in tags:
|
| 210 |
+
try:run_gains(tag, a, up, mem_gb)
|
| 211 |
+
except Exception as e:errors.append(tag);log('GAINS FAILED', tag, repr(e)[:400])
|
| 212 |
+
up.q.put(None);up.join()
|
| 213 |
+
json.dump(dict(errors=errors, upload_failed=up.failed, finished=time.time()), open(f'{a.root}/DONE2.json', 'w'))
|
| 214 |
+
log('stage 2 done', 'errors', errors, 'upload failures', up.failed);return
|
| 215 |
+
for tag in tags:
|
| 216 |
+
try:run_model(tag, a, up, mem_gb)
|
| 217 |
+
except Exception as e:errors.append(tag);log('MODEL FAILED', tag, repr(e)[:400])
|
| 218 |
+
if a.long and a.long in tags and a.long not in errors and a.long_T:
|
| 219 |
+
try:run_model(a.long, a, up, mem_gb, long=True)
|
| 220 |
+
except Exception as e:errors.append(a.long+'-long');log('MODEL FAILED', a.long, 'long', repr(e)[:400])
|
| 221 |
+
up.q.put(None);up.join()
|
| 222 |
+
json.dump(dict(errors=errors, upload_failed=up.failed, finished=time.time()), open(f'{a.root}/DONE.json', 'w'))
|
| 223 |
+
log('all done', 'errors', errors, 'upload failures', up.failed)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == '__main__':
|
| 227 |
+
main()
|
code/stage2/ring_ladder.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Across models: the ring's pre-registered tests from each results.json, side by side, plus Stouffer's z over models.
|
| 2 |
+
|
| 3 |
+
python ring_ladder.py runs/ring -> runs/ring/ladder.json and a table on stdout
|
| 4 |
+
"""
|
| 5 |
+
import json, math, os, sys
|
| 6 |
+
|
| 7 |
+
root = sys.argv[1]
|
| 8 |
+
ORDER = ['qwen3-1.7b', 'qwen3-4b', 'qwen3-8b', 'qwen3-14b', 'qwen3-4b-long']
|
| 9 |
+
models = [m for m in ORDER if os.path.exists(f'{root}/{m}/main/results.json')]
|
| 10 |
+
R = {m:json.load(open(f'{root}/{m}/main/results.json', encoding='utf-8')) for m in models}
|
| 11 |
+
PRIMARY = [('ring_err_vs_vel', ('explore', 'stuck', 'skill', 'lag100')), ('ring_err_vs_yoked_err', ('explore', 'stuck', 'skill', 'lag100')),
|
| 12 |
+
('ring_err_vs_shuf_err', ('explore', 'stuck', 'skill', 'lag100')), ('ring_err_vs_rand_err', ('explore', 'stuck', 'skill', 'lag100')),
|
| 13 |
+
('freeze_effect', ('explore', 'stuck', 'skill'))]
|
| 14 |
+
SECONDARY = [('ring_pred_vs_content', ('explore', 'stuck', 'skill', 'selffulfil')),
|
| 15 |
+
('ring_pred_vs_yoked_pred', ('explore', 'stuck', 'skill', 'selffulfil')),
|
| 16 |
+
('ring_err_vs_free', ('explore', 'stuck', 'skill')), ('ring_pred_vs_free', ('explore', 'stuck', 'skill'))]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def cell(t):
|
| 20 |
+
return ' — ' if not t else f"{t['diff']:+7.3f} t{t['t']:+6.1f}"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def stouffer(ts):
|
| 24 |
+
ts = [t['t'] for t in ts if t and t['se'] > 0]
|
| 25 |
+
return (sum(ts)/math.sqrt(len(ts)), len(ts)) if ts else (0., 0)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
out = dict(models=models, regimes={}, tests={}, privileged={})
|
| 29 |
+
print('regime per model (pilot rule): g = s, sigma; free minds at that setting')
|
| 30 |
+
for m in models:
|
| 31 |
+
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'])
|
| 32 |
+
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']}")
|
| 33 |
+
for title, block in (('PRIMARY', PRIMARY), ('SECONDARY', SECONDARY)):
|
| 34 |
+
print(f'\n{title}: paired difference (first minus second), t over seeds; last column Stouffer z over the main models')
|
| 35 |
+
print(f"{'test':26s} {'metric':8s} " + ' '.join(f'{m:>15s}' for m in models) + ' pooled z')
|
| 36 |
+
for name, metrics in block:
|
| 37 |
+
for k in metrics:
|
| 38 |
+
ts = [R[m]['tests'].get(name, {}).get(k) if R[m]['tests'].get(name) else None for m in models]
|
| 39 |
+
z, n = stouffer([t for m, t in zip(models, ts) if not m.endswith('-long')])
|
| 40 |
+
out['tests'][f'{name}.{k}'] = dict(per_model=dict(zip(models, ts)), stouffer_z=z, n_models=n)
|
| 41 |
+
print(f"{name:26s} {k:8s} " + ' '.join(f'{cell(t):>15s}' for t in ts) + f' {z:+6.1f} ({n})')
|
| 42 |
+
print('\nprivileged self-knowledge: own-fitted minus other-fitted next-state predictor (cosine), t over seeds')
|
| 43 |
+
for c in ('free', 'ring_err', 'ring_pred', 'content', 'vel', 'yoked_err'):
|
| 44 |
+
ts = [R[m]['privileged'].get(c, {}).get('test') for m in models]
|
| 45 |
+
z, n = stouffer([t for m, t in zip(models, ts) if not m.endswith('-long')])
|
| 46 |
+
out['privileged'][c] = dict(per_model=dict(zip(models, ts)), stouffer_z=z)
|
| 47 |
+
print(f"{c:12s} " + ' '.join(f'{cell(t):>15s}' for t in ts) + f' {z:+6.1f} ({n})')
|
| 48 |
+
print('\nper-condition means (explore / stuck / skill)')
|
| 49 |
+
conds = list(R[models[0]]['summary']) if models else []
|
| 50 |
+
for c in conds:
|
| 51 |
+
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}"
|
| 52 |
+
for m in models))
|
| 53 |
+
json.dump(out, open(f'{root}/ladder.json', 'w', encoding='utf-8'), indent=1)
|
code/stage2/ring_run2.sh
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Stage 2 (the exploratory gain ladder), chained after ring_run.sh, which must have been told to leave the instance up
|
| 3 |
+
# (/workspace/HOLD). Waits until stage 1 has finished and uploaded, runs ring_job.py --gains ..., pushes everything to
|
| 4 |
+
# the dataset, then destroys the instance. It stops the instance instead if the upload failed, and leaves it
|
| 5 |
+
# running if /workspace/HOLD2 exists.
|
| 6 |
+
# bash ring_run2.sh <ring_job.py args...>
|
| 7 |
+
cd "$(dirname "$0")"
|
| 8 |
+
PY=${PY:-/opt/conda/bin/python}
|
| 9 |
+
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True HF_HUB_DISABLE_PROGRESS_BARS=1 TOKENIZERS_PARALLELISM=false
|
| 10 |
+
say() { echo "$(date '+%F %T') [run2] $*" >> /workspace/job2.log; }
|
| 11 |
+
say "waiting for stage 1"
|
| 12 |
+
until grep -q "\[run\] HOLD set" /workspace/job.log 2>/dev/null; do
|
| 13 |
+
# stage 1's wrapper died before its end: go on once its DONE.json is 45 min old
|
| 14 |
+
[ -f /workspace/runs/ring/DONE.json ] && [ $(( $(date +%s) - $(stat -c %Y /workspace/runs/ring/DONE.json) )) -gt 2700 ] && break
|
| 15 |
+
sleep 20
|
| 16 |
+
done
|
| 17 |
+
say "stage 2 start"
|
| 18 |
+
setsid $PY ring_job.py "$@" >> /workspace/job2.log 2>&1 &
|
| 19 |
+
JOB=$!
|
| 20 |
+
while kill -0 $JOB 2>/dev/null; do
|
| 21 |
+
if [ $(date +%s) -gt $(cat /workspace/deadline) ]; then
|
| 22 |
+
say "deadline passed, stopping the job"; kill -TERM -- -$JOB 2>/dev/null; sleep 30; kill -KILL -- -$JOB 2>/dev/null
|
| 23 |
+
fi
|
| 24 |
+
sleep 20
|
| 25 |
+
done
|
| 26 |
+
wait $JOB; say "stage 2 ended (rc $?)"
|
| 27 |
+
UP=1
|
| 28 |
+
for i in 1 2 3; do timeout 2400 $PY ring_job.py "$@" --upload_only >> /workspace/job2.log 2>&1 && { UP=0; break; }; sleep 60; done
|
| 29 |
+
if [ -f /workspace/HOLD2 ]; then say "HOLD2 set: leaving the instance running (watchdog stops it an hour after the deadline)"
|
| 30 |
+
elif [ $UP = 0 ]; then say "uploaded, destroying the instance"; bash vast_self.sh destroy >> /workspace/job2.log 2>&1
|
| 31 |
+
else say "upload failed, stopping the instance (disk kept)"; bash vast_self.sh stop >> /workspace/job2.log 2>&1; fi
|