Pixedar commited on
Commit
4709002
·
verified ·
1 Parent(s): 2de5528

Parts 1-2 code: same as the GitHub release (citations by author)

Browse files
Files changed (2) hide show
  1. parts1-2_code/run_ladder.py +115 -115
  2. parts1-2_code/strange_loop.py +479 -479
parts1-2_code/run_ladder.py CHANGED
@@ -1,115 +1,115 @@
1
- """Run the strange-loop experiment up a ladder of model sizes, each with its own Neuronpedia J-lens.
2
-
3
- Per model: validate the lens (validate_lens.py); sweep the recurrent gain on observers and pick the one whose
4
- observers keep about as much memory as Qwen3-4B-Base did in run C (lag-1 similarity ~0.2, fluent); at that gain, test
5
- the reflection layer and gain on 16 observers and keep the one whose self-model best picks out its own window; then the
6
- main run (free / own individual self / foreign individual self / clamp, with the forward question) and its analysis.
7
- Each step is skipped when its output exists, so the ladder resumes after a crash.
8
-
9
- Dictionary: the lens is Neuronpedia's (Anthropic's reference code), the decomposition the paper's (non-negative
10
- pursuit, K = 25), the J-lens vectors those of common English words. The paper's every-token dictionary was measured
11
- first (fidelity_check.py, 16 observers): on Qwen3-1.7B it read the trajectory half as well (25 % vs 49 %, raw
12
- residual 46 %), on Qwen3-4B 57 % vs 68 % (raw 47 %).
13
-
14
- python run_ladder.py --models qwen3-1.7b,qwen3-4b,qwen3-8b,qwen3-14b,qwen3-32b
15
- """
16
- import argparse, json, os, re, subprocess, sys
17
- import numpy as np
18
-
19
- LENSES = {'qwen3-1.7b':('Qwen/Qwen3-1.7B', 'Qwen3-1.7B'), 'qwen3-4b':('Qwen/Qwen3-4B', 'Qwen3-4B'),
20
- 'qwen3-8b':('Qwen/Qwen3-8B', 'Qwen3-8B'), 'qwen3-14b':('Qwen/Qwen3-14B', 'Qwen3-14B'),
21
- 'qwen3-32b':('Qwen/Qwen3-32B', 'Qwen3-32B')}
22
- N_LAYERS = {'qwen3-1.7b':28, 'qwen3-4b':36, 'qwen3-8b':36, 'qwen3-14b':40, 'qwen3-32b':64}
23
- PY = sys.executable
24
-
25
-
26
- def sh(cmd, log):
27
- print('>>', ' '.join(cmd), flush=True)
28
- with open(log, 'a') as f:
29
- r = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT)
30
- if r.returncode:raise SystemExit(f'failed ({r.returncode}): see {log}')
31
-
32
-
33
- def lens_path(tag):
34
- from huggingface_hub import hf_hub_download
35
- name = LENSES[tag][1]
36
- return hf_hub_download('neuronpedia/jacobian-lens', f'{tag}/jlens/Salesforce-wikitext/{name}_jacobian_lens.pt')
37
-
38
-
39
- def pick_gain(sweep_dir, target=.2):
40
- """Gain: the observers' lag-1 similarity closest to `target` among fluent settings (run C of Qwen3-4B-Base sat at
41
- 0.19-0.23). Reflection: the layer and gain whose self-model best picks out its own window among all rows."""
42
- z = np.load(f'{sweep_dir}/traj.npz');m = json.load(open(f'{sweep_dir}/meta.json', encoding='utf-8'))
43
- rows, a = m['rows'], m['args'];K = a['K'];j = z['j'].astype(np.float32);N, B = j.shape[:2]
44
- unit = lambda x:x/np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-8)
45
- ju = unit(j);zz = np.zeros_like(j);s_ = np.zeros_like(j[0])
46
- for t in range(N):s_ = .6*s_+.4*j[t];zz[t] = s_
47
- wordy = lambda s:np.mean([bool(re.fullmatch(r"[A-Za-z',.!?;:-]+", w)) for w in s.split()] or [0])
48
- gains = {}
49
- for g in sorted({r['g'] for r in rows}):
50
- bs = [b for b, r in enumerate(rows) if r['g'] == g]
51
- lag1 = float(np.mean([(ju[10:-1, b]*ju[11:, b]).sum(-1).mean() for b in bs]))
52
- wd = float(np.mean([wordy(m['texts'][t][b]) for t in range(N) for b in bs]))
53
- d2 = float(np.mean([len(set(zip(w[:-1], w[1:])))/max(1, len(w)-1) for t in range(N) for b in bs for w in [m['texts'][t][b].split()]]))
54
- gains[g] = dict(lag1=lag1, wordy=wd, distinct2=d2)
55
- ok = [g for g, v in gains.items() if v['wordy'] >= .9 and v['distinct2'] >= .85] or list(gains)
56
- return dict(g=min(ok, key=lambda g:abs(gains[g]['lag1']-target)), gains=gains)
57
-
58
-
59
- def pick_reflection(sweep_dir):
60
- """All rows share one gain here, so a self-model's own window competes with 15 others like it."""
61
- z = np.load(f'{sweep_dir}/traj.npz');m = json.load(open(f'{sweep_dir}/meta.json', encoding='utf-8'))
62
- K = m['args']['K'];j = z['j'].astype(np.float32);N, B = j.shape[:2]
63
- unit = lambda x:x/np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-8)
64
- zz = np.zeros_like(j);s_ = np.zeros_like(j[0])
65
- for t in range(N):s_ = .6*s_+.4*j[t];zz[t] = s_
66
- NR = z['m'].shape[0];win = unit(np.stack([zz[r*K:(r+1)*K].mean(0) for r in range(NR)]))
67
- fid = {}
68
- for name in [f for f in z.files if f.startswith('fid_')]:
69
- M = unit(z[name].astype(np.float32));hit = []
70
- for r in range(1, NR):
71
- S = M[r]@win[r].T;hit += list(S.argmax(1) == np.arange(B))
72
- fid[name] = float(np.mean(hit))
73
- best = max(fid, key=fid.get);L_in, g_r = best[4:].split('_')
74
- return dict(L_in=int(L_in), g_r=float(g_r), fidelity=fid, chance=1/B)
75
-
76
-
77
- def main():
78
- p = argparse.ArgumentParser()
79
- p.add_argument('--models', default='qwen3-1.7b,qwen3-4b,qwen3-8b,qwen3-14b,qwen3-32b')
80
- p.add_argument('--seeds', type=int, default=12);p.add_argument('--n_iter', type=int, default=300)
81
- p.add_argument('--t_int', type=int, default=120);p.add_argument('--k', type=int, default=25)
82
- p.add_argument('--root', default='runs/ladder2');p.add_argument('--vocab', default='english')
83
- p.add_argument('--atoms', default='centred')
84
- p.add_argument('--depth', type=float, default=.5, help='read layer as a fraction of depth (Qwen3 lens check: concepts from ~0.6)')
85
- a = p.parse_args()
86
- for tag in a.models.split(','):
87
- model, _ = LENSES[tag];out = f'{a.root}/{tag}';os.makedirs(out, exist_ok=True);log = f'{out}/log.txt'
88
- lens = lens_path(tag);n = N_LAYERS[tag];L = int(round(a.depth*n))
89
- common = ['--model', model, '--jlens', lens, '--vocab', a.vocab, '--atoms', a.atoms, '--k', str(a.k), '--layer', str(L)]
90
- if not os.path.exists(f'{out}/val.json'):
91
- sh([PY, 'validate_lens.py', '--model', model, '--jlens', lens, '--out', f'{out}/val.json'], log)
92
- if not os.path.exists(f'{out}/gsweep/meta.json'):
93
- sh([PY, 'strange_loop.py', *common, '--grid', 'gsweep', '--gs', '.03,.05,.08,.12,.2', '--seeds', '6', '--n_iter', '60',
94
- '--L_in', str(L-1), '--out', f'{out}/gsweep'], log)
95
- if not os.path.exists(f'{out}/gain.json'):json.dump(pick_gain(f'{out}/gsweep'), open(f'{out}/gain.json', 'w'), indent=1)
96
- g = json.load(open(f'{out}/gain.json'))['g']
97
- if not os.path.exists(f'{out}/fsweep/meta.json'):
98
- offs = sorted({1, 2, 3, max(1, int(round(.1*n))), max(1, int(round(.15*n)))})
99
- fid = ','.join(f'{L-o}:{gr}' for o in offs for gr in (.5, 1.))
100
- sh([PY, 'strange_loop.py', *common, '--grid', 'gsweep', '--gs', str(g), '--seeds', '16', '--n_iter', '60',
101
- '--L_in', str(L-1), '--fid', fid, '--out', f'{out}/fsweep'], log)
102
- if not os.path.exists(f'{out}/params.json'):
103
- json.dump(dict(g=g, **pick_reflection(f'{out}/fsweep')), open(f'{out}/params.json', 'w'), indent=1)
104
- P = json.load(open(f'{out}/params.json'));print(tag, 'picked', {k:P[k] for k in ('g', 'L_in', 'g_r')}, flush=True)
105
- if not os.path.exists(f'{out}/main/meta.json'):
106
- sh([PY, 'strange_loop.py', *common, '--grid', 'main', '--conds', 'free,loopc,yokedc,clampc', '--seeds', str(a.seeds),
107
- '--n_iter', str(a.n_iter), '--t_int', str(a.t_int), '--clamp_len', '50', '--g', str(P['g']),
108
- '--L_in', str(P['L_in']), '--g_r', str(P['g_r']), '--out', f'{out}/main'], log)
109
- if not os.path.exists(f'{out}/main/results.json'):
110
- sh([PY, 'analyze.py', f'{out}/main'], f'{out}/main/summary.txt')
111
- print(tag, 'done', flush=True)
112
-
113
-
114
- if __name__ == '__main__':
115
- main()
 
1
+ """Run the strange-loop experiment up a ladder of model sizes, each with its own Neuronpedia J-lens.
2
+
3
+ Per model: validate the lens (validate_lens.py); sweep the recurrent gain on observers and pick the one whose
4
+ observers keep about as much memory as Qwen3-4B-Base did in run C (lag-1 similarity ~0.2, fluent); at that gain, test
5
+ the reflection layer and gain on 16 observers and keep the one whose self-model best picks out its own window; then the
6
+ main run (free / own individual self / foreign individual self / clamp, with the forward question) and its analysis.
7
+ Each step is skipped when its output exists, so the ladder resumes after a crash.
8
+
9
+ Dictionary: the lens is Neuronpedia's (the paper's reference code), the decomposition the paper's (non-negative
10
+ pursuit, K = 25), the J-lens vectors those of common English words. The paper's every-token dictionary was measured
11
+ first (fidelity_check.py, 16 observers): on Qwen3-1.7B it read the trajectory half as well (25 % vs 49 %, raw
12
+ residual 46 %), on Qwen3-4B 57 % vs 68 % (raw 47 %).
13
+
14
+ python run_ladder.py --models qwen3-1.7b,qwen3-4b,qwen3-8b,qwen3-14b,qwen3-32b
15
+ """
16
+ import argparse, json, os, re, subprocess, sys
17
+ import numpy as np
18
+
19
+ LENSES = {'qwen3-1.7b':('Qwen/Qwen3-1.7B', 'Qwen3-1.7B'), 'qwen3-4b':('Qwen/Qwen3-4B', 'Qwen3-4B'),
20
+ 'qwen3-8b':('Qwen/Qwen3-8B', 'Qwen3-8B'), 'qwen3-14b':('Qwen/Qwen3-14B', 'Qwen3-14B'),
21
+ 'qwen3-32b':('Qwen/Qwen3-32B', 'Qwen3-32B')}
22
+ N_LAYERS = {'qwen3-1.7b':28, 'qwen3-4b':36, 'qwen3-8b':36, 'qwen3-14b':40, 'qwen3-32b':64}
23
+ PY = sys.executable
24
+
25
+
26
+ def sh(cmd, log):
27
+ print('>>', ' '.join(cmd), flush=True)
28
+ with open(log, 'a') as f:
29
+ r = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT)
30
+ if r.returncode:raise SystemExit(f'failed ({r.returncode}): see {log}')
31
+
32
+
33
+ def lens_path(tag):
34
+ from huggingface_hub import hf_hub_download
35
+ name = LENSES[tag][1]
36
+ return hf_hub_download('neuronpedia/jacobian-lens', f'{tag}/jlens/Salesforce-wikitext/{name}_jacobian_lens.pt')
37
+
38
+
39
+ def pick_gain(sweep_dir, target=.2):
40
+ """Gain: the observers' lag-1 similarity closest to `target` among fluent settings (run C of Qwen3-4B-Base sat at
41
+ 0.19-0.23). Reflection: the layer and gain whose self-model best picks out its own window among all rows."""
42
+ z = np.load(f'{sweep_dir}/traj.npz');m = json.load(open(f'{sweep_dir}/meta.json', encoding='utf-8'))
43
+ rows, a = m['rows'], m['args'];K = a['K'];j = z['j'].astype(np.float32);N, B = j.shape[:2]
44
+ unit = lambda x:x/np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-8)
45
+ ju = unit(j);zz = np.zeros_like(j);s_ = np.zeros_like(j[0])
46
+ for t in range(N):s_ = .6*s_+.4*j[t];zz[t] = s_
47
+ wordy = lambda s:np.mean([bool(re.fullmatch(r"[A-Za-z',.!?;:-]+", w)) for w in s.split()] or [0])
48
+ gains = {}
49
+ for g in sorted({r['g'] for r in rows}):
50
+ bs = [b for b, r in enumerate(rows) if r['g'] == g]
51
+ lag1 = float(np.mean([(ju[10:-1, b]*ju[11:, b]).sum(-1).mean() for b in bs]))
52
+ wd = float(np.mean([wordy(m['texts'][t][b]) for t in range(N) for b in bs]))
53
+ d2 = float(np.mean([len(set(zip(w[:-1], w[1:])))/max(1, len(w)-1) for t in range(N) for b in bs for w in [m['texts'][t][b].split()]]))
54
+ gains[g] = dict(lag1=lag1, wordy=wd, distinct2=d2)
55
+ ok = [g for g, v in gains.items() if v['wordy'] >= .9 and v['distinct2'] >= .85] or list(gains)
56
+ return dict(g=min(ok, key=lambda g:abs(gains[g]['lag1']-target)), gains=gains)
57
+
58
+
59
+ def pick_reflection(sweep_dir):
60
+ """All rows share one gain here, so a self-model's own window competes with 15 others like it."""
61
+ z = np.load(f'{sweep_dir}/traj.npz');m = json.load(open(f'{sweep_dir}/meta.json', encoding='utf-8'))
62
+ K = m['args']['K'];j = z['j'].astype(np.float32);N, B = j.shape[:2]
63
+ unit = lambda x:x/np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-8)
64
+ zz = np.zeros_like(j);s_ = np.zeros_like(j[0])
65
+ for t in range(N):s_ = .6*s_+.4*j[t];zz[t] = s_
66
+ NR = z['m'].shape[0];win = unit(np.stack([zz[r*K:(r+1)*K].mean(0) for r in range(NR)]))
67
+ fid = {}
68
+ for name in [f for f in z.files if f.startswith('fid_')]:
69
+ M = unit(z[name].astype(np.float32));hit = []
70
+ for r in range(1, NR):
71
+ S = M[r]@win[r].T;hit += list(S.argmax(1) == np.arange(B))
72
+ fid[name] = float(np.mean(hit))
73
+ best = max(fid, key=fid.get);L_in, g_r = best[4:].split('_')
74
+ return dict(L_in=int(L_in), g_r=float(g_r), fidelity=fid, chance=1/B)
75
+
76
+
77
+ def main():
78
+ p = argparse.ArgumentParser()
79
+ p.add_argument('--models', default='qwen3-1.7b,qwen3-4b,qwen3-8b,qwen3-14b,qwen3-32b')
80
+ p.add_argument('--seeds', type=int, default=12);p.add_argument('--n_iter', type=int, default=300)
81
+ p.add_argument('--t_int', type=int, default=120);p.add_argument('--k', type=int, default=25)
82
+ p.add_argument('--root', default='runs/ladder2');p.add_argument('--vocab', default='english')
83
+ p.add_argument('--atoms', default='centred')
84
+ p.add_argument('--depth', type=float, default=.5, help='read layer as a fraction of depth (Qwen3 lens check: concepts from ~0.6)')
85
+ a = p.parse_args()
86
+ for tag in a.models.split(','):
87
+ model, _ = LENSES[tag];out = f'{a.root}/{tag}';os.makedirs(out, exist_ok=True);log = f'{out}/log.txt'
88
+ lens = lens_path(tag);n = N_LAYERS[tag];L = int(round(a.depth*n))
89
+ common = ['--model', model, '--jlens', lens, '--vocab', a.vocab, '--atoms', a.atoms, '--k', str(a.k), '--layer', str(L)]
90
+ if not os.path.exists(f'{out}/val.json'):
91
+ sh([PY, 'validate_lens.py', '--model', model, '--jlens', lens, '--out', f'{out}/val.json'], log)
92
+ if not os.path.exists(f'{out}/gsweep/meta.json'):
93
+ sh([PY, 'strange_loop.py', *common, '--grid', 'gsweep', '--gs', '.03,.05,.08,.12,.2', '--seeds', '6', '--n_iter', '60',
94
+ '--L_in', str(L-1), '--out', f'{out}/gsweep'], log)
95
+ if not os.path.exists(f'{out}/gain.json'):json.dump(pick_gain(f'{out}/gsweep'), open(f'{out}/gain.json', 'w'), indent=1)
96
+ g = json.load(open(f'{out}/gain.json'))['g']
97
+ if not os.path.exists(f'{out}/fsweep/meta.json'):
98
+ offs = sorted({1, 2, 3, max(1, int(round(.1*n))), max(1, int(round(.15*n)))})
99
+ fid = ','.join(f'{L-o}:{gr}' for o in offs for gr in (.5, 1.))
100
+ sh([PY, 'strange_loop.py', *common, '--grid', 'gsweep', '--gs', str(g), '--seeds', '16', '--n_iter', '60',
101
+ '--L_in', str(L-1), '--fid', fid, '--out', f'{out}/fsweep'], log)
102
+ if not os.path.exists(f'{out}/params.json'):
103
+ json.dump(dict(g=g, **pick_reflection(f'{out}/fsweep')), open(f'{out}/params.json', 'w'), indent=1)
104
+ P = json.load(open(f'{out}/params.json'));print(tag, 'picked', {k:P[k] for k in ('g', 'L_in', 'g_r')}, flush=True)
105
+ if not os.path.exists(f'{out}/main/meta.json'):
106
+ sh([PY, 'strange_loop.py', *common, '--grid', 'main', '--conds', 'free,loopc,yokedc,clampc', '--seeds', str(a.seeds),
107
+ '--n_iter', str(a.n_iter), '--t_int', str(a.t_int), '--clamp_len', '50', '--g', str(P['g']),
108
+ '--L_in', str(P['L_in']), '--g_r', str(P['g_r']), '--out', f'{out}/main'], log)
109
+ if not os.path.exists(f'{out}/main/results.json'):
110
+ sh([PY, 'analyze.py', f'{out}/main'], f'{out}/main/summary.txt')
111
+ print(tag, 'done', flush=True)
112
+
113
+
114
+ if __name__ == '__main__':
115
+ main()
parts1-2_code/strange_loop.py CHANGED
@@ -1,479 +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()
 
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
+ (Gurnee et al. 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()