brainx-skill 1.0.3 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +21 -63
  3. package/{lib → installation/lib}/installer.js +4 -4
  4. package/manifest.json +3 -1
  5. package/package.json +19 -9
  6. package/skills/brainstate/SKILL.md +399 -0
  7. package/skills/brainstate/agents/openai.yaml +4 -0
  8. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +483 -0
  9. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +176 -0
  10. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +199 -0
  11. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +166 -0
  12. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +210 -0
  13. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +450 -0
  14. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +157 -0
  15. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +286 -0
  16. package/skills/brainstate/references/braintools-optimizer-reference.md +133 -0
  17. package/skills/brainstate/references/collective_model_operations.md +195 -0
  18. package/skills/brainstate/references/extension_mechanisms.md +282 -0
  19. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -0
  20. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +217 -0
  21. package/skills/brainstate/references/libraries/solver-library-with-effects.md +85 -0
  22. package/skills/brainstate/references/model-interop-and-migration.md +295 -0
  23. package/skills/brainstate/references/simulation-environment.md +117 -0
  24. package/skills/brainstate/references/size-inference-variations.md +268 -0
  25. package/skills/brainstate/references/state-graph-operations.md +218 -0
  26. package/skills/brainstate/references/state_collections_and_utilities.md +224 -0
  27. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  28. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  29. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  30. package/skills/brainstate/scripts/resnet.py +130 -0
  31. package/skills/brainunit/SKILL.md +287 -0
  32. package/skills/brainunit/references/array-creation.md +158 -0
  33. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  34. package/skills/brainunit/references/array-mechanics.md +165 -0
  35. package/skills/brainunit/references/math-function-library.md +433 -0
  36. package/skills/brainunit/references/physical-constant-library.md +58 -0
  37. package/skills/brainunit/references/prefix-library.md +116 -0
  38. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  39. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  40. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  41. package/skills/brainx-install/SKILL.md +2 -2
  42. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  43. /package/{bin → installation/bin}/brainx.js +0 -0
  44. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  45. /package/{lib → installation/lib}/bundle.js +0 -0
  46. /package/{lib → installation/lib}/cli.js +0 -0
  47. /package/{lib → installation/lib}/constants.js +0 -0
  48. /package/{lib → installation/lib}/hash.js +0 -0
  49. /package/{lib → installation/lib}/paths.js +0 -0
  50. /package/{lib → installation/lib}/prompts.js +0 -0
  51. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,359 @@
1
+ """
2
+ Reference script mirrored from:
3
+ https://brainx.chaobrain.com/brainstate/examples/deep_learning/integrator_rnn.html
4
+
5
+ Purpose:
6
+ Nested full stateful sequence-training reference for synthetic temporal data, a custom
7
+ RNNCell, trainable initial state, ParamState collection, Adam optimization,
8
+ JIT prediction/training steps, gradient update, L2 regularization, epoch loop,
9
+ and evaluation visualization.
10
+ """
11
+
12
+ from typing import Callable
13
+
14
+ import jax
15
+ import jax.numpy as jnp
16
+ import matplotlib.pyplot as plt
17
+ import numpy as np
18
+
19
+ import brainstate
20
+ import braintools
21
+
22
+ # Set random seeds
23
+ np.random.seed(42)
24
+ brainstate.random.seed(42)
25
+
26
+ # Task parameters
27
+ dt = 0.04 # Time step
28
+ num_step = int(1.0 / dt) # Steps per trial (25 steps for 1.0 time unit)
29
+ num_batch = 512 # Batch size
30
+
31
+ # Network parameters
32
+ num_hidden = 100 # Hidden units in RNN
33
+
34
+ # Training parameters
35
+ learning_rate = 0.025
36
+ lr_decay_rate = 0.99975
37
+ l2_reg = 2e-4
38
+ num_epochs = 5
39
+ batches_per_epoch = 500
40
+
41
+ print(f"Configuration:")
42
+ print(f" Sequence length: {num_step} steps")
43
+ print(f" Batch size: {num_batch}")
44
+ print(f" Hidden units: {num_hidden}")
45
+ print(f" Training batches: {num_epochs * batches_per_epoch}")
46
+
47
+
48
+ @brainstate.transform.jit(static_argnums=2)
49
+ def build_inputs_and_targets(mean=0.025, scale=0.01, batch_size=10):
50
+ """Generate integration task data.
51
+
52
+ Args:
53
+ mean: Mean of the random walk bias
54
+ scale: Standard deviation of noise
55
+ batch_size: Number of sequences
56
+
57
+ Returns:
58
+ inputs: [num_step, batch_size, 1] - Input sequences
59
+ targets: [num_step, batch_size, 1] - Target cumulative sums
60
+ """
61
+ # Create initial bias
62
+ sample = brainstate.random.normal(size=(1, batch_size, 1))
63
+ bias = mean * 2.0 * (sample - 0.5)
64
+
65
+ # Generate white noise
66
+ samples = brainstate.random.normal(size=(num_step, batch_size, 1))
67
+ noise_t = scale / dt ** 0.5 * samples
68
+
69
+ # Inputs = bias + noise
70
+ inputs = bias + noise_t
71
+
72
+ # Targets = cumulative sum of inputs
73
+ targets = jnp.cumsum(inputs, axis=0)
74
+
75
+ return inputs, targets
76
+
77
+
78
+ def train_data():
79
+ """Generator for training data."""
80
+ for _ in range(batches_per_epoch * num_epochs):
81
+ yield build_inputs_and_targets(0.025, 0.01, num_batch)
82
+
83
+
84
+ # Generate one batch for visualization
85
+ sample_inputs, sample_targets = build_inputs_and_targets(0.025, 0.01, 3)
86
+
87
+ fig, axes = plt.subplots(1, 2, figsize=(14, 4))
88
+
89
+ # Plot inputs
90
+ for i in range(3):
91
+ axes[0].plot(sample_inputs[:, i, 0], alpha=0.7, label=f'Sample {i+1}')
92
+ axes[0].set_xlabel('Time Step')
93
+ axes[0].set_ylabel('Input Value')
94
+ axes[0].set_title('Input Sequences (Random Walks)', fontweight='bold')
95
+ axes[0].legend()
96
+ axes[0].grid(True, alpha=0.3)
97
+
98
+ # Plot targets
99
+ for i in range(3):
100
+ axes[1].plot(sample_targets[:, i, 0], alpha=0.7, label=f'Sample {i+1}')
101
+ axes[1].set_xlabel('Time Step')
102
+ axes[1].set_ylabel('Cumulative Sum')
103
+ axes[1].set_title('Target Sequences (Integrals)', fontweight='bold')
104
+ axes[1].legend()
105
+ axes[1].grid(True, alpha=0.3)
106
+
107
+ plt.tight_layout()
108
+ plt.show()
109
+
110
+
111
+ class RNNCell(brainstate.nn.Module):
112
+ """Vanilla RNN cell with trainable weights.
113
+
114
+ h_t = activation(W_combined @ [x_t; h_{t-1}] + b)
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ num_in: int,
120
+ num_out: int,
121
+ state_initializer: Callable = braintools.init.ZeroInit(),
122
+ w_initializer: Callable = braintools.init.XavierNormal(),
123
+ b_initializer: Callable = braintools.init.ZeroInit(),
124
+ activation: Callable = brainstate.nn.relu,
125
+ train_state: bool = False, # Whether to train initial state
126
+ ):
127
+ super().__init__()
128
+
129
+ self.num_out = num_out
130
+ self.train_state = train_state
131
+
132
+ # Activation function
133
+ self.activation = activation
134
+
135
+ # Combined weight matrix [input; hidden] -> hidden
136
+ W = braintools.init.param(
137
+ w_initializer,
138
+ (num_in + num_out, num_out)
139
+ )
140
+ b = braintools.init.param(b_initializer, (num_out,))
141
+
142
+ self.W = brainstate.ParamState(W)
143
+ self.b = brainstate.ParamState(b) if b is not None else None
144
+
145
+ # Trainable initial state (optional)
146
+ if train_state:
147
+ self.state2train = brainstate.ParamState(
148
+ braintools.init.ZeroInit()(num_out)
149
+ )
150
+
151
+ self._state_initializer = state_initializer
152
+
153
+ def init_state(self, batch_size=None, **kwargs):
154
+ """Initialize hidden state."""
155
+ self.state = brainstate.HiddenState(
156
+ braintools.init.param(
157
+ self._state_initializer,
158
+ (self.num_out,),
159
+ batch_size
160
+ )
161
+ )
162
+
163
+ # Use trainable initial state if specified
164
+ if self.train_state:
165
+ self.state.value = jnp.repeat(
166
+ jnp.expand_dims(self.state2train.value, axis=0),
167
+ batch_size,
168
+ axis=0
169
+ )
170
+
171
+ def update(self, x):
172
+ """Update RNN cell for one time step.
173
+
174
+ Args:
175
+ x: Input [batch, input_dim]
176
+
177
+ Returns:
178
+ h: New hidden state [batch, hidden_dim]
179
+ """
180
+ # Concatenate input and previous hidden state
181
+ x_combined = jnp.concatenate([x, self.state.value], axis=-1)
182
+
183
+ # Linear transformation
184
+ h = x_combined @ self.W.value
185
+ if self.b is not None:
186
+ h += self.b.value
187
+
188
+ # Apply activation
189
+ h = self.activation(h)
190
+
191
+ # Update state
192
+ self.state.value = h
193
+
194
+ return h
195
+
196
+
197
+ class RNN(brainstate.nn.Module):
198
+ """RNN with recurrent layer and linear output."""
199
+
200
+ def __init__(self, num_in, num_hidden):
201
+ super().__init__()
202
+
203
+ # RNN layer with trainable initial state
204
+ self.rnn = RNNCell(num_in, num_hidden, train_state=True)
205
+
206
+ # Output projection
207
+ self.out = brainstate.nn.Linear(num_hidden, 1)
208
+
209
+ def update(self, x):
210
+ """Process one time step.
211
+
212
+ Args:
213
+ x: Input at current time step
214
+
215
+ Returns:
216
+ output: Prediction at current time step
217
+ """
218
+ # RNN forward pass using >> operator (pipe)
219
+ return x >> self.rnn >> self.out
220
+
221
+
222
+ # Create RNN model
223
+ model = RNN(num_in=1, num_hidden=num_hidden)
224
+
225
+ # Get trainable parameters
226
+ weights = model.states(brainstate.ParamState)
227
+
228
+ # Create optimizer with learning rate decay
229
+ lr_schedule = braintools.optim.ExponentialDecayLR(
230
+ learning_rate,
231
+ decay_steps=1,
232
+ decay_rate=lr_decay_rate
233
+ )
234
+ optimizer = braintools.optim.Adam(lr=lr_schedule, eps=1e-1)
235
+ optimizer.register_trainable_weights(weights)
236
+
237
+ brainstate.nn.count_parameters(model)
238
+
239
+
240
+ @brainstate.transform.jit
241
+ def f_predict(inputs):
242
+ """Make predictions for a sequence.
243
+
244
+ Args:
245
+ inputs: [num_steps, batch_size, 1]
246
+
247
+ Returns:
248
+ predictions: [num_steps, batch_size, 1]
249
+ """
250
+ # Initialize RNN state
251
+ brainstate.nn.init_all_states(model, batch_size=inputs.shape[1])
252
+
253
+ # Process sequence
254
+ return brainstate.transform.for_loop(model.update, inputs)
255
+
256
+
257
+ def f_loss(inputs, targets, l2_reg=2e-4):
258
+ """Compute loss with L2 regularization.
259
+
260
+ Args:
261
+ inputs: Input sequences
262
+ targets: Target sequences
263
+ l2_reg: L2 regularization coefficient
264
+
265
+ Returns:
266
+ loss: Total loss value
267
+ """
268
+ # Get predictions
269
+ predictions = f_predict(inputs)
270
+
271
+ # Mean squared error
272
+ mse = braintools.metric.squared_error(predictions, targets).mean()
273
+
274
+ # L2 regularization on weights
275
+ l2 = 0.0
276
+ for weight in weights.values():
277
+ for leaf in jax.tree.leaves(weight.value):
278
+ l2 += jnp.sum(leaf ** 2)
279
+
280
+ return mse + l2_reg * l2
281
+
282
+
283
+ @brainstate.transform.jit
284
+ def f_train(inputs, targets):
285
+ """Perform one training step.
286
+
287
+ Args:
288
+ inputs: Input sequences
289
+ targets: Target sequences
290
+
291
+ Returns:
292
+ loss: Loss value
293
+ """
294
+ # Compute gradients
295
+ grads, loss = brainstate.transform.grad(
296
+ f_loss,
297
+ weights,
298
+ return_value=True
299
+ )(inputs, targets)
300
+
301
+ # Update parameters
302
+ optimizer.update(grads)
303
+
304
+ return loss
305
+
306
+
307
+ print("Starting training...\n")
308
+
309
+ for i_epoch in range(num_epochs):
310
+ epoch_losses = []
311
+
312
+ for i_batch, (inputs, targets) in enumerate(train_data()):
313
+ if i_batch >= batches_per_epoch:
314
+ break
315
+
316
+ loss = f_train(inputs, targets)
317
+ epoch_losses.append(float(loss))
318
+
319
+ if (i_batch + 1) % 100 == 0:
320
+ avg_loss = np.mean(epoch_losses[-100:])
321
+ print(f'Epoch {i_epoch}, Batch {i_batch + 1:3d}, Loss {avg_loss:.5f}')
322
+
323
+ avg_epoch_loss = np.mean(epoch_losses)
324
+ print(f'\nEpoch {i_epoch} completed: Avg Loss = {avg_epoch_loss:.5f}\n')
325
+
326
+ print("Training complete!")
327
+
328
+ # Generate test data
329
+ brainstate.nn.init_all_states(model, 1)
330
+ x_test, y_test = build_inputs_and_targets(0.025, 0.01, 1)
331
+ predictions = f_predict(x_test)
332
+
333
+ print(f"Test data generated:")
334
+ print(f" Input shape: {x_test.shape}")
335
+ print(f" Target shape: {y_test.shape}")
336
+ print(f" Prediction shape: {predictions.shape}")
337
+
338
+ plt.figure(figsize=(12, 5))
339
+
340
+ # Convert to numpy for plotting
341
+ y_true = np.asarray(y_test[:, 0]).flatten()
342
+ y_pred = np.asarray(predictions[:, 0]).flatten()
343
+ time_steps = np.arange(len(y_true))
344
+
345
+ # Plot ground truth and predictions
346
+ plt.plot(time_steps, y_true, 'b-', linewidth=2, label='Ground Truth', alpha=0.7)
347
+ plt.plot(time_steps, y_pred, 'r--', linewidth=2, label='RNN Prediction', alpha=0.7)
348
+
349
+ plt.xlabel('Time Step', fontsize=12)
350
+ plt.ylabel('Cumulative Value', fontsize=12)
351
+ plt.title('RNN Integration Task Performance', fontsize=14, fontweight='bold')
352
+ plt.legend(fontsize=11)
353
+ plt.grid(True, alpha=0.3)
354
+ plt.tight_layout()
355
+ plt.show()
356
+
357
+ # Compute final error
358
+ mse = np.mean((y_true - y_pred) ** 2)
359
+ print(f"\nTest MSE: {mse:.6f}")
@@ -0,0 +1,52 @@
1
+ """LIFNeuron state-management reference.
2
+
3
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/core/01_state_and_pytrees.html
4
+ """
5
+
6
+ import jax.numpy as jnp
7
+ import brainstate
8
+
9
+
10
+ class LIFNeuron(brainstate.nn.Module):
11
+ """Leaky Integrate-and-Fire neuron model."""
12
+
13
+ def __init__(self, n_neurons, tau=10.0, V_th=1.0, V_reset=0.0):
14
+ super().__init__()
15
+ self.tau = tau
16
+ self.V_th = V_th
17
+ self.V_reset = V_reset
18
+
19
+ # Hidden state: membrane potential (evolves continuously)
20
+ self.V = brainstate.HiddenState(jnp.full(n_neurons, V_reset))
21
+
22
+ # Short-term state: refractory period counter
23
+ self.t_last_spike = brainstate.ShortTermState(jnp.full(n_neurons, -1e7))
24
+
25
+ # Parameters: input weights
26
+ self.w_in = brainstate.ParamState(brainstate.random.randn(n_neurons, n_neurons) * 0.1)
27
+
28
+ def __call__(self, I_ext, t):
29
+ # Membrane potential dynamics
30
+ dV = (-self.V.value + I_ext) / self.tau
31
+ self.V.value = self.V.value + dV
32
+
33
+ # Spike generation
34
+ spike = self.V.value >= self.V_th
35
+
36
+ # Reset
37
+ self.V.value = jnp.where(spike, self.V_reset, self.V.value)
38
+ self.t_last_spike.value = jnp.where(spike, t, self.t_last_spike.value)
39
+
40
+ return spike
41
+
42
+ # Create and test the neuron
43
+ neuron = LIFNeuron(n_neurons=5)
44
+ print("Initial state:")
45
+ print(f"V: {neuron.V.value}")
46
+
47
+ # Simulate
48
+ for t in range(20):
49
+ I_ext = jnp.ones(5) * 0.2 # External current
50
+ spikes = neuron(I_ext, t)
51
+ if jnp.any(spikes):
52
+ print(f"t={t}: Spikes at neurons {jnp.where(spikes)[0]}")
@@ -0,0 +1,73 @@
1
+ """ModernCNN composition and fit-mode forward-pass reference.
2
+
3
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/core/04_activations_and_normalization.html
4
+ """
5
+
6
+ import brainstate
7
+ import brainunit as u
8
+
9
+
10
+ class ModernCNN(brainstate.nn.Module):
11
+ """CNN with modern activations and normalization."""
12
+
13
+ def __init__(self, num_classes=10):
14
+ super().__init__()
15
+
16
+ # Block 1: Conv + BatchNorm + GELU
17
+ self.conv1 = brainstate.nn.Conv2d((32, 32, 3), out_channels=64, kernel_size=(3, 3), padding='SAME')
18
+ self.bn1 = brainstate.nn.BatchNorm2d((32, 32, 64))
19
+ self.act1 = brainstate.nn.GELU()
20
+ self.pool1 = brainstate.nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
21
+
22
+ # Block 2
23
+ self.conv2 = brainstate.nn.Conv2d((16, 16, 64), out_channels=128, kernel_size=(3, 3), padding='SAME')
24
+ self.bn2 = brainstate.nn.BatchNorm2d((16, 16, 128))
25
+ self.act2 = brainstate.nn.GELU()
26
+ self.pool2 = brainstate.nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), in_size=self.bn2.out_size)
27
+
28
+ # Classifier
29
+ self.fc1 = brainstate.nn.Linear((128 * 8 * 8,), (256,))
30
+ self.ln = brainstate.nn.LayerNorm((256,))
31
+ self.act3 = brainstate.nn.GELU()
32
+ self.dropout = brainstate.nn.Dropout(prob=0.5)
33
+ self.fc2 = brainstate.nn.Linear((256,), (num_classes,))
34
+
35
+ def update(self, x):
36
+ # Block 1
37
+ x = self.conv1(x)
38
+ x = self.bn1(x)
39
+ x = self.act1(x)
40
+ x = self.pool1(x)
41
+
42
+ # Block 2
43
+ x = self.conv2(x)
44
+ x = self.bn2(x)
45
+ x = self.act2(x)
46
+ x = self.pool2(x)
47
+
48
+ # Classifier
49
+ x = u.math.flatten(x, start_axis=1)
50
+ x = self.fc1(x)
51
+ x = self.ln(x)
52
+ x = self.act3(x)
53
+ x = self.dropout(x)
54
+ x = self.fc2(x)
55
+
56
+ return x
57
+
58
+ # Create and test
59
+ brainstate.random.seed(0)
60
+ model = ModernCNN(num_classes=10)
61
+
62
+ # Forward pass
63
+ x = brainstate.random.randn(4, 32, 32, 3) # 4 images
64
+ with brainstate.environ.context(fit=True) as env:
65
+ logits = model(x)
66
+
67
+ print("Modern CNN with GELU + BatchNorm + LayerNorm:")
68
+ print(model)
69
+ print()
70
+ print("Input:", x.shape)
71
+ print("Output:", logits.shape)
72
+ print()
73
+ print("Logits:", logits[0])
@@ -0,0 +1,130 @@
1
+ """Residual connections and dynamic child registration for BrainState Modules.
2
+
3
+ Source: https://brainx.chaobrain.com/brainstate/tutorials/core/02_modules_and_graph.html
4
+ Role: Mirrors the tutorial's custom helpers and ``ResidualBlock``/``ResNet``
5
+ example as a standalone script.
6
+ """
7
+
8
+ import brainstate
9
+ import jax.numpy as jnp
10
+
11
+
12
+ class Linear(brainstate.nn.Module):
13
+ """A linear transformation: y = W @ x + b"""
14
+
15
+ def __init__(self, in_features, out_features, use_bias=True):
16
+ super().__init__()
17
+
18
+ self.in_features = in_features
19
+ self.out_features = out_features
20
+ self.use_bias = use_bias
21
+
22
+ # Initialize weight with Xavier/Glorot initialization
23
+ std = jnp.sqrt(2.0 / (in_features + out_features))
24
+ self.weight = brainstate.ParamState(
25
+ brainstate.random.randn(in_features, out_features) * std
26
+ )
27
+
28
+ # Initialize bias to zero
29
+ if use_bias:
30
+ self.bias = brainstate.ParamState(jnp.zeros(out_features))
31
+
32
+ def update(self, x):
33
+ """Forward pass.
34
+
35
+ Args:
36
+ x: Input tensor of shape (..., in_features)
37
+
38
+ Returns:
39
+ Output tensor of shape (..., out_features)
40
+ """
41
+ out = x @ self.weight.value
42
+ if self.use_bias:
43
+ out = out + self.bias.value
44
+ return out
45
+
46
+ def __repr__(self):
47
+ return f"Linear(in_features={self.in_features}, out_features={self.out_features}, use_bias={self.use_bias})"
48
+
49
+
50
+ class LeakyReLU(brainstate.nn.Module):
51
+ """Leaky ReLU activation: y = max(alpha * x, x)"""
52
+
53
+ def __init__(self, negative_slope=0.01):
54
+ super().__init__()
55
+ self.negative_slope = negative_slope
56
+
57
+ def update(self, x):
58
+ return jnp.where(x > 0, x, self.negative_slope * x)
59
+
60
+ def __repr__(self):
61
+ return f"LeakyReLU(negative_slope={self.negative_slope})"
62
+
63
+
64
+ class ResidualBlock(brainstate.nn.Module):
65
+ """Residual block: y = F(x) + x"""
66
+
67
+ def __init__(self, dim):
68
+ super().__init__()
69
+
70
+ # Two linear layers with activation in between
71
+ self.linear1 = Linear(dim, dim)
72
+ self.activation = LeakyReLU(0.0)
73
+ self.linear2 = Linear(dim, dim)
74
+
75
+ def update(self, x):
76
+ # Compute residual
77
+ residual = x
78
+
79
+ # Forward through layers
80
+ out = self.linear1(x)
81
+ out = self.activation(out)
82
+ out = self.linear2(out)
83
+
84
+ # Add residual
85
+ return out + residual
86
+
87
+
88
+ class ResNet(brainstate.nn.Module):
89
+ """Simple ResNet with multiple residual blocks."""
90
+
91
+ def __init__(self, input_dim, hidden_dim, output_dim, n_blocks=3):
92
+ super().__init__()
93
+
94
+ # Input projection
95
+ self.input_proj = Linear(input_dim, hidden_dim)
96
+
97
+ # Residual blocks
98
+ self.blocks = []
99
+ for i in range(n_blocks):
100
+ block = ResidualBlock(hidden_dim)
101
+ setattr(self, f"block_{i}", block)
102
+ self.blocks.append(block)
103
+
104
+ # Output projection
105
+ self.output_proj = Linear(hidden_dim, output_dim)
106
+
107
+ def update(self, x):
108
+ # Project to hidden dimension
109
+ x = self.input_proj(x)
110
+
111
+ # Pass through residual blocks
112
+ for block in self.blocks:
113
+ x = block(x)
114
+
115
+ # Project to output
116
+ x = self.output_proj(x)
117
+ return x
118
+
119
+
120
+ # Create ResNet
121
+ brainstate.random.seed(0)
122
+ resnet = ResNet(input_dim=10, hidden_dim=32, output_dim=5, n_blocks=3)
123
+
124
+ # Forward pass
125
+ x = brainstate.random.randn(10)
126
+ y = resnet(x)
127
+
128
+ print("ResNet:")
129
+ print(resnet)
130
+ print(f"\nOutput shape: {y.shape}")