brainx-skill 1.0.3 → 1.0.8

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 (117) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -64
  3. package/adapters/gemini.js +7 -0
  4. package/adapters/opencode.js +7 -0
  5. package/adapters/windsurf.js +7 -0
  6. package/{lib → installation/lib}/installer.js +8 -5
  7. package/manifest.json +7 -1
  8. package/package.json +25 -10
  9. package/skills/braincell/SKILL.md +182 -0
  10. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  11. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
  12. package/skills/braincell/references/channel-library.md +170 -0
  13. package/skills/braincell/references/ion-library.md +154 -0
  14. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  15. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  16. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  17. package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
  18. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  19. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  20. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  21. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
  22. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  23. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  24. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  25. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  26. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  27. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  28. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  29. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  30. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  31. package/skills/brainevent/SKILL.md +268 -0
  32. package/skills/brainevent/references/connectivity-variants.md +312 -0
  33. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  34. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  35. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  36. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  37. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  38. package/skills/brainevent/references/sparse-formats.md +182 -0
  39. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  40. package/skills/brainpy-state/SKILL.md +232 -0
  41. package/skills/brainpy-state/references/array-creation.md +158 -0
  42. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  43. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  44. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  45. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  46. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  47. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  48. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  49. package/skills/brainpy-state/references/component-selection.md +273 -0
  50. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  51. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  52. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  53. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  54. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  55. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  62. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  63. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  64. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  65. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  66. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  67. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  68. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  69. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  70. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  71. package/skills/brainstate/SKILL.md +399 -0
  72. package/skills/brainstate/agents/openai.yaml +4 -0
  73. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
  75. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
  76. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  77. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
  78. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
  79. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
  80. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
  81. package/skills/brainstate/references/collective_model_operations.md +195 -0
  82. package/skills/brainstate/references/extension_mechanisms.md +293 -0
  83. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
  84. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
  85. package/skills/brainstate/references/model-interop-and-migration.md +305 -0
  86. package/skills/brainstate/references/simulation-environment.md +117 -0
  87. package/skills/brainstate/references/size-inference-variations.md +279 -0
  88. package/skills/brainstate/references/state-graph-operations.md +216 -0
  89. package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
  90. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  91. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  92. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  93. package/skills/brainstate/scripts/resnet.py +130 -0
  94. package/skills/brainunit/SKILL.md +287 -0
  95. package/skills/brainunit/references/array-creation.md +158 -0
  96. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  97. package/skills/brainunit/references/array-mechanics.md +165 -0
  98. package/skills/brainunit/references/math-function-library.md +433 -0
  99. package/skills/brainunit/references/physical-constant-library.md +58 -0
  100. package/skills/brainunit/references/prefix-library.md +116 -0
  101. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  102. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  103. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  104. package/skills/brainx-general-guard/SKILL.md +153 -0
  105. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  106. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  107. package/skills/brainx-install/SKILL.md +2 -2
  108. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  109. /package/{bin → installation/bin}/brainx.js +0 -0
  110. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  111. /package/{lib → installation/lib}/bundle.js +0 -0
  112. /package/{lib → installation/lib}/cli.js +0 -0
  113. /package/{lib → installation/lib}/constants.js +0 -0
  114. /package/{lib → installation/lib}/hash.js +0 -0
  115. /package/{lib → installation/lib}/paths.js +0 -0
  116. /package/{lib → installation/lib}/prompts.js +0 -0
  117. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,468 @@
1
+ # BrainEvent custom GPU operators
2
+
3
+ Use this reference when BrainEvent's built-in operations cannot express a GPU computation and the operation should run through Numba CUDA, Warp, raw CUDA, Pallas, or Triton as a JAX-compatible custom call. Open `custom-operators-cpu.md` instead for Numba CPU or raw C++.
4
+
5
+ Define output shapes and dtypes statically, construct wrappers outside transformed functions, launch work on the XLA-managed stream, and validate every result against a trusted JAX implementation before measuring performance.
6
+
7
+ ## Choose a GPU implementation
8
+
9
+ | Path | Use when | Main constraint |
10
+ |---|---|---|
11
+ | Numba CUDA single kernel | One launch needs CUDA thread, block, shared-memory, or synchronization control from Python. | Specify either `grid` plus `block`, or `launch_dims`. |
12
+ | Numba CUDA callable | The operation requires multiple launches, temporary device buffers, or GPU orchestration from Python. | The callable receives all inputs, all outputs, then the XLA stream; zero-dimensional inputs are unsupported. |
13
+ | Warp | GPU authoring should remain Python-like and benefit from Warp types or atomic operations. | Use an in/out buffer and atomics for scatter accumulation. |
14
+ | Raw CUDA | Existing CUDA C++ should be reused or the operation needs full `nvcc`, launch, and compiler control. | Include `<cuda_runtime.h>`, accept the XLA stream, and launch on that stream. |
15
+ | Pallas or Triton registration | An existing Pallas or Triton kernel should participate in BrainEvent dispatch. | BrainEvent provides registration hooks, not package-specific authoring tutorials for these languages. |
16
+
17
+ Prefer a direct wrapper for one GPU implementation. Use `XLACustomKernel` when backend selection, CPU fallback, transformation rules, or cross-backend benchmarking belongs to the operation's contract.
18
+
19
+ ## Prepare the GPU toolchain
20
+
21
+ | Path | Requirement |
22
+ |---|---|
23
+ | Numba CUDA | Install `brainevent[cuda12]` or `brainevent[cuda13]` plus `numba`, and use an NVIDIA GPU with a working driver. |
24
+ | Warp | Install `brainevent[cuda12]` or `brainevent[cuda13]` plus `warp-lang`, and use an NVIDIA GPU with a working driver. |
25
+ | Raw CUDA | Install `brainevent[cuda12]` or `brainevent[cuda13]`, then provide an NVIDIA driver and a compatible host C++ compiler; the JAX CUDA packages supply `nvcc`, CUDA headers, and runtime libraries. |
26
+
27
+ Run `brainevent.print_diagnostics()` before debugging source when a compiler or backend cannot be found. Treat `ModuleNotFoundError` for Numba or Warp as a missing optional dependency, not as a kernel implementation failure.
28
+
29
+ ## Follow the GPU kernel contract
30
+
31
+ | Contract | Required behavior |
32
+ |---|---|
33
+ | Inputs | Pass runtime arrays before output buffers. Do not mutate an input unless `input_output_aliases` declares the alias. |
34
+ | Outputs | Declare every output with `jax.ShapeDtypeStruct`; write into its output buffer. An `XLACustomKernel` callable must return one result per flattened output specification, as a tuple even for one output. |
35
+ | Stream | Launch every Numba CUDA or raw CUDA operation on the XLA-managed stream; do not create an unrelated stream. |
36
+ | Wrapper lifetime | Construct and cache the wrapper at module definition or kernel-generator time, never inside `jax.jit`. |
37
+ | JIT | Call an already-created wrapper inside `jax.jit`; keep output shape and dtype trace-time static. |
38
+ | `vmap` | Set `vmap_method` or define an `XLACustomKernel` batching rule when the default behavior is incorrect or inefficient. |
39
+ | Autodiff | Register JVP and transpose rules when differentiation is required; a compiled forward kernel does not define derivatives automatically. |
40
+ | Verification | Compare shape, dtype, values, and mutation semantics with a JAX reference before benchmarking. |
41
+
42
+ ## Write a Numba CUDA kernel
43
+
44
+ Use `numba_cuda_kernel()` for one launch and `numba_cuda_callable()` for a multi-launch pipeline or temporary device storage.
45
+
46
+ | API | Description |
47
+ |---|---|
48
+ | `@cuda.jit` | Use to compile a GPU kernel; obtain thread indices with `cuda.grid(ndim)`, bounds-check them, and write outputs in place. |
49
+ | `numba_cuda_kernel(kernel, outs, *, grid=None, block=None, launch_dims=None, threads_per_block=256, shared_mem=0, vmap_method=None, input_output_aliases=None)` | Use for one CUDA launch. Supply `grid` with `block`, or use `launch_dims` for automatic decomposition; the forms are mutually exclusive. |
50
+ | `numba_cuda_callable(func, outs, *, vmap_method=None, input_output_aliases=None)` | Use for a Python callable that launches multiple kernels or allocates temporary device memory; its final argument is the XLA-managed Numba CUDA stream. |
51
+
52
+ ```python
53
+ import brainevent
54
+ import jax
55
+ import jax.numpy as jnp
56
+ from numba import cuda
57
+
58
+
59
+ @cuda.jit
60
+ def threshold_kernel(values, threshold, spikes):
61
+ i = cuda.grid(1)
62
+ if i < values.size:
63
+ spikes[i] = values[i] >= threshold[0]
64
+
65
+
66
+ n = 1024
67
+ detect_spikes = brainevent.numba_cuda_kernel(
68
+ threshold_kernel,
69
+ outs=jax.ShapeDtypeStruct((n,), jnp.bool_),
70
+ launch_dims=n,
71
+ threads_per_block=256,
72
+ )
73
+
74
+ values = jnp.linspace(-1.0, 1.0, n, dtype=jnp.float32)
75
+ threshold = jnp.array([0.25], dtype=jnp.float32)
76
+ spikes = detect_spikes(values, threshold)
77
+ assert jnp.array_equal(spikes, values >= threshold[0])
78
+ ```
79
+
80
+ Use explicit `grid` and `block` for fine launch control. Use `launch_dims=n` or `launch_dims=(m, n)` for automatic one- or multi-dimensional decomposition. Prefer block sizes that are multiples of 32.
81
+
82
+ ### Launch multiple Numba CUDA kernels
83
+
84
+ The callable receives all input buffers, all output buffers, then the XLA stream:
85
+
86
+ ```python
87
+ import brainevent
88
+ import jax
89
+ import jax.numpy as jnp
90
+ from numba import cuda
91
+
92
+
93
+ @cuda.jit
94
+ def square_kernel(x, temp):
95
+ i = cuda.grid(1)
96
+ if i < x.size:
97
+ temp[i] = x[i] * x[i]
98
+
99
+
100
+ @cuda.jit
101
+ def sqrt_kernel(temp, out):
102
+ import math
103
+
104
+ i = cuda.grid(1)
105
+ if i < out.size:
106
+ out[i] = math.sqrt(temp[i])
107
+
108
+
109
+ def absolute_value(x, out, stream):
110
+ n = x.shape[0]
111
+ threads = 256
112
+ blocks = (n + threads - 1) // threads
113
+ temp = cuda.device_array(n, dtype=x.dtype)
114
+ square_kernel[blocks, threads, stream](x, temp)
115
+ sqrt_kernel[blocks, threads, stream](temp, out)
116
+
117
+
118
+ n = 512
119
+ absolute = brainevent.numba_cuda_callable(
120
+ absolute_value,
121
+ outs=jax.ShapeDtypeStruct((n,), jnp.float32),
122
+ )
123
+ x = jnp.linspace(-5.0, 5.0, n, dtype=jnp.float32)
124
+ assert jnp.allclose(absolute(x), jnp.abs(x))
125
+ ```
126
+
127
+ Do not pass zero-dimensional arrays to `numba_cuda_callable()`; use a length-one array for scalar runtime values.
128
+
129
+ ## Write a Warp GPU kernel
130
+
131
+ Use Warp when GPU acceleration should remain Python-authored and the kernel benefits from Warp's array types, launch model, or atomic operations.
132
+
133
+ | API | Description |
134
+ |---|---|
135
+ | `@warp.kernel` | Use to define a GPU kernel with annotated Warp array arguments; the body runs once per `warp.tid()`. |
136
+ | `warp.jax_experimental.jax_kernel(...)` | Use to expose the Warp kernel to JAX. Select `output_dims` for allocated outputs or `in_out_argnames` for caller-provided accumulation buffers. |
137
+ | `jaxinfo_to_warpinfo(info)` | Use to convert `jax.ShapeDtypeStruct` into a Warp array annotation inside a generator. |
138
+ | `jaxtype_to_warptype(dtype)` | Use to convert a JAX or NumPy dtype into a Warp scalar type. |
139
+
140
+ ```python
141
+ import jax.numpy as jnp
142
+ import warp
143
+ from warp.jax_experimental import jax_kernel
144
+
145
+
146
+ @warp.kernel
147
+ def relu_kernel(
148
+ x: warp.array(dtype=warp.float32, ndim=1),
149
+ out: warp.array(dtype=warp.float32, ndim=1),
150
+ ):
151
+ i = warp.tid()
152
+ out[i] = warp.max(x[i], warp.float32(0.0))
153
+
154
+
155
+ n = 1024
156
+ relu = jax_kernel(
157
+ relu_kernel,
158
+ launch_dims=[n],
159
+ num_outputs=1,
160
+ output_dims={"out": (n,)},
161
+ )
162
+
163
+ x = jnp.linspace(-2.0, 2.0, n, dtype=jnp.float32)
164
+ (actual,) = relu(x)
165
+ assert jnp.allclose(actual, jnp.maximum(x, 0.0))
166
+ ```
167
+
168
+ For scatter-add synaptic accumulation, mark the accumulator as in/out and use an atomic update:
169
+
170
+ ```python
171
+ @warp.kernel
172
+ def scatter_add_kernel(
173
+ values: warp.array(dtype=warp.float32, ndim=1),
174
+ targets: warp.array(dtype=warp.int32, ndim=1),
175
+ postsynaptic_current: warp.array(dtype=warp.float32, ndim=1),
176
+ ):
177
+ edge = warp.tid()
178
+ warp.atomic_add(
179
+ postsynaptic_current,
180
+ targets[edge],
181
+ values[edge],
182
+ )
183
+
184
+
185
+ values = jnp.array([0.5, 0.2, 0.7], dtype=jnp.float32)
186
+ targets = jnp.array([0, 1, 0], dtype=jnp.int32)
187
+ scatter = jax_kernel(
188
+ scatter_add_kernel,
189
+ launch_dims=[values.size],
190
+ num_outputs=1,
191
+ in_out_argnames=["postsynaptic_current"],
192
+ )
193
+ (current,) = scatter(
194
+ values,
195
+ targets,
196
+ jnp.zeros(2, dtype=values.dtype),
197
+ )
198
+ assert jnp.allclose(current, jnp.array([1.2, 0.2]))
199
+ ```
200
+
201
+ A plain write is incorrect when several threads may target the same output element.
202
+
203
+ ## Register GPU and multi-backend operators
204
+
205
+ `XLACustomKernel` dispatches one logical primitive to a registered GPU backend and can also use the CPU implementation defined in `custom-operators-cpu.md` as a fallback.
206
+
207
+ | API | Description |
208
+ |---|---|
209
+ | `XLACustomKernel(name, doc=None)` | Use to create a uniquely named custom primitive. |
210
+ | `def_kernel(backend, platform, generator, asdefault=False)` | Use to register a general generator for a named backend and platform. |
211
+ | `def_numba_cuda_kernel(generator, asdefault=False)` | Use to register Numba CUDA for GPU. |
212
+ | `def_warp_kernel(generator, asdefault=False)` | Use to register Warp for GPU. |
213
+ | `def_cuda_raw_kernel(generator, asdefault=False)` | Use to register a generator that loads raw CUDA and returns its JAX FFI caller. |
214
+ | `def_pallas_kernel("gpu", generator, asdefault=False)` | Use to register an existing Pallas GPU kernel; the JAX version requirement is checked lazily. |
215
+ | `def_triton_kernel(generator, asdefault=False)` | Use to register an existing Triton GPU kernel. |
216
+ | `def_numba_kernel(generator, asdefault=False)` | Use to add the Numba CPU fallback defined in `custom-operators-cpu.md`. |
217
+ | `available_backends("gpu")` | Use to list registered GPU backends. |
218
+ | `set_default("gpu", backend)` | Use to select an already-registered GPU backend. |
219
+ | `get_default("gpu")` / `defaults` | Use to inspect the GPU default or all platform defaults. |
220
+
221
+ A Warp generator derives its types from trace-time output metadata and returns a tuple-producing runtime callable:
222
+
223
+ ```python
224
+ import brainevent
225
+ import jax
226
+ import jax.numpy as jnp
227
+ import warp
228
+ from warp.jax_experimental import jax_kernel
229
+
230
+
231
+ def relu_warp_generator(**kwargs):
232
+ out_spec = kwargs["outs"][0]
233
+ n = out_spec.shape[0]
234
+ array_type = brainevent.jaxinfo_to_warpinfo(out_spec)
235
+
236
+ @warp.kernel
237
+ def relu_kernel(x: array_type, out: array_type):
238
+ i = warp.tid()
239
+ out[i] = warp.max(x[i], array_type.dtype(0.0))
240
+
241
+ def run(x):
242
+ kernel = jax_kernel(
243
+ relu_kernel,
244
+ launch_dims=[n],
245
+ num_outputs=1,
246
+ output_dims={"out": (n,)},
247
+ )
248
+ return kernel(x)
249
+
250
+ return run
251
+
252
+
253
+ relu = brainevent.XLACustomKernel("reference_gpu_relu")
254
+ relu.def_warp_kernel(relu_warp_generator)
255
+
256
+ x = jnp.linspace(-2.0, 2.0, 256, dtype=jnp.float32)
257
+ out_spec = jax.ShapeDtypeStruct(x.shape, x.dtype)
258
+ actual = relu(x, outs=[out_spec])[0]
259
+ assert jnp.allclose(actual, jnp.maximum(x, 0.0))
260
+ ```
261
+
262
+ Do not read runtime array values while constructing a generator. Return a tuple matching flattened `outs`; Warp's `jax_kernel()` already returns a tuple.
263
+
264
+ ### Define transformations and benchmarks
265
+
266
+ | API | Description |
267
+ |---|---|
268
+ | `def_batching_rule(rule)` | Use to replace batching with a rule that returns batched outputs and output batch axes. |
269
+ | `register_general_batching()` | Use to restore the default `jax.lax.scan` batching rule; it is general but may be slower than native GPU batching. |
270
+ | `def_jvp_rule(rule)` | Use to define one forward-mode derivative rule. |
271
+ | `def_jvp_rule2(*rules)` | Use to define one tangent contribution per input; pass `None` for zero contributions. |
272
+ | `def_transpose_rule(rule)` | Use to define reverse-mode cotangent propagation. |
273
+ | `def_call(function)` / `call(...)` | Use to register and invoke a high-level call function. |
274
+ | `def_benchmark_data(function)` | Use to register benchmark configurations for a platform. |
275
+ | `benchmark(...)` | Use after registering call and data functions; it compares GPU backends and can validate outputs with `rtol` and `atol`. |
276
+ | `def_tags(*tags)` | Use to attach searchable categories such as `csr`, `binary`, or `mv`. |
277
+
278
+ Do not claim differentiability until JVP and transpose behavior has been tested. Benchmark equivalent GPU backends with output comparison enabled before choosing a default.
279
+
280
+ ## Compile a raw CUDA kernel
281
+
282
+ Use raw CUDA when the operation needs full CUDA C++ features, compiler flags, launch control, or an existing `.cu` implementation.
283
+
284
+ | API | Description |
285
+ |---|---|
286
+ | `load_cuda_inline(name, cuda_sources, functions=None, **options)` | Use for inline CUDA; it compiles with `nvcc`, caches the shared library, and registers discovered or explicitly listed functions. |
287
+ | `load_cuda_file(filepath, functions=None, *, name=None, **options)` | Use for one `.cu` file; it forwards options to `load_cuda_inline()`. |
288
+ | `load_cuda_dir(directory, functions=None, *, name=None, file_patterns=None, **options)` | Use to compile matching `.cu` sources from one directory as a module. |
289
+ | `jax.ffi.ffi_call(target, out_spec, ...)` | Use after registration to invoke the compiled target from eager or jitted JAX code. |
290
+
291
+ ```python
292
+ import brainevent
293
+ import jax
294
+ import jax.numpy as jnp
295
+
296
+ cuda_source = r"""
297
+ #include <cuda_runtime.h>
298
+ #include "brainevent/common.h"
299
+
300
+ __global__ void add_kernel(
301
+ const float* x,
302
+ const float* y,
303
+ float* out,
304
+ int64_t n
305
+ ) {
306
+ int64_t i = blockIdx.x * blockDim.x + threadIdx.x;
307
+ if (i < n) out[i] = x[i] + y[i];
308
+ }
309
+
310
+ // @BE vector_add arg arg ret stream
311
+ void vector_add(
312
+ const BE::Tensor x,
313
+ const BE::Tensor y,
314
+ BE::Tensor out,
315
+ int64_t stream
316
+ ) {
317
+ int64_t n = x.numel();
318
+ add_kernel<<<(n + 255) / 256, 256, 0, (cudaStream_t)stream>>>(
319
+ x.data_ptr<float>(),
320
+ y.data_ptr<float>(),
321
+ out.data_ptr<float>(),
322
+ n
323
+ );
324
+ BE_CHECK_KERNEL_LAUNCH();
325
+ }
326
+ """
327
+
328
+ brainevent.load_cuda_inline(
329
+ name="reference_cuda_ops",
330
+ cuda_sources=cuda_source,
331
+ )
332
+
333
+ n = 1024
334
+ add = jax.ffi.ffi_call(
335
+ "reference_cuda_ops.vector_add",
336
+ jax.ShapeDtypeStruct((n,), jnp.float32),
337
+ )
338
+ x = jnp.ones(n, dtype=jnp.float32)
339
+ y = jnp.full(n, 2.0, dtype=jnp.float32)
340
+ assert jnp.allclose(add(x, y), x + y)
341
+ ```
342
+
343
+ Always include `<cuda_runtime.h>`. Put the `stream` token last, accept it as `int64_t`, cast it to `cudaStream_t`, and launch every kernel on that stream.
344
+
345
+ ## Declare CUDA arguments
346
+
347
+ Every raw CUDA function needs an `arg_spec` so BrainEvent can generate the XLA FFI wrapper.
348
+
349
+ | Token | C++ parameter | Use |
350
+ |---|---|---|
351
+ | `"arg"` | `const BE::Tensor` | Mark an input for wrapper generation. |
352
+ | `"ret"` | `BE::Tensor` | Mark a preallocated output written by the function. |
353
+ | `"attr.<name>"` | Inferred scalar type | Pass a scalar keyword attribute whose type is parsed from the C++ signature. |
354
+ | `"attr.<name>:<type>"` | Explicit scalar type | Pass a scalar keyword attribute with an explicit supported type. |
355
+ | `"stream"` | `int64_t` | Pass the CUDA stream handle; place it last. |
356
+
357
+ Use parameter order `inputs -> outputs -> scalar attributes -> stream`. The aliases `"args"`, `"rets"`, `"attrs.<name>"`, and `"ctx.stream"` normalize to the corresponding tokens.
358
+
359
+ Supported scalar attribute types are:
360
+
361
+ | Token type | C++ type | Python call value |
362
+ |---|---|---|
363
+ | `bool` | `bool` | `True` or `False` |
364
+ | `int8` / `uint8` | `int8_t` / `uint8_t` | `numpy.int8` / `numpy.uint8` |
365
+ | `int16` / `uint16` | `int16_t` / `uint16_t` | `numpy.int16` / `numpy.uint16` |
366
+ | `int32` / `uint32` | `int32_t` / `uint32_t` | `numpy.int32` / `numpy.uint32` |
367
+ | `int64` / `uint64` | `int64_t` / `uint64_t` | `numpy.int64` / `numpy.uint64` |
368
+ | `float32` / `float64` | `float` / `double` | `numpy.float32` / `numpy.float64` |
369
+ | `complex64` / `complex128` | `std::complex<float>` / `std::complex<double>` | `numpy.complex64` / `numpy.complex128` |
370
+ | `float16` / `bfloat16` | `uint16_t` raw bits | Pass a `uint16` bit view and reinterpret it inside C++. |
371
+
372
+ Pass scalar attributes to the callable returned by `ffi_call`, not to `ffi_call` itself. Use the explicit token form for pointer types, `__half`, `__nv_bfloat16`, or non-standard type spellings.
373
+
374
+ `const BE::Tensor` marks an input only in wrapper metadata; it does not make the underlying memory read-only. Remove `const` from every tensor the function writes.
375
+
376
+ ## Use the CUDA C++ API
377
+
378
+ Include `<cuda_runtime.h>` and `"brainevent/common.h"`. Do not include BrainEvent's internal FFI headers.
379
+
380
+ | API | Description |
381
+ |---|---|
382
+ | `tensor.data_ptr()` / `tensor.data_ptr<T>()` | Return the untyped or typed contiguous device pointer. |
383
+ | `tensor.ndim()` | Return the number of dimensions. |
384
+ | `tensor.size(i)` / `tensor.shape(i)` | Return one dimension size. |
385
+ | `tensor.stride(i)` | Return one C-contiguous stride. |
386
+ | `tensor.shape_ptr()` / `tensor.strides_ptr()` | Return pointers to all shape or stride entries. |
387
+ | `tensor.dtype()` | Return the `BE::DType` enum. |
388
+ | `tensor.element_size()` | Return bytes per element. |
389
+ | `tensor.numel()` / `tensor.nbytes()` | Return element count or total byte count. |
390
+ | `tensor.is_contiguous()` | Report whether storage is contiguous. |
391
+ | `dtype_size(dtype)` / `dtype_name(dtype)` | Return a dtype's byte width or readable name. |
392
+ | `BE_CHECK(condition) << message` | Fail with a descriptive runtime message when an invariant is false. |
393
+ | `BE_CUDA_CHECK(call)` | Check a CUDA runtime return code. |
394
+ | `BE_CHECK_KERNEL_LAUNCH()` | Check `cudaGetLastError()` after a launch. |
395
+ | `BE_DISPATCH_FLOATING(...)` | Dispatch over float32 and float64. |
396
+ | `BE_DISPATCH_INTEGRAL(...)` | Dispatch over signed and unsigned integer dtypes. |
397
+ | `BE_DISPATCH_ALL_TYPES(...)` | Dispatch over all numeric floating and integral dtypes. |
398
+
399
+ `BE::DType` represents float16, float32, float64, bfloat16, signed and unsigned integers from 8 through 64 bits, bool, complex64, and complex128.
400
+
401
+ ## Configure GPU compilation and caching
402
+
403
+ | Option or API | Description |
404
+ |---|---|
405
+ | `optimization_level=0..3` | Select `-O<n>` for CUDA host and device compilation; the default is 3. Use 0 for source-level debugging. |
406
+ | `use_fast_math=True` | Enable flush-to-zero, approximate division and square root, and fused multiply-add; validate numerical changes before production use. |
407
+ | `extra_cuda_cflags=[...]` | Pass extra `nvcc` flags such as line information, register limits, or PTX assembler diagnostics. |
408
+ | `extra_ldflags=[...]` | Pass additional linker flags. |
409
+ | `extra_include_paths=[...]` | Add user include directories. |
410
+ | `compute_capability=...` | Override automatic GPU architecture detection. |
411
+ | `allow_cuda_graph=True` | Mark targets command-buffer compatible; disable it for host-side replay effects such as dynamic allocation or callbacks. |
412
+ | `build_directory=...` | Override the build directory for one load call. |
413
+ | `verbose=True` | Print the compiler command and detailed output. |
414
+ | `force_rebuild=True` | Ignore the cache and compile again. |
415
+ | `auto_register=False` | Compile without automatically registering FFI targets. |
416
+ | `target_prefix=...` | Override the prefix used by automatically registered targets. |
417
+ | `set_cache_dir(path)` / `get_cache_dir()` | Change or inspect the process cache directory. |
418
+ | `clear_cache(name=None)` | Remove all cache entries or only entries for one module; it returns the number removed. |
419
+
420
+ The default cache directory is `~/.cache/brainevent/`; `BRAINEVENT_CACHE_DIR` changes it globally. Cache keys include source, compiler flags, GPU architecture, compiler version, and BrainEvent version. Optimization and fast-math changes recompile; `allow_cuda_graph` changes registration only.
421
+
422
+ Repeated loading of the same cached shared library is safe. Registering a different module under an existing target name raises `KernelRegistrationError`.
423
+
424
+ ## Inspect and diagnose GPU kernels
425
+
426
+ | API | Description |
427
+ |---|---|
428
+ | `CompiledModule.path` | Return the loaded shared-library path. |
429
+ | `CompiledModule.function_names` | Return the compiled user function names. |
430
+ | `CompiledModule.get_handler(name)` | Return the `ctypes` FFI handler without the generated `be_` prefix. |
431
+ | `register_ffi_target(target_name, module, func_name, *, platform="CUDA")` | Register a compiled CUDA handler manually. |
432
+ | `list_registered_targets()` | Return registered FFI target names in sorted order. |
433
+ | `print_diagnostics()` | Print the BrainEvent compilation environment. |
434
+
435
+ | Exception | Meaning |
436
+ |---|---|
437
+ | `KernelToolchainError` / `CUDANotInstalledError` | The compiler, CUDA installation, driver, or compatible backend is unavailable. |
438
+ | `CompilationError` / `KernelCompilationError` | The toolchain exists but source, types, shapes, or backend constraints prevented compilation. |
439
+ | `KernelRegistrationError` | An FFI target conflicts with a live registration or could not be registered. |
440
+ | `KernelNotAvailableError` | Warp, Pallas, Triton, or another requested GPU backend is unavailable. |
441
+ | `KernelFallbackExhaustedError` | No registered GPU backend can handle the operation. |
442
+ | `KernelExecutionError` | Compilation succeeded but runtime execution failed, such as an invalid memory access or device assertion. |
443
+
444
+ For compilation failures, rerun raw CUDA with `verbose=True` and `optimization_level=0`. For runtime failures, add `BE_CHECK_KERNEL_LAUNCH()`, validate buffer shapes and dtypes, and compare against a CPU or JAX reference.
445
+
446
+ ## Verify a GPU operator
447
+
448
+ 1. Run the kernel on the smallest meaningful input.
449
+ 2. Compare every output with a pure JAX reference, including shape and dtype.
450
+ 3. Run the already-created wrapper inside `jax.jit`.
451
+ 4. Test `vmap`, JVP, and reverse-mode gradients only when the operation promises them.
452
+ 5. Exercise every registered GPU backend with the same fixtures.
453
+ 6. Benchmark after warmup and explicit output blocking.
454
+ 7. Enable fast math or CUDA graphs only after correctness and side-effect constraints pass.
455
+
456
+ Do not write a custom GPU kernel when a built-in BrainEvent operation already provides the required semantics and maintained backend coverage.
457
+
458
+ ## Official sources
459
+
460
+ - [Installation](https://brainx.chaobrain.com/brainevent/getting-started/installation.html)
461
+ - [Custom GPU operators with Numba CUDA](https://brainx.chaobrain.com/brainevent/tutorials/custom-operators/02_numba_cuda.html)
462
+ - [Custom GPU operators with Warp](https://brainx.chaobrain.com/brainevent/tutorials/custom-operators/03_warp.html)
463
+ - [Custom CUDA GPU kernels](https://brainx.chaobrain.com/brainevent/tutorials/custom-operators/05_cuda.html)
464
+ - [Custom-kernel framework API](https://brainx.chaobrain.com/brainevent/reference/apis/operator.html)
465
+ - [`arg_spec` system](https://brainx.chaobrain.com/brainevent/reference/kernels/arg-spec.html)
466
+ - [C++ API](https://brainx.chaobrain.com/brainevent/reference/kernels/cpp-api.html)
467
+ - [Compiler options](https://brainx.chaobrain.com/brainevent/reference/kernels/compiler-options.html)
468
+ - [Caching](https://brainx.chaobrain.com/brainevent/reference/kernels/caching.html)
@@ -0,0 +1,107 @@
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ #
17
+ # Implementation of the EI network from Brunel (1996) with the brainstate package.
18
+ #
19
+ # - Van Vreeswijk, Carl, and Haim Sompolinsky. “Chaos in neuronal networks with balanced
20
+ # excitatory and inhibitory activity.” Science 274.5293 (1996): 1724-1726.
21
+ #
22
+ # Dynamic of membrane potential is given as:
23
+ #
24
+ # $$ \tau \frac {dV_i}{dt} = -(V_i - V_{rest}) + I_i^{ext} + I_i^{net} (t) $$
25
+ #
26
+ # where $I_i^{net}(t)$ represents the synaptic current, which describes the sum of excitatory and inhibitory neurons.
27
+ #
28
+ # $$ I_i^{net} (t) = J_E \sum_{j=1}^{pN_e} \sum_{t_j^\alpha < t} f(t-t_j^\alpha ) - J_I \sum_{j=1}^{pN_i} \sum_{t_j^\alpha < t} f(t-t_j^\alpha )$$
29
+ #
30
+ # where
31
+ #
32
+ # $$ f(t) = \begin{cases} {\rm exp} (-\frac t {\tau_s} ), \quad t \geq 0 \\
33
+ # 0, \quad t < 0 \end{cases} $$
34
+ #
35
+ # Parameters: $J_E = \frac 1 {\sqrt {pN_e}}, J_I = \frac 1 {\sqrt {pN_i}}$
36
+ #
37
+
38
+
39
+ import brainunit as u
40
+ import matplotlib.pyplot as plt
41
+
42
+ import brainpy
43
+ import brainstate
44
+ import braintools
45
+
46
+
47
+ class EINet(brainstate.nn.Module):
48
+ def __init__(self, n_exc, n_inh, prob, JE, JI):
49
+ super().__init__()
50
+ self.n_exc = n_exc
51
+ self.n_inh = n_inh
52
+ self.num = n_exc + n_inh
53
+
54
+ # neurons
55
+ self.N = brainpy.state.LIF(
56
+ n_exc + n_inh,
57
+ V_rest=-52. * u.mV, V_th=-50. * u.mV, V_reset=-60. * u.mV, tau=10. * u.ms,
58
+ V_initializer=braintools.init.Normal(-60., 10., unit=u.mV), spk_reset='soft'
59
+ )
60
+
61
+ # synapses
62
+ self.E = brainpy.state.AlignPostProj(
63
+ comm=brainstate.nn.EventFixedProb(n_exc, self.num, prob, JE),
64
+ syn=brainpy.state.Expon.desc(self.num, tau=2. * u.ms),
65
+ out=brainpy.state.CUBA.desc(),
66
+ post=self.N,
67
+ )
68
+ self.I = brainpy.state.AlignPostProj(
69
+ comm=brainstate.nn.EventFixedProb(n_inh, self.num, prob, JI),
70
+ syn=brainpy.state.Expon.desc(self.num, tau=2. * u.ms),
71
+ out=brainpy.state.CUBA.desc(),
72
+ post=self.N,
73
+ )
74
+
75
+ def update(self, inp):
76
+ spks = self.N.get_spike() != 0.
77
+ self.E(spks[:self.n_exc])
78
+ self.I(spks[self.n_exc:])
79
+ self.N(inp)
80
+ return self.N.get_spike()
81
+
82
+
83
+ # connectivity
84
+ num_exc = 500
85
+ num_inh = 500
86
+ prob = 0.1
87
+ # external current
88
+ Ib = 3. * u.mA
89
+ # excitatory and inhibitory synaptic weights
90
+ JE = 1 / u.math.sqrt(prob * num_exc) * u.mS
91
+ JI = -1 / u.math.sqrt(prob * num_inh) * u.mS
92
+
93
+ # network
94
+ brainstate.environ.set(dt=0.1 * u.ms)
95
+ net = EINet(num_exc, num_inh, prob=prob, JE=JE, JI=JI)
96
+ brainstate.nn.init_all_states(net)
97
+
98
+ # simulation
99
+ times = u.math.arange(0. * u.ms, 1000. * u.ms, brainstate.environ.get_dt())
100
+ spikes = brainstate.transform.for_loop(lambda t: net.update(Ib), times, pbar=brainstate.transform.ProgressBar(10))
101
+
102
+ # visualization
103
+ t_indices, n_indices = u.math.where(spikes)
104
+ plt.scatter(times[t_indices], n_indices, s=1)
105
+ plt.xlabel('Time (ms)')
106
+ plt.ylabel('Neuron index')
107
+ plt.show()