quant-iota commited on
Commit
9ece6da
·
verified ·
1 Parent(s): 0462879

Upload 11 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ data/MNIST/raw/t10k-images-idx3-ubyte filter=lfs diff=lfs merge=lfs -text
37
+ data/MNIST/raw/train-images-idx3-ubyte filter=lfs diff=lfs merge=lfs -text
38
+ logo.png filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SKA Time-Invariance Explorer - Gradio App
2
+ import torch
3
+ import torch.nn as nn
4
+ import numpy as np
5
+ import matplotlib
6
+ matplotlib.use('Agg')
7
+ import matplotlib.pyplot as plt
8
+ from torchvision import datasets, transforms
9
+ import gradio as gr
10
+
11
+ # Load MNIST from local data
12
+ transform = transforms.Compose([transforms.ToTensor()])
13
+ mnist_dataset = datasets.MNIST(root='./data', train=True, download=False, transform=transform)
14
+
15
+ # Fixed architecture and characteristic time as per arXiv:2504.03214v1
16
+ LAYER_SIZES = [256, 128, 64, 10]
17
+ TAU = 0.5
18
+
19
+ # Exact 6 (eta, K) configurations from the paper — all satisfy eta * K = 0.5
20
+ CONFIGS = [
21
+ (0.020, 25),
22
+ (0.010, 50),
23
+ (0.005, 100),
24
+ (0.0033, 150),
25
+ (0.0025, 200),
26
+ (0.001, 500),
27
+ ]
28
+
29
+ CONFIG_COLORS = ['#1F77B4', '#FF7F0E', '#2CA02C', '#D62728', '#9467BD', '#8C564B']
30
+
31
+
32
+ class SKAModel(nn.Module):
33
+ def __init__(self, input_size=784, layer_sizes=[256, 128, 64, 10], K=50):
34
+ super(SKAModel, self).__init__()
35
+ self.input_size = input_size
36
+ self.layer_sizes = layer_sizes
37
+ self.K = K
38
+
39
+ self.weights = nn.ParameterList()
40
+ self.biases = nn.ParameterList()
41
+ prev_size = input_size
42
+ for size in layer_sizes:
43
+ self.weights.append(nn.Parameter(torch.randn(prev_size, size) * 0.01))
44
+ self.biases.append(nn.Parameter(torch.zeros(size)))
45
+ prev_size = size
46
+
47
+ self.Z = [None] * len(layer_sizes)
48
+ self.Z_prev = [None] * len(layer_sizes)
49
+ self.D = [None] * len(layer_sizes)
50
+ self.D_prev = [None] * len(layer_sizes)
51
+ self.delta_D = [None] * len(layer_sizes)
52
+ self.entropy = [None] * len(layer_sizes)
53
+
54
+ self.entropy_history = [[] for _ in range(len(layer_sizes))]
55
+ self.cosine_history = [[] for _ in range(len(layer_sizes))]
56
+ self.output_history = []
57
+
58
+ def forward(self, x):
59
+ batch_size = x.shape[0]
60
+ x = x.view(batch_size, -1)
61
+ for l in range(len(self.layer_sizes)):
62
+ z = torch.mm(x, self.weights[l]) + self.biases[l]
63
+ d = torch.sigmoid(z)
64
+ self.Z[l] = z
65
+ self.D[l] = d
66
+ x = d
67
+ return x
68
+
69
+ def calculate_entropy(self):
70
+ for l in range(len(self.layer_sizes)):
71
+ if self.Z[l] is not None and self.D_prev[l] is not None and self.D[l] is not None and self.Z_prev[l] is not None:
72
+ self.delta_D[l] = self.D[l] - self.D_prev[l]
73
+ H_lk = (-1 / np.log(2)) * (self.Z[l] * self.delta_D[l])
74
+ layer_entropy = torch.sum(H_lk)
75
+ self.entropy[l] = layer_entropy.item()
76
+ self.entropy_history[l].append(layer_entropy.item())
77
+
78
+ dot_product = torch.sum(self.Z[l] * self.delta_D[l])
79
+ z_norm = torch.norm(self.Z[l])
80
+ delta_d_norm = torch.norm(self.delta_D[l])
81
+ if z_norm > 0 and delta_d_norm > 0:
82
+ cos_theta = dot_product / (z_norm * delta_d_norm)
83
+ self.cosine_history[l].append(cos_theta.item())
84
+ else:
85
+ self.cosine_history[l].append(0.0)
86
+
87
+ def ska_update(self, inputs, learning_rate=0.01):
88
+ for l in range(len(self.layer_sizes)):
89
+ if self.delta_D[l] is not None:
90
+ prev_output = inputs.view(inputs.shape[0], -1) if l == 0 else self.D_prev[l-1]
91
+ d_prime = self.D[l] * (1 - self.D[l])
92
+ gradient = -1 / np.log(2) * (self.Z[l] * d_prime + self.delta_D[l])
93
+ dW = torch.matmul(prev_output.t(), gradient) / prev_output.shape[0]
94
+ self.weights[l] = self.weights[l] - learning_rate * dW
95
+ self.biases[l] = self.biases[l] - learning_rate * gradient.mean(dim=0)
96
+
97
+ def initialize_tensors(self, batch_size):
98
+ for l in range(len(self.layer_sizes)):
99
+ self.Z[l] = None
100
+ self.Z_prev[l] = None
101
+ self.D[l] = None
102
+ self.D_prev[l] = None
103
+ self.delta_D[l] = None
104
+ self.entropy[l] = None
105
+ self.entropy_history[l] = []
106
+ self.cosine_history[l] = []
107
+ self.output_history = []
108
+
109
+
110
+ def get_mnist_subset(samples_per_class, data_seed=0):
111
+ """Select N samples per class from MNIST."""
112
+ images_list = []
113
+ targets = mnist_dataset.targets.numpy()
114
+ rng = np.random.RandomState(data_seed)
115
+ for digit in range(10):
116
+ all_indices = np.where(targets == digit)[0]
117
+ rng.shuffle(all_indices)
118
+ indices = all_indices[:samples_per_class]
119
+ for idx in indices:
120
+ img, label = mnist_dataset[idx]
121
+ images_list.append(img)
122
+ images = torch.stack(images_list)
123
+ return images
124
+
125
+
126
+ def run_time_invariance(samples_per_class, data_seed):
127
+ samples_per_class = int(samples_per_class)
128
+ data_seed = int(data_seed)
129
+
130
+ inputs = get_mnist_subset(samples_per_class, data_seed)
131
+
132
+ results = []
133
+ for eta, K in CONFIGS:
134
+ torch.manual_seed(42)
135
+ np.random.seed(42)
136
+ model = SKAModel(input_size=784, layer_sizes=LAYER_SIZES, K=K)
137
+ model.initialize_tensors(inputs.size(0))
138
+
139
+ for k in range(K):
140
+ model.forward(inputs)
141
+ if k > 0:
142
+ model.calculate_entropy()
143
+ model.ska_update(inputs, eta)
144
+ model.D_prev = [d.clone().detach() if d is not None else None for d in model.D]
145
+ model.Z_prev = [z.clone().detach() if z is not None else None for z in model.Z]
146
+
147
+ results.append((eta, K, model.entropy_history, model.cosine_history))
148
+
149
+ layer_colors = ['#1F77B4', '#FF7F0E', '#2CA02C', '#D62728']
150
+ layer_labels = ['Layer 1', 'Layer 2', 'Layer 3', 'Layer 4']
151
+
152
+ # Plot 1: Entropy — 2x3 grid, one subplot per (eta, K) config, 4 layer curves each
153
+ fig1, axes1 = plt.subplots(3, 2, figsize=(14, 18))
154
+ for idx, (eta, K, entropy_history, _) in enumerate(results):
155
+ ax = axes1[idx // 2][idx % 2]
156
+ for l in range(len(LAYER_SIZES)):
157
+ ax.plot(entropy_history[l], color=layer_colors[l],
158
+ label=layer_labels[l], linewidth=1.5)
159
+ ax.set_title(f"Entropy Evolution Across Layers (Single Pass)\nη={eta:.4f}, K={K}", fontsize=10)
160
+ ax.set_xlabel("Step Index K")
161
+ ax.set_ylabel("Entropy")
162
+ ax.legend(fontsize=8)
163
+ ax.grid(True)
164
+ fig1.suptitle(
165
+ f"Time-Invariance — Entropy | T = η·K = {TAU} | [256, 128, 64, 10]",
166
+ fontsize=13, y=1.01
167
+ )
168
+ fig1.tight_layout()
169
+
170
+ # Plot 2: Cosine alignment — 2x3 grid, one subplot per (eta, K) config, 4 layer curves each
171
+ fig2, axes2 = plt.subplots(3, 2, figsize=(14, 18))
172
+ for idx, (eta, K, _, cosine_history) in enumerate(results):
173
+ ax = axes2[idx // 2][idx % 2]
174
+ for l in range(len(LAYER_SIZES)):
175
+ ax.plot(cosine_history[l], color=layer_colors[l],
176
+ label=layer_labels[l], linewidth=1.5)
177
+ ax.set_title(f"Cos(θ) Alignment Evolution Across Layers (Single Pass)\nη={eta:.4f}, K={K}", fontsize=10)
178
+ ax.set_xlabel("Step Index K")
179
+ ax.set_ylabel("Cos(θ)")
180
+ ax.legend(fontsize=8)
181
+ ax.grid(True)
182
+ fig2.suptitle(
183
+ f"Time-Invariance — Cosine Alignment | T = η·K = {TAU} | [256, 128, 64, 10]",
184
+ fontsize=13, y=1.01
185
+ )
186
+ fig2.tight_layout()
187
+
188
+ return fig1, fig2
189
+
190
+
191
+ with gr.Blocks(title="SKA Time-Invariance Explorer") as demo:
192
+ gr.Image("logo.png", show_label=False, height=100, container=False)
193
+ gr.Markdown("# SKA Time-Invariance Explorer")
194
+ gr.Markdown("Fix the characteristic time T = η · K = 0.5 and run 6 different (η, K) pairs automatically. All entropy and cosine curves collapse onto the same trajectory — revealing the intrinsic timescale of the architecture [256, 128, 64, 10] on MNIST.")
195
+
196
+ with gr.Row():
197
+ with gr.Column(scale=1):
198
+ gr.Markdown("**Architecture (fixed):** [256, 128, 64, 10]")
199
+ gr.Markdown("**Characteristic time (fixed):** T = η · K = 0.5")
200
+ samples_slider = gr.Slider(1, 100, value=100, step=1, label="Samples per class")
201
+ seed_slider = gr.Slider(0, 99, value=0, step=1, label="Data seed (shuffle samples)")
202
+ run_btn = gr.Button("Run Time-Invariance Test", variant="primary")
203
+
204
+ gr.Markdown("---")
205
+ gr.Markdown("### The 6 configurations")
206
+ gr.Markdown(
207
+ "| η | K |\n|---|---|\n"
208
+ "| 0.0200 | 25 |\n"
209
+ "| 0.0100 | 50 |\n"
210
+ "| 0.0050 | 100 |\n"
211
+ "| 0.0033 | 150 |\n"
212
+ "| 0.0025 | 200 |\n"
213
+ "| 0.0010 | 500 |"
214
+ )
215
+
216
+ gr.Markdown("---")
217
+ gr.Markdown("### Reference Paper")
218
+ gr.HTML('<a href="https://arxiv.org/abs/2504.03214v1" target="_blank">arXiv:2504.03214v1</a>')
219
+
220
+ gr.Markdown("""
221
+ **Abstract**
222
+ This paper aims to extend the Structured Knowledge Accumulation (SKA) framework recently proposed by mahi. We introduce two core concepts: the Tensor Net function and the characteristic time property of neural learning. First, we reinterpret the learning rate as a time step in a continuous system. This transforms neural learning from discrete optimization into continuous-time evolution. We show that learning dynamics remain consistent when the product of learning rate and iteration steps stays constant. This reveals a time-invariant behavior and identifies an intrinsic timescale of the network. Second, we define the Tensor Net function as a measure that captures the relationship between decision probabilities, entropy gradients, and knowledge change. Additionally, we define its zero-crossing as the equilibrium state between decision probabilities and entropy gradients. We show that the convergence of entropy and knowledge flow provides a natural stopping condition, replacing arbitrary thresholds with an information-theoretic criterion. We also establish that SKA dynamics satisfy a variational principle based on the Euler-Lagrange equation. These findings extend SKA into a continuous and self-organizing learning model. The framework links computational learning with physical systems that evolve by natural laws. By understanding learning as a time-based process, we open new directions for building efficient, robust, and biologically-inspired AI systems.
223
+
224
+ """)
225
+
226
+ gr.Markdown("---")
227
+ gr.Markdown("### SKA Explorer Suite")
228
+ gr.HTML('<a href="https://huggingface.co/quant-iota" target="_blank">⬅ All Apps</a>')
229
+ gr.Markdown("---")
230
+ gr.Markdown("### About this App")
231
+ gr.Markdown("Six (η, K) pairs all share the same characteristic time T = η · K = 0.5, the intrinsic timescale of the architecture [256, 128, 64, 10]. Each configuration is run independently and plotted as a function of the step index K. The trajectory shapes remain identical across all configurations while the amplitude scales with η — demonstrating that T is the true timescale of learning, not η or K individually. The characteristic time is the necessary time exposure of the sample to the learning system to complete. T = 0.5 is the characteristic time of the architecture [256, 128, 64, 10] on MNIST.")
232
+
233
+ with gr.Column(scale=2):
234
+ plot_entropy = gr.Plot(label="Entropy — 4 Layers")
235
+ plot_cosine = gr.Plot(label="Cosine Alignment — 4 Layers")
236
+
237
+ run_btn.click(
238
+ fn=run_time_invariance,
239
+ inputs=[samples_slider, seed_slider],
240
+ outputs=[plot_entropy, plot_cosine],
241
+ )
242
+
243
+ demo.launch(server_name="0.0.0.0", server_port=7861, share=True)
data/MNIST/raw/t10k-images-idx3-ubyte ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0fa7898d509279e482958e8ce81c8e77db3f2f8254e26661ceb7762c4d494ce7
3
+ size 7840016
data/MNIST/raw/t10k-images-idx3-ubyte.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d422c7b0a1c1c79245a5bcf07fe86e33eeafee792b84584aec276f5a2dbc4e6
3
+ size 1648877
data/MNIST/raw/t10k-labels-idx1-ubyte ADDED
Binary file (10 kB). View file
 
data/MNIST/raw/t10k-labels-idx1-ubyte.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7ae60f92e00ec6debd23a6088c31dbd2371eca3ffa0defaefb259924204aec6
3
+ size 4542
data/MNIST/raw/train-images-idx3-ubyte ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba891046e6505d7aadcbbe25680a0738ad16aec93bde7f9b65e87a2fc25776db
3
+ size 47040016
data/MNIST/raw/train-images-idx3-ubyte.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:440fcabf73cc546fa21475e81ea370265605f56be210a4024d2ca8f203523609
3
+ size 9912422
data/MNIST/raw/train-labels-idx1-ubyte ADDED
Binary file (60 kB). View file
 
data/MNIST/raw/train-labels-idx1-ubyte.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3552534a0a558bbed6aed32b30c495cca23d567ec52cac8be1a0730e8010255c
3
+ size 28881
logo.png ADDED

Git LFS Details

  • SHA256: a1fbe3d70086c916cd7b844c8e3be454b6d2ecb308cc048a4b719e1dfb0eb381
  • Pointer size: 131 Bytes
  • Size of remote file: 268 kB
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ matplotlib
4
+ seaborn
5
+ numpy