spyx.experimental
Research-stage building blocks that are not part of the stable Spyx surface. Everything here is tested and usable, but the contract is different from the rest of the library.
Stability contract
The APIs in spyx.experimental — and in some cases their numerical
behaviour — may change without a deprecation cycle as the underlying
research matures. Anything you depend on for production or a long-lived
experiment should come from the stable top-level modules
(spyx.nn, spyx.ssm, spyx.phasor,
spyx.nir, spyx.bench, spyx.quant,
spyx.data, spyx.optimize).
The rule of thumb: import experimental things from spyx.experimental so
the dependency is explicit; rely on the top-level modules for stable work.
See Research with Spyx for how things graduate
from here into the core.
What's here
| Symbol | Kind | Notes |
|---|---|---|
spyx.experimental.PSU_LIF |
Neuron | Reset-free parallel LIF. Physically defined in spyx.nn, surfaced here as its supported experimental entry point. |
spyx.experimental.ResonateFire |
Neuron | Complex resonate-and-fire oscillatory neuron. Physically defined in spyx.phasor. |
spyx.experimental.raven |
Module | Routing-slot memory (RavenRSM), spiking sibling (SpikingSlotMemory), SlotRouter, and the make_recall_batch MQAR generator. |
spyx.experimental.compress |
Module | Bit-packed activation storage for memory-efficient BPTT. |
spyx.experimental.stochastic |
Module | Stochastic (Bernoulli-spiking) and parallelizable prototypes: SPSN, StochasticAssociative{LIF,CuBaLIF}, and the sigmoid_bernoulli activations. |
spyx.experimental.hybrid |
Module | The 0+1 hybrid trainer: surrogate gradient + antithetic-NES correction projected orthogonal to the surrogate (hybrid_gradient, make_hybrid_train_step, es_gradient, hybrid_diagnostics), plus the surrogate-steered Self-Guided ES variant (sges_gradient, make_sges_hybrid_train_step) — the surrogate direction is SGES's guiding subspace, so ES is spent on the orthogonal complement at several-fold lower variance. |
spyx.experimental.matfree |
Module | Matmul-free linear primitives — ternary (BitNet: TernaryLinear, TernaryMLP) and shift-add (DeepShift: ShiftAddLinear) layers that replace dense multiplies with accumulations / bit-shifts, plus MatMulFreeBlock, MLGRU, RMSNorm, and the ternary_weights / power_of_two_weights / activation_quant STE helpers. The native train-from-scratch counterpart to the post-training spyx.quant.bitnet_ternary_rules path. |
spyx.experimental.zoo |
Package | Runnable reference recipes keyed by application (control / classification / language) and tagged by training method × architecture (REGISTRY, list_recipes, get). |
spyx.experimental.onnx |
Module | Export a spiking model to ONNX — per-timestep step, or the whole spyx.nn.run loop as a native ONNX Scan/Loop. Conversion deps imported lazily. |
Related research studies live under
research/new/ in the
repository.
Re-exported neurons
These two are physically defined in stable modules and re-exported here so the experimental surface is discoverable in one place.
Bases: Module
Parallel Spiking Unit LIF: a reset-free leaky integrate-and-fire neuron.
.. note::
Experimental. Its supported entry point is
:class:spyx.experimental.PSU_LIF; the API may change without a
deprecation cycle. It is defined here for locality with the other neurons.
A standard :class:LIF subtracts a reset spikes * threshold from the
membrane every step, which couples each timestep to the (nonlinear) spike
of the previous step and forces a strictly sequential O(T) scan.
Dropping the reset turns the membrane into a pure linear leaky integrator,
.. math:: V_t = \beta \, V_{t-1} + x_t ,
which is a first-order associative recurrence and can therefore be
evaluated with :func:jax.lax.associative_scan in O(\log T) parallel
depth on an accelerator. Spikes are a pointwise surrogate threshold applied
to the whole membrane trace, :math:s_t = \sigma(V_t - \text{threshold}).
Removing the reset is a deliberate accuracy/parallelism trade-off: the neuron never depresses after firing, so it can fire on consecutive steps while a well-tuned integration window keeps activity bounded. In exchange the sequence can be scored in logarithmic instead of linear depth.
Two execution modes are provided and are numerically identical:
- :meth:
__call__-- one reset-free timestep(x, V) -> (spikes, V)withV = beta * V + x; a drop-in for :func:spyx.nn.run, :class:Sequential, and NIR, exactly like :class:LIF. - :meth:
parallel-- the whole time-major sequence at once via an associative scan over the leak,O(\log T)depth.
Because both modes use the same clipped beta and the same surrogate,
and :meth:__call__ integrates the input before spiking, scanning
:meth:__call__ over x reproduces :meth:parallel exactly.
Source code in spyx/nn.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | |
__call__(x, V)
One reset-free timestep.
input vector coming from previous layer.
:V: neuron state tensor.
Integrates the input into the membrane (V = beta * V + x, no
reset), then emits a surrogate spike on the updated membrane so that
scanning this method matches :meth:parallel exactly.
Source code in spyx/nn.py
__init__(hidden_shape, beta=None, threshold=1.0, activation=None, *, rngs)
:hidden_shape: Shape of the layer. :beta: decay rate. Scalar if provided, else learnable per-unit init. :threshold: firing threshold. Defaults to 1. :activation: spyx.axn.Axon object determining the surrogate spike.
Source code in spyx/nn.py
parallel(x)
Score a whole time-major sequence with an associative scan.
input with shape
[Time, Batch, ...].
:return: spikes with shape [Time, Batch, ...].
Computes the full membrane trace V_t = beta * V_{t-1} + x_t (with
V_{-1} = 0) via :func:jax.lax.associative_scan over the time axis
in O(\log T) depth, then applies the surrogate spike pointwise.
Source code in spyx/nn.py
Bases: Module
Resonate-and-fire neuron: the complex/oscillatory sibling of PSU_LIF.
.. note::
Experimental. Its supported entry point is
:class:spyx.experimental.ResonateFire; the API may change without a
deprecation cycle. It is defined here for locality with the phasor layers.
A resonate-and-fire neuron carries a complex membrane that behaves as a damped harmonic oscillator. Written reset-free, its subthreshold dynamics are a complex linear recurrence
.. math:: z_t = a \, z_{t-1} + x_t , \qquad a = e^{\,\mathrm{dt}\,(-\lambda + i\,\omega)} ,
with per-unit decay :math:\lambda \ge 0 and angular frequency
:math:\omega. The real input current x_t is injected into the real
part of the membrane. Because there is no reset, the recurrence stays
linear, so exactly like :class:spyx.nn.PSU_LIF it can be evaluated with
:func:jax.lax.associative_scan in :math:O(\log T) parallel depth -- only
now the scan runs over a complex pole a instead of a real leak.
Spikes are emitted by a pointwise surrogate threshold on the real part of
the oscillator, :math:s_t = \sigma(\Re(z_t) - \text{threshold}). The rule
is reset-free so the linear recurrence -- and therefore the parallel scan --
is preserved.
Stability: the pole magnitude is |a| = exp(-dt * lambda). Storing the
decay through a softplus keeps :math:\lambda \ge 0, hence
:math:|a| \le 1 and the oscillation never grows.
Parameters that enter the complex pole (lambda, omega) are stored as
real float32 nnx.Param tensors, mirroring :class:PhasorLinear:
the complex structure appears only in the forward pass, so a stock
optax + jax.grad loop over a real loss trains them without the
Wirtinger-conjugate surprise.
Two execution modes are provided and are numerically identical:
- :meth:
__call__-- one reset-free timestep(x, z) -> (spikes, z)withz = a * z + x; a drop-in for :func:spyx.nn.run/ :class:Sequential. - :meth:
parallel-- the whole time-major sequence at once via an associative scan over the complex pole, :math:O(\log T)depth.
Because both modes use the same pole and surrogate and integrate the input
before spiking, scanning :meth:__call__ over x reproduces
:meth:parallel exactly.
Source code in spyx/phasor.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 | |
a
property
Complex oscillator pole a = exp(dt(-lambda + i*omega)).
The magnitude |a| = exp(-dt * lambda) <= 1 guarantees stability.
decay
property
Effective non-negative decay lambda = softplus(raw_lambda).
__call__(x, z)
One reset-free timestep.
real input current from the previous layer, broadcastable to
z.
:z: complex64 membrane state.
Injects x into the real part of the membrane and advances the
complex recurrence z = a * z + x (no reset), then emits a surrogate
spike on Re(z) so that scanning this method matches :meth:parallel.
Source code in spyx/phasor.py
__init__(hidden_shape, lambda_init=None, omega_init=None, threshold=1.0, dt=1.0, activation=None, *, rngs)
:hidden_shape: Per-unit shape of the layer.
:lambda_init: Membrane decay >= 0. Scalar constant if provided, else
a learnable per-unit initialisation. Stored through softplus so
the effective decay is always non-negative.
:omega_init: Angular frequency of the oscillator. Scalar constant if
provided, else a learnable per-unit initialisation.
:threshold: Real firing threshold on Re(z). Defaults to 1.
:dt: Integration timestep entering the pole exp(dt(-lambda+i*omega)).
:activation: :class:spyx.axn.Axon surrogate spike; defaults to
superspike.
Source code in spyx/phasor.py
initial_state(batch_size)
parallel(x)
Score a whole time-major sequence with an associative scan.
real input with shape
[Time, Batch, ...].
:return: spikes with shape [Time, Batch, ...].
Computes the full complex membrane trace z_t = a * z_{t-1} + x_t
(with z_{-1} = 0) via :func:jax.lax.associative_scan over the time
axis in :math:O(\log T) depth, then applies the surrogate spike
pointwise on Re(z).
Source code in spyx/phasor.py
spyx.experimental.raven
Raven Routing-Slot-Memory (RSM) block for Spyx.
A Flax NNX implementation of the Routing Slot Memory recurrence introduced by Raven (Afzal, Bick, Xing, Cevher, Gu, 2026; "High-recall sequence modeling with sparse memory routing"). Compressed-state recurrent models (a single SSM state with uniform decay) struggle with exact recall: every new token perturbs the whole state, so previously written associations interfere with each other.
Raven's fix is to partition the memory into M independent slots and use a
learned sparse router r_t to write only the selected slots, leaving the
rest untouched (shielded from interference). Writing slot m at step t:
.. math:: S_t = (1 - r_t) \odot S_{t-1} + r_t \odot ( D_t S_{t-1} A_t + U_t )
S_t: slot memory, shape(B, M, d_slot).r_t \in [0, 1]^M: the per-slot router (ideally sparse). Unselected slots (r_t[m] ≈ 0) pass through unchanged; selected slots decay and are written.U_t: the write (a projection of the current input).
The router is "a Mixture-of-Experts for memory". Two reductions are worth remembering (and are exercised by the tests):
- a dense router (
r_tall-ones) recovers a standard gated diagonal SSM, - a one-hot cyclic router recovers sliding-window attention.
Faithful-but-tractable simplification (documented, see
:class:RavenRSM): the per-slot transition is made diagonal — the full
matrix sandwich D_t S_{t-1} A_t is replaced by a per-slot (per-dim) decay
a ⊙ S_{t-1}, so each slot is a gated diagonal recurrence. The full
matrix-sandwich form is deferred. Likewise the recurrence is run with a plain
:func:jax.lax.scan reference (honest baseline); because the per-step transition
is input-dependent through the router gate (1 - r_t), the recurrence is a
per-timestep diagonal linear recurrence and an associative / chunked
associative_scan form is in principle possible (the Raven authors defer it to
a "Part 2"), but is not implemented here.
RavenRSM
Bases: Module
Routing-Slot-Memory recurrent block (diagonal simplification).
Sequence-in / sequence-out, matching the :mod:spyx.ssm interface:
__call__(u: (T, B, d_model)) -> (T, B, d_model).
Per step t the block computes, from u_t:
- a sparse write router
r_t = SlotRouter(u_t) \in [0, 1]^{(B, M)}, - the write
U_t = reshape(W_u u_t) \in (B, M, d_slot),
and updates the slot memory with the diagonal RSM recurrence
.. math:: S_t = (1 - r_t) \odot S_{t-1} + r_t \odot (a \odot S_{t-1} + U_t)
where a = sigmoid(raw_decay) \in (0, 1)^{(M, d_slot)} is a static,
learnable per-slot / per-dim decay (kept in (0, 1) for stability; an
input-dependent / selective decay is a straightforward extension but is not
used here so the dense reduction stays a clean gated diagonal SSM). The
recurrence is evaluated with :func:jax.lax.scan over time.
Readout (y_t): a query-gated read over slots. A learned query
q_t = softmax(W_q u_t) \in (B, M) mixes the slots into a single read
vector read_t = \sum_m q_t[m] S_t[m] \in (B, d_slot), which a linear map
projects back to (B, d_model). This mirrors the routing idea on the read
side: the query key selects which slot(s) to retrieve.
Simplifications (deferred, per the module docstring): (1) the full
matrix-sandwich transition D_t S_{t-1} A_t is replaced by the diagonal
decay a; (2) only a sequential lax.scan is provided — a chunked /
associative-scan form is possible but deferred.
Source code in spyx/experimental/raven.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
decay
property
Effective per-slot / per-dim decay a = sigmoid(raw_decay) in (0, 1).
__call__(u)
Apply the RSM block to a time-major input.
:u: real array of shape (T, B, d_model).
:return: real array of shape (T, B, d_model).
Source code in spyx/experimental/raven.py
initial_state(batch_size)
Return zero slot memory of shape (batch_size, M, d_slot).
step(state, u_t)
One reset-free RSM timestep.
:state: slot memory S_{t-1}, shape (B, M, d_slot).
:u_t: input (B, d_model).
:return: (S_t, y_t) with y_t of shape (B, d_model).
Source code in spyx/experimental/raven.py
SlotRouter
Bases: Module
Learned per-slot write gate r_t = sigmoid(W_r u_t).
A small, reusable submodule (the spiking Raven variant reuses it). Maps an
input of shape (..., d_model) to per-slot gates of shape (..., M) in
[0, 1]. With hard_top_k set, the gate is additionally sparsified to
the k most-active slots per row via a straight-through top-k (forward
is sparse, gradients stay dense); the default (None) is a soft gate.
Design choice: a per-input sigmoid (independent per-slot Bernoulli
logits) is used rather than a softmax so that several slots can be
written at once (a multi-write MoE-for-memory), and so the dense all-ones
reduction is reachable in the limit of large positive logits.
Source code in spyx/experimental/raven.py
__call__(u)
u: (..., d_model) -> gates (..., M) in [0, 1].
SpikingSlotMemory
Bases: Module
Spiking Routing-Slot Memory: a slot memory whose slots are spiking units.
This is the spiking sibling of :class:RavenRSM. It keeps the two ideas that
make Raven a high-recall memory -- a bank of M independent slots and
the same sparse write router -- but replaces each slot's linear
accumulator with the reset-free spiking membrane of
:class:spyx.nn.PSU_LIF: a leaky integrator V \leftarrow \beta V + x that
emits a surrogate spike s = \sigma(V - \text{threshold}). The result is
dual sparsity -- sparse in time (spikes) and sparse in slots
(routing).
The slot membrane V_t has shape (B, M, d_slot). Per step t, from
the input u_t:
- the write router
r_t = SlotRouter(u_t) \in [0, 1]^{(B, M)}(the exact router type reused from :class:RavenRSM--self.routeris a :class:SlotRouter, not a fork), and - the write
U_t = reshape(W_u u_t) \in (B, M, d_slot).
The membrane is then advanced with the routed, reset-free spiking recurrence
.. math:: V_t = (1 - r_t) \odot V_{t-1} + r_t \odot (\beta \odot V_{t-1} + U_t), \qquad s_t = \sigma(V_t - \text{threshold}),
where \beta = sigmoid(raw_beta) \in (0, 1)^{(M, d_slot)} is a static,
learnable per-slot / per-dim leak. Shielding: where r_t[m] = 0 the
update collapses to V_t[m] = V_{t-1}[m] -- the slot's membrane (and hence
its spike) is passed through byte-for-byte unchanged, shielded from
interference exactly as in :class:RavenRSM. Where r_t[m] = 1 the slot
runs a plain :class:spyx.nn.PSU_LIF step V \leftarrow \beta V + U_t.
Output is the raw slot spike train of shape (T, B, M, d_slot) (no
dense readout projection -- the block is a spiking memory; compose a linear
head downstream if real-valued outputs are needed).
Reset-freeness is deliberate: the membrane recurrence stays a first-order
linear map per slot, so -- exactly as documented for :class:spyx.nn.PSU_LIF
-- a chunked / :func:jax.lax.associative_scan parallel form is possible.
Because the per-step transition here is input-dependent through the router
gate (1 - r_t), the associative element is the affine map
V \mapsto A_t V + b_t with A_t = (1 - r_t) + r_t \beta and
b_t = r_t U_t; only the sequential :func:jax.lax.scan reference is
implemented here (an honest baseline), matching :class:RavenRSM.
Reductions (exercised by the tests): a dense router (r_t all-ones)
turns every slot into an independent, always-written
:class:spyx.nn.PSU_LIF -- i.e. a plain bank of spiking leaky integrators
driven by U_t; the routing is what makes it a memory.
Source code in spyx/experimental/raven.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 | |
beta
property
Effective per-slot / per-dim leak beta = sigmoid(raw_beta) in (0, 1).
__call__(u)
Apply the spiking slot memory to a time-major input.
:u: real array of shape (T, B, d_model).
:return: spike train of shape (T, B, M, d_slot).
Source code in spyx/experimental/raven.py
__init__(d_model, n_slots=8, d_slot=None, *, hard_top_k=None, beta_init=0.9, threshold=1.0, activation=None, rngs)
:d_model: Input feature width.
:n_slots: Number of independent memory slots M.
:d_slot: Per-slot membrane width (defaults to d_model).
:hard_top_k: If set, the router keeps only its k most-active slots per
step (straight-through top-k); the default is a soft gate.
:beta_init: Initial per-slot leak in (0, 1) (stored as a logit).
:threshold: Firing threshold on the membrane.
:activation: :class:spyx.axn.Axon surrogate spike; defaults to
superspike (matching :class:spyx.nn.PSU_LIF).
:rngs: NNX PRNG collection.
Source code in spyx/experimental/raven.py
initial_state(batch_size)
Return zero slot membrane of shape (batch_size, M, d_slot).
step(state, u_t)
One reset-free spiking-slot timestep.
:state: slot membrane V_{t-1}, shape (B, M, d_slot).
:u_t: input (B, d_model).
:return: (V_t, s_t) -- the new membrane and the slot spikes of shape
(B, M, d_slot).
Source code in spyx/experimental/raven.py
make_recall_batch(key, *, batch=8, n_pairs=3, n_keys=8, n_values=8)
Generate a multi-query associative-recall (MQAR-style) batch.
Each example is a sequence of n_pairs (key, value) bindings followed
by a single query token equal to one of the presented keys. The target
is the value bound to the queried key — a task compressed-state SSMs fail at
but slot-routed memories solve, because each binding can live in its own
(interference-free) slot.
Tokens are one-hot encoded into d_model = n_keys + n_values dims: key
i -> e_i; value j -> e_{n_keys + j}. The query token reuses
its key's encoding. Sequence length is T = 2 * n_pairs + 1.
PRNG key.
:batch: number of independent examples.
:n_pairs: key/value bindings per example (distinct keys, sampled w/o repl.).
:n_keys: key vocabulary size (must be
>= n_pairs).
:n_values: value vocabulary size.
:return: (u, target) where u is (T, B, d_model) float one-hots
and target is (B,) int32 value ids for the query.
Source code in spyx/experimental/raven.py
spyx.experimental.compress
Bit-packed activation storage for memory-efficient BPTT.
Training spiking networks with backpropagation-through-time is dominated,
memory-wise, by the activations saved for the backward pass. In an SNN the
activations feeding each linear layer are the spikes, which are exactly
{0, 1} valued. A dense op spikes @ weight normally stashes the full
floating-point spikes tensor as its backward residual so it can later form
dW = spikes^T @ g. Storing one bit per spike as a float wastes 8x-32x the
memory it needs.
This module bit-packs that residual with :func:jax.numpy.packbits (8 spikes
per uint8) and unpacks it lazily inside the backward pass. The forward
output and both gradients (w.r.t. weight and spikes) are numerically
identical to the naive spikes @ weight -- we only trade a cheap
unpack-recompute for a large cut in the dominant activation residual.
Correctness relies on the input being exactly binary (values in {0, 1});
:func:packed_spike_dense is only valid for spike tensors, not arbitrary
floats.
The lower half of this module generalises the same idea to quantized and
sparse activations (graded sigma-delta events, ternary, int-N): pack at
bits bits with :func:pack_nbit (bit-plane packing), use
:func:packed_quant_dense for the k-bit BPTT residual, or — when the tensor is
also sparse — store a 1-bit occupancy mask plus only the nonzero codes with
:func:sparse_quant_pack. :func:packing_footprint gives the byte counts and
the density crossover between the dense-k-bit and sparse schemes.
pack_nbit(codes, bits, axis=-1)
Bit-pack an integer-code tensor (values in [0, 2**bits)) along axis.
Generalises :func:pack_spikes (bits=1) to any width by packing each of the
bits bit-planes with :func:jax.numpy.packbits and stacking them on a new
leading axis. Storage is bits/8 bytes/element (a 32/bits x cut vs fp32).
Source code in spyx/experimental/compress.py
pack_spikes(x, axis=-1)
Bit-pack a binary spike tensor along axis.
Mirrors the np.packbits(..., axis=...) convention used by
:mod:spyx.data (which packs along the time axis): every group of 8
consecutive {0, 1} values along axis is packed into a single
uint8, big-endian bit order. If the axis length is not a multiple of
8 the final byte is zero-padded on the low bits, so the original length
must be supplied to :func:unpack_spikes to recover the exact tensor.
:param x: binary tensor (values in {0, 1}); cast to uint8.
:param axis: axis along which to pack (default last).
:return: uint8 tensor with ceil(len/8) entries along axis.
Source code in spyx/experimental/compress.py
packed_quant_dense(acts, weight, bits, step)
acts @ weight with a k-bit-packed backward residual.
The k-bit generalisation of :func:packed_spike_dense: for activations that are
grid-quantised (symmetric uniform grid of spacing step representable in bits
signed levels -- e.g. graded sigma-delta events, ternary, int-N), the backward saves
the bits-bit codes instead of the fp residual (a 32/bits x cut), unpacking
them to reform dW = acts^T @ g exactly. First-order VJP only; exact iff acts
lie on the grid {(c - 2**(bits-1)) * step}.
Source code in spyx/experimental/compress.py
packed_spike_dense(spikes, weight)
spikes @ weight with a bit-packed backward residual.
Forward numerics are a plain matmul over the trailing feature axis of
spikes (shape (..., in)) against weight (shape (in, out)),
yielding (..., out). The custom VJP saves packbits(spikes) -- a
uint8 tensor 8x smaller than spikes would be as bf16/fp -- instead
of the dense activations, unpacking it in the backward pass to form
dW = spikes^T @ g and dspikes = g @ weight^T.
Both first-order gradients equal those of the naive spikes @ weight.
Limitations: valid only when spikes is exactly binary (values in
{0, 1}) -- packing a general float tensor silently binarizes the saved
residual, so the forward stays exact but dW becomes wrong. Only the
first-order VJP is correct; second-order derivatives (grad-of-grad) are not,
since the packed residual is not itself differentiated. Both are fine for
ordinary first-order BPTT, the intended use.
Source code in spyx/experimental/compress.py
packing_footprint(n_elements, bits, density)
Bytes to store n_elements grid-quantised activations at bits bits and the
given nonzero density, under three schemes, plus which one wins.
Schemes: fp32 (4 B/elem), dense_kbit (N*bits/8), and
sparse (mask N/8 + nonzero codes nnz*bits/8). The sparse scheme wins below
the (bits-1)/bits density crossover.
Source code in spyx/experimental/compress.py
sparse_quant_pack(x, bits, step)
Pack a sparse + quantised tensor as (mask_packed, codes_packed, meta).
A 1-bit occupancy mask (packbits of x != 0) plus the nonzero values' bits-bit
codes (:func:pack_nbit). Footprint ceil(N/8) + ceil(nnz*bits/8) bytes, which beats
dense k-bit packing when density nnz/N < (bits-1)/bits. Exact for grid-quantised x.
Eager (uses the dynamic nonzero count) -- for storage / event transmission, not a jit loop.
Source code in spyx/experimental/compress.py
sparse_quant_unpack(mask_packed, codes_packed, meta)
Invert :func:sparse_quant_pack to the dense grid-quantised tensor.
Source code in spyx/experimental/compress.py
unpack_nbit(packed, bits, length, axis=-1)
Invert :func:pack_nbit, recovering integer codes length long on axis.
Source code in spyx/experimental/compress.py
unpack_spikes(packed, length, axis=-1)
Invert :func:pack_spikes, recovering length values along axis.
:param packed: uint8 tensor produced by :func:pack_spikes.
:param length: original (pre-pack) size of axis; trims the zero
padding introduced when length is not a multiple of 8.
:param axis: axis along which the tensor was packed (default last).
:return: uint8 tensor of {0, 1} values, length long on axis.
Source code in spyx/experimental/compress.py
spyx.experimental.stochastic
Experimental stochastic / parallelizable spiking-neuron prototypes.
Stochastic (Bernoulli-spiking) neurons and the SPSN prototype, all built on the
parallel prefix-scan (_pscan) membrane. Research-stage; the promoted,
production reset-free neuron is :class:spyx.experimental.PSU_LIF (in
spyx.nn). See [[SPSN]] (arXiv:2306.12666).
SPSN
Bases: Module
Prototype implementation of Stochastic Parallelizable Spiking Neuron:
https://doi.org/10.48550/arXiv.2306.12666
Source code in spyx/experimental/stochastic.py
beta = nnx.Param(nnx.initializers.truncated_normal(stddev=0.25)(rngs.params(), self.hidden_shape) + 0.5)
instance-attribute
hidden_shape = hidden_shape
instance-attribute
spike = sigmoid_bernoulli(k, threshold)
instance-attribute
threshold = threshold
instance-attribute
__call__(key, x)
Source code in spyx/experimental/stochastic.py
__init__(hidden_shape, threshold=1, k=10, *, rngs)
Source code in spyx/experimental/stochastic.py
StochasticAssociativeCuBaLIF
Bases: Module
Source code in spyx/experimental/stochastic.py
alpha = nnx.Param(nnx.initializers.truncated_normal(stddev=0.25)(rngs.params(), self.hidden_shape) + 0.5)
instance-attribute
beta = nnx.Param(nnx.initializers.truncated_normal(stddev=0.25)(rngs.params(), self.hidden_shape) + 0.5)
instance-attribute
hidden_shape = hidden_shape
instance-attribute
spike = refractory_sigmoid_bernoulli(k, threshold)
instance-attribute
__call__(key, u)
Source code in spyx/experimental/stochastic.py
__init__(hidden_shape, threshold=1, k=100, *, rngs)
Source code in spyx/experimental/stochastic.py
StochasticAssociativeLIF
Bases: Module
Source code in spyx/experimental/stochastic.py
beta = nnx.Param(nnx.initializers.truncated_normal(stddev=0.25)(rngs.params(), self.hidden_shape) + 0.5)
instance-attribute
hidden_shape = hidden_shape
instance-attribute
spike = sigmoid_bernoulli(k, threshold)
instance-attribute
threshold = threshold
instance-attribute
__call__(key, x)
__init__(hidden_shape, threshold=1, k=100, spike=True, *, rngs)
Source code in spyx/experimental/stochastic.py
refractory_sigmoid_bernoulli(k=50, threshold=1)
Source code in spyx/experimental/stochastic.py
sigmoid_bernoulli(k=10, threshold=1.0, max_prob=0.8)
Source code in spyx/experimental/stochastic.py
spyx.experimental.hybrid
Surrogate-gradient descent corrected by an orthogonalised evolutionary term. See Surrogate gradients & Gaussian smoothing for the theory and Training methods for where it fits.
Hybrid surrogate-gradient / evolutionary training for spiking networks.
.. note::
Experimental. Unstable API — may change without a deprecation cycle.
Import it as from spyx.experimental.hybrid import hybrid_gradient (the
:mod:spyx.experimental.hybrid submodule is importable without touching the
package __init__).
The idea
Surrogate-gradient descent through a spiking network is cheap but biased:
the true forward objective uses a hard Heaviside spike whose gradient is zero
almost everywhere, so we substitute a smooth surrogate (spyx.axn) in the
backward pass. The resulting direction descends a related landscape, not the
true one, and the mismatch is a systematic bias.
Evolutionary strategies (ES / NES) estimate the gradient of the true (hard-spike, non-differentiable) objective from forward evaluations alone, with no surrogate at all. Pure ES is unbiased but high-variance and slow to converge in high dimensions.
hybrid_gradient combines the two so that ES pays only for what the surrogate
gets wrong:
g_s = ∇θ loss_surrogate(θ)— the cheap, biased bulk descent direction (onejax.gradthrough the surrogate spikes).-
g_es— an antithetic NES estimate of the gradient of the true loss, drawn over the full flattened parameter vector::g_es = 1/(2 σ K) Σ_k [loss_true(θ + σ ε_k) − loss_true(θ − σ ε_k)] ε_k, ε_k ~ N(0, I).
-
Global orthogonalisation (over the whole flattened vector, not per-leaf). Let
ĝ_s = g_s / (‖g_s‖ + eps). Project the ES estimate onto the subspace the surrogate does not already cover::g_orth = g_es − ⟨g_es, ĝ_s⟩ ĝ_s.
-
Corrected gradient:
g = g_s + λ · g_orth.
The surrogate supplies the bulk direction; ES supplies only the correction in the subspace where the surrogate is blind (its bias). Orthogonalising avoids double-counting directions the surrogate already handles. This is the exact complement of Guided-ES (Maheswaranathan et al. 2019), which restricts the ES search to the surrogate's subspace; here we restrict it to the orthogonal complement and add it as an error-correction term.
Self-normalising λ
With a raw λ the correction magnitude λ·‖g_orth‖ depends on the ES
smoothing σ and sample count K — when ‖g_orth‖ ≫ ‖g_s‖ (common with a
high-variance estimate) even a modest λ lets the correction swamp the bulk
direction and hurt. Passing normalize=True reinterprets λ as a
dimensionless fraction of the surrogate step: the correction is rescaled by
λ · ‖g_s‖ / ‖g_orth‖ so that ‖applied correction‖ = λ · ‖g_s‖ exactly,
regardless of the ES scale. λ = 0.2 then means "nudge the surrogate step by at
most 20 % in the direction it is blind to," which transfers across regimes and
keeps the ES term from ever dominating.
Surrogate-steered Self-Guided ES (variance reduction)
The orthogonal correction above lives in the high-dimensional complement, so it is
high variance — the reason the raw λ blows up. :func:sges_gradient takes
the dual view of Self-Guided ES (Liu et al., IJCAI 2020): instead of adding ES
only in the complement, it uses the surrogate direction as SGES's guiding
subspace and stratifies the sampling — the along-guide directional derivative
is measured exactly (one antithetic pair, no Monte-Carlo variance) and the ES
budget is spent on the orthogonal complement. The result is an unbiased estimate of
the true gradient with several-fold lower variance than isotropic ES at the same
budget. Where Guided ES concentrates ES inside the surrogate subspace, and the
orthogonal hybrid puts it entirely outside, SGES does both — cheap-and-exact
in-subspace, sampled in the complement.
All the linear algebra happens on the flat parameter vector via
:func:jax.flatten_util.ravel_pytree, and perturbations are applied by
nnx.split → perturb-flat → nnx.merge, so the machinery is agnostic to
the model's pytree structure.
LossFn = Callable[..., jax.Array]
module-attribute
(model, *batch) -> scalar loss. Surrogate losses must be differentiable
through the spyx.axn surrogate spikes; true losses need only be evaluable.
es_gradient(model, loss_true, key, *, batch=(), num_samples=8, sigma=0.01)
Pure antithetic-NES gradient of the true loss as a param pytree.
Gradient-free: only forward evaluations of loss_true are used, so the
loss may be non-differentiable (hard Heaviside spikes, hard accuracy, …).
Returned grads match model's Param structure and drop into
optimizer.update(model, grads). This is the "pure ES" baseline arm; it is
also the term :func:hybrid_gradient orthogonalises against the surrogate.
:param model: the Spyx / Flax NNX module whose params are perturbed.
:param loss_true: (model, *batch) -> scalar true objective.
:param key: a jax.random.PRNGKey; antithetic pairs share ε.
:param batch: extra positional args forwarded to the loss (e.g. (x, y)).
:param num_samples: number K of antithetic perturbation pairs.
:param sigma: perturbation scale σ (smoothing radius of the estimate).
:return: an nnx.State of gradients matching the model's Param pytree.
Source code in spyx/experimental/hybrid.py
hybrid_diagnostics(model, loss_surrogate, loss_true, key, *, batch=(), num_samples=8, sigma=0.01, lam=1.0, eps=1e-08, normalize=False)
Diagnostics for a hybrid step without applying it.
Returns a dict describing the correction the ES term contributes:
cosine—⟨g_es, ĝ_s⟩ / ‖g_es‖: alignment of the ES estimate with the surrogate direction. Near±1means ES mostly re-derives the surrogate (little to correct); near0means ES points somewhere the surrogate is blind (the regime where hybrid should help).g_orth_norm—‖g_orth‖: magnitude of the (raw) orthogonal correction.g_s_norm/g_es_norm— the two source magnitudes.proj— the scalar projection⟨g_es, ĝ_s⟩.lam_eff— the weight actually applied tog_orth(equalslamunlessnormalize, where it islam · ‖g_s‖ / ‖g_orth‖).correction_fraction—‖lam_eff · g_orth‖ / ‖g_s‖(equalslaminnormalizemode); how big the applied correction is next to the surrogate.g_s/g_es/g_orth— the flat vectors themselves.
Same signature as :func:hybrid_gradient (minus return_diagnostics).
Source code in spyx/experimental/hybrid.py
hybrid_gradient(model, loss_surrogate, loss_true, key, *, batch=(), num_samples=8, sigma=0.01, lam=1.0, eps=1e-08, normalize=False, return_diagnostics=False)
Surrogate gradient corrected by orthogonalised evolutionary strategies.
Computes g = g_s + λ · g_orth (see the module docstring for the full
derivation), where g_s is the surrogate gradient and g_orth is the
antithetic-NES estimate of the true gradient with its surrogate-aligned
component projected out. The returned grads match model's Param
pytree, so::
grads = hybrid_gradient(model, loss_surrogate, loss_true, key, batch=(x, y))
optimizer.update(model, grads)
:param model: the Spyx / Flax NNX module to differentiate.
:param loss_surrogate: differentiable (model, *batch) -> scalar (surrogate
spikes). Supplies the cheap biased bulk direction g_s.
:param loss_true: (model, *batch) -> scalar true objective (may be
non-differentiable / hard-spike); evaluated only in the forward pass.
:param key: a jax.random.PRNGKey for the ES perturbations.
:param batch: extra positional args forwarded to both losses (e.g. (x, y)).
:param num_samples: number K of antithetic perturbation pairs.
:param sigma: ES perturbation scale σ.
:param lam: weight λ on the orthogonal ES correction. λ = 0 recovers
pure surrogate descent. With normalize=True it is a dimensionless
fraction of the surrogate step rather than a raw scale.
:param eps: numerical floor for the normalisation of g_s.
:param normalize: if True, self-normalise the correction so its magnitude
is exactly λ · ‖g_s‖ — the ES term becomes a bounded fraction of the
surrogate step, immune to the ES variance/σ scaling that otherwise lets
‖g_orth‖ swamp ‖g_s‖. Recommended when tuning λ across regimes.
:param return_diagnostics: if True also return the diagnostics dict from
:func:hybrid_diagnostics (cosine, g_orth_norm, lam_eff,
correction_fraction, the flat vectors, …).
:return: an nnx.State of grads, or (grads, diagnostics) if
return_diagnostics.
Source code in spyx/experimental/hybrid.py
make_hybrid_train_step(loss_surrogate, loss_true, *, num_samples=8, sigma=0.01, lam=1.0, normalize=False)
Build a single-step hybrid updater.
The returned callable has signature (model, optimizer, key, *batch) ->
true_loss and mutates model / optimizer in place via NNX, mirroring
:func:spyx.optimize.make_train_step but using :func:hybrid_gradient to
build the update. The scalar returned is loss_true evaluated at the
pre-update parameters (the objective the ES term actually targets).
:param loss_surrogate: differentiable (model, *batch) -> scalar.
:param loss_true: (model, *batch) -> scalar true objective.
:param num_samples: number K of antithetic perturbation pairs.
:param sigma: ES perturbation scale σ.
:param lam: weight λ on the orthogonal ES correction.
:param normalize: self-normalise the correction to λ · ‖g_s‖ (see
:func:hybrid_gradient).
:return: step(model, optimizer, key, *batch) -> true_loss.
Source code in spyx/experimental/hybrid.py
make_sges_hybrid_train_step(loss_surrogate, loss_true, *, num_samples=8, sigma=0.01, lam=1.0)
Single-step updater using :func:sges_gradient (surrogate-steered SGES).
step(model, optimizer, key, *batch) -> true_loss — mirrors
:func:make_hybrid_train_step but builds the update with the variance-reduced
Self-Guided-ES gradient. Returns loss_true at the pre-update parameters.
Source code in spyx/experimental/hybrid.py
sges_gradient(model, loss_surrogate, loss_true, key, *, batch=(), num_samples=8, sigma=0.01, lam=1.0, eps=1e-08, return_diagnostics=False)
Surrogate-steered Self-Guided ES — a variance-reduced 0+1 gradient.
The surrogate gradient g_s steers a Self-Guided-ES estimate g_es of
the true (hard-spike) loss gradient: g_s picks the guiding direction, its
along-guide component is measured exactly, and ES spends its whole budget on
the orthogonal complement (see :func:_sges_flat). Returns
g = (1-λ)·g_s + λ·g_es — λ=1 descends on the variance-reduced true-
gradient estimate (the surrogate only steers sampling), λ=0 recovers pure
surrogate descent.
This is the "0+1" method in its variance-reduced form: the 1st-order surrogate
steers where the 0th-order ES samples land, buying Self-Guided ES's variance
reduction (Liu et al., IJCAI 2020) with a surrogate-defined guiding subspace.
Unlike :func:hybrid_gradient (which adds ES only in the orthogonal
complement), ES here also corrects the surrogate's magnitude/sign along its
own direction, via the exact directional derivative a.
:param model: the Spyx / Flax NNX module to differentiate.
:param loss_surrogate: differentiable (model, *batch) -> scalar (the guide).
:param loss_true: (model, *batch) -> scalar true objective (forward-only).
:param key: jax.random.PRNGKey for the orthogonal ES perturbations.
:param batch: extra positional args forwarded to both losses.
:param num_samples: total antithetic pairs K (1 along-guide, K-1 orth).
:param sigma: ES perturbation scale σ.
:param lam: blend g = (1-λ)g_s + λ g_es; λ=1 = pure SGES estimate.
:param eps: numerical floor for normalisation.
:param return_diagnostics: also return the diagnostics dict.
:return: an nnx.State of grads, or (grads, diagnostics).
Source code in spyx/experimental/hybrid.py
spyx.experimental.zoo
Runnable recipes tagged by application × training method × architecture. Each
Recipe exposes build / synthetic_batch / demo on synthetic data; browse
with list_recipes(application=..., method=...).
The Spyx recipe zoo — runnable, synthetic-data SNN recipes.
Experimental. This whole subpackage lives under
:mod:spyx.experimental; its API may change without a deprecation cycle.
Each recipe is a self-contained, download-free example of training a spiking / state-space model for one application, tagged by method × architecture:
============== ============== ============= ==============
application method architecture module
============== ============== ============= ==============
control evolutionary LIF-MLP :mod:.control
classification surrogate RSNN :mod:.classification
language surrogate S5 :mod:.language
============== ============== ============= ==============
Every recipe exposes the same small surface via a :class:Recipe record:
build(rngs) -> nnx.Module— construct the model.synthetic_batch(...) -> tuple— sample a download-free batch.loss(model, *batch) -> scalar— a finite objective on that batch.demo(steps=...) -> list[float]— run a few train/evolve steps and return the fitness/loss history.
The zoo is importable as its own subpackage — from spyx.experimental.zoo
import REGISTRY, list_recipes, get — without touching
spyx.experimental.__init__.
Recipe
dataclass
A single runnable recipe, keyed by application and tagged by method × arch.
:name: unique registry key.
:application: one of 'control', 'classification', 'language'.
:method: training method, e.g. 'evolutionary', 'surrogate',
'conversion', 'hybrid'.
:architecture: model family, e.g. 'LIF-MLP', 'RSNN', 'S5'.
:build: (nnx.Rngs) -> nnx.Module model constructor.
:synthetic_batch: (...) -> tuple download-free batch sampler; the tuple
is splatted into loss after the model.
:describe: one-line human-readable description.
:loss: (model, *batch) -> scalar finite objective (fitness for
evolutionary recipes, training loss for gradient recipes).
:demo: (steps=...) -> list[float] short run returning a fitness/loss
history.
Source code in spyx/experimental/zoo/__init__.py
get(name)
Look up a recipe by name, raising KeyError with the valid keys.
list_recipes(application=None, method=None)
Return recipes, optionally filtered by application and/or method.
:application: keep only recipes with this application (None = any).
:method: keep only recipes with this method (None = any).
:return: list of matching :class:Recipe records.
Source code in spyx/experimental/zoo/__init__.py
spyx.experimental.matfree
Multiplication-light layers you build with, rather than convert to: ternary
(BitNet) weights collapse the matmul to signed accumulations, power-of-two
(DeepShift) weights to bit-shifts. Trained from scratch / QAT via straight-through
estimators. See Training methods for where
this sits relative to post-training quantization (spyx.quant).
Matmul-free linear primitives — ternary (BitNet) and shift-add (DeepShift).
.. note::
Experimental / sketch. Unstable API. These are the native (train-from-
scratch, QAT) counterpart to the post-training :func:spyx.quant.bitnet_ternary_rules
path: layers whose forward pass replaces the expensive multiplies of a dense
matmul with cheap accumulations (ternary) or bit-shifts (power-of-two),
so you can build multiplication-light architectures rather than convert them.
The multiply-free idea
A dense layer y = x @ W costs in*out multiplies. Two ways to remove them:
- Ternary (BitNet b1.58; Scalable MatMul-free LM, Zhu et al. 2024). Constrain
Wto{-1, 0, +1}times a per-tensor scaleβ. Theny = β · (Σ_{W=+1} x − Σ_{W=-1} x)— pure signed accumulation, plus one scale multiply per output. - Shift-add (DeepShift, Elhoushi et al. 2021; ShiftAddLLM, You et al. 2024).
Constrain
Wto signed powers of two±2^p. ThenW·x = ± (x << p)— a bit-shift and a sign, no multiply, on fixed-point hardware.
Both are trained with a straight-through estimator (STE): the forward uses the quantised weight, the backward flows to a full-precision shadow weight.
The spiking synthesis
Spyx's real leverage here: a binary spike activation (s ∈ {0,1}, from any
:mod:spyx.nn neuron) times a ternary weight (∈ {-1,0,+1}) is a fully
add-only operation — no multiplies anywhere in the layer. Pair these layers with
spiking neurons (or feed :func:spyx.experimental.compress.pack_spikes outputs) to
get networks that are matmul-free in both operands. See the roadmap in the module
for the matmul-free-LM block (ternary channel-mixer + an SSM / ternary-GRU token
mixer) that this is the substrate for.
MLGRU
Bases: Module
MatMul-free Linear GRU token mixer (Zhu et al., 2024).
The multiply-free replacement for attention: instead of an O(T²) QKᵀ
matmul, tokens are mixed by a causal element-wise linear recurrence
.. math:: h_t = f_t \odot h_{t-1} + (1 - f_t) \odot c_t,\qquad y_t = W_o (g_t \odot h_t)
where the gate/candidate projections (f, c, g) and the output o
are :class:TernaryLinear (accumulation-only) and everything else is
element-wise. The recurrence is a first-order linear scan — parallelisable with
jax.lax.associative_scan the same way :class:spyx.experimental.PSU_LIF is;
here it uses jax.lax.scan for clarity.
Input/output are batch-major [B, T, D]; the mixing is strictly causal.
Source code in spyx/experimental/matfree.py
MatMulFreeBlock
Bases: Module
A matmul-free transformer-style block: pre-norm, MLGRU mixer, ternary MLP.
x = x + MLGRU(RMSNorm(x)); x = x + TernaryMLP(RMSNorm(x)). Every dense
operation is ternary (accumulation-only); the token mixing is an element-wise
recurrence. Stack these for a matmul-free language model — swap it into
research/new/ternary_llm in place of a Transformer block and read the
efficiency off spyx.bench.
:param mlp_ratio: channel-mixer hidden width as a multiple of dim.
Source code in spyx/experimental/matfree.py
RMSNorm
Bases: Module
Root-mean-square layer norm — a per-feature rescale, no matmul.
The only non-accumulation op in a matmul-free block: an element-wise normalisation (O(D) work), negligible next to a dense layer's O(D²).
Source code in spyx/experimental/matfree.py
ShiftAddLinear
Bases: Module
Dense layer with signed-power-of-two weights — DeepShift / ShiftAdd.
Forward: y = x @ W_po2 + b with W_po2 = ±2^p; each product is a shift on
fixed-point hardware. Trained via STE through a full-precision shadow weight.
:param min_exp/max_exp: clamp range for the exponents p.
Source code in spyx/experimental/matfree.py
TernaryLinear
Bases: Module
Dense layer with ternary {-1,0,+1} weights — a BitNet BitLinear.
Forward: y = β · (x_q @ W_ternary) + b. The x_q @ W_ternary product is
accumulation-only. With activation_bits set, activations are absmax-quantised
first (BitNet b1.58 + a8). Trained via STE through a full-precision shadow weight.
:param activation_bits: if set, quantise inputs to this many bits (e.g. 8).
Source code in spyx/experimental/matfree.py
TernaryMLP
Bases: Module
A matmul-free channel mixer: two :class:TernaryLinear with a nonlinearity.
The multiply-free counterpart of a Transformer/SSM feed-forward block; drop it in
wherever a dense MLP sits. Pair with a matmul-free token mixer (an SSM from
:mod:spyx.ssm, or a ternary GRU — see the module roadmap) for a matmul-free LM.
Source code in spyx/experimental/matfree.py
activation_quant(x, bits=8, eps=1e-05)
Per-token absmax quantisation of activations to bits (BitNet's a8).
Returns the dequantised value (STE-friendly); pass through :func:ste to train.
Source code in spyx/experimental/matfree.py
power_of_two_weights(w, min_exp=-8, max_exp=0, eps=1e-12)
Round each weight to the nearest signed power of two ±2^p (DeepShift).
p is clamped to [min_exp, max_exp]; the result multiplies as a bit-shift
on fixed-point hardware. Near-zero weights round to the smallest magnitude.
Source code in spyx/experimental/matfree.py
ste(x, x_q)
Straight-through estimator: forward is x_q, backward is identity in x.
ste(x, quantize(x)) evaluates to the quantised value but passes gradients to
the full-precision x unchanged — the standard trick for training through a
non-differentiable quantiser.
Source code in spyx/experimental/matfree.py
ternary_weights(w, eps=1e-05)
BitNet b1.58 absmean ternarisation. Returns (w_ternary, scale).
scale = mean(|w|); w_ternary = round(clip(w/scale, -1, 1)) ∈ {-1, 0, +1}.
The reconstruction is scale · w_ternary.
Source code in spyx/experimental/matfree.py
spyx.experimental.onnx
Export a spiking model to ONNX — single-timestep step, or a full temporal loop.
.. warning:: Experimental — unstable API. May change without a deprecation cycle.
A spyx neuron (or a :class:spyx.nn.Sequential of them) implements one
timestep of the temporal loop::
(x_t, state) -> (out, new_state)
:func:spyx.nn.run scans this over the time axis with jax.lax.scan. There
are two useful things to hand a general runtime (ONNX Runtime, ONNX Runtime
Mobile on a phone, a browser, an embedded target):
-
Per-timestep (
sequence_length=None, the default). Export the single feed-forward step above; the application runs the temporal loop, calling the ONNX graph once per timestep and threading the neuron state (membrane potentials, adaptive thresholds, …) itself. ONNX speaks flat tensor I/O, not pytrees, so the exported signature is the flattened state::step(x_t, state_0, state_1, ...) -> (out, new_state_0, new_state_1, ...)
-
Full-sequence (
sequence_length=T). Export :func:spyx.nn.runoverTtimesteps so the whole temporal loop lives inside the ONNX graph as a nativeLoopop::run(x_seq, state_0, ...) -> (out_seq, final_state_0, ...)
with x_seq shaped (T, batch, *input_shape) and out_seq shaped
(T, batch, *out). jax2onnx's scan plugin lowers the jax.lax.scan
driving :func:spyx.nn.run straight to an ONNX Loop, so no host-side
temporal loop is needed at all — a real advantage over runtimes that lack a
clean scan primitive.
:func:step_signature returns a :class:ONNXStepSignature describing the flat
layout (order, shapes and dtypes of every state tensor, plus the pytree
structure needed to reassemble it) so callers know how to seed state (zeros of
the given shapes) and thread new_state_i back into the next call. It needs
only JAX, never the conversion stack.
The conversion is a direct jaxpr -> ONNX lowering via jax2onnx
<https://pypi.org/project/jax2onnx/>_: jax2onnx.to_onnx traces the pure
JAX function and emits an onnx.ModelProto — no TensorFlow, no jax2tf, no
TFLite, no tf2onnx. Its scan plugin maps jax.lax.scan to a native ONNX
Loop, which is what makes the full-sequence export a single self-contained
graph.
jax2onnx (and onnx) are imported lazily inside the functions, so
import spyx.experimental.onnx works without them installed. Install the
conversion dependencies with::
pip install jax2onnx onnx onnxruntime
Inference only needs onnxruntime (or ONNX Runtime Mobile on-device), not the
conversion stack. Only the forward Heaviside spike is exported; the surrogate
gradient is training-only and irrelevant to inference.
Example::
import jax.numpy as jnp
from flax import nnx
from spyx import nn
from spyx.experimental import onnx
rngs = nnx.Rngs(0)
model = nn.Sequential(
nnx.Linear(8, 16, rngs=rngs),
nn.LIF((16,), rngs=rngs),
nnx.Linear(16, 4, rngs=rngs),
nn.LI((4,), rngs=rngs),
)
onnx_bytes = onnx.to_onnx(model, (8,), batch=1) # per-timestep step
with open("step.onnx", "wb") as f:
f.write(onnx_bytes)
# Or the whole temporal loop in one graph (native ONNX Loop):
seq_bytes = onnx.to_onnx(model, (8,), batch=1, sequence_length=100)
sig = onnx.step_signature(model, (8,), batch=1)
# sig.state_shapes -> [(1, 16), (1, 4)] : seed each with zeros on-device.
ONNXStepSignature
dataclass
Flat tensor layout of an exported step (or full-sequence) function.
The per-timestep export has the signature step(x_t, *state_flat) ->
(out, *new_state_flat); the full-sequence export has
run(x_seq, *state_flat) -> (out_seq, *final_state_flat) where x_seq
carries a leading time axis. This dataclass records everything a caller
needs to drive either: how to seed the state (zeros of state_shapes /
state_dtypes), the order state tensors appear as inputs and outputs, and
the pytree structure to reassemble the flat state back into the model's
native (possibly nested / None-holed) state tree.
:input_shape: Shape of the input tensor (including batch, and, for the
full-sequence export, a leading time axis).
:input_dtype: NumPy dtype of the input.
:state_shapes: Shape of each flattened state tensor, in call order.
:state_dtypes: NumPy dtype of each flattened state tensor, in call order.
:output_shape: Shape of the primary output tensor.
:output_dtype: NumPy dtype of the primary output tensor.
:input_names: ONNX graph input names, in call order (x first, then each
flat state tensor).
:output_names: ONNX graph output names, in call order (primary output first,
then each flat new-/final-state tensor).
:sequence_length: None for the per-timestep export; T for the
full-sequence export.
:state_treedef: The pytree structure of the model's native state, so the
flat state_i tensors can be reassembled with
jax.tree_util.tree_unflatten(state_treedef, state_flat).
Source code in spyx/experimental/onnx.py
num_state
property
Number of flat state tensors threaded through the step.
seed_state(dtype=None)
Return a fresh zero-initialized flat state (one array per tensor).
:dtype: Override dtype for every state tensor; defaults to each
tensor's recorded state_dtypes entry.
Source code in spyx/experimental/onnx.py
step_signature(model, input_shape, *, batch=1, dtype=jnp.float32, sequence_length=None)
Describe the flat tensor I/O of model's exported step.
Does not require jax2onnx/onnx — it only traces shapes/dtypes with JAX,
so callers can plan state seeding/threading without running a conversion.
See :class:ONNXStepSignature.
:model: A spyx neuron or :class:spyx.nn.Sequential implementing
(x_t, state) -> (out, new_state) and exposing initial_state.
:input_shape: Per-timestep input feature shape, excluding batch and time
(e.g. (8,) for a length-8 input vector).
:batch: Batch dimension of the exported step. Defaults to 1.
:dtype: Input/compute dtype. Defaults to jnp.float32.
:sequence_length: None (default) describes the per-timestep step;
an integer T describes the full-sequence export (leading time axis).
Source code in spyx/experimental/onnx.py
to_onnx(model, input_shape, *, batch=1, dtype=jnp.float32, opset=None, sequence_length=None)
Export a spiking model to ONNX and return the serialized ModelProto.
With sequence_length=None (default) this exports the single feed-forward
step (x_t, state) -> (out, new_state) — no temporal scan — whose flat
ONNX signature is step(x_t, *state_flat) -> (out, *new_state_flat). The
application runs the temporal loop, calling the graph once per timestep and
threading new_state_i back in as state_i. Pair with
:func:step_signature to learn the flat state layout and to seed zeros.
With an integer sequence_length=T this exports :func:spyx.nn.run over
T timesteps, so the ONNX graph contains the whole temporal loop as a
native Loop (jax2onnx's scan plugin lowers the jax.lax.scan to it);
the signature becomes run(x_seq, *state_flat) -> (out_seq,
*final_state_flat) with a leading time axis of length T on x_seq
and out_seq.
Conversion is a direct jaxpr -> ONNX lowering via jax2onnx.to_onnx — no
TensorFlow. Only the forward Heaviside spike is exported; the surrogate
gradient is training-only and irrelevant to inference.
Requires jax2onnx and onnx (pip install jax2onnx onnx
onnxruntime); they are imported lazily here so importing this module does
not need them. Inference only needs onnxruntime (or ONNX Runtime Mobile
on a phone), not the conversion stack.
:model: A spyx neuron or :class:spyx.nn.Sequential implementing
(x_t, state) -> (out, new_state) and exposing initial_state.
:input_shape: Per-timestep input feature shape, excluding batch and time
(e.g. (8,)).
:batch: Batch dimension of the exported graph. Defaults to 1.
:dtype: Input/compute dtype. Defaults to jnp.float32.
:opset: ONNX opset version to target. None defaults to 21 (recent
enough for the native Loop used by the full-sequence export).
:sequence_length: None exports the per-timestep step; an integer T
exports the full spyx.nn.run over T timesteps.
:return: The serialized ONNX ModelProto as bytes.
Source code in spyx/experimental/onnx.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |