arudradey commited on
Commit
28b0caa
·
verified ·
1 Parent(s): 1ed5724

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -0
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gradio app for the Brain-like Predictive Coding Code World Model.
3
+ """
4
+
5
+ import gradio as gr
6
+ import numpy as np
7
+ import sys
8
+ import os
9
+
10
+ # Train and load model on startup
11
+ from brain_predictive_coding import PredictiveCodingNetwork, SimpleCodeTokenizer, generate_code
12
+
13
+ print("Training model...")
14
+ tok = SimpleCodeTokenizer(vocab_size=128)
15
+
16
+ # Generate and train
17
+ SEQ_LEN = 16
18
+ EMBED = 32
19
+ N_SAMPLES = 40
20
+ EPOCHS = 15
21
+
22
+ code = generate_code(n=N_SAMPLES, max_len=SEQ_LEN)
23
+ sequences = np.array([tok.embed_seq(tok.encode(c, SEQ_LEN)) for c in code])
24
+
25
+ net = PredictiveCodingNetwork(
26
+ embed_dim=EMBED,
27
+ l1_n=128, l2_n=96, l3_n=64,
28
+ l1_lr=5e-5, l2_lr=5e-5, l3_lr=5e-5
29
+ )
30
+
31
+ for epoch in range(EPOCHS):
32
+ for i in range(N_SAMPLES):
33
+ net.context = np.zeros_like(net.context)
34
+ net.process_seq(sequences[i], train=True)
35
+
36
+ print("Model trained!")
37
+
38
+
39
+ def predict_code(code_text, n_steps=5):
40
+ """Predict next characters in code sequence."""
41
+ if not code_text:
42
+ return "Please enter some code!"
43
+
44
+ net.context = np.zeros_like(net.context)
45
+
46
+ tokens = tok.encode(code_text, max_len=16)
47
+ embeddings = tok.embed_seq(tokens)
48
+
49
+ preds = net.predict_next(embeddings, n_steps=n_steps)
50
+ predicted_chars = [tok.nearest(p) for p in preds]
51
+
52
+ stats = {
53
+ "L1 mean activity": float(np.mean(net.l1.activities)),
54
+ "L1 sparsity": f"{np.mean(net.l1.activities > 0):.1%}",
55
+ "L2 mean activity": float(np.mean(net.l2.activities)),
56
+ "L2 sparsity": f"{np.mean(net.l2.activities > 0):.1%}",
57
+ "L3 mean activity": float(np.mean(net.l3.activities)),
58
+ "L3 sparsity": f"{np.mean(net.l3.activities > 0):.1%}",
59
+ "Context magnitude": float(np.linalg.norm(net.context)),
60
+ }
61
+
62
+ result = f"**Input:** `{code_text}`\n\n"
63
+ result += f"**Predicted next {n_steps} characters:**\n"
64
+ for i, ch in enumerate(predicted_chars):
65
+ result += f" Step {i+1}: `{ch}`\n"
66
+
67
+ result += f"\n**Brain-like Network Statistics:**\n"
68
+ for k, v in stats.items():
69
+ result += f" {k}: {v}\n"
70
+
71
+ return result
72
+
73
+
74
+ def get_layer_activities(code_text):
75
+ """Show layer activity statistics."""
76
+ net.context = np.zeros_like(net.context)
77
+ tokens = tok.encode(code_text, max_len=16)
78
+ embeddings = tok.embed_seq(tokens)
79
+ net.process_seq(embeddings, train=False)
80
+
81
+ l1_acts = net.l1.activities
82
+ l2_acts = net.l2.activities
83
+ l3_acts = net.l3.activities
84
+
85
+ output = "**Layer Activities (sample of active neurons):**\n\n"
86
+
87
+ output += f"L1 (Sensory, {len(l1_acts)} neurons):\n"
88
+ active_l1 = np.where(l1_acts > 0.01)[0]
89
+ output += f" Active: {len(active_l1)} ({len(active_l1)/len(l1_acts):.1%})\n"
90
+ output += f" Top 5: {l1_acts[np.argsort(l1_acts)[-5:]][::-1].round(4).tolist()}\n\n"
91
+
92
+ output += f"L2 (Hidden, {len(l2_acts)} neurons):\n"
93
+ active_l2 = np.where(l2_acts > 0.01)[0]
94
+ output += f" Active: {len(active_l2)} ({len(active_l2)/len(l2_acts):.1%})\n"
95
+ output += f" Top 5: {l2_acts[np.argsort(l2_acts)[-5:]][::-1].round(4).tolist()}\n\n"
96
+
97
+ output += f"L3 (Context, {len(l3_acts)} neurons):\n"
98
+ active_l3 = np.where(l3_acts > 0.01)[0]
99
+ output += f" Active: {len(active_l3)} ({len(active_l3)/len(l3_acts):.1%})\n"
100
+ output += f" Top 5: {l3_acts[np.argsort(l3_acts)[-5:]][::-1].round(4).tolist()}\n"
101
+
102
+ return output
103
+
104
+
105
+ description = """
106
+ # 🧠 Brain-like Predictive Coding Code World Model
107
+
108
+ This model uses a **hierarchical predictive coding network** inspired by the brain's cortical hierarchy:
109
+ - **L1 (Sensory)**: Processes code token embeddings like primary visual cortex
110
+ - **L2 (Hidden)**: Learns associative patterns like inferotemporal cortex
111
+ - **L3 (Context)**: Maintains sequence context like prefrontal cortex
112
+
113
+ **Brain-like features:**
114
+ - LIF (Leaky Integrate-and-Fire) neurons
115
+ - PES (Prescribed Error Sensitivity) learning — error-driven weight updates
116
+ - Top-down predictions from higher layers
117
+ - Prediction errors drive learning (free-energy principle)
118
+ - Numba JIT acceleration for fast CPU inference
119
+ """
120
+
121
+ with gr.Blocks(title="Brain-like PC Code Model") as demo:
122
+ gr.Markdown(description)
123
+
124
+ with gr.Tab("Code Prediction"):
125
+ with gr.Row():
126
+ with gr.Column():
127
+ code_input = gr.Textbox(
128
+ label="Input Code",
129
+ placeholder="def compute(x):\n return",
130
+ lines=3
131
+ )
132
+ n_steps = gr.Slider(1, 10, value=5, step=1, label="Prediction Steps")
133
+ predict_btn = gr.Button("Predict Next Tokens")
134
+
135
+ with gr.Column():
136
+ output = gr.Markdown(label="Predictions")
137
+
138
+ predict_btn.click(predict_code, inputs=[code_input, n_steps], outputs=output)
139
+
140
+ with gr.Tab("Layer Activities"):
141
+ with gr.Row():
142
+ with gr.Column():
143
+ code_input2 = gr.Textbox(
144
+ label="Input Code",
145
+ placeholder="for i in range(10):",
146
+ lines=2
147
+ )
148
+ act_btn = gr.Button("Show Activities")
149
+
150
+ with gr.Column():
151
+ act_output = gr.Markdown(label="Layer Activities")
152
+
153
+ act_btn.click(get_layer_activities, inputs=code_input2, outputs=act_output)
154
+
155
+ if __name__ == "__main__":
156
+ demo.launch()