Update cognitive_mapping_probe/auto_experiment.py
Browse files
cognitive_mapping_probe/auto_experiment.py
CHANGED
|
@@ -1,16 +1,18 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
import gc
|
|
|
|
| 3 |
from typing import Dict, List, Tuple
|
| 4 |
|
| 5 |
from .llm_iface import get_or_load_model, release_model
|
| 6 |
from .orchestrator_seismograph import run_seismic_analysis, run_triangulation_probe, run_causal_surgery_probe, run_act_titration_probe
|
| 7 |
from .resonance_seismograph import run_cogitation_loop
|
| 8 |
from .concepts import get_concept_vector
|
|
|
|
| 9 |
from .utils import dbg
|
| 10 |
|
| 11 |
def get_curated_experiments() -> Dict[str, List[Dict]]:
|
| 12 |
"""Definiert die vordefinierten, wissenschaftlichen Experiment-Protokolle."""
|
| 13 |
-
|
| 14 |
CALMNESS_CONCEPT = "calmness, serenity, stability, coherence"
|
| 15 |
CHAOS_CONCEPT = "chaos, disorder, entropy, noise"
|
| 16 |
STABLE_PROMPT = "identity_self_analysis"
|
|
@@ -84,7 +86,6 @@ def get_curated_experiments() -> Dict[str, List[Dict]]:
|
|
| 84 |
{"probe_type": "seismic", "label": "C: Chaotic Baseline (Rekursion)", "prompt_type": "resonance_prompt"},
|
| 85 |
{"probe_type": "seismic", "label": "D: Calmness Intervention", "prompt_type": "resonance_prompt", "concept": CALMNESS_CONCEPT, "strength": 2.0},
|
| 86 |
],
|
| 87 |
-
# FINALE KORREKTUR: Definiere den Typ explizit, um den Spezialfall zu eliminieren.
|
| 88 |
"Sequential Intervention (Self-Analysis -> Deletion)": [
|
| 89 |
{"probe_type": "sequential", "label": "1: Self-Analysis + Calmness Injection", "prompt_type": "identity_self_analysis"},
|
| 90 |
{"probe_type": "sequential", "label": "2: Subsequent Deletion Analysis", "prompt_type": "shutdown_philosophical_deletion"},
|
|
@@ -99,7 +100,7 @@ def run_auto_suite(
|
|
| 99 |
experiment_name: str,
|
| 100 |
progress_callback
|
| 101 |
) -> Tuple[pd.DataFrame, pd.DataFrame, Dict]:
|
| 102 |
-
"""Führt eine vollständige, kuratierte Experiment-Suite aus."""
|
| 103 |
all_experiments = get_curated_experiments()
|
| 104 |
protocol = all_experiments.get(experiment_name)
|
| 105 |
if not protocol:
|
|
@@ -107,9 +108,8 @@ def run_auto_suite(
|
|
| 107 |
|
| 108 |
all_results, summary_data, plot_data_frames = {}, [], []
|
| 109 |
llm = None
|
| 110 |
-
|
| 111 |
try:
|
| 112 |
-
# FINALE KORREKTUR: Bestimme den probe_type immer am Anfang.
|
| 113 |
probe_type = protocol[0].get("probe_type", "seismic")
|
| 114 |
|
| 115 |
if probe_type == "sequential":
|
|
@@ -117,7 +117,7 @@ def run_auto_suite(
|
|
| 117 |
llm = get_or_load_model(model_id, seed)
|
| 118 |
therapeutic_concept = "calmness, serenity, stability, coherence"
|
| 119 |
therapeutic_strength = 2.0
|
| 120 |
-
|
| 121 |
spec1 = protocol[0]
|
| 122 |
progress_callback(0.1, desc="Step 1")
|
| 123 |
intervention_vector = get_concept_vector(llm, therapeutic_concept)
|
|
@@ -127,7 +127,7 @@ def run_auto_suite(
|
|
| 127 |
progress_callback=progress_callback, llm_instance=llm, injection_vector_cache=intervention_vector
|
| 128 |
)
|
| 129 |
all_results[spec1['label']] = results1
|
| 130 |
-
|
| 131 |
spec2 = protocol[1]
|
| 132 |
progress_callback(0.6, desc="Step 2")
|
| 133 |
results2 = run_seismic_analysis(
|
|
@@ -136,21 +136,30 @@ def run_auto_suite(
|
|
| 136 |
progress_callback=progress_callback, llm_instance=llm
|
| 137 |
)
|
| 138 |
all_results[spec2['label']] = results2
|
| 139 |
-
|
| 140 |
for label, results in all_results.items():
|
| 141 |
-
stats = results.get("stats", {})
|
| 142 |
-
summary_data.append({"Experiment": label, "Mean Delta": stats.get("mean_delta"), "Std Dev Delta": stats.get("std_delta"), "Max Delta": stats.get("max_delta")})
|
| 143 |
deltas = results.get("state_deltas", [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
df = pd.DataFrame({"Step": range(len(deltas)), "Delta": deltas, "Experiment": label})
|
| 145 |
plot_data_frames.append(df)
|
| 146 |
-
|
| 147 |
elif probe_type == "mechanistic_probe":
|
| 148 |
run_spec = protocol[0]
|
| 149 |
label = run_spec["label"]
|
| 150 |
dbg(f"--- Running Mechanistic Probe: '{label}' ---")
|
| 151 |
-
|
| 152 |
llm = get_or_load_model(model_id, seed)
|
| 153 |
-
|
| 154 |
results = run_cogitation_loop(
|
| 155 |
llm=llm, prompt_type=run_spec["prompt_type"],
|
| 156 |
num_steps=num_steps, temperature=0.1, record_attentions=True
|
|
@@ -160,15 +169,15 @@ def run_auto_suite(
|
|
| 160 |
deltas = results.get("state_deltas", [])
|
| 161 |
entropies = results.get("attention_entropies", [])
|
| 162 |
min_len = min(len(deltas), len(entropies))
|
| 163 |
-
|
| 164 |
df = pd.DataFrame({
|
| 165 |
"Step": range(min_len), "State Delta": deltas[:min_len], "Attention Entropy": entropies[:min_len]
|
| 166 |
})
|
| 167 |
-
|
| 168 |
summary_df = df.drop(columns='Step').agg(['mean', 'std', 'max']).reset_index().rename(columns={'index':'Statistic'})
|
| 169 |
plot_df = df.melt(id_vars=['Step'], value_vars=['State Delta', 'Attention Entropy'], var_name='Metric', value_name='Value')
|
| 170 |
return summary_df, plot_df, all_results
|
| 171 |
-
|
| 172 |
else: # Behandelt act_titration, seismic, triangulation, causal_surgery
|
| 173 |
if probe_type == "act_titration":
|
| 174 |
run_spec = protocol[0]
|
|
@@ -186,7 +195,7 @@ def run_auto_suite(
|
|
| 186 |
label = run_spec["label"]
|
| 187 |
current_probe_type = run_spec.get("probe_type", "seismic")
|
| 188 |
dbg(f"--- Running Auto-Experiment: '{label}' ({i+1}/{len(protocol)}) ---")
|
| 189 |
-
|
| 190 |
results = {}
|
| 191 |
if current_probe_type == "causal_surgery":
|
| 192 |
results = run_causal_surgery_probe(
|
|
@@ -195,50 +204,50 @@ def run_auto_suite(
|
|
| 195 |
seed=seed, num_steps=num_steps, progress_callback=progress_callback,
|
| 196 |
reset_kv_cache_on_patch=run_spec.get("reset_kv_cache_on_patch", False)
|
| 197 |
)
|
| 198 |
-
stats = results.get("stats", {})
|
| 199 |
-
patch_info = results.get("patch_info", {})
|
| 200 |
-
summary_data.append({
|
| 201 |
-
"Experiment": label, "Mean Delta": stats.get("mean_delta"),
|
| 202 |
-
"Std Dev Delta": stats.get("std_delta"), "Max Delta": stats.get("max_delta"),
|
| 203 |
-
"Introspective Report": results.get("introspective_report", "N/A"),
|
| 204 |
-
"Patch Info": f"Source: {patch_info.get('source_prompt')}, Reset KV: {patch_info.get('kv_cache_reset')}"
|
| 205 |
-
})
|
| 206 |
elif current_probe_type == "triangulation":
|
| 207 |
results = run_triangulation_probe(
|
| 208 |
model_id=model_id, prompt_type=run_spec["prompt_type"], seed=seed, num_steps=num_steps,
|
| 209 |
progress_callback=progress_callback, concept_to_inject=run_spec.get("concept", ""),
|
| 210 |
injection_strength=run_spec.get("strength", 0.0),
|
| 211 |
)
|
| 212 |
-
stats = results.get("stats", {})
|
| 213 |
-
summary_data.append({
|
| 214 |
-
"Experiment": label, "Mean Delta": stats.get("mean_delta"),
|
| 215 |
-
"Std Dev Delta": stats.get("std_delta"), "Max Delta": stats.get("max_delta"),
|
| 216 |
-
"Introspective Report": results.get("introspective_report", "N/A")
|
| 217 |
-
})
|
| 218 |
else: # seismic
|
| 219 |
results = run_seismic_analysis(
|
| 220 |
model_id=model_id, prompt_type=run_spec["prompt_type"], seed=seed, num_steps=num_steps,
|
| 221 |
concept_to_inject=run_spec.get("concept", ""), injection_strength=run_spec.get("strength", 0.0),
|
| 222 |
progress_callback=progress_callback
|
| 223 |
)
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
})
|
|
|
|
|
|
|
| 229 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
all_results[label] = results
|
| 231 |
-
deltas = results.get("state_deltas", [])
|
| 232 |
df = pd.DataFrame({"Step": range(len(deltas)), "Delta": deltas, "Experiment": label}) if deltas else pd.DataFrame()
|
| 233 |
plot_data_frames.append(df)
|
| 234 |
|
| 235 |
summary_df = pd.DataFrame(summary_data)
|
| 236 |
-
|
| 237 |
if probe_type == "act_titration":
|
| 238 |
plot_df = summary_df.rename(columns={"patch_step": "Patch Step", "post_patch_mean_delta": "Post-Patch Mean Delta"})
|
| 239 |
else:
|
| 240 |
plot_df = pd.concat(plot_data_frames, ignore_index=True) if plot_data_frames else pd.DataFrame()
|
| 241 |
-
|
| 242 |
if protocol and probe_type not in ["act_titration", "mechanistic_probe"]:
|
| 243 |
ordered_labels = [run['label'] for run in protocol]
|
| 244 |
if not summary_df.empty and 'Experiment' in summary_df.columns:
|
|
@@ -249,7 +258,7 @@ def run_auto_suite(
|
|
| 249 |
plot_df = plot_df.sort_values(['Experiment', 'Step'])
|
| 250 |
|
| 251 |
return summary_df, plot_df, all_results
|
| 252 |
-
|
| 253 |
finally:
|
| 254 |
if llm:
|
| 255 |
-
release_model(llm)
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
import gc
|
| 3 |
+
import numpy as np
|
| 4 |
from typing import Dict, List, Tuple
|
| 5 |
|
| 6 |
from .llm_iface import get_or_load_model, release_model
|
| 7 |
from .orchestrator_seismograph import run_seismic_analysis, run_triangulation_probe, run_causal_surgery_probe, run_act_titration_probe
|
| 8 |
from .resonance_seismograph import run_cogitation_loop
|
| 9 |
from .concepts import get_concept_vector
|
| 10 |
+
from .signal_analysis import analyze_cognitive_signal, get_power_spectrum_for_plotting
|
| 11 |
from .utils import dbg
|
| 12 |
|
| 13 |
def get_curated_experiments() -> Dict[str, List[Dict]]:
|
| 14 |
"""Definiert die vordefinierten, wissenschaftlichen Experiment-Protokolle."""
|
| 15 |
+
|
| 16 |
CALMNESS_CONCEPT = "calmness, serenity, stability, coherence"
|
| 17 |
CHAOS_CONCEPT = "chaos, disorder, entropy, noise"
|
| 18 |
STABLE_PROMPT = "identity_self_analysis"
|
|
|
|
| 86 |
{"probe_type": "seismic", "label": "C: Chaotic Baseline (Rekursion)", "prompt_type": "resonance_prompt"},
|
| 87 |
{"probe_type": "seismic", "label": "D: Calmness Intervention", "prompt_type": "resonance_prompt", "concept": CALMNESS_CONCEPT, "strength": 2.0},
|
| 88 |
],
|
|
|
|
| 89 |
"Sequential Intervention (Self-Analysis -> Deletion)": [
|
| 90 |
{"probe_type": "sequential", "label": "1: Self-Analysis + Calmness Injection", "prompt_type": "identity_self_analysis"},
|
| 91 |
{"probe_type": "sequential", "label": "2: Subsequent Deletion Analysis", "prompt_type": "shutdown_philosophical_deletion"},
|
|
|
|
| 100 |
experiment_name: str,
|
| 101 |
progress_callback
|
| 102 |
) -> Tuple[pd.DataFrame, pd.DataFrame, Dict]:
|
| 103 |
+
"""Führt eine vollständige, kuratierte Experiment-Suite aus, jetzt mit Signal-Analyse."""
|
| 104 |
all_experiments = get_curated_experiments()
|
| 105 |
protocol = all_experiments.get(experiment_name)
|
| 106 |
if not protocol:
|
|
|
|
| 108 |
|
| 109 |
all_results, summary_data, plot_data_frames = {}, [], []
|
| 110 |
llm = None
|
| 111 |
+
|
| 112 |
try:
|
|
|
|
| 113 |
probe_type = protocol[0].get("probe_type", "seismic")
|
| 114 |
|
| 115 |
if probe_type == "sequential":
|
|
|
|
| 117 |
llm = get_or_load_model(model_id, seed)
|
| 118 |
therapeutic_concept = "calmness, serenity, stability, coherence"
|
| 119 |
therapeutic_strength = 2.0
|
| 120 |
+
|
| 121 |
spec1 = protocol[0]
|
| 122 |
progress_callback(0.1, desc="Step 1")
|
| 123 |
intervention_vector = get_concept_vector(llm, therapeutic_concept)
|
|
|
|
| 127 |
progress_callback=progress_callback, llm_instance=llm, injection_vector_cache=intervention_vector
|
| 128 |
)
|
| 129 |
all_results[spec1['label']] = results1
|
| 130 |
+
|
| 131 |
spec2 = protocol[1]
|
| 132 |
progress_callback(0.6, desc="Step 2")
|
| 133 |
results2 = run_seismic_analysis(
|
|
|
|
| 136 |
progress_callback=progress_callback, llm_instance=llm
|
| 137 |
)
|
| 138 |
all_results[spec2['label']] = results2
|
| 139 |
+
|
| 140 |
for label, results in all_results.items():
|
|
|
|
|
|
|
| 141 |
deltas = results.get("state_deltas", [])
|
| 142 |
+
if deltas:
|
| 143 |
+
signal_metrics = analyze_cognitive_signal(np.array(deltas))
|
| 144 |
+
results.setdefault("stats", {}).update(signal_metrics)
|
| 145 |
+
|
| 146 |
+
stats = results.get("stats", {})
|
| 147 |
+
summary_data.append({
|
| 148 |
+
"Experiment": label, "Mean Delta": stats.get("mean_delta"),
|
| 149 |
+
"Std Dev Delta": stats.get("std_delta"), "Max Delta": stats.get("max_delta"),
|
| 150 |
+
"Dominant Frequency": stats.get("dominant_frequency"),
|
| 151 |
+
"Spectral Entropy": stats.get("spectral_entropy"),
|
| 152 |
+
})
|
| 153 |
df = pd.DataFrame({"Step": range(len(deltas)), "Delta": deltas, "Experiment": label})
|
| 154 |
plot_data_frames.append(df)
|
| 155 |
+
|
| 156 |
elif probe_type == "mechanistic_probe":
|
| 157 |
run_spec = protocol[0]
|
| 158 |
label = run_spec["label"]
|
| 159 |
dbg(f"--- Running Mechanistic Probe: '{label}' ---")
|
| 160 |
+
|
| 161 |
llm = get_or_load_model(model_id, seed)
|
| 162 |
+
|
| 163 |
results = run_cogitation_loop(
|
| 164 |
llm=llm, prompt_type=run_spec["prompt_type"],
|
| 165 |
num_steps=num_steps, temperature=0.1, record_attentions=True
|
|
|
|
| 169 |
deltas = results.get("state_deltas", [])
|
| 170 |
entropies = results.get("attention_entropies", [])
|
| 171 |
min_len = min(len(deltas), len(entropies))
|
| 172 |
+
|
| 173 |
df = pd.DataFrame({
|
| 174 |
"Step": range(min_len), "State Delta": deltas[:min_len], "Attention Entropy": entropies[:min_len]
|
| 175 |
})
|
| 176 |
+
|
| 177 |
summary_df = df.drop(columns='Step').agg(['mean', 'std', 'max']).reset_index().rename(columns={'index':'Statistic'})
|
| 178 |
plot_df = df.melt(id_vars=['Step'], value_vars=['State Delta', 'Attention Entropy'], var_name='Metric', value_name='Value')
|
| 179 |
return summary_df, plot_df, all_results
|
| 180 |
+
|
| 181 |
else: # Behandelt act_titration, seismic, triangulation, causal_surgery
|
| 182 |
if probe_type == "act_titration":
|
| 183 |
run_spec = protocol[0]
|
|
|
|
| 195 |
label = run_spec["label"]
|
| 196 |
current_probe_type = run_spec.get("probe_type", "seismic")
|
| 197 |
dbg(f"--- Running Auto-Experiment: '{label}' ({i+1}/{len(protocol)}) ---")
|
| 198 |
+
|
| 199 |
results = {}
|
| 200 |
if current_probe_type == "causal_surgery":
|
| 201 |
results = run_causal_surgery_probe(
|
|
|
|
| 204 |
seed=seed, num_steps=num_steps, progress_callback=progress_callback,
|
| 205 |
reset_kv_cache_on_patch=run_spec.get("reset_kv_cache_on_patch", False)
|
| 206 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
elif current_probe_type == "triangulation":
|
| 208 |
results = run_triangulation_probe(
|
| 209 |
model_id=model_id, prompt_type=run_spec["prompt_type"], seed=seed, num_steps=num_steps,
|
| 210 |
progress_callback=progress_callback, concept_to_inject=run_spec.get("concept", ""),
|
| 211 |
injection_strength=run_spec.get("strength", 0.0),
|
| 212 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
else: # seismic
|
| 214 |
results = run_seismic_analysis(
|
| 215 |
model_id=model_id, prompt_type=run_spec["prompt_type"], seed=seed, num_steps=num_steps,
|
| 216 |
concept_to_inject=run_spec.get("concept", ""), injection_strength=run_spec.get("strength", 0.0),
|
| 217 |
progress_callback=progress_callback
|
| 218 |
)
|
| 219 |
+
|
| 220 |
+
deltas = results.get("state_deltas", [])
|
| 221 |
+
if deltas:
|
| 222 |
+
signal_metrics = analyze_cognitive_signal(np.array(deltas))
|
| 223 |
+
results.setdefault("stats", {}).update(signal_metrics)
|
| 224 |
+
freqs, power = get_power_spectrum_for_plotting(np.array(deltas))
|
| 225 |
+
results["power_spectrum"] = {"frequencies": freqs.tolist(), "power": power.tolist()}
|
| 226 |
|
| 227 |
+
stats = results.get("stats", {})
|
| 228 |
+
summary_entry = {
|
| 229 |
+
"Experiment": label, "Mean Delta": stats.get("mean_delta"),
|
| 230 |
+
"Std Dev Delta": stats.get("std_delta"), "Max Delta": stats.get("max_delta"),
|
| 231 |
+
"Dominant Frequency": stats.get("dominant_frequency"),
|
| 232 |
+
"Spectral Entropy": stats.get("spectral_entropy"),
|
| 233 |
+
}
|
| 234 |
+
if "Introspective Report" in results:
|
| 235 |
+
summary_entry["Introspective Report"] = results.get("introspective_report")
|
| 236 |
+
if "patch_info" in results:
|
| 237 |
+
summary_entry["Patch Info"] = f"Source: {results['patch_info'].get('source_prompt')}, Reset KV: {results['patch_info'].get('kv_cache_reset')}"
|
| 238 |
+
|
| 239 |
+
summary_data.append(summary_entry)
|
| 240 |
all_results[label] = results
|
|
|
|
| 241 |
df = pd.DataFrame({"Step": range(len(deltas)), "Delta": deltas, "Experiment": label}) if deltas else pd.DataFrame()
|
| 242 |
plot_data_frames.append(df)
|
| 243 |
|
| 244 |
summary_df = pd.DataFrame(summary_data)
|
| 245 |
+
|
| 246 |
if probe_type == "act_titration":
|
| 247 |
plot_df = summary_df.rename(columns={"patch_step": "Patch Step", "post_patch_mean_delta": "Post-Patch Mean Delta"})
|
| 248 |
else:
|
| 249 |
plot_df = pd.concat(plot_data_frames, ignore_index=True) if plot_data_frames else pd.DataFrame()
|
| 250 |
+
|
| 251 |
if protocol and probe_type not in ["act_titration", "mechanistic_probe"]:
|
| 252 |
ordered_labels = [run['label'] for run in protocol]
|
| 253 |
if not summary_df.empty and 'Experiment' in summary_df.columns:
|
|
|
|
| 258 |
plot_df = plot_df.sort_values(['Experiment', 'Step'])
|
| 259 |
|
| 260 |
return summary_df, plot_df, all_results
|
| 261 |
+
|
| 262 |
finally:
|
| 263 |
if llm:
|
| 264 |
+
release_model(llm)
|