RFTSystems commited on
Commit
cfcbbdd
·
verified ·
1 Parent(s): f0679ed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +337 -0
app.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import time
3
+ import torch
4
+ import matplotlib.pyplot as plt
5
+ import tempfile
6
+ import hashlib
7
+ import json
8
+ import gradio as gr
9
+
10
+ # -----------------------------
11
+ # Part A: RFT Simulation Kernel
12
+ # -----------------------------
13
+ def fused_mom_update_cpu(m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
14
+ dt, eps, sigma_const, theta_global, k_shred_global,
15
+ event_counts_t=None, event_buffer_t=None):
16
+ m_root_t = m_root_t.to(torch.float32)
17
+ A_t = A_t.to(torch.float32)
18
+ Q_t = Q_t.to(torch.float32)
19
+ alpha_t = alpha_t.to(torch.float32)
20
+ gamma_t = gamma_t.to(torch.float32)
21
+ omega_t = omega_t.to(torch.float32)
22
+
23
+ alpha_exp = alpha_t.unsqueeze(0)
24
+ gamma_exp = gamma_t.unsqueeze(0)
25
+ omega_exp = omega_t.unsqueeze(0)
26
+ m_root_exp = m_root_t.unsqueeze(1)
27
+
28
+ A_dot = alpha_exp * m_root_exp - gamma_exp * A_t + sigma_const * Q_t
29
+ f_drive = sigma_const * m_root_exp * omega_exp * A_t
30
+ Q_dot = f_drive - Q_t
31
+
32
+ A_t.add_(dt * A_dot)
33
+ Q_t.add_(dt * Q_dot)
34
+
35
+ Xi = (omega_exp * A_t).sum(dim=1)
36
+ Xi_norm = Xi / (m_root_t + eps)
37
+ shred_mask = Xi_norm >= theta_global
38
+
39
+ if torch.any(shred_mask):
40
+ eta_values = torch.zeros_like(Xi_norm)
41
+ eta_calc = 1.0 - torch.exp(-k_shred_global * (Xi_norm[shred_mask] - theta_global))
42
+ eta_values[shred_mask] = torch.clamp(eta_calc, 0.0, 1.0)
43
+
44
+ diss = 0.01 * m_root_t * eta_values
45
+ m_post = (1.0 - eta_values) * m_root_t - diss
46
+ m_post = torch.clamp(m_post, min=0.0)
47
+
48
+ m_root_t[shred_mask] = m_post[shred_mask]
49
+
50
+ shred_count = int(torch.sum(shred_mask).item())
51
+ if event_counts_t is not None:
52
+ if isinstance(event_counts_t, torch.Tensor):
53
+ if event_counts_t.dtype not in (torch.int64, torch.int32):
54
+ event_counts_t = event_counts_t.to(torch.int64)
55
+ event_counts_t.add_(shred_count)
56
+ else:
57
+ event_counts_t += shred_count
58
+
59
+ return m_root_t, A_t, Q_t, event_counts_t
60
+
61
+ class MOMKernel:
62
+ def __init__(self):
63
+ self.kernel = fused_mom_update_cpu
64
+ self.device = torch.device('cpu')
65
+
66
+ def __call__(self, m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
67
+ dt, eps, sigma_const, theta_global, k_shred_global,
68
+ event_counts_t=None, event_buffer_t=None):
69
+ return self.kernel(m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
70
+ dt, eps, sigma_const, theta_global, k_shred_global,
71
+ event_counts_t, event_buffer_t)
72
+
73
+ class MOMSystemLoop:
74
+ def __init__(self, mom_kernel, m_root_initial, A_modes_initial, Q_drive_initial,
75
+ alpha, gamma, omega, dt=0.02, eps=1e-6, sigma=0.75,
76
+ theta=2.2, k_shred=1.2, event_buffer_size=1024):
77
+ self.mom_kernel = mom_kernel
78
+ self.device = mom_kernel.device
79
+ self.m_root = m_root_initial.to(self.device).clone().to(torch.float32)
80
+ self.A_modes = A_modes_initial.to(self.device).clone().to(torch.float32)
81
+ self.Q_drive = Q_drive_initial.to(self.device).clone().to(torch.float32)
82
+ self.alpha = alpha.to(self.device).to(torch.float32)
83
+ self.gamma = gamma.to(self.device).to(torch.float32)
84
+ self.omega = omega.to(self.device).to(torch.float32)
85
+ self.dt = dt; self.eps = eps; self.sigma = sigma
86
+ self.theta = theta; self.k_shred = k_shred
87
+ self.event_counts = torch.zeros((), dtype=torch.int64, device=self.device)
88
+ self.event_buffer = torch.zeros(event_buffer_size, dtype=torch.int64, device=self.device)
89
+ self.m_root_history = []
90
+ self.A_modes_history = []
91
+ self.event_counts_history = []
92
+ self.shred_onset = np.full((self.m_root.shape[0],), -1, dtype=np.int32)
93
+
94
+ def feedback(self, m_root, A_modes, Q_drive):
95
+ decay = 0.995; noise_level = 1e-4
96
+ A_modes_new = A_modes * decay + noise_level * torch.randn_like(A_modes, device=self.device)
97
+ A_modes_new = torch.clamp(A_modes_new, min=0.0)
98
+ m_root_new = m_root * decay + noise_level * torch.randn_like(m_root, device=self.device)
99
+ m_root_new = torch.clamp(m_root_new, min=0.0)
100
+ return m_root_new, A_modes_new, Q_drive
101
+
102
+ def run(self, iterations):
103
+ for i in range(iterations):
104
+ self.event_counts.zero_()
105
+ self.mom_kernel(self.m_root, self.A_modes, self.Q_drive,
106
+ self.alpha, self.gamma, self.omega,
107
+ self.dt, self.eps, self.sigma, self.theta, self.k_shred,
108
+ self.event_counts, self.event_buffer)
109
+ m_np = self.m_root.detach().cpu().numpy()
110
+ collapsed_mask = m_np <= 1e-8
111
+ for idx, collapsed in enumerate(collapsed_mask):
112
+ if collapsed and self.shred_onset[idx] == -1:
113
+ self.shred_onset[idx] = i
114
+ self.m_root, self.A_modes, self.Q_drive = self.feedback(self.m_root, self.A_modes, self.Q_drive)
115
+ self.m_root_history.append(float(self.m_root.mean().item()))
116
+ self.A_modes_history.append(float(self.A_modes.mean().item()))
117
+ self.event_counts_history.append(int(self.event_counts.item()))
118
+
119
+ def run_rft_simulation(Ncells, Nmode, iterations, dt=0.02, eps=1e-6, sigma=0.75,
120
+ theta=2.2, k_shred=1.2, seed=42):
121
+ torch.manual_seed(seed); np.random.seed(seed)
122
+ mom_kernel_instance = MOMKernel()
123
+ device = mom_kernel_instance.device
124
+ alpha = torch.empty(Nmode, device=device).uniform_(0.02, 0.12)
125
+ gamma = torch.empty(Nmode, device=device).uniform_(0.01, 0.06)
126
+ omega = torch.linspace(1.0, 8.0, Nmode, device=device)
127
+ m_root_initial = torch.ones(Ncells, device=device)
128
+ A_modes_initial = torch.rand(Ncells, Nmode, device=device) * 0.01
129
+ Q_drive_initial = torch.zeros(Ncells, Nmode, device=device)
130
+ mom_system = MOMSystemLoop(mom_kernel_instance, m_root_initial, A_modes_initial, Q_drive_initial,
131
+ alpha, gamma, omega, dt=dt, eps=eps, sigma=sigma,
132
+ theta=theta, k_shred=k_shred)
133
+ start_time = time.time()
134
+ mom_system.run(iterations)
135
+ elapsed_time = max(time.time() - start_time, 1e-9)
136
+ ops_per_cell_per_iter = 12 * Nmode + 13
137
+ flops_per_iteration = float(Ncells) * float(ops_per_cell_per_iter)
138
+ total_flops = flops_per_iteration * float(iterations)
139
+ gflops = total_flops / (elapsed_time * 1e9)
140
+ return {
141
+ 'final_m_root': mom_system.m_root.cpu().numpy(),
142
+ 'final_A_modes': mom_system.A_modes.cpu().numpy(),
143
+ 'final_Q_drive': mom_system.Q_drive.cpu().numpy(),
144
+ 'm_root_history': np.array(mom_system.m_root_history),
145
+ 'A_modes_history': np.array(mom_system.A_modes_history),
146
+ 'event_counts_history': np.array(mom_system.event_counts_history),
147
+ 'shred_onset': mom_system.shred_onset,
148
+ 'elapsed_time_seconds': float(elapsed_time),
149
+ 'gflops': float(gflops),
150
+ }
151
+
152
+ def rft_simulation_interface(Ncells, Nmode, iterations, dt, eps, sigma, theta, k_shred):
153
+ try:
154
+ results = run_rft_simulation(Ncells, Nmode, iterations, dt, eps, sigma, theta, k_shred)
155
+ fig = plt.figure(figsize=(10, 14))
156
+ ax1 = fig.add_subplot(4, 1, 1)
157
+ ax1.plot(results['m_root_history'], label='Mean m_root')
158
+ ax1.set_title('Mean m_root Over Iterations'); ax1.set_xlabel('Iteration'); ax1.set_ylabel('Mean m_root')
159
+ ax1.grid(True); ax1.legend()
160
+ ax2 = fig.add_subplot(4, 1, 2)
161
+ ax2.plot(results['A_modes_history'], label='Mean A_modes', color='orange')
162
+ ax2.set_title('Mean A_modes Over Iterations')
163
+ ax2.set_xlabel('Iteration'); ax2.set_ylabel('Mean A_modes')
164
+ ax2.grid(True); ax2.legend()
165
+
166
+ # Plot 3: Cumulative Shredding Events
167
+ ax3 = fig.add_subplot(4, 1, 3)
168
+ cumulative_events = np.cumsum(results['event_counts_history'])
169
+ ax3.plot(cumulative_events, label='Cumulative Shredding Events', color='red')
170
+ ax3.set_title('Cumulative Shredding Events')
171
+ ax3.set_xlabel('Iteration'); ax3.set_ylabel('Cumulative Events')
172
+ ax3.grid(True); ax3.legend()
173
+
174
+ # Plot 4: Raster of shredding onset per cell
175
+ ax4 = fig.add_subplot(4, 1, 4)
176
+ onset = results['shred_onset']
177
+ for idx, val in enumerate(onset):
178
+ if val >= 0:
179
+ ax4.vlines(val, idx, idx + 1, color='black', linewidth=0.8)
180
+ ax4.set_title('Shredding Onset per Cell')
181
+ ax4.set_xlabel('Iteration'); ax4.set_ylabel('Cell Index')
182
+ ax4.grid(True)
183
+
184
+ plt.tight_layout()
185
+ _, plot_path = tempfile.mkstemp(suffix=".png")
186
+ plt.savefig(plot_path)
187
+ plt.close(fig)
188
+
189
+ summary_output = (
190
+ f"Simulation completed in {results['elapsed_time_seconds']:.2f} seconds.\n\n"
191
+ f"Estimated GFLOPS: {results['gflops']:.2f}\n"
192
+ f"Final Mean m_root: {np.mean(results['final_m_root']):.6f}\n"
193
+ f"Final Mean A_modes: {np.mean(results['final_A_modes']):.6f}\n"
194
+ f"Total Events (last iteration): {results['event_counts_history'][-1] if len(results['event_counts_history']) > 0 else 0}\n\n"
195
+ f"-- Historical Data (first 5 values) --\n"
196
+ f"Mean m_root history: {results['m_root_history'][:5].tolist()}\n"
197
+ f"Mean A_modes history: {results['A_modes_history'][:5].tolist()}\n"
198
+ f"Event counts history: {results['event_counts_history'][:5].tolist()}"
199
+ )
200
+ except Exception as e:
201
+ summary_output = f"Error during RFT simulation: {e}"
202
+ plot_path = None
203
+
204
+ return summary_output, plot_path
205
+
206
+ # -----------------------------
207
+ # Part B: Entanglement/IPURL Simulation
208
+ # -----------------------------
209
+ class Agent:
210
+ def __init__(self, agent_id, alpha, beta, energy_init, energy_threshold):
211
+ self.agent_id = agent_id
212
+ self.alpha = alpha
213
+ self.beta = beta
214
+ self.energy = energy_init
215
+ self.energy_threshold = energy_threshold
216
+ self.phi = 0.0
217
+ self.override_log = []
218
+
219
+ def intrinsic_update(self, dt):
220
+ theta = 1 if self.energy > self.energy_threshold else 0
221
+ dphi = (-self.alpha * self.phi + self.beta * theta) * dt
222
+ self.phi += dphi
223
+ self.energy -= abs(self.phi) * dt * 0.1
224
+ self.energy = max(self.energy, 0)
225
+ self.log_override()
226
+
227
+ def entanglement_update(self, influence, dt):
228
+ self.phi += influence * dt
229
+ self.energy -= abs(influence) * dt * 0.05
230
+ self.energy = max(self.energy, 0)
231
+ self.log_override()
232
+
233
+ def log_override(self):
234
+ self.override_log.append({
235
+ 'phi': self.phi,
236
+ 'energy': self.energy,
237
+ 'override': self.phi > 0,
238
+ })
239
+
240
+ def hash_override_log(agent):
241
+ serialized = json.dumps(agent.override_log, sort_keys=True, separators=(',', ':')).encode('utf-8')
242
+ return hashlib.sha512(serialized).hexdigest()
243
+
244
+ def simulate(agents, coupling_matrix, dt=0.01, steps=1000):
245
+ n = len(agents)
246
+ for step in range(steps):
247
+ phis = np.array([agent.phi for agent in agents])
248
+ for agent in agents:
249
+ agent.intrinsic_update(dt)
250
+ for i, agent in enumerate(agents):
251
+ influence = sum(coupling_matrix[i, j] * phis[j] for j in range(n) if j != i)
252
+ agent.entanglement_update(influence, dt)
253
+
254
+ def run_entanglement_simulation(alpha_vals, beta_vals, thresholds, steps=1000, dt=0.01):
255
+ agents = [
256
+ Agent('reflex', alpha_vals[0], beta_vals[0], energy_init=100, energy_threshold=thresholds[0]),
257
+ Agent('instinct', alpha_vals[1], beta_vals[1], energy_init=100, energy_threshold=thresholds[1]),
258
+ Agent('conscious', alpha_vals[2], beta_vals[2], energy_init=100, energy_threshold=thresholds[2]),
259
+ Agent('meta', alpha_vals[3], beta_vals[3], energy_init=100, energy_threshold=thresholds[3]),
260
+ ]
261
+ coupling_matrix = np.array([
262
+ [0.0, 0.1, 0.2, 0.3],
263
+ [0.1, 0.0, 0.4, 0.5],
264
+ [0.2, 0.4, 0.0, 0.6],
265
+ [0.3, 0.5, 0.6, 0.0],
266
+ ])
267
+ simulate(agents, coupling_matrix, dt=dt, steps=steps)
268
+ ipurls = [f"rft-ipurl:v1:{agent.agent_id}:{hash_override_log(agent)}" for agent in agents]
269
+ return "\n".join(ipurls)
270
+
271
+ # -----------------------------
272
+ # Gradio Interface
273
+ # -----------------------------
274
+ with gr.Blocks(title="Codex Simulation Suite") as iface:
275
+ with gr.Tab("RFT Simulation"):
276
+ gr.Markdown("""
277
+ ### Rendered Frame Theory (RFT) Simulation
278
+ RFT models collapse dynamics in adaptive systems. Each cell evolves through coupled updates,
279
+ feedback loops, and shredding events when stress crosses a threshold. The plots show mean values,
280
+ cumulative events, and shredding onset per cell.
281
+ """)
282
+ with gr.Row():
283
+ with gr.Column():
284
+ Ncells_slider = gr.Slider(16, 512, step=16, value=64, label="⚡ Number of Cells")
285
+ Nmode_slider = gr.Slider(2, 32, step=2, value=8, label="🔮 Number of Modes")
286
+ iterations_slider = gr.Slider(10, 200, step=10, value=50, label="♾ Iterations")
287
+ dt_slider = gr.Slider(0.001, 0.1, step=0.001, value=0.02, label="⌛ Time Step")
288
+ eps_slider = gr.Slider(1e-7, 1e-4, step=1e-7, value=1e-6, label="🧿 Epsilon")
289
+ sigma_slider = gr.Slider(0.1, 1.0, step=0.05, value=0.75, label="🌌 Sigma")
290
+ theta_slider = gr.Slider(0.1, 5.0, step=0.1, value=2.2, label="🔭 Theta")
291
+ k_shred_slider = gr.Slider(0.1, 5.0, step=0.1, value=1.2, label="🌀 K_shred")
292
+ run_button = gr.Button("Run RFT Simulation")
293
+ with gr.Column():
294
+ summary_output_textbox = gr.Textbox(label="Simulation Summary", lines=15)
295
+ plot_output_image = gr.Image(label="Simulation Plots", type="filepath")
296
+ run_button.click(
297
+ fn=rft_simulation_interface,
298
+ inputs=[Ncells_slider, Nmode_slider, iterations_slider, dt_slider, eps_slider,
299
+ sigma_slider, theta_slider, k_shred_slider],
300
+ outputs=[summary_output_textbox, plot_output_image]
301
+ )
302
+
303
+ with gr.Tab("Entanglement/IPURL Simulation"):
304
+ gr.Markdown("""
305
+ ### Override Log & Entanglement Simulation
306
+ This prototype models symbolic agents (reflex, instinct, conscious, meta) with intrinsic dynamics
307
+ and entanglement influences. Each agent logs override states, which are sealed into reproducible
308
+ IPURL hashes. The output shows cryptographic lineage entries for each agent.
309
+ """)
310
+ alpha_inputs = [gr.Number(value=0.1, label="Alpha Reflex"),
311
+ gr.Number(value=0.1, label="Alpha Instinct"),
312
+ gr.Number(value=0.2, label="Alpha Conscious"),
313
+ gr.Number(value=0.3, label="Alpha Meta")]
314
+ beta_inputs = [gr.Number(value=0.0, label="Beta Reflex"),
315
+ gr.Number(value=0.5, label="Beta Instinct"),
316
+ gr.Number(value=1.0, label="Beta Conscious"),
317
+ gr.Number(value=1.5, label="Beta Meta")]
318
+ thresholds = [gr.Number(value=10, label="Threshold Reflex"),
319
+ gr.Number(value=20, label="Threshold Instinct"),
320
+ gr.Number(value=30, label="Threshold Conscious"),
321
+ gr.Number(value=40, label="Threshold Meta")]
322
+ steps_slider = gr.Slider(minimum=100, maximum=10000, step=100, value=5000, label="♾ Steps")
323
+ run_button2 = gr.Button("Run Entanglement Simulation")
324
+ ipurl_output = gr.Textbox(label="IPURL Entries", lines=10)
325
+
326
+ run_button2.click(
327
+ fn=lambda a1,a2,a3,a4,b1,b2,b3,b4,t1,t2,t3,t4,steps: run_entanglement_simulation(
328
+ [a1,a2,a3,a4],[b1,b2,b3,b4],[t1,t2,t3,t4],steps),
329
+ inputs=alpha_inputs+beta_inputs+thresholds+[steps_slider],
330
+ outputs=ipurl_output
331
+ )
332
+
333
+ # -----------------------------
334
+ # Launch
335
+ # -----------------------------
336
+ if __name__ == "__main__":
337
+ iface.launch()