brainx-skill 1.0.6 → 1.0.9
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.
- package/README.md +10 -8
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/installation/lib/installer.js +4 -1
- package/manifest.json +6 -1
- package/package.json +8 -2
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
- package/skills/braincell/references/channel-library.md +85 -0
- package/skills/braincell/references/ion-library.md +87 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainmass/SKILL.md +290 -0
- package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
- package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
- package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainmass/references/braintools/cogtask.md +190 -0
- package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
- package/skills/brainmass/references/braintools/metric.md +157 -0
- package/skills/brainmass/references/braintools/optimizer.md +187 -0
- package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
- package/skills/brainmass/references/braintools/surrogate.md +151 -0
- package/skills/brainmass/references/coupling-network-api.md +148 -0
- package/skills/brainmass/references/datasets-api.md +72 -0
- package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
- package/skills/brainmass/references/forward-observation-api.md +131 -0
- package/skills/brainmass/references/horn-task-training.md +199 -0
- package/skills/brainmass/references/modellibrary.md +104 -0
- package/skills/brainmass/references/noiseprocesses.md +121 -0
- package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
- package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
- package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
- package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
- package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
- package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
- package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
- package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
- package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
- package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
- package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
- package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
- package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
- package/skills/brainmass/references/visualization-analysis-api.md +130 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- package/skills/brainstate/SKILL.md +1 -1
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
- package/skills/brainstate/references/collective_model_operations.md +9 -9
- package/skills/brainstate/references/extension_mechanisms.md +12 -1
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
- package/skills/brainstate/references/model-interop-and-migration.md +11 -1
- package/skills/brainstate/references/size-inference-variations.md +11 -0
- package/skills/brainstate/references/state-graph-operations.md +13 -15
- package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
- package/skills/brainx-general-guard/SKILL.md +68 -0
- package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
# BrainEvent custom CPU operators
|
|
2
|
+
|
|
3
|
+
Use this reference when BrainEvent's built-in operations cannot express a CPU computation and the operation should run through Numba or compiled C++ as a JAX-compatible custom call. Open `custom-operators-gpu.md` instead for Numba CUDA, Warp, raw CUDA, Pallas, or Triton.
|
|
4
|
+
|
|
5
|
+
Define output shapes and dtypes statically, construct wrappers outside transformed functions, and validate every custom result against a trusted JAX implementation before measuring performance.
|
|
6
|
+
|
|
7
|
+
## Choose a CPU implementation
|
|
8
|
+
|
|
9
|
+
| Path | Use when | Main constraint |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| Numba CPU | The algorithm has irregular sparse access, sequential loops, or modest problem sizes and should remain Python-authored. | The kernel takes inputs followed by output buffers and writes results in place. |
|
|
12
|
+
| Raw C++ | Existing C++ should be reused or the operation needs compiler-level CPU control. | Declare inputs as `const BE::Tensor` and outputs as non-`const` `BE::Tensor`. |
|
|
13
|
+
|
|
14
|
+
Prefer `numba_kernel()` for one CPU implementation. Use `XLACustomKernel` when the operation also needs named backend dispatch, explicit batching or autodiff rules, or BrainEvent benchmarking.
|
|
15
|
+
|
|
16
|
+
## Prepare the CPU toolchain
|
|
17
|
+
|
|
18
|
+
Install `brainevent[cpu]`, which includes the Numba CPU backend. Raw C++ additionally requires a host compiler such as `g++` or `clang++`.
|
|
19
|
+
|
|
20
|
+
Run `brainevent.print_diagnostics()` before debugging kernel source when Numba or the compiler cannot be found. Treat `ModuleNotFoundError: numba` as a missing CPU extra, not as a kernel implementation failure.
|
|
21
|
+
|
|
22
|
+
## Follow the CPU kernel contract
|
|
23
|
+
|
|
24
|
+
| Contract | Required behavior |
|
|
25
|
+
|---|---|
|
|
26
|
+
| Inputs | Pass runtime arrays before output buffers. Do not mutate an input unless `input_output_aliases` declares the alias. |
|
|
27
|
+
| 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. |
|
|
28
|
+
| Wrapper lifetime | Construct and cache the wrapper at module definition or kernel-generator time, never inside `jax.jit`. |
|
|
29
|
+
| JIT | Call an already-created wrapper inside `jax.jit`; keep output shape and dtype trace-time static. |
|
|
30
|
+
| `vmap` | Set `vmap_method` or define an `XLACustomKernel` batching rule when the default behavior is incorrect or inefficient. |
|
|
31
|
+
| Autodiff | Register JVP and transpose rules when differentiation is required; a compiled forward kernel does not define derivatives automatically. |
|
|
32
|
+
| Verification | Compare shape, dtype, values, and mutation semantics with a JAX reference before benchmarking. |
|
|
33
|
+
|
|
34
|
+
## Write a Numba CPU kernel
|
|
35
|
+
|
|
36
|
+
Use Numba CPU for custom loops and sparse or irregular memory access that does not map cleanly to a massively parallel backend.
|
|
37
|
+
|
|
38
|
+
| API | Description |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `@numba.njit` | Use to compile `kernel(inputs..., outputs...)`; it writes all results into output arrays and returns nothing. |
|
|
41
|
+
| `@numba.njit(parallel=True)` | Use when the outer loop has independent iterations; it enables CPU threading. |
|
|
42
|
+
| `numba.prange(...)` | Use for the independent outer loop; keep dependent inner loops sequential. |
|
|
43
|
+
| `numba_kernel(kernel, outs, *, vmap_method=None, input_output_aliases=None)` | Use to expose the Numba dispatcher to JAX; `outs` is one shape/dtype struct or a sequence for multiple outputs. |
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import brainevent
|
|
47
|
+
import jax
|
|
48
|
+
import jax.numpy as jnp
|
|
49
|
+
import numba
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@numba.njit(parallel=True)
|
|
53
|
+
def add_kernel(x, y, out):
|
|
54
|
+
for i in numba.prange(out.size):
|
|
55
|
+
out[i] = x[i] + y[i]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
n = 512
|
|
59
|
+
add = brainevent.numba_kernel(
|
|
60
|
+
add_kernel,
|
|
61
|
+
outs=jax.ShapeDtypeStruct((n,), jnp.float32),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@jax.jit
|
|
66
|
+
def add_then_scale(x, y):
|
|
67
|
+
result = add(x, y)
|
|
68
|
+
result = result[0] if isinstance(result, tuple) else result
|
|
69
|
+
return result * 2.0
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
x = jnp.arange(n, dtype=jnp.float32)
|
|
73
|
+
y = jnp.ones(n, dtype=jnp.float32)
|
|
74
|
+
actual = add_then_scale(x, y)
|
|
75
|
+
assert jnp.allclose(actual, (x + y) * 2.0)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
For multiple outputs, append all output buffers to the Numba signature and pass matching `ShapeDtypeStruct` values in the same order.
|
|
79
|
+
|
|
80
|
+
## Register a CPU operator
|
|
81
|
+
|
|
82
|
+
`XLACustomKernel` owns one logical primitive and selects a registered implementation for the current platform.
|
|
83
|
+
|
|
84
|
+
| API | Description |
|
|
85
|
+
|---|---|
|
|
86
|
+
| `XLACustomKernel(name, doc=None)` | Use to create a uniquely named custom primitive. |
|
|
87
|
+
| `def_kernel(backend, platform, generator, asdefault=False)` | Use to register a general generator for a named backend and platform; the first backend for a platform becomes its default. |
|
|
88
|
+
| `def_numba_kernel(generator, asdefault=False)` | Use to register a Numba generator for CPU. |
|
|
89
|
+
| `available_backends("cpu")` | Use to list registered CPU backends. |
|
|
90
|
+
| `set_default("cpu", backend)` | Use to select an already-registered CPU backend. |
|
|
91
|
+
| `get_default("cpu")` / `defaults` | Use to inspect the CPU default or all platform defaults. |
|
|
92
|
+
|
|
93
|
+
A generator reads trace-time metadata from keyword arguments and returns the runtime callable:
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
import brainevent
|
|
97
|
+
import jax
|
|
98
|
+
import jax.numpy as jnp
|
|
99
|
+
import numba
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@numba.njit(parallel=True)
|
|
103
|
+
def scale_kernel(x, scale, out):
|
|
104
|
+
for i in numba.prange(out.size):
|
|
105
|
+
out[i] = x[i] * scale[0]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def scale_numba_generator(**kwargs):
|
|
109
|
+
out_spec = kwargs["outs"][0]
|
|
110
|
+
|
|
111
|
+
def run(x, scale):
|
|
112
|
+
result = brainevent.numba_kernel(
|
|
113
|
+
scale_kernel,
|
|
114
|
+
outs=out_spec,
|
|
115
|
+
)(x, scale)
|
|
116
|
+
return result if isinstance(result, tuple) else (result,)
|
|
117
|
+
|
|
118
|
+
return run
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
scale = brainevent.XLACustomKernel("reference_cpu_scale")
|
|
122
|
+
scale.def_numba_kernel(scale_numba_generator)
|
|
123
|
+
|
|
124
|
+
x = jnp.arange(128, dtype=jnp.float32)
|
|
125
|
+
factor = jnp.array([3.0], dtype=jnp.float32)
|
|
126
|
+
out_spec = jax.ShapeDtypeStruct(x.shape, x.dtype)
|
|
127
|
+
actual = scale(x, factor, outs=[out_spec])[0]
|
|
128
|
+
assert jnp.allclose(actual, x * factor[0])
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Do not read runtime array values while constructing the generator. Return a tuple matching flattened `outs`; a direct one-output wrapper may return a bare array, but `XLACustomKernel` lowering uses multiple-result semantics.
|
|
132
|
+
|
|
133
|
+
### Define transformations and benchmarks
|
|
134
|
+
|
|
135
|
+
| API | Description |
|
|
136
|
+
|---|---|
|
|
137
|
+
| `def_batching_rule(rule)` | Use to replace batching with a rule that returns batched outputs and output batch axes. |
|
|
138
|
+
| `register_general_batching()` | Use to restore the default `jax.lax.scan` batching rule; it is general but may be slower than native batching. |
|
|
139
|
+
| `def_jvp_rule(rule)` | Use to define one forward-mode derivative rule. |
|
|
140
|
+
| `def_jvp_rule2(*rules)` | Use to define one tangent contribution per input; pass `None` for zero contributions. |
|
|
141
|
+
| `def_transpose_rule(rule)` | Use to define reverse-mode cotangent propagation. |
|
|
142
|
+
| `def_call(function)` / `call(...)` | Use to register and invoke a high-level call function. |
|
|
143
|
+
| `def_benchmark_data(function)` | Use to register benchmark configurations for a platform. |
|
|
144
|
+
| `benchmark(...)` | Use after registering call and data functions; it compares CPU backends and can validate outputs with `rtol` and `atol`. |
|
|
145
|
+
| `def_tags(*tags)` | Use to attach searchable categories such as `csr`, `binary`, or `mv`. |
|
|
146
|
+
|
|
147
|
+
Do not claim differentiability until JVP and transpose behavior has been tested.
|
|
148
|
+
|
|
149
|
+
## Compile a raw C++ CPU kernel
|
|
150
|
+
|
|
151
|
+
Use raw C++ when existing C++ should be reused or compiler-level control matters more than Python authoring.
|
|
152
|
+
|
|
153
|
+
| API | Description |
|
|
154
|
+
|---|---|
|
|
155
|
+
| `load_cpp_inline(name, cpp_sources, functions=None, **options)` | Use for inline C++; it compiles with the host compiler and returns a `CompiledModule`. Pass function names for auto-detection, a dict for explicit `arg_spec`, or `None` for `// @BE` discovery. |
|
|
156
|
+
| `load_cpp_file(filepath, functions=None, *, name=None, **options)` | Use for one `.cpp` or `.cc` file; it forwards options to `load_cpp_inline()`. |
|
|
157
|
+
| `jax.ffi.ffi_call(target, out_spec, ...)` | Use after registration to call `"<target_prefix>.<function>"` from eager or jitted JAX code. |
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
import brainevent
|
|
161
|
+
import jax
|
|
162
|
+
import jax.numpy as jnp
|
|
163
|
+
|
|
164
|
+
cpp_source = r"""
|
|
165
|
+
#include "brainevent/common.h"
|
|
166
|
+
|
|
167
|
+
void add_one(const BE::Tensor x, BE::Tensor out) {
|
|
168
|
+
const float* input = x.data_ptr<float>();
|
|
169
|
+
float* output = out.data_ptr<float>();
|
|
170
|
+
for (int64_t i = 0; i < x.numel(); ++i) {
|
|
171
|
+
output[i] = input[i] + 1.0f;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
brainevent.load_cpp_inline(
|
|
177
|
+
name="reference_cpu_ops",
|
|
178
|
+
cpp_sources=cpp_source,
|
|
179
|
+
functions=["add_one"],
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
add_one = jax.ffi.ffi_call(
|
|
183
|
+
"reference_cpu_ops.add_one",
|
|
184
|
+
jax.ShapeDtypeStruct((3,), jnp.float32),
|
|
185
|
+
vmap_method="broadcast_all",
|
|
186
|
+
)
|
|
187
|
+
x = jnp.array([1.0, 2.0, 3.0], dtype=jnp.float32)
|
|
188
|
+
assert jnp.allclose(add_one(x), x + 1.0)
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Declare C++ arguments
|
|
192
|
+
|
|
193
|
+
Every compiled function needs an `arg_spec` so BrainEvent can generate the XLA FFI wrapper.
|
|
194
|
+
|
|
195
|
+
| Token | C++ parameter | Use |
|
|
196
|
+
|---|---|---|
|
|
197
|
+
| `"arg"` | `const BE::Tensor` | Mark an input for wrapper generation. |
|
|
198
|
+
| `"ret"` | `BE::Tensor` | Mark a preallocated output written by the function. |
|
|
199
|
+
| `"attr.<name>"` | Inferred scalar type | Pass a scalar keyword attribute whose type is parsed from the C++ signature. |
|
|
200
|
+
| `"attr.<name>:<type>"` | Explicit scalar type | Pass a scalar keyword attribute with an explicit supported type. |
|
|
201
|
+
|
|
202
|
+
Use parameter order `inputs -> outputs -> scalar attributes`. The aliases `"args"`, `"rets"`, and `"attrs.<name>"` normalize to the corresponding tokens.
|
|
203
|
+
|
|
204
|
+
Supported scalar attribute types are:
|
|
205
|
+
|
|
206
|
+
| Token type | C++ type | Python call value |
|
|
207
|
+
|---|---|---|
|
|
208
|
+
| `bool` | `bool` | `True` or `False` |
|
|
209
|
+
| `int8` / `uint8` | `int8_t` / `uint8_t` | `numpy.int8` / `numpy.uint8` |
|
|
210
|
+
| `int16` / `uint16` | `int16_t` / `uint16_t` | `numpy.int16` / `numpy.uint16` |
|
|
211
|
+
| `int32` / `uint32` | `int32_t` / `uint32_t` | `numpy.int32` / `numpy.uint32` |
|
|
212
|
+
| `int64` / `uint64` | `int64_t` / `uint64_t` | `numpy.int64` / `numpy.uint64` |
|
|
213
|
+
| `float32` / `float64` | `float` / `double` | `numpy.float32` / `numpy.float64` |
|
|
214
|
+
| `complex64` / `complex128` | `std::complex<float>` / `std::complex<double>` | `numpy.complex64` / `numpy.complex128` |
|
|
215
|
+
| `float16` / `bfloat16` | `uint16_t` raw bits | Pass a `uint16` bit view and reinterpret it inside C++. |
|
|
216
|
+
|
|
217
|
+
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.
|
|
218
|
+
|
|
219
|
+
`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. If every tensor is `const`, auto-detection cannot find an output.
|
|
220
|
+
|
|
221
|
+
## Use the C++ tensor API
|
|
222
|
+
|
|
223
|
+
Include `"brainevent/common.h"` for `BE::Tensor` and checking macros. Do not include BrainEvent's internal FFI headers.
|
|
224
|
+
|
|
225
|
+
| API | Description |
|
|
226
|
+
|---|---|
|
|
227
|
+
| `tensor.data_ptr()` / `tensor.data_ptr<T>()` | Return the untyped or typed contiguous data pointer. |
|
|
228
|
+
| `tensor.ndim()` | Return the number of dimensions. |
|
|
229
|
+
| `tensor.size(i)` / `tensor.shape(i)` | Return one dimension size. |
|
|
230
|
+
| `tensor.stride(i)` | Return one C-contiguous stride. |
|
|
231
|
+
| `tensor.shape_ptr()` / `tensor.strides_ptr()` | Return pointers to all shape or stride entries. |
|
|
232
|
+
| `tensor.dtype()` | Return the `BE::DType` enum. |
|
|
233
|
+
| `tensor.element_size()` | Return bytes per element. |
|
|
234
|
+
| `tensor.numel()` / `tensor.nbytes()` | Return element count or total byte count. |
|
|
235
|
+
| `tensor.is_contiguous()` | Report whether storage is contiguous. |
|
|
236
|
+
| `dtype_size(dtype)` / `dtype_name(dtype)` | Return a dtype's byte width or readable name. |
|
|
237
|
+
| `BE_CHECK(condition) << message` | Fail with a descriptive runtime message when an invariant is false. |
|
|
238
|
+
| `BE_DISPATCH_FLOATING(...)` | Dispatch over float32 and float64. |
|
|
239
|
+
| `BE_DISPATCH_INTEGRAL(...)` | Dispatch over signed and unsigned integer dtypes. |
|
|
240
|
+
| `BE_DISPATCH_ALL_TYPES(...)` | Dispatch over all numeric floating and integral dtypes. |
|
|
241
|
+
|
|
242
|
+
`BE::DType` represents float16, float32, float64, bfloat16, signed and unsigned integers from 8 through 64 bits, bool, complex64, and complex128.
|
|
243
|
+
|
|
244
|
+
## Configure CPU compilation and caching
|
|
245
|
+
|
|
246
|
+
| Option or API | Description |
|
|
247
|
+
|---|---|
|
|
248
|
+
| `extra_cflags=[...]` | Pass additional host compiler flags. |
|
|
249
|
+
| `extra_ldflags=[...]` | Pass additional linker flags. |
|
|
250
|
+
| `extra_include_paths=[...]` | Add user include directories. |
|
|
251
|
+
| `build_directory=...` | Override the build directory for one load call. |
|
|
252
|
+
| `verbose=True` | Print the compiler command and detailed output. |
|
|
253
|
+
| `force_rebuild=True` | Ignore the cache and compile again. |
|
|
254
|
+
| `auto_register=False` | Compile without automatically registering FFI targets. |
|
|
255
|
+
| `target_prefix=...` | Override the prefix used by automatically registered targets. |
|
|
256
|
+
| `set_cache_dir(path)` / `get_cache_dir()` | Change or inspect the process cache directory. |
|
|
257
|
+
| `clear_cache(name=None)` | Remove all cache entries or only entries for one module; it returns the number removed. |
|
|
258
|
+
|
|
259
|
+
The default cache directory is `~/.cache/brainevent/`; `BRAINEVENT_CACHE_DIR` changes it globally. Cache keys include source, compiler flags, CPU architecture marker, compiler version, and BrainEvent version.
|
|
260
|
+
|
|
261
|
+
Repeated loading of the same cached shared library is safe. Registering a different module under an existing target name raises `KernelRegistrationError`.
|
|
262
|
+
|
|
263
|
+
## Inspect and diagnose CPU kernels
|
|
264
|
+
|
|
265
|
+
| API | Description |
|
|
266
|
+
|---|---|
|
|
267
|
+
| `CompiledModule.path` | Return the loaded shared-library path. |
|
|
268
|
+
| `CompiledModule.function_names` | Return the compiled user function names. |
|
|
269
|
+
| `CompiledModule.get_handler(name)` | Return the `ctypes` FFI handler without the generated `be_` prefix. |
|
|
270
|
+
| `register_ffi_target(target_name, module, func_name, *, platform="cpu")` | Register a compiled CPU handler manually. |
|
|
271
|
+
| `list_registered_targets()` | Return registered FFI target names in sorted order. |
|
|
272
|
+
| `print_diagnostics()` | Print the BrainEvent compilation environment. |
|
|
273
|
+
|
|
274
|
+
| Exception | Meaning |
|
|
275
|
+
|---|---|
|
|
276
|
+
| `KernelToolchainError` | The host compiler is missing or incompatible. |
|
|
277
|
+
| `CompilationError` / `KernelCompilationError` | The toolchain exists but source, types, shapes, or backend constraints prevented compilation. |
|
|
278
|
+
| `KernelRegistrationError` | An FFI target conflicts with a live registration or could not be registered. |
|
|
279
|
+
| `KernelNotAvailableError` | The requested CPU backend is not installed or version-compatible. |
|
|
280
|
+
| `KernelFallbackExhaustedError` | No registered CPU backend can handle the operation. |
|
|
281
|
+
| `KernelExecutionError` | Compilation succeeded but runtime execution failed. |
|
|
282
|
+
|
|
283
|
+
For compilation failures, rerun the load with `verbose=True`, then validate buffer shapes, dtypes, and bounds.
|
|
284
|
+
|
|
285
|
+
## Verify a CPU operator
|
|
286
|
+
|
|
287
|
+
1. Run the kernel eagerly on the smallest meaningful input.
|
|
288
|
+
2. Compare every output with a pure JAX reference, including shape and dtype.
|
|
289
|
+
3. Run the already-created wrapper inside `jax.jit`.
|
|
290
|
+
4. Test `vmap`, JVP, and reverse-mode gradients only when the operation promises them.
|
|
291
|
+
5. Exercise every registered CPU backend with the same fixtures.
|
|
292
|
+
6. Benchmark only after warmup and output blocking.
|
|
293
|
+
|
|
294
|
+
Do not write a custom CPU kernel when a built-in BrainEvent operation already provides the required semantics and maintained backend coverage.
|
|
295
|
+
|
|
296
|
+
## Official sources
|
|
297
|
+
|
|
298
|
+
- [Installation](https://brainx.chaobrain.com/brainevent/getting-started/installation.html)
|
|
299
|
+
- [Custom CPU operators with Numba](https://brainx.chaobrain.com/brainevent/tutorials/custom-operators/01_numba.html)
|
|
300
|
+
- [Custom C++ CPU kernels](https://brainx.chaobrain.com/brainevent/tutorials/custom-operators/04_cpp.html)
|
|
301
|
+
- [Custom-kernel framework API](https://brainx.chaobrain.com/brainevent/reference/apis/operator.html)
|
|
302
|
+
- [`arg_spec` system](https://brainx.chaobrain.com/brainevent/reference/kernels/arg-spec.html)
|
|
303
|
+
- [C++ API](https://brainx.chaobrain.com/brainevent/reference/kernels/cpp-api.html)
|
|
304
|
+
- [Caching](https://brainx.chaobrain.com/brainevent/reference/kernels/caching.html)
|