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

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -249
app.py DELETED
@@ -1,249 +0,0 @@
1
- import gradio as gr
2
- import numpy as np
3
- import time
4
- import torch
5
- import matplotlib.pyplot as plt
6
- import tempfile
7
-
8
- # CPU kernel
9
- def fused_mom_update_cpu(m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
10
- dt, eps, sigma_const, theta_global, k_shred_global,
11
- event_counts_t=None, event_buffer_t=None):
12
- m_root_t = m_root_t.to(torch.float32)
13
- A_t = A_t.to(torch.float32)
14
- Q_t = Q_t.to(torch.float32)
15
- alpha_t = alpha_t.to(torch.float32)
16
- gamma_t = gamma_t.to(torch.float32)
17
- omega_t = omega_t.to(torch.float32)
18
-
19
- alpha_exp = alpha_t.unsqueeze(0)
20
- gamma_exp = gamma_t.unsqueeze(0)
21
- omega_exp = omega_t.unsqueeze(0)
22
- m_root_exp = m_root_t.unsqueeze(1)
23
-
24
- A_dot = alpha_exp * m_root_exp - gamma_exp * A_t + sigma_const * Q_t
25
- f_drive = sigma_const * m_root_exp * omega_exp * A_t
26
- Q_dot = f_drive - Q_t
27
-
28
- A_t.add_(dt * A_dot)
29
- Q_t.add_(dt * Q_dot)
30
-
31
- Xi = (omega_exp * A_t).sum(dim=1)
32
- Xi_norm = Xi / (m_root_t + eps)
33
- shred_mask = Xi_norm >= theta_global
34
-
35
- if torch.any(shred_mask):
36
- eta_values = torch.zeros_like(Xi_norm)
37
- eta_calc = 1.0 - torch.exp(-k_shred_global * (Xi_norm[shred_mask] - theta_global))
38
- eta_values[shred_mask] = torch.clamp(eta_calc, 0.0, 1.0)
39
-
40
- diss = 0.01 * m_root_t * eta_values
41
- m_post = (1.0 - eta_values) * m_root_t - diss
42
- m_post = torch.clamp(m_post, min=0.0)
43
-
44
- m_root_t[shred_mask] = m_post[shred_mask]
45
-
46
- shred_count = int(torch.sum(shred_mask).item())
47
- if event_counts_t is not None:
48
- if isinstance(event_counts_t, torch.Tensor):
49
- if event_counts_t.dtype not in (torch.int64, torch.int32):
50
- event_counts_t = event_counts_t.to(torch.int64)
51
- event_counts_t.add_(shred_count)
52
- else:
53
- event_counts_t += shred_count
54
-
55
- return m_root_t, A_t, Q_t, event_counts_t
56
-
57
- class MOMKernel:
58
- def __init__(self):
59
- self.kernel = fused_mom_update_cpu
60
- self.device = torch.device('cpu')
61
-
62
- def __call__(self, m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
63
- dt, eps, sigma_const, theta_global, k_shred_global,
64
- event_counts_t=None, event_buffer_t=None):
65
- return self.kernel(m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
66
- dt, eps, sigma_const, theta_global, k_shred_global,
67
- event_counts_t, event_buffer_t)
68
-
69
- class MOMSystemLoop:
70
- def __init__(self, mom_kernel, m_root_initial, A_modes_initial, Q_drive_initial,
71
- alpha, gamma, omega, dt=0.02, eps=1e-6, sigma=0.75,
72
- theta=2.2, k_shred=1.2, event_buffer_size=1024):
73
- self.mom_kernel = mom_kernel
74
- self.device = mom_kernel.device
75
- self.m_root = m_root_initial.to(self.device).clone().to(torch.float32)
76
- self.A_modes = A_modes_initial.to(self.device).clone().to(torch.float32)
77
- self.Q_drive = Q_drive_initial.to(self.device).clone().to(torch.float32)
78
- self.alpha = alpha.to(self.device).to(torch.float32)
79
- self.gamma = gamma.to(self.device).to(torch.float32)
80
- self.omega = omega.to(self.device).to(torch.float32)
81
- self.dt = dt; self.eps = eps; self.sigma = sigma
82
- self.theta = theta; self.k_shred = k_shred
83
- self.event_counts = torch.zeros((), dtype=torch.int64, device=self.device)
84
- self.event_buffer = torch.zeros(event_buffer_size, dtype=torch.int64, device=self.device)
85
- self.m_root_history = []
86
- self.A_modes_history = []
87
- self.event_counts_history = []
88
- self.shred_onset = np.full((self.m_root.shape[0],), -1, dtype=np.int32)
89
-
90
- def feedback(self, m_root, A_modes, Q_drive):
91
- decay = 0.995; noise_level = 1e-4
92
- A_modes_new = A_modes * decay + noise_level * torch.randn_like(A_modes, device=self.device)
93
- A_modes_new = torch.clamp(A_modes_new, min=0.0)
94
- m_root_new = m_root * decay + noise_level * torch.randn_like(m_root, device=self.device)
95
- m_root_new = torch.clamp(m_root_new, min=0.0)
96
- return m_root_new, A_modes_new, Q_drive
97
-
98
- def run(self, iterations):
99
- for i in range(iterations):
100
- self.event_counts.zero_()
101
- self.mom_kernel(self.m_root, self.A_modes, self.Q_drive,
102
- self.alpha, self.gamma, self.omega,
103
- self.dt, self.eps, self.sigma, self.theta, self.k_shred,
104
- self.event_counts, self.event_buffer)
105
- m_np = self.m_root.detach().cpu().numpy()
106
- collapsed_mask = m_np <= 1e-8
107
- for idx, collapsed in enumerate(collapsed_mask):
108
- if collapsed and self.shred_onset[idx] == -1:
109
- self.shred_onset[idx] = i
110
- self.m_root, self.A_modes, self.Q_drive = self.feedback(self.m_root, self.A_modes, self.Q_drive)
111
- self.m_root_history.append(float(self.m_root.mean().item()))
112
- self.A_modes_history.append(float(self.A_modes.mean().item()))
113
- self.event_counts_history.append(int(self.event_counts.item()))
114
-
115
- def run_rft_simulation(Ncells, Nmode, iterations, dt=0.02, eps=1e-6, sigma=0.75,
116
- theta=2.2, k_shred=1.2, seed=42):
117
- torch.manual_seed(seed); np.random.seed(seed)
118
- mom_kernel_instance = MOMKernel()
119
- device = mom_kernel_instance.device
120
- alpha = torch.empty(Nmode, device=device).uniform_(0.02, 0.12)
121
- gamma = torch.empty(Nmode, device=device).uniform_(0.01, 0.06)
122
- omega = torch.linspace(1.0, 8.0, Nmode, device=device)
123
- m_root_initial = torch.ones(Ncells, device=device)
124
- A_modes_initial = torch.rand(Ncells, Nmode, device=device) * 0.01
125
- Q_drive_initial = torch.zeros(Ncells, Nmode, device=device)
126
- mom_system = MOMSystemLoop(mom_kernel_instance, m_root_initial, A_modes_initial, Q_drive_initial,
127
- alpha, gamma, omega, dt=dt, eps=eps, sigma=sigma,
128
- theta=theta, k_shred=k_shred)
129
- start_time = time.time()
130
- mom_system.run(iterations)
131
- elapsed_time = max(time.time() - start_time, 1e-9)
132
- ops_per_cell_per_iter = 12 * Nmode + 13
133
- flops_per_iteration = float(Ncells) * float(ops_per_cell_per_iter)
134
- total_flops = flops_per_iteration * float(iterations)
135
- gflops = total_flops / (elapsed_time * 1e9)
136
- return {
137
- 'final_m_root': mom_system.m_root.cpu().numpy(),
138
- 'final_A_modes': mom_system.A_modes.cpu().numpy(),
139
- 'final_Q_drive': mom_system.Q_drive.cpu().numpy(),
140
- 'm_root_history': np.array(mom_system.m_root_history),
141
- 'A_modes_history': np.array(mom_system.A_modes_history),
142
- 'event_counts_history': np.array(mom_system.event_counts_history),
143
- 'shred_onset': mom_system.shred_onset,
144
- 'elapsed_time_seconds': float(elapsed_time),
145
- 'gflops': float(gflops),
146
- }
147
-
148
- def rft_simulation_interface(Ncells, Nmode, iterations, dt, eps, sigma, theta, k_shred):
149
- try:
150
- results = run_rft_simulation(Ncells, Nmode, iterations, dt, eps, sigma, theta, k_shred)
151
- fig = plt.figure(figsize=(10, 14))
152
- ax1 = fig.add_subplot(4, 1, 1)
153
- ax1.plot(results['m_root_history'], label='Mean m_root')
154
- ax1.set_title('Mean m_root Over Iterations'); ax1.set_xlabel('Iteration'); ax1.set_ylabel('Mean m_root')
155
- ax1.grid(True); ax1.legend()
156
- ax2 = fig.add_subplot(4, 1, 2)
157
- ax2.plot(results['A_modes_history'], label='Mean A_modes', color='orange')
158
- ax2.set_title('Mean A_modes Over Iterations')
159
- ax2.set_xlabel('Iteration'); ax2.set_ylabel('Mean A_modes')
160
- ax2.grid(True); ax2.legend()
161
-
162
- # Plot 3: Cumulative Shredding Events
163
- ax3 = fig.add_subplot(4, 1, 3)
164
- cumulative_events = np.cumsum(results['event_counts_history'])
165
- ax3.plot(cumulative_events, label='Cumulative Shredding Events', color='red')
166
- ax3.set_title('Cumulative Shredding Events')
167
- ax3.set_xlabel('Iteration'); ax3.set_ylabel('Cumulative Events')
168
- ax3.grid(True); ax3.legend()
169
-
170
- # Plot 4: Raster of shredding onset per cell
171
- ax4 = fig.add_subplot(4, 1, 4)
172
- onset = results['shred_onset']
173
- for idx, val in enumerate(onset):
174
- if val >= 0:
175
- ax4.vlines(val, idx, idx + 1, color='black', linewidth=0.8)
176
- ax4.set_title('Shredding Onset per Cell')
177
- ax4.set_xlabel('Iteration'); ax4.set_ylabel('Cell Index')
178
- ax4.grid(True)
179
-
180
- plt.tight_layout()
181
- _, plot_path = tempfile.mkstemp(suffix=".png")
182
- plt.savefig(plot_path)
183
- plt.close(fig)
184
-
185
- summary_output = (
186
- f"Simulation completed in {results['elapsed_time_seconds']:.2f} seconds.\n\n"
187
- f"Estimated GFLOPS: {results['gflops']:.2f}\n"
188
- f"Final Mean m_root: {np.mean(results['final_m_root']):.6f}\n"
189
- f"Final Mean A_modes: {np.mean(results['final_A_modes']):.6f}\n"
190
- f"Total Events (last iteration): {results['event_counts_history'][-1] if len(results['event_counts_history']) > 0 else 0}\n\n"
191
- f"-- Historical Data (first 5 values) --\n"
192
- f"Mean m_root history: {results['m_root_history'][:5].tolist()}\n"
193
- f"Mean A_modes history: {results['A_modes_history'][:5].tolist()}\n"
194
- f"Event counts history: {results['event_counts_history'][:5].tolist()}"
195
- )
196
- except Exception as e:
197
- summary_output = f"Error during RFT simulation: {e}"
198
- plot_path = None
199
-
200
- return summary_output, plot_path
201
-
202
- # --- Explanatory markdown embedded directly ---
203
- with gr.Blocks(title="Rendered Frame Theory (RFT) Simulation Interface") as iface:
204
- gr.Markdown("""
205
- ### What is Rendered Frame Theory (RFT)?
206
-
207
- Rendered Frame Theory (RFT) is a computational framework for simulating complex adaptive systems with emergent, non-linear dynamics. It models a system as a collection of cells, each with internal modes that evolve over time through coupled updates and event-driven transitions.
208
-
209
- **Key features:**
210
- - ⚡ Dynamic systems: Evolves m_root (root mass), A_modes (mode amplitudes), and Q_drive (drive) over iterations.
211
- - 🔄 Feedback loops: Each iteration adjusts states based on prior values, enabling adaptation.
212
- - 🌀 Emergent behavior: A shredding mechanism triggers non-linear collapse when stress crosses a threshold.
213
- - 📈 Performance scaling: Designed to scale with the number of cells and modes, enabling large explorations.
214
-
215
- **Why it matters:**
216
- - 🔬 Granularity: Captures local interactions and cell-level transitions that averaged models miss.
217
- - ⚠️ Critical events: Models sudden cascades like market crashes, neural avalanches, or material failure.
218
- - 🌍 Versatility: Applicable to finance, biology, engineering, and AI research.
219
-
220
- The shredding onset plot shows when each cell first collapses, making cascades visible in time.
221
- """)
222
-
223
- with gr.Row():
224
- with gr.Column():
225
- gr.Markdown("### Simulation Parameters")
226
- Ncells_slider = gr.Slider(minimum=16, maximum=512, step=16, value=64, label="⚡ Number of Cells (Ncells)")
227
- Nmode_slider = gr.Slider(minimum=2, maximum=32, step=2, value=8, label="🔮 Number of Modes (Nmode)")
228
- iterations_slider = gr.Slider(minimum=10, maximum=200, step=10, value=50, label="♾ Iterations")
229
- dt_slider = gr.Slider(minimum=0.001, maximum=0.1, step=0.001, value=0.02, label="⌛ Time Step (dt)")
230
- eps_slider = gr.Slider(minimum=1e-7, maximum=1e-4, step=1e-7, value=1e-6, label="🧿 Epsilon (eps)")
231
- sigma_slider = gr.Slider(minimum=0.1, maximum=1.0, step=0.05, value=0.75, label="🌌 Sigma (coupling strength)")
232
- theta_slider = gr.Slider(minimum=0.1, maximum=5.0, step=0.1, value=2.2, label="🔭 Theta (Shredding Threshold)")
233
- k_shred_slider = gr.Slider(minimum=0.1, maximum=5.0, step=0.1, value=1.2, label="🌀 K_shred (Shredding Rate)")
234
- run_button = gr.Button("Run Simulation")
235
-
236
- with gr.Column():
237
- gr.Markdown("### Simulation Results")
238
- summary_output_textbox = gr.Textbox(label="Simulation Summary", lines=15)
239
- plot_output_image = gr.Image(label="Simulation Plots", type="filepath")
240
-
241
- run_button.click(
242
- fn=rft_simulation_interface,
243
- inputs=[Ncells_slider, Nmode_slider, iterations_slider, dt_slider, eps_slider,
244
- sigma_slider, theta_slider, k_shred_slider],
245
- outputs=[summary_output_textbox, plot_output_image]
246
- )
247
-
248
- if __name__ == "__main__":
249
- iface.launch(share=True)