RFTSystems commited on
Commit
a1a657f
·
verified ·
1 Parent(s): b060419

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -272
app.py DELETED
@@ -1,272 +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
- # Conditional import of cupy
9
- try:
10
- import cupy as cp
11
- _has_cupy = True
12
- except ImportError:
13
- _has_cupy = False
14
- print("CuPy not found. Running in CPU-only mode. Performance will be significantly lower.")
15
-
16
- # --- CUDA kernel source (kept for GPU path) ---
17
- cuda_source = r''' ... ''' # (unchanged, omitted for brevity)
18
-
19
- # --- CPU kernel ---
20
- def fused_mom_update_cpu(m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
21
- dt, eps, sigma_const, theta_global, k_shred_global,
22
- event_counts_t=None, event_buffer_t=None):
23
- m_root_t = m_root_t.to(torch.float32)
24
- A_t = A_t.to(torch.float32)
25
- Q_t = Q_t.to(torch.float32)
26
- alpha_t = alpha_t.to(torch.float32)
27
- gamma_t = gamma_t.to(torch.float32)
28
- omega_t = omega_t.to(torch.float32)
29
-
30
- alpha_exp = alpha_t.unsqueeze(0)
31
- gamma_exp = gamma_t.unsqueeze(0)
32
- omega_exp = omega_t.unsqueeze(0)
33
- m_root_exp = m_root_t.unsqueeze(1)
34
-
35
- A_dot = alpha_exp * m_root_exp - gamma_exp * A_t + sigma_const * Q_t
36
- f_drive = sigma_const * m_root_exp * omega_exp * A_t
37
- Q_dot = f_drive - Q_t
38
-
39
- A_t.add_(dt * A_dot)
40
- Q_t.add_(dt * Q_dot)
41
-
42
- Xi = (omega_exp * A_t).sum(dim=1)
43
- Xi_norm = Xi / (m_root_t + eps)
44
- shred_mask = Xi_norm >= theta_global
45
-
46
- if torch.any(shred_mask):
47
- eta_values = torch.zeros_like(Xi_norm)
48
- eta_calc = 1.0 - torch.exp(-k_shred_global * (Xi_norm[shred_mask] - theta_global))
49
- eta_values[shred_mask] = torch.clamp(eta_calc, 0.0, 1.0)
50
-
51
- diss = 0.01 * m_root_t * eta_values
52
- m_post = (1.0 - eta_values) * m_root_t - diss
53
- m_post = torch.clamp(m_post, min=0.0)
54
-
55
- m_root_t[shred_mask] = m_post[shred_mask]
56
-
57
- shred_count = int(torch.sum(shred_mask).item())
58
- if event_counts_t is not None:
59
- if isinstance(event_counts_t, torch.Tensor):
60
- if event_counts_t.dtype not in (torch.int64, torch.int32):
61
- event_counts_t = event_counts_t.to(torch.int64)
62
- event_counts_t.add_(shred_count)
63
- else:
64
- event_counts_t += shred_count
65
-
66
- return m_root_t, A_t, Q_t, event_counts_t
67
-
68
- # --- Kernel wrapper ---
69
- class MOMKernel:
70
- def __init__(self, cuda_source, kernel_name='fused_mom_update', block_dim=128):
71
- self.use_cuda = torch.cuda.is_available() and _has_cupy
72
- if self.use_cuda:
73
- try:
74
- self.module = cp.RawModule(code=cuda_source, backend='nvcc', options=('-std=c++11',))
75
- self.kernel = self.module.get_function(kernel_name)
76
- self.device = torch.device('cuda')
77
- except Exception:
78
- self.use_cuda = False
79
- self.kernel = fused_mom_update_cpu
80
- self.device = torch.device('cpu')
81
- else:
82
- self.kernel = fused_mom_update_cpu
83
- self.device = torch.device('cpu')
84
-
85
- def __call__(self, m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
86
- dt, eps, sigma_const, theta_global, k_shred_global,
87
- event_counts_t=None, event_buffer_t=None):
88
- if not self.use_cuda:
89
- return self.kernel(m_root_t, A_t, Q_t, alpha_t, gamma_t, omega_t,
90
- dt, eps, sigma_const, theta_global, k_shred_global,
91
- event_counts_t, event_buffer_t)
92
- return m_root_t, A_t, Q_t, event_counts_t
93
-
94
- # --- Feedback system ---
95
- class MOMSystemLoop:
96
- def __init__(self, mom_kernel, m_root_initial, A_modes_initial, Q_drive_initial,
97
- alpha, gamma, omega, dt=0.02, eps=1e-6, sigma=0.75,
98
- theta=2.2, k_shred=1.2, event_buffer_size=1024):
99
- self.mom_kernel = mom_kernel
100
- self.device = mom_kernel.device
101
- self.m_root = m_root_initial.to(self.device).clone().to(torch.float32)
102
- self.A_modes = A_modes_initial.to(self.device).clone().to(torch.float32)
103
- self.Q_drive = Q_drive_initial.to(self.device).clone().to(torch.float32)
104
- self.alpha = alpha.to(self.device).to(torch.float32)
105
- self.gamma = gamma.to(self.device).to(torch.float32)
106
- self.omega = omega.to(self.device).to(torch.float32)
107
- self.dt = dt; self.eps = eps; self.sigma = sigma
108
- self.theta = theta; self.k_shred = k_shred
109
- self.event_counts = torch.zeros((), dtype=torch.int64, device=self.device)
110
- self.event_buffer = torch.zeros(event_buffer_size, dtype=torch.int64, device=self.device)
111
- self.m_root_history = []; self.A_modes_history = []; self.event_counts_history = []
112
- self.shred_onset = np.full((self.m_root.shape[0],), -1, dtype=np.int32)
113
-
114
- def feedback(self, m_root, A_modes, Q_drive):
115
- decay = 0.995; noise_level = 1e-4
116
- A_modes_new = A_modes * decay + noise_level * torch.randn_like(A_modes, device=self.device)
117
- A_modes_new = torch.clamp(A_modes_new, min=0.0)
118
- m_root_new = m_root * decay + noise_level * torch.randn_like(m_root, device=self.device)
119
- m_root_new = torch.clamp(m_root_new, min=0.0)
120
- return m_root_new, A_modes_new, Q_drive
121
-
122
- def run(self, iterations):
123
- for i in range(iterations):
124
- self.event_counts.zero_()
125
- self.mom_kernel(self.m_root, self.A_modes, self.Q_drive,
126
- self.alpha, self.gamma, self.omega,
127
- self.dt, self.eps, self.sigma, self.theta, self.k_shred,
128
- self.event_counts, self.event_buffer)
129
- # record shred onset
130
- shredded = (self.m_root.cpu().numpy() == 0.0)
131
- for idx, flag in enumerate(shredded):
132
- if flag and self.shred_onset[idx] == -1:
133
- self.shred_onset[idx] = i
134
- self.m_root, self.A_modes, self.Q_drive = self.feedback(self.m_root, self.A_modes, self.Q_drive)
135
- self.m_root_history.append(self.m_root.mean().item())
136
- self.A_modes_history.append(self.A_modes.mean().item())
137
- self.event_counts_history.append(int(self.event_counts.item()))
138
-
139
- # --- Simulation wrapper ---
140
- def run_rft_simulation(Ncells, Nmode, iterations, dt=0.02, eps=1e-6, sigma=0.75,
141
- theta=2.2, k_shred=1.2, seed=42):
142
- torch.manual_seed(seed); np.random.seed(seed)
143
- mom_kernel_instance = MOMKernel(cuda_source)
144
- device = mom_kernel_instance.device
145
- alpha = torch.empty(Nmode, device=device).uniform_(0.02, 0.12)
146
- gamma = torch.empty(Nmode, device=device).uniform_(0.01, 0.06)
147
- omega = torch.linspace(1.0, 8.0, Nmode, device=device)
148
- m_root_initial = torch.ones(Ncells, device=device)
149
- A_modes_initial = torch.rand(Ncells, Nmode, device=device) * 0.01
150
- Q_drive_initial = torch.zeros(Ncells, Nmode, device=device)
151
- mom_system = MOMSystemLoop(mom_kernel_instance, m_root_initial, A_modes_initial, Q_drive_initial,
152
- alpha, gamma, omega, dt=dt, eps=eps, sigma=sigma,
153
- theta=theta, k_shred=k_shred)
154
- start_time = time.time()
155
- mom_system.run(iterations)
156
- elapsed_time = max(time.time() - start_time, 1e-9)
157
- ops_per_cell_per_iter = 12 * Nmode + 13
158
- flops_per_iteration = float(Ncells) * float(ops_per_cell_per_iter)
159
- total_flops = flops_per_iteration * float(iterations)
160
- gflops = total_flops / (elapsed_time * 1e9)
161
- return {
162
- 'final_m_root': mom_system.m_root.cpu().numpy(),
163
- 'final_A_modes': mom_system.A_modes.cpu().numpy(),
164
- 'final_Q_drive': mom_system.Q_drive.cpu().numpy(),
165
- 'm_root_history': np.array(mom_system.m_root_history),
166
- 'A_modes_history': np.array(mom_system.A_modes_history),
167
- 'event_counts_history': np.array(mom_system.event_counts_history),
168
- 'shred_onset': mom_system.shred_onset,
169
- 'elapsed_time_seconds': float(elapsed_time),
170
- 'gflops': float(gflops),
171
- }
172
-
173
-
174
- def rft_simulation_interface(Ncells, Nmode, iterations, dt, eps, sigma, theta, k_shred):
175
- try:
176
- results = run_rft_simulation(
177
- Ncells=Ncells, Nmode=Nmode, iterations=iterations,
178
- dt=dt, eps=eps, sigma=sigma, theta=theta, k_shred=k_shred
179
- )
180
-
181
- fig = plt.figure(figsize=(10, 14))
182
-
183
- # Plot 1: Mean m_root
184
- ax1 = fig.add_subplot(4, 1, 1)
185
- ax1.plot(results['m_root_history'], label='Mean m_root')
186
- ax1.set_title('Mean m_root Over Iterations')
187
- ax1.set_xlabel('Iteration'); ax1.set_ylabel('Mean m_root')
188
- ax1.grid(True); ax1.legend()
189
-
190
- # Plot 2: Mean A_modes
191
- ax2 = fig.add_subplot(4, 1, 2)
192
- ax2.plot(results['A_modes_history'], label='Mean A_modes', color='orange')
193
- ax2.set_title('Mean A_modes Over Iterations')
194
- ax2.set_xlabel('Iteration'); ax2.set_ylabel('Mean A_modes')
195
- ax2.grid(True); ax2.legend()
196
-
197
- # Plot 3: Cumulative Shredding Events
198
- ax3 = fig.add_subplot(4, 1, 3)
199
- cumulative_events = np.cumsum(results['event_counts_history'])
200
- ax3.plot(cumulative_events, label='Cumulative Shredding Events', color='red')
201
- ax3.set_title('Cumulative Shredding Events')
202
- ax3.set_xlabel('Iteration'); ax3.set_ylabel('Cumulative Events')
203
- ax3.grid(True); ax3.legend()
204
-
205
- # Plot 4: Raster of shredding onset
206
- ax4 = fig.add_subplot(4, 1, 4)
207
- onset = results['shred_onset']
208
- for idx, val in enumerate(onset):
209
- if val >= 0:
210
- ax4.vlines(val, idx, idx+1, color='black')
211
- ax4.set_title('Shredding Onset per Cell')
212
- ax4.set_xlabel('Iteration'); ax4.set_ylabel('Cell Index')
213
- ax4.grid(True)
214
-
215
- plt.tight_layout()
216
- _, plot_path = tempfile.mkstemp(suffix=".png")
217
- plt.savefig(plot_path); plt.close(fig)
218
-
219
- summary_output = (
220
- f"Simulation completed in {results['elapsed_time_seconds']:.2f} seconds.\n\n"
221
- f"Estimated GFLOPS: {results['gflops']:.2f}\n"
222
- f"Final Mean m_root: {np.mean(results['final_m_root']):.6f}\n"
223
- f"Final Mean A_modes: {np.mean(results['final_A_modes']):.6f}\n"
224
- f"Total Events (last iteration): {results['event_counts_history'][-1]}\n\n"
225
- f"-- Historical Data (first 5 values) --\n"
226
- f"Mean m_root history: {results['m_root_history'][:5].tolist()}\n"
227
- f"Mean A_modes history: {results['A_modes_history'][:5].tolist()}\n"
228
- f"Event counts history: {results['event_counts_history'][:5].tolist()}"
229
- )
230
- except Exception as e:
231
- summary_output = f"Error during RFT simulation: {e}"
232
- plot_path = None
233
-
234
- return summary_output, plot_path
235
-
236
-
237
- # --- Gradio UI ---
238
- what_is_this_markdown = '''
239
- ### Render Frame Theory (RFT)
240
- ... (unchanged explanatory text) ...
241
- '''
242
-
243
- with gr.Blocks(title="Render Frame Theory (RFT) Simulation Interface (CPU-ready)") as iface:
244
- gr.Markdown(what_is_this_markdown)
245
-
246
- with gr.Row():
247
- with gr.Column():
248
- gr.Markdown("### Simulation Parameters")
249
- Ncells_slider = gr.Slider(16, 512, step=16, value=64, label="⚡ Number of Cells (Ncells)")
250
- Nmode_slider = gr.Slider(2, 32, step=2, value=8, label="🔮 Number of Modes (Nmode)")
251
- iterations_slider = gr.Slider(10, 200, step=10, value=50, label="♾ Iterations")
252
- dt_slider = gr.Slider(0.001, 0.1, step=0.001, value=0.02, label="⌛ Time Step (dt)")
253
- eps_slider = gr.Slider(1e-7, 1e-4, step=1e-7, value=1e-6, label="🧿 Epsilon (eps)")
254
- sigma_slider = gr.Slider(0.1, 1.0, step=0.05, value=0.75, label="🌌 Sigma (coupling strength)")
255
- theta_slider = gr.Slider(0.1, 5.0, step=0.1, value=2.2, label="🔭 Theta (Shredding Threshold)")
256
- k_shred_slider = gr.Slider(0.1, 5.0, step=0.1, value=1.2, label="🌀 K_shred (Shredding Rate)")
257
- run_button = gr.Button("Run Simulation")
258
-
259
- with gr.Column():
260
- gr.Markdown("### Simulation Results")
261
- summary_output_textbox = gr.Textbox(label="Simulation Summary", lines=15)
262
- plot_output_image = gr.Image(label="Simulation Plots", type="filepath")
263
-
264
- run_button.click(
265
- fn=rft_simulation_interface,
266
- inputs=[Ncells_slider, Nmode_slider, iterations_slider, dt_slider, eps_slider,
267
- sigma_slider, theta_slider, k_shred_slider],
268
- outputs=[summary_output_textbox, plot_output_image]
269
- )
270
-
271
- if __name__ == "__main__":
272
- iface.launch(share=True)