quant-iota commited on
Commit
a60dc89
·
verified ·
1 Parent(s): 2f527b3

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,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SKA Discrete vs Continuous 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
+
16
+ class SKAModel(nn.Module):
17
+ def __init__(self, input_size=784, layer_sizes=[256, 128, 64, 10], K=50):
18
+ super(SKAModel, self).__init__()
19
+ self.input_size = input_size
20
+ self.layer_sizes = layer_sizes
21
+ self.K = K
22
+
23
+ self.weights = nn.ParameterList()
24
+ self.biases = nn.ParameterList()
25
+ prev_size = input_size
26
+ for size in layer_sizes:
27
+ self.weights.append(nn.Parameter(torch.randn(prev_size, size) * 0.01))
28
+ self.biases.append(nn.Parameter(torch.zeros(size)))
29
+ prev_size = size
30
+
31
+ self.Z = [None] * len(layer_sizes)
32
+ self.Z_prev = [None] * len(layer_sizes)
33
+ self.D = [None] * len(layer_sizes)
34
+ self.D_prev = [None] * len(layer_sizes)
35
+ self.delta_D = [None] * len(layer_sizes)
36
+ self.entropy = [None] * len(layer_sizes)
37
+
38
+ self.entropy_history = [[] for _ in range(len(layer_sizes))]
39
+ self.cosine_history = [[] for _ in range(len(layer_sizes))]
40
+
41
+ def forward(self, x):
42
+ batch_size = x.shape[0]
43
+ x = x.view(batch_size, -1)
44
+ for l in range(len(self.layer_sizes)):
45
+ z = torch.mm(x, self.weights[l]) + self.biases[l]
46
+ d = torch.sigmoid(z)
47
+ self.Z[l] = z
48
+ self.D[l] = d
49
+ x = d
50
+ return x
51
+
52
+ def calculate_entropy(self):
53
+ for l in range(len(self.layer_sizes)):
54
+ 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:
55
+ self.delta_D[l] = self.D[l] - self.D_prev[l]
56
+ H_lk = (-1 / np.log(2)) * (self.Z[l] * self.delta_D[l])
57
+ layer_entropy = torch.sum(H_lk)
58
+ self.entropy[l] = layer_entropy.item()
59
+ self.entropy_history[l].append(layer_entropy.item())
60
+
61
+ dot_product = torch.sum(self.Z[l] * self.delta_D[l])
62
+ z_norm = torch.norm(self.Z[l])
63
+ delta_d_norm = torch.norm(self.delta_D[l])
64
+ if z_norm > 0 and delta_d_norm > 0:
65
+ cos_theta = dot_product / (z_norm * delta_d_norm)
66
+ self.cosine_history[l].append(cos_theta.item())
67
+ else:
68
+ self.cosine_history[l].append(0.0)
69
+
70
+ def ska_update(self, inputs, learning_rate=0.01, use_delta_d=True):
71
+ for l in range(len(self.layer_sizes)):
72
+ if self.delta_D[l] is not None:
73
+ prev_output = inputs.view(inputs.shape[0], -1) if l == 0 else self.D_prev[l-1]
74
+ d_prime = self.D[l] * (1 - self.D[l])
75
+ if use_delta_d:
76
+ gradient = -1 / np.log(2) * (self.Z[l] * d_prime + self.delta_D[l])
77
+ else:
78
+ gradient = -1 / np.log(2) * (self.Z[l] * d_prime)
79
+ dW = torch.matmul(prev_output.t(), gradient) / prev_output.shape[0]
80
+ self.weights[l] = self.weights[l] - learning_rate * dW
81
+ self.biases[l] = self.biases[l] - learning_rate * gradient.mean(dim=0)
82
+
83
+ def initialize_tensors(self, batch_size):
84
+ for l in range(len(self.layer_sizes)):
85
+ self.Z[l] = None
86
+ self.Z_prev[l] = None
87
+ self.D[l] = None
88
+ self.D_prev[l] = None
89
+ self.delta_D[l] = None
90
+ self.entropy[l] = None
91
+ self.entropy_history[l] = []
92
+ self.cosine_history[l] = []
93
+
94
+
95
+ def get_mnist_subset(samples_per_class, data_seed=0):
96
+ """Select N samples per class from MNIST."""
97
+ images_list = []
98
+ targets = mnist_dataset.targets.numpy()
99
+ rng = np.random.RandomState(data_seed)
100
+ for digit in range(10):
101
+ all_indices = np.where(targets == digit)[0]
102
+ rng.shuffle(all_indices)
103
+ indices = all_indices[:samples_per_class]
104
+ for idx in indices:
105
+ img, label = mnist_dataset[idx]
106
+ images_list.append(img)
107
+ images = torch.stack(images_list)
108
+ return images
109
+
110
+
111
+ def run_delta_d_comparison(neurons_str, K, tau, samples_per_class, data_seed):
112
+ try:
113
+ layer_sizes = [int(x.strip()) for x in neurons_str.split(",")]
114
+ except ValueError:
115
+ return None, None, None, None
116
+
117
+ K = int(K)
118
+ samples_per_class = int(samples_per_class)
119
+ data_seed = int(data_seed)
120
+ learning_rate = tau / K
121
+
122
+ inputs = get_mnist_subset(samples_per_class, data_seed)
123
+
124
+ layer_colors = ['#1F77B4', '#FF7F0E', '#2CA02C', '#D62728']
125
+ layer_labels = [f'Layer {l+1}' for l in range(len(layer_sizes))]
126
+
127
+ results = {}
128
+ for use_delta_d in [True, False]:
129
+ torch.manual_seed(42)
130
+ np.random.seed(42)
131
+ model = SKAModel(input_size=784, layer_sizes=layer_sizes, K=K)
132
+ model.initialize_tensors(inputs.size(0))
133
+
134
+ for k in range(K):
135
+ model.forward(inputs)
136
+ if k > 0:
137
+ model.calculate_entropy()
138
+ model.ska_update(inputs, learning_rate, use_delta_d=use_delta_d)
139
+ model.D_prev = [d.clone().detach() if d is not None else None for d in model.D]
140
+ model.Z_prev = [z.clone().detach() if z is not None else None for z in model.Z]
141
+
142
+ results[use_delta_d] = (model.entropy_history, model.cosine_history)
143
+
144
+ figs = []
145
+ for use_delta_d in [True, False]:
146
+ entropy_history, cosine_history = results[use_delta_d]
147
+ label = "With ΔD" if use_delta_d else "Without ΔD"
148
+
149
+ fig1, ax1 = plt.subplots(figsize=(7, 4))
150
+ for l in range(len(layer_sizes)):
151
+ ax1.plot(entropy_history[l], color=layer_colors[l % len(layer_colors)],
152
+ label=layer_labels[l], linewidth=1.5)
153
+ ax1.set_title(f"Entropy Evolution — {label}")
154
+ ax1.set_xlabel("Step Index K")
155
+ ax1.set_ylabel("Entropy")
156
+ ax1.legend(fontsize=8)
157
+ ax1.grid(True)
158
+ fig1.tight_layout()
159
+
160
+ fig2, ax2 = plt.subplots(figsize=(7, 4))
161
+ for l in range(len(layer_sizes)):
162
+ ax2.plot(cosine_history[l], color=layer_colors[l % len(layer_colors)],
163
+ label=layer_labels[l], linewidth=1.5)
164
+ ax2.set_title(f"Cosine Alignment — {label}")
165
+ ax2.set_xlabel("Step Index K")
166
+ ax2.set_ylabel("Cos(θ)")
167
+ ax2.legend(fontsize=8)
168
+ ax2.grid(True)
169
+ fig2.tight_layout()
170
+
171
+ figs.extend([fig1, fig2])
172
+
173
+ # entropy_with, cosine_with, entropy_without, cosine_without
174
+ return figs[0], figs[1], figs[2], figs[3]
175
+
176
+
177
+ with gr.Blocks(title="SKA Entropy Gradient Explorer") as demo:
178
+ gr.Image("logo.png", show_label=False, height=100, container=False)
179
+ gr.Markdown("# SKA Entropy Gradient Explorer")
180
+ gr.Markdown("Compare the entropy and cosine alignment trajectories with and without the ΔD term in the SKA gradient. Same architecture, same data, same weights — only the gradient formulation differs.")
181
+
182
+ with gr.Row():
183
+ with gr.Column(scale=1):
184
+ neurons_input = gr.Textbox(label="Layer sizes (comma-separated)", value="256, 128, 64, 10")
185
+ k_slider = gr.Slider(1, 200, value=50, step=1, label="K (forward steps)")
186
+ tau_slider = gr.Slider(0.1, 0.75, value=0.5, step=0.01, label="Learning budget τ (τ = η·K)")
187
+ samples_slider = gr.Slider(1, 100, value=100, step=1, label="Samples per class")
188
+ seed_slider = gr.Slider(0, 99, value=0, step=1, label="Data seed (shuffle samples)")
189
+ run_btn = gr.Button("Run Comparison", variant="primary")
190
+
191
+ gr.Markdown("---")
192
+ gr.Markdown("### The Two Entropy Gradient Variants")
193
+ gr.Markdown(
194
+ "| Variant | Entropy Gradient ∂H/∂z |\n|---|---|\n"
195
+ "| **With ΔD** | -(1/ln2) [ z·D(1-D) + ΔD ] |\n"
196
+ "| **Without ΔD** | -(1/ln2) [ z·D(1-D) ] |"
197
+ )
198
+
199
+ gr.Markdown("---")
200
+ gr.Markdown("### Reference Paper")
201
+ gr.HTML('<a href="https://arxiv.org/abs/2503.13942v1" target="_blank">arXiv:2503.13942v1</a>')
202
+
203
+ gr.Markdown("""
204
+ **Abstract**
205
+
206
+ We introduce the Structured Knowledge Accumulation (SKA) framework, which reinterprets entropy as a dynamic, layer-wise measure of knowledge alignment in neural networks. Instead of relying on traditional gradient-based optimization, SKA defines entropy in terms of knowledge vectors and their influence on decision probabilities across multiple layers. This formulation naturally leads to the emergence of activation functions such as the sigmoid as a consequence of entropy minimization. Unlike conventional backpropagation, SKA allows each layer to optimize independently by aligning its knowledge representation with changes in decision probabilities. As a result, total network entropy decreases in a hierarchical manner, allowing knowledge structures to evolve progressively. This approach provides a scalable, biologically plausible alternative to gradient-based learning, bridging information theory and artificial intelligence while offering promising applications in resource-constrained and parallel computing environments.
207
+ """)
208
+
209
+ gr.Markdown("---")
210
+ gr.Markdown("### SKA Explorer Suite")
211
+ gr.HTML('<a href="https://huggingface.co/quant-iota" target="_blank">⬅ All Apps</a>')
212
+ gr.Markdown("---")
213
+ gr.Markdown("### About this App")
214
+ gr.Markdown("The ΔD term captures the discrete change in decision probability between two consecutive forward passes. Removing it reduces the gradient to a continuous-like form. This app runs both variants side by side — same weights, same data, same architecture — so the role of ΔD is immediately visible in the entropy and cosine trajectories.")
215
+
216
+ with gr.Column(scale=2):
217
+ gr.Markdown("### With ΔD")
218
+ plot_entropy_with = gr.Plot(label="Entropy — With ΔD")
219
+ plot_cosine_with = gr.Plot(label="Cosine Alignment — With ΔD")
220
+
221
+ with gr.Column(scale=2):
222
+ gr.Markdown("### Without ΔD")
223
+ plot_entropy_without = gr.Plot(label="Entropy — Without ΔD")
224
+ plot_cosine_without = gr.Plot(label="Cosine Alignment — Without ΔD")
225
+
226
+ run_btn.click(
227
+ fn=run_delta_d_comparison,
228
+ inputs=[neurons_input, k_slider, tau_slider, samples_slider, seed_slider],
229
+ outputs=[plot_entropy_with, plot_cosine_with, plot_entropy_without, plot_cosine_without],
230
+ )
231
+
232
+ demo.launch(server_name="0.0.0.0", server_port=7860, 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,4 @@
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ matplotlib
4
+ numpy