Networks, connections and event sources#

Build a Network from named Populations, add event or continuous connections, then call network.initialize(dt). Network execution uses that fixed timestep. For connected compiled simulations, see Run models with explicit state.

Network#

class Network(populations, netstim=None, seed=None, *, track_netcon_events=False, netcon_delay_backend='dense', netcon_train_backend='auto')[source]#

Container for interacting populations, synaptic connections, and optional stimuli.

A Network bundles:

  • Populations: named collections of axons/neurons (Population instances).

  • NetCons: directed connections materialized as NetCon objects that deliver events from pre- to post-synaptic compartments (including optional weights, delays, thresholds, and alternate pre variables such as conductance).

  • NetStim: an optional NetStim source that injects spikes into the network (treated as a special “population” named netstim).

Connections are specified incrementally (e.g., via connect_one_to_one(), connect_dense(), connect_prob(), connect_prob_n()), then materialized when build()/initialize() is called. Running the network steps each population forward in time while advancing all synapses and optional NetStim.

Note

Device placement can be heterogeneous across populations and NetStim. NetCons are built on each post-synaptic population’s device. Device changes are detected at build() time and trigger rebuilds (as do dt changes or force_rebuild=True). Call build() (and typically initialize()) after manual device moves to realign connectivity buffers.

Note

Event delivery follows Dendra’s sampled, fixed-step ordering. At the start of a timestep, NetStim and NetCon state is advanced using the currently visible source state; populations are then integrated to the next sample. A voltage threshold crossing created by that integration is consequently observed by its NetCon on the following network step. Ordinary hard-event connection delays are quantized to integer timesteps (differentiable delay modes may interpolate adjacent bins). This phase convention is part of Dendra’s network semantics and need not match another simulator’s within-step event queue, even when the membrane and synaptic response kinetics agree.

Parameters:
  • populations (dict[str, Population]) – Mapping from population name to Population instance. Populations are built, registered as attributes, and used as sources/targets for connectivity.

  • netstim (NetStim, optional) – Optional spike generator attached under the name netstim. A source may also be registered later with attach_netstim().

  • seed (int, optional) – Seed for network-level RNG used in stochastic wiring utilities.

  • track_netcon_events (bool, optional) – If True, event-based NetCons allocate the historical per-connection event_queue used for delivery introspection. If False (default), NetCons skip that large debug queue during inference and keep only the lightweight current-step events buffer.

  • netcon_delay_backend ({"dense", "sparse_calendar", "bitpacked_history"}, optional) – Delay-line backend for event-based NetCons. "dense" is the default differentiable/dense implementation. "sparse_calendar" is an inference-only backend that stores pending nonzero deliveries in sparse calendar buckets while preserving the existing net_receive dense-payload API. Can be beneficial for memory efficiency and speed on CPU when networks have long delays and are not densely spiking. Should be avoided on GPU. "bitpacked_history" is an inference-only backend that stores packed source-spike history and reconstructs the dense delivery payload from the static edge list. Suitable for networks where threshold is uniform and / or determined solely by the pre-synaptic population, so that the same source spike history can be shared across synapses. Can be very beneficial for memory efficiency and speed on GPU for large networks with long delays. The first run with ‘bitpacked_history’ will be slow due to CUDA kernel compilation, but subsequent runs will be much faster.

  • netcon_train_backend ({"dense", "source_history", "auto"}, optional) – Differentiable training backend for event NetCons. "dense" keeps the fully general per-synapse delay buffer. "source_history" uses compact source-level histories when thresholds/events are source-level; with diff_spiking=False this uses packed hard source spikes and with diff_spiking=True this uses floating source gates. "auto" uses source history when exact and otherwise falls back to dense. Default is "auto" so common source-level SNN projections get the compact differentiable backend without opting in explicitly.

attach_netstim(netstim, *, replace=False)[source]#

Attach a NetStim after network construction.

The constructor’s netstim= argument remains supported, but callers may now build a purely cellular network first and add an artificial source later:

net = dn.Network({"cell": cell})
net.build(dt)
net.attach_netstim(dn.NetStim(N=8))
net.connect_one_to_one(net.netstim[:], target, synapse)
net.initialize(dt)

Attaching a source invalidates materialized NetCons. Likewise, every subsequent connect* call invalidates them. Call build() or, normally, initialize() before the next run(). Attaching to an already initialized/running network is supported structurally, but reinitialization is required because rebuilding replaces all NetCon runtime queues.

Parameters:
  • netstim (NetStim) – Artificial spike source to register as network.netstim.

  • replace (bool, default False) – Replace an existing NetStim. When existing NetStim-sourced connection specifications are present, replacement is accepted only if the new source has the same shape, because those specifications store source-flat indices.

Returns:

Self, for chaining.

Return type:

Network

batch(n, include_netstim=True)[source]#

Create a batched version of the network by tiling populations n times.

Parameters:
  • n (int) – Batch size (number of replicas).

  • include_netstim (bool, optional) – If False, do not batch NetStim even if present. Default True.

Returns:

Self, with populations and NetCons batched.

Return type:

Network

build(dt, max_delay_ms=None, force_rebuild=False)[source]#

Build synaptic modules for the current wiring spec.

Parameters:
  • dt (float) – Simulation timestep (ms) used for NetCon buffers.

  • max_delay_ms (float, optional) – Maximum delay allowed for NetCons. Default is None (no cap).

  • force_rebuild (bool, optional) – If True, rebuild even if dt has not changed. Default is False.

Returns:

Self, for chaining.

Return type:

Network

cache_state()[source]#

Cache population and connection runtime state for steady_state().

Populations still use their normal state_dict(). Event NetCons and ContinuousCons package their own backend-specific delay/runtime state so Network does not need to know whether a NetCon is dense, sparse-calendar, or bitpacked-history backed.

clear_state_cache()[source]#

Clear Network-owned Population and connection initialization caches.

Returns:

The running model state is unchanged. Later initialization no longer restores Network-owned caches. Individual Populations’ steady-state caches are retained and can still restore during initialization; clear those separately with population.clear_steady_state().

Return type:

None

clear_synapses()[source]#

Remove all queued synapse specs and built NetCon modules.

Use when re-wiring the network before calling build() again.

concat(*, threads=16, **kwargs)[source]#

Concatenates populations to solve with fewer kernel launches. All connections are preserved.

Parameters:
  • threads (int, optional) – DHS solver lane count for groups containing Tree or Cable models. Must divide 32. Default is 16.

  • **kwargs (dict) – Populations to concatenate, where keys are the new population names and values are lists of population names to concatenate. If no populations are specified, all populations will be concatenated into ‘all_populations’. A group may reuse the name of one of the populations it replaces, but may not collide with an unselected population or a Network attribute.

Returns:

A new network with the concatenated populations.

Return type:

Network

Examples

>>> net = Network(...)
>>> print(list(net.populations.keys()))
['exc1', 'exc2', 'inh']
>>> net0 = net.concat()
>>> print(list(net0.populations.keys()))
['all_populations']
>>> net1 = net.concat(all=['exc1', 'exc2', 'inh'])
>>> print(list(net1.populations.keys()))
['all']
>>> net2 = net.concat(exc=['exc1', 'exc2'])
>>> print(list(net2.populations.keys()))
['exc', 'inh']

Notes

This is a preprocessing transform rather than a live simulation-state continuation. The returned Network owns cloned population and NetStim objects, so a subsequent batch() cannot mutate the source Network. Wiring weight, delay, and transform modules retain their identity, so existing optimizer references to those connection modules remain valid. Population parameter modules are cloned; create an optimizer after this transform when optimizing population parameters. Apply concatenation before initialization when pending event queues and the exact runtime clock matter.

concatenated_weights()[source]#

Returns the concatenated weights of all synapses.

connect(source, target, synapse=None, conn_spec=None, *, threshold=0.0, weight=1.0, delay=0.0, pre_var=None, auto_expand=False, allow_autapses=None, allow_multapses=None)[source]#

Connect source to target using a NEST-style connectivity specification.

target may be a physical population/slice, or a SynapseSlots object returned by population.slots(...), slice.slots(...), or network.synapse_slots(...). Slot targets remove the ambiguity that arises when a banked point-process mechanism has several local slots on one physical compartment.

delay is in ms. threshold uses the coordinate of pre_var (mV for the default membrane-voltage source); use None when the source already provides discrete events. weight is target-defined. Built-in point-process expsyn and exp2syn targets expect a bare numerical value in µS, so weight=0.05 means 0.05 µS and must not be multiplied by dendra.units.uS.

connect_continuous(source, target, synapse=None, conn_spec=None, *, pre_var='v', input=None, weight=1.0, delay=0.0, reduce='sum', transform=None, auto_expand=False, allow_autapses=None, allow_multapses=None)[source]#

Connect a continuous presynaptic variable to a ContinuousSynapse.

Slot targets are supported in the same way as for event-based connections: a SynapseSlots target is already in synapse-local coordinates and avoids ambiguous colocated slots.

delay is in ms. The product of weight and the optionally transformed pre_var must have the unit expected by the receiving input buffer; there is no universal continuous-connection weight unit. For the built-in density-style graded_syn driven by its dimensionless release gate, weight and g_pre are in S/cm².

connect_continuous_one_to_one(source, target, synapse=None, *, pre_var='v', input=None, weight=1.0, delay=0.0, reduce='sum', transform=None, allow_autapses=False, allow_multapses=False)[source]#

One-to-one wrapper around connect_continuous().

connect_dense(source, target, synapse=None, threshold=0.0, weight=1.0, delay=0.0, pre_var=None, auto_expand=False, allow_autapses=False, allow_multapses=False)[source]#

Connect source to target densely, i.e. all-to-all between selections.

Backward-compatible wrapper around connect(..., conn_spec={"rule": "all_to_all"}). Threshold, weight, and delay follow connect()’s unit contract.

connect_one_to_one(source, target, synapse=None, threshold=0.0, weight=1.0, delay=0.0, pre_var=None, allow_autapses=False, allow_multapses=False)[source]#

Connect source to target one-to-one.

This is a backward-compatible wrapper around connect(..., conn_spec={"rule": "one_to_one"}). Unlike the general NEST-style connect entry point, the legacy wrapper keeps autapses disabled by default. Threshold, weight, and delay follow connect()’s unit contract.

connect_one_to_one_slots(source, target, synapse=None, *, slots=None, local_index=None, threshold=0.0, weight=1.0, delay=0.0, pre_var=None, allow_autapses=False, allow_multapses=False)[source]#

Connect source elements one-to-one with explicit target slots.

Threshold, weight, and delay follow connect()’s unit contract.

connect_prob(source, target, synapse, prob, threshold=0.0, weight=1.0, delay=0.0, pre_var=None, auto_expand=False, allow_autapses=False, allow_multapses=False, strategy='bernoulli')[source]#

Connect source to target probabilistically.

strategy='bernoulli' maps to NEST pairwise_bernoulli and uses prob as the pairwise connection probability. strategy='poisson' or 'pairwise_poisson' maps to NEST pairwise_poisson and uses prob as pairwise_avg_num_conns; for that rule, allow_multapses must be True. Threshold, weight, and delay follow connect()’s unit contract.

connect_prob_n(source, target, synapse, n, threshold=0.0, weight=1.0, delay=0.0, pre_var=None, auto_expand=False, allow_autapses=False, allow_multapses=False)[source]#

Connect exactly n random pre-post pairs.

This maps to NEST fixed_total_number. With allow_multapses=True, pairs are drawn with replacement. With allow_multapses=False the sampled source-target pairs are unique. Threshold, weight, and delay follow connect()’s unit contract.

connect_to_slots(source, target, synapse=None, *, slots=None, local_index=None, conn_spec=None, threshold=0.0, weight=1.0, delay=0.0, pre_var=None, auto_expand=False, allow_autapses=None, allow_multapses=None)[source]#

Connect sources to explicit synapse-local target slots.

target may be a SynapseSlots object, or a population/slice plus synapse and slots/local_index. This is the public API for banked point processes with multiple colocated local slots. Threshold, weight, and delay follow connect()’s unit contract.

delete_injections()[source]#

Deletes all current injections from all populations in the network.

detach()[source]#

Truncate simulation history while retaining live raw parameter sources.

Populations, connection histories, queued payloads and NetStim carry retain their values. Clocks, duration remainder, RNG streams, schedules and raw parameter/Tensor identities are unchanged. Callback carry has separate ownership; use its collection’s detach_state method.

The next positive-step, gradient-enabled training call reconnects effective connection parameters from current raw sources and retained independent sampling draws, without resampling or initializing state. Evaluation, no-grad, inference-mode and zero-step calls defer this work. Quantized delay routes remain initialization configuration; dynamic differentiable event delays must fit the allocated history capacity. Externally computed nonleaf sources remain caller-owned.

Returns:

Self, for chaining.

Return type:

Network

device()[source]#

Legacy aggregate device (first population). For multi-device setups, prefer devices().

devices()[source]#

Return a mapping of population name -> device to support heterogeneous placement.

dtype()[source]#

Legacy aggregate dtype (first population). For multi-device setups, prefer dtypes().

dtypes()[source]#

Return a mapping of population name -> dtype to support heterogeneous placement.

eval()[source]#

Switch populations and synapses into evaluation mode.

Disables gradients for stepping and sets the compiled stepping function to the eval variant.

Returns:

Self, for chaining.

Return type:

Network

Notes

Dense-to-dense switches preserve pending traffic. Compact runtime layouts must be reinitialized before execution, as described by train().

initialize(dt, reinit_weights=True, reinit_delays=True, t=0.0, max_delay_ms=None, force_rebuild=False, *, draws=None)[source]#

Initialize populations, synapses, and optional NetStim for simulation.

Parameters:
  • dt (float) – Simulation timestep (ms).

  • reinit_weights (bool, optional) – Re-sample or refresh synaptic weights. Default is True. When initializing from a steady-state cache after an optimizer update, leave this True so expanded WeightExpander.w buffers are regenerated from the current weight parameters before cached pending deliveries are rebuilt.

  • reinit_delays (bool, optional) – Re-sample or refresh synaptic delays. Default is True. When initializing from a steady-state cache after delay parameters have changed, leave this True so expanded delay values and integer delay metadata are regenerated before cache restore.

  • t (float, optional) – Starting simulation time (ms). Finite negative values are allowed; booleans and non-finite values are rejected. Default is 0.0.

  • max_delay_ms (float, optional) – Maximum allowed synaptic delay. Default is None.

  • force_rebuild (bool, optional) – If True, rebuild NetCons even if already built. Default is False.

  • draws (dendra.func.InitializationDraws, optional) – Replay explicit Population, connection and NetStim initialization draws without automatic sampling. The packet’s RNG boundaries remain authoritative for subsequent execution. Omission retains automatic native initialization.

Returns:

Self, for chaining.

Return type:

Network

load(state_dict)[source]#

Load model weights from a state dictionary.

This method supports loading weights from: 1. A file path as a string 2. An actual state dictionary object

The loaded weights are matched to the model’s current state dict structure and only compatible weights are loaded.

Parameters:

state_dict (str or dict) – Can be one of: - A file path to a saved model state - A state dictionary object

Returns:

The model instance with loaded weights

Return type:

self

load_state_cache(state_cache=None, syn_cache=None)[source]#

Install initialization caches without restoring running state immediately.

Parameters:
  • state_cache (mapping, optional) – Population-state cache assigned directly. Omission retains the current Population cache.

  • syn_cache (mapping, optional) – Event/continuous connection cache assigned directly. Omission retains the current connection cache.

Notes

The supplied mappings are retained by identity. initialize() performs restoration using the active parameter and cache policies.

longrun(tstop=None, chunklength=None, extra=None, callbacks=None, progressbar=False, *, steps=None, duration=None, inputs=None, draws=None, callback_state=None, functional_callbacks=None, functional_callback_state=None)[source]#

Advance the network in bounded-memory chunks without resetting state.

longrun has the same timestep and event-delivery semantics as run(), but prepares intracellular and extracellular stimuli one chunk at a time. Population, NetStim, and NetCon state remains live across chunk boundaries. Callback loop hooks run once for the complete call, while chunk hooks run once around each chunk.

Parameters:
  • tstop (float, optional) – Compatibility spelling for duration. Only complete timesteps are executed; a fractional remainder is retained and combined with the next run(), longrun(), or longrun_checkpointed() call.

  • steps (int, optional) – Exact non-negative timestep count, leaving retained fractional duration unchanged. Supply only one horizon argument.

  • duration (float, optional) – Requested simulation duration in milliseconds, using the same retained-duration budget as tstop.

  • chunklength (int) – Positive number of timesteps per chunk. The final chunk may be shorter.

  • extra (dict[str, tuple[torch.Tensor, object]], optional) – Population-specific extracellular stimuli with the same public (v, waveform) format and shape contract as run().

  • inputs (mapping of str to dendra.func.Inputs, optional) – Deterministic time-leading voltage/current tapes with the same contract as run(). Chunk boundaries retain tape views and gradients; all tape lengths match the selected timestep count.

  • draws (dendra.func.RuntimeDraws, optional) – Explicit time-leading draws with the same contract as run(). Each accepted step consumes its own waveform recipe and RNG frame; changing chunklength does not change replayed stochastic values.

  • callbacks (sequence of Callback or dendra.func.FunctionalCallbacks, optional) – Native hook sequence, or a pure collection prepared once with dn.func.make_callbacks for this Network or a compatible initialized Network with matching timestep and mode. Pure observations read this receiver’s state with fixed prepared paths, scopes and selections. They run after clock advancement and before native post-step hooks. Native hooks retain their loop/chunk/step timing.

  • progressbar (bool or tqdm.tqdm, optional) – If truthy, display progress over completed timesteps.

  • callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through callbacks or functional_callbacks. Resumes sampling phase and reducer totals without another initial observation.

  • functional_callbacks (dendra.func.FunctionalCallbacks, optional) – Compatibility spelling for the prepared pure collection. Use it alongside callbacks=[...] to combine native hooks and pure observations. Supply the collection through only one argument.

  • functional_callback_state (dendra.func.FunctionalCallbackState, optional) – Compatibility spelling for callback_state. Supply carry through only one argument; either collection spelling is accepted.

Returns:

Returns named pure observations and carry when supplied; otherwise returns None. Cadence and gradients continue across chunks and calls without resetting the live Network state.

Return type:

None or dendra.func.FunctionalCallbackResults

longrun_checkpointed(tstop=None, chunklength=None, extra=None, callbacks=None, progressbar=False, *, steps=None, duration=None, inputs=None, draws=None, safe_checkpoint=False, restore_state_after_backward=True, return_final_state=False, callback_state=None, functional_callbacks=None, functional_callback_state=None)[source]#

Run the network for a long horizon using activation checkpointing.

This method mirrors Population.longrun_checkpointed() but is specialized for Network:

Parameters:
  • tstop (float | None) – Compatibility spelling for duration. Only complete timesteps are executed; fractional time is retained for the next duration-based network call.

  • steps – Exact non-negative timestep count, leaving retained fractional duration unchanged. Supply only one horizon argument.

  • duration – Requested simulation duration in milliseconds, using the same retained-duration budget as tstop.

  • chunklength (int | None) – Number of time steps per checkpoint chunk.

  • extra – Optional population-specific (v, waveform) mapping with the same shape and broadcasting contract as run().

  • inputs (mapping of str to dendra.func.Inputs, optional) – Deterministic time-leading voltage/current tapes with the same contract as run(). Checkpoint chunks retain their own tape slices so replay uses the same frames and preserves input gradients.

  • draws (dendra.func.RuntimeDraws, optional) – Explicit time-leading draws with the same contract as run(). Checkpoint replay consumes the same accepted-step recipes and RNG frames. Keep the tape unchanged until backward has completed. Checkpointed training requires mutation counters; clone inference tensors outside torch.inference_mode() before passing them here.

  • callbacks (sequence of Callback or dendra.func.FunctionalCallbacks, optional) – Native hook sequence, or a pure collection prepared once with dn.func.make_callbacks for this Network or a compatible initialized Network with matching timestep and mode. Pure observations read this receiver’s state with fixed prepared paths, scopes and selections. They run after clock advancement and before native post-step hooks. Native hooks retain their loop/chunk/step timing.

  • progressbar – If True, displays a tqdm progress bar over chunks.

  • safe_checkpoint (bool) – If True, clone checkpoint input tensors at each chunk boundary to guard against inadvertent in-place mutation.

  • restore_state_after_backward (bool) – If True, isolate checkpoint recomputation from the live Network state, including differentiation through pure callback results. Backward, autograd.grad and higher-order derivatives preserve the state visible before replay, including later simulation calls.

  • return_final_state (bool) – If True, return (loss, final_state_dict).

  • callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through callbacks or functional_callbacks. Resumes sampling phase and reducer totals without another initial observation.

  • functional_callbacks (dendra.func.FunctionalCallbacks, optional) – Compatibility spelling for the prepared pure collection. Use it alongside callbacks=[...] to combine native hooks and pure observations. Supply the collection through only one argument.

  • functional_callback_state (dendra.func.FunctionalCallbackState, optional) – Compatibility spelling for callback_state. Supply carry through only one argument; either collection spelling is accepted.

Returns:

Without pure observations, retains the ordinary loss or (loss, final_state_dict) return. With pure observations, returns (loss_or_none, results), or (loss_or_none, final_state_dict, results) when return_final_state=True. Results contain named observations and explicit callback carry; model state remains on the Network.

Return type:

loss or tuple

Notes

Callback contract (restricted)

To remain replay-safe under activation checkpointing, callbacks should be pure functions of the model state. Hooks may optionally return a scalar tensor loss contribution. Any non-None returns from:

  • post_step_hook(model)

  • post_chunk_hook(model, t_chunk)

  • post_loop_hook(model)

are summed and returned as the total loss.

restore_dict_from_checkpoint(state_dict)[source]#

Restore a whole-network runtime checkpoint atomically.

run(tstop=None, extra=None, callbacks=None, progressbar=False, *, steps=None, duration=None, inputs=None, draws=None, callback_state=None, functional_callbacks=None, functional_callback_state=None)[source]#

Advance the network for a timestep count or physical duration.

Parameters:
  • tstop (float, optional) – Compatibility spelling for duration. Only complete timesteps are executed. Any fractional remainder is retained and combined with the next duration-based call, so partitioned calls advance the same number of steps as their combined duration.

  • steps (int, optional) – Exact non-negative timestep count. Leaves any retained fractional duration unchanged. Supply only one of steps, duration, or tstop.

  • duration (float, optional) – Requested simulation duration in milliseconds, using the same retained-duration budget as tstop.

  • extra (dict[str, tuple[torch.Tensor, object]], optional) – Optional mapping of population name to extracellular stimulus tuple (v, waveform). For each population, v is normalized to [*batch, np, n_comp] and the time-last Waveform output to [*batch, np, n_timesteps]. Ordinary trailing broadcasting is tried first; only on failure may low-rank value axes use a right-aligned batch-only fallback. Explicit singleton axes disambiguate equal-size batch and spatial dimensions.

  • inputs (mapping of str to dendra.func.Inputs, optional) – Deterministic time-leading voltage/current tapes keyed by exact Population names. Tape lengths must equal the selected horizon’s timestep count. Fields share the conflict rules of step().

  • draws (dendra.func.RuntimeDraws, optional) – Explicit time-leading NOISE/SDE, NetStim and Poisson waveform draws, including mechanism-owned injections. Populations with randomized Poisson banks consume one bank recipe per accepted step, independently of execution chunking. Other banks retain native bulk waveform preparation. Base draws and schedules remain detached; model and stimulation parameters retain their gradients. Omission retains automatic sampling and native bank preparation cadence.

  • callbacks (sequence of Callback or dendra.func.FunctionalCallbacks, optional) – Native hook sequence, or a pure collection prepared once with dn.func.make_callbacks for this Network or a compatible initialized Network with matching timestep and mode. Pure observations read this receiver’s state with fixed prepared paths, scopes and selections. They run after clock advancement and before native post-step hooks. Native hooks retain their loop/chunk/step timing.

  • progressbar (bool or tqdm.tqdm, optional) – If truthy, show a progress bar (auto-created if True). Default False.

  • callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through callbacks or functional_callbacks. Resumes sampling phase and reducer totals without another initial observation.

  • functional_callbacks (dendra.func.FunctionalCallbacks, optional) – Compatibility spelling for the prepared pure collection. Use it alongside callbacks=[...] to combine native hooks and pure observations. Supply the collection through only one argument.

  • functional_callback_state (dendra.func.FunctionalCallbackState, optional) – Compatibility spelling for callback_state. Supply carry through only one argument; either collection spelling is accepted.

Returns:

Returns named pure observations and explicit callback carry when supplied; otherwise returns None. Model state remains on the Network. Retained observations preserve gradients and are isolated from subsequent native state mutation.

Return type:

None or dendra.func.FunctionalCallbackResults

Notes

The call that completes a retained fractional timestep supplies that step’s extra input and callbacks; inputs from earlier no-step calls are not buffered.

set_synaptic_diff_config(**kwargs)[source]#

Configure differentiation for existing event connections and NetStim schedules.

Parameters:

**kwargs – Keyword arguments forwarded to NetCon.set_diff_config(). Only diff_scheduled_times and sched_width are forwarded to an attached NetStim; omitted values for those controls use True and 1.0 respectively.

Notes

This changes connection differentiation controls, not the Network’s training/evaluation mode.

state_dict_for_checkpoint()[source]#

Return the mutable runtime state required to continue an exact replay.

Weights, delays, and other model parameters remain in state_dict(); callers restoring into a fresh object must load or construct matching parameters separately. The structure fingerprint rejects mismatched population/connection layouts and runtime backend modes before mutation.

steady_state(tstop=1000, dt=0.025, progressbar=False, max_delay_ms=None)[source]#

Run the network until it reaches a steady state.

Parameters:
  • tstop (float, optional) – Total time to run the network in ms. Default is 1000 ms.

  • dt (float, optional) – Time step in ms. Default is 0.025 ms.

  • progressbar (bool, optional) – If True, show a progress bar during the steady-state run.

  • max_delay_ms (float, optional) – Optional delay-horizon cap used when building synapse state for the steady-state/cache run. Supplying the largest delay expected in later simulations lets the cache retain enough history when delays grow after optimization updates. Later calls to initialize may keep the default reinit_weights=True and reinit_delays=True; the cached synapse histories are parameter-invariant and are replayed through the current expanded weights and delays.

Returns:

The network after running to steady state.

Return type:

Network

step(*, extra=None, inputs=None, draws=None, callbacks=None, loop_hooks=False, callback_state=None, functional_callbacks=None, functional_callback_state=None)[source]#

Advance this network by exactly one timestep.

The timestep is the network timestep established by initialize(dt) or build(dt). This method preserves the same event-delivery phase ordering as run(), but avoids constructing a one-step simulation loop.

Parameters:
  • extra (dict, optional) – Optional mapping from population name to extracellular stimulus specification (v, waveform), with the same semantics as run(). For a population shaped [*batch, np, n_comp], the spatial value is normalized to that shape and the time-last Waveform output to [*batch, np, 1]. Ordinary trailing broadcasting is tried first, followed only on failure by a low-rank, right-aligned batch-only fallback.

  • inputs (mapping of str to dendra.func.Inputs, optional) – Deterministic extracellular voltage and intracellular current frames keyed by exact Population names. A supplied ve conflicts with extra for that Population; supplied intra conflicts with registered solver stimulation. Omitted fields retain those sources.

  • draws (dendra.func.RuntimeDraws, optional) – One explicit NOISE/SDE and NetStim frame with authoritative RNG boundaries. Solver-owned intracellular and call-local extracellular Poisson banks, and mechanism-owned waveform injections, consume invocation-indexed draws in native Network order. Omission retains automatic sampling; supplied base draws and schedules remain detached.

  • callbacks (sequence of Callback or dendra.func.FunctionalCallbacks, optional) – Native hook sequence, or a pure collection prepared once with dn.func.make_callbacks for this Network or a compatible initialized Network with matching timestep and mode. Pure observations read this receiver’s state with fixed prepared paths, scopes and selections. They run after clock advancement and before native post-step hooks. Native hooks retain their loop/chunk/step timing.

  • loop_hooks (bool, optional) – If True, also call pre_loop_hook before the step and post_loop_hook after the step.

  • callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through callbacks or functional_callbacks. Resumes sampling phase and reducer totals without another initial observation.

  • functional_callbacks (dendra.func.FunctionalCallbacks, optional) – Compatibility spelling for the prepared pure collection. Use it alongside callbacks=[...] to combine native hooks and pure observations. Supply the collection through only one argument.

  • functional_callback_state (dendra.func.FunctionalCallbackState, optional) – Compatibility spelling for callback_state. Supply carry through only one argument; either collection spelling is accepted.

Returns:

Returns self for chaining when pure observations are omitted. With pure observations, returns their named results and explicit callback carry. Model state remains on the Network. Observations preserve gradients and own their sampled tensor values.

Return type:

Network or dendra.func.FunctionalCallbackResults

synapse_slots(target, synapse=None, *, slots=None, local_index=None)[source]#

Return explicit local slots of a postsynaptic mechanism.

This is a convenience wrapper around Population.slots and Slice.slots. It is useful for banked point-process mechanisms where several independent synapse slots may share one physical compartment.

train(mode=True)[source]#

Switch populations and synapses into training mode.

Parameters:

mode (bool, optional) – If True, enable training mode (grad-enabled stepping). If False, disable grads for faster inference. Default is True.

Returns:

Self, for chaining.

Return type:

Network

Notes

Dense-to-dense NetCon mode switches preserve queued deliveries and take effect immediately. A switch that crosses a compact inference or source-history runtime layout requires initialize() before the next execution call; stepping fails closed until then.

weight_modules()[source]#

Returns the weight modules of all synapses as a dictionary.

weights()[source]#

Returns the weights of all synapses as a dictionary.

Connection handles#

Connections are created by Network methods. Use their returned handles to bind live weight/time sources or schedule additional events; implementing a custom synapse does not require subclassing NetCon.

Weights use the units expected by the receiver. Built-in expsyn and exp2syn use bare numerical conductances in µS: weight=0.05 means 0.05 µS. A scheduled event’s weight is instead a dimensionless multiplier of the connection weight. See Writing your own synapse and Units used in Dendra.

class NetCon(pre, pre_idx, thresholds, post, post_idx, post_syn, weight, delay, dt, pre_var=None, max_delay=None, track_events=False, delay_backend='dense', train_delay_backend='auto', device=None, dtype=None, pre_device=None, pre_dtype=None)[source]#

Event-based connectivity wrapper between a pre-synaptic source and a post-synaptic synapse mechanism.

Overview#

A NetCon instance mediates communication between:

  • a pre-synaptic source (population module or NetStim),

  • a post-synaptic synapse mechanism (module exposing net_receive), and

  • an implicit post population that owns the synapse state.

Conceptually, each time step performs three operations:

  1. Event detection:

    • Observe a pre-synaptic variable (by default pre.v or an explicit gate on a NetStim).

    • Detect intrinsic events (hard or surrogate spiking) via threshold crossings, or directly consume externally scheduled events.

  2. Weighting and delay:

    • Combine intrinsic and scheduled events into a scalar gate per connection.

    • Multiply by a per-connection weight (optionally differentiable).

    • Write the resulting payload into a per-synapse delay line (delivery buffer) according to per-connection delays (integer or differentiable).

  3. Delivery:

    • At each step, read the current row of the delay buffer.

    • Call syn.net_receive(payload, netcon=self) on the synapse mechanism, with payload reshaped to syn.shape_f.

The class is designed to:

  • Support heterogeneous device placement for pre, post, and synapse modules.

  • Provide differentiable pathways for:

    • weights,

    • delays,

    • spiking / event detection,

    • and optionally scheduled event times.

  • Provide explicit scheduled events that can be trained by reference.

Construction and lifecycle#

NetCon objects are normally constructed by dendra.models.networks.Network during Network.build(). Initialization and stepping are managed by the network’s simulation loop.

  1. Construction (usually internal):

    nc = NetCon(
        pre=pre_pop,
        pre_idx=pre_indices,
        thresholds=thresholds,
        post=post_pop,
        post_idx=post_indices,
        post_syn=synapse_module,
        weight=weight_param,
        delay=delay_param,
        dt=dt,
        pre_var="v",         # optional
        max_delay=None,      # optional
    )
    
  2. Differentiable configuration (optional but required for training):

    Call set_diff_config() once before the first differentiable simulation step to configure which components are treated as differentiable:

    nc.set_diff_config(
        diff_weights=True,
        diff_delays=True,
        diff_spiking=True,
        diff_scheduled_times=True,
        # taps, sigma, tau, sched_width as appropriate
    )
    
  3. Initialization:

    Call initialize() before stepping:

    nc.train()         # if using standard PyTorch training mode
    nc.set_diff_config(...)  # must be called before first advance_diff
    nc.initialize(
        reinit_weights=True,
        reinit_delays=True,
        clear_deliveries=True,
    )
    

    initialize will:

    • select nc.advance to point to either advance_diff() or advance_non_diff() depending on nc.training,

    • (re)initialize weight and delay parameter modules,

    • rebuild internal delay buffers if delays changed,

    • reset the internal timing state, and

    • detach buffers from any pre-existing computation graph (fresh forward pass).

  4. Simulation loop:

    for step in range(T):
        nc.advance()  # calls advance_diff or advance_non_diff
    

    At each call, NetCon delivers events to post_syn via post_syn.net_receive(...).

Scheduling: value- vs reference-mode#

In addition to intrinsic spiking, NetCon supports scheduled events. These are particularly useful for:

  • injecting known spike trains or stimulus patterns,

  • training event weights and/or times as separate learnable tensors,

  • conditioning the synaptic drive on external controllers or task structure.

There are two orthogonal axes:

  1. Value mode (direct tensors):

    • You provide explicit event weights and/or times (as numbers or Tensors).

    • Gradients flow into those tensors if they require gradients and are wired into your optimization loop.

    Value-mode APIs:

  2. Reference mode (indices into bound sources):

    • You bind a source tensor once via bind_weight_source() or bind_time_source().

    • You then schedule events by storing integer indices into the source; the values are looked up on-the-fly during the simulation.

    • Gradients flow into the bound source tensors, not the indices.

    Reference-mode APIs:

Mixed use is allowed: you can combine intrinsic spiking, value-mode scheduled events, and reference-mode scheduled events in the same NetCon.

Order-of-operations for training scheduled weights#

To make scheduled event weights trainable by reference:

  1. Create a trainable weight source:

    # Example: one scalar weight per planned event
    sched_w = torch.nn.Parameter(
        torch.zeros(num_events, device=device, dtype=dtype)
    )
    
  2. Bind the weight source once:

    nc.bind_weight_source(sched_w)
    

    This does not copy data; it stores a reference to sched_w. The tensor must live on the same device as the synapse.

  3. Schedule events by index using schedule_ref():

    # con_indices or pre_indices must map to concrete connections
    nc.schedule_ref(
        con_indices=con_idx,   # or pre_indices=...
        times_ms=t_ms,         # float times in ms
        weight_idx=w_idx,      # Long tensor of indices into sched_w
        allow_past=False,
    )
    

    On each time step:

    • NetCon will look up per-event weights as sched_w[weight_idx].

    • These contribute to the per-connection gates, and hence to the synaptic deliveries.

    • Gradients from the loss will flow back into sched_w.

Order-of-operations for training scheduled times#

To make scheduled event times trainable by reference:

  1. Create a trainable time source:

    # Example: one scalar time per event, in ms
    sched_t = torch.nn.Parameter(
        torch.zeros(num_events, device=device, dtype=dtype)
    )
    
  2. Bind the time source once:

    nc.bind_time_source(sched_t)
    
  3. Schedule events by time index using schedule_time_ref():

    nc.schedule_time_ref(
        con_indices=con_idx,   # or pre_indices=...
        time_idx=t_idx,        # Long tensor of indices into sched_t
        weight=1.0,            # scalar or tensor (value mode)
        allow_past=False,
    )
    

    On each time step:

    • NetCon will read the current values from sched_t[time_idx].

    • The resulting times are interpreted in one of two ways:

      • If diff_scheduled_times=True in set_diff_config(), events are smeared with a differentiable triangular kernel over time steps, so gradients can move event times.

      • If diff_scheduled_times=False, each time is assigned to the first integer step at or after the event and treated as exact.

    In both cases, gradients flow into sched_t when using the differentiable configuration.

Interactions with global time#

Many scheduling methods accept an allow_past flag:

  • When allow_past=False (default), events whose scheduled steps are earlier than the current internal global_step are silently dropped.

  • When allow_past=True, events are kept regardless of their scheduled step index.

In practice, this means that you usually want to:

  • Call initialize() (which also sets global_step) before scheduling events, or

  • Explicitly pass allow_past=True when scheduling relative to a fixed origin (e.g., step 0) while reusing a NetCon.

Notes

  • NetCon automatically tracks and realigns its internal buffers when moved across devices via .to(...) or when the peer modules move.

  • The class is intentionally conservative about in-loop memory allocation: buffers are pre-allocated where possible and reused across steps.

param pre:

Pre-synaptic population module or NetStim. The module must implement device() and dtype(); when pre is not a NetStim, it is also expected to expose the attribute named by pre_var (e.g., v) which holds the pre-synaptic state used for spiking.

type pre:

Population or NetStim

param pre_idx:

1-D Long tensor of indices into the flattened pre-synaptic variable (e.g., pre.v.view(-1)[pre_idx]). Length defines the number of managed connections.

type pre_idx:

torch.Tensor

param thresholds:

Per-connection spiking thresholds in the same shape as pre_idx. Entries may be NaN to indicate:

  • all-NaN: skip thresholding and treat the selected pre variable as a continuous gate;

  • mixed: apply thresholding for finite entries, and use the raw pre variable wherever the threshold is NaN.

type thresholds:

torch.Tensor

param post:

Post-synaptic population module that owns the synapse mechanism. Must implement device() and dtype() interfaces and is used mainly for device alignment.

type post:

Population

param post_idx:

1-D Long tensor of indices into the flattened synapse output space; used to scatter connection events into the synapse’s delivery buffer.

type post_idx:

torch.Tensor

param post_syn:

Synapse mechanism module. Must expose:

  • shape_f: final tensor shape of per-synapse payloads, and

  • net_receive(payload, netcon): function invoked each step with delivery buffer slice reshaped to shape_f.

type post_syn:

dendra.models.mechanisms.Synapse

param weight:

Parameter-like module representing per-connection weights. Must support:

  • weight.init(reinit: bool),

  • weight() returning the current weight tensor, and

  • weight.w exposing the underlying tensor.

type weight:

torch.nn.Module

param delay:

Parameter-like module representing per-connection delays in ms. Must support:

  • delay.init(reinit: bool) and

  • delay() returning the current delays tensor.

type delay:

torch.nn.Module

param dt:

Simulation time step in milliseconds.

type dt:

float

param pre_var:

Name of the attribute on pre to use as the spiking variable when pre is not a NetStim. Defaults to "v".

type pre_var:

str, optional

param max_delay:

Optional maximum delay (ms). If provided, the internal delay buffer depth is set to int(max_delay / dt) + 1; otherwise it is inferred from the maximum delay in delay.

type max_delay:

float, optional

param track_events:

If True, allocate and maintain the historical event_queue used for per-connection delivery introspection. If False (default), skip the large [max_delay_steps, n_connections] int32 queue and keep only the lightweight current-step events buffer, which is zeroed on each non-differentiable step.

type track_events:

bool, optional

param delay_backend:

Delay-line implementation for non-differentiable inference. The default "dense" keeps the existing [max_delay_steps, syn_numel] ring buffer, but uses precomputed integer-delay routing metadata and specialized uniform-/mixed-delay hot paths. The "sparse_calendar" backend stores pending nonzero inference deliveries in a compact tensor calendar and uses only a reusable one-row dense scratch buffer before calling syn.net_receive(...). "bitpacked_history" is an inference-only source-spike history backend for large SNNs: it stores only packed source spikes over the delay horizon and reconstructs the dense postsynaptic receive payload with a lazy C++/CUDA extension on eligible CUDA paths, falling back to PyTorch otherwise. The separate Triton implementation is an experimental/reference path and is not selected automatically.

type delay_backend:

{“dense”, “sparse_calendar”, “bitpacked_history”}, optional

param train_delay_backend:

Differentiable training delay backend. "dense" preserves the fully general dense differentiable delay buffer. "source_history" uses source-level spike/gate history when the NetCon has exact source-level event semantics. With diff_spiking=False this uses packed boolean source history and still differentiates weights and delays for realized events. With diff_spiking=True this uses a floating source-gate history so surrogate gradients can flow through source-level thresholding. "auto" selects source history when exact and otherwise falls back to dense. Default is "auto" so source-level projections use the compact training backend when it is safe, while per-connection/scheduled cases retain dense semantics.

type train_delay_backend:

{“dense”, “source_history”, “auto”}, optional

Notes

This constructor is typically invoked by dendra.models.networks.Network during Network.build(); user code usually interacts with NetCon via high-level network building APIs rather than constructing it directly.

bind_time_source(source)[source]#

Bind a tensor providing per-event times (ms) for reference-mode scheduling.

This method supplies live indexed times for schedule() through time_idx and for its schedule_time_ref() adapter. Instead of storing times directly in NetCon, you bind a tensor (usually a parameter) and then reference entries in that tensor by integer indices.

Parameters:

source (torch.Tensor) –

Tensor containing candidate event times in milliseconds. It must:

  • reside on the same device as the synapse (self.device), and

  • have a size at least as large as any time_idx used in schedule() or schedule_time_ref().

Typically this is a torch.nn.Parameter or another tensor that participates in the training loop.

Notes

Order of operations:

  1. Construct the time source tensor (e.g. nn.Parameter in ms).

  2. Call netcon.bind_time_source(time_source).

  3. Use schedule() with time_idx values indexing into the bound tensor.

  • Calling this replaces any previously bound time source.

  • The tensor is not copied; NetCon reads from it at runtime.

  • When used with set_diff_config(diff_scheduled_times=True)(), and when the bound tensor requires gradients, event times become differentiable via the triangular timing kernel.

bind_weight_source(source)[source]#

Bind a tensor providing per-event weights for reference-mode scheduling.

This method supplies live indexed weights for schedule() through weight_idx and for its schedule_ref() adapter. Instead of storing per-event weights directly inside NetCon, you bind a tensor (usually a parameter) and then refer to entries in that tensor by integer indices.

Parameters:

source (torch.Tensor) –

Tensor containing candidate dimensionless multipliers for scheduled events. Each value multiplies the target-unit base connection weight; it is not itself another target-unit weight. It must:

  • reside on the same device as the synapse (self.device), and

  • have a size at least as large as any weight_idx used in schedule() or schedule_ref().

Typically this is a torch.nn.Parameter or another tensor that participates in the training loop.

Notes

Order of operations:

  1. Construct the weight source tensor (e.g. nn.Parameter).

  2. Call netcon.bind_weight_source(weight_source) exactly once (or whenever you want to replace the source).

  3. Use schedule() with weight_idx values indexing into the bound tensor.

  • Calling this replaces any previously bound weight source.

  • The tensor is not copied; NetCon keeps a reference and reads from it during simulation.

  • Gradients flow into the bound tensor through differentiable schedule evaluation. diff_weights separately controls base connection weight gradients.

clear_schedule()[source]#

Remove all scheduled events and reset scheduling-related buffers.

This clears both value-mode and reference-mode scheduled events:

  • connection indices (sched_con_idx),

  • absolute step indices (sched_abs_step),

  • value-mode weights and times (sched_weight, sched_time_ms),

  • reference-mode indices (sched_weight_idx, sched_time_idx),

  • per-connection introspection statistics (sched_wsum, sched_counts).

The bound sources set via bind_weight_source() and bind_time_source() are not modified.

Notes

  • This is typically called between episodes or trials when you want to reuse the same NetCon instance but with a fresh schedule.

detach()[source]#

Detach runtime history and defer fresh effective parameter graphs.

Pending deliveries retain their enqueue-time values. Raw parameter and schedule sources remain unchanged; initialized quantized routing stays fixed until initialization. Network execution reconnects pending weight and delay materializations at its next gradient-enabled training boundary.

restore_dict_from_checkpoint(state_dict)[source]#

Restore the state of this NetCon from a checkpoint dictionary created by state_dict_for_checkpoint().

Important checkpointing detail: - delivery_buffer must be rebound directly (to preserve gradient flow). - non-differentiable tensors that NetCon mutates in-place should be cloned here to avoid in-place mutation of checkpoint inputs inside a chunk.

This matches the expectation in longrun_checkpointed that restore rebinds mutable tensors.

schedule(*, con_indices=None, pre_indices=None, times_ms=None, weight=1.0, time_idx=None, weight_idx=None, allow_past=False)[source]#

Schedule events with direct values or indexed bound sources.

Direct weights and times are declaration-time tensors owned by the NetCon. Indexed values are gathered from the corresponding bound source during simulation; both quantities can use indexed sources on the same events.

Exactly one of con_indices or pre_indices must be provided.

Parameters:
  • con_indices (Sequence[int] or torch.Tensor, optional) – Explicit connection indices at which to schedule events. Must be in [0, num_connections). Mutually exclusive with pre_indices.

  • pre_indices (Sequence[int] or torch.Tensor, optional) – Pre-synaptic indices. These are expanded internally to a set of connection indices using the pre→connection CSR map (see _expand_pre_to_con()). Mutually exclusive with con_indices.

  • times_ms (Sequence[float] or torch.Tensor, optional) – Event times in milliseconds. Must be broadcast-compatible with the selected connections after filtering out past events (see allow_past). Times are converted to steps via the first grid step at or after the event for non-differentiable scheduling, and interpreted as continuous values when diff_scheduled_times=True. Omit when using time_idx.

  • weight (float or torch.Tensor, optional) –

    Dimensionless scalar or per-event weight multiplier applied on top of the base connection weights returned by self.weight(). It is not another value in the target synapse’s weight unit. Accepted shapes:

    • scalar (single value): broadcast to all scheduled events;

    • tensor of length E_before (events before past-event filtering): will be sliced by the filter; or

    • tensor of length E_after (events after filtering): used as is.

    When provided as a tensor requiring gradients, and when differentiable scheduling is enabled, gradients will flow into this tensor.

  • time_idx (Sequence[int] or torch.Tensor, optional) – Nonnegative per-event indices into the tensor supplied to bind_time_source(). Mutually exclusive with times_ms.

  • weight_idx (Sequence[int] or torch.Tensor, optional) – Nonnegative per-event indices into the tensor supplied to bind_weight_source(). Referenced weights use that source alone: omit weight or pass None. The default numeric weight=1.0 is treated as omitted.

  • allow_past (bool, optional) – If False (default), events whose scheduled integer step is smaller than the current global_step are dropped. If True, no such filtering is applied.

Notes

  • Direct values are stored in self.sched_weight and self.sched_time_ms; indexed quantities have zero value slots.

  • schedule_ref() and schedule_time_ref() are compatible adapters for declarations with one indexed quantity.

  • This method can be called multiple times; new events are appended.

schedule_ref(*, con_indices=None, pre_indices=None, times_ms=None, weight_idx=None, allow_past=False)[source]#

Schedule reference-mode events with weights drawn from a bound source.

This is the compatible adapter for schedule() with weight_idx.

This API is the reference-mode counterpart to schedule(). Instead of passing explicit weights, you pass integer indices into a tensor that has previously been bound via bind_weight_source().

Exactly one of con_indices or pre_indices must be provided, and bind_weight_source() must have been called beforehand.

Parameters:
  • con_indices (Sequence[int] or torch.Tensor, optional) – Explicit connection indices at which to schedule events. Mutually exclusive with pre_indices.

  • pre_indices (Sequence[int] or torch.Tensor, optional) – Pre-synaptic indices to expand to connection indices via the CSR map (see _expand_pre_to_con()). Mutually exclusive with con_indices.

  • times_ms (Sequence[float] or torch.Tensor) – Event times in milliseconds, one per event. Assigned to the first grid step at or after each event for non-differentiable behavior; used as continuous times when diff_scheduled_times=True.

  • weight_idx (Sequence[int] or torch.Tensor) – Integer indices into the tensor bound by bind_weight_source(). Must have the same length as times_ms and con_indices / expanded connections.

  • allow_past (bool, optional) – If False (default), events scheduled before the current global_step are discarded. If True, no filtering is applied.

Notes

Reference-mode scheduling is designed for scenarios where you want scheduled weights to be:

  • shared across multiple events or NetCon instances,

  • trained by a separate module or optimizer, or

  • constrained/regularized jointly (e.g., via an external loss).

Because the weight values are read from a shared tensor at runtime, gradients from all events that reference a given index accumulate into that entry.

Order of operations:

  1. Bind a weight source tensor:

    nc.bind_weight_source(weight_source)
    
  2. Schedule reference-mode events:

    nc.schedule_ref(
        con_indices=...,
        times_ms=...,
        weight_idx=...,
    )
    
  3. Run simulation (nc.advance() in a loop).

  • If bind_weight_source() has not been called, this method raises a RuntimeError.

  • The value-mode slots for weights are still allocated but set to zero; only reference-mode contributions are active for these events.

schedule_time_ref(*, con_indices=None, pre_indices=None, time_idx=None, weight=1.0, allow_past=False)[source]#

Schedule events whose times come by reference from a bound tensor.

This is the compatible adapter for schedule() with time_idx.

This API is the time-reference analogue of schedule(). Instead of providing explicit event times, you provide integer indices into a tensor bound via bind_time_source(). Weights are still supplied in value mode.

Exactly one of con_indices or pre_indices must be provided, and bind_time_source() must have been called beforehand.

Parameters:
  • con_indices (Sequence[int] or torch.Tensor, optional) – Explicit connection indices for the events.

  • pre_indices (Sequence[int] or torch.Tensor, optional) – Pre-synaptic indices, expanded to connection indices via the CSR map.

  • time_idx (Sequence[int] or torch.Tensor) – Integer indices into the tensor bound via bind_time_source(). Must match the number of events after expanding pre_indices if used.

  • weight (float or torch.Tensor, optional) – Dimensionless value-mode weight multiplier, as in schedule(). May be a scalar or a per-event tensor of length equal to the number of scheduled events. Gradients can flow into this tensor when differentiable scheduling is enabled.

  • allow_past (bool, optional) – If False (default), events whose current time (from the bound source) would be in the past relative to global_step are dropped. If True, keep all events.

Notes

Time-reference scheduling is designed for scenarios where you want to:

  • train event times explicitly as parameters,

  • share timing parameters across multiple events,

  • or couple event times to other model components (e.g., another network).

When used with diff_scheduled_times=True in set_diff_config(), gradients flow into the bound time tensor and can move events in time.

Order of operations:

  1. Bind a time source tensor:

    nc.bind_time_source(time_source)
    
  2. Schedule events by time index:

    nc.schedule_time_ref(
        con_indices=...,
        time_idx=...,
        weight=...,
    )
    
  3. Run simulation (nc.advance() in a loop).

  • If bind_time_source() has not been called, this method raises a RuntimeError.

  • The value-mode time slot in sched_time_ms is populated with zeros; the actual times are obtained at runtime from the bound tensor via sched_time_idx.

set_diff_config(diff_weights=True, diff_delays=True, diff_spiking=True, taps=2, sigma=0.35, tau=0.1, diff_scheduled_times=True, sched_width=1.0, train_delay_backend=None)[source]#

Configure differentiable behavior for training.

This method must be called before the first call to advance_diff() (via NetCon.advance in training mode). It controls which aspects of the connection are treated as differentiable and how.

Parameters:
  • diff_weights (bool, optional) – If True (default), synaptic weights are treated as differentiable parameters. If False, the weight tensor returned by self.weight() is detached before being used to compute deliveries, freezing its contribution during training.

  • diff_delays (bool, optional) – If True (default), delays are interpreted as continuous values in milliseconds and used with a soft, differentiable interpolation scheme over time steps (2-tap linear or 3-tap Gaussian, see taps and sigma). If False, delays are rounded to integer steps and used as hard delay lines.

  • diff_spiking (bool, optional) – If True (default), pre-synaptic spiking is computed via a surrogate gradient function (see update_active_diff()), allowing gradients to flow through threshold crossings. If False, hard thresholding via update_active() is used, yielding non- differentiable (boolean) spikes.

  • taps (int, optional) –

    Number of interpolation taps to use when diff_delays=True.

    • 2 (default): 2-tap linear interpolation between adjacent steps.

    • 3: 3-tap Gaussian-like interpolation weighted by sigma.

  • sigma (float, optional) – Standard deviation (in steps) for the 3-tap Gaussian interpolation when taps=3. Ignored for taps=2.

  • tau (float, optional) – Temperature parameter for surrogate spiking, passed through to update_active_diff() as tau. Lower values yield a steeper surrogate; higher values produce smoother gates.

  • diff_scheduled_times (bool, optional) – If True (default), scheduled event times (including those provided via schedule_time_ref()) are handled via a differentiable triangular kernel over time steps. This allows gradients to move event times when they come from value- or reference-mode tensors. If False, scheduled times are assigned to the first integer step at or after the event, and timing behavior is non-differentiable.

  • sched_width (float, optional) – Half-width of the triangular kernel (in steps) when diff_scheduled_times=True. A value of 1.0 yields contributions spread over approximately 2 steps around the nominal event time.

  • train_delay_backend ({"dense", "source_history", "auto"}, optional) – Optional per-NetCon training backend override. "source_history" requires source-level event semantics; "auto" uses source history when exact and otherwise keeps the dense differentiable path.

Notes

  • set_diff_config does not itself change training mode; it only records configuration flags. NetCon.advance will dispatch to advance_diff() when self.training = True and to advance_non_diff() otherwise.

  • track_events=True is supported in training only when delays, spiking, and scheduled times all use hard semantics. Surrogate or fractional deliveries do not define unambiguous integer event counts.

state_cache()[source]#

Package runtime state for Network.cache_state()/steady_state().

This cache is detached and normalized to a zero current_time_step. It is intentionally distinct from state_dict_for_checkpoint(), which is used for BPTT/checkpoint replay and may need to preserve autograd history.

state_dict_for_checkpoint()[source]#

Return a state dictionary suitable for gradient checkpointing / long-run chunking.

This should include ONLY mutable tensors that affect future dynamics and are mutated by advance_*(). The returned structure must be stable across chunks (same keys; same shapes).

Notes

  • This is not a full PyTorch state_dict. It is the minimal mutable runtime state needed to resume stepping identically mid-simulation.

  • Do NOT include weights/delays/modules here; those are model params and remain constant across a forward.

  • Tracked event counts are public runtime state. events records the most recently delivered counts, while the dense event_queue (or a compact backend’s event calendar) determines future observations; both are retained so checkpoint replay preserves event introspection.

property w#

Raw synaptic weight tensor for this NetCon.

Returns:

The underlying weight tensor managed by the weight parameter module (i.e., self.weight.w). This tensor has one entry per connection and is typically used for:

  • inspection and diagnostics,

  • direct regularization or constraints,

  • manual initialization or export.

Return type:

torch.Tensor

Notes

To obtain the current weight values used during simulation steps (which may include functional transformations), use self.weight() instead of accessing w directly.

class ContinuousCon(pre, pre_idx, post, post_idx, post_syn, weight, delay, dt, pre_var=None, input=None, reduce='sum', max_delay=None, transform=None, reset_inputs=False, device=None, dtype=None, pre_device=None, pre_dtype=None)[source]#

Continuous analog projection between a presynaptic variable and a postsynaptic mechanism.

ContinuousCon is the analog counterpart of NetCon: it gathers a presynaptic variable, applies optional weighting and integer delay, scatters the resulting values into the target synapse’s local shape, and calls syn.continuous_receive(...). It performs no thresholding and no event detection.

The hot path is specialized at construction / delay-rebuild time. Static delay masks, selected post indices, flat delay-buffer offsets, and dispatch mode are precomputed once so advance() does not repeatedly build masks or check for empty delayed subsets.

detach()[source]#

Detach continued state while preserving raw parameter sources.

n_connections()[source]#

Return the number of directed continuous connections as a Python integer.

state_cache()[source]#

Package runtime state for Network.cache_state()/steady_state().

Unlike state_dict_for_checkpoint(), this cache is detached and normalized so it can be restored by Network.initialize(…): row 0 of the cached delivery buffer is the next row due after the cached state.

state_dict_for_checkpoint()[source]#

Return the live delay queue, masks, and clock tensors for exact continuation.

Returns:

Runtime tensors retained by reference. Use state_cache() for a detached initialization cache instead.

Return type:

dict

restore_dict_from_checkpoint(state_dict)[source]#

Validate and restore an exact runtime checkpoint in place.

Parameters:

state_dict (dict) – Runtime queue and clock tensors compatible with this connection’s layout.

NetStim#

NetStim generates stochastic renewal events and accepts predetermined schedules. Use explicit initialization/runtime draws for reproducible replay; see Stimulation, input tapes and randomness.

class NetStim(N=1, interval=10.0, start=0.0, noise=0.0, max_spikes=1000000000.0, tau=0.1, seed=None, device=None, dtype=None)[source]#

Differentiable spike generator modeled after NEURON’s NetStim.

The last tensor dimension indexes the N independent NetStim generators. Any leading dimensions are treated as batch dimensions. For example, an unbatched instance with N == i has state/parameter shape (i,); after batch(n) the shape is (n, i). Calling batch again prepends another leading batch dimension rather than flattening generators.

Each generator produces a renewal process with mean interval interval. A noise parameter blends deterministic intervals with exponential variability:

\[T_{k+1} = T_k + (1 - \eta)\,\Delta + \eta\,\Delta\,E,\]

where Delta = interval, eta = noise in [0,1], and E is unit-rate exponential. When eta=0 firing is periodic; when eta=1 firing is Poisson with rate 1/interval. The initial clock is start + noise * interval * E, or start when noise=0; a sampled call emits the spike at or after that clock. A straight-through estimator gate provides a hard spike mask for simulation while preserving gradients through the soft sigmoid surface, enabling differentiation w.r.t. interval parameters.

Parameters:
  • N (int, optional) – Number of independent generators in the final dimension. Default is 1.

  • interval (float or Iterable[float] or torch.Tensor, optional) – Mean inter-spike interval (ms). Can be scalar, per-generator with shape (N,), or broadcastable to a shape ending in N. Default is 10.0.

  • start (float or Iterable[float] or torch.Tensor, optional) – Start time (ms) after which spikes may occur. Can be scalar, per-generator, or batched/broadcastable. Default is 0.0.

  • noise (float or Iterable[float] or torch.Tensor, optional) – Randomness in [0, 1]; 0=deterministic, 1=Poisson. Can be scalar, per-generator, or batched/broadcastable. Default is 0.0.

  • max_spikes (int or Iterable[int] or torch.Tensor, optional) – Maximum spikes per generator. Can be scalar, per-generator, or batched/broadcastable. Default is 1e9.

  • tau (float, optional) – Sigmoid temperature for the straight-through gate (ms). Default is 0.1.

  • seed (int, optional) – Seed for reproducible randomness. Default is None.

  • device (str or torch.device, optional) – Tensor device. Uses the Dendra context, defaulting to CPU.

  • dtype (torch.dtype or str, optional) – Floating-point dtype. Uses the Dendra context, defaulting to float32.

batch(n)[source]#

Prepend one or more batch dimensions to this NetStim in-place.

Unlike the previous flattening behavior, batch(n) transforms an unbatched shape (N,) into (n, N). Existing leading dimensions are preserved, so another batch(m) gives (m, n, N). Each replicated state element receives its own stochastic draw and schedule heap.

Parameters:

n (int or Iterable[int]) – Batch dimension(s) to prepend. All must be positive.

Returns:

Self, with parameters and state expanded over the new leading batch dimensions.

Return type:

NetStim

bind_time_source(source)[source]#

Bind a tensor that provides scheduled-event times, in ms, by index.

bind_weight_source(source)[source]#

Bind a tensor that provides scheduled-event amplitudes by index.

clear_schedule(indices=None)[source]#

Remove scheduled spikes for selected state elements, or all if None.

detach()[source]#

Detach state tensors from any computation graph.

Returns:

Self, detached in-place.

Return type:

NetStim

device()[source]#

Device on which the generator state lives.

Returns:

Device of internal buffers.

Return type:

torch.device

dtype()[source]#

Data type used by generator state.

Returns:

Dtype of internal buffers.

Return type:

torch.dtype

freeze()[source]#
initialize()[source]#

Reset generator state while preserving scheduled spikes.

Notes

  • next_stoch_time is set to start plus an exponential offset when noise>0 so the first interval is drawn from the same renewal distribution used during stepping.

  • Scheduled spikes already enqueued via schedule() are retained.

renewal_parameters()[source]#

Derive renewal inputs from their current registered raw sources.

restore_dict_from_checkpoint(state_dict)[source]#

Restore a NetStim runtime checkpoint atomically.

schedule(indices, times=None, weight=1.0, *, times_ms=None, allow_past=False, differentiable=None, time_idx=None, weight_idx=None)[source]#

Add explicit scheduled spikes, optionally with differentiable weights/times.

differentiable=True selects tensor scheduling; False selects the consuming unit-amplitude calendar. When omitted, times requiring gradients, tensor/list weights, or non-unit scalar weights select tensor scheduling. Other unit-amplitude events use a cached compact calendar retaining Python-float precision. Calendar events are consumed at the first sampled time at or beyond their head, coalescing overdue events into one spike. Tensor schedules reevaluate on each call and assign hard events causally to the first fixed-step grid point at or after their absolute time.

Tensor schedules contribute their amplitude to spike_gate; downstream NetCons must use diff_spiking=True to propagate gradients into the scheduled times or weights.

time_idx reads live times from bind_time_source instead of times/times_ms. weight_idx reads live amplitudes from bind_weight_source instead of weight. Either or both fields may be indexed. Referenced fields have no additive value offset: the default unit weight (or None) is omitted when weight_idx is supplied. Indices must be nonnegative. Indexed events use tensor storage; differentiable=False selects the incompatible consuming calendar.

schedule_ref(indices, times=None, weight_idx=None, *, times_ms=None, allow_past=False)[source]#

Schedule events whose amplitudes are read from a bound weight source.

schedule_time_ref(indices, time_idx, weight=1.0, *, allow_past=False)[source]#

Schedule events whose times are read from a bound time source.

set_diff_config(*, diff_scheduled_times=True, sched_width=1.0, **_)[source]#

Configure differentiable tensor-backed scheduled events.

This mirrors the scheduled-time portion of NetCon.set_diff_config. Tensor-backed schedules use spike_gate for differentiable amplitudes; downstream NetCons must use diff_spiking=True to consume that gate.

state_dict_for_checkpoint()[source]#

Return a replay-safe snapshot of NetStim dynamic state.

This is intended for activation checkpointing in long unrolled runs. Key points:

  • We MUST include the per-instance torch.Generator RNG state, because torch.utils.checkpoint can preserve global RNG state, but not custom Generator objects passed via generator=….

  • Scheduled spikes use a fixed compact calendar and explicit cursor. Legacy remaining-heap records and full original heap layouts retain compatibility with old checkpoints and later NaN insertions.

  • shape is stored so batched checkpoint restore can rebuild the flat schedule heap layout.

Returns:

A lightweight state snapshot that can be passed through torch.utils.checkpoint and used to deterministically restore the NetStim internal state.

Return type:

dict

unfreeze()[source]#

Low-level pure projection interfaces are documented in Functional plans and tensor packets.