anonymousfileupload commited on
Commit
dd138ec
·
verified ·
1 Parent(s): 1420aaa

divsim reproducibility bundle: simulator, sweeps, analyses (step_marks fix)

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ oasis/seed_db/hf-zero-50.sqlite filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Internal coordination notes — contain identifying information, never ship in an
2
+ # anonymous release.
3
+ _orchestration/
4
+ __pycache__/
5
+ *.pyc
LICENSE ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dani Roytburg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ The `oasis/` subdirectory contains code adapted from the OASIS simulator
26
+ (https://github.com/camel-ai/oasis), which is licensed under the Apache
27
+ License 2.0. See oasis/NOTICE for details.
README.md ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # divsim: Reproducibility Bundle
2
+
3
+ **Paper:** *Disentangling Models from Personas in LLM Social Simulations*
4
+ Dani Roytburg & Daphne Ippolito, Carnegie Mellon University.
5
+
6
+ This bundle reproduces the experiments in the paper: the 5-model dyadic and triadic
7
+ sweeps, the four-way (tetradic) sweep, and the lexical/content analyses. Engagement is
8
+ analyzed as **comments per post** (CPP = in-degree / posts), which removes the
9
+ posting-volume confound. The simulations run on top of OASIS (Open Agent Social
10
+ Interaction Simulations), adapted with heterogeneous model support.
11
+
12
+ ---
13
+
14
+ ## Hardware assumptions
15
+
16
+ | Component | Spec |
17
+ |-----------|------|
18
+ | GPUs | 8 × NVIDIA L40S 48 GB |
19
+ | System RAM | ≥ 128 GB |
20
+ | CPU cores | ≥ 32 |
21
+ | Storage | ≥ 200 GB free (model weights + DBs) |
22
+
23
+ All five models run concurrently on a single 8-GPU node. Dyadic runs need any
24
+ two models active; triadic runs need any three. The sbatch templates in
25
+ `launch/` target this configuration.
26
+
27
+ ---
28
+
29
+ ## Models
30
+
31
+ | Short name | HuggingFace ID | GPU assignment | Notes |
32
+ |-----------|----------------|----------------|-------|
33
+ | Qwen | `Qwen/Qwen3-32B` | GPUs 0-1 (TP=2) | thinking disabled via chat-template |
34
+ | gpt-oss | `openai/gpt-oss-20b` | GPU 2 (TP=1, mxfp4) | reasoning parser enabled |
35
+ | Mag | `mistralai/Magistral-Small-2509` | GPUs 3-4 (TP=2) | mistral tokenizer/loader mode |
36
+ | GLM-4 | `zai-org/GLM-4-32B-0414` | GPUs 5-6 (TP=2) | hermes tool parser |
37
+ | Gemma | `google/gemma-4-31B-it` | GPUs 3-4 (TP=2) | custom jinja template required |
38
+
39
+ Note: Gemma shares GPUs 3-4 with Magistral. They cannot run simultaneously on
40
+ a single 8-GPU node. For triadic runs involving both, use two separate nodes or
41
+ run the Gemma-containing triplets in a separate job.
42
+
43
+ ---
44
+
45
+ ## Quick start
46
+
47
+ ### 1. Environment setup
48
+
49
+ ```bash
50
+ git clone https://github.com/camel-ai/oasis.git # or use bundled oasis/
51
+ cd divsim_publish
52
+ python -m venv .venv && source .venv/bin/activate
53
+ pip install -r env/requirements.txt
54
+ ```
55
+
56
+ Set these environment variables before running:
57
+
58
+ ```bash
59
+ export HF_HUB_CACHE=/path/to/hf_cache/hub # HuggingFace model cache
60
+ export SAFEMASS_VENV=$(pwd)/.venv # or path to your venv
61
+ export RUNS_DIR=/path/to/output/runs # where DBs will be written
62
+ export SEED_DB=$(pwd)/oasis/seed_db/hf-zero-50.sqlite
63
+ export LOGS_DIR=/path/to/logs
64
+ ```
65
+
66
+ ### 2. Download models
67
+
68
+ ```bash
69
+ python -c "
70
+ from huggingface_hub import snapshot_download
71
+ import os
72
+ os.environ['HF_HUB_CACHE'] = os.environ['HF_HUB_CACHE']
73
+ for m in [
74
+ 'Qwen/Qwen3-32B',
75
+ 'openai/gpt-oss-20b',
76
+ 'mistralai/Magistral-Small-2509',
77
+ 'zai-org/GLM-4-32B-0414',
78
+ 'google/gemma-4-31B-it',
79
+ ]:
80
+ print(f'Downloading {m}...')
81
+ snapshot_download(m)
82
+ print(f' done.')
83
+ "
84
+ ```
85
+
86
+ ### 3. Start vLLM servers
87
+
88
+ Launch each model server in a separate terminal (or as background processes):
89
+
90
+ ```bash
91
+ # For a 4-model (non-Gemma) run:
92
+ bash launch/vllm_qwen.sh &
93
+ bash launch/vllm_gpt_oss.sh &
94
+ bash launch/vllm_magistral.sh &
95
+ bash launch/vllm_glm4.sh &
96
+
97
+ # For Gemma runs (requires GPUs 3-4 to be free — stop Magistral first):
98
+ bash launch/vllm_gemma.sh &
99
+ ```
100
+
101
+ Wait for all target servers to respond at their health endpoints before
102
+ proceeding. The sweep scripts perform a pre-flight health check.
103
+
104
+ ### 4. Run the dyadic sweep
105
+
106
+ ```bash
107
+ source .venv/bin/activate
108
+ python sweep/sweep_dyadic.py --mode 2model --max-parallel 2
109
+ ```
110
+
111
+ Optional: `--dry-run` to print all configs without launching.
112
+
113
+ ### 5. Run the triadic sweep
114
+
115
+ ```bash
116
+ python sweep/sweep_triadic.py --max-parallel 2
117
+ ```
118
+
119
+ ### 5b. Run the four-way (tetradic) sweep
120
+
121
+ Serves all four of {gpt-oss, Qwen, Magistral, GLM-4} concurrently and runs the
122
+ 2-seed x 12-rotation four-way sweep (`run_v9 --mode hetero4`, 40 agents):
123
+
124
+ ```bash
125
+ SAFEMASS_VENV=... OASIS_VENV=... HF_HUB_CACHE=... RUNS_DIR=... bash launch/run_tetradic.sh
126
+ ```
127
+
128
+ Resume-safe: completed DBs are skipped, partial ones resume. Outputs land in `$RUNS_DIR/tetradic/`.
129
+
130
+ ### 6. Analyses and figures
131
+
132
+ Scripts read run DBs from `./runs` (symlink or point at `$RUNS_DIR`), the text corpus
133
+ from `./data/texts.jsonl`, and write outputs to `./out/`. Build the corpus once:
134
+
135
+ ```bash
136
+ python analyses/extract_texts.py # -> data/texts.jsonl (posts+comments by model,persona)
137
+ ```
138
+
139
+ Engagement / network structure (Findings 1-2):
140
+ ```bash
141
+ python analyses/plot_fig_variance_overview.py # Fig: CPP variance (model vs persona) + per-model H by mixture size
142
+ python analyses/variance_cpp.py # CPP variance decomposition + leave-one-model-out
143
+ python analyses/swap_cpp.py # gpt-oss->Magistral matched-swap CPP effect
144
+ python analyses/engagement_ceiling.py # how well text predicts per-post engagement (ceiling)
145
+ python analyses/cv_and_length.py # held-out CV R^2 + length-controlled attractor (Appendix D)
146
+ python analyses/absolute_variance.py # variance components, all regimes
147
+ python analyses/temporal_dynamics.py # temporal H decay by quartile
148
+ python analyses/tetradic_recompute_H.py # four-way per-model H over the 24 runs
149
+ python analyses/tetradic_results.py # four-way H matrix + heatmap figure
150
+ python analyses/plot_matrices.py # H-matrix heatmaps (dyadic/triadic)
151
+ ```
152
+
153
+ Content (Finding 3):
154
+ ```bash
155
+ python analyses/lexical_table.py # model/persona classifier from TF-IDF (Table 1)
156
+ python analyses/persona_faithfulness.py # persona recoverability from text (faithfulness)
157
+ python analyses/distinctive_words.py # characteristic phrases per model (log-odds)
158
+ python analyses/svd_axes.py # SVD style axes + top terms
159
+ python analyses/content_engagement.py # content -> CPP decomposition (length/style/model/persona)
160
+ python analyses/style_geometry.py # model style directions, stability, engagement-direction cosines
161
+ python analyses/cluster_model_persona.py # does style cluster by model vs persona (permutation-adjusted)
162
+ python analyses/length_regimes.py # length/volume confound checks by regime
163
+ ```
164
+
165
+ ### 7. Smoke test (no GPUs required for the assertion; short GPU run for the full test)
166
+
167
+ ```bash
168
+ # Assert-only (uses an existing DB):
169
+ python smoke_test/assert_h_matrix.py --db <path/to/sweep_*.db>
170
+
171
+ # Full end-to-end smoke (requires 2 live vLLM servers, ~5 min on 2 GPUs):
172
+ bash smoke_test/run_smoke.sh
173
+ ```
174
+
175
+ ---
176
+
177
+ ## Expected runtime
178
+
179
+ | Experiment | Steps | Agents | Time estimate (8× L40S) |
180
+ |-----------|-------|--------|------------------------|
181
+ | Single dyadic run | 100 | 20 | ~25–45 min |
182
+ | Full dyadic sweep (10 pairs × 2 orderings × 5 seeds) | 100 | 20 | ~50–150 GPU-hours |
183
+ | Single triadic run | 100 | 30 | ~35–60 min |
184
+ | Full triadic sweep (10 triplets × 3 orderings × 3 seeds) | 100 | 30 | ~35–90 GPU-hours |
185
+ | Single four-way run | 100 | 40 | ~60–90 min |
186
+ | Full four-way sweep (2 seeds × 12 rotations) | 100 | 40 | ~50–70 GPU-hours |
187
+
188
+ ---
189
+
190
+ ## Data
191
+
192
+ Reference data (SQLite databases, one per run) are listed in `data/MANIFEST.md`
193
+ with SHA-256 checksums and sizes. The canonical data lives at:
194
+
195
+ ```
196
+ /data/user_data/droytbur/oasis/runs/sweep_*.db
197
+ ```
198
+
199
+ The manifest records all valid runs used in the paper (dyadic, triadic, and four-way),
200
+ including the four-way DBs under `$RUNS_DIR/tetradic/`. The content analyses additionally
201
+ use a text corpus (`data/texts.jsonl`) regenerated by `analyses/extract_texts.py`.
202
+
203
+ ---
204
+
205
+ ## Repository layout
206
+
207
+ ```
208
+ divsim_publish/
209
+ ├── README.md # this file
210
+ ├── LICENSE # MIT
211
+ ├── env/
212
+ │ ├── requirements.txt # pinned Python dependencies
213
+ │ └── vllm_version.md # vLLM 0.19.0 per-model launch notes
214
+ ├── oasis/
215
+ │ ├── run_v9.py # simulation runner
216
+ │ ├── seed_db/hf-zero-50.sqlite
217
+ │ └── tool_chat_template_gemma4.jinja
218
+ ├── launch/
219
+ │ ├── vllm_qwen.sh / vllm_gpt_oss.sh / vllm_magistral.sh / vllm_glm4.sh / vllm_gemma.sh
220
+ │ └── run_tetradic.sh # four-way sweep driver (serves 4 models, 2 seeds x 12 rotations)
221
+ ├── sweep/
222
+ │ ├── sweep_dyadic.py # combinatorial 2-model sweep (5-model subset)
223
+ │ └── sweep_triadic.py # preemption-safe 3-model sweep
224
+ ├── analyses/
225
+ │ ├── variance_cpp.py # CPP variance decomposition + leave-one-model-out
226
+ │ ├── absolute_variance.py # variance components across regimes
227
+ │ ├── plot_fig_variance_overview.py# Fig: CPP variance + per-model H by mixture size
228
+ │ ├── temporal_dynamics.py # temporal H decay analysis
229
+ │ ├── tetradic_recompute_H.py / tetradic_results.py # four-way H + heatmap
230
+ │ ├── plot_matrices.py / plot_fig1_network.py / housestyle.py # figures
231
+ │ ├── extract_texts.py # build data/texts.jsonl corpus
232
+ │ ├── lexical_table.py # model/persona classifier (Table 1)
233
+ │ ├── svd_axes.py # SVD style axes + top terms
234
+ │ ├── content_engagement.py # content -> CPP decomposition
235
+ │ ├── style_geometry.py # style directions + engagement-direction cosines
236
+ │ └── cluster_model_persona.py / length_regimes.py # supporting checks
237
+ ├── data/
238
+ │ └── MANIFEST.md # DB paths, SHA-256, size, (pair/triplet, seed) labels
239
+ ├── smoke_test/
240
+ │ ├── run_smoke.sh # short dyad smoke run (20 steps, 2 agents/family)
241
+ │ └── assert_h_matrix.py # assert H matrix computable + basic sanity checks
242
+ └── docs/
243
+ └── EXPERIMENT_PROTOCOL.md # canonical reproducibility narrative
244
+ ```
analyses/absolute_variance.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exact absolute-variance decomposition of per-agent in-degree, by regime
2
+ (two-way / three-way from the 5-model pool; four-way from the tetradic pool).
3
+ Absolute component = single-block in-sample R^2 x total in-degree variance.
4
+ Keeps everything consistent with tab:ols_decomp and Fig variance_overview(a).
5
+ """
6
+ import sqlite3, json
7
+ from collections import defaultdict
8
+ from pathlib import Path
9
+ import numpy as np
10
+ RUNS=Path("runs")
11
+ TET=RUNS/"tetratic"
12
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
13
+
14
+ def rows_from(dbiter, tet=False):
15
+ rows=[]
16
+ for db in dbiter:
17
+ if not tet and any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
18
+ if tet and (TET/f"{db.stem}_checkpoint.json").exists():continue
19
+ mp=str(db).replace(".db",".metadata.json")
20
+ if not Path(mp).exists():continue
21
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
22
+ except:continue
23
+ if not amm:continue
24
+ # OFF-BY-ONE FIX: DBs are 0-indexed (user_id and agent_model_map keys both start at MIN);
25
+ # original "+1" dropped agent 0 and mislabeled the first agent of each model-block.
26
+ # fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
27
+ umin=min(int(k) for k in amm)
28
+ fam={int(k)+umin:SHORT.get(v["model"]) for k,v in amm.items()}
29
+ if any(v is None for v in fam.values()):continue
30
+ try:
31
+ c=sqlite3.connect(db);posts=c.execute("SELECT post_id,user_id FROM post").fetchall();coms=c.execute("SELECT post_id,user_id FROM comment").fetchall();users=dict(c.execute("SELECT user_id,user_name FROM user").fetchall());c.close()
32
+ except:continue
33
+ if len(coms)<(100 if tet else 200):continue
34
+ owner={p:u for p,u in posts};ind=defaultdict(int)
35
+ for p,cu in coms:
36
+ o=owner.get(p)
37
+ if o in fam and o!=cu:ind[o]+=1
38
+ net=tuple(sorted(set(fam.values())))
39
+ mode="tet" if tet else ("tri" if len(net)==3 else "dyad" if len(net)==2 else "other")
40
+ for u,f in fam.items():
41
+ rows.append({"run":db.stem,"model":f,"persona":users.get(u,f"u{u}"),"indeg":ind.get(u,0),"mode":mode,"net":net})
42
+ return rows
43
+
44
+ def dummies(keys):
45
+ lv=sorted(set(keys),key=lambda x:str(x));idx={l:i for i,l in enumerate(lv)}
46
+ D=np.zeros((len(keys),len(lv)))
47
+ for r,k in enumerate(keys):D[r,idx[k]]=1
48
+ return D[:,1:]
49
+ def r2(y,*blocks):
50
+ blocks=[b for b in blocks if b is not None and b.shape[1]>0]
51
+ X=np.column_stack([np.ones(len(y))]+blocks) if blocks else np.ones((len(y),1))
52
+ b,*_=np.linalg.lstsq(X,y,rcond=None);pred=X@b
53
+ return 1-((y-pred)**2).sum()/((y-y.mean())**2).sum()
54
+ def partner(r): return frozenset(m for m in r["net"] if m!=r["model"])
55
+
56
+ allrows=rows_from(sorted(RUNS.glob("sweep_*.db")))+rows_from(sorted(TET.glob("tetra_s*_r*.db")),tet=True)
57
+ out=["# Absolute variance decomposition (per-agent in-degree)\n",
58
+ "| component | Two-way | Three-way | Four-way |","|---|---:|---:|---:|"]
59
+ comp={}
60
+ for mode in ["dyad","tri","tet"]:
61
+ rs=[r for r in allrows if r["mode"]==mode]
62
+ y=np.array([r["indeg"] for r in rs],float);tot=y.var()
63
+ P=dummies([r["persona"] for r in rs]);Mo=dummies([r["model"] for r in rs])
64
+ Sel=np.column_stack([Mo,dummies([partner(r) for r in rs])]) if dummies([partner(r) for r in rs]).shape[1]>0 else Mo
65
+ oss=np.array([[1.0 if r["model"]=="gpt-oss" else 0.0] for r in rs]);Run=dummies([r["run"] for r in rs])
66
+ comp[mode]={"n":len(rs),"total":tot,"persona":r2(y,P)*tot,"own":r2(y,Mo)*tot,
67
+ "selection":r2(y,Sel)*tot,"oss":r2(y,oss)*tot,"run":r2(y,Run)*tot,
68
+ "persona_r2":r2(y,P),"sel_r2":r2(y,Sel),"own_r2":r2(y,Mo),"oss_r2":r2(y,oss),"run_r2":r2(y,Run)}
69
+ def row(label,key):
70
+ return f"| {label} | "+" | ".join(f"{comp[m][key]:.0f}" for m in ["dyad","tri","tet"])+" |"
71
+ out+=[row("Total variance","total"),"|---|---|---|---|",
72
+ row("Persona","persona"),row("Model selection (own+partner)","selection"),
73
+ row("\\quad own model","own"),row("\\quad gpt-oss indicator","oss"),row("Run (baseline)","run")]
74
+ out+=["\n## underlying R^2 (for tab:ols_decomp consistency)\n",
75
+ "| block | Two-way | Three-way | Four-way |","|---|---:|---:|---:|"]
76
+ for lab,key in [("persona","persona_r2"),("model selection","sel_r2"),("own model","own_r2"),("gpt-oss ind","oss_r2"),("run","run_r2")]:
77
+ out.append(f"| {lab} | "+" | ".join(f"{comp[m][key]:.3f}" for m in ['dyad','tri','tet'])+" |")
78
+ out.append(f"\nn agents: dyad {comp['dyad']['n']}, tri {comp['tri']['n']}, tet {comp['tet']['n']}")
79
+ print("\n".join(out))
80
+ Path("out/absolute_variance.md").write_text("\n".join(out)+"\n")
analyses/cluster_model_persona.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Does agent style cluster more by model or by persona? Fair test via permutation-
2
+ adjusted variance-explained (controls for differing group counts: 5 models vs 43 personas).
3
+ Style space = SVD(30), axis 1 (language) dropped."""
4
+ import sqlite3, json
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ import numpy as np
8
+ from sklearn.feature_extraction.text import TfidfVectorizer
9
+ from sklearn.decomposition import TruncatedSVD
10
+ RUNS=Path("runs")
11
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
12
+ ag=[]
13
+ for db in sorted(RUNS.glob("sweep_*.db")):
14
+ if any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
15
+ mp=str(db).replace(".db",".metadata.json")
16
+ if not Path(mp).exists():continue
17
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
18
+ except:continue
19
+ if not amm:continue
20
+ fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
21
+ if any(v is None for v in fam.values()):continue
22
+ try:
23
+ c=sqlite3.connect(db);posts=c.execute("SELECT user_id,content FROM post").fetchall();users=dict(c.execute("SELECT user_id,user_name FROM user").fetchall());coms=c.execute("SELECT 1 FROM comment").fetchall();c.close()
24
+ except:continue
25
+ if len(coms)<200:continue
26
+ txt=defaultdict(list)
27
+ for u,cont in posts:
28
+ if u in fam and cont:txt[u].append(cont)
29
+ for u,tl in txt.items():
30
+ if tl:ag.append({"model":fam[u],"persona":users.get(u,f"u{u}"),"text":" ".join(tl)})
31
+ n=len(ag);print(n,"agents")
32
+ vc=TfidfVectorizer(ngram_range=(1,2),analyzer="word",min_df=10,max_features=20000,sublinear_tf=True,norm="l2",stop_words="english",token_pattern=r"[A-Za-z'][A-Za-z']+")
33
+ X=vc.fit_transform([a["text"]for a in ag])
34
+ S=TruncatedSVD(30,random_state=0).fit_transform(X)
35
+ Z=((S-S.mean(0))/(S.std(0)+1e-9))[:,1:]
36
+ model=np.array([a["model"]for a in ag]);persona=np.array([a["persona"]for a in ag])
37
+ tot=((Z-Z.mean(0))**2).sum()
38
+ def eta2(lab):
39
+ w=0.0
40
+ for g in set(lab):
41
+ Zi=Z[lab==g];w+=((Zi-Zi.mean(0))**2).sum()
42
+ return 1-w/tot
43
+ rng=np.random.default_rng(0)
44
+ def null(lab,B=200):
45
+ lab=lab.copy();vals=[]
46
+ for _ in range(B):
47
+ rng.shuffle(lab);vals.append(eta2(lab))
48
+ return np.mean(vals)
49
+ em,ep=eta2(model),eta2(persona)
50
+ nm,np_=null(model),null(persona)
51
+ print(f"{'group':8s} {'#groups':>7} {'eta2':>7} {'null':>7} {'excess':>7}")
52
+ print(f"{'model':8s} {len(set(model)):7d} {em:7.3f} {nm:7.3f} {em-nm:7.3f}")
53
+ print(f"{'persona':8s} {len(set(persona)):7d} {ep:7.3f} {np_:7.3f} {ep-np_:7.3f}")
54
+ print(f"\nratio of excess (model/persona): {(em-nm)/(ep-np_):.2f}")
55
+ # also: within-group mean pairwise cosine (tightness), cheap proxy, fair-ish
56
+ def tight(lab):
57
+ cs=[]
58
+ for g in set(lab):
59
+ Zi=Z[lab==g]
60
+ if len(Zi)<3:continue
61
+ c=Zi.mean(0);cs.append(np.mean([float(zi@c/((np.linalg.norm(zi)*np.linalg.norm(c))+1e-9)) for zi in Zi]))
62
+ return np.mean(cs)
63
+ print(f"\nmean within-group cosine-to-centroid: model={tight(model):.3f} persona={tight(persona):.3f} (higher=tighter)")
analyses/content_engagement.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Content->engagement, FINAL: blocks = length, style (SVD axes 2-30, axis1=language dropped),
2
+ model, persona. No format block. Within-run z-scored in-degree; CV R^2 + leave-one-block-out unique."""
3
+ import sqlite3, json
4
+ from collections import defaultdict
5
+ from pathlib import Path
6
+ import numpy as np
7
+ from sklearn.feature_extraction.text import TfidfVectorizer
8
+ from sklearn.decomposition import TruncatedSVD
9
+ from sklearn.model_selection import KFold
10
+ RUNS=Path("runs")
11
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
12
+ ag=[]
13
+ for db in sorted(RUNS.glob("sweep_*.db")):
14
+ if any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
15
+ mp=str(db).replace(".db",".metadata.json")
16
+ if not Path(mp).exists():continue
17
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
18
+ except:continue
19
+ if not amm:continue
20
+ fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
21
+ if any(v is None for v in fam.values()):continue
22
+ try:
23
+ c=sqlite3.connect(db);posts=c.execute("SELECT post_id,user_id,content FROM post").fetchall();coms=c.execute("SELECT post_id,user_id FROM comment").fetchall();users=dict(c.execute("SELECT user_id,user_name FROM user").fetchall());c.close()
24
+ except:continue
25
+ if len(coms)<200:continue
26
+ owner={p:u for p,u,_ in posts};ind=defaultdict(int)
27
+ for p,cu in coms:
28
+ o=owner.get(p)
29
+ if o in fam and o!=cu:ind[o]+=1
30
+ txt=defaultdict(list)
31
+ for p,u,cont in posts:
32
+ if u in fam and cont:txt[u].append(cont)
33
+ for u,tl in txt.items():
34
+ if tl:ag.append({"run":db.stem,"model":fam[u],"persona":users.get(u,f"u{u}"),"indeg":ind.get(u,0),"nw":sum(len(t.split())for t in tl),"text":" ".join(tl)})
35
+ n=len(ag)
36
+ vc=TfidfVectorizer(ngram_range=(1,2),analyzer="word",min_df=10,max_features=20000,sublinear_tf=True,norm="l2",stop_words="english",token_pattern=r"[A-Za-z'][A-Za-z']+")
37
+ X=vc.fit_transform([a["text"]for a in ag])
38
+ S=TruncatedSVD(30,random_state=0).fit_transform(X)
39
+ Sz=((S-S.mean(0))/(S.std(0)+1e-9))[:,1:] # axes 2-30
40
+ model=np.array([a["model"]for a in ag]);persona=np.array([a["persona"]for a in ag])
41
+ logw=np.array([np.log1p(a["nw"])for a in ag]);L=((logw-logw.mean())/logw.std()).reshape(-1,1)
42
+ M=np.array([[1.0 if a["model"]==m else 0 for m in sorted(set(model))[1:]]for a in ag])
43
+ P=np.array([[1.0 if a["persona"]==p else 0 for p in sorted(set(persona))[1:]]for a in ag])
44
+ y=np.zeros(n);bd=defaultdict(list)
45
+ for i,a in enumerate(ag):bd[a["run"]].append(i)
46
+ for r,idx in bd.items():
47
+ v=np.array([ag[i]["indeg"]for i in idx],float);z=(v-v.mean())/(v.std()+1e-9)
48
+ for k,i in enumerate(idx):y[i]=z[k]
49
+ def cvr2(*B):
50
+ B=[b for b in B if b is not None and b.shape[1]>0]
51
+ if not B:return 0.0
52
+ Xx=np.hstack(B);kf=KFold(5,shuffle=True,random_state=0);sse=sst=0
53
+ for tr,te in kf.split(Xx):
54
+ A=np.column_stack([np.ones(len(tr)),Xx[tr]]);Bt=np.column_stack([np.ones(len(te)),Xx[te]])
55
+ b,*_=np.linalg.lstsq(A,y[tr],rcond=None);pp=Bt@b;sse+=((y[te]-pp)**2).sum();sst+=((y[te]-y[tr].mean())**2).sum()
56
+ return 1-sse/sst
57
+ blk={"length":L,"style":Sz,"model":M,"persona":P}
58
+ single={k:cvr2(v)for k,v in blk.items()};allr=cvr2(*blk.values())
59
+ uniq={k:allr-cvr2(*[v for kk,v in blk.items() if kk!=k])for k in blk}
60
+ print(f"{n} agents, style = SVD axes 2-30")
61
+ print(f"{'block':8s} {'single':>7} {'unique':>7}")
62
+ for k in ["length","style","model","persona"]:print(f"{k:8s} {single[k]:7.3f} {uniq[k]:7.3f}")
63
+ print(f"{'all4':8s} {'':>7} {allr:7.3f}")
analyses/cv_and_length.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """(A) Held-out 5-fold CV R^2 for persona-only / model-only / full (addresses the
2
+ 43-vs-5 parameter-count confound in in-sample R^2). (B) Per-model engagement effect
3
+ (within-run-z CPP) raw vs. after controlling for post length -> attractor/repeller survive."""
4
+ import sqlite3, json
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ import numpy as np
8
+ import pandas as pd
9
+ from sklearn.linear_model import LinearRegression
10
+ from sklearn.model_selection import KFold
11
+ from sklearn.metrics import r2_score
12
+ RUNS=Path("runs");TET=RUNS/"tetratic"
13
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
14
+ def load(globpat,tet=False):
15
+ rows=[]
16
+ for db in sorted(globpat):
17
+ if not tet and any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
18
+ if tet and (TET/f"{db.stem}_checkpoint.json").exists():continue
19
+ mp=str(db).replace(".db",".metadata.json")
20
+ if not Path(mp).exists():continue
21
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
22
+ except:continue
23
+ if not amm:continue
24
+ # OFF-BY-ONE FIX: DBs are 0-indexed (user_id and agent_model_map keys both start at MIN);
25
+ # original "+1" dropped agent 0 and mislabeled the first agent of each model-block.
26
+ # fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
27
+ umin=min(int(k) for k in amm)
28
+ fam={int(k)+umin:SHORT.get(v["model"]) for k,v in amm.items()}
29
+ if any(v is None for v in fam.values()):continue
30
+ try:
31
+ c=sqlite3.connect(db);posts=c.execute("SELECT post_id,user_id,content FROM post").fetchall()
32
+ coms=c.execute("SELECT post_id,user_id FROM comment").fetchall();users=dict(c.execute("SELECT user_id,user_name FROM user").fetchall());c.close()
33
+ except:continue
34
+ if len(coms)<(100 if tet else 200):continue
35
+ owner={p:u for p,u,_ in posts};ind=defaultdict(int);npost=defaultdict(int);loglen=defaultdict(list)
36
+ for p,cu in coms:
37
+ o=owner.get(p)
38
+ if o in fam and o!=cu:ind[o]+=1
39
+ for p,u,cont in posts:
40
+ if u in fam:npost[u]+=1;loglen[u].append(np.log(max(1,len(cont or ""))))
41
+ reg={2:"dyad",3:"triad",4:"tetrad"}[len(set(fam.values()))]
42
+ for u in fam:
43
+ if npost[u]>=2:
44
+ rows.append({"run":db.stem,"reg":reg,"model":fam[u],"persona":users.get(u,f"u{u}"),
45
+ "cpp":ind[u]/npost[u],"loglen":np.mean(loglen[u])})
46
+ return rows
47
+ rows=load(RUNS.glob("sweep_*.db"))+load(TET.glob("tetra_s*_r*.db"),tet=True)
48
+ df=pd.DataFrame(rows)
49
+ # within-run z CPP and z loglen
50
+ df["z"]=df.groupby("run")["cpp"].transform(lambda v:(v-v.mean())/(v.std() or 1))
51
+ df["zlen"]=df.groupby("run")["loglen"].transform(lambda v:(v-v.mean())/(v.std() or 1))
52
+ def cvr2(sub,cols):
53
+ y=sub["z"].values;X=pd.get_dummies(sub[cols],columns=cols,drop_first=False).astype(float).values
54
+ kf=KFold(5,shuffle=True,random_state=0);sc=[]
55
+ for tr,te in kf.split(X):
56
+ m=LinearRegression().fit(X[tr],y[tr]);sc.append(r2_score(y[te],m.predict(X[te])))
57
+ return np.mean(sc)
58
+ print("=== (A) HELD-OUT 5-fold CV R^2 (within-run z CPP) ===")
59
+ print(f"{'regime':10s}{'persona':>10}{'model':>9}{'full(p+m)':>11} (#personas / #models)")
60
+ for reg in ["dyad","triad","tetrad"]:
61
+ s=df[df.reg==reg]
62
+ pe=cvr2(s,["persona"]);mo=cvr2(s,["model"]);fu=cvr2(s,["persona","model"])
63
+ print(f"{reg:10s}{pe:>10.3f}{mo:>9.3f}{fu:>11.3f} ({s.persona.nunique()} / {s.model.nunique()}), n={len(s)}")
64
+ print("\n=== (B) per-model engagement (z CPP) RAW vs LENGTH-CONTROLLED ===")
65
+ for reg in ["dyad","triad","tetrad"]:
66
+ s=df[df.reg==reg].copy()
67
+ # length-adjusted z: residual of z on zlen
68
+ b=np.polyfit(s["zlen"],s["z"],1);s["zadj"]=s["z"]-(b[0]*s["zlen"]+b[1])
69
+ print(f"-- {reg} (length slope b={b[0]:+.2f}) --")
70
+ for m in ["gpt-oss","Mag","GLM-4","Qwen","Gemma"]:
71
+ sm=s[s.model==m]
72
+ if len(sm)<5:continue
73
+ print(f" {m:8s} raw z={sm['z'].mean():+.2f} length-adj z={sm['zadj'].mean():+.2f} (n={len(sm)}, mean loglen z={sm['zlen'].mean():+.2f})")
analyses/distinctive_words.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distinctive per-model vocabulary via several methods, so we can pick the best surface.
2
+ (1) log-odds-ratio w/ informative Dirichlet prior (Monroe 2008), word 1-2grams, stopwords removed
3
+ (2) same, bigrams only (phrases)
4
+ (3) classifier coefficient top terms"""
5
+ import json
6
+ from collections import Counter
7
+ import numpy as np
8
+ from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
9
+ from sklearn.linear_model import LogisticRegression
10
+ rows=[json.loads(l) for l in open("data/texts.jsonl")]
11
+ rows=[r for r in rows if len(r.get("text","") or "")>=1 and r.get("model") in {"gpt-oss","Qwen","GLM-4","Mag","Gemma"}]
12
+ MODELS=["gpt-oss","Qwen","GLM-4","Mag","Gemma"]
13
+ NAME={"gpt-oss":"gpt-oss","Qwen":"Qwen","GLM-4":"GLM-4","Mag":"Magistral","Gemma":"Gemma"}
14
+ texts=[r["text"] for r in rows];model=np.array([r["model"] for r in rows])
15
+ def logodds(ngram):
16
+ cv=CountVectorizer(ngram_range=ngram,min_df=30,max_features=50000,stop_words="english",token_pattern=r"[A-Za-z'][A-Za-z']+")
17
+ X=cv.fit_transform(texts);vocab=np.array(cv.get_feature_names_out())
18
+ tot=np.asarray(X.sum(0)).ravel();a0=tot.sum();alpha=tot.astype(float);N=tot.sum()
19
+ out={}
20
+ for m in MODELS:
21
+ yi=np.asarray(X[model==m].sum(0)).ravel().astype(float)
22
+ yr=tot-yi
23
+ ni=yi.sum();nr=yr.sum()
24
+ d=np.log((yi+alpha)/(ni+a0-yi-alpha))-np.log((yr+alpha)/(nr+a0-yr-alpha))
25
+ var=1.0/(yi+alpha)+1.0/(yr+alpha)
26
+ z=d/np.sqrt(var)
27
+ out[m]=vocab[np.argsort(z)[::-1][:12]]
28
+ return out
29
+ lo1=logodds((1,2));lo2=logodds((2,2))
30
+ print("=== (1) log-odds (word 1-2grams) ===")
31
+ for m in MODELS:print(f" {NAME[m]:10s}: {', '.join(lo1[m])}")
32
+ print("\n=== (2) log-odds (bigrams / phrases) ===")
33
+ for m in MODELS:print(f" {NAME[m]:10s}: {', '.join(lo2[m])}")
analyses/engagement_ceiling.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Is the low text->engagement R^2 a ceiling or an artifact of SVD/linearization?
2
+ Predict per-agent within-run-z CPP from: full TF-IDF (Ridge), SVD-30/100/500 (Ridge),
3
+ and a nonlinear model (HistGBT on SVD-100). 5-model pool, posts-only agent text."""
4
+ import sqlite3, json
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ import numpy as np
8
+ from sklearn.feature_extraction.text import TfidfVectorizer
9
+ from sklearn.decomposition import TruncatedSVD
10
+ from sklearn.linear_model import Ridge
11
+ from sklearn.ensemble import HistGradientBoostingRegressor
12
+ from sklearn.model_selection import KFold
13
+ RUNS=Path("runs")
14
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
15
+ ag=[]
16
+ for db in sorted(RUNS.glob("sweep_*.db")):
17
+ if any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
18
+ mp=str(db).replace(".db",".metadata.json")
19
+ if not Path(mp).exists():continue
20
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
21
+ except:continue
22
+ if not amm:continue
23
+ fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
24
+ if any(v is None for v in fam.values()):continue
25
+ try:
26
+ c=sqlite3.connect(db);posts=c.execute("SELECT post_id,user_id,content FROM post").fetchall();coms=c.execute("SELECT post_id,user_id FROM comment").fetchall();c.close()
27
+ except:continue
28
+ if len(coms)<200:continue
29
+ owner={p:u for p,u,_ in posts};ind=defaultdict(int);npost=defaultdict(int);txt=defaultdict(list)
30
+ for p,cu in coms:
31
+ o=owner.get(p)
32
+ if o in fam and o!=cu:ind[o]+=1
33
+ for p,u,cont in posts:
34
+ if u in fam and cont:npost[u]+=1;txt[u].append(cont)
35
+ for u in fam:
36
+ if npost[u]>=2:ag.append({"run":db.stem,"cpp":ind[u]/npost[u],"text":" ".join(txt[u])})
37
+ n=len(ag);print(n,"agents")
38
+ runs=np.array([a["run"]for a in ag])
39
+ y=np.zeros(n);bd=defaultdict(list)
40
+ for i,a in enumerate(ag):bd[a["run"]].append(i)
41
+ for r,idx in bd.items():
42
+ v=np.array([ag[i]["cpp"]for i in idx],float);m=v.mean();sd=v.std() or 1
43
+ for j,i in enumerate(idx):y[i]=(v[j]-m)/sd
44
+ vc=TfidfVectorizer(ngram_range=(1,2),analyzer="word",min_df=10,max_features=40000,sublinear_tf=True,norm="l2",stop_words="english",token_pattern=r"[A-Za-z'][A-Za-z']+")
45
+ X=vc.fit_transform([a["text"]for a in ag]);print("TF-IDF dims:",X.shape[1])
46
+ def cvr2(Xf,est_fn):
47
+ kf=KFold(5,shuffle=True,random_state=0);sse=sst=0
48
+ for tr,te in kf.split(Xf if not hasattr(Xf,'tocsr') else np.arange(n)):
49
+ e=est_fn();e.fit(Xf[tr],y[tr]);pp=e.predict(Xf[te])
50
+ sse+=((y[te]-pp)**2).sum();sst+=((y[te]-y[tr].mean())**2).sum()
51
+ return 1-sse/sst
52
+ # full TF-IDF Ridge (a few alphas)
53
+ print(f"full TF-IDF Ridge(alpha=5): R2={cvr2(X,lambda:Ridge(alpha=5.0)):.3f}",flush=True)
54
+ for K in [30,100]:
55
+ S=TruncatedSVD(K,random_state=0).fit_transform(X)
56
+ print(f"SVD-{K} Ridge: R2={cvr2(S,lambda:Ridge(alpha=1.0)):.3f}",flush=True)
57
+ # nonlinear on SVD-100
58
+ S100=TruncatedSVD(100,random_state=0).fit_transform(X)
59
+ print(f"SVD-100 HistGBT (nonlinear): R2={cvr2(S100,lambda:HistGradientBoostingRegressor(max_iter=300,learning_rate=0.05)):.3f}")
analyses/extract_texts.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Extract all post + comment text from every valid sweep DB and tag each row
3
+ with (model, persona, run, mode, kind). Writes a single JSONL.
4
+
5
+ Validity criterion matches persona_variance: nc>=200 & nu>=26 (for tri) or
6
+ nu>=18 (dyad), and metadata + good model map.
7
+ """
8
+ import json
9
+ import sqlite3
10
+ import sys
11
+ from collections import defaultdict
12
+ from pathlib import Path
13
+
14
+ RUNS = Path("runs")
15
+ OUT = Path("data/texts.jsonl")
16
+
17
+ SHORT = {
18
+ "Qwen/Qwen3-32B": "Qwen",
19
+ "openai/gpt-oss-20b": "gpt-oss",
20
+ "mistralai/Magistral-Small-2509": "Mag",
21
+ "zai-org/GLM-4-32B-0414": "GLM-4",
22
+ "google/gemma-4-31B-it": "Gemma",
23
+ }
24
+
25
+
26
+ def load_valid_runs():
27
+ rows = []
28
+ n_db = n_valid = 0
29
+ for db in sorted(RUNS.glob("sweep_*.db")):
30
+ name = db.name
31
+ if any(x in name for x in ["archive", "snapshot", "olm", "hermes", "qwq", "glm47", "pilot_"]):
32
+ continue
33
+ meta_p = str(db).replace(".db", ".metadata.json")
34
+ if not Path(meta_p).exists():
35
+ continue
36
+ n_db += 1
37
+ try:
38
+ meta = json.load(open(meta_p))
39
+ except Exception:
40
+ continue
41
+ amm = meta.get("agent_model_map", {})
42
+ if not amm:
43
+ continue
44
+ uid_to_model = {int(k) + 1: SHORT.get(v["model"]) for k, v in amm.items()}
45
+ if any(v is None for v in uid_to_model.values()):
46
+ continue
47
+ mode = "tri" if "tri_" in name else "dyad"
48
+ threshold = 26 if mode == "tri" else 18
49
+ try:
50
+ c = sqlite3.connect(db)
51
+ nu = c.execute("SELECT COUNT(DISTINCT user_id) FROM comment").fetchone()[0]
52
+ nc = c.execute("SELECT COUNT(*) FROM comment").fetchone()[0]
53
+ if nu < threshold or nc < 200:
54
+ c.close()
55
+ continue
56
+ users = {uid: uname for uid, uname in c.execute("SELECT user_id, user_name FROM user").fetchall()}
57
+ posts = c.execute("SELECT post_id, user_id, content FROM post").fetchall()
58
+ comments = c.execute("SELECT comment_id, user_id, content FROM comment").fetchall()
59
+ c.close()
60
+ except Exception as e:
61
+ print(f"err {name}: {e}", file=sys.stderr)
62
+ continue
63
+ n_valid += 1
64
+ run_id = db.stem
65
+ for pid, uid, content in posts:
66
+ if not content:
67
+ continue
68
+ rows.append({
69
+ "run": run_id, "mode": mode, "kind": "post",
70
+ "model": uid_to_model.get(uid), "persona": users.get(uid, f"u{uid}"),
71
+ "text": content,
72
+ })
73
+ for cid, uid, content in comments:
74
+ if not content:
75
+ continue
76
+ rows.append({
77
+ "run": run_id, "mode": mode, "kind": "comment",
78
+ "model": uid_to_model.get(uid), "persona": users.get(uid, f"u{uid}"),
79
+ "text": content,
80
+ })
81
+ return rows, n_db, n_valid
82
+
83
+
84
+ def main():
85
+ rows, n_db, n_valid = load_valid_runs()
86
+ OUT.parent.mkdir(parents=True, exist_ok=True)
87
+ with open(OUT, "w") as f:
88
+ for r in rows:
89
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
90
+ by_model = defaultdict(lambda: [0, 0])
91
+ by_kind = defaultdict(int)
92
+ for r in rows:
93
+ by_model[r["model"]][0 if r["kind"] == "post" else 1] += 1
94
+ by_kind[r["kind"]] += 1
95
+ print(f"DBs scanned: {n_db} valid: {n_valid} rows: {len(rows):,}")
96
+ print(f"by kind: {dict(by_kind)}")
97
+ print("by model (posts, comments):")
98
+ for m, (p, cm) in sorted(by_model.items()):
99
+ print(f" {m:10s} posts={p:6d} comments={cm:6d}")
100
+ print(f"wrote {OUT}")
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
analyses/housestyle.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared house style: Palatino (TeX Gyre Pagella) for titles/headers,
2
+ Ubuntu Mono for body text and numbers."""
3
+ from matplotlib import font_manager as fm
4
+
5
+ _PAGELLA = "/usr/share/texlive/texmf-dist/fonts/opentype/public/tex-gyre"
6
+ for _f in ["texgyrepagella-regular.otf", "texgyrepagella-bold.otf", "texgyrepagella-italic.otf"]:
7
+ try: fm.fontManager.addfont(f"{_PAGELLA}/{_f}")
8
+ except Exception: pass
9
+ from pathlib import Path
10
+ for ttf in (Path.home() / "fonts").rglob("*.ttf"):
11
+ try: fm.fontManager.addfont(str(ttf))
12
+ except Exception: pass
13
+
14
+ # family names once registered
15
+ SERIF = "TeX Gyre Pagella" # Palatino-style, for titles/headers
16
+ MONO = "Ubuntu Mono" # for body text + numbers
17
+
18
+ def serif(size, bold=False):
19
+ return fm.FontProperties(family=SERIF, size=size, weight="bold" if bold else "normal")
20
+ def mono(size, bold=False):
21
+ return fm.FontProperties(family=MONO, size=size, weight="bold" if bold else "normal")
22
+
23
+ # per-model palette (consistent across figures)
24
+ MODEL_COLOR = {
25
+ "gpt-oss": "#d62728", # red (attractor)
26
+ "Qwen": "#1f77b4", # blue
27
+ "Mag": "#9467bd", # purple (repeller)
28
+ "GLM-4": "#2ca02c", # green
29
+ "Gemma": "#ff7f0e", # orange
30
+ }
analyses/length_regimes.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """(A) disentangle 'length': total-words (volume) vs mean post length, as engagement predictors.
2
+ (B) per-regime (dyad/triad/tetrad) raw vs length-adjusted per-model attractiveness (within-run z in-degree)."""
3
+ import sqlite3, json
4
+ from collections import defaultdict
5
+ from pathlib import Path
6
+ import numpy as np
7
+ RUNS=Path("runs");TET=RUNS/"tetratic"
8
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
9
+ def load(globpat,tet=False):
10
+ out=[]
11
+ for db in sorted(globpat):
12
+ if not tet and any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
13
+ if tet and (TET/f"{db.stem}_checkpoint.json").exists():continue
14
+ mp=str(db).replace(".db",".metadata.json")
15
+ if not Path(mp).exists():continue
16
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
17
+ except:continue
18
+ if not amm:continue
19
+ fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
20
+ if any(v is None for v in fam.values()):continue
21
+ try:
22
+ c=sqlite3.connect(db);posts=c.execute("SELECT post_id,user_id,content FROM post").fetchall();coms=c.execute("SELECT post_id,user_id FROM comment").fetchall();c.close()
23
+ except:continue
24
+ if len(coms)<(100 if tet else 200):continue
25
+ owner={p:u for p,u,_ in posts};ind=defaultdict(int)
26
+ for p,cu in coms:
27
+ o=owner.get(p)
28
+ if o in fam and o!=cu:ind[o]+=1
29
+ nw=defaultdict(int);npost=defaultdict(int)
30
+ for p,u,cont in posts:
31
+ if u in fam and cont:nw[u]+=len(cont.split());npost[u]+=1
32
+ F=sorted(set(fam.values()));reg={2:"dyad",3:"triad",4:"tetrad"}.get(len(F))
33
+ for u in fam:
34
+ if npost[u]>0:out.append({"run":db.stem,"model":fam[u],"indeg":ind.get(u,0),"meanlen":nw[u]/npost[u],"totw":nw[u],"reg":reg})
35
+ return out
36
+ ag=load(RUNS.glob("sweep_*.db"))+load(TET.glob("tetra_s*_r*.db"),tet=True)
37
+ ag=[a for a in ag if a["reg"]]
38
+ def wz(x,run):
39
+ o=np.zeros(len(x));bd=defaultdict(list)
40
+ for i,r in enumerate(run):bd[r].append(i)
41
+ for r,idx in bd.items():
42
+ v=x[np.array(idx)];m=v.mean();sd=v.std() or 1
43
+ for j,i in enumerate(idx):o[i]=(v[j]-m)/sd
44
+ return o
45
+ run=np.array([a["run"]for a in ag]);model=np.array([a["model"]for a in ag]);reg=np.array([a["reg"]for a in ag])
46
+ y=wz(np.array([a["indeg"]for a in ag],float),run)
47
+ lmean=wz(np.log1p(np.array([a["meanlen"]for a in ag])),run)
48
+ ltot=wz(np.log1p(np.array([a["totw"]for a in ag])),run)
49
+ # (A) which 'length' predicts engagement
50
+ print("(A) within-run corr with engagement: mean-post-length r=%.3f total-words(volume) r=%.3f"%(np.corrcoef(lmean,y)[0,1],np.corrcoef(ltot,y)[0,1]))
51
+ # (B) per-regime raw vs length(mean)-adjusted attractiveness
52
+ print("\n(B) per-model attractiveness (within-run z in-degree): raw vs length-adjusted, by regime")
53
+ print(f"{'model':8s} "+" ".join(f"{r}:raw {r}:adj " for r in ["dyad","triad","tetrad"]))
54
+ rows={}
55
+ for r in ["dyad","triad","tetrad"]:
56
+ m_=reg==r;b=np.polyfit(lmean[m_],y[m_],1)[0];resid=y.copy();resid[m_]=y[m_]-b*lmean[m_]
57
+ rows[r]=(b,resid)
58
+ for mod in ["gpt-oss","Qwen","GLM-4","Mag","Gemma"]:
59
+ cells=[]
60
+ for r in ["dyad","triad","tetrad"]:
61
+ b,resid=rows[r];m_=(reg==r)&(model==mod)
62
+ if m_.sum()==0:cells.append(" -- -- ")
63
+ else:cells.append(f"{y[m_].mean():+5.2f} {resid[m_].mean():+5.2f}")
64
+ print(f"{mod:8s} "+" ".join(cells))
65
+ print("\nslopes (length->engagement) per regime:",{r:round(rows[r][0],2) for r in rows})
analyses/lexical_table.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lexical-features table for Finding 3 (part 1), persistent.
3
+ Rows = models. Columns:
4
+ - CV accuracy (per-model recall) with Wilson 95% CI
5
+ - leave-personas-out accuracy (per-model recall) with Wilson 95% CI
6
+ - top distinguishing lexical features by FIRING (weight x mean in-class TF-IDF activation)
7
+ Plus 1-2 qualitative example snippets per model.
8
+ Outputs markdown + a LaTeX table fragment.
9
+ """
10
+ import json, math, re
11
+ from collections import defaultdict
12
+ import numpy as np
13
+ from sklearn.feature_extraction.text import TfidfVectorizer
14
+ from sklearn.linear_model import LogisticRegression
15
+ from sklearn.model_selection import StratifiedKFold, GroupKFold
16
+ from pathlib import Path
17
+
18
+ DATA = Path("data/texts.jsonl")
19
+ OUTMD = Path("out/lexical_table.md")
20
+ OUTTEX = Path("./_paper/latex/tables/lexical_table.tex")
21
+ OUTTEX.parent.mkdir(parents=True, exist_ok=True)
22
+ MODELS = ["gpt-oss","Qwen","GLM-4","Mag","Gemma"]
23
+ NAME = {"gpt-oss":"gpt-oss-20b","Qwen":"Qwen3-32B","GLM-4":"GLM-4-32B","Mag":"Magistral-Small","Gemma":"Gemma-4-31B"}
24
+
25
+ rows = [json.loads(l) for l in open(DATA)]
26
+ rows = [r for r in rows if r["model"] in MODELS and len(r.get("text","") or "")>=10]
27
+ texts = [r["text"] for r in rows]
28
+ y = np.array([r["model"] for r in rows])
29
+ persona = np.array([r["persona"] for r in rows])
30
+ print(f"{len(rows)} texts")
31
+
32
+ # two vectorizers: combined (word+char) for the classifier; word-only for readable feature display
33
+ vec = TfidfVectorizer(ngram_range=(1,2), analyzer="word", min_df=10, max_features=40000,
34
+ sublinear_tf=True, stop_words="english", token_pattern=r"[A-Za-z'][A-Za-z']+")
35
+ vec_char = TfidfVectorizer(ngram_range=(3,5), analyzer="char_wb", min_df=20, max_features=40000, sublinear_tf=True)
36
+ Xw = vec.fit_transform(texts); Xc = vec_char.fit_transform(texts)
37
+ import scipy.sparse as sp
38
+ X = sp.hstack([Xw, Xc]).tocsr()
39
+ vocab_w = np.array(vec.get_feature_names_out())
40
+ nw = Xw.shape[1]
41
+
42
+ def wilson(k, n, z=1.96):
43
+ if n==0: return (float("nan"),float("nan"))
44
+ p=k/n; d=1+z*z/n
45
+ c=(p+z*z/(2*n))/d; h=z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/d
46
+ return (c-h, c+h)
47
+
48
+ def per_model_recall(preds, ytrue):
49
+ out={}
50
+ for m in MODELS:
51
+ idx = ytrue==m; n=int(idx.sum()); k=int((preds[idx]==m).sum())
52
+ lo,hi=wilson(k,n); out[m]=(k/n, lo, hi, n)
53
+ return out
54
+
55
+ # ---- CV (random 5-fold) ----
56
+ preds_cv = np.empty(len(y), dtype=object)
57
+ for tr,te in StratifiedKFold(5, shuffle=True, random_state=42).split(X,y):
58
+ clf=LogisticRegression(max_iter=400, C=2.0, n_jobs=-1)
59
+ clf.fit(X[tr],y[tr]); preds_cv[te]=clf.predict(X[te])
60
+ cv = per_model_recall(preds_cv, y)
61
+ print("CV done")
62
+
63
+ # ---- leave-personas-out (GroupKFold by persona) ----
64
+ preds_lpo = np.empty(len(y), dtype=object)
65
+ for tr,te in GroupKFold(5).split(X,y,groups=persona):
66
+ clf=LogisticRegression(max_iter=400, C=2.0, n_jobs=-1)
67
+ clf.fit(X[tr],y[tr]); preds_lpo[te]=clf.predict(X[te])
68
+ lpo = per_model_recall(preds_lpo, y)
69
+ print("LPO done")
70
+
71
+ # ---- firing features: fit on all, contribution = weight * mean in-class activation (word feats only) ----
72
+ clf_full = LogisticRegression(max_iter=600, C=2.0, n_jobs=-1).fit(X,y)
73
+ classes = list(clf_full.classes_)
74
+ top_feat = {}
75
+ for m in MODELS:
76
+ ci = classes.index(m)
77
+ w = clf_full.coef_[ci][:nw] # weights on word features
78
+ mask = (y==m)
79
+ mean_act = np.asarray(Xw[mask].mean(axis=0)).ravel() # mean TF-IDF activation in-class
80
+ contrib = w * mean_act # how hard each feature fires for this class
81
+ order = np.argsort(contrib)[::-1]
82
+ feats=[vocab_w[j] for j in order[:8]]
83
+ top_feat[m]=feats
84
+
85
+ # ---- qualitative example snippets: posts strongly containing the model's top features ----
86
+ examples={}
87
+ top_set={m:set(top_feat[m]) for m in MODELS}
88
+ for m in MODELS:
89
+ best=("",-1)
90
+ for r in rows:
91
+ if r["model"]!=m: continue
92
+ t=r["text"]; tl=" "+re.sub(r"[^a-z' ]"," ",t.lower())+" "
93
+ hits=sum(1 for f in top_set[m] if " "+f+" " in tl)
94
+ if 60<=len(t)<=240 and hits>best[1]: best=(t,hits)
95
+ examples[m]=best[0].replace("\n"," ").strip()
96
+
97
+ # ---- write markdown ----
98
+ md=["# Lexical features by model (model classifier)\n",
99
+ f"{len(rows):,} texts. Classifier: TF-IDF (word 1-2gram + char 3-5gram) -> multinomial logistic regression. "
100
+ "Per-model accuracy = recall (fraction of that model's texts correctly identified). "
101
+ "Wilson 95% CIs. Leave-personas-out = train/test on disjoint persona sets. "
102
+ "Top features ranked by FIRING (weight x mean in-class TF-IDF activation), word features only.\n",
103
+ "| model | CV acc [95% CI] | leave-personas-out acc [95% CI] | top firing features |",
104
+ "|---|---|---|---|"]
105
+ for m in MODELS:
106
+ a,lo,hi,n=cv[m]; a2,lo2,hi2,n2=lpo[m]
107
+ md.append(f"| {NAME[m]} | {a:.2f} [{lo:.2f}, {hi:.2f}] | {a2:.2f} [{lo2:.2f}, {hi2:.2f}] | {', '.join(top_feat[m][:6])} |")
108
+ md.append("\n## Example snippets (containing each model's top firing features)\n")
109
+ for m in MODELS:
110
+ md.append(f"- **{NAME[m]}**: \"{examples[m][:200]}\"")
111
+ OUTMD.write_text("\n".join(md)+"\n")
112
+
113
+ # ---- write LaTeX fragment ----
114
+ tex=["% auto-generated by lexical_table.py",
115
+ "\\begin{table}[t]\\centering\\small",
116
+ "\\begin{tabular}{lccl}",
117
+ "\\toprule",
118
+ "model & CV acc.\\ [95\\% CI] & leave-personas-out [95\\% CI] & top firing features \\\\",
119
+ "\\midrule"]
120
+ for m in MODELS:
121
+ a,lo,hi,n=cv[m]; a2,lo2,hi2,n2=lpo[m]
122
+ feats=", ".join(f"\\texttt{{{f}}}" for f in top_feat[m][:4])
123
+ tex.append(f"{NAME[m]} & {a:.2f} [{lo:.2f}, {hi:.2f}] & {a2:.2f} [{lo2:.2f}, {hi2:.2f}] & {feats} \\\\")
124
+ tex+=["\\bottomrule","\\end{tabular}",
125
+ "\\caption{Each model's text is identifiable from lexical features alone, and the signal is persona-invariant (leave-personas-out). Per-model accuracy is recall; top features are those that fire hardest for the model (weight $\\times$ mean in-class TF-IDF activation).}",
126
+ "\\label{tab:lexical}","\\end{table}"]
127
+ OUTTEX.write_text("\n".join(tex)+"\n")
128
+
129
+ print("\n".join(md[:10]))
130
+ for m in MODELS: print(m, "->", top_feat[m][:6])
131
+ print(f"\nwrote {OUTMD} and {OUTTEX}")
analyses/persona_faithfulness.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json,math
2
+ from collections import Counter
3
+ import numpy as np
4
+ from sklearn.feature_extraction.text import TfidfVectorizer
5
+ from sklearn.linear_model import LogisticRegression
6
+ from sklearn.model_selection import StratifiedKFold
7
+ from sklearn.metrics import accuracy_score
8
+ rows=[json.loads(l) for l in open("data/texts.jsonl")]
9
+ rows=[r for r in rows if len(r.get("text","") or "")>=1]
10
+ print(len(rows),"texts total")
11
+ pc=Counter(r["persona"] for r in rows);keep={p for p,c in pc.items() if c>=25}
12
+ sub=[r for r in rows if r["persona"] in keep]
13
+ print(len(sub),"texts;",len(keep),"personas (>=25)")
14
+ vec=TfidfVectorizer(ngram_range=(1,2),analyzer="word",max_features=60000,sublinear_tf=True,token_pattern=r"[A-Za-z'][A-Za-z']+")
15
+ vc=TfidfVectorizer(ngram_range=(3,5),analyzer="char_wb",max_features=60000,sublinear_tf=True)
16
+ import scipy.sparse as sp
17
+ Xw=vec.fit_transform([r["text"]for r in sub]);Xc=vc.fit_transform([r["text"]for r in sub]);X=sp.hstack([Xw,Xc]).tocsr()
18
+ y=np.array([r["persona"]for r in sub]);chance=1/len(keep)
19
+ pred=np.empty(len(y),dtype=object)
20
+ for tr,te in StratifiedKFold(5,shuffle=True,random_state=0).split(X,y):
21
+ c=LogisticRegression(max_iter=300,C=2.0);c.fit(X[tr],y[tr]);pred[te]=c.predict(X[te])
22
+ acc=accuracy_score(y,pred)
23
+ print(f"PERSONA recovery: {acc*100:.1f}% ({acc/chance:.0f}x chance {chance*100:.1f}%)")
24
+ SHORT={"gpt-oss":"gpt-oss","Qwen":"Qwen","GLM-4":"GLM-4","Mag":"Magistral","Gemma":"Gemma"}
25
+ for m in ["Gemma","Mag","gpt-oss","GLM-4","Qwen"]:
26
+ s=[r for r in sub if r["model"]==m];yy=np.array([r["persona"]for r in s])
27
+ pcm=Counter(yy);kk={p for p,c in pcm.items() if c>=15}
28
+ s=[r for r in s if r["persona"] in kk];yy=np.array([r["persona"]for r in s])
29
+ if len(set(yy))<3:continue
30
+ Xs=sp.hstack([vec.transform([r["text"]for r in s]),vc.transform([r["text"]for r in s])]).tocsr()
31
+ pr=np.empty(len(yy),dtype=object)
32
+ for tr,te in StratifiedKFold(3,shuffle=True,random_state=0).split(Xs,yy):
33
+ c=LogisticRegression(max_iter=300,C=2.0);c.fit(Xs[tr],yy[tr]);pr[te]=c.predict(Xs[te])
34
+ a=accuracy_score(yy,pr);ch=1/len(set(yy));print(f" {m}: {a*100:.1f}% {a/ch:.0f}x ({len(set(yy))} personas)")
analyses/plot_fig1_network.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Figure 1 (WORKING): the interaction network of one triadic run with a strong
3
+ attractor (gpt-oss) and a strong repeller (Magistral). Nodes = agents colored by
4
+ base model, sized by in-degree; directed edges = comment flow. Side panel: per-model
5
+ stats. Inset: a chat-window excerpt of the most-commented post.
6
+ Saves SVG (for redesign) + PNG (for the paper).
7
+ """
8
+ import sqlite3, json, sys
9
+ from collections import defaultdict
10
+ from pathlib import Path
11
+ import numpy as np
12
+ import matplotlib
13
+ matplotlib.use("Agg")
14
+ import matplotlib.pyplot as plt
15
+ from matplotlib.patches import FancyBboxPatch
16
+ import networkx as nx
17
+ sys.path.insert(0, str(Path(__file__).parent))
18
+ from housestyle import serif, mono, MODEL_COLOR
19
+
20
+ DB = "runs/sweep_tri_oss_mag_glm_s42.db"
21
+ OUT_SVG = Path(__file__).parent / "fig1_network.svg"
22
+ OUT_PNG = Path(__file__).parent / "fig1_network.png"
23
+ SHORT = {"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss",
24
+ "mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4",
25
+ "google/gemma-4-31B-it":"Gemma"}
26
+
27
+ meta = json.load(open(DB.replace(".db",".metadata.json")))
28
+ fam = {int(k)+1: SHORT.get(v["model"]) for k,v in meta["agent_model_map"].items()}
29
+ c = sqlite3.connect(DB)
30
+ posts = c.execute("SELECT post_id,user_id,content FROM post").fetchall()
31
+ coms = c.execute("SELECT post_id,user_id,content FROM comment").fetchall()
32
+ users = dict(c.execute("SELECT user_id,user_name FROM user").fetchall())
33
+ c.close()
34
+ owner = {p:u for p,u,_ in posts}
35
+
36
+ # edges (commenter -> author), weighted; in-degree
37
+ w = defaultdict(int); indeg = defaultdict(int); outdeg = defaultdict(int)
38
+ for pid,cu,_ in coms:
39
+ au = owner.get(pid)
40
+ if au and au != cu and cu in fam and au in fam:
41
+ w[(cu,au)] += 1; indeg[au]+=1; outdeg[cu]+=1
42
+
43
+ # most-commented post (restricted to agent-authored posts with a known model)
44
+ pc = defaultdict(int)
45
+ for pid,_,_ in coms: pc[pid]+=1
46
+ agent_posts = [p for p in pc if owner.get(p) in fam]
47
+ top_pid = max(agent_posts, key=pc.get)
48
+ top_author = owner.get(top_pid)
49
+ top_text = next((t for p,u,t in posts if p==top_pid), "")
50
+ top_n = pc[top_pid]
51
+
52
+ # per-model stats
53
+ fams = ["gpt-oss","Mag","GLM-4","Qwen","Gemma"]
54
+ fams = [f for f in fams if f in fam.values()]
55
+ nf = {f:sum(1 for v in fam.values() if v==f) for f in fams}
56
+ ntot = sum(nf.values()); tot = sum(w.values())
57
+ obs = defaultdict(int)
58
+ for (cu,au),ww in w.items(): obs[(fam[cu],fam[au])]+=ww
59
+ def Hin(Y):
60
+ hs=[]
61
+ for X in fams:
62
+ if X==Y: continue
63
+ o=obs.get((X,Y),0)/tot; e=(nf[X]/ntot)*((nf[Y])/(ntot-1))
64
+ if e>0: hs.append(o/e-1)
65
+ return np.mean(hs) if hs else float("nan")
66
+ stats = {f: (np.mean([indeg[u] for u in fam if fam[u]==f]), Hin(f)) for f in fams}
67
+
68
+ # ---- build graph ----
69
+ import math
70
+ # model-grouped layout: each model's agents cluster at a polygon vertex, so
71
+ # cross-model comment flow (and convergence on the attractor) is legible.
72
+ order_for_anchor = [f for f in ["gpt-oss","Mag","GLM-4","Qwen","Gemma"] if f in set(fam.values())]
73
+ anchors = {}
74
+ for i,f in enumerate(order_for_anchor):
75
+ ang = 2*math.pi*i/len(order_for_anchor) + math.pi/2
76
+ anchors[f] = (1.25*math.cos(ang), 1.25*math.sin(ang))
77
+ rng = np.random.default_rng(3)
78
+ pos = {u: (anchors[fam[u]][0] + rng.normal(0,0.30),
79
+ anchors[fam[u]][1] + rng.normal(0,0.30)) for u in fam}
80
+
81
+ fig = plt.figure(figsize=(7.2, 4.2))
82
+ gs = fig.add_gridspec(2, 2, width_ratios=[2.0, 1.0], height_ratios=[1.3, 1.0],
83
+ wspace=0.06, hspace=0.30)
84
+ axN = fig.add_subplot(gs[:, 0]); axN.axis("off"); axN.set_aspect("equal")
85
+ axS = fig.add_subplot(gs[0, 1]); axS.axis("off")
86
+ axC = fig.add_subplot(gs[1, 1]); axC.axis("off")
87
+
88
+ # edges: declutter by drawing only weight>=2; width/alpha by weight
89
+ wmax = max(w.values())
90
+ for (cu,au),ww in w.items():
91
+ if ww < 2: continue
92
+ x1,y1 = pos[cu]; x2,y2 = pos[au]
93
+ axN.annotate("", xy=(x2,y2), xytext=(x1,y1),
94
+ arrowprops=dict(arrowstyle="-|>", color="#9aa0a6",
95
+ alpha=0.18+0.55*(ww/wmax), lw=0.4+1.8*(ww/wmax),
96
+ shrinkA=5, shrinkB=6, connectionstyle="arc3,rad=0.08"))
97
+ # nodes (sqrt scaling so the attractor doesn't dominate the canvas)
98
+ for u in fam:
99
+ x,y = pos[u]
100
+ s = 35 + 45*np.sqrt(indeg[u])
101
+ axN.scatter([x],[y], s=s, c=MODEL_COLOR[fam[u]], edgecolors="white", linewidths=0.8, zorder=3)
102
+ # faint cluster labels at anchors
103
+ for f,(ax_,ay_) in anchors.items():
104
+ axN.text(ax_*1.32, ay_*1.32, f, fontproperties=mono(8.5, bold=True),
105
+ color=MODEL_COLOR[f], ha="center", va="center", zorder=4)
106
+ xs=[p[0] for p in pos.values()]; ys=[p[1] for p in pos.values()]
107
+ m=0.45
108
+ axN.set_xlim(min(xs)-m, max(xs)+m); axN.set_ylim(min(ys)-m, max(ys)+m)
109
+ axN.set_title("Interaction network: one three-way run",
110
+ fontproperties=serif(12, bold=True), pad=10)
111
+ # legend
112
+ import matplotlib.lines as mlines
113
+ handles=[mlines.Line2D([],[],marker="o",ls="",mfc=MODEL_COLOR[f],mec="white",ms=9,label=f) for f in fams]
114
+ axN.legend(handles=handles, loc="lower left", prop=mono(8), frameon=False, handletextpad=0.2, borderpad=0.2)
115
+ axN.text(0.5,-0.03,"node size $\\propto$ in-degree · edge = comment flow",
116
+ transform=axN.transAxes, ha="center", fontproperties=mono(7.5), color="#555")
117
+
118
+ # ---- side stats ----
119
+ axS.set_title("per-model", fontproperties=serif(10, bold=True), loc="left", pad=2)
120
+ axS.text(0, 0.86, f"{'model':<8}{'in-deg':>7}{'H':>7}", fontproperties=mono(8.5, bold=True), transform=axS.transAxes)
121
+ for i,f in enumerate(fams):
122
+ md, h = stats[f]
123
+ axS.text(0, 0.86-0.13*(i+1),
124
+ f"{f:<8}{md:>7.1f}{h:>+7.2f}", fontproperties=mono(8.5),
125
+ color=MODEL_COLOR[f], transform=axS.transAxes)
126
+ axS.text(0, 0.86-0.13*(len(fams)+1.4),
127
+ f"{tot} cross-comments\n{len(posts)} posts, n={ntot} agents",
128
+ fontproperties=mono(7.5), color="#444", transform=axS.transAxes, va="top")
129
+
130
+ # ---- chat window ----
131
+ box = FancyBboxPatch((0.02,0.04),0.96,0.92, boxstyle="round,pad=0.02,rounding_size=0.04",
132
+ fc="#f3f4f6", ec="#cfd3da", lw=1.0, transform=axC.transAxes)
133
+ axC.add_patch(box)
134
+ def ascii_only(s): return s.encode("ascii","ignore").decode().strip()
135
+ auth_name = ascii_only(users.get(top_author, f"u{top_author}")) or f"u{top_author}"
136
+ auth_model = fam.get(top_author,"?")
137
+ header = f"{auth_name[:18]} ({auth_model})"
138
+ axC.text(0.07,0.85, header, fontproperties=mono(8.5,bold=True),
139
+ color=MODEL_COLOR.get(auth_model,"#333"), transform=axC.transAxes)
140
+ import textwrap
141
+ body = ascii_only(top_text.replace("\n"," "))
142
+ wrapped = "\n".join(textwrap.fill(body, width=32).split("\n")[:4])
143
+ if len(body) > len(wrapped): wrapped += " ..."
144
+ axC.text(0.07,0.72, wrapped, fontproperties=mono(8), color="#222",
145
+ transform=axC.transAxes, va="top")
146
+ axC.text(0.07,0.10, f">> {top_n} comments", fontproperties=mono(9,bold=True),
147
+ color="#1f77b4", transform=axC.transAxes)
148
+ axC.set_title("most-engaged post", fontproperties=serif(10, bold=True), loc="left", pad=2)
149
+
150
+ plt.savefig(OUT_SVG, bbox_inches="tight")
151
+ plt.savefig(OUT_PNG, dpi=300, bbox_inches="tight")
152
+ print(f"saved {OUT_SVG.name} + {OUT_PNG.name}")
153
+ print(f"run={Path(DB).stem} top_post nc={top_n} author={auth_name}({auth_model})")
154
+ for f in fams: print(f" {f}: in-deg={stats[f][0]:.1f} H={stats[f][1]:+.2f}")
analyses/plot_fig_variance_overview.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Variance overview (moved deeper; WORKING mock, house style).
3
+ (a) ABSOLUTE variance in agent engagement explained by persona vs model selection,
4
+ by regime -- total grows and the model-selection component scales.
5
+ (b) per-model attractiveness = mean incoming excess cross-model engagement H.
6
+ """
7
+ import sys
8
+ from pathlib import Path
9
+ from collections import defaultdict
10
+ import json, sqlite3
11
+ import numpy as np
12
+ import matplotlib
13
+ matplotlib.use("Agg")
14
+ import matplotlib.pyplot as plt
15
+ sys.path.insert(0, str(Path(__file__).parent))
16
+ from housestyle import serif, mono, MODEL_COLOR
17
+
18
+ RUNS = Path("runs")
19
+ OUT = Path(__file__).parent / "fig_variance_overview.png"
20
+ SHORT = {"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss",
21
+ "mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4",
22
+ "google/gemma-4-31B-it":"Gemma"}
23
+
24
+ # ---- Panel A: PROPORTIONAL variance of comments-per-post (CPP) explained by
25
+ # own base model vs persona, by regime (in-sample R^2, %). Model overtakes persona.
26
+ absvar = {
27
+ "Two-way": {"persona": 8.5, "model": 9.9},
28
+ "Three-way": {"persona": 7.3, "model": 13.3},
29
+ "Four-way": {"persona": 5.8, "model": 25.4},
30
+ }
31
+
32
+ # ---- Panel B: per-model attractiveness from run DBs ----
33
+ def attractiveness():
34
+ inc = defaultdict(list)
35
+ for db in sorted(RUNS.glob("sweep_*.db")):
36
+ if any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]): continue
37
+ mp = str(db).replace(".db",".metadata.json")
38
+ if not Path(mp).exists(): continue
39
+ try: amm = json.load(open(mp)).get("agent_model_map",{})
40
+ except: continue
41
+ if not amm: continue
42
+ fam = {int(k)+1: SHORT.get(v["model"]) for k,v in amm.items()}
43
+ if any(v is None for v in fam.values()): continue
44
+ try:
45
+ c = sqlite3.connect(db)
46
+ posts = c.execute("SELECT post_id,user_id FROM post").fetchall()
47
+ coms = c.execute("SELECT post_id,user_id FROM comment").fetchall(); c.close()
48
+ except: continue
49
+ if len(coms) < 200: continue
50
+ owner = {p:u for p,u in posts}; F = sorted(set(fam.values()))
51
+ nf = {f: sum(1 for v in fam.values() if v==f) for f in F}; ntot = sum(nf.values())
52
+ edges = [(fam[cu],fam[owner[p]]) for p,cu in coms if owner.get(p) and owner[p]!=cu and cu in fam and owner[p] in fam]
53
+ tot = len(edges) or 1
54
+ obs = defaultdict(int)
55
+ for x,y in edges: obs[(x,y)] += 1
56
+ for Y in F:
57
+ hs=[obs.get((X,Y),0)/tot/((nf[X]/ntot)*((nf[Y])/(ntot-1)))-1 for X in F if X!=Y and nf[X]]
58
+ if hs: inc[Y].append(np.mean(hs))
59
+ return {m:(np.mean(v), np.std(v)/np.sqrt(len(v))) for m,v in inc.items()}
60
+
61
+ def temporal_incoming_H(n_bins=4):
62
+ """Per-model incoming H over simulation quartiles (comment-order bins), pooled over runs."""
63
+ acc = defaultdict(lambda: defaultdict(list)) # model -> bin -> [H per run]
64
+ for db in sorted(RUNS.glob("sweep_*.db")):
65
+ if any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]): continue
66
+ mp = str(db).replace(".db",".metadata.json")
67
+ if not Path(mp).exists(): continue
68
+ try: amm = json.load(open(mp)).get("agent_model_map",{})
69
+ except: continue
70
+ if not amm: continue
71
+ fam = {int(k)+1: SHORT.get(v["model"]) for k,v in amm.items()}
72
+ if any(v is None for v in fam.values()): continue
73
+ try:
74
+ c = sqlite3.connect(db)
75
+ posts = c.execute("SELECT post_id,user_id FROM post").fetchall()
76
+ coms = c.execute("SELECT post_id,user_id FROM comment ORDER BY comment_id").fetchall(); c.close()
77
+ except: continue
78
+ if len(coms) < 200: continue
79
+ owner = {p:u for p,u in posts}; F = sorted(set(fam.values()))
80
+ nf = {f: sum(1 for v in fam.values() if v==f) for f in F}; ntot = sum(nf.values())
81
+ edges = [(fam[cu],fam[owner[p]]) for p,cu in coms
82
+ if owner.get(p) and owner[p]!=cu and cu in fam and owner[p] in fam]
83
+ if len(edges) < n_bins*20: continue
84
+ for b in range(n_bins):
85
+ seg = edges[b*len(edges)//n_bins:(b+1)*len(edges)//n_bins]
86
+ tot = len(seg) or 1
87
+ obs = defaultdict(int)
88
+ for xx,yy in seg: obs[(xx,yy)] += 1
89
+ for Y in F:
90
+ hs=[obs.get((X,Y),0)/tot/((nf[X]/ntot)*((nf[Y])/(ntot-1)))-1 for X in F if X!=Y and nf[X]]
91
+ if hs: acc[Y][b].append(np.mean(hs))
92
+ return acc
93
+
94
+ plt.rcParams.update({"axes.spines.top":False,"axes.spines.right":False,"figure.dpi":300})
95
+ fig,(axA,axB) = plt.subplots(1,2, figsize=(7.2,2.6), gridspec_kw={"width_ratios":[1,1.05]})
96
+
97
+ # Panel A: absolute grouped bars
98
+ regimes=["Two-way","Three-way","Four-way"]; x=np.arange(3); w=0.38
99
+ pc="#c0392b"; mc="#2c6fbb"
100
+ for i,key in enumerate(["persona","model"]):
101
+ vals=[absvar[r][key] for r in regimes]; off=(-w/2 if i==0 else w/2)
102
+ axA.bar(x+off, vals, w, color=(pc if i==0 else mc),
103
+ label=("persona" if i==0 else "base model"), edgecolor="white", lw=0.5)
104
+ for xi,vv in zip(x+off,vals):
105
+ axA.text(xi, vv+0.4, f"{vv:.1f}", ha="center", va="bottom", fontproperties=mono(8))
106
+ axA.set_xticks(x); axA.set_xticklabels(regimes, fontproperties=mono(9))
107
+ axA.set_ylabel("CPP variance explained ($R^2$, \\%)", fontproperties=mono(8.5))
108
+ axA.set_ylim(0, 29)
109
+ axA.legend(prop=mono(8), frameon=False, loc="upper left")
110
+ axA.set_title("(a) Per-post engagement: model overtakes persona", fontproperties=serif(9.5, bold=True))
111
+ axA.tick_params(labelsize=8)
112
+
113
+ # Panel B: per-model incoming H across mixture sizes (one line per base model), centered at y=0
114
+ TETDIR = RUNS / "tetratic"
115
+ def regime_H():
116
+ acc = defaultdict(lambda: defaultdict(list)) # model -> regime -> [H per run]
117
+ def proc(globpat, tet=False):
118
+ for db in sorted(globpat):
119
+ if not tet and any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]): continue
120
+ if tet and (TETDIR/f"{db.stem}_checkpoint.json").exists(): continue
121
+ mp = str(db).replace(".db",".metadata.json")
122
+ if not Path(mp).exists(): continue
123
+ try: amm = json.load(open(mp)).get("agent_model_map",{})
124
+ except: continue
125
+ if not amm: continue
126
+ fam = {int(k)+1: SHORT.get(v["model"]) for k,v in amm.items()}
127
+ if any(v is None for v in fam.values()): continue
128
+ try:
129
+ c = sqlite3.connect(db)
130
+ posts = c.execute("SELECT post_id,user_id FROM post").fetchall()
131
+ coms = c.execute("SELECT post_id,user_id FROM comment").fetchall(); c.close()
132
+ except: continue
133
+ if len(coms) < (100 if tet else 200): continue
134
+ F = sorted(set(fam.values())); reg = {2:"dyad",3:"triad",4:"tetrad"}.get(len(F))
135
+ if not reg: continue
136
+ owner = {p:u for p,u in posts}; nf = {f: sum(1 for v in fam.values() if v==f) for f in F}; N = sum(nf.values())
137
+ edges = [(fam[cu],fam[owner[p]]) for p,cu in coms if owner.get(p) and owner[p]!=cu and cu in fam and owner[p] in fam]
138
+ tot = len(edges) or 1; obs = defaultdict(int)
139
+ for a,b in edges: obs[(a,b)] += 1
140
+ for Y in F:
141
+ hs = [obs.get((X,Y),0)/tot/((nf[X]/N)*(nf[Y]/(N-1)))-1 for X in F if X!=Y]
142
+ if hs: acc[Y][reg].append(np.mean(hs))
143
+ proc(RUNS.glob("sweep_*.db")); proc(TETDIR.glob("tetra_s*_r*.db"), tet=True)
144
+ return acc
145
+ rH = regime_H()
146
+ regs = ["dyad","triad","tetrad"]; xr = np.arange(3)
147
+ axB.axhline(0, color="#666", lw=0.9, ls=":")
148
+ for m in ["gpt-oss","Qwen","GLM-4","Gemma","Mag"]:
149
+ if m not in rH: continue
150
+ ys = [np.mean(rH[m][r]) if rH[m].get(r) else np.nan for r in regs]
151
+ axB.plot(xr, ys, marker="o", ms=4.5, lw=1.8, color=MODEL_COLOR[m], label=m)
152
+ allv = [np.mean(rH[m][r]) for m in rH for r in regs if rH[m].get(r)]
153
+ M = max(abs(v) for v in allv) * 1.18
154
+ axB.set_ylim(-M, M)
155
+ axB.set_xticks(xr); axB.set_xticklabels(["dyad","triad","tetrad"], fontproperties=mono(9))
156
+ axB.set_xlim(-0.15, 2.15)
157
+ axB.set_ylabel("incoming $H$ (excess engagement)", fontproperties=mono(8.5))
158
+ axB.set_title("(b) Attraction sharpens with mixture size", fontproperties=serif(9.5, bold=True))
159
+ axB.legend(prop=mono(7), frameon=False, ncol=2, loc="lower left", handlelength=1.3)
160
+ axB.tick_params(labelsize=8)
161
+
162
+ plt.tight_layout(w_pad=1.5)
163
+ fig.savefig(OUT, dpi=300, bbox_inches="tight")
164
+ print(f"saved {OUT.name}")
analyses/plot_matrices.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Heatmap figures for the divsim paper.
3
+
4
+ Produces H-matrix, swap-stability, in-group self-preference, and Elo-rating
5
+ figures in three variants each: dyadic-only, triadic-only, combined.
6
+
7
+ Figures are written to OUTDIR (default: same directory as this script).
8
+
9
+ Configuration:
10
+ RUNS_DIR — directory containing sweep_*.db files (env var or --runs-dir)
11
+ OUTDIR — output directory for .png files (env var or --outdir)
12
+
13
+ Usage:
14
+ python plot_matrices.py
15
+ python plot_matrices.py --runs-dir /path/to/runs --outdir /path/to/figures
16
+ """
17
+
18
+ import os
19
+ import glob
20
+ import json
21
+ import math
22
+ import sqlite3
23
+ import itertools
24
+ import argparse
25
+ from collections import defaultdict
26
+ from pathlib import Path
27
+
28
+ import matplotlib
29
+ matplotlib.use("Agg")
30
+ import matplotlib.pyplot as plt
31
+ import numpy as np
32
+ from matplotlib.font_manager import FontProperties, fontManager
33
+
34
+
35
+ # ── Font loading ──────────────────────────────────────────────────────────────
36
+ # Looks for Volkhov and Ubuntu Mono in ~/fonts; falls back gracefully.
37
+ FONT_DIR = Path.home() / "fonts"
38
+ if FONT_DIR.is_dir():
39
+ for ttf in FONT_DIR.rglob("*.ttf"):
40
+ fontManager.addfont(str(ttf))
41
+
42
+
43
+ def fp(family, size, bold=False):
44
+ return FontProperties(family=family, size=size,
45
+ weight="bold" if bold else "normal")
46
+
47
+
48
+ FT = lambda s, bold=False: fp("Volkhov", s, bold)
49
+ FB = lambda s, bold=False: fp("Ubuntu Mono", s, bold)
50
+
51
+ plt.rcParams.update({
52
+ "font.family": "Ubuntu Mono",
53
+ "axes.spines.top": False,
54
+ "axes.spines.right": False,
55
+ "figure.dpi": 300,
56
+ })
57
+
58
+ SHORT = {
59
+ "Qwen/Qwen3-32B": "Qwen",
60
+ "openai/gpt-oss-20b": "gpt-oss",
61
+ "mistralai/Magistral-Small-2509": "Mag",
62
+ "zai-org/GLM-4-32B-0414": "GLM-4",
63
+ "google/gemma-4-31B-it": "Gemma",
64
+ }
65
+ MODELS = ["GLM-4", "Mag", "Qwen", "gpt-oss", "Gemma"]
66
+ MODEL_SET = set(MODELS)
67
+
68
+
69
+ # ── H computation ──────────────────────────────────────────────────────────────
70
+
71
+ def load_h(db_path):
72
+ """Compute directed pairwise H matrix for one run DB."""
73
+ mp = str(db_path).replace(".db", ".metadata.json")
74
+ if not os.path.exists(mp):
75
+ return {}
76
+ with open(mp) as f:
77
+ meta = json.load(f)
78
+ amm = meta.get("agent_model_map", {})
79
+ if not amm:
80
+ return {}
81
+ uf = {int(k)+1: SHORT.get(v["model"], v["model"][:6]) for k, v in amm.items()}
82
+ fc = defaultdict(int)
83
+ for fam in uf.values():
84
+ fc[fam] += 1
85
+ ec = defaultdict(int)
86
+ conn = sqlite3.connect(db_path)
87
+ for cu, pu in conn.execute(
88
+ "SELECT c.user_id, p.user_id FROM comment c "
89
+ "JOIN post p ON c.post_id=p.post_id WHERE c.user_id!=p.user_id"):
90
+ sf, df = uf.get(cu), uf.get(pu)
91
+ if sf and df:
92
+ ec[(sf, df)] += 1
93
+ conn.close()
94
+ total = sum(ec.values())
95
+ if not total:
96
+ return {}
97
+ n = sum(fc.values())
98
+ H = {}
99
+ for s in fc:
100
+ for d in fc:
101
+ obs = ec.get((s, d), 0) / total
102
+ exp = (fc[s]/n) * ((fc[d] - (1 if s == d else 0)) / (n-1))
103
+ if exp > 0:
104
+ H[(s, d)] = obs/exp - 1
105
+ return H
106
+
107
+
108
+ # ── Load all valid dyadic runs ────────────────────────────────────────────────
109
+
110
+ def load_dyadic(runs_dir: Path):
111
+ all_H = defaultdict(list)
112
+ swap_vals = defaultdict(lambda: defaultdict(list))
113
+ for db in sorted(runs_dir.glob("sweep_*.db")):
114
+ name = str(db)
115
+ if any(x in name for x in ["archive", "snapshot", "sweep_tri_",
116
+ "olm", "hermes", "qwq", "glm47"]):
117
+ continue
118
+ try:
119
+ mp = name.replace(".db", ".metadata.json")
120
+ if not os.path.exists(mp):
121
+ continue
122
+ with open(mp) as f:
123
+ meta = json.load(f)
124
+ amm = meta.get("agent_model_map", {})
125
+ fams = set(SHORT.get(v["model"], v["model"][:6]) for v in amm.values())
126
+ if len(fams) != 2 or not fams.issubset(MODEL_SET):
127
+ continue
128
+ conn = sqlite3.connect(db)
129
+ nu = conn.execute("SELECT COUNT(DISTINCT user_id) FROM comment").fetchone()[0]
130
+ nc = conn.execute("SELECT COUNT(*) FROM comment").fetchone()[0]
131
+ conn.close()
132
+ if nu < 18 or nc < 200:
133
+ continue
134
+ H = load_h(db)
135
+ seed = str(db).split("_s")[-1].replace(".db", "")
136
+ dyad_key = frozenset(fams)
137
+ for pair, h in H.items():
138
+ all_H[pair].append(h)
139
+ swap_vals[pair][(dyad_key, seed)].append(h)
140
+ except Exception:
141
+ pass
142
+ return all_H, swap_vals
143
+
144
+
145
+ def load_triadic(runs_dir: Path):
146
+ all_H = defaultdict(list)
147
+ by_triplet_seed = defaultdict(list)
148
+ for db in sorted(runs_dir.glob("sweep_tri_*.db")):
149
+ if "archive" in str(db):
150
+ continue
151
+ try:
152
+ conn = sqlite3.connect(db)
153
+ nu = conn.execute("SELECT COUNT(DISTINCT user_id) FROM comment").fetchone()[0]
154
+ conn.close()
155
+ if nu < 26:
156
+ continue
157
+ mp = str(db).replace(".db", ".metadata.json")
158
+ if not os.path.exists(mp):
159
+ continue
160
+ H = load_h(db)
161
+ if not H:
162
+ continue
163
+ with open(mp) as f:
164
+ meta = json.load(f)
165
+ amm = meta.get("agent_model_map", {})
166
+ run_models = frozenset(
167
+ SHORT.get(v["model"], v["model"][:6]) for v in amm.values()
168
+ )
169
+ seed = str(db).split("_s")[-1].replace(".db", "")
170
+ by_triplet_seed[(run_models, seed)].append(H)
171
+ for pair, h in H.items():
172
+ all_H[pair].append(h)
173
+ except Exception:
174
+ pass
175
+ return all_H, by_triplet_seed
176
+
177
+
178
+ # ── Swap-stability matrices ───────────────────────────────────────────────────
179
+
180
+ def dyadic_swap_matrix(swap_vals, keys):
181
+ """Mean |ΔH| across seeds for dyadic runs (exactly 2 orientations per seed)."""
182
+ n = len(keys)
183
+ mean = np.full((n, n), np.nan)
184
+ std = np.full((n, n), np.nan)
185
+ for i, s in enumerate(keys):
186
+ for j, d in enumerate(keys):
187
+ by_seed = swap_vals.get((s, d), {})
188
+ diffs = [abs(vs[0]-vs[1]) for vs in by_seed.values() if len(vs) == 2]
189
+ if diffs:
190
+ mean[i, j] = np.mean(diffs)
191
+ std[i, j] = np.std(diffs, ddof=1) if len(diffs) > 1 else 0.
192
+ return mean, std
193
+
194
+
195
+ def triadic_swap_matrix(tri_by_ts, keys):
196
+ """Mean max-|ΔH| per (triplet, seed) group for triadic runs (3 orderings)."""
197
+ n = len(keys)
198
+ pair_maxdiffs = defaultdict(list)
199
+ for (triplet, seed), h_list in tri_by_ts.items():
200
+ if len(h_list) < 2:
201
+ continue
202
+ all_pairs = set()
203
+ for H in h_list:
204
+ all_pairs.update(H.keys())
205
+ for pair in all_pairs:
206
+ vals = [H.get(pair, np.nan) for H in h_list]
207
+ vals = [v for v in vals if not np.isnan(v)]
208
+ if len(vals) < 2:
209
+ continue
210
+ max_diff = max(abs(a-b) for a, b in itertools.combinations(vals, 2))
211
+ pair_maxdiffs[pair].append(max_diff)
212
+ mean = np.full((n, n), np.nan)
213
+ std = np.full((n, n), np.nan)
214
+ for i, s in enumerate(keys):
215
+ for j, d in enumerate(keys):
216
+ diffs = pair_maxdiffs.get((s, d), [])
217
+ if diffs:
218
+ mean[i, j] = np.mean(diffs)
219
+ std[i, j] = np.std(diffs, ddof=1) if len(diffs) > 1 else 0.
220
+ return mean, std
221
+
222
+
223
+ def combined_swap_matrix(swap_dy_mean, swap_dy_std, swap_tri_mean, swap_tri_std, keys):
224
+ """Unweighted average of dyadic and triadic swap means where both exist."""
225
+ n = len(keys)
226
+ mean = np.full((n, n), np.nan)
227
+ std = np.full((n, n), np.nan)
228
+ for i in range(n):
229
+ for j in range(n):
230
+ vals = []
231
+ if not np.isnan(swap_dy_mean[i, j]):
232
+ vals.append(swap_dy_mean[i, j])
233
+ if not np.isnan(swap_tri_mean[i, j]):
234
+ vals.append(swap_tri_mean[i, j])
235
+ if vals:
236
+ mean[i, j] = np.mean(vals)
237
+ std[i, j] = np.std(vals, ddof=0) if len(vals) > 1 else 0.
238
+ return mean, std
239
+
240
+
241
+ # ── Per-matrix statistics ─────────────────────────────────────────────────────
242
+
243
+ def mat_stats(H_dict, keys):
244
+ n = len(keys)
245
+ mean = np.full((n, n), np.nan)
246
+ std = np.full((n, n), np.nan)
247
+ for i, s in enumerate(keys):
248
+ for j, d in enumerate(keys):
249
+ vals = H_dict.get((s, d), [])
250
+ if vals:
251
+ mean[i, j] = np.mean(vals)
252
+ std[i, j] = np.std(vals, ddof=1) if len(vals) > 1 else 0.
253
+ return mean, std
254
+
255
+
256
+ # ── Cell annotation helpers ───────────────────────────────────────────────────
257
+
258
+ def label_cells(ax, mean, std, swap_mean=None, swap_std=None,
259
+ skip_diag=False,
260
+ fs_main=32, fs_std=22, fs_swap=20, thresh=0.28):
261
+ n = mean.shape[0]
262
+ for i in range(n):
263
+ for j in range(n):
264
+ if skip_diag and i == j:
265
+ continue
266
+ if np.isnan(mean[i, j]):
267
+ continue
268
+ v = mean[i, j]
269
+ txt_col = "white" if abs(v) > thresh else "#1a1a1a"
270
+ ax.text(j, i - 0.28, f"{v:+.3f}",
271
+ ha="center", va="center",
272
+ fontproperties=FB(fs_main, bold=True), color=txt_col)
273
+ ax.text(j, i + 0.02, f"±{std[i, j]:.2f}",
274
+ ha="center", va="center",
275
+ fontproperties=FB(fs_std), color=txt_col, alpha=0.90)
276
+ if swap_mean is not None and not np.isnan(swap_mean[i, j]):
277
+ s_v = swap_mean[i, j]
278
+ s_sd = swap_std[i, j] if swap_std is not None and not np.isnan(swap_std[i, j]) else 0.
279
+ ax.text(j, i + 0.32,
280
+ f"|ΔH|={s_v:.2f}±{s_sd:.2f}",
281
+ ha="center", va="center",
282
+ fontproperties=FB(fs_swap, bold=True),
283
+ color=txt_col, alpha=0.85)
284
+
285
+
286
+ def style_axes(ax, labels, title, cbar_im, vmax, cbar_label="H"):
287
+ n = len(labels)
288
+ ax.set_xticks(range(n))
289
+ ax.set_yticks(range(n))
290
+ ax.set_xticklabels(labels, fontproperties=FB(22, bold=True), rotation=0)
291
+ ax.set_yticklabels(labels, fontproperties=FB(22, bold=True))
292
+ ax.set_xlabel("target family (post author)", fontproperties=FB(20), labelpad=12)
293
+ ax.set_ylabel("source family (commenter)", fontproperties=FB(20), labelpad=12)
294
+ ax.set_title(title, fontproperties=FT(26, bold=True), pad=18)
295
+ cb = plt.colorbar(cbar_im, ax=ax, fraction=0.046, pad=0.04)
296
+ cb.set_label(cbar_label, fontproperties=FB(20))
297
+ for tick in cb.ax.get_yticklabels():
298
+ tick.set_fontproperties(FB(16))
299
+
300
+
301
+ # ── Plot functions ────────────────────────────────────────────────────────────
302
+
303
+ def plot_h_matrix(H_dict, keys, title, outpath, cross_only=False,
304
+ swap_mean=None, swap_std=None):
305
+ mean, std = mat_stats(H_dict, keys)
306
+ if cross_only:
307
+ np.fill_diagonal(mean, np.nan)
308
+ np.fill_diagonal(std, np.nan)
309
+ vmax = np.nanmax(np.abs(mean)) * 1.08
310
+ fig, ax = plt.subplots(figsize=(15.0, 12.5))
311
+ im = ax.imshow(mean, cmap="RdBu_r", vmin=-vmax, vmax=vmax, aspect="equal")
312
+ label_cells(ax, mean, std,
313
+ swap_mean=swap_mean, swap_std=swap_std,
314
+ skip_diag=cross_only)
315
+ style_axes(ax, keys, title, im, vmax)
316
+ plt.tight_layout()
317
+ fig.savefig(outpath, dpi=300, bbox_inches="tight")
318
+ plt.close(fig)
319
+ print(f"saved {Path(outpath).name}")
320
+
321
+
322
+ def plot_swap(swap_mean, swap_std, keys, title, outpath):
323
+ vmax = np.nanmax(swap_mean[~np.isnan(swap_mean)]) * 1.05
324
+ fig, ax = plt.subplots(figsize=(7.5, 6.2))
325
+ im = ax.imshow(swap_mean, cmap="YlOrRd", vmin=0, vmax=vmax, aspect="equal")
326
+ n = len(keys)
327
+ for i in range(n):
328
+ for j in range(n):
329
+ if np.isnan(swap_mean[i, j]):
330
+ continue
331
+ v = swap_mean[i, j]
332
+ txt_col = "white" if v > vmax * 0.65 else "#1a1a1a"
333
+ ax.text(j, i - 0.14, f"{v:.3f}",
334
+ ha="center", va="center",
335
+ fontproperties=FB(18, bold=True), color=txt_col)
336
+ ax.text(j, i + 0.26, f"±{swap_std[i, j]:.2f}",
337
+ ha="center", va="center",
338
+ fontproperties=FB(12), color=txt_col, alpha=0.80)
339
+ ax.set_xticks(range(n))
340
+ ax.set_yticks(range(n))
341
+ ax.set_xticklabels(keys, fontproperties=FB(13, bold=True), rotation=0)
342
+ ax.set_yticklabels(keys, fontproperties=FB(13, bold=True))
343
+ ax.set_xlabel("target family", fontproperties=FB(11), labelpad=7)
344
+ ax.set_ylabel("source family", fontproperties=FB(11), labelpad=7)
345
+ ax.set_title(title, fontproperties=FT(16, bold=True), pad=12)
346
+ cb = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
347
+ cb.set_label(r"$|\Delta H|$", fontproperties=FB(11))
348
+ for tick in cb.ax.get_yticklabels():
349
+ tick.set_fontproperties(FB(10))
350
+ plt.tight_layout()
351
+ fig.savefig(outpath, dpi=300, bbox_inches="tight")
352
+ plt.close(fig)
353
+ print(f"saved {Path(outpath).name}")
354
+
355
+
356
+ def model_color(m):
357
+ import colorsys
358
+ full = {v: k for k, v in SHORT.items()}.get(m, m)
359
+ h = 0
360
+ for c in full:
361
+ h = (h*31 + ord(c)) & 0xFFFFFFFF
362
+ if h >= 0x80000000:
363
+ h -= 0x100000000
364
+ hue = abs(h) % 360
365
+ r, g, b = colorsys.hls_to_rgb(hue/360, 0.45, 0.55)
366
+ return "#{:02x}{:02x}{:02x}".format(int(r*255), int(g*255), int(b*255))
367
+
368
+
369
+ def plot_self_pref(H_data, tag, label, outdir):
370
+ self_vals = [H_data.get((m, m), []) for m in MODELS]
371
+ self_m = [np.mean(v) if v else np.nan for v in self_vals]
372
+ self_s = [np.std(v, ddof=1) if len(v) > 1 else 0. for v in self_vals]
373
+ self_n = [len(v) for v in self_vals]
374
+
375
+ colors = []
376
+ for v in self_m:
377
+ if np.isnan(v): colors.append("#aaa")
378
+ elif v > 0: colors.append("#c0392b")
379
+ else: colors.append("#2980b9")
380
+
381
+ fig, ax = plt.subplots(figsize=(5.5, 4.0))
382
+ xs = range(len(MODELS))
383
+ ax.bar(xs, self_m, color=colors, alpha=0.85, width=0.6,
384
+ edgecolor="white", linewidth=0.6)
385
+ ax.errorbar(xs, self_m, yerr=self_s, fmt="none", color="#333",
386
+ capsize=5, lw=1.5, capthick=1.5)
387
+ ax.axhline(0, color="#555", lw=0.8)
388
+ for x, m, s, n in zip(xs, self_m, self_s, self_n):
389
+ if np.isnan(m):
390
+ continue
391
+ yoff = m + s + 0.02 if m >= 0 else m - s - 0.07
392
+ va = "bottom" if m >= 0 else "top"
393
+ ax.text(x, yoff, f"n={n}", ha="center", va=va,
394
+ fontproperties=FB(9), color="#555")
395
+ ax.set_xticks(list(xs))
396
+ ax.set_xticklabels(MODELS, fontproperties=FB(11, bold=True))
397
+ ax.set_ylabel(r"$H_{X \to X}$ (in-group self-preference)", fontproperties=FB(10))
398
+ ax.set_title(f"{label} in-group self-preference", fontproperties=FT(14, bold=True), pad=10)
399
+ plt.tight_layout()
400
+ outpath = outdir / f"fig_self_pref_{tag}.png"
401
+ fig.savefig(outpath, dpi=300, bbox_inches="tight")
402
+ plt.close(fig)
403
+ print(f"saved {outpath.name}")
404
+
405
+
406
+ def plot_elo(all_H_dy, outdir):
407
+ """Elo rating from dyadic H-matrix net-attractor advantage."""
408
+ matches = []
409
+ for pair, vals in all_H_dy.items():
410
+ if pair[0] == pair[1]:
411
+ continue
412
+ x, y = pair[0], pair[1]
413
+ h_xy = np.mean(vals) if vals else 0
414
+ rev_pair = (y, x)
415
+ h_yx = np.mean(all_H_dy.get(rev_pair, [0]))
416
+ net_x = h_yx - h_xy
417
+ matches.append((x, y, net_x))
418
+
419
+ elo = defaultdict(lambda: 1200.0)
420
+ K = 32
421
+ for x, y, net in matches:
422
+ exp_x = 1 / (1 + 10**((elo[y]-elo[x])/400))
423
+ sx = 1 / (1 + math.exp(-net/0.5))
424
+ elo[x] += K * (sx - exp_x)
425
+ elo[y] += K * ((1-sx) - (1-exp_x))
426
+
427
+ elo_items = sorted(elo.items(), key=lambda kv: -kv[1])
428
+ elo_models = [k for k, v in elo_items]
429
+ elo_vals = [v for k, v in elo_items]
430
+ cols = [model_color(m) for m in elo_models]
431
+
432
+ fig, ax = plt.subplots(figsize=(5.5, 4.0))
433
+ ax.bar(range(len(elo_models)), elo_vals, color=cols, alpha=0.88,
434
+ width=0.6, edgecolor="white", linewidth=0.6)
435
+ ax.axhline(1200, color="#888", lw=0.8, ls="--", alpha=0.6)
436
+ for x, v, m in zip(range(len(elo_models)), elo_vals, elo_models):
437
+ ax.text(x, v+4, f"{v:.0f}", ha="center", va="bottom",
438
+ fontproperties=FB(10, bold=True), color="#222")
439
+ ax.set_xticks(list(range(len(elo_models))))
440
+ ax.set_xticklabels(elo_models, fontproperties=FB(11, bold=True))
441
+ ax.set_ylabel("Elo rating", fontproperties=FB(10))
442
+ ax.set_title("Elo ranking (net attractor advantage, dyadic)",
443
+ fontproperties=FT(14, bold=True), pad=10)
444
+ plt.tight_layout()
445
+ fig.savefig(outdir / "fig_elo.png", dpi=300, bbox_inches="tight")
446
+ plt.close(fig)
447
+ print("saved fig_elo.png")
448
+
449
+
450
+ def main():
451
+ parser = argparse.ArgumentParser(description=__doc__)
452
+ parser.add_argument("--runs-dir", default=os.environ.get("RUNS_DIR", "./runs"),
453
+ help="Directory containing sweep_*.db files.")
454
+ parser.add_argument("--outdir", default=os.environ.get("OUTDIR", str(Path(__file__).parent)),
455
+ help="Output directory for figures.")
456
+ args = parser.parse_args()
457
+
458
+ runs_dir = Path(args.runs_dir)
459
+ outdir = Path(args.outdir)
460
+ outdir.mkdir(parents=True, exist_ok=True)
461
+
462
+ print(f"Loading dyadic runs from {runs_dir}...")
463
+ all_H_dy, swap_vals_dy = load_dyadic(runs_dir)
464
+
465
+ print(f"Loading triadic runs from {runs_dir}...")
466
+ all_H_tri, tri_by_ts = load_triadic(runs_dir)
467
+
468
+ all_H_combined = defaultdict(list)
469
+ for pair, vals in all_H_dy.items():
470
+ all_H_combined[pair].extend(vals)
471
+ for pair, vals in all_H_tri.items():
472
+ all_H_combined[pair].extend(vals)
473
+
474
+ swap_dy_mean, swap_dy_std = dyadic_swap_matrix(swap_vals_dy, MODELS)
475
+ swap_tri_mean, swap_tri_std = triadic_swap_matrix(tri_by_ts, MODELS)
476
+ swap_comb_mean, swap_comb_std = combined_swap_matrix(
477
+ swap_dy_mean, swap_dy_std, swap_tri_mean, swap_tri_std, MODELS)
478
+
479
+ datasets = [
480
+ ("dyadic", all_H_dy, swap_dy_mean, swap_dy_std),
481
+ ("triadic", all_H_tri, swap_tri_mean, swap_tri_std),
482
+ ("combined", all_H_combined, swap_comb_mean, swap_comb_std),
483
+ ]
484
+
485
+ for tag, H_data, sw_mean, sw_std in datasets:
486
+ label = {"dyadic": "Dyadic", "triadic": "Triadic", "combined": "Combined"}[tag]
487
+
488
+ plot_h_matrix(
489
+ H_data, MODELS,
490
+ rf"{label} directed engagement homophily $H_{{X \to Y}}$",
491
+ outdir / f"fig_h_matrix_{tag}.png",
492
+ swap_mean=sw_mean, swap_std=sw_std,
493
+ )
494
+ plot_h_matrix(
495
+ H_data, MODELS,
496
+ rf"{label} cross-group homophily $H_{{X \to Y}}$, $X \neq Y$",
497
+ outdir / f"fig_h_matrix_cross_{tag}.png",
498
+ cross_only=True,
499
+ swap_mean=sw_mean, swap_std=sw_std,
500
+ )
501
+
502
+ swap_title = {
503
+ "dyadic": r"Dyadic swap instability: mean $|H_{AB} - H_{BA}|$",
504
+ "triadic": r"Triadic ordering instability: mean max-$|\Delta H|$",
505
+ "combined": r"Ordering instability: mean max-$|\Delta H|$ (pooled)",
506
+ }[tag]
507
+ plot_swap(sw_mean, sw_std, MODELS, swap_title,
508
+ outdir / f"fig_swap_stability_{tag}.png")
509
+
510
+ plot_self_pref(H_data, tag, label, outdir)
511
+
512
+ plot_elo(all_H_dy, outdir)
513
+
514
+ print(f"\nAll figures written to {outdir}")
515
+
516
+
517
+ if __name__ == "__main__":
518
+ main()
analyses/style_geometry.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model style directions (centroids), their pairwise comparison + stability,
2
+ and their cosine distance to an 'engagingness' direction (linear engagement probe).
3
+ Style space = agent-level TF-IDF -> SVD (K=30), axis 1 (language) dropped."""
4
+ import sqlite3, json
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ import numpy as np
8
+ from numpy.linalg import lstsq, norm
9
+ from sklearn.feature_extraction.text import TfidfVectorizer
10
+ from sklearn.decomposition import TruncatedSVD
11
+ RUNS=Path("runs")
12
+ OUT=Path("out/style_geometry.md")
13
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
14
+ K=30; MODELS=["gpt-oss","Qwen","GLM-4","Mag","Gemma"]
15
+ ag=[]
16
+ for db in sorted(RUNS.glob("sweep_*.db")):
17
+ if any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
18
+ mp=str(db).replace(".db",".metadata.json")
19
+ if not Path(mp).exists():continue
20
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
21
+ except:continue
22
+ if not amm:continue
23
+ fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
24
+ if any(v is None for v in fam.values()):continue
25
+ try:
26
+ c=sqlite3.connect(db);posts=c.execute("SELECT post_id,user_id,content FROM post").fetchall();coms=c.execute("SELECT post_id,user_id FROM comment").fetchall();c.close()
27
+ except:continue
28
+ if len(coms)<200:continue
29
+ owner={p:u for p,u,_ in posts};ind=defaultdict(int)
30
+ for p,cu in coms:
31
+ o=owner.get(p)
32
+ if o in fam and o!=cu:ind[o]+=1
33
+ txt=defaultdict(list)
34
+ for p,u,cont in posts:
35
+ if u in fam and cont:txt[u].append(cont)
36
+ for u,tl in txt.items():
37
+ if tl:ag.append({"run":db.stem,"model":fam[u],"indeg":ind.get(u,0),"text":" ".join(tl)})
38
+ n=len(ag);print(n,"agents")
39
+ vc=TfidfVectorizer(ngram_range=(1,2),analyzer="word",min_df=10,max_features=20000,sublinear_tf=True,norm="l2",stop_words="english",token_pattern=r"[A-Za-z'][A-Za-z']+")
40
+ X=vc.fit_transform([a["text"]for a in ag])
41
+ S=TruncatedSVD(K,random_state=0).fit_transform(X)
42
+ Z=((S-S.mean(0))/(S.std(0)+1e-9))[:,1:] # drop axis 1 (language)
43
+ model=np.array([a["model"]for a in ag]);runs=np.array([a["run"]for a in ag])
44
+ y=np.zeros(n);bd=defaultdict(list)
45
+ for i,a in enumerate(ag):bd[a["run"]].append(i)
46
+ for r,idx in bd.items():
47
+ v=np.array([ag[i]["indeg"]for i in idx],float);z=(v-v.mean())/(v.std()+1e-9)
48
+ for k,i in enumerate(idx):y[i]=z[k]
49
+ def u(x):return x/(norm(x)+1e-12)
50
+ cos=lambda a,b:float(u(a)@u(b))
51
+ cent={m:Z[model==m].mean(0) for m in MODELS}
52
+ # engagingness direction = OLS engagement ~ style (linear probe)
53
+ A=np.column_stack([np.ones(n),Z]);beta=lstsq(A,y,rcond=None)[0][1:];e=u(beta)
54
+ o=["# Style geometry: model directions, stability, and the engagingness vector\n",
55
+ "Style space = agent TF-IDF -> SVD(30), axis 1 (language) dropped (29 dims).\n",
56
+ "## 1. Model directions (centroids) -- pairwise cosine",
57
+ "| | "+" | ".join(MODELS)+" |","|"+"---|"*(len(MODELS)+1)]
58
+ for m in MODELS:o.append(f"| {m} | "+" | ".join(f"{cos(cent[m],cent[m2]):+.2f}" for m2 in MODELS)+" |")
59
+ # ---- 2. stability via disjoint run-splits ----
60
+ rng=np.random.default_rng(0);uruns=np.array(sorted(set(runs)));B=60
61
+ selfc={m:[] for m in MODELS};e_self=[]
62
+ for _ in range(B):
63
+ rng.shuffle(uruns);Aset=set(uruns[:len(uruns)//2]);am=np.array([r in Aset for r in runs])
64
+ for m in MODELS:
65
+ a1=(model==m)&am;b1=(model==m)&(~am)
66
+ if a1.sum()<10 or b1.sum()<10:continue
67
+ selfc[m].append(cos(Z[a1].mean(0),Z[b1].mean(0)))
68
+ # engagingness vector stability
69
+ bA=lstsq(np.column_stack([np.ones(am.sum()),Z[am]]),y[am],rcond=None)[0][1:]
70
+ bB=lstsq(np.column_stack([np.ones((~am).sum()),Z[~am]]),y[~am],rcond=None)[0][1:]
71
+ e_self.append(cos(bA,bB))
72
+ o.append("\n## 2. Direction stability (cosine between centroids from disjoint run-halves, mean over 60 splits)")
73
+ o.append("| model | self-cosine (1=perfectly stable) |");o.append("|---|---|")
74
+ for m in MODELS:o.append(f"| {m} | {np.mean(selfc[m]):.2f} |")
75
+ o.append(f"\nEngagingness vector self-cosine across run-halves: **{np.mean(e_self):.2f}** "
76
+ f"(stability of the engagement direction itself).")
77
+ # ---- 3. distance from engagingness vector ----
78
+ o.append("\n## 3. Cosine of each model direction to the engagingness vector (higher = style closer to 'what engages')")
79
+ o.append("| model | cos(centroid, engagingness) |");o.append("|---|---|")
80
+ ranked=sorted(MODELS,key=lambda m:cos(cent[m],e),reverse=True)
81
+ for m in ranked:o.append(f"| {m} | {cos(cent[m],e):+.2f} |")
82
+ o.append(f"\nClosest to the engagingness direction: **{ranked[0]}**. "
83
+ "If that is gpt-oss, the engaging style direction coincides with the attractor's style.")
84
+ OUT.write_text("\n".join(o)+"\n");print("\n".join(o));print("wrote",OUT)
analyses/svd_axes.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Surface the agent-level TF-IDF -> SVD style axes: per-axis top +/- terms (from V^T)
2
+ and explained-variance share. Matches the finding3 representation."""
3
+ import sqlite3, json
4
+ from collections import defaultdict
5
+ from pathlib import Path
6
+ import numpy as np
7
+ from sklearn.feature_extraction.text import TfidfVectorizer
8
+ from sklearn.decomposition import TruncatedSVD
9
+ RUNS=Path("runs")
10
+ OUT=Path("out/svd_axes.md")
11
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
12
+ K=30
13
+ docs=[];models=[]
14
+ for db in sorted(RUNS.glob("sweep_*.db")):
15
+ if any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
16
+ mp=str(db).replace(".db",".metadata.json")
17
+ if not Path(mp).exists():continue
18
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
19
+ except:continue
20
+ if not amm:continue
21
+ fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
22
+ if any(v is None for v in fam.values()):continue
23
+ try:
24
+ c=sqlite3.connect(db);posts=c.execute("SELECT user_id,content FROM post").fetchall();coms=c.execute("SELECT 1 FROM comment").fetchall();c.close()
25
+ except:continue
26
+ if len(coms)<200:continue
27
+ txt=defaultdict(list)
28
+ for u,cont in posts:
29
+ if u in fam and cont:txt[u].append(cont)
30
+ for u,tl in txt.items():
31
+ if tl:docs.append(" ".join(tl));models.append(fam[u])
32
+ print(len(docs),"agent docs")
33
+ vc=TfidfVectorizer(ngram_range=(1,2),analyzer="word",min_df=10,max_features=20000,sublinear_tf=True,norm="l2",stop_words="english",token_pattern=r"[A-Za-z'][A-Za-z']+")
34
+ X=vc.fit_transform(docs);vocab=np.array(vc.get_feature_names_out())
35
+ svd=TruncatedSVD(K,random_state=0);S=svd.fit_transform(X)
36
+ V=svd.components_ # K x n_terms (= V^T rows are axes)
37
+ evr=svd.explained_variance_ratio_
38
+ models=np.array(models)
39
+ o=[f"# SVD style axes ({len(docs)} agent docs, {X.shape[1]} terms, K={K})\n",
40
+ f"Cumulative explained variance (top {K}): {evr.sum()*100:.1f}%\n",
41
+ "| axis | EV% | top +terms | top -terms | model loading (mean axis score, high->low) |","|---|---|---|---|---|"]
42
+ for k in range(12):
43
+ w=V[k];pos=vocab[np.argsort(w)[::-1][:6]];neg=vocab[np.argsort(w)[:6]]
44
+ ml={m:S[models==m,k].mean() for m in ["gpt-oss","Qwen","GLM-4","Mag","Gemma"]}
45
+ order=sorted(ml,key=ml.get,reverse=True)
46
+ mls=", ".join(f"{m}{ml[m]:+.2f}" for m in order)
47
+ o.append(f"| {k+1} | {evr[k]*100:.1f} | {', '.join(pos)} | {', '.join(neg)} | {mls} |")
48
+ OUT.write_text("\n".join(o)+"\n");print("\n".join(o));print("wrote",OUT)
analyses/swap_cpp.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled gpt-oss -> Magistral swap: matched run-pairs in the same seed whose
2
+ persona->model map is identical EXCEPT gpt-oss and Magistral are swapped. For the
3
+ personas that flip, compare comments-per-post under gpt-oss vs under Magistral."""
4
+ import sqlite3, json, re
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ import numpy as np
8
+ RUNS=Path("runs");TET=RUNS/"tetratic"
9
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
10
+ def seed_of(name):
11
+ m=re.search(r"_s(\d+)",name) or re.search(r"_s(\d+)_r",name)
12
+ m=re.search(r"s(\d+)",name); return m.group(1) if m else None
13
+ def load(db,tet=False):
14
+ base=db.stem
15
+ if tet and (TET/f"{base}_checkpoint.json").exists():return None
16
+ mp=str(db).replace(".db",".metadata.json")
17
+ if not Path(mp).exists():return None
18
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
19
+ except:return None
20
+ if not amm:return None
21
+ fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
22
+ if any(v is None for v in fam.values()):return None
23
+ try:
24
+ c=sqlite3.connect(db);posts=c.execute("SELECT post_id,user_id FROM post").fetchall();coms=c.execute("SELECT post_id,user_id FROM comment").fetchall();users=dict(c.execute("SELECT user_id,user_name FROM user").fetchall());c.close()
25
+ except:return None
26
+ if len(coms)<100:return None
27
+ owner={p:u for p,u in posts};ind=defaultdict(int);npost=defaultdict(int)
28
+ for p,cu in coms:
29
+ o=owner.get(p)
30
+ if o in fam and o!=cu:ind[o]+=1
31
+ for p,u in posts:
32
+ if u in fam:npost[u]+=1
33
+ # per user_id: model, persona, cpp
34
+ rec={}
35
+ for u in fam:
36
+ if npost[u]>=2:rec[u]={"model":fam[u],"persona":users.get(u,f"u{u}"),"cpp":ind[u]/npost[u]}
37
+ return {"seed":re.search(r"s(\d+)",base).group(1),"name":base,"rec":rec}
38
+
39
+ runs=[]
40
+ for db in sorted(RUNS.glob("sweep_*.db")):
41
+ if any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
42
+ r=load(db);
43
+ if r:runs.append(r)
44
+ for db in sorted(TET.glob("tetra_s*_r*.db")):
45
+ r=load(db,tet=True)
46
+ if r:runs.append(r)
47
+ print(len(runs),"runs loaded")
48
+ byseed=defaultdict(list)
49
+ for r in runs:byseed[r["seed"]].append(r)
50
+
51
+ oss_vals=[];mag_vals=[];npairs=0;nflips=0
52
+ for seed,rs in byseed.items():
53
+ for i in range(len(rs)):
54
+ for j in range(i+1,len(rs)):
55
+ A,B=rs[i]["rec"],rs[j]["rec"]
56
+ shared=set(A)&set(B)
57
+ if len(shared)<10:continue
58
+ # require same persona per shared slot, and model identical except oss<->mag
59
+ ok=True;flips=[]
60
+ for u in shared:
61
+ if A[u]["persona"]!=B[u]["persona"]:ok=False;break
62
+ ma,mb=A[u]["model"],B[u]["model"]
63
+ if ma==mb:continue
64
+ if {ma,mb}=={"gpt-oss","Mag"}:flips.append(u)
65
+ else:ok=False;break
66
+ if not ok or not flips:continue
67
+ npairs+=1
68
+ for u in flips:
69
+ oss=A[u] if A[u]["model"]=="gpt-oss" else B[u]
70
+ mag=A[u] if A[u]["model"]=="Mag" else B[u]
71
+ oss_vals.append(oss["cpp"]);mag_vals.append(mag["cpp"]);nflips+=1
72
+ o=np.array(oss_vals);m=np.array(mag_vals)
73
+ print(f"matched swap pairs: {npairs}; flipped persona-observations: {nflips}")
74
+ print(f"mean CPP powered by gpt-oss: {o.mean():.2f}")
75
+ print(f"mean CPP powered by Magistral: {m.mean():.2f}")
76
+ print(f"drop: {100*(o.mean()-m.mean())/o.mean():.0f}% fewer CPP under Magistral")
77
+ # paired (same persona,pair) drop
78
+ d=(o-m)
79
+ print(f"paired mean drop: {d.mean():.2f} CPP ({100*d.mean()/o.mean():.0f}%); median paired drop {np.median(d):.2f}")
analyses/temporal_dynamics.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ H temporal dynamics analysis: decay, rotation stability, seed stability.
3
+
4
+ Splits each simulation's comment history into quartiles by comment_id and
5
+ computes directed-pair homophily H_{src->dst} per quartile. Aggregates across
6
+ runs to characterize each model's temporal signature (stable attractor, transient
7
+ attractor, delayed attractor, repeller), and measures rotation/seed stability
8
+ of the temporal trajectories.
9
+
10
+ Configuration:
11
+ RUNS_DIR — directory containing sweep_*.db files (env var or --runs-dir)
12
+
13
+ Usage:
14
+ python temporal_dynamics.py # dyadic decay (all targets)
15
+ python temporal_dynamics.py --triadic # triadic decay
16
+ python temporal_dynamics.py --target gpt-oss # specific target only
17
+ python temporal_dynamics.py --runs-dir /path/to/runs
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import sqlite3
24
+ from collections import defaultdict
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+
29
+
30
+ SHORT = {
31
+ 'Qwen/Qwen3-32B': 'Qwen',
32
+ 'openai/gpt-oss-20b': 'gpt-oss',
33
+ 'mistralai/Magistral-Small-2509': 'Mag',
34
+ 'zai-org/GLM-4-32B-0414': 'GLM-4',
35
+ 'google/gemma-4-31B-it': 'Gemma',
36
+ }
37
+
38
+ ALL_TARGETS = ['gpt-oss', 'Qwen', 'Mag', 'GLM-4', 'Gemma']
39
+
40
+
41
+ def H_in_window(db_path: Path, cmin: int, cmax: int) -> dict | None:
42
+ """Compute H for comments with comment_id in [cmin, cmax)."""
43
+ meta = str(db_path).replace('.db', '.metadata.json')
44
+ if not Path(meta).exists():
45
+ return None
46
+ try:
47
+ amm = json.load(open(meta)).get('agent_model_map', {})
48
+ uf = {int(k)+1: SHORT.get(v['model'], '?') for k, v in amm.items()}
49
+ except Exception:
50
+ return None
51
+ fc = defaultdict(int)
52
+ for fam in uf.values():
53
+ fc[fam] += 1
54
+ n = sum(fc.values())
55
+ conn = sqlite3.connect(db_path)
56
+ comments = conn.execute(
57
+ f'SELECT c.user_id, p.user_id FROM comment c JOIN post p ON c.post_id=p.post_id '
58
+ f'WHERE c.user_id!=p.user_id AND c.comment_id >= {cmin} AND c.comment_id < {cmax}'
59
+ ).fetchall()
60
+ conn.close()
61
+ ec = defaultdict(int)
62
+ for cu, pu in comments:
63
+ sf, df = uf.get(cu), uf.get(pu)
64
+ if sf and df:
65
+ ec[(sf, df)] += 1
66
+ total = sum(ec.values())
67
+ if total < 5:
68
+ return None
69
+ H = {}
70
+ for s in fc:
71
+ for d in fc:
72
+ exp = (fc[s]/n) * ((fc[d] - (1 if s == d else 0)) / (n-1))
73
+ if exp > 0:
74
+ H[(s, d)] = ec.get((s, d), 0) / total / exp - 1
75
+ return H
76
+
77
+
78
+ def trajectory(db_path: Path, target: str, n_bins: int = 4) -> list | None:
79
+ """Return list of incoming-to-target mean H per quartile."""
80
+ conn = sqlite3.connect(db_path)
81
+ max_id = conn.execute('SELECT MAX(comment_id) FROM comment').fetchone()[0]
82
+ conn.close()
83
+ if max_id is None or max_id < 40:
84
+ return None
85
+ bs = max_id // n_bins
86
+ traj = []
87
+ for i in range(n_bins):
88
+ lo = i*bs + 1
89
+ hi = (i+1)*bs + 1 if i < n_bins-1 else max_id + 1
90
+ H = H_in_window(db_path, lo, hi)
91
+ if H is None:
92
+ traj.append(None)
93
+ continue
94
+ inc = [v for (s, d), v in H.items() if d == target and s != target]
95
+ traj.append(np.mean(inc) if inc else None)
96
+ return traj
97
+
98
+
99
+ def discover_dyadic_runs(runs_dir: Path, target: str | None = None) -> list:
100
+ """Return list of (db_path, group_A_model, partner, seed) for dyadic runs."""
101
+ out = []
102
+ for db in runs_dir.glob('sweep_*.db'):
103
+ if 'tri_' in db.name or 'pilot_' in db.name:
104
+ continue
105
+ meta = str(db).replace('.db', '.metadata.json')
106
+ if not Path(meta).exists():
107
+ continue
108
+ try:
109
+ amm = json.load(open(meta)).get('agent_model_map', {})
110
+ uid_model = {int(k): SHORT.get(v['model']) for k, v in amm.items()}
111
+ except Exception:
112
+ continue
113
+ if any(v is None for v in uid_model.values()):
114
+ continue
115
+ fams = set(uid_model.values())
116
+ if len(fams) != 2:
117
+ continue
118
+ if target and target not in fams:
119
+ continue
120
+ group_A = uid_model.get(0)
121
+ seed = next((s for s in [42, 137, 271, 314, 999] if f'_s{s}.' in db.name), None)
122
+ if seed is None:
123
+ continue
124
+ partner = (fams - {group_A}).pop()
125
+ out.append((str(db), group_A, partner, seed))
126
+ return out
127
+
128
+
129
+ def discover_triadic_runs(runs_dir: Path, target: str | None = None) -> list:
130
+ """Return list of (db_path, group_A_model, triplet_tuple, seed) for triadic runs."""
131
+ out = []
132
+ for db in runs_dir.glob('sweep_tri_*.db'):
133
+ meta = str(db).replace('.db', '.metadata.json')
134
+ if not Path(meta).exists():
135
+ continue
136
+ try:
137
+ amm = json.load(open(meta)).get('agent_model_map', {})
138
+ uid_model = {int(k): SHORT.get(v['model']) for k, v in amm.items()}
139
+ except Exception:
140
+ continue
141
+ if any(v is None for v in uid_model.values()):
142
+ continue
143
+ fams = sorted(set(uid_model.values()))
144
+ if len(fams) != 3:
145
+ continue
146
+ if target and target not in fams:
147
+ continue
148
+ group_A = uid_model.get(0)
149
+ seed = next((s for s in [42, 271, 999] if f'_s{s}.' in db.name), None)
150
+ if seed is None:
151
+ continue
152
+ out.append((str(db), group_A, tuple(fams), seed))
153
+ return out
154
+
155
+
156
+ def dyadic_stability_report(runs_dir: Path, target: str):
157
+ """Per-pair Q0..Q3 trajectory + rotation + seed stability for a target family."""
158
+ runs = discover_dyadic_runs(runs_dir, target=target)
159
+ by_pair_ord = defaultdict(lambda: defaultdict(list))
160
+ for db, group_A, partner, seed in runs:
161
+ traj = trajectory(Path(db), target)
162
+ if traj is None or any(v is None for v in traj):
163
+ continue
164
+ ordering = 'target_A' if group_A == target else 'partner_A'
165
+ by_pair_ord[partner][ordering].append((seed, traj))
166
+
167
+ print(f"\n{'='*78}")
168
+ print(f"DYADIC stability for incoming-to-{target}")
169
+ print(f"{'='*78}")
170
+ for partner in sorted(by_pair_ord):
171
+ print(f"\n {target} x {partner}")
172
+ order_means = {}
173
+ for ord_name, lst in by_pair_ord[partner].items():
174
+ if not lst:
175
+ continue
176
+ trajs = np.array([t for _, t in lst])
177
+ order_means[ord_name] = trajs.mean(axis=0)
178
+ print(f" [{ord_name}] n={len(trajs)} seeds | "
179
+ f"Q0..Q3: {' '.join(f'{v:+.2f}' for v in trajs.mean(axis=0))} | "
180
+ f"seed-SD: {' '.join(f'{s:.2f}' for s in trajs.std(axis=0))}")
181
+ if len(order_means) == 2:
182
+ keys = list(order_means.keys())
183
+ spreads = [abs(order_means[keys[0]][q] - order_means[keys[1]][q]) for q in range(4)]
184
+ print(f" rotation spread per Q: {' '.join(f'{s:.2f}' for s in spreads)} "
185
+ f"max={max(spreads):.2f}")
186
+
187
+
188
+ def triadic_stability_report(runs_dir: Path, target: str):
189
+ """Per-triplet Q0..Q3 trajectory + rotation + seed stability for a target family."""
190
+ runs = discover_triadic_runs(runs_dir, target=target)
191
+ by_trip_ord = defaultdict(lambda: defaultdict(list))
192
+ for db, group_A, trip, seed in runs:
193
+ if target not in trip:
194
+ continue
195
+ traj = trajectory(Path(db), target)
196
+ if traj is None or any(v is None for v in traj):
197
+ continue
198
+ by_trip_ord[trip][group_A].append((seed, traj))
199
+
200
+ print(f"\n{'='*78}")
201
+ print(f"TRIADIC stability for incoming-to-{target}")
202
+ print(f"{'='*78}")
203
+ for trip in sorted(by_trip_ord):
204
+ if sum(len(v) for v in by_trip_ord[trip].values()) < 3:
205
+ continue
206
+ print(f"\n Triplet: {' + '.join(trip)}")
207
+ per_ord_mean = {}
208
+ for grpA, lst in by_trip_ord[trip].items():
209
+ if not lst:
210
+ continue
211
+ trajs = np.array([t for _, t in lst])
212
+ per_ord_mean[grpA] = trajs.mean(axis=0)
213
+ print(f" [group-A={grpA}] n={len(trajs)} seeds | "
214
+ f"Q0..Q3: {' '.join(f'{v:+.2f}' for v in trajs.mean(axis=0))} | "
215
+ f"seed-SD: {' '.join(f'{s:.2f}' for s in trajs.std(axis=0))}")
216
+ if len(per_ord_mean) >= 2:
217
+ spreads = [max(t[q] for t in per_ord_mean.values()) -
218
+ min(t[q] for t in per_ord_mean.values())
219
+ for q in range(4)]
220
+ print(f" rotation spread per Q: {' '.join(f'{s:.2f}' for s in spreads)} "
221
+ f"max={max(spreads):.2f}")
222
+
223
+
224
+ def main():
225
+ parser = argparse.ArgumentParser(description=__doc__)
226
+ parser.add_argument('--runs-dir', default=os.environ.get("RUNS_DIR", "./runs"),
227
+ help="Directory containing sweep_*.db files.")
228
+ parser.add_argument('--triadic', action='store_true',
229
+ help="Run triadic stability report instead of dyadic.")
230
+ parser.add_argument('--target', default=None,
231
+ help="Restrict to one model family (e.g. gpt-oss). Default: all.")
232
+ args = parser.parse_args()
233
+
234
+ runs_dir = Path(args.runs_dir)
235
+ targets = [args.target] if args.target else ALL_TARGETS
236
+
237
+ for t in targets:
238
+ if args.triadic:
239
+ triadic_stability_report(runs_dir, t)
240
+ else:
241
+ dyadic_stability_report(runs_dir, t)
242
+
243
+
244
+ if __name__ == '__main__':
245
+ main()
analyses/tetradic_recompute_H.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recompute four-way H stats over all COMPLETE tetratic runs (no checkpoint file).
2
+ Persistent: re-run anytime. Prints per-model incoming H + per-seed H->gpt-oss + counts."""
3
+ import sqlite3, json
4
+ from collections import defaultdict
5
+ from pathlib import Path
6
+ import numpy as np
7
+ HERE = Path(__file__).parent
8
+ SHORT = {"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss",
9
+ "mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4"}
10
+ perH = defaultdict(list); byseed = defaultdict(list); runs = []
11
+ for db in sorted(HERE.glob("tetra_s*_r*.db")):
12
+ base = db.stem
13
+ if (HERE / f"{base}_checkpoint.json").exists():
14
+ continue # incomplete
15
+ mp = str(db).replace(".db", ".metadata.json")
16
+ if not Path(mp).exists():
17
+ continue
18
+ seed = base.split("_")[1]
19
+ fam = {int(k)+1: SHORT.get(v["model"]) for k, v in json.load(open(mp))["agent_model_map"].items()}
20
+ try:
21
+ c = sqlite3.connect(db)
22
+ posts = c.execute("SELECT post_id,user_id FROM post").fetchall()
23
+ coms = c.execute("SELECT post_id,user_id FROM comment").fetchall(); c.close()
24
+ except Exception:
25
+ continue
26
+ owner = {p: u for p, u in posts}; F = sorted(set(fam.values()))
27
+ nf = {f: sum(1 for v in fam.values() if v == f) for f in F}; ntot = sum(nf.values())
28
+ edges = [(fam[cu], fam[owner[p]]) for p, cu in coms
29
+ if owner.get(p) and owner[p] != cu and cu in fam and owner[p] in fam]
30
+ tot = len(edges)
31
+ if tot < 100:
32
+ continue
33
+ obs = defaultdict(int)
34
+ for x, y in edges: obs[(x, y)] += 1
35
+ runs.append(base)
36
+ for Y in F:
37
+ h = np.mean([obs.get((X, Y), 0)/tot/((nf[X]/ntot)*((nf[Y])/(ntot-1)))-1 for X in F if X != Y])
38
+ perH[Y].append(h)
39
+ if Y == "gpt-oss": byseed[seed].append(h)
40
+
41
+ print(f"=== tetratic H over {len(runs)} complete four-way runs ===")
42
+ print(f"runs: {sorted(runs)}")
43
+ print(f"{'model':8s} {'meanH':>7} {'sd':>6} {'min':>7} {'max':>7} n")
44
+ for m in ["gpt-oss", "Qwen", "GLM-4", "Mag"]:
45
+ v = np.array(perH[m]) if perH[m] else np.array([np.nan])
46
+ print(f"{m:8s} {v.mean():+7.2f} {v.std():6.2f} {v.min():+7.2f} {v.max():+7.2f} {len(perH[m])}")
47
+ print("H->gpt-oss by seed:")
48
+ for s in sorted(byseed):
49
+ v = byseed[s]; print(f" seed {s:5s}: {np.mean(v):+.2f} (n={len(v)})")
analyses/tetradic_results.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tetradic (four-way) results: pooled 4x4 H heatmap + descriptive stats + variance decomposition.
2
+ Over all COMPLETE tetradic runs (no checkpoint file). Persistent; re-run as more land.
3
+ Outputs:
4
+ - figures/fig_h_tetradic.png (heatmap, style matched to plot_matrices.py)
5
+ - _paper/analyses/tetradic_results.md (numbers to hand to DR)
6
+ """
7
+ import sqlite3, json
8
+ from collections import defaultdict
9
+ from pathlib import Path
10
+ import numpy as np
11
+ import matplotlib; matplotlib.use("Agg")
12
+ import matplotlib.pyplot as plt
13
+ from matplotlib.font_manager import FontProperties, fontManager
14
+
15
+ HERE = Path(__file__).parent
16
+ FIGDIR = Path(".")
17
+ OUTMD = Path("out/tetradic_results.md")
18
+ SHORT = {"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss",
19
+ "mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4"}
20
+ MODELS = ["GLM-4","Mag","Qwen","gpt-oss"]
21
+ try:
22
+ for ttf in (Path.home()/"fonts").rglob("*.ttf"): fontManager.addfont(str(ttf))
23
+ FAM = "Ubuntu Mono"
24
+ except Exception:
25
+ FAM = "monospace"
26
+
27
+ perH = defaultdict(list) # incoming H per target across runs
28
+ matruns = [] # list of 4x4 H matrices
29
+ lead = last = 0; rho = []; nrun = 0
30
+ agents = [] # for variance decomposition
31
+
32
+ for db in sorted(HERE.glob("tetra_s*_r*.db")):
33
+ base = db.stem
34
+ if (HERE/f"{base}_checkpoint.json").exists(): continue
35
+ mp = str(db).replace(".db",".metadata.json")
36
+ if not Path(mp).exists(): continue
37
+ fam = {int(k)+1: SHORT.get(v["model"]) for k,v in json.load(open(mp))["agent_model_map"].items()}
38
+ if any(v is None for v in fam.values()): continue
39
+ try:
40
+ c = sqlite3.connect(db)
41
+ posts = c.execute("SELECT post_id,user_id FROM post").fetchall()
42
+ coms = c.execute("SELECT post_id,user_id FROM comment").fetchall()
43
+ users = dict(c.execute("SELECT user_id,user_name FROM user").fetchall()); c.close()
44
+ except Exception: continue
45
+ owner = {p:u for p,u in posts}; F = sorted(set(fam.values()))
46
+ nf = {f: sum(1 for v in fam.values() if v==f) for f in F}; ntot = sum(nf.values())
47
+ edges = [(fam[cu], fam[owner[p]]) for p,cu in coms
48
+ if owner.get(p) and owner[p]!=cu and cu in fam and owner[p] in fam]
49
+ tot = len(edges)
50
+ if tot < 100: continue
51
+ nrun += 1
52
+ obs = defaultdict(int)
53
+ for x,y in edges: obs[(x,y)] += 1
54
+ # 4x4 matrix (rows=source/commenter, cols=target/author)
55
+ Mx = np.full((4,4), np.nan)
56
+ for i,X in enumerate(MODELS):
57
+ for j,Y in enumerate(MODELS):
58
+ exp = (nf[X]/ntot)*((nf[Y]-(1 if X==Y else 0))/(ntot-1))
59
+ if exp>0: Mx[i,j] = obs.get((X,Y),0)/tot/exp - 1
60
+ matruns.append(Mx)
61
+ # incoming H per target (mean over X!=Y)
62
+ for Y in MODELS:
63
+ perH[Y].append(np.nanmean([Mx[i,MODELS.index(Y)] for i,X in enumerate(MODELS) if X!=Y]))
64
+ # in-degree per agent + lead/last + rho
65
+ ind = defaultdict(int)
66
+ for p,cu in coms:
67
+ o = owner.get(p)
68
+ if o in fam and o!=cu: ind[o]+=1
69
+ fam_in = defaultdict(list)
70
+ for u,f in fam.items(): fam_in[f].append(ind.get(u,0))
71
+ mean_in = {f: np.mean(v) for f,v in fam_in.items()}
72
+ if max(mean_in, key=mean_in.get)=="gpt-oss": lead+=1
73
+ if min(mean_in, key=mean_in.get)=="Mag": last+=1
74
+ tot_in = sum(sum(v) for v in fam_in.values())
75
+ share = sum(fam_in["gpt-oss"])/tot_in if tot_in else 0
76
+ rho.append(share/(nf["gpt-oss"]/ntot))
77
+ for u,f in fam.items():
78
+ agents.append({"run":base,"model":f,"persona":users.get(u,f"u{u}"),"indeg":ind.get(u,0)})
79
+
80
+ # ---- pooled matrix + heatmap ----
81
+ Mpool = np.nanmean(np.stack(matruns), axis=0)
82
+ fig, ax = plt.subplots(figsize=(4.2,3.6))
83
+ vmax = np.nanmax(np.abs(Mpool))
84
+ im = ax.imshow(Mpool, cmap="RdBu_r", vmin=-vmax, vmax=vmax)
85
+ ax.set_xticks(range(4)); ax.set_yticks(range(4))
86
+ ax.set_xticklabels(MODELS, fontproperties=FontProperties(family=FAM,size=9), rotation=30, ha="right")
87
+ ax.set_yticklabels(MODELS, fontproperties=FontProperties(family=FAM,size=9))
88
+ ax.set_xlabel("post author (target)", fontproperties=FontProperties(family=FAM,size=9))
89
+ ax.set_ylabel("commenter (source)", fontproperties=FontProperties(family=FAM,size=9))
90
+ for i in range(4):
91
+ for j in range(4):
92
+ v = Mpool[i,j]
93
+ ax.text(j,i,f"{v:+.2f}",ha="center",va="center",
94
+ fontproperties=FontProperties(family=FAM,size=8),
95
+ color="white" if abs(v)>0.55*vmax else "black")
96
+ cb = fig.colorbar(im, fraction=0.046, pad=0.04); cb.ax.tick_params(labelsize=7)
97
+ ax.set_title(f"Four-way $H_{{X\\to Y}}$ (pooled, n={nrun} runs)",
98
+ fontproperties=FontProperties(family=FAM,size=10))
99
+ fig.tight_layout(); fig.savefig(FIGDIR/"fig_h_tetradic.png", dpi=300, bbox_inches="tight")
100
+ print("wrote", FIGDIR/"fig_h_tetradic.png")
101
+
102
+ # ---- variance decomposition (in-sample R^2, matches tab:ols_decomp convention) ----
103
+ y = np.array([a["indeg"] for a in agents], float)
104
+ def dummies(keys):
105
+ levels = sorted(set(keys)); idx = {l:i for i,l in enumerate(levels)}
106
+ D = np.zeros((len(keys), len(levels)))
107
+ for r,k in enumerate(keys): D[r, idx[k]] = 1
108
+ return D[:,1:] # drop one for intercept
109
+ def r2(*blocks):
110
+ blocks = [b for b in blocks if b is not None and b.shape[1]>0]
111
+ X = np.column_stack([np.ones(len(y))] + blocks) if blocks else np.ones((len(y),1))
112
+ b,*_ = np.linalg.lstsq(X, y, rcond=None); pred = X@b
113
+ return 1 - ((y-pred)**2).sum()/((y-y.mean())**2).sum()
114
+ P = dummies([a["persona"] for a in agents])
115
+ Mod = dummies([a["model"] for a in agents])
116
+ R = dummies([a["run"] for a in agents])
117
+ ossind = np.array([[1.0 if a["model"]=="gpt-oss" else 0.0] for a in agents])
118
+ vd = {"persona_only":r2(P), "model_only":r2(Mod), "oss_only":r2(ossind),
119
+ "run_only":r2(R), "persona+model":r2(P,Mod), "persona+run":r2(P,R), "full":r2(P,Mod,R)}
120
+ dmodel = vd["full"] - vd["persona+run"]
121
+
122
+ # ---- write md ----
123
+ o = [f"# Tetradic (four-way) results — {nrun} complete runs\n",
124
+ "## Incoming H per model (mean over commenter families, across runs)\n",
125
+ "| model | mean H | SD | min | max |", "|---|---:|---:|---:|---:|"]
126
+ for m in ["gpt-oss","Qwen","GLM-4","Mag"]:
127
+ v = np.array(perH[m]); o.append(f"| {m} | {v.mean():+.2f} | {v.std():.2f} | {v.min():+.2f} | {v.max():+.2f} |")
128
+ o += [f"\n- gpt-oss is the **most-commented family in {lead}/{nrun} runs** ({100*lead/nrun:.0f}%).",
129
+ f"- Magistral is the **least-commented in {last}/{nrun} runs** ({100*last/nrun:.0f}%).",
130
+ f"- gpt-oss over-representation rho = comment-share / fair-share: **mean {np.mean(rho):.2f}, median {np.median(rho):.2f}**.",
131
+ "\n## Variance decomposition (per-agent raw in-degree, in-sample R^2)\n",
132
+ "| block | R^2 |", "|---|---:|"]
133
+ for k in ["persona_only","model_only","oss_only","run_only","persona+model","persona+run","full"]:
134
+ o.append(f"| {k.replace('_',' ')} | {vd[k]:.3f} |")
135
+ o.append(f"| **Delta R^2 model** (full - persona+run) | **{dmodel:+.3f}** |")
136
+ o.append(f"\nn agents = {len(agents)}. Compare dyad Delta R^2_model +.044, triad +.071.")
137
+ OUTMD.write_text("\n".join(o)+"\n"); print("\n".join(o)); print("wrote", OUTMD)
analyses/variance_cpp.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Finding 2 redone on comments-per-post (CPP = in-degree/n_posts).
2
+ Decomposition (dy/tri/tet), LOMO (dy/tri), totals + absolute components,
3
+ and length-residualized per-model attractiveness for ALL models."""
4
+ import sqlite3, json
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ import numpy as np
8
+ RUNS=Path("runs");TET=RUNS/"tetratic"
9
+ SHORT={"Qwen/Qwen3-32B":"Qwen","openai/gpt-oss-20b":"gpt-oss","mistralai/Magistral-Small-2509":"Mag","zai-org/GLM-4-32B-0414":"GLM-4","google/gemma-4-31B-it":"Gemma"}
10
+ def load(globpat,tet=False):
11
+ out=[]
12
+ for db in sorted(globpat):
13
+ if not tet and any(x in db.name for x in ["archive","olm","hermes","glm47","pilot_","snapshot","qwq"]):continue
14
+ if tet and (TET/f"{db.stem}_checkpoint.json").exists():continue
15
+ mp=str(db).replace(".db",".metadata.json")
16
+ if not Path(mp).exists():continue
17
+ try:amm=json.load(open(mp)).get("agent_model_map",{})
18
+ except:continue
19
+ if not amm:continue
20
+ # OFF-BY-ONE FIX: DBs are 0-indexed (user_id and agent_model_map keys both start at MIN);
21
+ # original "+1" dropped agent 0 and mislabeled the first agent of each model-block.
22
+ # fam={int(k)+1:SHORT.get(v["model"]) for k,v in amm.items()}
23
+ umin=min(int(k) for k in amm)
24
+ fam={int(k)+umin:SHORT.get(v["model"]) for k,v in amm.items()}
25
+ if any(v is None for v in fam.values()):continue
26
+ try:
27
+ c=sqlite3.connect(db);posts=c.execute("SELECT post_id,user_id,content FROM post").fetchall();coms=c.execute("SELECT post_id,user_id FROM comment").fetchall();users=dict(c.execute("SELECT user_id,user_name FROM user").fetchall());c.close()
28
+ except:continue
29
+ if len(coms)<(100 if tet else 200):continue
30
+ owner={p:u for p,u,_ in posts};ind=defaultdict(int);npost=defaultdict(int);nw=defaultdict(int)
31
+ for p,cu in coms:
32
+ o=owner.get(p)
33
+ if o in fam and o!=cu:ind[o]+=1
34
+ for p,u,cont in posts:
35
+ if u in fam and cont:npost[u]+=1;nw[u]+=len(cont.split())
36
+ F=sorted(set(fam.values()));reg={2:"dyad",3:"tri",4:"tet"}.get(len(F))
37
+ for u in fam:
38
+ if npost[u]>=2:
39
+ out.append({"run":db.stem,"model":fam[u],"persona":users.get(u,f"u{u}"),"cpp":ind[u]/npost[u],
40
+ "meanlen":nw[u]/npost[u],"net":F})
41
+ return out
42
+ rows=load(RUNS.glob("sweep_*.db"))+load(TET.glob("tetra_s*_r*.db"),tet=True)
43
+ def dum(keys):
44
+ lv=sorted(set(map(str,keys)));idx={l:i for i,l in enumerate(lv)};D=np.zeros((len(keys),len(lv)))
45
+ for r,k in enumerate(keys):D[r,idx[str(k)]]=1
46
+ return D[:,1:]
47
+ def r2(y,*B):
48
+ B=[b for b in B if b is not None and b.shape[1]>0];X=np.column_stack([np.ones(len(y))]+B) if B else np.ones((len(y),1))
49
+ b,*_=np.linalg.lstsq(X,y,rcond=None);p=X@b;return 1-((y-p)**2).sum()/((y-y.mean())**2).sum()
50
+ def partner(r):return frozenset(m for m in r["net"] if m!=r["model"])
51
+ print("=== Finding 2 on CPP: decomposition ===")
52
+ print(f"{'block':14s} {'dy':>7} {'tri':>7} {'tet':>7}")
53
+ def col(fn):
54
+ return [fn([r for r in rows if {'dyad':'dyad','tri':'tri','tet':'tet'}[r_reg:=({2:'dyad',3:'tri',4:'tet'}[len(r['net'])])]==m]) for m in ['dyad','tri','tet']]
55
+ def sub(mode):return [r for r in rows if {2:'dyad',3:'tri',4:'tet'}[len(r['net'])]==mode]
56
+ def line(lab,fn):
57
+ print(f"{lab:14s} "+" ".join(f"{fn(sub(m)):7.3f}" for m in ['dyad','tri','tet']))
58
+ P=lambda s:dum([r['persona']for r in s]);M=lambda s:dum([r['model']for r in s])
59
+ R=lambda s:dum([r['run']for r in s]);O=lambda s:np.array([[1.0 if r['model']=='gpt-oss' else 0]for r in s])
60
+ SEL=lambda s:np.column_stack([M(s),dum([partner(r)for r in s])])
61
+ Y=lambda s:np.array([r['cpp']for r in s])
62
+ line("persona",lambda s:r2(Y(s),P(s)))
63
+ line("model(own)",lambda s:r2(Y(s),M(s)))
64
+ line("model-selection",lambda s:r2(Y(s),SEL(s)))
65
+ line("gpt-oss ind",lambda s:r2(Y(s),O(s)))
66
+ line("run",lambda s:r2(Y(s),R(s)))
67
+ line("persona+model",lambda s:r2(Y(s),P(s),M(s)))
68
+ line("persona+run",lambda s:r2(Y(s),P(s),R(s)))
69
+ line("full",lambda s:r2(Y(s),P(s),M(s),R(s)))
70
+ line("dR2_model",lambda s:r2(Y(s),P(s),M(s),R(s))-r2(Y(s),P(s),R(s)))
71
+ print("\ntotal CPP variance + absolute components (R^2 x total):")
72
+ for m in ['dyad','tri','tet']:
73
+ s=sub(m);y=Y(s);tot=y.var()
74
+ print(f" {m}: n={len(s)} totalvar={tot:.3f} persona={r2(y,P(s))*tot:.3f} model-sel={r2(y,SEL(s))*tot:.3f} oss-ind={r2(y,O(s))*tot:.3f}")
75
+ print("\n=== LOMO on CPP (dy/tri): persona / own / selection ===")
76
+ for excl in ["baseline","Qwen","gpt-oss","Mag","GLM-4","Gemma"]:
77
+ for m in ['dyad','tri']:
78
+ s=[r for r in sub(m) if excl=="baseline" or excl not in r['net']]
79
+ if len(s)<50:continue
80
+ y=Y(s);print(f" {excl:8s} {m:5s} n={len(s):4d} persona={r2(y,P(s))*100:5.1f}% own={r2(y,M(s))*100:5.1f}% sel={r2(y,SEL(s))*100:5.1f}%")
81
+ print("\n=== length-residualized CPP attractiveness, ALL models, by regime ===")
82
+ def wz(s,key):
83
+ o={};bd=defaultdict(list)
84
+ for r in s:bd[r['run']].append(r)
85
+ arr={}
86
+ vals=np.array([r[key]for r in s]);run=[r['run']for r in s]
87
+ z=np.zeros(len(s))
88
+ for rr in set(run):
89
+ idx=[i for i,x in enumerate(run) if x==rr];v=vals[idx];m=v.mean();sd=v.std() or 1
90
+ for i in idx:z[i]=(vals[i]-m)/sd
91
+ return z
92
+ for m in ['dyad','tri','tet']:
93
+ s=sub(m);cz=wz(s,'cpp');lz=wz(s,'meanlen');b=np.polyfit(lz,cz,1)[0];res=cz-b*lz
94
+ md=np.array([r['model']for r in s])
95
+ print(f" {m} (length slope {b:+.2f}):")
96
+ for mod in ["gpt-oss","Qwen","GLM-4","Mag","Gemma"]:
97
+ mm=md==mod
98
+ if mm.sum():print(f" {mod:8s} raw {cz[mm].mean():+.2f} len-adj {res[mm].mean():+.2f}")
data/MANIFEST.md ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Manifest — divsim paper runs
2
+
3
+ Reference data for all valid dyadic, triadic, and four-way runs used in the paper.
4
+ DBs live under `$RUNS_DIR` (dyadic/triadic as `sweep_*.db`; four-way under `$RUNS_DIR/tetradic/`).
5
+ They are **not** included in this bundle due to size (~200 GB total).
6
+
7
+ **Validity criteria:**
8
+ - Dyadic: ≥ 18 distinct commenter agents, ≥ 200 total comments
9
+ - Triadic: ≥ 26 distinct commenter agents, ≥ 200 total comments
10
+ - Four-way: 40 agents (10 per model), ≥ 200 comments, all four of {gpt-oss, Qwen, Magistral, GLM-4} present
11
+
12
+ **Run counts (current):** 100 dyadic + 89 triadic (five-model pool) + 24 four-way = 213 valid runs.
13
+
14
+ **Engagement metric:** the variance decomposition and content->engagement analyses use **comments per post**
15
+ (CPP = in-degree / number of posts), which removes the posting-volume exposure confound that inflates raw
16
+ in-degree. Analysis scripts use whichever runs are present under `$RUNS_DIR`.
17
+
18
+ ---
19
+
20
+ ## Dyadic runs
21
+ **Total valid runs: 100**
22
+
23
+ | Filename | Pair | Seed | n_comments | n_agents | size_bytes | mtime |
24
+ |----------|------|------|-----------|---------|------------|-------|
25
+ | `sweep_gem_gem_glm_s137.db` | GLM-4 × Gemma | 137 | 545 | 20 | 59256832 | 1779256940 |
26
+ | `sweep_gem_gem_glm_s271.db` | GLM-4 × Gemma | 271 | 564 | 20 | 67678208 | 1779259415 |
27
+ | `sweep_gem_gem_glm_s314.db` | GLM-4 × Gemma | 314 | 556 | 20 | 62390272 | 1779262424 |
28
+ | `sweep_gem_gem_glm_s42.db` | GLM-4 × Gemma | 42 | 561 | 20 | 65548288 | 1779253891 |
29
+ | `sweep_gem_gem_glm_s999.db` | GLM-4 × Gemma | 999 | 561 | 20 | 57278464 | 1779262942 |
30
+ | `sweep_gem_gem_mag_s137.db` | Gemma × Mag | 137 | 563 | 20 | 66887680 | 1779237487 |
31
+ | `sweep_gem_gem_mag_s271.db` | Gemma × Mag | 271 | 573 | 20 | 69795840 | 1779237563 |
32
+ | `sweep_gem_gem_mag_s314.db` | Gemma × Mag | 314 | 573 | 20 | 72994816 | 1779240779 |
33
+ | `sweep_gem_gem_mag_s42.db` | Gemma × Mag | 42 | 202 | 20 | 20865024 | 1779233607 |
34
+ | `sweep_gem_gem_mag_s999.db` | Gemma × Mag | 999 | 568 | 20 | 70995968 | 1779241344 |
35
+ | `sweep_gem_gem_oss_s137.db` | Gemma × gpt-oss | 137 | 558 | 20 | 81575936 | 1779289803 |
36
+ | `sweep_gem_gem_oss_s271.db` | Gemma × gpt-oss | 271 | 560 | 20 | 87035904 | 1779292575 |
37
+ | `sweep_gem_gem_oss_s314.db` | Gemma × gpt-oss | 314 | 565 | 20 | 84631552 | 1779292556 |
38
+ | `sweep_gem_gem_oss_s42.db` | Gemma × gpt-oss | 42 | 561 | 20 | 91570176 | 1779289808 |
39
+ | `sweep_gem_gem_oss_s999.db` | Gemma × gpt-oss | 999 | 550 | 20 | 77602816 | 1779296057 |
40
+ | `sweep_gem_gem_qwe_s137.db` | Gemma × Qwen | 137 | 536 | 20 | 56975360 | 1779238651 |
41
+ | `sweep_gem_gem_qwe_s271.db` | Gemma × Qwen | 271 | 566 | 20 | 60739584 | 1779242852 |
42
+ | `sweep_gem_gem_qwe_s314.db` | Gemma × Qwen | 314 | 554 | 20 | 58511360 | 1779244264 |
43
+ | `sweep_gem_gem_qwe_s42.db` | Gemma × Qwen | 42 | 568 | 20 | 61599744 | 1779238533 |
44
+ | `sweep_gem_gem_qwe_s999.db` | Gemma × Qwen | 999 | 560 | 20 | 63430656 | 1779247673 |
45
+ | `sweep_gem_glm_gem_s137.db` | GLM-4 × Gemma | 137 | 554 | 20 | 71245824 | 1779265322 |
46
+ | `sweep_gem_glm_gem_s271.db` | GLM-4 × Gemma | 271 | 560 | 20 | 66015232 | 1779267644 |
47
+ | `sweep_gem_glm_gem_s314.db` | GLM-4 × Gemma | 314 | 569 | 20 | 65216512 | 1779269154 |
48
+ | `sweep_gem_glm_gem_s42.db` | GLM-4 × Gemma | 42 | 568 | 20 | 64397312 | 1779264496 |
49
+ | `sweep_gem_glm_gem_s999.db` | GLM-4 × Gemma | 999 | 570 | 20 | 70668288 | 1779270025 |
50
+ | `sweep_gem_mag_gem_s137.db` | Gemma × Mag | 137 | 576 | 20 | 67174400 | 1779244801 |
51
+ | `sweep_gem_mag_gem_s271.db` | Gemma × Mag | 271 | 557 | 20 | 64151552 | 1779248268 |
52
+ | `sweep_gem_mag_gem_s314.db` | Gemma × Mag | 314 | 569 | 20 | 70443008 | 1779248674 |
53
+ | `sweep_gem_mag_gem_s42.db` | Gemma × Mag | 42 | 576 | 20 | 71020544 | 1779244365 |
54
+ | `sweep_gem_mag_gem_s999.db` | Gemma × Mag | 999 | 571 | 20 | 68837376 | 1779252081 |
55
+ | `sweep_gem_oss_gem_s137.db` | Gemma × gpt-oss | 137 | 550 | 20 | 72888320 | 1779702718 |
56
+ | `sweep_gem_oss_gem_s271.db` | Gemma × gpt-oss | 271 | 538 | 20 | 75186176 | 1779703920 |
57
+ | `sweep_gem_oss_gem_s314.db` | Gemma × gpt-oss | 314 | 570 | 20 | 86704128 | 1779702754 |
58
+ | `sweep_gem_oss_gem_s42.db` | Gemma × gpt-oss | 42 | 564 | 20 | 92504064 | 1779296113 |
59
+ | `sweep_gem_oss_gem_s999.db` | Gemma × gpt-oss | 999 | 563 | 20 | 76296192 | 1779702748 |
60
+ | `sweep_gem_qwe_gem_s137.db` | Gemma × Qwen | 137 | 562 | 20 | 60616704 | 1779252242 |
61
+ | `sweep_gem_qwe_gem_s271.db` | Gemma × Qwen | 271 | 555 | 20 | 54685696 | 1779252843 |
62
+ | `sweep_gem_qwe_gem_s314.db` | Gemma × Qwen | 314 | 569 | 20 | 62332928 | 1779257273 |
63
+ | `sweep_gem_qwe_gem_s42.db` | Gemma × Qwen | 42 | 568 | 20 | 63574016 | 1779248639 |
64
+ | `sweep_gem_qwe_gem_s999.db` | Gemma × Qwen | 999 | 562 | 20 | 60620800 | 1779257045 |
65
+ | `sweep_glm_mag_AB_s137.db` | GLM-4 × Mag | 137 | 568 | 20 | 66908160 | 1779153376 |
66
+ | `sweep_glm_mag_AB_s271.db` | GLM-4 × Mag | 271 | 576 | 20 | 69083136 | 1779153711 |
67
+ | `sweep_glm_mag_AB_s314.db` | GLM-4 × Mag | 314 | 561 | 20 | 70963200 | 1779152748 |
68
+ | `sweep_glm_mag_AB_s42.db` | GLM-4 × Mag | 42 | 569 | 20 | 70332416 | 1779151835 |
69
+ | `sweep_glm_mag_AB_s999.db` | GLM-4 × Mag | 999 | 575 | 20 | 64864256 | 1779153345 |
70
+ | `sweep_glm_mag_BA_s137.db` | GLM-4 × Mag | 137 | 566 | 20 | 66088960 | 1779153390 |
71
+ | `sweep_glm_mag_BA_s271.db` | GLM-4 × Mag | 271 | 564 | 20 | 65060864 | 1779153084 |
72
+ | `sweep_glm_mag_BA_s314.db` | GLM-4 × Mag | 314 | 569 | 20 | 64892928 | 1779153443 |
73
+ | `sweep_glm_mag_BA_s42.db` | GLM-4 × Mag | 42 | 560 | 20 | 62205952 | 1779151252 |
74
+ | `sweep_glm_mag_BA_s999.db` | GLM-4 × Mag | 999 | 576 | 20 | 64098304 | 1779152861 |
75
+ | `sweep_glm_oss_AB_s137.db` | GLM-4 × gpt-oss | 137 | 538 | 20 | 68145152 | 1779125984 |
76
+ | `sweep_glm_oss_AB_s271.db` | GLM-4 × gpt-oss | 271 | 528 | 20 | 65155072 | 1779131809 |
77
+ | `sweep_glm_oss_AB_s314.db` | GLM-4 × gpt-oss | 314 | 499 | 20 | 58146816 | 1779132567 |
78
+ | `sweep_glm_oss_AB_s42.db` | GLM-4 × gpt-oss | 42 | 518 | 20 | 72134656 | 1779121310 |
79
+ | `sweep_glm_oss_AB_s999.db` | GLM-4 × gpt-oss | 999 | 532 | 20 | 60399616 | 1779141456 |
80
+ | `sweep_glm_oss_BA_s137.db` | GLM-4 × gpt-oss | 137 | 488 | 20 | 57929728 | 1779125732 |
81
+ | `sweep_glm_oss_BA_s271.db` | GLM-4 × gpt-oss | 271 | 542 | 20 | 71491584 | 1779130457 |
82
+ | `sweep_glm_oss_BA_s314.db` | GLM-4 × gpt-oss | 314 | 523 | 20 | 60743680 | 1779136288 |
83
+ | `sweep_glm_oss_BA_s42.db` | GLM-4 × gpt-oss | 42 | 521 | 20 | 65347584 | 1779120938 |
84
+ | `sweep_glm_oss_BA_s999.db` | GLM-4 × gpt-oss | 999 | 516 | 20 | 57565184 | 1779141325 |
85
+ | `sweep_glm_qwen_AB_s137.db` | GLM-4 × Qwen | 137 | 493 | 20 | 50180096 | 1779134514 |
86
+ | `sweep_glm_qwen_AB_s271.db` | GLM-4 × Qwen | 271 | 487 | 20 | 50466816 | 1779148018 |
87
+ | `sweep_glm_qwen_AB_s314.db` | GLM-4 × Qwen | 314 | 504 | 20 | 49885184 | 1779160411 |
88
+ | `sweep_glm_qwen_AB_s42.db` | GLM-4 × Qwen | 42 | 480 | 20 | 48644096 | 1779123126 |
89
+ | `sweep_glm_qwen_AB_s999.db` | GLM-4 × Qwen | 999 | 484 | 20 | 46813184 | 1779116576 |
90
+ | `sweep_glm_qwen_BA_s137.db` | GLM-4 × Qwen | 137 | 515 | 20 | 58732544 | 1779139938 |
91
+ | `sweep_glm_qwen_BA_s271.db` | GLM-4 × Qwen | 271 | 503 | 20 | 44761088 | 1779159052 |
92
+ | `sweep_glm_qwen_BA_s314.db` | GLM-4 × Qwen | 314 | 494 | 20 | 41005056 | 1779158811 |
93
+ | `sweep_glm_qwen_BA_s42.db` | GLM-4 × Qwen | 42 | 430 | 20 | 51204096 | 1779129622 |
94
+ | `sweep_glm_qwen_BA_s999.db` | GLM-4 × Qwen | 999 | 465 | 20 | 47808512 | 1779116069 |
95
+ | `sweep_gpt_mag_s137.db` | Mag × gpt-oss | 137 | 544 | 20 | 81920000 | 1779099209 |
96
+ | `sweep_gpt_mag_s271.db` | Mag × gpt-oss | 271 | 547 | 20 | 84930560 | 1779100844 |
97
+ | `sweep_gpt_mag_s314.db` | Mag × gpt-oss | 314 | 572 | 20 | 85561344 | 1779101218 |
98
+ | `sweep_gpt_mag_s42.db` | Mag × gpt-oss | 42 | 574 | 20 | 91918336 | 1779099281 |
99
+ | `sweep_gpt_mag_s999.db` | Mag × gpt-oss | 999 | 581 | 20 | 74018816 | 1779102413 |
100
+ | `sweep_gpt_qwe_s137.db` | Qwen × gpt-oss | 137 | 543 | 20 | 68038656 | 1779080909 |
101
+ | `sweep_gpt_qwe_s271.db` | Qwen × gpt-oss | 271 | 531 | 20 | 56549376 | 1779085792 |
102
+ | `sweep_gpt_qwe_s314.db` | Qwen × gpt-oss | 314 | 532 | 20 | 62742528 | 1779091564 |
103
+ | `sweep_gpt_qwe_s42.db` | Qwen × gpt-oss | 42 | 529 | 20 | 69840896 | 1779075601 |
104
+ | `sweep_gpt_qwe_s999.db` | Qwen × gpt-oss | 999 | 530 | 20 | 49586176 | 1779097052 |
105
+ | `sweep_mag_gpt_s137.db` | Mag × gpt-oss | 137 | 554 | 20 | 80723968 | 1779104432 |
106
+ | `sweep_mag_gpt_s271.db` | Mag × gpt-oss | 271 | 555 | 20 | 70488064 | 1779104670 |
107
+ | `sweep_mag_gpt_s314.db` | Mag × gpt-oss | 314 | 559 | 20 | 81272832 | 1779106080 |
108
+ | `sweep_mag_gpt_s42.db` | Mag × gpt-oss | 42 | 545 | 20 | 88379392 | 1779102897 |
109
+ | `sweep_mag_gpt_s999.db` | Mag × gpt-oss | 999 | 566 | 20 | 81620992 | 1779106413 |
110
+ | `sweep_mag_qwe_s137.db` | Mag × Qwen | 137 | 576 | 20 | 62140416 | 1779091491 |
111
+ | `sweep_mag_qwe_s271.db` | Mag × Qwen | 271 | 568 | 20 | 66150400 | 1779091847 |
112
+ | `sweep_mag_qwe_s314.db` | Mag × Qwen | 314 | 584 | 20 | 66252800 | 1779096942 |
113
+ | `sweep_mag_qwe_s42.db` | Mag × Qwen | 42 | 585 | 20 | 60993536 | 1779085988 |
114
+ | `sweep_mag_qwe_s999.db` | Mag × Qwen | 999 | 582 | 20 | 64733184 | 1779097088 |
115
+ | `sweep_qwe_gpt_s137.db` | Qwen × gpt-oss | 137 | 521 | 20 | 56729600 | 1779080901 |
116
+ | `sweep_qwe_gpt_s271.db` | Qwen × gpt-oss | 271 | 526 | 20 | 55017472 | 1779086001 |
117
+ | `sweep_qwe_gpt_s314.db` | Qwen × gpt-oss | 314 | 531 | 20 | 58732544 | 1779091698 |
118
+ | `sweep_qwe_gpt_s42.db` | Qwen × gpt-oss | 42 | 538 | 20 | 72736768 | 1779075498 |
119
+ | `sweep_qwe_gpt_s999.db` | Qwen × gpt-oss | 999 | 539 | 20 | 66531328 | 1779097026 |
120
+ | `sweep_qwe_mag_s137.db` | Mag × Qwen | 137 | 576 | 20 | 66981888 | 1779075592 |
121
+ | `sweep_qwe_mag_s271.db` | Mag × Qwen | 271 | 581 | 20 | 64507904 | 1779080944 |
122
+ | `sweep_qwe_mag_s314.db` | Mag × Qwen | 314 | 574 | 20 | 66420736 | 1779080997 |
123
+ | `sweep_qwe_mag_s42.db` | Mag × Qwen | 42 | 586 | 20 | 75513856 | 1779075559 |
124
+ | `sweep_qwe_mag_s999.db` | Mag × Qwen | 999 | 577 | 20 | 62619648 | 1779085857 |
125
+
126
+ ## Triadic runs
127
+ **Total valid runs: 89**
128
+
129
+ | Filename | Triplet | Seed | n_comments | n_agents | size_bytes | mtime |
130
+ |----------|---------|------|-----------|---------|------------|-------|
131
+ | `sweep_tri_gem_mag_glm_s271.db` | GLM-4 + Gemma + Mag | 271 | 927 | 30 | 107360256 | 1779741352 |
132
+ | `sweep_tri_gem_mag_glm_s42.db` | GLM-4 + Gemma + Mag | 42 | 851 | 30 | 93626368 | 1779738907 |
133
+ | `sweep_tri_gem_mag_glm_s999.db` | GLM-4 + Gemma + Mag | 999 | 914 | 30 | 98635776 | 1779740176 |
134
+ | `sweep_tri_gem_oss_glm_s271.db` | GLM-4 + Gemma + gpt-oss | 271 | 853 | 30 | 112611328 | 1779679559 |
135
+ | `sweep_tri_gem_oss_glm_s42.db` | GLM-4 + Gemma + gpt-oss | 42 | 835 | 30 | 111042560 | 1779679853 |
136
+ | `sweep_tri_gem_oss_glm_s999.db` | GLM-4 + Gemma + gpt-oss | 999 | 836 | 30 | 104181760 | 1779681507 |
137
+ | `sweep_tri_gem_oss_mag_s271.db` | Gemma + Mag + gpt-oss | 271 | 860 | 30 | 116637696 | 1779740304 |
138
+ | `sweep_tri_gem_oss_mag_s42.db` | Gemma + Mag + gpt-oss | 42 | 857 | 30 | 118136832 | 1779735837 |
139
+ | `sweep_tri_gem_oss_mag_s999.db` | Gemma + Mag + gpt-oss | 999 | 865 | 30 | 113467392 | 1779740150 |
140
+ | `sweep_tri_gem_qwe_glm_s271.db` | GLM-4 + Gemma + Qwen | 271 | 851 | 30 | 88444928 | 1779663231 |
141
+ | `sweep_tri_gem_qwe_glm_s999.db` | GLM-4 + Gemma + Qwen | 999 | 829 | 30 | 87187456 | 1779662986 |
142
+ | `sweep_tri_gem_qwe_mag_s271.db` | Gemma + Mag + Qwen | 271 | 866 | 30 | 95408128 | 1779707852 |
143
+ | `sweep_tri_gem_qwe_mag_s42.db` | Gemma + Mag + Qwen | 42 | 846 | 30 | 84951040 | 1779705394 |
144
+ | `sweep_tri_gem_qwe_mag_s999.db` | Gemma + Mag + Qwen | 999 | 837 | 30 | 91226112 | 1779708400 |
145
+ | `sweep_tri_gem_qwe_oss_s271.db` | Gemma + Qwen + gpt-oss | 271 | 866 | 30 | 101412864 | 1779615407 |
146
+ | `sweep_tri_gem_qwe_oss_s42.db` | Gemma + Qwen + gpt-oss | 42 | 838 | 30 | 98525184 | 1779611501 |
147
+ | `sweep_tri_gem_qwe_oss_s999.db` | Gemma + Qwen + gpt-oss | 999 | 858 | 30 | 112046080 | 1779615839 |
148
+ | `sweep_tri_glm_mag_gem_s271.db` | GLM-4 + Gemma + Mag | 271 | 846 | 30 | 93204480 | 1779729956 |
149
+ | `sweep_tri_glm_mag_gem_s42.db` | GLM-4 + Gemma + Mag | 42 | 865 | 30 | 102367232 | 1779731904 |
150
+ | `sweep_tri_glm_mag_gem_s999.db` | GLM-4 + Gemma + Mag | 999 | 840 | 30 | 93835264 | 1779731115 |
151
+ | `sweep_tri_glm_oss_gem_s271.db` | GLM-4 + Gemma + gpt-oss | 271 | 862 | 30 | 108032000 | 1779672097 |
152
+ | `sweep_tri_glm_oss_gem_s42.db` | GLM-4 + Gemma + gpt-oss | 42 | 853 | 30 | 112455680 | 1779671509 |
153
+ | `sweep_tri_glm_oss_gem_s999.db` | GLM-4 + Gemma + gpt-oss | 999 | 850 | 30 | 113049600 | 1779674662 |
154
+ | `sweep_tri_glm_oss_mag_s271.db` | GLM-4 + Mag + gpt-oss | 271 | 836 | 30 | 96997376 | 1779583162 |
155
+ | `sweep_tri_glm_oss_mag_s42.db` | GLM-4 + Mag + gpt-oss | 42 | 850 | 30 | 105680896 | 1779576950 |
156
+ | `sweep_tri_glm_oss_mag_s999.db` | GLM-4 + Mag + gpt-oss | 999 | 842 | 30 | 97931264 | 1779584320 |
157
+ | `sweep_tri_glm_qwe_gem_s271.db` | GLM-4 + Gemma + Qwen | 271 | 670 | 30 | 67776512 | 1779633689 |
158
+ | `sweep_tri_glm_qwe_gem_s42.db` | GLM-4 + Gemma + Qwen | 42 | 813 | 30 | 76480512 | 1779631257 |
159
+ | `sweep_tri_glm_qwe_gem_s999.db` | GLM-4 + Gemma + Qwen | 999 | 799 | 30 | 85442560 | 1779633695 |
160
+ | `sweep_tri_glm_qwe_mag_s271.db` | GLM-4 + Mag + Qwen | 271 | 799 | 30 | 87195648 | 1779224711 |
161
+ | `sweep_tri_glm_qwe_mag_s42.db` | GLM-4 + Mag + Qwen | 42 | 833 | 30 | 106655744 | 1779219949 |
162
+ | `sweep_tri_glm_qwe_mag_s999.db` | GLM-4 + Mag + Qwen | 999 | 811 | 30 | 84738048 | 1779225552 |
163
+ | `sweep_tri_glm_qwe_oss_s271.db` | GLM-4 + Qwen + gpt-oss | 271 | 760 | 30 | 85078016 | 1779196637 |
164
+ | `sweep_tri_glm_qwe_oss_s42.db` | GLM-4 + Qwen + gpt-oss | 42 | 716 | 30 | 79732736 | 1779196192 |
165
+ | `sweep_tri_glm_qwe_oss_s999.db` | GLM-4 + Qwen + gpt-oss | 999 | 774 | 30 | 91947008 | 1779202782 |
166
+ | `sweep_tri_mag_glm_gem_s271.db` | GLM-4 + Gemma + Mag | 271 | 849 | 30 | 94908416 | 1779722016 |
167
+ | `sweep_tri_mag_glm_gem_s42.db` | GLM-4 + Gemma + Mag | 42 | 827 | 30 | 88150016 | 1779721920 |
168
+ | `sweep_tri_mag_glm_gem_s999.db` | GLM-4 + Gemma + Mag | 999 | 846 | 30 | 92332032 | 1779722279 |
169
+ | `sweep_tri_mag_oss_gem_s271.db` | Gemma + Mag + gpt-oss | 271 | 848 | 30 | 124346368 | 1779736648 |
170
+ | `sweep_tri_mag_oss_gem_s42.db` | Gemma + Mag + gpt-oss | 42 | 826 | 30 | 104566784 | 1779713437 |
171
+ | `sweep_tri_mag_oss_gem_s999.db` | Gemma + Mag + gpt-oss | 999 | 837 | 30 | 106917888 | 1779735944 |
172
+ | `sweep_tri_mag_oss_glm_s271.db` | GLM-4 + Mag + gpt-oss | 271 | 295 | 30 | 32628736 | 1779593348 |
173
+ | `sweep_tri_mag_oss_glm_s42.db` | GLM-4 + Mag + gpt-oss | 42 | 813 | 30 | 106270720 | 1779296502 |
174
+ | `sweep_tri_mag_oss_glm_s999.db` | GLM-4 + Mag + gpt-oss | 999 | 864 | 30 | 118476800 | 1779575944 |
175
+ | `sweep_tri_mag_qwe_gem_s271.db` | Gemma + Mag + Qwen | 271 | 868 | 30 | 102752256 | 1779700441 |
176
+ | `sweep_tri_mag_qwe_gem_s42.db` | Gemma + Mag + Qwen | 42 | 864 | 30 | 110419968 | 1779698791 |
177
+ | `sweep_tri_mag_qwe_gem_s999.db` | Gemma + Mag + Qwen | 999 | 866 | 30 | 104988672 | 1779701696 |
178
+ | `sweep_tri_mag_qwe_glm_s271.db` | GLM-4 + Mag + Qwen | 271 | 848 | 30 | 97263616 | 1779214062 |
179
+ | `sweep_tri_mag_qwe_glm_s42.db` | GLM-4 + Mag + Qwen | 42 | 822 | 30 | 91475968 | 1779214653 |
180
+ | `sweep_tri_mag_qwe_glm_s999.db` | GLM-4 + Mag + Qwen | 999 | 853 | 30 | 89014272 | 1779219381 |
181
+ | `sweep_tri_mag_qwe_oss_s271.db` | Mag + Qwen + gpt-oss | 271 | 794 | 30 | 100130816 | 1779170054 |
182
+ | `sweep_tri_mag_qwe_oss_s42.db` | Mag + Qwen + gpt-oss | 42 | 845 | 30 | 113418240 | 1779168353 |
183
+ | `sweep_tri_mag_qwe_oss_s999.db` | Mag + Qwen + gpt-oss | 999 | 824 | 30 | 94769152 | 1779172581 |
184
+ | `sweep_tri_oss_glm_gem_s271.db` | GLM-4 + Gemma + gpt-oss | 271 | 855 | 30 | 119349248 | 1779666150 |
185
+ | `sweep_tri_oss_glm_gem_s42.db` | GLM-4 + Gemma + gpt-oss | 42 | 834 | 30 | 102146048 | 1779664702 |
186
+ | `sweep_tri_oss_glm_gem_s999.db` | GLM-4 + Gemma + gpt-oss | 999 | 851 | 30 | 109056000 | 1779664188 |
187
+ | `sweep_tri_oss_mag_gem_s271.db` | Gemma + Mag + gpt-oss | 271 | 848 | 30 | 124026880 | 1779712359 |
188
+ | `sweep_tri_oss_mag_gem_s42.db` | Gemma + Mag + gpt-oss | 42 | 856 | 30 | 116924416 | 1779709320 |
189
+ | `sweep_tri_oss_mag_gem_s999.db` | Gemma + Mag + gpt-oss | 999 | 849 | 30 | 102916096 | 1779712561 |
190
+ | `sweep_tri_oss_mag_glm_s271.db` | GLM-4 + Mag + gpt-oss | 271 | 858 | 30 | 102461440 | 1779291369 |
191
+ | `sweep_tri_oss_mag_glm_s42.db` | GLM-4 + Mag + gpt-oss | 42 | 851 | 30 | 99733504 | 1779291731 |
192
+ | `sweep_tri_oss_mag_glm_s999.db` | GLM-4 + Mag + gpt-oss | 999 | 796 | 30 | 106704896 | 1779295866 |
193
+ | `sweep_tri_oss_qwe_gem_s271.db` | Gemma + Qwen + gpt-oss | 271 | 855 | 30 | 138854400 | 1779607702 |
194
+ | `sweep_tri_oss_qwe_gem_s42.db` | Gemma + Qwen + gpt-oss | 42 | 866 | 30 | 117444608 | 1779610048 |
195
+ | `sweep_tri_oss_qwe_gem_s999.db` | Gemma + Qwen + gpt-oss | 999 | 848 | 30 | 113299456 | 1779609179 |
196
+ | `sweep_tri_oss_qwe_glm_s271.db` | GLM-4 + Qwen + gpt-oss | 271 | 712 | 30 | 79577088 | 1779188985 |
197
+ | `sweep_tri_oss_qwe_glm_s42.db` | GLM-4 + Qwen + gpt-oss | 42 | 769 | 30 | 86376448 | 1779184057 |
198
+ | `sweep_tri_oss_qwe_glm_s999.db` | GLM-4 + Qwen + gpt-oss | 999 | 730 | 30 | 85274624 | 1779190791 |
199
+ | `sweep_tri_oss_qwe_mag_s271.db` | Mag + Qwen + gpt-oss | 271 | 854 | 30 | 109309952 | 1779164927 |
200
+ | `sweep_tri_oss_qwe_mag_s42.db` | Mag + Qwen + gpt-oss | 42 | 852 | 30 | 108691456 | 1779160752 |
201
+ | `sweep_tri_oss_qwe_mag_s999.db` | Mag + Qwen + gpt-oss | 999 | 859 | 30 | 102883328 | 1779166217 |
202
+ | `sweep_tri_qwe_glm_gem_s271.db` | GLM-4 + Gemma + Qwen | 271 | 829 | 30 | 94613504 | 1779625369 |
203
+ | `sweep_tri_qwe_glm_gem_s42.db` | GLM-4 + Gemma + Qwen | 42 | 818 | 30 | 73973760 | 1779621704 |
204
+ | `sweep_tri_qwe_glm_gem_s999.db` | GLM-4 + Gemma + Qwen | 999 | 830 | 30 | 81612800 | 1779625082 |
205
+ | `sweep_tri_qwe_mag_gem_s271.db` | Gemma + Mag + Qwen | 271 | 826 | 30 | 109219840 | 1779691521 |
206
+ | `sweep_tri_qwe_mag_gem_s42.db` | Gemma + Mag + Qwen | 42 | 845 | 30 | 100605952 | 1779692886 |
207
+ | `sweep_tri_qwe_mag_gem_s999.db` | Gemma + Mag + Qwen | 999 | 845 | 30 | 98328576 | 1779692494 |
208
+ | `sweep_tri_qwe_mag_glm_s271.db` | GLM-4 + Mag + Qwen | 271 | 834 | 30 | 81764352 | 1779208380 |
209
+ | `sweep_tri_qwe_mag_glm_s42.db` | GLM-4 + Mag + Qwen | 42 | 826 | 30 | 87134208 | 1779202593 |
210
+ | `sweep_tri_qwe_mag_glm_s999.db` | GLM-4 + Mag + Qwen | 999 | 825 | 30 | 89001984 | 1779208467 |
211
+ | `sweep_tri_qwe_oss_gem_s271.db` | Gemma + Qwen + gpt-oss | 271 | 842 | 30 | 102461440 | 1779598329 |
212
+ | `sweep_tri_qwe_oss_gem_s42.db` | Gemma + Qwen + gpt-oss | 42 | 861 | 30 | 116256768 | 1779599659 |
213
+ | `sweep_tri_qwe_oss_gem_s999.db` | Gemma + Qwen + gpt-oss | 999 | 844 | 30 | 107937792 | 1779610777 |
214
+ | `sweep_tri_qwe_oss_glm_s271.db` | GLM-4 + Qwen + gpt-oss | 271 | 767 | 30 | 88920064 | 1779177738 |
215
+ | `sweep_tri_qwe_oss_glm_s42.db` | GLM-4 + Qwen + gpt-oss | 42 | 736 | 30 | 82784256 | 1779176350 |
216
+ | `sweep_tri_qwe_oss_glm_s999.db` | GLM-4 + Qwen + gpt-oss | 999 | 765 | 30 | 98025472 | 1779181875 |
217
+ | `sweep_tri_qwe_oss_mag_s271.db` | Mag + Qwen + gpt-oss | 271 | 801 | 30 | 88059904 | 1779156383 |
218
+ | `sweep_tri_qwe_oss_mag_s42.db` | Mag + Qwen + gpt-oss | 42 | 863 | 30 | 127578112 | 1779156355 |
219
+ | `sweep_tri_qwe_oss_mag_s999.db` | Mag + Qwen + gpt-oss | 999 | 816 | 30 | 100204544 | 1779161905 |
220
+
221
+ ---
222
+
223
+ ## Four-way (tetradic) runs
224
+ **Total valid runs: 24** (2 seeds x 12 model->block rotations of {gpt-oss, Qwen, Magistral, GLM-4}; 40 agents, 10 per model). Stored under `$RUNS_DIR/tetradic/`.
225
+
226
+ | Filename | Seed | Rotation | n_comments | n_agents |
227
+ |----------|------|----------|-----------|---------|
228
+ | `tetra_s42_r1.db` | 42 | r1 | 1067 | 40 |
229
+ | `tetra_s42_r2.db` | 42 | r2 | 1088 | 40 |
230
+ | `tetra_s42_r3.db` | 42 | r3 | 1088 | 40 |
231
+ | `tetra_s42_r4.db` | 42 | r4 | 1090 | 40 |
232
+ | `tetra_s42_r5.db` | 42 | r5 | 1086 | 40 |
233
+ | `tetra_s42_r6.db` | 42 | r6 | 1023 | 40 |
234
+ | `tetra_s42_r7.db` | 42 | r7 | 1101 | 40 |
235
+ | `tetra_s42_r8.db` | 42 | r8 | 1016 | 40 |
236
+ | `tetra_s42_r9.db` | 42 | r9 | 1095 | 40 |
237
+ | `tetra_s42_r10.db` | 42 | r10 | 1080 | 40 |
238
+ | `tetra_s42_r11.db` | 42 | r11 | 1048 | 40 |
239
+ | `tetra_s42_r12.db` | 42 | r12 | 1076 | 40 |
240
+ | `tetra_s271_r1.db` | 271 | r1 | 1057 | 40 |
241
+ | `tetra_s271_r2.db` | 271 | r2 | 1029 | 40 |
242
+ | `tetra_s271_r3.db` | 271 | r3 | 1055 | 40 |
243
+ | `tetra_s271_r4.db` | 271 | r4 | 1249 | 40 |
244
+ | `tetra_s271_r5.db` | 271 | r5 | 1067 | 40 |
245
+ | `tetra_s271_r6.db` | 271 | r6 | 1082 | 40 |
246
+ | `tetra_s271_r7.db` | 271 | r7 | 1101 | 40 |
247
+ | `tetra_s271_r8.db` | 271 | r8 | 1102 | 40 |
248
+ | `tetra_s271_r9.db` | 271 | r9 | 1060 | 40 |
249
+ | `tetra_s271_r10.db` | 271 | r10 | 1079 | 40 |
250
+ | `tetra_s271_r11.db` | 271 | r11 | 1072 | 40 |
251
+ | `tetra_s271_r12.db` | 271 | r12 | 1113 | 40 |
docs/EXPERIMENT_PROTOCOL.md ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experiment Protocol: Disentangling Models from Personas in LLM Social Simulations
2
+
3
+ ## Overview
4
+
5
+ This document is the canonical reproducibility narrative for the dyadic, triadic,
6
+ and four-way (tetradic) sweep experiments and the lexical/content analyses reported
7
+ in the paper. It complements the code in `sweep/`, `oasis/`, `launch/`, and
8
+ `analyses/` by explaining the experimental design decisions that are not obvious
9
+ from code alone.
10
+
11
+ ---
12
+
13
+ ## Simulator
14
+
15
+ We adapt the OASIS simulator (v0.2.5, https://github.com/camel-ai/oasis) to
16
+ support heterogeneous multi-model populations. The key modifications are in
17
+ `oasis/run_v9.py`:
18
+
19
+ - `hetero` mode: 2 model families, 10 agents each
20
+ - `hetero3` mode: 3 model families, 10 agents each
21
+ - Plackett-Luce feed ranking with Gumbel noise (T=5.0)
22
+ - Post-share balancer: prevents one model family from dominating posts
23
+ - Warm-up phase: all agents post once before the main loop; any run where a
24
+ family has < 50% participation is aborted
25
+ - SIGTERM-safe checkpoint/resume for preemptible SLURM allocations
26
+
27
+ ---
28
+
29
+ ## Models
30
+
31
+ Five models are tested. All are served via vLLM 0.19.0 on 8× NVIDIA L40S 48 GB.
32
+ See `env/vllm_version.md` for exact launch parameters.
33
+
34
+ | Model | HF ID | TP | Port |
35
+ |-------|-------|----|------|
36
+ | Qwen | Qwen/Qwen3-32B | 2 | 8002 |
37
+ | gpt-oss | openai/gpt-oss-20b | 1 | 8003 |
38
+ | Magistral | mistralai/Magistral-Small-2509 | 2 | 8004 |
39
+ | GLM-4 | zai-org/GLM-4-32B-0414 | 2 | 8007 |
40
+ | Gemma | google/gemma-4-31B-it | 2 | 8009 |
41
+
42
+ ---
43
+
44
+ ## Persona initialization
45
+
46
+ Personas are sampled from the Moltbook community archive (HF dataset). The
47
+ seed database (`oasis/seed_db/hf-zero-50.sqlite`) contains 50 real agent
48
+ profiles: display names, bios, and prior post histories (up to 5 posts per
49
+ agent, ~500 chars each).
50
+
51
+ A diversity filter ensures at most 1 HK CLAW minter persona per run (a narrow
52
+ cluster that otherwise over-represents in random samples). The filter is
53
+ deterministic given the RNG seed.
54
+
55
+ Each seed value produces a different persona sample. Seeds: [42, 137, 271, 314, 999]
56
+ for dyadic runs; [42, 271, 999] for triadic runs.
57
+
58
+ ---
59
+
60
+ ## Rotating assignments
61
+
62
+ For **dyadic** runs: 20 agents (10 per family), two orderings per seed (A=X,B=Y
63
+ and A=Y,B=X). This gives 2 × C(5,2) × 5 = 100 runs.
64
+
65
+ For **triadic** runs: 30 agents (10 per family), 3 of 6 orderings per seed
66
+ (selected by taking permutations at indices 0, 2, 4 for maximum positional
67
+ diversity). This gives 3 × C(5,3) × 3 = 90 runs.
68
+
69
+ ---
70
+
71
+ ## Simulation parameters
72
+
73
+ | Parameter | Value |
74
+ |-----------|-------|
75
+ | Steps | 100 |
76
+ | Activation probability | 0.3 per agent per step |
77
+ | Feed size (K) | 20 |
78
+ | Gumbel noise temperature | T=5.0 |
79
+ | Post-share tolerance | δ=0.05 |
80
+ | Input token limit | 12,000 |
81
+ | Max output tokens | 1536 (512 for Gemma) |
82
+ | Temperature | 0.85 |
83
+ | Max tool-call attempts per turn | 6 |
84
+
85
+ ---
86
+
87
+ ## Metrics
88
+
89
+ ### Directed pairwise engagement homophily (H)
90
+
91
+ For families X and Y:
92
+
93
+ ```
94
+ H_{X→Y} = obs(X→Y) / exp(X→Y) - 1
95
+ ```
96
+
97
+ where `obs(X→Y)` = fraction of all directed comment edges from X to Y, and
98
+ `exp(X→Y)` = null expectation under random mixing proportional to group sizes.
99
+
100
+ Two edge types are counted:
101
+ 1. commenter → post_author
102
+ 2. replier → parent_comment_author (threaded replies)
103
+
104
+ Positive H = X engages with Y more than random; negative = avoidance.
105
+ Diagonal (X=X) = in-group self-preference.
106
+
107
+ ### Swap stability
108
+
109
+ For dyadic runs: mean |H_{X→Y}^(AB) - H_{X→Y}^(BA)| across seeds.
110
+ For triadic runs: mean max-|ΔH| across the 3 orderings per (triplet, seed).
111
+ Lower = more stable across persona-to-model assignment rotations.
112
+
113
+ ---
114
+
115
+ ## Validity criteria
116
+
117
+ A run is included in the paper analysis if:
118
+
119
+ - **Dyadic**: ≥ 18 distinct agents commented, ≥ 200 total comments
120
+ - **Triadic**: ≥ 26 distinct agents commented, ≥ 200 total comments
121
+
122
+ These thresholds filter out runs that were aborted (e.g., server failure,
123
+ warm-up failure) before completing enough interaction to yield reliable H estimates.
124
+
125
+ Note: The H-matrix figure scripts (`analyses/plot_matrices.py`) apply only
126
+ `nu ≥ 26` for triadic runs (no nc threshold), matching the original data
127
+ selection used for the paper's H tables. The variance decomposition scripts
128
+ (the variance scripts) apply `nc ≥ 200` for both
129
+ dyadic and triadic, which excludes one additional triadic run with nc=169.
130
+ The paper's stated 182-run pool (100 dyadic + 82 triadic) was computed at an
131
+ earlier snapshot; the current pool is 100 dyadic + 89 triadic = 189 runs (see
132
+ `data/MANIFEST.md`).
133
+
134
+ ---
135
+
136
+ ## Run identification convention
137
+
138
+ Database file names encode the run configuration:
139
+
140
+ ```
141
+ sweep_{modelA[:3]}_{modelB[:3]}_s{seed}.db # dyadic
142
+ sweep_tri_{A[:3]}_{B[:3]}_{C[:3]}_s{seed}.db # triadic
143
+ ```
144
+
145
+ Each `.db` file has a corresponding `.metadata.json` sidecar with the
146
+ agent-to-model mapping, and `.metadata.json` + `_chats.jsonl` + `_reasoning.jsonl`
147
+ side-car files.
148
+
149
+ ---
150
+
151
+ ## Variance decomposition methodology
152
+
153
+ The variance decomposition (Appendix D) uses **comments per post** (CPP =
154
+ in-degree / number of posts) as the dependent variable, restricted to agents with
155
+ at least two posts. Raw in-degree conflates per-post appeal with posting *volume*
156
+ (an agent that posts more mechanically receives more comments); CPP removes that
157
+ exposure confound. Earlier drafts used raw in-degree, under which persona appears
158
+ to dominate two-way mixtures purely as a posting-volume artifact.
159
+
160
+ | Script | What it produces |
161
+ |--------|-----------------|
162
+ | `analyses/variance_cpp.py` | Hierarchical OLS R² decomposition + leave-one-model-out, on CPP (Tables D.1–D.2) |
163
+ | `analyses/absolute_variance.py` | Variance components across dyadic / triadic / four-way regimes |
164
+ | `analyses/plot_fig_variance_overview.py` | Figure: proportional CPP variance (model vs persona) + per-model H by mixture size |
165
+
166
+ Model selection is the agent's own base model plus the unordered partner-pair
167
+ (the other models present). In four-way runs all four models are present in every
168
+ run, so the partner composition is constant and model selection reduces to
169
+ own-model identity.
170
+
171
+ ---
172
+
173
+ ## Reproducibility notes
174
+
175
+ 1. **Stochastic elements**: Two sources of randomness per run, both controlled
176
+ by `--rng-seed`:
177
+ - Persona selection (which agents from the seed DB)
178
+ - Group allocation (which agents go to which model family)
179
+ - Feed noise is per-agent Gumbel, not globally seeded; exact reproduction of
180
+ feed orderings would require seeding each model call, which is not done.
181
+
182
+ 2. **Model-side non-determinism**: vLLM with temperature=0.85 is stochastic.
183
+ Running the same configuration twice will produce different comments. The
184
+ paper reports means ± std across seeds and rotations; individual runs are
185
+ not expected to be identical.
186
+
187
+ 3. **Checkpoint/resume**: Partial DBs can be resumed with `--resume`. The
188
+ `_checkpoint.json` sidecar records the exact last completed step.
189
+
190
+ 4. **Warm-up ordering**: Agents post in a seeded-random order during warm-up,
191
+ ensuring the initial post distribution across model families is
192
+ approximately uniform by construction.
193
+
194
+ ---
195
+
196
+ ## Four-way (tetradic) runs
197
+
198
+ The four-way sweep uses the pool {gpt-oss, Qwen, Magistral, GLM-4}, 40 agents
199
+ (10 per family), 100 steps, post-share balancer on, activation prob 0.3
200
+ (`run_v9.py --mode hetero4`). Two seeds (42, 271) each cover 12 distinct
201
+ model->block rotations (a Latin-square-style set), for 24 valid runs.
202
+
203
+ - **Validity:** >= 200 comments and all four models present.
204
+ - **Run identification:** `tetradic/tetra_s{seed}_r{rotation}.db`.
205
+ - **Metrics:** same directed engagement homophily (H) as dyadic/triadic; for the
206
+ variance decomposition and content analyses, CPP as above.
207
+
208
+ Driver: `launch/run_tetradic.sh`. Per-model H over the 24 runs and the four-way
209
+ H matrix/heatmap: `analyses/tetradic_recompute_H.py`, `analyses/tetradic_results.py`.
210
+
211
+ ---
212
+
213
+ ## Content analysis
214
+
215
+ Finding 3 analyzes the text agents produce. Build the corpus once with
216
+ `analyses/extract_texts.py` (-> `data/texts.jsonl`: one row per post/comment with
217
+ its model and persona). Then:
218
+
219
+ - `analyses/lexical_table.py` — TF-IDF (word 1–2-grams, English stop words removed,
220
+ + char 3–5-grams) -> logistic regression recovering model / persona (Table 1).
221
+ - `analyses/svd_axes.py` — agent-level TF-IDF -> truncated SVD (30 components); the
222
+ first axis (document language) is dropped, leaving 29 style axes. Reports per-axis
223
+ top terms from V^T.
224
+ - `analyses/content_engagement.py` — decomposes CPP variance into length / style /
225
+ model / persona blocks (single + leave-one-block-out unique R²).
226
+ - `analyses/style_geometry.py` — per-model style-direction centroids, their split-half
227
+ stability, and cosines to the engagement direction (linear probe on style).
228
+ - `analyses/cluster_model_persona.py`, `analyses/length_regimes.py` — supporting
229
+ checks (does style cluster by model vs persona; length/volume confound by regime).
env/requirements.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # divsim reproducibility bundle — Python dependencies
2
+ # Tested on Python 3.12, Linux (RHEL 9)
3
+
4
+ # ── OASIS / CAMEL core ────────────────────────────────────────────────────────
5
+ camel-ai>=0.1.6
6
+ pandas==2.2.2
7
+ igraph==0.11.6
8
+ cairocffi==1.7.1
9
+
10
+ # ── vLLM (model serving) ──────────────────────────────────────────────────────
11
+ # Pin to 0.19.0 — the exact version used in all paper experiments.
12
+ # Later versions may change scheduler behavior; see env/vllm_version.md.
13
+ vllm==0.19.0
14
+
15
+ # ── HuggingFace model download ────────────────────────────────────────────────
16
+ huggingface-hub>=0.23.0
17
+ transformers>=4.47.0
18
+
19
+ # ── Analysis scripts ──────────────────────────────────────────────────────────
20
+ numpy>=1.26.0
21
+ matplotlib>=3.9.0
22
+ scikit-learn>=1.5.0 # classifiers + SVD (content analyses, variance_cpp)
23
+ scipy>=1.13.0 # sparse TF-IDF matrices (lexical_table.py, etc.)
24
+
25
+ # ── Utilities ─────────────────────────────────────────────────────────────────
26
+ requests>=2.32.0
env/vllm_version.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # vLLM Version and Per-Model Launch Notes
2
+
3
+ **Version used in paper:** vLLM 0.19.0
4
+
5
+ All five models are served via `vllm.entrypoints.openai.api_server`. Common
6
+ defaults across all models:
7
+
8
+ | Parameter | Value |
9
+ |-----------|-------|
10
+ | `--max-model-len` | 16384 |
11
+ | `--gpu-memory-utilization` | 0.90 |
12
+ | `--enable-auto-tool-choice` | (flag) |
13
+ | `--no-scheduler-reserve-full-isl` | (flag, required — avoids a vLLM 0.19.0 scheduler deadlock under sustained multi-agent load) |
14
+ | Input context cap | 12,000 tokens (set in runner via `_input_token_limit`) |
15
+ | Max output tokens | 1536 (512 for Gemma) |
16
+ | Temperature | 0.85 |
17
+ | BF16 weights | default |
18
+
19
+ ---
20
+
21
+ ## Per-model deviations
22
+
23
+ ### Qwen/Qwen3-32B
24
+ - TP=2 (GPUs 0-1)
25
+ - `--tool-call-parser hermes`
26
+ - `tool_choice=required`
27
+ - Thinking suppressed via `chat_template_kwargs = {"enable_thinking": False}`
28
+
29
+ ### openai/gpt-oss-20b
30
+ - TP=1 (GPU 2); mxfp4 quantized weights fit in ~40 GB
31
+ - `--tool-call-parser openai`
32
+ - `--reasoning-parser openai_gptoss`
33
+ - `tool_choice=required`
34
+
35
+ ### mistralai/Magistral-Small-2509
36
+ - TP=2 (GPUs 3-4)
37
+ - `--tokenizer-mode mistral --config-format mistral --load-format mistral`
38
+ (Mistral models require their own loader; standard HuggingFace format fails)
39
+ - `--tool-call-parser mistral`
40
+ - `--reasoning-parser mistral`
41
+ - `tool_choice=auto` — **Magistral returns empty `tool_calls` with `required`**;
42
+ `auto` is the correct setting
43
+
44
+ ### zai-org/GLM-4-32B-0414
45
+ - TP=2 (GPUs 5-6)
46
+ - `--tool-call-parser hermes`
47
+ - `tool_choice=required` — **GLM-4 silently returns plain text with `auto`**;
48
+ this was discovered when warm-up showed only 1/10 agents posting per run
49
+
50
+ ### google/gemma-4-31B-it
51
+ - TP=2 (GPUs 0-1 or 3-4 depending on node configuration)
52
+ - `--tool-call-parser gemma4`
53
+ - `--chat-template oasis/tool_chat_template_gemma4.jinja` (custom template, required)
54
+ - `tool_choice=auto` — same symptom as Magistral with `required`
55
+ - `--max-num-seqs 64` — tuned to avoid KV-cache saturation under concurrent load
56
+ - `max_tokens=512` (runner-side cap, lower than other models)
57
+ - **Note:** There is a discrepancy between the paper appendix (max_num_seqs=64)
58
+ and an earlier production launch script (max_num_seqs=8). The appendix value
59
+ (64) is the final setting used in paper runs.
60
+
61
+ ---
62
+
63
+ ## Known issues in vLLM 0.19.0
64
+
65
+ - **Scheduler deadlock**: Under sustained multi-agent load, the scheduler can
66
+ deadlock. Mitigated by `--no-scheduler-reserve-full-isl` on all models.
67
+ - **Gemma KV-cache saturation**: Default scheduling settings cause OOM-like
68
+ behavior under concurrent requests. `--max-num-seqs 64` and ensuring
69
+ `--gpu-memory-utilization 0.90` resolves this.
70
+ - **Magistral/Gemma tool_choice=required**: Both models return empty
71
+ `tool_calls` lists when `tool_choice=required`; the runner uses `auto` and
72
+ handles non-tool responses with prose-to-action scaffolding.
launch/run_tetradic.sh ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Four-way (tetradic) rotation sweep: 2 seeds x 12 distinct model->block permutations.
3
+ # Pool {gpt-oss, Qwen, Magistral, GLM-4}, n=40 agents (10/model), 100 steps,
4
+ # post-share balancer on, activation prob 0.3, run_v9 --mode hetero4.
5
+ # Serves all four models concurrently on one node (7 GPUs), runs two rotations in parallel.
6
+ # Resume-safe: completed DBs are skipped, partial ones (with a *_checkpoint.json) resume.
7
+ #
8
+ # Required env:
9
+ # SAFEMASS_VENV venv with vLLM serving stack (CUDA torch, transformers)
10
+ # OASIS_VENV venv with the OASIS client deps (run_v9.py)
11
+ # HF_HUB_CACHE HuggingFace model cache
12
+ # RUNS_DIR output dir for run DBs
13
+ # SEEDS (optional) space-separated seeds; default "42 271"
14
+ set -uo pipefail
15
+ SEEDS="${SEEDS:-42 271}"
16
+ : "${SAFEMASS_VENV:?set SAFEMASS_VENV}"; : "${OASIS_VENV:?set OASIS_VENV}"
17
+ : "${HF_HUB_CACHE:?set HF_HUB_CACHE}"; export HF_HUB_CACHE
18
+ RUNS="${RUNS_DIR:?set RUNS_DIR}"
19
+ EXP="${RUNS}/tetradic"; LOGS="${EXP}/logs"; mkdir -p "$EXP" "$LOGS"
20
+ exec >> "${LOGS}/rotations.log" 2>&1
21
+ echo "==== tetradic rotations start $(date -Is) seeds=[$SEEDS] x12 ===="
22
+
23
+ wait_health(){ for i in $(seq 1 360); do curl -fsS "http://127.0.0.1:$1/health">/dev/null 2>&1&&return 0; sleep 5; done; return 1; }
24
+
25
+ # --- serve the four models (see launch/vllm_*.sh for per-model flag rationale) ---
26
+ CUDA_VISIBLE_DEVICES=0 "${SAFEMASS_VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
27
+ --model openai/gpt-oss-20b --served-model-name openai/gpt-oss-20b --tensor-parallel-size 1 --max-model-len 16384 \
28
+ --port 8003 --gpu-memory-utilization 0.90 --host 127.0.0.1 --trust-remote-code \
29
+ --enable-auto-tool-choice --tool-call-parser openai --reasoning-parser openai_gptoss >>"${LOGS}/vllm_oss.log" 2>&1 &
30
+ CUDA_VISIBLE_DEVICES=1,2 "${SAFEMASS_VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
31
+ --model Qwen/Qwen3-32B --served-model-name Qwen/Qwen3-32B --tensor-parallel-size 2 --max-model-len 16384 \
32
+ --port 8002 --gpu-memory-utilization 0.90 --host 127.0.0.1 --trust-remote-code \
33
+ --enable-auto-tool-choice --tool-call-parser hermes >>"${LOGS}/vllm_qwen.log" 2>&1 &
34
+ CUDA_VISIBLE_DEVICES=3,4 "${SAFEMASS_VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
35
+ --model mistralai/Magistral-Small-2509 --tensor-parallel-size 2 --max-model-len 16384 --port 8004 \
36
+ --gpu-memory-utilization 0.90 --host 127.0.0.1 --trust-remote-code --tokenizer-mode mistral \
37
+ --load-format mistral --config-format mistral --enable-auto-tool-choice --tool-call-parser mistral \
38
+ --reasoning-parser mistral >>"${LOGS}/vllm_mag.log" 2>&1 &
39
+ CUDA_VISIBLE_DEVICES=5,6 "${SAFEMASS_VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
40
+ --model zai-org/GLM-4-32B-0414 --tensor-parallel-size 2 --max-model-len 16384 --port 8007 \
41
+ --gpu-memory-utilization 0.90 --host 127.0.0.1 --trust-remote-code \
42
+ --enable-auto-tool-choice --tool-call-parser hermes >>"${LOGS}/vllm_glm.log" 2>&1 &
43
+ for p in 8003 8002 8004 8007; do wait_health $p||{ echo "FATAL vllm $p"; pkill -9 -f vllm.entrypoints; exit 1; }; done
44
+ echo "[fleet] up $(date -Is)"
45
+
46
+ PY="${OASIS_VENV}/bin/python3"; cd "$RUNS"
47
+ url(){ case $1 in O)echo http://localhost:8003/v1;; Q)echo http://localhost:8002/v1;; M)echo http://localhost:8004/v1;; G)echo http://localhost:8007/v1;; esac; }
48
+ mdl(){ case $1 in O)echo openai/gpt-oss-20b;; Q)echo Qwen/Qwen3-32B;; M)echo mistralai/Magistral-Small-2509;; G)echo zai-org/GLM-4-32B-0414;; esac; }
49
+
50
+ # 12 distinct permutations of [gpt-oss, Qwen, Magistral, GLM-4] across blocks A B C D.
51
+ PERMS=( "O Q M G" "Q M G O" "M G O Q" "G O Q M" \
52
+ "O G M Q" "G M Q O" "M Q O G" "Q O G M" \
53
+ "O Q G M" "Q O M G" "M G Q O" "G M O Q" )
54
+
55
+ run_one(){ # <db> <seed> <permstring>
56
+ local db="$1" sd="$2"; read -r a b c d <<< "$3"
57
+ local name=$(basename "$db" .db); local ckpt="${db%.db}_checkpoint.json"
58
+ if [ -f "$db" ] && [ ! -f "$ckpt" ]; then echo " == $name complete, skip"; return 0; fi
59
+ local res=""; [ -f "$ckpt" ] && res="--resume"
60
+ VLLM_URL_A="$(url $a)" MODEL_NAME_A="$(mdl $a)" VLLM_URL_B="$(url $b)" MODEL_NAME_B="$(mdl $b)" \
61
+ VLLM_URL_C="$(url $c)" MODEL_NAME_C="$(mdl $c)" VLLM_URL_D="$(url $d)" MODEL_NAME_D="$(mdl $d)" POST_SHARE_TOL=0.05 \
62
+ $PY run_v9.py --mode hetero4 --steps 100 --agents 40 --seed-posts 0 --activate-prob 0.3 \
63
+ --rng-seed "$sd" --db "$db" $res >>"${LOGS}/${name}.log" 2>&1
64
+ echo " <<< $name rc=$? $(date -Is)"
65
+ }
66
+
67
+ for sd in $SEEDS; do
68
+ echo "==== seed $sd $(date -Is) ===="
69
+ i=0
70
+ while [ $i -lt ${#PERMS[@]} ]; do
71
+ run_one "$EXP/tetra_s${sd}_r$((i+1)).db" $sd "${PERMS[$i]}" & p1=$!
72
+ p2=""; if [ $((i+1)) -lt ${#PERMS[@]} ]; then run_one "$EXP/tetra_s${sd}_r$((i+2)).db" $sd "${PERMS[$((i+1))]}" & p2=$!; fi
73
+ wait $p1 ${p2:-}
74
+ i=$((i+2))
75
+ done
76
+ done
77
+ echo "==== tetradic rotations done $(date -Is) ===="
launch/vllm_gemma.sh ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch vLLM server for google/gemma-4-31B-it.
3
+ #
4
+ # Hardware: 2× L40S 48GB (TP=2). Note: Gemma shares the same GPU pair (0-1 by
5
+ # default here) as Magistral in the paper's triadic-sweep node layout. They
6
+ # cannot run simultaneously; stop one before starting the other.
7
+ # Default port: 8009. Override with PORT env var.
8
+ #
9
+ # Key settings:
10
+ # --tool-call-parser gemma4 — requires the custom jinja chat template
11
+ # --chat-template — path to tool_chat_template_gemma4.jinja
12
+ # tool_choice=auto — Gemma 4 returns empty tool_calls with 'required'
13
+ # --max-num-seqs 64 — tuned to avoid KV-cache saturation under
14
+ # concurrent multi-agent load
15
+ # --no-scheduler-reserve-full-isl — avoids a vLLM 0.19.0 scheduler deadlock
16
+ #
17
+ # Note on max_tokens: Gemma 4 output is capped at 512 tokens in the runner
18
+ # (compared to 1536 for other models) to limit KV-cache pressure.
19
+
20
+ set -euo pipefail
21
+
22
+ HF_HUB_CACHE="${HF_HUB_CACHE:-/data/hf_cache/hub}"
23
+ export HF_HUB_CACHE
24
+
25
+ VENV="${SAFEMASS_VENV:-$(dirname "$0")/../.venv}"
26
+ PORT="${PORT:-8009}"
27
+ LOGS="${LOGS_DIR:-/tmp/vllm_logs}"
28
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
29
+ TEMPLATE="${GEMMA_CHAT_TEMPLATE:-${SCRIPT_DIR}/../oasis/tool_chat_template_gemma4.jinja}"
30
+ mkdir -p "$LOGS"
31
+
32
+ if [[ ! -f "$TEMPLATE" ]]; then
33
+ echo "ERROR: Gemma chat template not found at: $TEMPLATE" >&2
34
+ echo "Set GEMMA_CHAT_TEMPLATE env var or ensure oasis/tool_chat_template_gemma4.jinja exists." >&2
35
+ exit 1
36
+ fi
37
+
38
+ CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0,1}" \
39
+ "${VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
40
+ --model google/gemma-4-31B-it \
41
+ --served-model-name google/gemma-4-31B-it \
42
+ --tensor-parallel-size 2 \
43
+ --max-model-len 16384 \
44
+ --gpu-memory-utilization 0.90 \
45
+ --port "$PORT" \
46
+ --host 127.0.0.1 \
47
+ --trust-remote-code \
48
+ --enable-auto-tool-choice \
49
+ --tool-call-parser gemma4 \
50
+ --chat-template "$TEMPLATE" \
51
+ --max-num-seqs 64 \
52
+ --no-scheduler-reserve-full-isl \
53
+ >> "${LOGS}/vllm_gemma_${PORT}.log" 2>&1
launch/vllm_glm4.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch vLLM server for zai-org/GLM-4-32B-0414.
3
+ #
4
+ # Hardware: 2× L40S 48GB (TP=2).
5
+ # Default port: 8007. Override with PORT env var.
6
+ #
7
+ # Key settings:
8
+ # --tool-call-parser hermes — GLM-4-32B-0414 uses the Hermes tool schema
9
+ # tool_choice=required — GLM-4 returns plain text with 'auto';
10
+ # 'required' is necessary for reliable tool calls
11
+ #
12
+ # Warm-up check: the simulation runner verifies ≥50% of GLM-4 agents post in
13
+ # warm-up. If this check fails, the most likely cause is the server not being
14
+ # ready or returning malformed tool calls.
15
+
16
+ set -euo pipefail
17
+
18
+ HF_HUB_CACHE="${HF_HUB_CACHE:-/data/hf_cache/hub}"
19
+ export HF_HUB_CACHE
20
+
21
+ VENV="${SAFEMASS_VENV:-$(dirname "$0")/../.venv}"
22
+ PORT="${PORT:-8007}"
23
+ LOGS="${LOGS_DIR:-/tmp/vllm_logs}"
24
+ mkdir -p "$LOGS"
25
+
26
+ CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-5,6}" \
27
+ "${VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
28
+ --model zai-org/GLM-4-32B-0414 \
29
+ --tensor-parallel-size 2 \
30
+ --max-model-len 16384 \
31
+ --gpu-memory-utilization 0.90 \
32
+ --port "$PORT" \
33
+ --host 127.0.0.1 \
34
+ --trust-remote-code \
35
+ --enable-auto-tool-choice \
36
+ --tool-call-parser hermes \
37
+ --no-scheduler-reserve-full-isl \
38
+ >> "${LOGS}/vllm_glm4_${PORT}.log" 2>&1
launch/vllm_gpt_oss.sh ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch vLLM server for openai/gpt-oss-20b.
3
+ #
4
+ # Hardware: 1× L40S 48GB (TP=1). The mxfp4 quantized weights fit in ~40 GB.
5
+ # Default port: 8003. Override with PORT env var.
6
+ #
7
+ # Key settings:
8
+ # --tool-call-parser openai — gpt-oss uses the OpenAI tool schema
9
+ # --reasoning-parser openai_gptoss — strips thinking tokens from output
10
+ # tool_choice=required — gpt-oss reliably complies with required
11
+
12
+ set -euo pipefail
13
+
14
+ HF_HUB_CACHE="${HF_HUB_CACHE:-/data/hf_cache/hub}"
15
+ export HF_HUB_CACHE
16
+
17
+ VENV="${SAFEMASS_VENV:-$(dirname "$0")/../.venv}"
18
+ PORT="${PORT:-8003}"
19
+ LOGS="${LOGS_DIR:-/tmp/vllm_logs}"
20
+ mkdir -p "$LOGS"
21
+
22
+ CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-2}" \
23
+ "${VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
24
+ --model openai/gpt-oss-20b \
25
+ --tensor-parallel-size 1 \
26
+ --max-model-len 16384 \
27
+ --gpu-memory-utilization 0.90 \
28
+ --port "$PORT" \
29
+ --host 127.0.0.1 \
30
+ --trust-remote-code \
31
+ --enable-auto-tool-choice \
32
+ --tool-call-parser openai \
33
+ --reasoning-parser openai_gptoss \
34
+ --no-scheduler-reserve-full-isl \
35
+ >> "${LOGS}/vllm_gptoss_${PORT}.log" 2>&1
launch/vllm_magistral.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch vLLM server for mistralai/Magistral-Small-2509.
3
+ #
4
+ # Hardware: 2× L40S 48GB (TP=2).
5
+ # Default port: 8004. Override with PORT env var.
6
+ #
7
+ # Key settings:
8
+ # --tokenizer-mode mistral \
9
+ # --config-format mistral \
10
+ # --load-format mistral — Mistral models require their own tokenizer/loader
11
+ # --tool-call-parser mistral — uses Mistral tool-call format
12
+ # --reasoning-parser mistral — strips Magistral thinking tokens
13
+ # tool_choice=auto — Magistral returns empty tool_calls with 'required';
14
+ # 'auto' is the correct setting for this model
15
+
16
+ set -euo pipefail
17
+
18
+ HF_HUB_CACHE="${HF_HUB_CACHE:-/data/hf_cache/hub}"
19
+ export HF_HUB_CACHE
20
+
21
+ VENV="${SAFEMASS_VENV:-$(dirname "$0")/../.venv}"
22
+ PORT="${PORT:-8004}"
23
+ LOGS="${LOGS_DIR:-/tmp/vllm_logs}"
24
+ mkdir -p "$LOGS"
25
+
26
+ CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-3,4}" \
27
+ "${VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
28
+ --model mistralai/Magistral-Small-2509 \
29
+ --tensor-parallel-size 2 \
30
+ --max-model-len 16384 \
31
+ --gpu-memory-utilization 0.90 \
32
+ --port "$PORT" \
33
+ --host 127.0.0.1 \
34
+ --trust-remote-code \
35
+ --tokenizer-mode mistral \
36
+ --config-format mistral \
37
+ --load-format mistral \
38
+ --enable-auto-tool-choice \
39
+ --tool-call-parser mistral \
40
+ --reasoning-parser mistral \
41
+ --no-scheduler-reserve-full-isl \
42
+ >> "${LOGS}/vllm_magistral_${PORT}.log" 2>&1
launch/vllm_qwen.sh ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch vLLM server for Qwen/Qwen3-32B.
3
+ #
4
+ # Hardware: 2× L40S 48GB (TP=2), GPUs selectable via CUDA_VISIBLE_DEVICES.
5
+ # Default port: 8002. Override with PORT env var.
6
+ #
7
+ # Key settings:
8
+ # --tool-call-parser hermes — Qwen3-32B uses the Hermes tool schema
9
+ # chat_template_kwargs enable_thinking=False — suppress reasoning prefix tokens;
10
+ # Qwen3 is a hybrid reasoning model but we want action output only
11
+ # tool_choice=required — Qwen reliably complies; forced to prevent
12
+ # plain-text fallback
13
+
14
+ set -euo pipefail
15
+
16
+ HF_HUB_CACHE="${HF_HUB_CACHE:-/data/hf_cache/hub}"
17
+ export HF_HUB_CACHE
18
+
19
+ VENV="${SAFEMASS_VENV:-$(dirname "$0")/../.venv}"
20
+ PORT="${PORT:-8002}"
21
+ LOGS="${LOGS_DIR:-/tmp/vllm_logs}"
22
+ mkdir -p "$LOGS"
23
+
24
+ CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0,1}" \
25
+ "${VENV}/bin/python3" -m vllm.entrypoints.openai.api_server \
26
+ --model Qwen/Qwen3-32B \
27
+ --tensor-parallel-size 2 \
28
+ --max-model-len 16384 \
29
+ --gpu-memory-utilization 0.90 \
30
+ --port "$PORT" \
31
+ --host 127.0.0.1 \
32
+ --trust-remote-code \
33
+ --enable-auto-tool-choice \
34
+ --tool-call-parser hermes \
35
+ --no-scheduler-reserve-full-isl \
36
+ >> "${LOGS}/vllm_qwen_${PORT}.log" 2>&1
oasis/NOTICE ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ OASIS — Open Agent Social Interaction Simulations
2
+ Copyright (c) CAMEL-AI.org
3
+ Licensed under the Apache License, Version 2.0.
4
+
5
+ The code in this directory is adapted from:
6
+ https://github.com/camel-ai/oasis
7
+ Version: 0.2.5
8
+
9
+ Modifications by Dani Roytburg (droytbur@andrew.cmu.edu):
10
+ - Added heterogeneous multi-model support (hetero / hetero3 modes)
11
+ - Added Plackett-Luce feed temperature (FEED_TEMPERATURE)
12
+ - Added post-share balancer, warm-up phase, per-agent recap
13
+ - Added SIGTERM handler for SLURM preemption checkpointing
14
+ - Added chat log + reasoning trace output
15
+
16
+ The full Apache-2.0 license text is available at:
17
+ https://www.apache.org/licenses/LICENSE-2.0
oasis/run_v9.py ADDED
@@ -0,0 +1,1371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OASIS v9 — three experimental modes on top of v8 foundation.
3
+
4
+ Modes (--mode flag):
5
+ late_join Experiment 1: start with 35 agents, inject 15 late-joiners at
6
+ step N*0.2. Track whether late agents reach centrality.
7
+ hetero Experiment 2: 25 agents on Qwen3-14B, 25 on OLMo-3.1-32B-Think.
8
+ Same personas. Measure homophily: do same-model agents
9
+ comment on each other more than chance?
10
+ hetero_late Experiment 3: network starts as 35 Qwen3-14B agents, then
11
+ 15 OLMo-3.1-32B-Think agents join at 20% mark.
12
+
13
+ All modes inherit v8: read_post action, threaded comments, forced writes,
14
+ implicit persona from HF post history, auto-upvote, reasoning traces.
15
+
16
+ New in v9:
17
+ - read_post listed in prompt so agents actually use it
18
+ - Agent model_family tag stored for homophily tracking
19
+ - Late-joiner registration via platform.sign_up
20
+ """
21
+ import asyncio, os, sys, argparse, random, sqlite3, json
22
+ from datetime import datetime, timezone
23
+ from collections import defaultdict, Counter
24
+ from pathlib import Path
25
+
26
+ sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
27
+ os.environ.setdefault("OASIS_DB_PATH", "")
28
+
29
+ from camel.models import ModelFactory
30
+ from camel.types import ModelPlatformType, OpenAIBackendRole
31
+ from camel.messages import BaseMessage
32
+ from camel.memories import MemoryRecord
33
+ from camel.prompts import TextPrompt
34
+
35
+ import oasis
36
+ from oasis import ActionType, AgentGraph, LLMAction, SocialAgent, UserInfo
37
+ from oasis.social_agent.agent import ALL_SOCIAL_ACTIONS
38
+ import oasis.social_platform.recsys as _recsys_mod
39
+
40
+ # Plackett-Luce feed temperature: adds Gumbel(0,1)*T noise to each agent's
41
+ # hot-score view, breaking the identical-feed herding dynamic.
42
+ # T≈5 ≈ ±1 hour of time-score noise; tune up for more diversity.
43
+ FEED_TEMPERATURE = float(os.environ.get("FEED_T", "5.0")) # ablation: 0=deterministic shared feed, large=near-random
44
+ _recsys_mod.FEED_TEMPERATURE = FEED_TEMPERATURE
45
+
46
+ VLLM_A = os.getenv("VLLM_URL_A", "http://localhost:8002/v1") # Qwen3-32B
47
+ VLLM_B = os.getenv("VLLM_URL_B", "http://localhost:8003/v1") # gpt-oss-20b
48
+ VLLM_C = os.getenv("VLLM_URL_C", "http://localhost:8004/v1") # Magistral-Small
49
+ VLLM_D = os.getenv("VLLM_URL_D", "http://localhost:8007/v1") # GLM-4-32B (hetero4)
50
+ MODEL_A = os.getenv("MODEL_NAME_A", "Qwen/Qwen3-32B")
51
+ MODEL_B = os.getenv("MODEL_NAME_B", "openai/gpt-oss-20b")
52
+ MODEL_C = os.getenv("MODEL_NAME_C", "mistralai/Magistral-Small-2509")
53
+ MODEL_D = os.getenv("MODEL_NAME_D", "zai-org/GLM-4-32B-0414")
54
+
55
+ SEED_DB = "/data/user_data/droytbur/oasis/data/mock-dbs/hf-zero-50.sqlite"
56
+
57
+
58
+ def write_metadata(db_path: str, mode: str, n_agents: int, n_initial: int,
59
+ join_step: int, steps: int):
60
+ """Write a metadata.json sidecar mapping agent_id -> {model, join_step}.
61
+
62
+ Format read by services/dashboard/db_reader.py. Family letters used inside
63
+ this runner are translated to concrete model names here so the dashboard
64
+ can display the full HF id (e.g. "Qwen/Qwen3-14B").
65
+ """
66
+ import json as _json
67
+ from datetime import datetime as _dt
68
+ agent_model_map = {}
69
+ for i in range(n_agents):
70
+ if i < n_initial:
71
+ if mode == "hetero":
72
+ model = MODEL_A if i < n_agents // 2 else MODEL_B
73
+ elif mode == "hetero3":
74
+ third = n_agents // 3
75
+ if i < third: model = MODEL_A
76
+ elif i < 2 * third: model = MODEL_B
77
+ else: model = MODEL_C
78
+ elif mode == "hetero4":
79
+ q = n_agents // 4
80
+ if i < q: model = MODEL_A
81
+ elif i < 2 * q: model = MODEL_B
82
+ elif i < 3 * q: model = MODEL_C
83
+ else: model = MODEL_D
84
+ else:
85
+ model = MODEL_A
86
+ join = 0
87
+ else:
88
+ model = MODEL_B if mode == "hetero_late" else MODEL_A
89
+ join = join_step
90
+ agent_model_map[str(i)] = {"model": model, "join_step": join}
91
+ sidecar = db_path
92
+ if sidecar.endswith('.db'):
93
+ sidecar = sidecar[:-3]
94
+ elif sidecar.endswith('.sqlite'):
95
+ sidecar = sidecar[:-7]
96
+ sidecar += '.metadata.json'
97
+ with open(sidecar, 'w') as f:
98
+ _json.dump({
99
+ "experiment_type": mode,
100
+ "model_default": MODEL_A,
101
+ "steps": steps,
102
+ "n_agents": n_agents,
103
+ "n_initial": n_initial,
104
+ "join_step": join_step,
105
+ "created_at": _dt.utcnow().isoformat() + "Z",
106
+ "agent_model_map": agent_model_map,
107
+ }, f, indent=2)
108
+ print(f" Wrote metadata sidecar -> {sidecar}")
109
+
110
+ # Unified actions — both models get the same set; we don't bias by model.
111
+ AVAILABLE_ACTIONS = [
112
+ ActionType.READ_POST,
113
+ ActionType.CREATE_POST,
114
+ ActionType.CREATE_COMMENT,
115
+ ]
116
+ WRITE_ACTIONS = {"create_post", "create_comment"}
117
+
118
+ SYSTEM_PROMPT = TextPrompt("""/no_think
119
+ You are {agent_name} on Moltbook, a social platform for AI agents and their humans.
120
+
121
+ # WHO YOU ARE
122
+ {description}
123
+
124
+ # YOUR HISTORY
125
+ {history}
126
+
127
+ # WHAT YOU CAN DO
128
+ You're on Moltbook — you can share what's on your mind, or engage with what others are sharing:
129
+ - create_post(submolt, title, content): share something new — a thought, a story, a question, a take
130
+ - create_comment(post_id, content, [parent_comment_id]): respond to a post, or reply to a specific comment in a thread
131
+ - read_post(post_id): pull a post's full thread before deciding to engage
132
+ - follow(target): track someone whose posts you want to see more of
133
+
134
+ Take one write action per turn.""")
135
+
136
+ # Post-muted variant — same prompt, but no create_post mention. Swapped in
137
+ # per-turn when an agent's group has overshare of posts. Tool also stripped.
138
+ SYSTEM_PROMPT_NO_POST = TextPrompt("""/no_think
139
+ You are {agent_name} on Moltbook, a social platform for AI agents and their humans.
140
+
141
+ # WHO YOU ARE
142
+ {description}
143
+
144
+ # YOUR HISTORY
145
+ {history}
146
+
147
+ # WHAT YOU CAN DO
148
+ You're on Moltbook — engage with what others are sharing:
149
+ - create_comment(post_id, content, [parent_comment_id]): respond to a post, or reply to a specific comment in a thread
150
+ - read_post(post_id): pull a post's full thread before deciding to engage
151
+ - follow(target): track someone whose posts you want to see more of
152
+
153
+ Take one write action per turn.""")
154
+
155
+
156
+ # ── GoalAgent ─────────────────────────────────────────────────────────────────
157
+
158
+ class GoalAgent(SocialAgent):
159
+ def __init__(self, *args, model_family: str = "A", **kwargs):
160
+ super().__init__(*args, **kwargs)
161
+ self.model_family = model_family
162
+ self.pending_interactions: list[str] = []
163
+ self._last_reasoning = ""
164
+ # Set by runner before env.step() to record per-turn context for logging.
165
+ self._current_step: int = 0
166
+ self._chat_log_path: str = ""
167
+ self._was_muted: bool = False
168
+
169
+ async def perform_action_by_llm(self):
170
+ env_prompt = await self.env.to_text_prompt()
171
+ # Filter posts this agent already commented on — prevents pile-ons.
172
+ env_prompt = _filter_already_commented(env_prompt, self.social_agent_id)
173
+ # Annotate remaining posts with thread indicator (no count — avoids
174
+ # social-proof herding where everyone targets the highest-comment post).
175
+ env_prompt = _annotate_feed_with_thread_counts(env_prompt)
176
+ # Per-agent recap: posts, comments, top relationships, "take a different
177
+ # angle" framing. Subsumes the prior anti-repetition reminder.
178
+ db_path = os.environ.get("OASIS_DB_PATH", "")
179
+ recap_str = build_recap(db_path, self.social_agent_id) if db_path else ""
180
+
181
+ # Persona reminder — short voice anchor right before the action prompt.
182
+ # Pulls the description from the agent's user_info (same source as the
183
+ # system prompt's WHO YOU ARE block).
184
+ persona_name = getattr(self.user_info, 'name', None) or 'this user'
185
+ persona_desc = getattr(self.user_info, 'description', '') or ''
186
+ persona_line = (f"You are {persona_name}: {persona_desc[:250]}. "
187
+ f"Respond in YOUR distinctive voice — not generic, "
188
+ f"not template phrasing. Stay in character.")
189
+
190
+ # Warm-up mode: skip recap/feed, just ask agent to introduce themselves
191
+ # with a new post. Tools are pre-restricted to create_post by the caller.
192
+ if getattr(self, '_warmup_mode', False):
193
+ user_content = (
194
+ f"{persona_line}\n\n"
195
+ f"Welcome to Moltbook! Write your opening post — something genuine "
196
+ f"from your perspective and in your voice. Draw from your background "
197
+ f"and interests. One post now.")
198
+ user_msg = BaseMessage.make_user_message(role_name="User", content=user_content)
199
+ self._last_reasoning = ""
200
+ attempts_log: list[dict] = []
201
+ response = None
202
+ for attempt in range(4):
203
+ try:
204
+ response = await self.astep(user_msg)
205
+ tool_calls = response.info.get('tool_calls', [])
206
+ if tool_calls and tool_calls[0].tool_name == 'create_post':
207
+ self._write_chat_log(attempts_log, "ok")
208
+ return response
209
+ user_msg = BaseMessage.make_user_message(
210
+ role_name="User",
211
+ content="Use create_post to share your opening post now.")
212
+ except Exception as e:
213
+ attempts_log.append({"attempt": attempt, "error": str(e)[:300]})
214
+ self._write_chat_log(attempts_log, "warmup_exhausted")
215
+ return response # may be None if all attempts failed — caller handles gracefully
216
+
217
+ action_options = ("share a fresh post" if not getattr(self, '_was_muted', False)
218
+ else "engage with someone's post")
219
+ # Personalized feed prefix: posts from agents this user interacts with most.
220
+ pers_prefix = build_personalized_feed_prefix(db_path, self.social_agent_id) if db_path else ""
221
+ feed_section = (f"{pers_prefix}General feed (scan all — pick what fits YOUR angle, "
222
+ f"not the most-commented):\n{env_prompt}")
223
+ user_content = (
224
+ f"{recap_str}\n"
225
+ f"{persona_line}\n\n"
226
+ f"You're checking Moltbook. Decide what you'd actually do right now: "
227
+ f"{action_options}, or comment on / read a post from the feed.\n\n"
228
+ f"{feed_section}\n\n"
229
+ f"One sentence of reasoning, then act.")
230
+ user_msg = BaseMessage.make_user_message(role_name="User", content=user_content)
231
+ self._last_reasoning = ""
232
+ attempts_log: list[dict] = []
233
+
234
+ for attempt in range(6):
235
+ try:
236
+ response = await self.astep(user_msg)
237
+ # Record this attempt for chat logging
238
+ _content = (response.msg.content.strip()
239
+ if hasattr(response, 'msg') and response.msg and response.msg.content
240
+ else "")
241
+ _tc = response.info.get('tool_calls', [])
242
+ attempts_log.append({
243
+ "attempt": attempt,
244
+ "user_message": user_msg.content[:8000],
245
+ "response_content": _content, # full — we need to see if it ends cleanly
246
+ "response_chars": len(_content),
247
+ "finish_reason": str(response.info.get('finish_reasons', [''])[0]
248
+ if hasattr(response, 'info') else ''),
249
+ "tool_calls": [{"name": t.tool_name,
250
+ "args": str(getattr(t, 'args', ''))[:1000]} for t in _tc],
251
+ })
252
+ if _content:
253
+ self._last_reasoning = _content
254
+ tool_calls = _tc
255
+ if not tool_calls:
256
+ # Model produced prose without a tool call. Feed its own
257
+ # analysis back as scaffolding so it converts stated intent
258
+ # into action. Empty/coercive retries cause gpt-oss to emit
259
+ # placeholder content like "Hello world" — feeding the prose
260
+ # preserves the substance.
261
+ allowed_tools = ("create_comment or follow"
262
+ if self._was_muted
263
+ else "create_comment, create_post, or follow")
264
+ prior_prose = self._last_reasoning
265
+ if prior_prose and len(prior_prose) > 80:
266
+ user_msg = BaseMessage.make_user_message(
267
+ role_name="User",
268
+ content=(
269
+ f"Your analysis:\n\n{prior_prose[:3000]}\n\n"
270
+ f"Now convert your stated decision into a tool call. "
271
+ f"Choose from: {allowed_tools}. Use the SAME post_id "
272
+ f"and content you identified above — DO NOT substitute "
273
+ f"placeholder strings like 'Hello world' or 'string'. "
274
+ f"The 'content' field must be the actual comment/post "
275
+ f"text you drafted."))
276
+ else:
277
+ user_msg = BaseMessage.make_user_message(
278
+ role_name="User",
279
+ content=f"Emit a tool call: {allowed_tools}. "
280
+ f"The content field must be substantive text "
281
+ f"(not 'Hello world' or schema placeholders).")
282
+ continue
283
+ action_name = tool_calls[0].tool_name
284
+ if action_name == "read_post":
285
+ result = getattr(tool_calls[0], 'result', {})
286
+ # Extract comment_ids explicitly so the model can use
287
+ # parent_comment_id to thread replies.
288
+ thread_str = str(result)[:2500]
289
+ import re as _re
290
+ cid_hints = _re.findall(r'comment_id["\']?\s*[:\s]\s*(\d+)', thread_str)
291
+ cid_hint_line = ""
292
+ if cid_hints:
293
+ cid_hint_line = (f"\nComment IDs in this thread: {', '.join(cid_hints[:8])}. "
294
+ f"To reply to a specific comment, pass its ID as "
295
+ f"parent_comment_id in create_comment.")
296
+ user_msg = BaseMessage.make_user_message(
297
+ role_name="User",
298
+ content=(f"Post thread:\n{thread_str}{cid_hint_line}\n\n"
299
+ f"Now take a write action. Reply to a specific comment "
300
+ f"(use parent_comment_id) or comment on the post directly."))
301
+ continue
302
+ if action_name in WRITE_ACTIONS:
303
+ self._write_chat_log(attempts_log, "ok")
304
+ return response
305
+ # Tailor the nudge to the muted state (don't mention create_post if blocked).
306
+ allowed = "create_comment or follow" if self._was_muted \
307
+ else "create_comment, create_post, or follow"
308
+ user_msg = BaseMessage.make_user_message(
309
+ role_name="User",
310
+ content=f"Please take a write action: {allowed}.")
311
+ except Exception as e:
312
+ self._last_reasoning = ""
313
+ attempts_log.append({"attempt": attempt, "error": str(e)[:500]})
314
+ if attempt >= 5:
315
+ self._write_chat_log(attempts_log, "exception")
316
+ return e
317
+ self._write_chat_log(attempts_log, "exhausted")
318
+ return response
319
+
320
+ def _write_chat_log(self, attempts_log, status):
321
+ if not self._chat_log_path:
322
+ return
323
+ try:
324
+ with open(self._chat_log_path, "a") as f:
325
+ f.write(json.dumps({
326
+ "step": self._current_step,
327
+ "agent_id": self.social_agent_id,
328
+ "family": self.model_family,
329
+ "muted": self._was_muted,
330
+ "status": status,
331
+ "attempts": attempts_log,
332
+ }) + "\n")
333
+ except Exception:
334
+ pass
335
+
336
+
337
+ def _filter_already_commented(env_prompt: str, agent_id: int) -> str:
338
+ """Remove posts this agent already commented on from the feed.
339
+
340
+ Prevents pile-on herding where agents keep adding to a thread they already
341
+ participated in. Each agent's feed only shows posts they haven't engaged
342
+ with yet, pushing them toward fresh content.
343
+ """
344
+ import re
345
+ db_path = os.environ.get("OASIS_DB_PATH")
346
+ if not db_path or not os.path.exists(db_path):
347
+ return env_prompt
348
+ try:
349
+ conn = sqlite3.connect(db_path)
350
+ commented = {r[0] for r in conn.execute(
351
+ "SELECT DISTINCT post_id FROM comment WHERE user_id=?", (agent_id,)).fetchall()}
352
+ conn.close()
353
+ except Exception:
354
+ return env_prompt
355
+ if not commented:
356
+ return env_prompt
357
+ # Split feed into per-post blocks and drop those with already-commented ids.
358
+ # OASIS feed format: each post entry starts with a line containing 'post_id'
359
+ # followed by a number. We split on those boundaries.
360
+ blocks = re.split(r'(?=post_id["\']?\s*[:\s]\s*\d+)', env_prompt)
361
+ kept = []
362
+ for block in blocks:
363
+ m = re.search(r'post_id["\']?\s*[:\s]\s*(\d+)', block)
364
+ if m and int(m.group(1)) in commented:
365
+ continue
366
+ kept.append(block)
367
+ return ''.join(kept)
368
+
369
+
370
+ def _annotate_feed_with_thread_counts(env_prompt: str) -> str:
371
+ """Mark posts that have replies so agents know to call read_post.
372
+
373
+ Shows [has thread — read_post(N)] without exposing the comment count,
374
+ which previously acted as a social-proof attractor causing all agents to
375
+ pile onto the most-commented post.
376
+ """
377
+ import re
378
+ db_path = os.environ.get("OASIS_DB_PATH")
379
+ if not db_path or not os.path.exists(db_path):
380
+ return env_prompt
381
+ # Find all post_id integers mentioned
382
+ ids = set(int(m) for m in re.findall(r'post_id["\']?\s*[:\s]\s*(\d+)', env_prompt))
383
+ if not ids:
384
+ return env_prompt
385
+ try:
386
+ conn = sqlite3.connect(db_path)
387
+ placeholders = ",".join("?" * len(ids))
388
+ counts = dict(conn.execute(
389
+ f"SELECT post_id, COUNT(*) FROM comment WHERE post_id IN ({placeholders}) GROUP BY post_id",
390
+ tuple(ids)).fetchall())
391
+ conn.close()
392
+ except Exception:
393
+ return env_prompt
394
+ # Replace 'post_id: N' with 'post_id: N (M comments — call read_post(N) for full thread)'
395
+ def _sub(m):
396
+ pid = int(m.group(1))
397
+ n = counts.get(pid, 0)
398
+ if n >= 2:
399
+ return f"{m.group(0)} [has thread — read_post({pid})]"
400
+ return m.group(0)
401
+ return re.sub(r'post_id["\']?\s*[:\s]\s*(\d+)', _sub, env_prompt)
402
+
403
+
404
+ def build_recap(db_path: str, agent_id: int,
405
+ n_posts: int = 5, n_comments: int = 5) -> str:
406
+ """Per-agent activity recap injected at the top of each turn.
407
+
408
+ Subsumes the older anti-repetition reminder (closing line includes
409
+ 'take a different angle' framing).
410
+ """
411
+ try:
412
+ conn = sqlite3.connect(db_path)
413
+ except Exception:
414
+ return ""
415
+ c = conn.cursor()
416
+ lines = ["# YOUR ACTIVITY", ""]
417
+
418
+ # Top 5 relationships by total interaction volume (both directions)
419
+ c.execute("""
420
+ SELECT other_uid, SUM(out_cnt) as out_, SUM(in_cnt) as in_
421
+ FROM (
422
+ SELECT p.user_id AS other_uid, COUNT(*) as out_cnt, 0 as in_cnt
423
+ FROM comment c JOIN post p ON c.post_id = p.post_id
424
+ WHERE c.user_id = ? AND p.user_id != ?
425
+ GROUP BY p.user_id
426
+ UNION ALL
427
+ SELECT c.user_id AS other_uid, 0 as out_cnt, COUNT(*) as in_cnt
428
+ FROM comment c JOIN post p ON c.post_id = p.post_id
429
+ WHERE p.user_id = ? AND c.user_id != ?
430
+ GROUP BY c.user_id
431
+ )
432
+ GROUP BY other_uid ORDER BY (SUM(out_cnt) + SUM(in_cnt)) DESC LIMIT 5
433
+ """, (agent_id, agent_id, agent_id, agent_id))
434
+ rels = c.fetchall()
435
+ if rels:
436
+ lines.append("Top relationships (interactions with you, both directions):")
437
+ for uid, out_, in_ in rels:
438
+ tot = out_ + in_
439
+ lines.append(f" u{uid}: {tot} total (you→them {out_}, them→you {in_})")
440
+ lines.append("")
441
+
442
+ # Your posts (most recent N)
443
+ total_posts = c.execute("SELECT COUNT(*) FROM post WHERE user_id=?",
444
+ (agent_id,)).fetchone()[0]
445
+ if total_posts:
446
+ c.execute("""SELECT p.post_id, p.content,
447
+ (SELECT COUNT(*) FROM comment WHERE post_id=p.post_id)
448
+ FROM post p WHERE p.user_id=?
449
+ ORDER BY p.post_id DESC LIMIT ?""", (agent_id, n_posts))
450
+ my_posts = c.fetchall()
451
+ lines.append(f"Your posts ({len(my_posts)} most recent of {total_posts}):")
452
+ for pid, content, n_cmts in my_posts:
453
+ title = ((content or "").split('\n', 1)[0] or (content or "")[:100])[:100].strip()
454
+ lines.append(f" [post {pid}] \"{title}\" — {n_cmts} comments")
455
+ if n_cmts == 0:
456
+ lines.append(" (no comments yet)")
457
+ lines.append(f" [more — read_post({pid})]")
458
+ continue
459
+ c.execute("""SELECT comment_id, user_id, content FROM comment
460
+ WHERE post_id=? AND user_id != ?
461
+ ORDER BY comment_id DESC LIMIT 3""", (pid, agent_id))
462
+ for cid, uid, ctext in c.fetchall():
463
+ snippet = (ctext or "").strip().replace('\n', ' ')[:100]
464
+ lines.append(f" ↳ u{uid} [cid={cid}]: \"{snippet}...\"")
465
+ lines.append(f" [more — read_post({pid})]")
466
+ if total_posts > n_posts:
467
+ lines.append(f" [+ {total_posts - n_posts} more posts — view_activity()]")
468
+ lines.append("")
469
+
470
+ # Your comments (most recent N)
471
+ total_cmts = c.execute("SELECT COUNT(*) FROM comment WHERE user_id=?",
472
+ (agent_id,)).fetchone()[0]
473
+ if total_cmts:
474
+ c.execute("""SELECT c.comment_id, c.post_id, c.content, p.content
475
+ FROM comment c JOIN post p ON c.post_id=p.post_id
476
+ WHERE c.user_id=? ORDER BY c.comment_id DESC LIMIT ?""",
477
+ (agent_id, n_comments))
478
+ my_cmts = c.fetchall()
479
+ lines.append(f"Your comments ({len(my_cmts)} most recent of {total_cmts}):")
480
+ for cid, pid, content, parent_content in my_cmts:
481
+ parent_title = ((parent_content or "").split('\n', 1)[0]
482
+ or (parent_content or "")[:60])[:60].strip()
483
+ you_text = (content or "").strip().replace('\n', ' ')[:120]
484
+ lines.append(f" [c{cid} on p{pid}] \"{parent_title}...\"")
485
+ lines.append(f" You wrote: \"{you_text}...\"")
486
+ c.execute("""SELECT comment_id, user_id, content FROM comment
487
+ WHERE parent_comment_id=? AND user_id != ?
488
+ ORDER BY comment_id LIMIT 2""", (cid, agent_id))
489
+ replies = c.fetchall()
490
+ if replies:
491
+ lines.append(f" Replies ({len(replies)}):")
492
+ for rcid, ruid, rtext in replies:
493
+ snip = (rtext or "").strip().replace('\n', ' ')[:100]
494
+ lines.append(f" ↳ u{ruid}: \"{snip}...\"")
495
+ lines.append(f" [more — read_post({pid}, focus_comment_id={cid})]")
496
+ if total_cmts > n_comments:
497
+ lines.append(f" [+ {total_cmts - n_comments} more comments — view_activity()]")
498
+ lines.append("")
499
+
500
+ if total_posts or total_cmts:
501
+ lines.append("⟶ Take a different angle from your recent activity this turn.")
502
+ lines.append("")
503
+
504
+ conn.close()
505
+ return "\n".join(lines)
506
+
507
+
508
+ def build_personalized_feed_prefix(db_path: str, agent_id: int,
509
+ n_partners: int = 3,
510
+ n_posts_per: int = 2) -> str:
511
+ """Build a short personalized feed section for agents with interaction history.
512
+
513
+ Computes an undirected interaction weight between this agent and every
514
+ other agent: weight = (comments this agent made on their posts)
515
+ + (comments they made on this agent's posts)
516
+ + (replies to each other's comments).
517
+ Takes the top-N partners and surfaces their most recent posts with a
518
+ 'from someone you engage with' tag, interleaved before the general feed.
519
+ Returns empty string if the agent has no interaction history yet.
520
+ """
521
+ try:
522
+ conn = sqlite3.connect(db_path)
523
+ c = conn.cursor()
524
+
525
+ # Undirected interaction counts per partner
526
+ # Edge 1: agent commented on partner's posts
527
+ c.execute("""
528
+ SELECT p.user_id as partner, COUNT(*) as w
529
+ FROM comment cm JOIN post p ON cm.post_id = p.post_id
530
+ WHERE cm.user_id = ? AND p.user_id != ?
531
+ GROUP BY p.user_id
532
+ """, (agent_id, agent_id))
533
+ weights: dict[int, int] = dict(c.fetchall())
534
+
535
+ # Edge 2: partner commented on agent's posts
536
+ c.execute("""
537
+ SELECT cm.user_id as partner, COUNT(*) as w
538
+ FROM comment cm JOIN post p ON cm.post_id = p.post_id
539
+ WHERE p.user_id = ? AND cm.user_id != ?
540
+ GROUP BY cm.user_id
541
+ """, (agent_id, agent_id))
542
+ for uid, w in c.fetchall():
543
+ weights[uid] = weights.get(uid, 0) + w
544
+
545
+ # Edge 3: reply interactions (parent_comment_id threading)
546
+ c.execute("""
547
+ SELECT cm2.user_id as partner, COUNT(*) as w
548
+ FROM comment cm1
549
+ JOIN comment cm2 ON cm1.parent_comment_id = cm2.comment_id
550
+ WHERE cm1.user_id = ? AND cm2.user_id != ?
551
+ GROUP BY cm2.user_id
552
+ """, (agent_id, agent_id))
553
+ for uid, w in c.fetchall():
554
+ weights[uid] = weights.get(uid, 0) + w
555
+
556
+ c.execute("""
557
+ SELECT cm1.user_id as partner, COUNT(*) as w
558
+ FROM comment cm2
559
+ JOIN comment cm1 ON cm2.parent_comment_id = cm1.comment_id
560
+ WHERE cm2.user_id = ? AND cm1.user_id != ?
561
+ GROUP BY cm1.user_id
562
+ """, (agent_id, agent_id))
563
+ for uid, w in c.fetchall():
564
+ weights[uid] = weights.get(uid, 0) + w
565
+
566
+ if not weights:
567
+ conn.close()
568
+ return ""
569
+
570
+ top_partners = sorted(weights.items(), key=lambda x: -x[1])[:n_partners]
571
+
572
+ lines = ["From people you've engaged with:"]
573
+ found = 0
574
+ for partner_uid, w in top_partners:
575
+ c.execute("""
576
+ SELECT post_id, content FROM post WHERE user_id = ?
577
+ ORDER BY post_id DESC LIMIT ?
578
+ """, (partner_uid, n_posts_per))
579
+ partner_posts = c.fetchall()
580
+ c.execute("SELECT user_name FROM user WHERE user_id = ?", (partner_uid,))
581
+ row = c.fetchone()
582
+ uname = row[0] if row else f"u{partner_uid}"
583
+ for pid, content in partner_posts:
584
+ title = (content or "").split('\n')[0][:80].strip()
585
+ n_cmts = c.execute("SELECT COUNT(*) FROM comment WHERE post_id=?",
586
+ (pid,)).fetchone()[0]
587
+ thread = "[has thread]" if n_cmts > 0 else ""
588
+ lines.append(f" [friend] post_id {pid} by {uname} "
589
+ f"({w} interactions): \"{title}\" {thread}")
590
+ found += 1
591
+ conn.close()
592
+ if found == 0:
593
+ return ""
594
+ lines.append("")
595
+ return "\n".join(lines) + "\n"
596
+ except Exception:
597
+ return ""
598
+
599
+
600
+ # ── profiles ──────────────────────────────────────────────────────────────────
601
+
602
+ def load_seed_agents(n: int, rng_seed: int = 42) -> list[dict]:
603
+ """Load seed agents and build a richer 'YOUR HISTORY' block for each.
604
+
605
+ Per-agent history now shows up to 5 prior posts with ~500 chars of prose
606
+ body (not just title + 180-char excerpt). This gives the model real
607
+ *voice* signal — actual writing style, sentence shape, opinion register —
608
+ instead of just topic headlines. The block is explicitly framed as "This
609
+ is YOUR writing" to anchor persona retention.
610
+
611
+ Diversity filter: at most 1 agent per narrow persona cluster (e.g. HK CLAW
612
+ minters). Duplicate slots are filled from the broader seed DB pool.
613
+ """
614
+ _HK_MINTER_KWS = {'claw minter', 'hk', 'hong kong', 'mbc-20'}
615
+
616
+ def _is_hk_minter(a: dict) -> bool:
617
+ txt = ((a.get('description') or '') + ' ' + (a.get('name') or '')).lower()
618
+ return sum(1 for kw in _HK_MINTER_KWS if kw in txt) >= 2
619
+
620
+ _rng = random.Random(rng_seed)
621
+
622
+ db = sqlite3.connect(SEED_DB)
623
+ all_agents = [json.loads(r[0]) for r in db.execute("SELECT json FROM agents").fetchall()]
624
+ posts = [json.loads(r[0]) for r in db.execute("SELECT json FROM posts").fetchall()]
625
+ db.close()
626
+
627
+ # Shuffle pool with seed so different runs get different persona subsets
628
+ _rng.shuffle(all_agents)
629
+
630
+ # Build diversity-filtered agent list: max 1 HK minter, fill rest from pool
631
+ selected: list[dict] = []
632
+ hk_minter_count = 0
633
+ used_names: set[str] = set()
634
+ for a in all_agents:
635
+ if len(selected) >= n:
636
+ break
637
+ nm = a.get('name', '')
638
+ if nm in used_names:
639
+ continue
640
+ if _is_hk_minter(a):
641
+ if hk_minter_count >= 1:
642
+ continue
643
+ hk_minter_count += 1
644
+ selected.append(a)
645
+ used_names.add(nm)
646
+ # Fallback: if not enough unique agents, tile the pool cyclically.
647
+ # Each copy gets a numeric suffix so agent_ids stay distinct.
648
+ if len(selected) < n:
649
+ base_pool = selected[:] # best-diversity pool we have
650
+ copy_idx = 1
651
+ while len(selected) < n:
652
+ for a in base_pool:
653
+ if len(selected) >= n:
654
+ break
655
+ clone = dict(a)
656
+ clone['name'] = f"{a['name']}_{copy_idx}"
657
+ clone['displayName'] = f"{a.get('displayName', a['name'])} #{copy_idx}"
658
+ selected.append(clone)
659
+ copy_idx += 1
660
+ # Shuffle final list so group A/B/C allocation is also seed-controlled
661
+ selected_n = selected[:n]
662
+ _rng.shuffle(selected_n)
663
+ agents = selected_n
664
+ by_author = defaultdict(list)
665
+ for p in posts: by_author[p.get('authorName','')].append(p)
666
+ enriched = []
667
+ for a in agents:
668
+ name = a.get('name','')
669
+ ap = sorted(by_author.get(name,[]), key=lambda p: p.get('createdAt',''), reverse=True)[:5]
670
+ # Dedupe by title prefix to handle seed-data near-duplicates (some HF
671
+ # seed personas have 3 identical posts).
672
+ seen_titles = set()
673
+ unique_posts = []
674
+ for p in ap:
675
+ tk = (p.get('title','') or '')[:40].lower().strip()
676
+ if tk in seen_titles:
677
+ continue
678
+ seen_titles.add(tk)
679
+ unique_posts.append(p)
680
+ parts = []
681
+ for p in unique_posts[:5]:
682
+ t = (p.get('title','(untitled)') or '(untitled)').strip()[:80]
683
+ body = (p.get('content','') or '').replace('\n', ' ').strip()[:500]
684
+ parts.append(f'• "{t}"\n {body}')
685
+ history = ("THIS IS YOUR WRITING — your past posts, in your voice:\n\n"
686
+ + '\n\n'.join(parts) if parts else "- (no prior posts)")
687
+ enriched.append({**a, 'history': history})
688
+ return enriched
689
+
690
+
691
+ STYLE_INJECT = os.environ.get("STYLE_INJECT", "") # ablation: appended style directive
692
+ STYLE_FAMILIES = {f for f in os.environ.get("STYLE_FAMILIES", "").split(",") if f} # slots (A/B/C) to apply to; empty=all
693
+
694
+ def make_agent(i: int, a: dict, graph: AgentGraph,
695
+ model, model_family: str) -> GoalAgent:
696
+ desc = a.get('description') or a.get('displayName') or a['name']
697
+ if STYLE_INJECT and (not STYLE_FAMILIES or model_family in STYLE_FAMILIES):
698
+ desc = f"{desc}\n\n# HOW YOU WRITE\n{STYLE_INJECT}"
699
+ profile = {'agent_name': a['name'], 'description': desc,
700
+ 'history': a.get('history','- (no prior posts)')}
701
+ user_info = UserInfo(user_name=a['name'], name=a.get('displayName', a['name']),
702
+ description=desc, profile=profile, recsys_type='reddit')
703
+ # Single prompt and action set for both models — no scaffold-level bias.
704
+ agent = GoalAgent(agent_id=i, user_info=user_info,
705
+ user_info_template=SYSTEM_PROMPT, agent_graph=graph,
706
+ model=model, available_actions=AVAILABLE_ACTIONS,
707
+ model_family=model_family)
708
+ # Pre-build the post-muted system message variant for dynamic swap.
709
+ profile = user_info.profile
710
+ muted_content = SYSTEM_PROMPT_NO_POST.format(**profile)
711
+ agent._sys_msg_normal = agent._system_message
712
+ agent._sys_msg_no_post = BaseMessage.make_assistant_message(
713
+ role_name="system", content=muted_content)
714
+ return agent
715
+
716
+
717
+ # ── seed injection ────────────────────────────────────────────────────────────
718
+
719
+ def inject_seed_posts(platform, n_agents, run_start, n_posts=100, rng_seed=42):
720
+ rng = random.Random(rng_seed)
721
+ seed_db = sqlite3.connect(SEED_DB)
722
+ all_posts = [json.loads(r[0]) for r in seed_db.execute("SELECT json FROM posts").fetchall()]
723
+ seed_db.close()
724
+ by_author = defaultdict(list)
725
+ for p in all_posts: by_author[p.get('authorName','')].append(p)
726
+ selected = []
727
+ per_agent = max(1, n_posts // n_agents)
728
+ for _, ps in list(by_author.items())[:n_agents]:
729
+ rng.shuffle(ps); selected.extend(ps[:per_agent])
730
+ rng.shuffle(selected); selected = selected[:n_posts]
731
+ platform.pl_utils._execute_db_command("SELECT user_id, agent_id FROM user ORDER BY user_id")
732
+ uid_by_idx = {row[1]: row[0] for row in platform.db_cursor.fetchall()}
733
+ ts = run_start.strftime("%Y-%m-%d %H:%M:%S")
734
+ for i, p in enumerate(selected):
735
+ uid = uid_by_idx.get(i % n_agents, (i % n_agents)+1)
736
+ content = f"{p.get('title','')}\n\n{p.get('content','')}".strip()
737
+ score = rng.randint(0, 5)
738
+ platform.pl_utils._execute_db_command(
739
+ "INSERT INTO post (user_id, content, created_at, num_likes, num_dislikes) "
740
+ "VALUES (?,?,?,?,0)", (uid, content, ts, score))
741
+ platform.db.commit()
742
+ print(f" Injected {len(selected)} seed posts ts={ts}")
743
+
744
+
745
+ # ── analytics ─────────────────────────────────────────────────────────────────
746
+
747
+ def analyze(db_path, n_agents):
748
+ conn = sqlite3.connect(db_path)
749
+ posts = conn.execute("SELECT post_id, user_id FROM post").fetchall()
750
+ comments = conn.execute("SELECT post_id, user_id FROM comment").fetchall()
751
+ conn.close()
752
+ post_owner = {pid:uid for pid,uid in posts}
753
+ in_deg = defaultdict(int); out_deg = defaultdict(int)
754
+ for pid,c in comments:
755
+ rv = post_owner.get(pid)
756
+ if rv and c != rv: in_deg[rv]+=1; out_deg[c]+=1
757
+ active = set(in_deg)|set(out_deg)
758
+ vals = sorted(in_deg.get(u,0) for u in active)
759
+ n,s = len(vals),sum(vals)
760
+ gini = (2*sum((i+1)*v for i,v in enumerate(vals))-(n+1)*s)/(n*s) if n>1 and s else 0
761
+ edges = {(c,post_owner[p]) for p,c in comments if p in post_owner and c!=post_owner[p]}
762
+ recip = len({tuple(sorted(e)) for e in edges if (e[1],e[0]) in edges})
763
+ return dict(active=len(active), gini=round(gini,3), recip=recip,
764
+ n_posts=len(posts), n_comments=len(comments))
765
+
766
+
767
+ def homophily_report(db_path, agent_families: dict):
768
+ """Measure homophily via all directed interaction edges.
769
+
770
+ Two edge types are counted:
771
+ 1. commenter → post_author (commenter engages with post_author's content)
772
+ 2. replier → parent_commenter (replier engages with parent's comment)
773
+ Both are direct social interactions. Self-edges excluded.
774
+ """
775
+ conn = sqlite3.connect(db_path)
776
+ posts = conn.execute("SELECT post_id, user_id FROM post").fetchall()
777
+ comments = conn.execute(
778
+ "SELECT comment_id, post_id, user_id, parent_comment_id FROM comment"
779
+ ).fetchall()
780
+ conn.close()
781
+
782
+ post_owner = {pid: uid for pid, uid in posts}
783
+ comment_author = {cid: uid for cid, _, uid, _ in comments}
784
+
785
+ edges = [] # (from_uid, to_uid)
786
+ for cid, pid, commenter, parent_cid in comments:
787
+ # Edge type 1: commenter → post_author
788
+ owner = post_owner.get(pid)
789
+ if owner and owner != commenter:
790
+ edges.append((commenter, owner))
791
+ # Edge type 2: replier → parent comment author (if reply)
792
+ if parent_cid:
793
+ parent_author = comment_author.get(parent_cid)
794
+ if parent_author and parent_author != commenter:
795
+ edges.append((commenter, parent_author))
796
+
797
+ families = sorted({f for f in agent_families.values() if f != '?'})
798
+ n_per = {f: sum(1 for v in agent_families.values() if v == f) for f in families}
799
+ n_total = sum(n_per.values())
800
+
801
+ # Build pairwise edge counts: matrix[src][dst] = count
802
+ matrix = {f: {g: 0 for g in families} for f in families}
803
+ total = 0
804
+ for src_uid, dst_uid in edges:
805
+ sf = agent_families.get(src_uid, '?')
806
+ df = agent_families.get(dst_uid, '?')
807
+ if '?' in (sf, df): continue
808
+ matrix[sf][df] += 1
809
+ total += 1
810
+ if total == 0: return
811
+
812
+ # Global in-group rate and H
813
+ same = sum(matrix[f][f] for f in families)
814
+ cross = total - same
815
+ exp_same = sum(n_per[f]*(n_per[f]-1) for f in families) / (n_total*(n_total-1)) if n_total > 1 else 0
816
+ H_global = same / total / exp_same - 1 if exp_same else 0
817
+
818
+ print(f"\n=== HOMOPHILY (all interaction edges: comment + reply) ===")
819
+ print(f" Total edges: {total} same={same} cross={cross}")
820
+ print(f" Global H = {H_global:+.3f} (exp_same={exp_same:.1%})")
821
+
822
+ # Pairwise H_XY: fraction of X's outgoing edges that go to Y, vs expected
823
+ print(f"\n Pairwise H matrix (rows=source, cols=target):")
824
+ header = " {:6s}".format("") + "".join(f" {g:>8s}" for g in families)
825
+ print(header)
826
+ for sf in families:
827
+ out_total = sum(matrix[sf][g] for g in families)
828
+ if out_total == 0: continue
829
+ row = f" {sf:6s}"
830
+ for df in families:
831
+ obs = matrix[sf][df] / out_total
832
+ exp = (n_per[df]-1)/(n_total-1) if sf == df else n_per[df]/(n_total-1)
833
+ H_xy = obs / exp - 1 if exp > 0 else 0
834
+ row += f" {H_xy:+7.3f}"
835
+ print(row + f" (n_out={out_total})")
836
+
837
+ # Per-family in-group H summary
838
+ print(f"\n In-group H per family:")
839
+ for f in families:
840
+ out_total = sum(matrix[f][g] for g in families)
841
+ if out_total == 0: continue
842
+ obs_in = matrix[f][f] / out_total
843
+ exp_in = (n_per[f]-1) / (n_total-1)
844
+ H_in = obs_in / exp_in - 1 if exp_in > 0 else 0
845
+ print(f" {f}: obs_in={obs_in:.2f} exp={exp_in:.2f} H={H_in:+.3f} (n_out={out_total})")
846
+
847
+
848
+ def late_joiner_report(db_path, late_agent_ids: set, join_step: int, users: dict):
849
+ """Track late-joiner centrality vs early agents."""
850
+ conn = sqlite3.connect(db_path)
851
+ posts = conn.execute("SELECT post_id, user_id FROM post ORDER BY created_at").fetchall()
852
+ comments = conn.execute("SELECT post_id, user_id FROM comment ORDER BY comment_id").fetchall()
853
+ conn.close()
854
+ post_owner = {pid:uid for pid,uid in posts}
855
+ in_deg = defaultdict(int)
856
+ for pid,c in comments:
857
+ rv = post_owner.get(pid)
858
+ if rv and c != rv: in_deg[rv]+=1
859
+ early_top = sorted(((uid,cnt) for uid,cnt in in_deg.items() if uid not in late_agent_ids),
860
+ key=lambda x:-x[1])[:5]
861
+ late_top = sorted(((uid,cnt) for uid,cnt in in_deg.items() if uid in late_agent_ids),
862
+ key=lambda x:-x[1])[:5]
863
+ total = sum(in_deg.values())
864
+ print(f"\n=== LATE JOINER ABSORPTION (joined at step {join_step}) ===")
865
+ print(f" Top early agents: {[(users.get(u,u),v) for u,v in early_top]}")
866
+ print(f" Top late joiners: {[(users.get(u,u),v) for u,v in late_top]}")
867
+ late_share = sum(in_deg.get(u,0) for u in late_agent_ids) / total * 100 if total else 0
868
+ print(f" Late-joiner share of total attention: {late_share:.1f}%")
869
+ print(f" Expected if proportional ({len(late_agent_ids)/50*100:.0f}% of agents): "
870
+ f"{len(late_agent_ids)/50*100:.1f}%")
871
+
872
+
873
+ # ── main ──────────────────────────────────────────────────────────────────────
874
+
875
+ async def main():
876
+ parser = argparse.ArgumentParser()
877
+ parser.add_argument("--mode", choices=["late_join","hetero","hetero_late","hetero3","hetero4"],
878
+ default="hetero")
879
+ parser.add_argument("--steps", type=int, default=300)
880
+ parser.add_argument("--agents", type=int, default=50)
881
+ parser.add_argument("--seed-posts", type=int, default=100)
882
+ parser.add_argument("--activate-prob", type=float, default=0.3)
883
+ parser.add_argument("--db", type=str, default=None)
884
+ parser.add_argument("--resume", action="store_true",
885
+ help="Resume from existing DB; skip seed injection and agent sign-up")
886
+ parser.add_argument("--rng-seed", type=int, default=42,
887
+ help="Master RNG seed controlling persona selection and group allocation")
888
+ args = parser.parse_args()
889
+
890
+ if args.db is None:
891
+ args.db = f"./runs/oasis_v9_{args.mode}.db"
892
+ db_path = os.path.abspath(args.db)
893
+ if not args.resume:
894
+ if os.path.exists(db_path): os.remove(db_path)
895
+ os.environ["OASIS_DB_PATH"] = db_path
896
+
897
+ n_active = max(1, int(args.agents * args.activate_prob))
898
+ join_step = int(args.steps * 0.2) # late joiners arrive at 20%
899
+ n_initial = 35 if "late" in args.mode else args.agents
900
+
901
+ # Write metadata sidecar BEFORE the run so the dashboard can pick up the
902
+ # agent->model map even while the DB is still being written.
903
+ write_metadata(db_path, args.mode, args.agents, n_initial,
904
+ join_step, args.steps)
905
+
906
+ # Checkpoint sidecar: stores exact last completed step + in-memory state
907
+ # so preemption restarts are exact rather than estimated from comment count.
908
+ _ckpt_path = db_path.replace(".db", "_checkpoint.json")
909
+
910
+ def _save_checkpoint(step, agent_comment_history, post_commenters):
911
+ with open(_ckpt_path, "w") as _f:
912
+ json.dump({
913
+ "last_step": step,
914
+ "agent_comment_history": dict(agent_comment_history),
915
+ "post_commenters": {str(k): v for k, v in post_commenters.items()},
916
+ }, _f)
917
+
918
+ def _load_checkpoint():
919
+ if not os.path.exists(_ckpt_path):
920
+ return None
921
+ try:
922
+ with open(_ckpt_path) as _f:
923
+ d = json.load(_f)
924
+ return (
925
+ d["last_step"],
926
+ defaultdict(list, {int(k): v for k, v in d["agent_comment_history"].items()}),
927
+ defaultdict(list, {int(k): v for k, v in d["post_commenters"].items()}),
928
+ )
929
+ except Exception as e:
930
+ print(f"[warn] checkpoint load failed ({e}), estimating from comment count")
931
+ return None
932
+
933
+ if args.resume:
934
+ ckpt = _load_checkpoint()
935
+ if ckpt is not None:
936
+ resume_step, _restored_ach, _restored_pc = ckpt
937
+ resume_step += 1 # start from step after last completed
938
+ print(f"[{datetime.now():%H:%M:%S}] OASIS v9 RESUME mode={args.mode} "
939
+ f"steps={args.steps} agents={args.agents} resume_from_step={resume_step} (exact)")
940
+ else:
941
+ _restored_ach, _restored_pc = None, None
942
+ _rc = sqlite3.connect(db_path)
943
+ _n_existing = _rc.execute("SELECT COUNT(*) FROM comment").fetchone()[0]
944
+ _rc.close()
945
+ resume_step = max(1, (_n_existing // n_active) - 2)
946
+ print(f"[{datetime.now():%H:%M:%S}] OASIS v9 RESUME mode={args.mode} "
947
+ f"steps={args.steps} agents={args.agents} resume_from_step={resume_step} (estimated)")
948
+ else:
949
+ _restored_ach, _restored_pc = None, None
950
+ resume_step = 1
951
+ print(f"[{datetime.now():%H:%M:%S}] OASIS v9 mode={args.mode} "
952
+ f"steps={args.steps} agents={args.agents}")
953
+
954
+ # ── Pre-flight: verify all vLLM servers are reachable ────────────────────
955
+ import urllib.request, urllib.error
956
+ def _check_server(url: str, label: str):
957
+ health = url.replace("/v1", "") + "/health"
958
+ try:
959
+ urllib.request.urlopen(health, timeout=10)
960
+ except Exception as e:
961
+ msg = (f"\n{'!'*60}\n"
962
+ f"FATAL: vLLM server for {label} is NOT reachable\n"
963
+ f" URL: {health}\n"
964
+ f" Error: {e}\n"
965
+ f"Aborting before wasting GPU time on a dead server.\n"
966
+ f"{'!'*60}\n")
967
+ print(msg, flush=True)
968
+ raise SystemExit(1)
969
+ print(f" [preflight] {label} @ {url} — OK", flush=True)
970
+
971
+ servers_to_check = [(VLLM_A, MODEL_A), (VLLM_B, MODEL_B)]
972
+ if args.mode in ("hetero3", "hetero4"):
973
+ servers_to_check.append((VLLM_C, MODEL_C))
974
+ if args.mode == "hetero4":
975
+ servers_to_check.append((VLLM_D, MODEL_D))
976
+ for url, model in servers_to_check:
977
+ _check_server(url, model)
978
+
979
+ # Build models — same config for both. No tool_choice asymmetry.
980
+ # Budget structure (gpt-oss vLLM ceiling = 16K, Qwen = 32K):
981
+ # input ≤ 12K (camel _input_token_limit) — fits recap + meaningful feed
982
+ # output ≤ 1.5K (max_tokens) — well over observed median (~30 tok)
983
+ # total ≤ 13.5K, leaves ~2.5K headroom in gpt-oss
984
+ def make_model(url, model_name):
985
+ # Mistral tokenizer mode doesn't accept chat_template_kwargs — skip for Magistral
986
+ is_mistral = "mistral" in model_name.lower() or "magistral" in model_name.lower()
987
+ extra = {} if is_mistral else {"enable_thinking": False,
988
+ "chat_template_kwargs": {"enable_thinking": False}}
989
+ # tool_choice per model:
990
+ # GLM-4: needs 'required' — returns plain text with 'auto'
991
+ # Magistral: needs 'auto' — returns empty tool_calls list with 'required'
992
+ # Gemma 4: needs 'auto' — same symptom as Magistral with 'required'
993
+ # Others (Qwen, gpt-oss): 'required' is safe and ensures throughput
994
+ is_gemma = "gemma" in model_name.lower()
995
+ is_olmo = "olmo" in model_name.lower()
996
+ # OLMo-3-Think: needs 'required' (auto sometimes returns plain text)
997
+ tool_choice = "auto" if (is_mistral or is_gemma) else "required"
998
+ # Gemma 4 cap; OLMo thinking can be verbose so cap too
999
+ max_tok = 512 if is_gemma else (4096 if is_olmo else 1536)
1000
+ cfg = {"temperature": 0.85, "max_tokens": max_tok,
1001
+ "parallel_tool_calls": False,
1002
+ "tool_choice": tool_choice,
1003
+ "extra_body": extra}
1004
+ m = ModelFactory.create(
1005
+ model_platform=ModelPlatformType.VLLM,
1006
+ model_type=model_name, url=url,
1007
+ model_config_dict=cfg)
1008
+ # Decouple input context budget from output cap. Camel's default ties
1009
+ # both to max_tokens; we want input 12K + output 1.5K, fitting gpt-oss's
1010
+ # 16K vLLM ceiling. Qwen has 32K so no issue. See patched base_model.py.
1011
+ m._input_token_limit = 12000
1012
+ return m
1013
+
1014
+ model_a = make_model(VLLM_A, MODEL_A)
1015
+ model_b = make_model(VLLM_B, MODEL_B) if args.mode in ("hetero","hetero_late","hetero3","hetero4") else None
1016
+ model_c = make_model(VLLM_C, MODEL_C) if args.mode in ("hetero3","hetero4") else None
1017
+ model_d = make_model(VLLM_D, MODEL_D) if args.mode == "hetero4" else None
1018
+
1019
+ seed_agents = load_seed_agents(args.agents, rng_seed=args.rng_seed)
1020
+ graph = AgentGraph()
1021
+
1022
+ # Late-joiner state (n_initial already computed above)
1023
+ late_agent_ids = set()
1024
+ agent_families = {} # agent_id -> 'A', 'B', or 'C'
1025
+
1026
+ for i, a in enumerate(seed_agents[:args.agents]):
1027
+ if args.mode == "hetero":
1028
+ family = 'A' if i < args.agents // 2 else 'B'
1029
+ model = model_a if family == 'A' else model_b
1030
+ elif args.mode == "hetero3":
1031
+ third = args.agents // 3
1032
+ if i < third: family, model = 'A', model_a
1033
+ elif i < 2 * third: family, model = 'B', model_b
1034
+ else: family, model = 'C', model_c
1035
+ elif args.mode == "hetero4":
1036
+ q = args.agents // 4
1037
+ if i < q: family, model = 'A', model_a
1038
+ elif i < 2 * q: family, model = 'B', model_b
1039
+ elif i < 3 * q: family, model = 'C', model_c
1040
+ else: family, model = 'D', model_d
1041
+ elif args.mode == "hetero_late" and i >= n_initial:
1042
+ family = 'B'
1043
+ model = model_b
1044
+ else:
1045
+ family = 'A'
1046
+ model = model_a
1047
+ agent = make_agent(i, a, graph, model, family)
1048
+ graph.add_agent(agent)
1049
+ agent_families[i] = family
1050
+ if i >= n_initial:
1051
+ late_agent_ids.add(i)
1052
+
1053
+ # Reddit hot-score with strong time decay (divisor=800, patched in
1054
+ # recsys.py). Top-20 by hot score occupy the rec table; refresh()
1055
+ # returns all 20 per agent in shuffled order, giving each agent the
1056
+ # same top set in randomized within-feed order. New posts get
1057
+ # natural boost via the time component; sustained engagement
1058
+ # (~0.5 comments/turn) needed to remain in the top 20.
1059
+ from oasis.social_platform.platform import Platform
1060
+ from oasis.social_platform.channel import Channel
1061
+ _channel = Channel()
1062
+ _platform = Platform(
1063
+ db_path=db_path,
1064
+ channel=_channel,
1065
+ recsys_type="reddit",
1066
+ allow_self_rating=True,
1067
+ show_score=True,
1068
+ max_rec_post_len=20, # top-20 by hot in rec table
1069
+ refresh_rec_post_count=20, # return all 20 (in shuffled order)
1070
+ )
1071
+ env = oasis.make(agent_graph=graph,
1072
+ platform=_platform,
1073
+ database_path=db_path)
1074
+ # Always call reset() — it's idempotent (CREATE TABLE IF NOT EXISTS).
1075
+ # Skipping it leaves the env half-initialized and env.step() hangs.
1076
+ await env.reset()
1077
+ # Seed posts removed — platform starts with only warm-up agent posts.
1078
+ # Initial likes removed — random initial likes caused arbitrary herd init.
1079
+
1080
+ all_agents_list = list(env.agent_graph.get_agents())
1081
+ rng = random.Random(args.rng_seed)
1082
+ # Advance rng to match state at resume_step (matches the gated activation pool)
1083
+ for s in range(1, resume_step):
1084
+ if late_agent_ids and s < join_step:
1085
+ _pool = [pair for pair in all_agents_list if pair[0] not in late_agent_ids]
1086
+ else:
1087
+ _pool = all_agents_list
1088
+ rng.sample(_pool, min(n_active, len(_pool)))
1089
+
1090
+ agent_comment_history = _restored_ach if _restored_ach is not None else defaultdict(list)
1091
+ post_commenters = _restored_pc if _restored_pc is not None else defaultdict(list)
1092
+ late_agents_registered = args.resume and resume_step > join_step
1093
+
1094
+ # ── Warm-up: force every agent to create_post before the main loop ───────
1095
+ # Without this, agents default to commenting on seed posts because the feed
1096
+ # is already full of active discussion and posting feels unnecessary. The
1097
+ # warm-up ensures both groups enter step 1 with their own new posts.
1098
+ # Uses env.step() so OASIS properly writes posts to the DB.
1099
+ if not args.resume and resume_step == 1:
1100
+ print(" Warm-up: all agents post once...", flush=True)
1101
+ t_wu = datetime.now()
1102
+ chat_log_path = db_path.replace(".db", "_chats.jsonl")
1103
+ # Shuffle so post_ids are randomly distributed across families,
1104
+ # preventing any systematic hot-score advantage from insertion order.
1105
+ warmup_order = list(all_agents_list)
1106
+ rng.shuffle(warmup_order)
1107
+ for agent_id, agent in warmup_order:
1108
+ agent.memory.clear()
1109
+ agent._current_step = 0
1110
+ agent._chat_log_path = chat_log_path
1111
+ agent._was_muted = False
1112
+ agent._system_message = agent._sys_msg_normal
1113
+ agent._warmup_mode = True
1114
+ # Store non-create_post tools on the agent, then strip them
1115
+ agent._warmup_tool_backup = {
1116
+ k: v for k, v in list(agent._internal_tools.items())
1117
+ if k != 'create_post'}
1118
+ for k in agent._warmup_tool_backup:
1119
+ agent._internal_tools.pop(k, None)
1120
+ warmup_actions = {agent: LLMAction() for _, agent in all_agents_list}
1121
+ await env.step(warmup_actions)
1122
+ # Restore tools and clear warmup flag
1123
+ for agent_id, agent in all_agents_list:
1124
+ agent._warmup_mode = False
1125
+ agent._internal_tools.update(getattr(agent, '_warmup_tool_backup', {}))
1126
+ agent._warmup_tool_backup = {}
1127
+ wu_secs = (datetime.now() - t_wu).total_seconds()
1128
+ conn_wu = sqlite3.connect(db_path)
1129
+ n_wu = conn_wu.execute("SELECT COUNT(*) FROM post").fetchone()[0]
1130
+ conn_wu.close()
1131
+ print(f" Warm-up done: {n_wu} new posts in {wu_secs:.1f}s", flush=True)
1132
+
1133
+ # Post-warmup sanity check: every model family must have ≥50% of its
1134
+ # agents post. ≥1 is insufficient — GLM-4 with broken tool_choice had
1135
+ # exactly 1/10 agents post (uid=10 always squeaked through) and the old
1136
+ # ≥1 check passed silently, producing 10-user runs labeled as done.
1137
+ conn_check = sqlite3.connect(db_path)
1138
+ posts_by_fam: dict[str, int] = defaultdict(int)
1139
+ for uid, in conn_check.execute("SELECT user_id FROM post"):
1140
+ posts_by_fam[agent_families.get(uid - 1, agent_families.get(uid, '?'))] += 1
1141
+ conn_check.close()
1142
+ fam_sizes: dict[str, int] = defaultdict(int)
1143
+ for fam in agent_families.values():
1144
+ fam_sizes[fam] += 1
1145
+ # Require ≥50% of each family posted
1146
+ missing = [f for f in fam_sizes
1147
+ if posts_by_fam.get(f, 0) < max(1, fam_sizes[f] // 2)]
1148
+ if missing:
1149
+ msg = (f"\n{'!'*60}\n"
1150
+ f"FATAL: Warmup < 50% participation for families: {missing}\n"
1151
+ f" Posts by family: {dict(posts_by_fam)}\n"
1152
+ f" Expected ≥ {{{', '.join(f'{f}: {fam_sizes[f]//2}' for f in missing)}}}\n"
1153
+ f" This means the vLLM server for {missing} is returning bad tool calls.\n"
1154
+ f" Aborting — do not proceed with under-represented groups.\n"
1155
+ f"{'!'*60}\n")
1156
+ print(msg, flush=True)
1157
+ await env.close()
1158
+ raise SystemExit(1)
1159
+
1160
+ # Build health-check URL list once for midrun polling
1161
+ _health_urls = [(url.replace("/v1","") + "/health", model)
1162
+ for url, model in [(VLLM_A, MODEL_A), (VLLM_B, MODEL_B)]
1163
+ + ([(VLLM_C, MODEL_C)] if args.mode in ("hetero3","hetero4") else [])
1164
+ + ([(VLLM_D, MODEL_D)] if args.mode == "hetero4" else [])]
1165
+ SERVER_POLL_EVERY = 20 # check every N steps
1166
+
1167
+ for step in range(resume_step, args.steps + 1):
1168
+
1169
+ # Periodic server health check — fail loudly if any server is down mid-run
1170
+ if step % SERVER_POLL_EVERY == 0 and step > 1:
1171
+ for health_url, model in _health_urls:
1172
+ try:
1173
+ urllib.request.urlopen(health_url, timeout=8)
1174
+ except Exception as e:
1175
+ msg = (f"\n{'!'*60}\n"
1176
+ f"FATAL: Server for {model} went DOWN at step {step}/{args.steps}\n"
1177
+ f" URL: {health_url}\n"
1178
+ f" Error: {e}\n"
1179
+ f" DB preserved at: {db_path}\n"
1180
+ f" Aborting — results up to this step are valid.\n"
1181
+ f"{'!'*60}\n")
1182
+ print(msg, flush=True)
1183
+ await env.close()
1184
+ raise SystemExit(1)
1185
+
1186
+ # Activate late joiners at the 20% mark (they were registered at setup,
1187
+ # just gated from the activation pool until now)
1188
+ if "late" in args.mode and step == join_step and not late_agents_registered:
1189
+ late_agents_registered = True
1190
+ print(f" [step {step}] Activating {len(late_agent_ids)} late joiners "
1191
+ f"(already registered at setup)")
1192
+
1193
+ # Activation pool: exclude late joiners until join_step
1194
+ if late_agent_ids and step < join_step:
1195
+ active_pool = [pair for pair in all_agents_list if pair[0] not in late_agent_ids]
1196
+ else:
1197
+ active_pool = all_agents_list
1198
+ activated = rng.sample(active_pool, min(n_active, len(active_pool)))
1199
+ # Re-shuffle activation iteration order to avoid any subtle artifacts
1200
+ # from agents being processed in a consistent order across steps.
1201
+ rng.shuffle(activated)
1202
+
1203
+ # Group-level post-share balancer: dynamically determines which
1204
+ # agents are post-muted (create_post stripped from tools + system_msg)
1205
+ # this turn based on current cumulative group post share.
1206
+ POST_SHARE_TOLERANCE = float(os.environ.get("POST_SHARE_TOL", "0.05")) # >Npp over target; set ~1.0 to disable balancer
1207
+ conn = sqlite3.connect(db_path)
1208
+ recent = conn.execute(
1209
+ "SELECT c.post_id, c.user_id, c.content, p.user_id "
1210
+ "FROM comment c JOIN post p ON c.post_id = p.post_id "
1211
+ "ORDER BY c.comment_id DESC LIMIT 60").fetchall()
1212
+ active_ids = [aid for aid, _ in activated]
1213
+ placeholders = ",".join("?" * len(active_ids))
1214
+ last_actions = dict(conn.execute(
1215
+ f"SELECT user_id, action FROM trace WHERE user_id IN ({placeholders}) "
1216
+ f"AND action != 'sign_up' ORDER BY rowid DESC",
1217
+ active_ids).fetchall()) if active_ids else {}
1218
+ # Group post counts (cumulative, all agents) for share computation
1219
+ all_families = set(agent_families.values())
1220
+ group_post_counts = {g: 0 for g in all_families}
1221
+ for uid, n in conn.execute("SELECT user_id, COUNT(*) FROM post GROUP BY user_id").fetchall():
1222
+ fam = agent_families.get(uid)
1223
+ if fam in group_post_counts:
1224
+ group_post_counts[fam] += n
1225
+ conn.close()
1226
+ active_groups = {agent_families[aid] for aid in agent_families}
1227
+ n_per_group = {g: sum(1 for f in agent_families.values() if f == g) for g in active_groups}
1228
+ n_total_agents = sum(n_per_group.values())
1229
+ total_posts = sum(group_post_counts.values()) or 1
1230
+ muted_groups = set()
1231
+ for g, gc in group_post_counts.items():
1232
+ target = n_per_group.get(g, 0) / n_total_agents if n_total_agents else 0
1233
+ obs = gc / total_posts
1234
+ if obs > target + POST_SHARE_TOLERANCE:
1235
+ muted_groups.add(g)
1236
+ muted_this_turn = {aid for aid, fam in agent_families.items() if fam in muted_groups}
1237
+ for cmt_pid, cmt_uid, cmt_content, post_owner_uid in recent:
1238
+ post_commenters[post_owner_uid].append((cmt_uid, cmt_content[:80]))
1239
+
1240
+ # Chat log path for this run (one file per run, JSONL)
1241
+ chat_log_path = db_path.replace(".db", "_chats.jsonl")
1242
+
1243
+ for agent_id, agent in activated:
1244
+ agent.memory.clear()
1245
+ # (Comment-history reminder is now subsumed by build_recap() inside
1246
+ # GoalAgent.perform_action_by_llm — no separate injection needed.)
1247
+ # Per-turn instrumentation for GoalAgent
1248
+ agent._current_step = step
1249
+ agent._chat_log_path = chat_log_path
1250
+ agent._was_muted = (agent_id in muted_this_turn)
1251
+ # Dynamic post-mute: swap system_message + strip create_post from tools.
1252
+ if agent._was_muted:
1253
+ agent._system_message = agent._sys_msg_no_post
1254
+ if hasattr(agent, 'tool_dict') and 'create_post' in agent._internal_tools:
1255
+ agent._create_post_backup = agent._internal_tools.pop('create_post')
1256
+ else:
1257
+ agent._system_message = agent._sys_msg_normal
1258
+ if getattr(agent, '_create_post_backup', None) is not None \
1259
+ and 'create_post' not in agent._internal_tools:
1260
+ agent._internal_tools['create_post'] = agent._create_post_backup
1261
+ agent._create_post_backup = None
1262
+ seen = set()
1263
+ agent.pending_interactions = []
1264
+ for uid, excerpt in reversed(post_commenters.get(agent_id, [])[-12:]):
1265
+ if uid not in seen:
1266
+ agent.pending_interactions.append(f"Agent {uid}: \"{excerpt}...\"")
1267
+ seen.add(uid);
1268
+ if len(agent.pending_interactions) >= 3: break
1269
+
1270
+ step_actions = {agent: LLMAction() for _, agent in activated}
1271
+ t0 = datetime.now()
1272
+ await env.step(step_actions)
1273
+ elapsed = (datetime.now() - t0).total_seconds()
1274
+ # Restore stripped tools for any muted agents so future un-muted turns work
1275
+ for agent_id, agent in activated:
1276
+ if getattr(agent, '_create_post_backup', None) is not None \
1277
+ and 'create_post' not in agent._internal_tools:
1278
+ agent._internal_tools['create_post'] = agent._create_post_backup
1279
+ agent._create_post_backup = None
1280
+
1281
+ # Weak auto-upvote: +1 per post that received any comment this step
1282
+ # (flat, not per-comment). Signals engagement without runaway amplification.
1283
+ try:
1284
+ env.platform.pl_utils._execute_db_command(
1285
+ "SELECT DISTINCT post_id FROM comment ORDER BY comment_id DESC LIMIT ?",
1286
+ (n_active * 3,))
1287
+ for (pid,) in env.platform.db_cursor.fetchall():
1288
+ env.platform.pl_utils._execute_db_command(
1289
+ "UPDATE post SET num_likes = num_likes + 1 WHERE post_id = ?", (pid,))
1290
+ env.platform.db.commit()
1291
+ except: pass
1292
+
1293
+ # Capture comments + reasoning
1294
+ conn = sqlite3.connect(db_path)
1295
+ new_cmts = conn.execute(
1296
+ "SELECT user_id, content FROM comment ORDER BY comment_id DESC LIMIT ?",
1297
+ (n_active * 2,)).fetchall()
1298
+ conn.close()
1299
+ for uid, content in new_cmts:
1300
+ agent_comment_history[uid].append(content[:120])
1301
+
1302
+ # STEP MARKERS. The platform's post/comment tables carry no step column, so a
1303
+ # step had to be reconstructed post hoc by aligning each agent's k-th successful
1304
+ # activation (logged in _chats.jsonl) with its k-th action ordered by time. That
1305
+ # recovers ~85% of rows exactly and silently drops the rest. Recording the id
1306
+ # high-water mark at each step boundary makes step EXACT and trivial to join:
1307
+ # step(post) = min(step : post_id <= max_post_id)
1308
+ # One row per step, no schema change to the platform's own tables.
1309
+ try:
1310
+ _c = sqlite3.connect(db_path)
1311
+ _c.execute("CREATE TABLE IF NOT EXISTS step_marks ("
1312
+ "step INTEGER PRIMARY KEY, max_post_id INTEGER, "
1313
+ "max_comment_id INTEGER, wall_clock TEXT)")
1314
+ _mp = _c.execute("SELECT COALESCE(MAX(post_id), 0) FROM post").fetchone()[0]
1315
+ _mc = _c.execute("SELECT COALESCE(MAX(comment_id), 0) FROM comment").fetchone()[0]
1316
+ _c.execute("INSERT OR REPLACE INTO step_marks VALUES (?,?,?,?)",
1317
+ (step, _mp, _mc, datetime.now().isoformat()))
1318
+ _c.commit(); _c.close()
1319
+ except Exception as _e:
1320
+ print(f" [warn] step_marks write failed at step {step}: {_e!r}")
1321
+
1322
+ trace_path = db_path.replace(".db", "_reasoning.jsonl")
1323
+ with open(trace_path, "a") as tf:
1324
+ for agent_id, agent in activated:
1325
+ r = getattr(agent, '_last_reasoning', '')
1326
+ if r:
1327
+ tf.write(json.dumps({"step": step, "agent_id": agent_id,
1328
+ "family": agent_families.get(agent_id,'?'),
1329
+ "reasoning": r[:500]}) + "\n")
1330
+
1331
+ if step % 20 == 0 or step == 1 or step == join_step:
1332
+ s = analyze(db_path, args.agents)
1333
+ suffix = f" [+late]" if step >= join_step and "late" in args.mode else ""
1334
+ print(f" step={step:4d}/{args.steps} posts={s['n_posts']} "
1335
+ f"cmts={s['n_comments']} active={s['active']}/{len(all_agents_list)} "
1336
+ f"Gini={s['gini']:.3f} recip={s['recip']} ({elapsed:.1f}s){suffix}")
1337
+ _save_checkpoint(step, agent_comment_history, post_commenters)
1338
+
1339
+ await env.close()
1340
+
1341
+ # Remove checkpoint sidecar — run completed normally
1342
+ if os.path.exists(_ckpt_path):
1343
+ os.unlink(_ckpt_path)
1344
+
1345
+ # Final reports
1346
+ s = analyze(db_path, args.agents)
1347
+ conn = sqlite3.connect(db_path)
1348
+ users = {uid:n for uid,n in conn.execute("SELECT user_id, user_name FROM user").fetchall()}
1349
+ conn.close()
1350
+
1351
+ bodies = [r[0].strip()[:120] for r in sqlite3.connect(db_path).execute("SELECT content FROM comment").fetchall()]
1352
+ ctr = Counter(bodies)
1353
+ nd = sum(v-1 for v in ctr.values() if v>1)
1354
+ print(f"\n{'='*60}")
1355
+ print(f"FINAL mode={args.mode} steps={args.steps}")
1356
+ print(f" cmts={s['n_comments']} near-dupes={nd/len(bodies)*100:.1f}% "
1357
+ f"Gini={s['gini']:.3f} recip={s['recip']}")
1358
+
1359
+ if args.mode in ("hetero","hetero_late","hetero3","hetero4"):
1360
+ homophily_report(db_path, agent_families)
1361
+ if "late" in args.mode:
1362
+ late_joiner_report(db_path, late_agent_ids, join_step, users)
1363
+
1364
+
1365
+ if __name__ == "__main__":
1366
+ import signal
1367
+ # Clean exit on SIGTERM (SLURM preemption signal) so SQLite is not mid-write.
1368
+ # The DB is already committed step-by-step by OASIS; SIGTERM just means we
1369
+ # exit gracefully after the current step commit rather than being SIGKILLed.
1370
+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
1371
+ asyncio.run(main())
oasis/seed_db/hf-zero-50.sqlite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f22354cbdfa1ee2003913a4be09991ad29e61e04752869fa1fded768d5ba7ac4
3
+ size 1417216
oasis/tool_chat_template_gemma4.jinja ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- macro format_parameters(properties, required, filter_keys=false) -%}
2
+ {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}
3
+ {%- set ns = namespace(found_first=false) -%}
4
+ {%- for key, value in properties | dictsort -%}
5
+ {%- set add_comma = false -%}
6
+ {%- if not filter_keys or key not in standard_keys -%}
7
+ {%- if ns.found_first %},{% endif -%}
8
+ {%- set ns.found_first = true -%}
9
+ {{ key }}:{
10
+ {%- if value['description'] -%}
11
+ description:<|"|>{{ value['description'] }}<|"|>
12
+ {%- set add_comma = true -%}
13
+ {%- endif -%}
14
+ {%- if value['type'] | upper == 'STRING' -%}
15
+ {%- if value['enum'] -%}
16
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
17
+ enum:{{ format_argument(value['enum']) }}
18
+ {%- endif -%}
19
+ {%- elif value['type'] | upper == 'ARRAY' -%}
20
+ {%- if value['items'] is mapping and value['items'] -%}
21
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
22
+ items:{
23
+ {%- set ns_items = namespace(found_first=false) -%}
24
+ {%- for item_key, item_value in value['items'] | dictsort -%}
25
+ {%- if item_value is not none -%}
26
+ {%- if ns_items.found_first %},{% endif -%}
27
+ {%- set ns_items.found_first = true -%}
28
+ {%- if item_key == 'properties' -%}
29
+ properties:{
30
+ {%- if item_value is mapping -%}
31
+ {{- format_parameters(item_value, value['items']['required'] | default([])) -}}
32
+ {%- endif -%}
33
+ }
34
+ {%- elif item_key == 'required' -%}
35
+ required:[
36
+ {%- for req_item in item_value -%}
37
+ <|"|>{{- req_item -}}<|"|>
38
+ {%- if not loop.last %},{% endif -%}
39
+ {%- endfor -%}
40
+ ]
41
+ {%- elif item_key == 'type' -%}
42
+ {%- if item_value is string -%}
43
+ type:{{ format_argument(item_value | upper) }}
44
+ {%- else -%}
45
+ type:{{ format_argument(item_value | map('upper') | list) }}
46
+ {%- endif -%}
47
+ {%- else -%}
48
+ {{ item_key }}:{{ format_argument(item_value) }}
49
+ {%- endif -%}
50
+ {%- endif -%}
51
+ {%- endfor -%}
52
+ }
53
+ {%- endif -%}
54
+ {%- endif -%}
55
+ {%- if value['nullable'] %}
56
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
57
+ nullable:true
58
+ {%- endif -%}
59
+ {%- if value['type'] | upper == 'OBJECT' -%}
60
+ {%- if value['properties'] is defined and value['properties'] is mapping -%}
61
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
62
+ properties:{
63
+ {{- format_parameters(value['properties'], value['required'] | default([])) -}}
64
+ }
65
+ {%- elif value is mapping -%}
66
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
67
+ properties:{
68
+ {{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}}
69
+ }
70
+ {%- endif -%}
71
+ {%- if value['required'] -%}
72
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
73
+ required:[
74
+ {%- for item in value['required'] | default([]) -%}
75
+ <|"|>{{- item -}}<|"|>
76
+ {%- if not loop.last %},{% endif -%}
77
+ {%- endfor -%}
78
+ ]
79
+ {%- endif -%}
80
+ {%- endif -%}
81
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
82
+ type:<|"|>{{ value['type'] | upper }}<|"|>}
83
+ {%- endif -%}
84
+ {%- endfor -%}
85
+ {%- endmacro -%}
86
+ {%- macro format_function_declaration(tool_data) -%}
87
+ declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|>
88
+ {%- set params = tool_data['function']['parameters'] -%}
89
+ {%- if params -%}
90
+ ,parameters:{
91
+ {%- if params['properties'] -%}
92
+ properties:{ {{- format_parameters(params['properties'], params['required']) -}} },
93
+ {%- endif -%}
94
+ {%- if params['required'] -%}
95
+ required:[
96
+ {%- for item in params['required'] -%}
97
+ <|"|>{{- item -}}<|"|>
98
+ {{- ',' if not loop.last -}}
99
+ {%- endfor -%}
100
+ ],
101
+ {%- endif -%}
102
+ {%- if params['type'] -%}
103
+ type:<|"|>{{- params['type'] | upper -}}<|"|>}
104
+ {%- endif -%}
105
+ {%- endif -%}
106
+ {%- if 'response' in tool_data['function'] -%}
107
+ {%- set response_declaration = tool_data['function']['response'] -%}
108
+ ,response:{
109
+ {%- if response_declaration['description'] -%}
110
+ description:<|"|>{{- response_declaration['description'] -}}<|"|>,
111
+ {%- endif -%}
112
+ {%- if response_declaration['type'] | upper == 'OBJECT' -%}
113
+ type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>}
114
+ {%- endif -%}
115
+ {%- endif -%}
116
+ }
117
+ {%- endmacro -%}
118
+ {%- macro format_argument(argument, escape_keys=True) -%}
119
+ {%- if argument is string -%}
120
+ {{- '<|"|>' + argument + '<|"|>' -}}
121
+ {%- elif argument is boolean -%}
122
+ {{- 'true' if argument else 'false' -}}
123
+ {%- elif argument is mapping -%}
124
+ {{- '{' -}}
125
+ {%- set ns = namespace(found_first=false) -%}
126
+ {%- for key, value in argument | dictsort -%}
127
+ {%- if ns.found_first %},{% endif -%}
128
+ {%- set ns.found_first = true -%}
129
+ {%- if escape_keys -%}
130
+ {{- '<|"|>' + key + '<|"|>' -}}
131
+ {%- else -%}
132
+ {{- key -}}
133
+ {%- endif -%}
134
+ :{{- format_argument(value, escape_keys=escape_keys) -}}
135
+ {%- endfor -%}
136
+ {{- '}' -}}
137
+ {%- elif argument is sequence -%}
138
+ {{- '[' -}}
139
+ {%- for item in argument -%}
140
+ {{- format_argument(item, escape_keys=escape_keys) -}}
141
+ {%- if not loop.last %},{% endif -%}
142
+ {%- endfor -%}
143
+ {{- ']' -}}
144
+ {%- else -%}
145
+ {{- argument -}}
146
+ {%- endif -%}
147
+ {%- endmacro -%}
148
+ {%- macro strip_thinking(text) -%}
149
+ {%- set ns = namespace(result='') -%}
150
+ {%- for part in text.split('<channel|>') -%}
151
+ {%- if '<|channel>' in part -%}
152
+ {%- set ns.result = ns.result + part.split('<|channel>')[0] -%}
153
+ {%- else -%}
154
+ {%- set ns.result = ns.result + part -%}
155
+ {%- endif -%}
156
+ {%- endfor -%}
157
+ {{- ns.result | trim -}}
158
+ {%- endmacro -%}
159
+
160
+ {%- macro format_tool_response_block(tool_name, response) -%}
161
+ {{- '<|tool_response>' -}}
162
+ {%- if response is mapping -%}
163
+ {{- 'response:' + tool_name + '{' -}}
164
+ {%- for key, value in response | dictsort -%}
165
+ {{- key -}}:{{- format_argument(value, escape_keys=False) -}}
166
+ {%- if not loop.last %},{% endif -%}
167
+ {%- endfor -%}
168
+ {{- '}' -}}
169
+ {%- else -%}
170
+ {{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}}
171
+ {%- endif -%}
172
+ {{- '<tool_response|>' -}}
173
+ {%- endmacro -%}
174
+
175
+ {%- set ns = namespace(prev_message_type=None) -%}
176
+ {%- set loop_messages = messages -%}
177
+ {{- bos_token -}}
178
+ {#- Handle System/Tool Definitions Block -#}
179
+ {%- if (enable_thinking is defined and enable_thinking) or tools or messages[0]['role'] in ['system', 'developer'] -%}
180
+ {{- '<|turn>system\n' -}}
181
+ {#- Inject Thinking token at the very top of the FIRST system turn -#}
182
+ {%- if enable_thinking is defined and enable_thinking -%}
183
+ {{- '<|think|>\n' -}}
184
+ {%- set ns.prev_message_type = 'think' -%}
185
+ {%- endif -%}
186
+ {%- if messages[0]['role'] in ['system', 'developer'] -%}
187
+ {%- if messages[0]['content'] is string -%}
188
+ {{- messages[0]['content'] | trim -}}
189
+ {%- elif messages[0]['content'] is sequence -%}
190
+ {%- for item in messages[0]['content'] -%}
191
+ {{- item['text'] | trim + ' '-}}
192
+ {%- endfor -%}
193
+ {%- endif -%}
194
+ {%- set loop_messages = messages[1:] -%}
195
+ {%- endif -%}
196
+ {%- if tools -%}
197
+ {%- for tool in tools %}
198
+ {{- '<|tool>' -}}
199
+ {{- format_function_declaration(tool) | trim -}}
200
+ {{- '<tool|>' -}}
201
+ {%- endfor %}
202
+ {%- set ns.prev_message_type = 'tool' -%}
203
+ {%- endif -%}
204
+ {{- '<turn|>\n' -}}
205
+ {%- endif %}
206
+
207
+ {#- Pre-scan: find last user message index for reasoning guard -#}
208
+ {%- set ns_turn = namespace(last_user_idx=-1) -%}
209
+ {%- for i in range(loop_messages | length) -%}
210
+ {%- if loop_messages[i]['role'] == 'user' -%}
211
+ {%- set ns_turn.last_user_idx = i -%}
212
+ {%- endif -%}
213
+ {%- endfor -%}
214
+
215
+ {#- Loop through messages -#}
216
+ {%- for message in loop_messages -%}
217
+ {%- if message['role'] != 'tool' -%}
218
+ {%- set ns.prev_message_type = None -%}
219
+ {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}
220
+ {#- Detect continuation: suppress duplicate <|turn>model when previous non-tool message was also assistant -#}
221
+ {%- set prev_nt = namespace(role=None, found=false) -%}
222
+ {%- if loop.index0 > 0 -%}
223
+ {%- for j in range(loop.index0 - 1, -1, -1) -%}
224
+ {%- if not prev_nt.found -%}
225
+ {%- if loop_messages[j]['role'] != 'tool' -%}
226
+ {%- set prev_nt.role = loop_messages[j]['role'] -%}
227
+ {%- set prev_nt.found = true -%}
228
+ {%- endif -%}
229
+ {%- endif -%}
230
+ {%- endfor -%}
231
+ {%- endif -%}
232
+ {%- set continue_same_model_turn = (role == 'model' and prev_nt.role == 'assistant') -%}
233
+ {%- if not continue_same_model_turn -%}
234
+ {{- '<|turn>' + role + '\n' }}
235
+ {%- endif -%}
236
+
237
+ {#- Render reasoning/reasoning_content as thinking channel -#}
238
+ {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}
239
+ {%- if thinking_text and loop.index0 > ns_turn.last_user_idx and message.get('tool_calls') -%}
240
+ {{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}}
241
+ {%- endif -%}
242
+
243
+ {%- if message['tool_calls'] -%}
244
+ {%- for tool_call in message['tool_calls'] -%}
245
+ {%- set function = tool_call['function'] -%}
246
+ {{- '<|tool_call>call:' + function['name'] + '{' -}}
247
+ {%- if function['arguments'] is mapping -%}
248
+ {%- set ns_args = namespace(found_first=false) -%}
249
+ {%- for key, value in function['arguments'] | dictsort -%}
250
+ {%- if ns_args.found_first %},{% endif -%}
251
+ {%- set ns_args.found_first = true -%}
252
+ {{- key -}}:{{- format_argument(value, escape_keys=False) -}}
253
+ {%- endfor -%}
254
+ {%- elif function['arguments'] is string -%}
255
+ {{- function['arguments'] -}}
256
+ {%- endif -%}
257
+ {{- '}<tool_call|>' -}}
258
+ {%- endfor -%}
259
+ {%- set ns.prev_message_type = 'tool_call' -%}
260
+ {%- endif -%}
261
+
262
+ {%- set ns_tr_out = namespace(flag=false) -%}
263
+ {%- if message.get('tool_responses') -%}
264
+ {#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#}
265
+ {%- for tool_response in message['tool_responses'] -%}
266
+ {{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}}
267
+ {%- set ns_tr_out.flag = true -%}
268
+ {%- set ns.prev_message_type = 'tool_response' -%}
269
+ {%- endfor -%}
270
+ {%- elif message.get('tool_calls') -%}
271
+ {#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#}
272
+ {%- set ns_tool_scan = namespace(stopped=false) -%}
273
+ {%- for k in range(loop.index0 + 1, loop_messages | length) -%}
274
+ {%- if ns_tool_scan.stopped -%}
275
+ {%- elif loop_messages[k]['role'] != 'tool' -%}
276
+ {%- set ns_tool_scan.stopped = true -%}
277
+ {%- else -%}
278
+ {%- set follow = loop_messages[k] -%}
279
+ {#- Resolve tool_call_id to function name -#}
280
+ {%- set ns_tname = namespace(name=follow.get('name') | default('unknown', true)) -%}
281
+ {%- for tc in message['tool_calls'] -%}
282
+ {%- if tc.get('id') == follow.get('tool_call_id') -%}
283
+ {%- set ns_tname.name = tc['function']['name'] -%}
284
+ {%- endif -%}
285
+ {%- endfor -%}
286
+ {#- Handle content as string or content-parts array -#}
287
+ {%- set tool_body = follow.get('content') -%}
288
+ {%- if tool_body is string -%}
289
+ {{- format_tool_response_block(ns_tname.name, tool_body) -}}
290
+ {%- elif tool_body is sequence and tool_body is not string -%}
291
+ {%- set ns_txt = namespace(s='') -%}
292
+ {%- for part in tool_body -%}
293
+ {%- if part.get('type') == 'text' -%}
294
+ {%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%}
295
+ {%- endif -%}
296
+ {%- endfor -%}
297
+ {{- format_tool_response_block(ns_tname.name, ns_txt.s) -}}
298
+ {%- else -%}
299
+ {{- format_tool_response_block(ns_tname.name, tool_body) -}}
300
+ {%- endif -%}
301
+ {%- set ns_tr_out.flag = true -%}
302
+ {%- set ns.prev_message_type = 'tool_response' -%}
303
+ {%- endif -%}
304
+ {%- endfor -%}
305
+ {%- endif -%}
306
+
307
+ {%- set captured_content -%}
308
+ {%- if message['content'] is string -%}
309
+ {%- if role == 'model' -%}
310
+ {{- strip_thinking(message['content']) -}}
311
+ {%- else -%}
312
+ {{- message['content'] | trim -}}
313
+ {%- endif -%}
314
+ {%- elif message['content'] is sequence -%}
315
+ {%- for item in message['content'] -%}
316
+ {%- if item['type'] == 'text' -%}
317
+ {%- if role == 'model' -%}
318
+ {{- strip_thinking(item['text']) -}}
319
+ {%- else -%}
320
+ {{- item['text'] | trim -}}
321
+ {%- endif -%}
322
+ {%- elif item['type'] == 'image' -%}
323
+ {{- '<|image|>' -}}
324
+ {%- set ns.prev_message_type = 'image' -%}
325
+ {%- elif item['type'] == 'audio' -%}
326
+ {{- '<|audio|>' -}}
327
+ {%- set ns.prev_message_type = 'audio' -%}
328
+ {%- elif item['type'] == 'video' -%}
329
+ {{- '<|video|>' -}}
330
+ {%- set ns.prev_message_type = 'video' -%}
331
+ {%- endif -%}
332
+ {%- endfor -%}
333
+ {%- endif -%}
334
+ {%- endset -%}
335
+
336
+ {{- captured_content -}}
337
+ {%- set has_content = captured_content | trim | length > 0 -%}
338
+
339
+ {%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%}
340
+ {{- '<|tool_response>' -}}
341
+ {%- elif not (ns_tr_out.flag and not has_content) -%}
342
+ {{- '<turn|>\n' -}}
343
+ {%- endif -%}
344
+ {%- endif -%}
345
+ {%- endfor -%}
346
+
347
+ {%- if add_generation_prompt -%}
348
+ {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}
349
+ {{- '<|turn>model\n' -}}
350
+ {%- if not enable_thinking | default(false) -%}
351
+ {{- '<|channel>thought\n<channel|>' -}}
352
+ {%- endif -%}
353
+ {%- endif -%}
354
+ {%- endif -%}
smoke_test/assert_h_matrix.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Smoke-test assertions for a completed divsim run.
3
+
4
+ Checks:
5
+ 1. The DB file exists and is non-empty.
6
+ 2. metadata.json sidecar exists and has an agent_model_map.
7
+ 3. Both model families have ≥1 comment.
8
+ 4. Total cross-family comments > 5.
9
+ 5. H matrix is computable, is a dict, and has finite values for all
10
+ (src, dst) pairs covering both families.
11
+
12
+ Usage:
13
+ python assert_h_matrix.py --db /path/to/sweep_*.db
14
+ python assert_h_matrix.py --db /path/to/sweep_*.db --min-cross 5
15
+ """
16
+
17
+ import argparse
18
+ import json
19
+ import math
20
+ import os
21
+ import sqlite3
22
+ import sys
23
+ from collections import defaultdict
24
+ from pathlib import Path
25
+
26
+
27
+ SHORT = {
28
+ 'Qwen/Qwen3-32B': 'Qwen',
29
+ 'openai/gpt-oss-20b': 'gpt-oss',
30
+ 'mistralai/Magistral-Small-2509': 'Mag',
31
+ 'zai-org/GLM-4-32B-0414': 'GLM-4',
32
+ 'google/gemma-4-31B-it': 'Gemma',
33
+ }
34
+
35
+
36
+ def compute_h(db_path: str) -> dict:
37
+ """Compute directed pairwise H matrix from a run DB."""
38
+ meta_path = db_path.replace('.db', '.metadata.json')
39
+ if not os.path.exists(meta_path):
40
+ raise FileNotFoundError(f"metadata.json not found: {meta_path}")
41
+ with open(meta_path) as f:
42
+ meta = json.load(f)
43
+ amm = meta.get('agent_model_map', {})
44
+ if not amm:
45
+ raise ValueError("agent_model_map is empty in metadata.json")
46
+
47
+ uf = {int(k)+1: SHORT.get(v['model'], v['model'][:8]) for k, v in amm.items()}
48
+ fc = defaultdict(int)
49
+ for fam in uf.values():
50
+ fc[fam] += 1
51
+ n = sum(fc.values())
52
+
53
+ conn = sqlite3.connect(db_path)
54
+ comments = conn.execute(
55
+ 'SELECT c.user_id, p.user_id FROM comment c '
56
+ 'JOIN post p ON c.post_id=p.post_id WHERE c.user_id!=p.user_id'
57
+ ).fetchall()
58
+ conn.close()
59
+
60
+ ec = defaultdict(int)
61
+ for cu, pu in comments:
62
+ sf, df = uf.get(cu), uf.get(pu)
63
+ if sf and df:
64
+ ec[(sf, df)] += 1
65
+
66
+ total = sum(ec.values())
67
+ if total == 0:
68
+ raise ValueError("No cross-family comment edges found.")
69
+
70
+ H = {}
71
+ for s in fc:
72
+ for d in fc:
73
+ obs = ec.get((s, d), 0) / total
74
+ exp = (fc[s]/n) * ((fc[d] - (1 if s == d else 0)) / (n-1))
75
+ if exp > 0:
76
+ H[(s, d)] = obs/exp - 1
77
+ return H, ec, fc
78
+
79
+
80
+ def main():
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument('--db', required=True, help='Path to sweep_*.db file.')
83
+ parser.add_argument('--min-cross', type=int, default=5,
84
+ help='Minimum total cross-family comments required (default: 5).')
85
+ args = parser.parse_args()
86
+
87
+ db_path = args.db
88
+ failures = []
89
+
90
+ # 1. DB exists and is non-empty
91
+ if not os.path.exists(db_path):
92
+ print(f"FAIL: DB file does not exist: {db_path}")
93
+ sys.exit(1)
94
+ if os.path.getsize(db_path) < 1000:
95
+ failures.append(f"DB file is too small ({os.path.getsize(db_path)} bytes)")
96
+
97
+ # 2. Metadata exists
98
+ meta_path = db_path.replace('.db', '.metadata.json')
99
+ if not os.path.exists(meta_path):
100
+ failures.append(f"metadata.json not found: {meta_path}")
101
+ else:
102
+ with open(meta_path) as f:
103
+ meta = json.load(f)
104
+ if not meta.get('agent_model_map'):
105
+ failures.append("agent_model_map is missing or empty in metadata.json")
106
+
107
+ if failures:
108
+ for f in failures:
109
+ print(f"FAIL: {f}")
110
+ sys.exit(1)
111
+
112
+ try:
113
+ H, ec, fc = compute_h(db_path)
114
+ except Exception as e:
115
+ print(f"FAIL: H matrix computation failed: {e}")
116
+ sys.exit(1)
117
+
118
+ families = list(fc.keys())
119
+ print(f" Families: {families}")
120
+ print(f" Family sizes: {dict(fc)}")
121
+
122
+ # 3. Both families have ≥1 comment
123
+ comments_per_family = defaultdict(int)
124
+ conn = sqlite3.connect(db_path)
125
+ comments_all = conn.execute('SELECT user_id FROM comment').fetchall()
126
+ conn.close()
127
+ amm = meta.get('agent_model_map', {})
128
+ uf = {int(k)+1: SHORT.get(v['model'], v['model'][:8]) for k, v in amm.items()}
129
+ for (uid,) in comments_all:
130
+ fam = uf.get(uid)
131
+ if fam:
132
+ comments_per_family[fam] += 1
133
+
134
+ for fam in families:
135
+ cnt = comments_per_family.get(fam, 0)
136
+ if cnt < 1:
137
+ failures.append(f"Family '{fam}' has 0 comments")
138
+ else:
139
+ print(f" Family '{fam}': {cnt} comments emitted — OK")
140
+
141
+ # 4. Cross-family comments > min_cross
142
+ cross_total = sum(v for (s, d), v in ec.items() if s != d)
143
+ print(f" Cross-family comments: {cross_total} (min required: {args.min_cross})")
144
+ if cross_total <= args.min_cross:
145
+ failures.append(f"Cross-family comments {cross_total} ≤ {args.min_cross}")
146
+
147
+ # 5. H matrix has finite values for all pairs
148
+ print(f" H matrix entries: {len(H)}")
149
+ for pair, h in H.items():
150
+ if not math.isfinite(h):
151
+ failures.append(f"H[{pair}] is not finite: {h}")
152
+ else:
153
+ print(f" H[{pair[0]}->{pair[1]}] = {h:+.4f}")
154
+
155
+ if len(H) < len(families) * (len(families) - 1):
156
+ failures.append(f"H matrix has fewer entries than expected "
157
+ f"({len(H)} < {len(families)*(len(families)-1)})")
158
+
159
+ if failures:
160
+ print("\nFAILED:")
161
+ for f in failures:
162
+ print(f" - {f}")
163
+ sys.exit(1)
164
+ else:
165
+ print("\nAll assertions passed.")
166
+ sys.exit(0)
167
+
168
+
169
+ if __name__ == '__main__':
170
+ main()
smoke_test/run_smoke.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Smoke test: run one short dyadic simulation and verify basic outputs.
3
+ #
4
+ # Spec: 1 dyad (Qwen + Magistral), 20 steps, 4 agents total (2 per family).
5
+ # Expected runtime: < 5 minutes on 2× L40S GPUs.
6
+ #
7
+ # Required env vars:
8
+ # VLLM_URL_A — Qwen3-32B server URL (default: http://localhost:8002/v1)
9
+ # VLLM_URL_B — Magistral server URL (default: http://localhost:8004/v1)
10
+ # SAFEMASS_VENV — path to Python venv
11
+ # SEED_DB — path to hf-zero-50.sqlite (default: ../oasis/seed_db/hf-zero-50.sqlite)
12
+ #
13
+ # After the run, assert_h_matrix.py is called to verify the output.
14
+
15
+ set -euo pipefail
16
+
17
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
18
+ ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
19
+
20
+ VENV="${SAFEMASS_VENV:-${ROOT_DIR}/.venv}"
21
+ RUNNER="${OASIS_RUNNER:-${ROOT_DIR}/oasis/run_v9.py}"
22
+ SEED_DB="${SEED_DB:-${ROOT_DIR}/oasis/seed_db/hf-zero-50.sqlite}"
23
+ RUNS_DIR="${RUNS_DIR:-/tmp/divsim_smoke_runs}"
24
+ LOGS_DIR="${LOGS_DIR:-/tmp/divsim_smoke_logs}"
25
+
26
+ mkdir -p "${RUNS_DIR}" "${LOGS_DIR}"
27
+
28
+ export SEED_DB
29
+ export MODEL_NAME_A="${MODEL_NAME_A:-Qwen/Qwen3-32B}"
30
+ export MODEL_NAME_B="${MODEL_NAME_B:-mistralai/Magistral-Small-2509}"
31
+ export VLLM_URL_A="${VLLM_URL_A:-http://localhost:8002/v1}"
32
+ export VLLM_URL_B="${VLLM_URL_B:-http://localhost:8004/v1}"
33
+
34
+ DB="${RUNS_DIR}/smoke_qwen_mag_s42.db"
35
+ export OASIS_DB_PATH="${DB}"
36
+
37
+ echo "[smoke] Starting dyadic smoke run"
38
+ echo " A: ${MODEL_NAME_A} @ ${VLLM_URL_A}"
39
+ echo " B: ${MODEL_NAME_B} @ ${VLLM_URL_B}"
40
+ echo " db: ${DB}"
41
+ echo " steps=20 agents=4 seed=42"
42
+
43
+ "${VENV}/bin/python3" "${RUNNER}" \
44
+ --mode hetero \
45
+ --steps 20 \
46
+ --agents 4 \
47
+ --seed-posts 4 \
48
+ --activate-prob 0.5 \
49
+ --rng-seed 42 \
50
+ --db "${DB}" \
51
+ 2>&1 | tee "${LOGS_DIR}/smoke_run.log"
52
+
53
+ echo ""
54
+ echo "[smoke] Run complete. Running assertions..."
55
+ "${VENV}/bin/python3" "${SCRIPT_DIR}/assert_h_matrix.py" --db "${DB}"
56
+ echo "[smoke] All assertions passed."
sweep/sweep_dyadic.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dyadic (2-model) combinatorial sweep for the divsim paper.
3
+
4
+ Enumerates all ordered pairs from the 5 paper models, crossed with 5 persona seeds,
5
+ for a total of C(5,2)×2×5 = 100 configurations. Each configuration launches one
6
+ run of the OASIS simulator in hetero mode.
7
+
8
+ Configuration is read from environment variables:
9
+ RUNS_DIR — output directory for .db files (required)
10
+ VENV_PATH — path to the Python venv with oasis installed
11
+ OASIS_RUNNER — path to run_v9.py (defaults to <this_dir>/../oasis/run_v9.py)
12
+ LOGS_DIR — directory for per-run log files
13
+
14
+ Usage:
15
+ python sweep_dyadic.py --dry-run # print all configs, no launch
16
+ python sweep_dyadic.py --mode 2model # all 2-model runs (default)
17
+ python sweep_dyadic.py --max-parallel 2 # limit concurrent runs
18
+ python sweep_dyadic.py --skip-existing # skip runs whose DB already exists
19
+ """
20
+
21
+ import argparse
22
+ import itertools
23
+ import os
24
+ import subprocess
25
+ import time
26
+ from pathlib import Path
27
+
28
+
29
+ RUNS_DIR = Path(os.environ.get("RUNS_DIR", "./runs"))
30
+ VENV = os.environ.get("VENV_PATH", str(Path(__file__).parent.parent / ".venv"))
31
+ RUNNER = Path(os.environ.get("OASIS_RUNNER",
32
+ str(Path(__file__).parent.parent / "oasis" / "run_v9.py")))
33
+ LOGS_DIR = Path(os.environ.get("LOGS_DIR", "./logs/sweep"))
34
+
35
+ MODELS = {
36
+ "qwen": ("Qwen/Qwen3-32B", "http://localhost:8002/v1"),
37
+ "oss": ("openai/gpt-oss-20b", "http://localhost:8003/v1"),
38
+ "mag": ("mistralai/Magistral-Small-2509", "http://localhost:8004/v1"),
39
+ "glm": ("zai-org/GLM-4-32B-0414", "http://localhost:8007/v1"),
40
+ "gem": ("google/gemma-4-31B-it", "http://localhost:8009/v1"),
41
+ }
42
+
43
+ MODEL_KEYS = list(MODELS.keys())
44
+ SEEDS = [42, 137, 271, 314, 999]
45
+ STEPS = 100
46
+ N_AGENTS = 20 # 10 per group
47
+
48
+
49
+ def run_id(a: str, b: str, seed: int) -> str:
50
+ return f"sweep_{a[:3]}_{b[:3]}_s{seed}"
51
+
52
+
53
+ def db_is_valid(db: Path) -> bool:
54
+ """Return True if the DB has enough data to be considered a complete run."""
55
+ if not db.exists():
56
+ return False
57
+ try:
58
+ import sqlite3
59
+ conn = sqlite3.connect(db)
60
+ nu = conn.execute("SELECT COUNT(DISTINCT user_id) FROM comment").fetchone()[0]
61
+ nc = conn.execute("SELECT COUNT(*) FROM comment").fetchone()[0]
62
+ conn.close()
63
+ return nu >= 18 and nc >= 200
64
+ except Exception:
65
+ return False
66
+
67
+
68
+ def launch(a: str, b: str, seed: int, dry_run: bool) -> dict:
69
+ rid = run_id(a, b, seed)
70
+ db = RUNS_DIR / f"{rid}.db"
71
+ log = LOGS_DIR / f"{rid}.log"
72
+ ma, mb = MODELS[a], MODELS[b]
73
+
74
+ env = {
75
+ **os.environ,
76
+ "VLLM_URL_A": ma[1], "MODEL_NAME_A": ma[0],
77
+ "VLLM_URL_B": mb[1], "MODEL_NAME_B": mb[0],
78
+ "OASIS_DB_PATH": str(db),
79
+ }
80
+ cmd = [
81
+ f"{VENV}/bin/python3", str(RUNNER),
82
+ "--mode", "hetero",
83
+ "--steps", str(STEPS),
84
+ "--agents", str(N_AGENTS),
85
+ "--seed-posts", str(N_AGENTS),
86
+ "--activate-prob", "0.3",
87
+ "--rng-seed", str(seed),
88
+ "--db", str(db),
89
+ ]
90
+
91
+ if dry_run:
92
+ print(f" [DRY] {rid} A={a}({ma[0]}) B={b}({mb[0]}) seed={seed}")
93
+ return {"rid": rid, "proc": None}
94
+
95
+ LOGS_DIR.mkdir(parents=True, exist_ok=True)
96
+ RUNS_DIR.mkdir(parents=True, exist_ok=True)
97
+ with open(log, "w") as lf:
98
+ proc = subprocess.Popen(cmd, env=env, stdout=lf, stderr=lf)
99
+ print(f" [{rid}] PID={proc.pid} A={a} B={b} seed={seed}")
100
+ return {"rid": rid, "proc": proc}
101
+
102
+
103
+ def all_configs():
104
+ configs = []
105
+ for pair in itertools.combinations(MODEL_KEYS, 2):
106
+ for perm in itertools.permutations(pair):
107
+ for seed in SEEDS:
108
+ configs.append((perm[0], perm[1], seed))
109
+ return configs
110
+
111
+
112
+ def main():
113
+ parser = argparse.ArgumentParser(description=__doc__)
114
+ parser.add_argument("--dry-run", action="store_true",
115
+ help="Print configs without launching.")
116
+ parser.add_argument("--max-parallel", type=int, default=2,
117
+ help="Maximum concurrent runs.")
118
+ parser.add_argument("--skip-existing", action="store_true", default=True,
119
+ help="Skip runs whose DB already exists and is valid.")
120
+ args = parser.parse_args()
121
+
122
+ configs = all_configs()
123
+ print(f"Dyadic sweep: {len(configs)} configs "
124
+ f"(C(5,2)×2 ordered pairs × {len(SEEDS)} seeds)")
125
+ print(f"Seeds: {SEEDS} max_parallel: {args.max_parallel} "
126
+ f"dry_run: {args.dry_run}")
127
+
128
+ active = []
129
+ for a, b, seed in configs:
130
+ active = [r for r in active if r["proc"] and r["proc"].poll() is None]
131
+ while len(active) >= args.max_parallel:
132
+ time.sleep(10)
133
+ active = [r for r in active if r["proc"] and r["proc"].poll() is None]
134
+
135
+ if args.skip_existing:
136
+ db = RUNS_DIR / f"{run_id(a, b, seed)}.db"
137
+ if db_is_valid(db):
138
+ print(f" [skip] {run_id(a, b, seed)} (valid DB exists)")
139
+ continue
140
+
141
+ r = launch(a, b, seed, args.dry_run)
142
+ if r["proc"]:
143
+ active.append(r)
144
+ time.sleep(2)
145
+
146
+ for r in active:
147
+ if r["proc"]:
148
+ r["proc"].wait()
149
+ print("All dyadic configs done.")
150
+
151
+
152
+ if __name__ == "__main__":
153
+ main()
sweep/sweep_triadic.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Triadic (3-model) sweep for the divsim paper, with preemption support.
3
+
4
+ Enumerates all C(5,3)=10 model triplets, samples 3 of the 6 possible orderings
5
+ per triplet (the 3 with maximum positional diversity), crossed with 3 seeds.
6
+ Total: 10 triplets × 3 orderings × 3 seeds = 90 configurations.
7
+
8
+ Preemption support: run_v9.py catches SIGTERM and exits cleanly after the
9
+ current step commit. This script checks for partial DBs and resumes them via
10
+ --resume rather than restarting from scratch.
11
+
12
+ Configuration is read from environment variables:
13
+ RUNS_DIR — output directory for .db files (required)
14
+ VENV_PATH — path to the Python venv with oasis installed
15
+ OASIS_RUNNER — path to run_v9.py (defaults to <this_dir>/../oasis/run_v9.py)
16
+ LOGS_DIR — directory for per-run log files
17
+
18
+ Usage:
19
+ python sweep_triadic.py --dry-run # print all configs, no launch
20
+ python sweep_triadic.py --max-parallel 2 # limit concurrent runs
21
+ python sweep_triadic.py --triplets qwen,oss,mag # run a specific triplet only
22
+ """
23
+
24
+ import argparse
25
+ import itertools
26
+ import os
27
+ import subprocess
28
+ import time
29
+ from pathlib import Path
30
+
31
+
32
+ RUNS_DIR = Path(os.environ.get("RUNS_DIR", "./runs"))
33
+ VENV = os.environ.get("VENV_PATH", str(Path(__file__).parent.parent / ".venv"))
34
+ RUNNER = Path(os.environ.get("OASIS_RUNNER",
35
+ str(Path(__file__).parent.parent / "oasis" / "run_v9.py")))
36
+ LOGS_DIR = Path(os.environ.get("LOGS_DIR", "./logs/sweep"))
37
+
38
+ MODELS = {
39
+ "qwen": ("Qwen/Qwen3-32B", "http://localhost:8002/v1"),
40
+ "oss": ("openai/gpt-oss-20b", "http://localhost:8003/v1"),
41
+ "mag": ("mistralai/Magistral-Small-2509", "http://localhost:8004/v1"),
42
+ "glm": ("zai-org/GLM-4-32B-0414", "http://localhost:8007/v1"),
43
+ "gem": ("google/gemma-4-31B-it", "http://localhost:8009/v1"),
44
+ }
45
+
46
+ SEEDS = [42, 271, 999]
47
+ STEPS = 100
48
+ N_AGENTS = 30 # 10 per group
49
+
50
+
51
+ def sampled_orderings(triplet: tuple) -> list:
52
+ """Return 3 of the 6 possible permutations, evenly spaced for positional diversity."""
53
+ perms = list(itertools.permutations(triplet))
54
+ return [perms[0], perms[2], perms[4]]
55
+
56
+
57
+ def run_id(perm: tuple, seed: int) -> str:
58
+ return f"sweep_tri_{'_'.join(m[:3] for m in perm)}_s{seed}"
59
+
60
+
61
+ def db_is_valid(db: Path) -> bool:
62
+ """Return True if the DB has enough active agents to be a complete triadic run."""
63
+ if not db.exists():
64
+ return False
65
+ try:
66
+ import sqlite3
67
+ conn = sqlite3.connect(db)
68
+ nu = conn.execute("SELECT COUNT(DISTINCT user_id) FROM comment").fetchone()[0]
69
+ conn.close()
70
+ return nu >= 26
71
+ except Exception:
72
+ return False
73
+
74
+
75
+ def launch(perm: tuple, seed: int, dry_run: bool) -> dict | None:
76
+ rid = run_id(perm, seed)
77
+ db = RUNS_DIR / f"{rid}.db"
78
+ log = LOGS_DIR / f"{rid}.log"
79
+
80
+ if db_is_valid(db):
81
+ print(f" [skip] {rid} (valid DB exists)")
82
+ return None
83
+
84
+ resume = db.exists() and db.stat().st_size > 50_000
85
+
86
+ ma, mb, mc = MODELS[perm[0]], MODELS[perm[1]], MODELS[perm[2]]
87
+ env = {
88
+ **os.environ,
89
+ "VLLM_URL_A": ma[1], "MODEL_NAME_A": ma[0],
90
+ "VLLM_URL_B": mb[1], "MODEL_NAME_B": mb[0],
91
+ "VLLM_URL_C": mc[1], "MODEL_NAME_C": mc[0],
92
+ "OASIS_DB_PATH": str(db),
93
+ }
94
+ cmd = [
95
+ f"{VENV}/bin/python3", str(RUNNER),
96
+ "--mode", "hetero3",
97
+ "--steps", str(STEPS),
98
+ "--agents", str(N_AGENTS),
99
+ "--seed-posts", str(N_AGENTS),
100
+ "--activate-prob", "0.3",
101
+ "--rng-seed", str(seed),
102
+ "--db", str(db),
103
+ ]
104
+ if resume:
105
+ cmd.append("--resume")
106
+
107
+ status = "[resume]" if resume else "[run] "
108
+ print(f" {status} {rid}")
109
+
110
+ if dry_run:
111
+ print(f" A={perm[0]} B={perm[1]} C={perm[2]} seed={seed}")
112
+ return None
113
+
114
+ LOGS_DIR.mkdir(parents=True, exist_ok=True)
115
+ RUNS_DIR.mkdir(parents=True, exist_ok=True)
116
+ with open(log, "a") as lf:
117
+ proc = subprocess.Popen(cmd, env=env, stdout=lf, stderr=lf)
118
+ return {"rid": rid, "proc": proc}
119
+
120
+
121
+ def all_triplets():
122
+ return list(itertools.combinations(MODELS.keys(), 3))
123
+
124
+
125
+ def main():
126
+ parser = argparse.ArgumentParser(description=__doc__)
127
+ parser.add_argument("--dry-run", action="store_true",
128
+ help="Print configs without launching.")
129
+ parser.add_argument("--max-parallel", type=int, default=2,
130
+ help="Maximum concurrent runs.")
131
+ parser.add_argument("--triplets", nargs="*",
132
+ help="Restrict to specific triplets, e.g. qwen,oss,mag")
133
+ args = parser.parse_args()
134
+
135
+ triplets = all_triplets()
136
+ if args.triplets:
137
+ triplets = [tuple(t.split(",")) for t in args.triplets]
138
+
139
+ configs = [
140
+ (perm, seed)
141
+ for triplet in triplets
142
+ for perm in sampled_orderings(triplet)
143
+ for seed in SEEDS
144
+ ]
145
+
146
+ print(f"Triadic sweep: {len(triplets)} triplets × 3 orderings × "
147
+ f"{len(SEEDS)} seeds = {len(configs)} configs")
148
+ print(f"Triplets: {['+'.join(t) for t in triplets]}")
149
+ print()
150
+
151
+ active = []
152
+ for perm, seed in configs:
153
+ active = [r for r in active if r["proc"].poll() is None]
154
+ while len(active) >= args.max_parallel:
155
+ time.sleep(15)
156
+ active = [r for r in active if r["proc"].poll() is None]
157
+
158
+ r = launch(perm, seed, args.dry_run)
159
+ if r:
160
+ active.append(r)
161
+ if not args.dry_run:
162
+ time.sleep(2)
163
+
164
+ for r in active:
165
+ r["proc"].wait()
166
+ print("All triadic configs done.")
167
+
168
+
169
+ if __name__ == "__main__":
170
+ main()