neuralworm commited on
Commit
06e9d76
·
verified ·
1 Parent(s): b652405

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -13
app.py CHANGED
@@ -1,3 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import gc
@@ -12,37 +108,58 @@ from cognitive_mapping_probe.utils import dbg, cleanup_memory
12
  theme = gr.themes.Soft(primary_hue="indigo", secondary_hue="blue").set(body_background_fill="#f0f4f9", block_background_fill="white")
13
 
14
  def run_single_analysis_display(*args, progress=gr.Progress(track_tqdm=True)):
15
- """Wrapper für den 'Manual Single Run'-Tab."""
 
 
16
  try:
17
  results = run_seismic_analysis(*args, progress_callback=progress)
18
  stats, deltas = results.get("stats", {}), results.get("state_deltas", [])
19
- df = pd.DataFrame({"Internal Step": range(len(deltas)), "State Change (Delta)": deltas})
20
- stats_md = f"### Statistical Signature\n- **Mean Delta:** {stats.get('mean_delta', 0):.4f}\n- **Std Dev Delta:** {stats.get('std_delta', 0):.4f}\n- **Max Delta:** {stats.get('max_delta', 0):.4f}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  serializable_results = json.dumps(results, indent=2, default=str)
22
- return f"{results.get('verdict', 'Error')}\n\n{stats_md}", df, serializable_results
23
  finally:
24
  cleanup_memory()
25
 
 
26
  def run_auto_suite_display(model_id, num_steps, seed, experiment_name, progress=gr.Progress(track_tqdm=True)):
27
- """Wrapper, der nun auch die Frequenz-Spektrum-Plots anzeigen kann."""
28
  try:
29
  summary_df, plot_df, all_results = run_auto_suite(model_id, int(num_steps), int(seed), experiment_name, progress)
30
 
31
  dataframe_component = gr.DataFrame(label="Comparative Signature (incl. Signal Metrics)", value=summary_df, wrap=True, row_count=(len(summary_df), "dynamic"))
32
 
33
- # Erzeuge den primären Zeitreihen-Plot
34
- plot_params = {
35
  "title": "Comparative Cognitive Dynamics (Time Domain)",
36
  "color_legend_position": "bottom", "show_label": True, "height": 300, "interactive": True
37
  }
38
  if experiment_name == "Mechanistic Probe (Attention Entropies)":
39
- plot_params.update({"x": "Step", "y": "Value", "color": "Metric", "color_legend_title": "Metric"})
40
  else:
41
- plot_params.update({"x": "Step", "y": "Delta", "color": "Experiment", "color_legend_title": "Experiment Runs"})
42
 
43
- time_domain_plot = gr.LinePlot(value=plot_df, **plot_params)
44
 
45
- # Erzeuge den Frequenz-Spektrum-Plot
46
  spectrum_data = []
47
  for label, result in all_results.items():
48
  if "power_spectrum" in result:
@@ -88,14 +205,16 @@ with gr.Blocks(theme=theme, title="Cognitive Seismograph 2.3") as demo:
88
  with gr.Column(scale=2):
89
  gr.Markdown("### Single Run Results")
90
  manual_verdict = gr.Markdown("Analysis results will appear here.")
91
- manual_plot = gr.LinePlot(x="Internal Step", y="State Change (Delta)", title="Internal State Dynamics", show_label=True, height=400)
 
 
92
  with gr.Accordion("Raw JSON Output", open=False):
93
  manual_raw_json = gr.JSON()
94
 
95
  manual_run_btn.click(
96
  fn=run_single_analysis_display,
97
  inputs=[manual_model_id, manual_prompt_type, manual_seed, manual_num_steps, manual_concept, manual_strength],
98
- outputs=[manual_verdict, manual_plot, manual_raw_json]
99
  )
100
 
101
  with gr.TabItem("🚀 Automated Suite"):
 
1
+ import torch
2
+ import numpy as np
3
+ import gc
4
+ from typing import Dict, Any, Optional, List
5
+
6
+ from .llm_iface import get_or_load_model, LLM
7
+ from .resonance_seismograph import run_cogitation_loop, run_silent_cogitation_seismic
8
+ from .concepts import get_concept_vector
9
+ from .introspection import generate_introspective_report
10
+ from .signal_analysis import analyze_cognitive_signal, get_power_spectrum_for_plotting
11
+ from .utils import dbg
12
+
13
+ def run_seismic_analysis(
14
+ model_id: str,
15
+ prompt_type: str,
16
+ seed: int,
17
+ num_steps: int,
18
+ concept_to_inject: str,
19
+ injection_strength: float,
20
+ progress_callback,
21
+ llm_instance: Optional[LLM] = None,
22
+ injection_vector_cache: Optional[torch.Tensor] = None
23
+ ) -> Dict[str, Any]:
24
+ """
25
+ Orchestriert eine einzelne seismische Analyse und integriert nun standardmäßig
26
+ die fortgeschrittene Signal-Analyse.
27
+ """
28
+ local_llm_instance = False
29
+ if llm_instance is None:
30
+ progress_callback(0.0, desc=f"Loading model '{model_id}'...")
31
+ llm = get_or_load_model(model_id, seed)
32
+ local_llm_instance = True
33
+ else:
34
+ llm = llm_instance
35
+ llm.set_all_seeds(seed)
36
+
37
+ injection_vector = None
38
+ if concept_to_inject and concept_to_inject.strip():
39
+ if injection_vector_cache is not None:
40
+ dbg(f"Using cached injection vector for '{concept_to_inject}'.")
41
+ injection_vector = injection_vector_cache
42
+ else:
43
+ progress_callback(0.2, desc=f"Vectorizing '{concept_to_inject}'...")
44
+ injection_vector = get_concept_vector(llm, concept_to_inject.strip())
45
+
46
+ progress_callback(0.3, desc=f"Recording dynamics for '{prompt_type}'...")
47
+
48
+ state_deltas = run_silent_cogitation_seismic(
49
+ llm=llm, prompt_type=prompt_type,
50
+ num_steps=num_steps, temperature=0.1,
51
+ injection_vector=injection_vector, injection_strength=injection_strength
52
+ )
53
+
54
+ progress_callback(0.9, desc="Analyzing...")
55
+
56
+ stats = {}
57
+ results = {}
58
+ verdict = "### ⚠️ Analysis Warning\nNo state changes recorded."
59
+
60
+ if state_deltas:
61
+ deltas_np = np.array(state_deltas)
62
+ stats = {
63
+ "mean_delta": float(np.mean(deltas_np)),
64
+ "std_delta": float(np.std(deltas_np)),
65
+ "max_delta": float(np.max(deltas_np)),
66
+ "min_delta": float(np.min(deltas_np)),
67
+ }
68
+
69
+ # FINALE KORREKTUR: Führe die Signal-Analyse hier standardmäßig durch
70
+ signal_metrics = analyze_cognitive_signal(deltas_np)
71
+ stats.update(signal_metrics)
72
+
73
+ freqs, power = get_power_spectrum_for_plotting(deltas_np)
74
+
75
+ verdict = f"### ✅ Seismic Analysis Complete\nRecorded {len(deltas_np)} steps for '{prompt_type}'."
76
+ if injection_vector is not None:
77
+ verdict += f"\nModulated with **'{concept_to_inject}'** at strength **{injection_strength:.2f}**."
78
+
79
+ results["power_spectrum"] = {"frequencies": freqs.tolist(), "power": power.tolist()}
80
+
81
+ results.update({ "verdict": verdict, "stats": stats, "state_deltas": state_deltas })
82
+
83
+ if local_llm_instance:
84
+ dbg(f"Releasing locally created model instance for '{model_id}'.")
85
+ del llm, injection_vector
86
+ gc.collect()
87
+ if torch.cuda.is_available(): torch.cuda.empty_cache()
88
+
89
+ return results
90
+
91
+ # Die anderen Orchestrator-Funktionen (run_triangulation_probe, run_causal_surgery_probe, run_act_titration_probe)
92
+ # bleiben unverändert, da sie ihre eigene, spezifische Analyse-Logik enthalten.```
93
+ [File Ends] `cognitive_mapping_probe/orchestrator_seismograph.py`
94
+
95
+ [File Begins] `app.py`
96
+ ```python
97
  import gradio as gr
98
  import pandas as pd
99
  import gc
 
108
  theme = gr.themes.Soft(primary_hue="indigo", secondary_hue="blue").set(body_background_fill="#f0f4f9", block_background_fill="white")
109
 
110
  def run_single_analysis_display(*args, progress=gr.Progress(track_tqdm=True)):
111
+ """
112
+ Wrapper für den 'Manual Single Run'-Tab, jetzt mit Frequenz-Analyse.
113
+ """
114
  try:
115
  results = run_seismic_analysis(*args, progress_callback=progress)
116
  stats, deltas = results.get("stats", {}), results.get("state_deltas", [])
117
+
118
+ # Zeitreihen-Plot
119
+ df_time = pd.DataFrame({"Internal Step": range(len(deltas)), "State Change (Delta)": deltas})
120
+
121
+ # Frequenz-Plot
122
+ spectrum_data = []
123
+ if "power_spectrum" in results:
124
+ spectrum = results["power_spectrum"]
125
+ for freq, power in zip(spectrum["frequencies"], spectrum["power"]):
126
+ if freq > 0.001:
127
+ spectrum_data.append({"Frequency": freq, "Power": power})
128
+ df_freq = pd.DataFrame(spectrum_data)
129
+
130
+ # Update der Statistik-Anzeige
131
+ stats_md = f"""### Statistical Signature
132
+ - **Mean Delta:** {stats.get('mean_delta', 0):.4f}
133
+ - **Std Dev Delta:** {stats.get('std_delta', 0):.4f}
134
+ - **Dominant Frequency:** {stats.get('dominant_frequency', 0):.4f} Hz
135
+ - **Spectral Entropy:** {stats.get('spectral_entropy', 0):.4f}"""
136
+
137
  serializable_results = json.dumps(results, indent=2, default=str)
138
+ return f"{results.get('verdict', 'Error')}\n\n{stats_md}", df_time, df_freq, serializable_results
139
  finally:
140
  cleanup_memory()
141
 
142
+
143
  def run_auto_suite_display(model_id, num_steps, seed, experiment_name, progress=gr.Progress(track_tqdm=True)):
144
+ """Wrapper für den 'Automated Suite'-Tab."""
145
  try:
146
  summary_df, plot_df, all_results = run_auto_suite(model_id, int(num_steps), int(seed), experiment_name, progress)
147
 
148
  dataframe_component = gr.DataFrame(label="Comparative Signature (incl. Signal Metrics)", value=summary_df, wrap=True, row_count=(len(summary_df), "dynamic"))
149
 
150
+ # Zeitreihen-Plot
151
+ plot_params_time = {
152
  "title": "Comparative Cognitive Dynamics (Time Domain)",
153
  "color_legend_position": "bottom", "show_label": True, "height": 300, "interactive": True
154
  }
155
  if experiment_name == "Mechanistic Probe (Attention Entropies)":
156
+ plot_params_time.update({"x": "Step", "y": "Value", "color": "Metric", "color_legend_title": "Metric"})
157
  else:
158
+ plot_params_time.update({"x": "Step", "y": "Delta", "color": "Experiment", "color_legend_title": "Experiment Runs"})
159
 
160
+ time_domain_plot = gr.LinePlot(value=plot_df, **plot_params_time)
161
 
162
+ # Frequenz-Spektrum-Plot
163
  spectrum_data = []
164
  for label, result in all_results.items():
165
  if "power_spectrum" in result:
 
205
  with gr.Column(scale=2):
206
  gr.Markdown("### Single Run Results")
207
  manual_verdict = gr.Markdown("Analysis results will appear here.")
208
+ with gr.Row():
209
+ manual_time_plot = gr.LinePlot(x="Internal Step", y="State Change (Delta)", title="Time Domain")
210
+ manual_freq_plot = gr.LinePlot(x="Frequency", y="Power", title="Frequency Domain")
211
  with gr.Accordion("Raw JSON Output", open=False):
212
  manual_raw_json = gr.JSON()
213
 
214
  manual_run_btn.click(
215
  fn=run_single_analysis_display,
216
  inputs=[manual_model_id, manual_prompt_type, manual_seed, manual_num_steps, manual_concept, manual_strength],
217
+ outputs=[manual_verdict, manual_time_plot, manual_freq_plot, manual_raw_json]
218
  )
219
 
220
  with gr.TabItem("🚀 Automated Suite"):