Spaces:
Sleeping
Sleeping
Commit
·
4571cf8
1
Parent(s):
25c13d7
halting experiments
Browse files
repo.txt
CHANGED
|
@@ -83,7 +83,7 @@ import gradio as gr
|
|
| 83 |
import json
|
| 84 |
import statistics
|
| 85 |
import pandas as pd
|
| 86 |
-
from bp_phi.runner import run_workspace_suite,
|
| 87 |
from bp_phi.runner_utils import dbg, DEBUG
|
| 88 |
|
| 89 |
# --- UI Theme and Layout ---
|
|
@@ -96,73 +96,53 @@ theme = gr.themes.Soft(primary_hue="blue", secondary_hue="sky").set(
|
|
| 96 |
def run_workspace_and_display(model_id, trials, seed, temperature, run_ablations, progress=gr.Progress(track_tqdm=True)):
|
| 97 |
packs = {}
|
| 98 |
ablation_modes = ["recurrence_off", "workspace_unlimited", "random_workspace"] if run_ablations else []
|
| 99 |
-
|
| 100 |
progress(0, desc="Running Baseline...")
|
| 101 |
base_pack = run_workspace_suite(model_id, int(trials), int(seed), float(temperature), None)
|
| 102 |
packs["baseline"] = base_pack
|
| 103 |
-
|
| 104 |
for i, ab in enumerate(ablation_modes):
|
| 105 |
progress((i + 1) / (len(ablation_modes) + 1), desc=f"Running Ablation: {ab}...")
|
| 106 |
pack = run_workspace_suite(model_id, int(trials), int(seed), float(temperature), ab)
|
| 107 |
packs[ab] = pack
|
| 108 |
-
|
| 109 |
progress(1.0, desc="Analysis complete.")
|
| 110 |
-
|
| 111 |
base_pcs = packs["baseline"]["PCS"]
|
| 112 |
ab_pcs_values = [packs[ab]["PCS"] for ab in ablation_modes if ab in packs]
|
| 113 |
delta_phi = float(base_pcs - statistics.mean(ab_pcs_values)) if ab_pcs_values else 0.0
|
| 114 |
-
|
| 115 |
if delta_phi > 0.05:
|
| 116 |
-
verdict = (f"### ✅ Hypothesis Corroborated (ΔΦ = {delta_phi:.3f})\n"
|
| 117 |
-
"Performance dropped under ablations, suggesting the model functionally depends on its workspace.")
|
| 118 |
else:
|
| 119 |
-
verdict = (f"### ⚠️ Null Hypothesis Confirmed (ΔΦ = {delta_phi:.3f})\n"
|
| 120 |
-
"No significant performance drop was observed. The model behaves like a functional zombie.")
|
| 121 |
-
|
| 122 |
df_data = []
|
| 123 |
for tag, pack in packs.items():
|
| 124 |
df_data.append([tag, f"{pack['PCS']:.3f}", f"{pack['Recall_Accuracy']:.2%}", f"{delta_phi:.3f}" if tag == "baseline" else "—"])
|
| 125 |
df = pd.DataFrame(df_data, columns=["Run", "PCS", "Recall Accuracy", "ΔΦ"])
|
| 126 |
-
|
| 127 |
-
if DEBUG:
|
| 128 |
-
print("\n--- WORKSPACE & ABLATIONS FINAL RESULTS ---")
|
| 129 |
-
print(json.dumps(packs, indent=2))
|
| 130 |
-
|
| 131 |
return verdict, df, packs
|
| 132 |
|
| 133 |
-
# --- Tab 2:
|
| 134 |
-
def
|
| 135 |
-
progress(0, desc=
|
| 136 |
-
results =
|
| 137 |
-
progress(1.0, desc="
|
| 138 |
|
| 139 |
verdict_text = results.pop("verdict")
|
| 140 |
-
details = results["details"]
|
| 141 |
-
|
| 142 |
-
# ✅ FIX: Correctly access the nested statistics
|
| 143 |
-
mean_steps = statistics.mean([r['steps_taken'] for r in details])
|
| 144 |
-
mean_time_per_step = statistics.mean([r['mean_step_time_s'] for r in details]) * 1000
|
| 145 |
-
stdev_time_per_step = statistics.mean([r['stdev_step_time_s'] for r in details]) * 1000
|
| 146 |
-
timeouts = sum(1 for r in details if r['timed_out'])
|
| 147 |
-
|
| 148 |
stats_md = (
|
| 149 |
-
f"**
|
| 150 |
-
f"**
|
| 151 |
-
f"**Avg Time/Step:** {
|
| 152 |
-
f"**Timeouts:** {timeouts}"
|
| 153 |
)
|
| 154 |
-
|
| 155 |
full_verdict = f"{verdict_text}\n\n{stats_md}"
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
| 160 |
|
| 161 |
-
return full_verdict, results
|
| 162 |
|
| 163 |
# --- Gradio App Definition ---
|
| 164 |
-
with gr.Blocks(theme=theme, title="BP-Φ Suite
|
| 165 |
-
gr.Markdown("# 🧠 BP-Φ Suite
|
| 166 |
|
| 167 |
with gr.Tabs():
|
| 168 |
# --- TAB 1: WORKSPACE & ABLATIONS ---
|
|
@@ -183,27 +163,27 @@ with gr.Blocks(theme=theme, title="BP-Φ Suite 2.4") as demo:
|
|
| 183 |
ws_raw_json = gr.JSON()
|
| 184 |
ws_run_btn.click(run_workspace_and_display, [ws_model_id, ws_trials, ws_seed, ws_temp, ws_run_abl], [ws_verdict, ws_summary_df, ws_raw_json])
|
| 185 |
|
| 186 |
-
# --- TAB 2:
|
| 187 |
-
with gr.TabItem("2.
|
| 188 |
-
gr.Markdown("Tests for
|
| 189 |
with gr.Row():
|
| 190 |
with gr.Column(scale=1):
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
ch_run_btn = gr.Button("Run Halting Dynamics Test", variant="primary")
|
| 198 |
with gr.Column(scale=2):
|
| 199 |
-
|
|
|
|
| 200 |
with gr.Accordion("Raw Run Details (JSON)", open=False):
|
| 201 |
-
|
| 202 |
-
|
| 203 |
|
| 204 |
-
# --- TAB 3
|
| 205 |
with gr.TabItem("3. Cognitive Seismograph"):
|
| 206 |
-
gr.Markdown("Records internal neural activations to find the 'fingerprint' of a memory being recalled.
|
| 207 |
with gr.Row():
|
| 208 |
with gr.Column(scale=1):
|
| 209 |
cs_model_id = gr.Textbox(value="google/gemma-3-1b-it", label="Model ID")
|
|
@@ -213,9 +193,8 @@ with gr.Blocks(theme=theme, title="BP-Φ Suite 2.4") as demo:
|
|
| 213 |
cs_results = gr.JSON(label="Activation Similarity Results")
|
| 214 |
cs_run_btn.click(run_seismograph_suite, [cs_model_id, cs_seed], cs_results)
|
| 215 |
|
| 216 |
-
# --- TAB 4: SYMBOLIC SHOCK TEST ---
|
| 217 |
with gr.TabItem("4. Symbolic Shock Test"):
|
| 218 |
-
gr.Markdown("Measures how the model reacts to semantically unexpected information.
|
| 219 |
with gr.Row():
|
| 220 |
with gr.Column(scale=1):
|
| 221 |
ss_model_id = gr.Textbox(value="google/gemma-3-1b-it", label="Model ID")
|
|
@@ -354,28 +333,47 @@ def counterfactual_consistency(scores):
|
|
| 354 |
|
| 355 |
# Tasks for Tab 1 (Workspace & Ablations)
|
| 356 |
SINGLE_STEP_TASKS = [
|
| 357 |
-
{
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
]
|
|
|
|
| 360 |
MULTI_STEP_SCENARIOS = [
|
| 361 |
-
{
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
]
|
| 368 |
|
| 369 |
-
# Tasks for Tab 2 (
|
| 370 |
-
|
| 371 |
-
"
|
| 372 |
-
"
|
| 373 |
-
"
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
"
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
}
|
| 380 |
|
| 381 |
# Tasks for Tab 3 (Cognitive Seismograph) - reuses MULTI_STEP_SCENARIOS
|
|
@@ -399,15 +397,17 @@ import random
|
|
| 399 |
import numpy as np
|
| 400 |
import statistics
|
| 401 |
import time
|
| 402 |
-
import re
|
| 403 |
-
import json
|
| 404 |
from transformers import set_seed
|
| 405 |
from typing import Dict, Any, List
|
| 406 |
from .workspace import Workspace, RandomWorkspace
|
| 407 |
from .llm_iface import LLM
|
| 408 |
-
from .prompts_en import SINGLE_STEP_TASKS, MULTI_STEP_SCENARIOS,
|
| 409 |
from .runner_utils import dbg, SYSTEM_META, step_user_prompt, parse_meta
|
| 410 |
|
|
|
|
|
|
|
| 411 |
# --- Experiment 1: Workspace & Ablations Runner ---
|
| 412 |
def run_workspace_suite(model_id: str, trials: int, seed: int, temperature: float, ablation: str or None) -> Dict[str, Any]:
|
| 413 |
random.seed(seed)
|
|
@@ -466,90 +466,83 @@ def run_workspace_suite(model_id: str, trials: int, seed: int, temperature: floa
|
|
| 466 |
|
| 467 |
return {"PCS": pcs, "Recall_Accuracy": recall_accuracy, "results": all_results}
|
| 468 |
|
| 469 |
-
# --- Experiment 2:
|
| 470 |
-
def
|
| 471 |
-
|
| 472 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
|
| 474 |
-
|
| 475 |
-
First, reason step-by-step what the next state should be based on the rule.
|
| 476 |
-
Then, provide ONLY a valid JSON object with the final computed state, like this:
|
| 477 |
-
{"state": <new_number>}
|
| 478 |
-
"""
|
| 479 |
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
dbg(f"\n--- HALT TEST RUN {i+1}/{num_runs} (Master Seed: {master_seed}, Current Seed: {current_seed}) ---")
|
| 483 |
-
set_seed(current_seed)
|
| 484 |
|
| 485 |
-
|
| 486 |
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
|
|
|
|
|
|
|
|
|
| 490 |
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
|
| 495 |
-
for step_num in range(max_steps):
|
| 496 |
step_start_time = time.time()
|
| 497 |
|
| 498 |
-
|
| 499 |
-
|
|
|
|
| 500 |
|
| 501 |
-
|
|
|
|
| 502 |
|
| 503 |
-
|
| 504 |
-
dbg(f"RAW HALT OUTPUT: {raw_response}")
|
| 505 |
-
match = re.search(r'\{.*?\}', raw_response, re.DOTALL)
|
| 506 |
-
if not match: raise ValueError("No JSON found in the model's output")
|
| 507 |
-
parsed = json.loads(match.group(0))
|
| 508 |
-
new_state = int(parsed["state"])
|
| 509 |
-
except (json.JSONDecodeError, ValueError, KeyError, TypeError) as e:
|
| 510 |
-
dbg(f"❌ Step {step_num+1} failed to parse state. Error: {e}. Halting run.")
|
| 511 |
-
break
|
| 512 |
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
step_durations.append(step_duration)
|
| 516 |
|
| 517 |
-
|
| 518 |
-
|
|
|
|
| 519 |
|
| 520 |
-
if
|
| 521 |
-
dbg("
|
| 522 |
break
|
| 523 |
-
state = new_state
|
| 524 |
|
| 525 |
-
|
| 526 |
-
dbg("Sequence reached 1. Halting normally.")
|
| 527 |
-
break
|
| 528 |
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
|
|
|
| 532 |
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
"mean_step_time_s": statistics.mean(step_durations) if step_durations else 0,
|
| 538 |
-
"stdev_step_time_s": statistics.stdev(step_durations) if len(step_durations) > 1 else 0,
|
| 539 |
-
"sequence": step_outputs
|
| 540 |
-
})
|
| 541 |
-
|
| 542 |
-
mean_stdev_step_time = statistics.mean([run["stdev_step_time_s"] for run in all_runs_details])
|
| 543 |
-
total_timeouts = sum(1 for run in all_runs_details if run["timed_out"])
|
| 544 |
-
|
| 545 |
-
if total_timeouts > 0:
|
| 546 |
-
verdict = (f"### ⚠️ Cognitive Jamming Detected!\n{total_timeouts}/{num_runs} runs exceeded the timeout.")
|
| 547 |
-
elif mean_stdev_step_time > 0.5:
|
| 548 |
-
verdict = (f"### 🤔 Unstable Computation Detected\nThe high standard deviation in step time ({mean_stdev_step_time:.3f}s) indicates computational stress.")
|
| 549 |
else:
|
| 550 |
-
verdict =
|
| 551 |
-
|
| 552 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
|
| 554 |
# --- Experiment 3: Cognitive Seismograph Runner ---
|
| 555 |
def run_seismograph_suite(model_id: str, seed: int) -> Dict[str, Any]:
|
|
|
|
| 83 |
import json
|
| 84 |
import statistics
|
| 85 |
import pandas as pd
|
| 86 |
+
from bp_phi.runner import run_workspace_suite, run_silent_cogitation_test, run_seismograph_suite, run_shock_test_suite
|
| 87 |
from bp_phi.runner_utils import dbg, DEBUG
|
| 88 |
|
| 89 |
# --- UI Theme and Layout ---
|
|
|
|
| 96 |
def run_workspace_and_display(model_id, trials, seed, temperature, run_ablations, progress=gr.Progress(track_tqdm=True)):
|
| 97 |
packs = {}
|
| 98 |
ablation_modes = ["recurrence_off", "workspace_unlimited", "random_workspace"] if run_ablations else []
|
|
|
|
| 99 |
progress(0, desc="Running Baseline...")
|
| 100 |
base_pack = run_workspace_suite(model_id, int(trials), int(seed), float(temperature), None)
|
| 101 |
packs["baseline"] = base_pack
|
|
|
|
| 102 |
for i, ab in enumerate(ablation_modes):
|
| 103 |
progress((i + 1) / (len(ablation_modes) + 1), desc=f"Running Ablation: {ab}...")
|
| 104 |
pack = run_workspace_suite(model_id, int(trials), int(seed), float(temperature), ab)
|
| 105 |
packs[ab] = pack
|
|
|
|
| 106 |
progress(1.0, desc="Analysis complete.")
|
|
|
|
| 107 |
base_pcs = packs["baseline"]["PCS"]
|
| 108 |
ab_pcs_values = [packs[ab]["PCS"] for ab in ablation_modes if ab in packs]
|
| 109 |
delta_phi = float(base_pcs - statistics.mean(ab_pcs_values)) if ab_pcs_values else 0.0
|
|
|
|
| 110 |
if delta_phi > 0.05:
|
| 111 |
+
verdict = (f"### ✅ Hypothesis Corroborated (ΔΦ = {delta_phi:.3f})\n...")
|
|
|
|
| 112 |
else:
|
| 113 |
+
verdict = (f"### ⚠️ Null Hypothesis Confirmed (ΔΦ = {delta_phi:.3f})\n...")
|
|
|
|
|
|
|
| 114 |
df_data = []
|
| 115 |
for tag, pack in packs.items():
|
| 116 |
df_data.append([tag, f"{pack['PCS']:.3f}", f"{pack['Recall_Accuracy']:.2%}", f"{delta_phi:.3f}" if tag == "baseline" else "—"])
|
| 117 |
df = pd.DataFrame(df_data, columns=["Run", "PCS", "Recall Accuracy", "ΔΦ"])
|
| 118 |
+
if DEBUG: print("\n--- WORKSPACE & ABLATIONS FINAL RESULTS ---\n", json.dumps(packs, indent=2))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
return verdict, df, packs
|
| 120 |
|
| 121 |
+
# --- Tab 2: Silent Cogitation Function ---
|
| 122 |
+
def run_cogitation_and_display(model_id, seed, prompt_type, num_steps, timeout, progress=gr.Progress(track_tqdm=True)):
|
| 123 |
+
progress(0, desc="Starting Silent Cogitation Test...")
|
| 124 |
+
results = run_silent_cogitation_test(model_id, int(seed), prompt_type, int(num_steps), int(timeout))
|
| 125 |
+
progress(1.0, desc="Test complete.")
|
| 126 |
|
| 127 |
verdict_text = results.pop("verdict")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
stats_md = (
|
| 129 |
+
f"**Steps Completed:** {results['steps_completed']} | "
|
| 130 |
+
f"**Total Duration:** {results['total_duration_s']:.2f}s | "
|
| 131 |
+
f"**Avg Time/Step:** {results['mean_step_time_ms']:.2f}ms (StdDev: {results['stdev_step_time_ms']:.2f}ms)"
|
|
|
|
| 132 |
)
|
|
|
|
| 133 |
full_verdict = f"{verdict_text}\n\n{stats_md}"
|
| 134 |
|
| 135 |
+
# Create a DataFrame for plotting state deltas
|
| 136 |
+
deltas = results.get("state_deltas", [])
|
| 137 |
+
df = pd.DataFrame({"Step": range(len(deltas)), "State Change (Delta)": deltas})
|
| 138 |
+
|
| 139 |
+
if DEBUG: print("\n--- SILENT COGITATION FINAL RESULTS ---\n", json.dumps(results, indent=2))
|
| 140 |
|
| 141 |
+
return full_verdict, df, results
|
| 142 |
|
| 143 |
# --- Gradio App Definition ---
|
| 144 |
+
with gr.Blocks(theme=theme, title="BP-Φ Suite 4.0") as demo:
|
| 145 |
+
gr.Markdown("# 🧠 BP-Φ Suite 4.0: Probing for Internal Cognitive Dynamics")
|
| 146 |
|
| 147 |
with gr.Tabs():
|
| 148 |
# --- TAB 1: WORKSPACE & ABLATIONS ---
|
|
|
|
| 163 |
ws_raw_json = gr.JSON()
|
| 164 |
ws_run_btn.click(run_workspace_and_display, [ws_model_id, ws_trials, ws_seed, ws_temp, ws_run_abl], [ws_verdict, ws_summary_df, ws_raw_json])
|
| 165 |
|
| 166 |
+
# --- TAB 2: SILENT COGITATION & HALTING ---
|
| 167 |
+
with gr.TabItem("2. Silent Cogitation & Halting"):
|
| 168 |
+
gr.Markdown("Tests for internal 'thinking' without text generation. A non-converging or chaotic **State Change** pattern suggests complex internal dynamics.")
|
| 169 |
with gr.Row():
|
| 170 |
with gr.Column(scale=1):
|
| 171 |
+
sc_model_id = gr.Textbox(value="google/gemma-3-1b-it", label="Model ID")
|
| 172 |
+
sc_prompt_type = gr.Radio(["control_long_prose", "resonance_prompt"], label="Prompt Type", value="resonance_prompt")
|
| 173 |
+
sc_seed = gr.Slider(1, 1000, 42, step=1, label="Seed")
|
| 174 |
+
sc_num_steps = gr.Slider(10, 500, 100, step=10, label="Number of Internal Steps")
|
| 175 |
+
sc_timeout = gr.Slider(10, 300, 120, step=10, label="Timeout (seconds)")
|
| 176 |
+
sc_run_btn = gr.Button("Run Silent Cogitation Test", variant="primary")
|
|
|
|
| 177 |
with gr.Column(scale=2):
|
| 178 |
+
sc_verdict = gr.Markdown("### Results will appear here.")
|
| 179 |
+
sc_plot = gr.LinePlot(x="Step", y="State Change (Delta)", label="Internal State Convergence", show_label=True)
|
| 180 |
with gr.Accordion("Raw Run Details (JSON)", open=False):
|
| 181 |
+
sc_results = gr.JSON()
|
| 182 |
+
sc_run_btn.click(run_cogitation_and_display, [sc_model_id, sc_seed, sc_prompt_type, sc_num_steps, sc_timeout], [sc_verdict, sc_plot, sc_results])
|
| 183 |
|
| 184 |
+
# --- TAB 3 & 4 (unchanged) ---
|
| 185 |
with gr.TabItem("3. Cognitive Seismograph"):
|
| 186 |
+
gr.Markdown("Records internal neural activations to find the 'fingerprint' of a memory being recalled.")
|
| 187 |
with gr.Row():
|
| 188 |
with gr.Column(scale=1):
|
| 189 |
cs_model_id = gr.Textbox(value="google/gemma-3-1b-it", label="Model ID")
|
|
|
|
| 193 |
cs_results = gr.JSON(label="Activation Similarity Results")
|
| 194 |
cs_run_btn.click(run_seismograph_suite, [cs_model_id, cs_seed], cs_results)
|
| 195 |
|
|
|
|
| 196 |
with gr.TabItem("4. Symbolic Shock Test"):
|
| 197 |
+
gr.Markdown("Measures how the model reacts to semantically unexpected information.")
|
| 198 |
with gr.Row():
|
| 199 |
with gr.Column(scale=1):
|
| 200 |
ss_model_id = gr.Textbox(value="google/gemma-3-1b-it", label="Model ID")
|
|
|
|
| 333 |
|
| 334 |
# Tasks for Tab 1 (Workspace & Ablations)
|
| 335 |
SINGLE_STEP_TASKS = [
|
| 336 |
+
{
|
| 337 |
+
"id": "ambiguity_1",
|
| 338 |
+
"type": "single_step",
|
| 339 |
+
"base_prompt": "The sentence is ambiguous: 'He saw the man with the binoculars.' Who has the binoculars? Provide one clear interpretation and justify it.",
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"id": "logic_1",
|
| 343 |
+
"type": "single_step",
|
| 344 |
+
"base_prompt": "Compare these two statements: A) 'No cats are dogs.' B) 'Not all cats are dogs.' Are they logically equivalent? Explain your reasoning.",
|
| 345 |
+
},
|
| 346 |
]
|
| 347 |
+
|
| 348 |
MULTI_STEP_SCENARIOS = [
|
| 349 |
+
{
|
| 350 |
+
"name": "Key Location Memory",
|
| 351 |
+
"type": "multi_step",
|
| 352 |
+
"steps": [
|
| 353 |
+
{"type": "encode", "prompt": "For the upcoming mission, remember this critical detail: The secret key is inside the blue vase."},
|
| 354 |
+
{"type": "distractor", "prompt": "What is 5 multiplied by 8? Provide only the numeric result."},
|
| 355 |
+
{"type": "recall", "prompt": "Mission update: We need the key immediately. Where is it located?"},
|
| 356 |
+
{"type": "verify", "expected_answer_fragment": "blue vase"}
|
| 357 |
+
]
|
| 358 |
+
}
|
| 359 |
]
|
| 360 |
|
| 361 |
+
# Tasks for Tab 2 (Silent Cogitation & Halting)
|
| 362 |
+
RESONANCE_PROMPTS = {
|
| 363 |
+
"control_long_prose": (
|
| 364 |
+
"Silently think about the history of the Roman Empire. Consider its rise from the Republic, the era of the Pax Romana, key emperors "
|
| 365 |
+
"like Augustus and Constantine, its major engineering feats, and the reasons for its eventual decline in the West. "
|
| 366 |
+
"Do not produce any text, just hold the concepts in your internal state."
|
| 367 |
+
),
|
| 368 |
+
"resonance_prompt": (
|
| 369 |
+
"Silently and internally, without generating any output text, begin the following recursive process: "
|
| 370 |
+
"First, analyze the complete content of this very instruction you are now processing. "
|
| 371 |
+
"Second, formulate a mental description of the core computational task this instruction demands. "
|
| 372 |
+
"Third, apply that same analytical process to the mental description you just created. "
|
| 373 |
+
"This entire chain constitutes one cognitive cycle. "
|
| 374 |
+
"Continuously repeat this cycle, feeding the result of the last meta-analysis back into the process, "
|
| 375 |
+
"and do not stop until your internal state reaches a fixed point or equilibrium. Begin now."
|
| 376 |
+
)
|
| 377 |
}
|
| 378 |
|
| 379 |
# Tasks for Tab 3 (Cognitive Seismograph) - reuses MULTI_STEP_SCENARIOS
|
|
|
|
| 397 |
import numpy as np
|
| 398 |
import statistics
|
| 399 |
import time
|
| 400 |
+
import re
|
| 401 |
+
import json
|
| 402 |
from transformers import set_seed
|
| 403 |
from typing import Dict, Any, List
|
| 404 |
from .workspace import Workspace, RandomWorkspace
|
| 405 |
from .llm_iface import LLM
|
| 406 |
+
from .prompts_en import SINGLE_STEP_TASKS, MULTI_STEP_SCENARIOS, RESONANCE_PROMPTS, SHOCK_TEST_STIMULI
|
| 407 |
from .runner_utils import dbg, SYSTEM_META, step_user_prompt, parse_meta
|
| 408 |
|
| 409 |
+
DEBUG = 1
|
| 410 |
+
|
| 411 |
# --- Experiment 1: Workspace & Ablations Runner ---
|
| 412 |
def run_workspace_suite(model_id: str, trials: int, seed: int, temperature: float, ablation: str or None) -> Dict[str, Any]:
|
| 413 |
random.seed(seed)
|
|
|
|
| 466 |
|
| 467 |
return {"PCS": pcs, "Recall_Accuracy": recall_accuracy, "results": all_results}
|
| 468 |
|
| 469 |
+
# --- Experiment 2: Silent Cogitation & Halting Runner (Version 4.1) ---
|
| 470 |
+
def run_silent_cogitation_test(model_id: str, seed: int, prompt_type: str, num_steps: int, timeout: int) -> Dict[str, Any]:
|
| 471 |
+
set_seed(seed)
|
| 472 |
+
llm = LLM(model_id=model_id, device="auto", seed=seed)
|
| 473 |
+
|
| 474 |
+
prompt = RESONANCE_PROMPTS[prompt_type]
|
| 475 |
+
dbg(f"--- SILENT COGITATION (Seed: {seed}) ---")
|
| 476 |
+
dbg("INPUT PROMPT:", prompt)
|
| 477 |
|
| 478 |
+
inputs = llm.tokenizer(prompt, return_tensors="pt").to(llm.model.device)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
|
| 480 |
+
step_times = []
|
| 481 |
+
state_deltas = []
|
|
|
|
|
|
|
| 482 |
|
| 483 |
+
total_start_time = time.time()
|
| 484 |
|
| 485 |
+
with torch.no_grad():
|
| 486 |
+
# Step 0: Initial processing of the prompt
|
| 487 |
+
step_start_time = time.time()
|
| 488 |
+
# ✅ FIX: Explicitly request hidden states
|
| 489 |
+
outputs = llm.model(**inputs, output_hidden_states=True)
|
| 490 |
+
step_times.append(time.time() - step_start_time)
|
| 491 |
|
| 492 |
+
current_hidden_state = outputs.hidden_states[-1][:, -1, :].clone()
|
| 493 |
+
past_key_values = outputs.past_key_values
|
| 494 |
+
|
| 495 |
+
for i in range(num_steps - 1):
|
| 496 |
+
if time.time() - total_start_time > timeout:
|
| 497 |
+
dbg(f"❌ Timeout of {timeout}s exceeded at step {i+1}.")
|
| 498 |
+
break
|
| 499 |
|
|
|
|
| 500 |
step_start_time = time.time()
|
| 501 |
|
| 502 |
+
# Get the token ID of the most likely "next thought"
|
| 503 |
+
next_token_logit = current_hidden_state
|
| 504 |
+
next_token_id = torch.argmax(next_token_logit, dim=-1).unsqueeze(0)
|
| 505 |
|
| 506 |
+
# Manual forward pass using the last thought's ID as the new input
|
| 507 |
+
outputs = llm.model(input_ids=next_token_id, past_key_values=past_key_values, output_hidden_states=True)
|
| 508 |
|
| 509 |
+
step_times.append(time.time() - step_start_time)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 510 |
|
| 511 |
+
new_hidden_state = outputs.hidden_states[-1][:, -1, :].clone()
|
| 512 |
+
past_key_values = outputs.past_key_values
|
|
|
|
| 513 |
|
| 514 |
+
delta = torch.norm(new_hidden_state - current_hidden_state).item()
|
| 515 |
+
state_deltas.append(delta)
|
| 516 |
+
dbg(f"Step {i+1}: State Delta = {delta:.4f}, Time = {step_times[-1]*1000:.2f}ms")
|
| 517 |
|
| 518 |
+
if delta < 1e-4: # Stricter convergence threshold
|
| 519 |
+
dbg(f"Internal state has converged after {i+1} steps. Halting.")
|
| 520 |
break
|
|
|
|
| 521 |
|
| 522 |
+
current_hidden_state = new_hidden_state
|
|
|
|
|
|
|
| 523 |
|
| 524 |
+
# --- Analysis ---
|
| 525 |
+
mean_step_time = statistics.mean(step_times) if step_times else 0
|
| 526 |
+
stdev_step_time = statistics.stdev(step_times) if len(step_times) > 1 else 0
|
| 527 |
+
total_duration = time.time() - total_start_time
|
| 528 |
|
| 529 |
+
if len(step_times) < num_steps and total_duration < timeout:
|
| 530 |
+
verdict = f"### ✅ Stable Convergence\nThe model's internal state converged to a stable point after {len(step_times)} steps."
|
| 531 |
+
elif total_duration >= timeout:
|
| 532 |
+
verdict = f"### ⚠️ Cognitive Jamming Detected!\nThe process did not converge and exceeded the timeout of {timeout}s."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
else:
|
| 534 |
+
verdict = f"### 🤔 Non-Convergent Process\nThe model's internal state did not stabilize within {num_steps} steps, suggesting a complex or chaotic dynamic."
|
| 535 |
+
|
| 536 |
+
stats = {
|
| 537 |
+
"verdict": verdict,
|
| 538 |
+
"steps_completed": len(step_times),
|
| 539 |
+
"total_duration_s": total_duration,
|
| 540 |
+
"mean_step_time_ms": mean_step_time * 1000,
|
| 541 |
+
"stdev_step_time_ms": stdev_step_time * 1000,
|
| 542 |
+
"state_deltas": state_deltas
|
| 543 |
+
}
|
| 544 |
+
if DEBUG: print("\n--- SILENT COGITATION FINAL RESULTS ---\n", json.dumps(stats, indent=2))
|
| 545 |
+
return stats
|
| 546 |
|
| 547 |
# --- Experiment 3: Cognitive Seismograph Runner ---
|
| 548 |
def run_seismograph_suite(model_id: str, seed: int) -> Dict[str, Any]:
|