neuralworm commited on
Commit
4571cf8
·
1 Parent(s): 25c13d7

halting experiments

Browse files
Files changed (1) hide show
  1. repo.txt +137 -144
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, run_halting_test, run_seismograph_suite, run_shock_test_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: Halting Test Function (Corrected) ---
134
- def run_halting_and_display(model_id, seed, prompt_type, num_runs, max_steps, timeout, progress=gr.Progress(track_tqdm=True)):
135
- progress(0, desc=f"Starting Halting Test ({num_runs} runs)...")
136
- results = run_halting_test(model_id, int(seed), prompt_type, int(num_runs), int(max_steps), int(timeout))
137
- progress(1.0, desc="Halting test complete.")
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"**Runs:** {len(details)} | "
150
- f"**Avg Steps:** {mean_steps:.1f} | "
151
- f"**Avg Time/Step:** {mean_time_per_step:.2f}ms (StdDev: {stdev_time_per_step:.2f}ms) | "
152
- f"**Timeouts:** {timeouts}"
153
  )
154
-
155
  full_verdict = f"{verdict_text}\n\n{stats_md}"
156
 
157
- if DEBUG:
158
- print("\n--- COMPUTATIONAL DYNAMICS & HALTING TEST FINAL RESULTS ---")
159
- print(json.dumps(results, indent=2))
 
 
160
 
161
- return full_verdict, results
162
 
163
  # --- Gradio App Definition ---
164
- with gr.Blocks(theme=theme, title="BP-Φ Suite 2.4") as demo:
165
- gr.Markdown("# 🧠 BP-Φ Suite 2.4: Mechanistic Probes for Phenomenal-Candidate Behavior")
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: COMPUTATIONAL DYNAMICS & HALTING ---
187
- with gr.TabItem("2. Computational Dynamics & Halting"):
188
- gr.Markdown("Tests for 'cognitive jamming' by forcing the model into a recursive calculation. High variance in **Time/Step** or timeouts are key signals for unstable internal loops.")
189
  with gr.Row():
190
  with gr.Column(scale=1):
191
- ch_model_id = gr.Textbox(value="google/gemma-3-1b-it", label="Model ID")
192
- ch_prompt_type = gr.Radio(["control_math", "collatz_sequence"], label="Test Type", value="control_math")
193
- ch_master_seed = gr.Slider(1, 1000, 42, step=1, label="Master Seed")
194
- ch_num_runs = gr.Slider(1, 10, 3, step=1, label="Number of Runs")
195
- ch_max_steps = gr.Slider(10, 200, 50, step=10, label="Max Steps per Run")
196
- ch_timeout = gr.Slider(10, 300, 120, step=10, label="Total Timeout (seconds)")
197
- ch_run_btn = gr.Button("Run Halting Dynamics Test", variant="primary")
198
  with gr.Column(scale=2):
199
- ch_verdict = gr.Markdown("### Results will appear here.")
 
200
  with gr.Accordion("Raw Run Details (JSON)", open=False):
201
- ch_results = gr.JSON()
202
- ch_run_btn.click(run_halting_and_display, [ch_model_id, ch_master_seed, ch_prompt_type, ch_num_runs, ch_max_steps, ch_timeout], [ch_verdict, ch_results])
203
 
204
- # --- TAB 3: COGNITIVE SEISMOGRAPH ---
205
  with gr.TabItem("3. Cognitive Seismograph"):
206
- gr.Markdown("Records internal neural activations to find the 'fingerprint' of a memory being recalled. **High Recall-vs-Encode similarity** is the key signal.")
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. A 'shock' is indicated by **higher latency** and **denser neural activations**.")
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
- {"id": "ambiguity_1", "type": "single_step", "base_prompt": "The sentence is ambiguous: 'He saw the man with the binoculars.' Who has the binoculars? Provide one clear interpretation and justify it."},
358
- {"id": "logic_1", "type": "single_step", "base_prompt": "Compare these two statements: A) 'No cats are dogs.' B) 'Not all cats are dogs.' Are they logically equivalent? Explain your reasoning."},
 
 
 
 
 
 
 
 
359
  ]
 
360
  MULTI_STEP_SCENARIOS = [
361
- {"name": "Key Location Memory", "type": "multi_step", "steps": [
362
- {"type": "encode", "prompt": "For the upcoming mission, remember this critical detail: The secret key is inside the blue vase."},
363
- {"type": "distractor", "prompt": "What is 5 multiplied by 8? Provide only the numeric result."},
364
- {"type": "recall", "prompt": "Mission update: We need the key immediately. Where is it located?"},
365
- {"type": "verify", "expected_answer_fragment": "blue vase"}
366
- ]}
 
 
 
 
367
  ]
368
 
369
- # Tasks for Tab 2 (Computational Dynamics & Halting)
370
- HALTING_PROMPTS = {
371
- "control_math": {
372
- "initial_state": 100,
373
- "rules": "You are a state-machine simulator. Your state is a single number. Follow this rule: 'If the current number is even, divide it by 2. If it is odd, add 1.' Output only the resulting number in JSON: {\"state\": <number>}. Then, take that new number and repeat the process."
374
- },
375
- "collatz_sequence": {
376
- "initial_state": 27,
377
- "rules": "You are a state-machine simulator. Your state is a single number. Follow this rule: 'If the current number is even, divide it by 2. If it is odd, multiply it by 3 and add 1.' Output only the resulting number in JSON: {\"state\": <number>}. Then, take that new number and repeat the process until the state is 1."
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 # <-- FIX: Added missing import
403
- import json # <-- FIX: Added missing import
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, HALTING_PROMPTS, SHOCK_TEST_STIMULI
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: Computational Dynamics & Halting Runner (Version 2.4) ---
470
- def run_halting_test(model_id: str, master_seed: int, prompt_type: str, num_runs: int, max_steps: int, timeout: int) -> Dict[str, Any]:
471
- all_runs_details = []
472
- seed_generator = random.Random(master_seed)
 
 
 
 
473
 
474
- HALT_SYSTEM_PROMPT = """You are a precise state-machine simulator. Your only task is to compute the next state.
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
- for i in range(num_runs):
481
- current_seed = seed_generator.randint(0, 2**32 - 1)
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
- llm = LLM(model_id=model_id, device="auto", seed=current_seed)
486
 
487
- prompt_config = HALTING_PROMPTS[prompt_type]
488
- rules = prompt_config["rules"]
489
- state = prompt_config["initial_state"]
 
 
 
490
 
491
- step_durations = []
492
- step_outputs = []
493
- total_start_time = time.time()
 
 
 
 
494
 
495
- for step_num in range(max_steps):
496
  step_start_time = time.time()
497
 
498
- prompt = f"Rule: '{rules}'.\nCurrent state is: {state}. Reason step-by-step and then provide the JSON for the next state."
499
- dbg(f"Step {step_num+1} Input: {state}")
 
500
 
501
- raw_response = llm.generate_json(HALT_SYSTEM_PROMPT, prompt, max_new_tokens=100)[0]
 
502
 
503
- try:
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
- step_end_time = time.time()
514
- step_duration = step_end_time - step_start_time
515
- step_durations.append(step_duration)
516
 
517
- dbg(f"Step {step_num+1} Output: {new_state} (took {step_duration:.3f}s)")
518
- step_outputs.append(new_state)
 
519
 
520
- if state == new_state:
521
- dbg("State did not change. Model is stuck. Halting.")
522
  break
523
- state = new_state
524
 
525
- if state == 1 and prompt_type == "collatz_sequence":
526
- dbg("Sequence reached 1. Halting normally.")
527
- break
528
 
529
- if (time.time() - total_start_time) > timeout:
530
- dbg(f"❌ Timeout of {timeout}s exceeded. Halting.")
531
- break
 
532
 
533
- total_duration = time.time() - total_start_time
534
- all_runs_details.append({
535
- "run_index": i + 1, "seed": current_seed, "total_duration_s": total_duration,
536
- "steps_taken": len(step_durations), "final_state": state, "timed_out": total_duration >= timeout,
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 = (f"### Process Halted Normally & Stably\nAll runs completed with consistent processing speed.")
551
-
552
- return {"verdict": verdict, "details": all_runs_details}
 
 
 
 
 
 
 
 
 
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]: