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
Networkbundles:Populations: named collections of axons/neurons (
Populationinstances).NetCons: directed connections materialized as
NetConobjects that deliver events from pre- to post-synaptic compartments (including optional weights, delays, thresholds, and alternate pre variables such as conductance).NetStim: an optional
NetStimsource that injects spikes into the network (treated as a special “population” namednetstim).
Connections are specified incrementally (e.g., via
connect_one_to_one(),connect_dense(),connect_prob(),connect_prob_n()), then materialized whenbuild()/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 dodtchanges orforce_rebuild=True). Callbuild()(and typicallyinitialize()) 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
Populationinstance. 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 withattach_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_queueused for delivery introspection. If False (default), NetCons skip that large debug queue during inference and keep only the lightweight current-stepeventsbuffer.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 existingnet_receivedense-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; withdiff_spiking=Falsethis uses packed hard source spikes and withdiff_spiking=Truethis 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
NetStimafter 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. Callbuild()or, normally,initialize()before the nextrun(). 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:
- 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:
- 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:
- 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:
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.
- 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.
targetmay be a physical population/slice, or aSynapseSlotsobject returned bypopulation.slots(...),slice.slots(...), ornetwork.synapse_slots(...). Slot targets remove the ambiguity that arises when a banked point-process mechanism has several local slots on one physical compartment.delayis in ms.thresholduses the coordinate ofpre_var(mV for the default membrane-voltage source); useNonewhen the source already provides discrete events.weightis target-defined. Built-in point-processexpsynandexp2syntargets expect a bare numerical value in µS, soweight=0.05means 0.05 µS and must not be multiplied bydendra.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
SynapseSlotstarget is already in synapse-local coordinates and avoids ambiguous colocated slots.delayis in ms. The product ofweightand the optionally transformedpre_varmust have the unit expected by the receivinginputbuffer; there is no universal continuous-connection weight unit. For the built-in density-stylegraded_syndriven by its dimensionless release gate,weightandg_preare 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 followconnect()’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-styleconnectentry point, the legacy wrapper keeps autapses disabled by default. Threshold, weight, and delay followconnect()’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 NESTpairwise_bernoulliand usesprobas the pairwise connection probability.strategy='poisson'or'pairwise_poisson'maps to NESTpairwise_poissonand usesprobaspairwise_avg_num_conns; for that rule,allow_multapsesmust beTrue. Threshold, weight, and delay followconnect()’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
nrandom pre-post pairs.This maps to NEST
fixed_total_number. Withallow_multapses=True, pairs are drawn with replacement. Withallow_multapses=Falsethe sampled source-target pairs are unique. Threshold, weight, and delay followconnect()’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.
targetmay be aSynapseSlotsobject, or a population/slice plussynapseandslots/local_index. This is the public API for banked point processes with multiple colocated local slots. Threshold, weight, and delay followconnect()’s unit contract.
- 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_statemethod.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:
- 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().
- 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:
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.wbuffers 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:
- 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.
longrunhas the same timestep and event-delivery semantics asrun(), 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 nextrun(),longrun(), orlongrun_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 asrun().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; changingchunklengthdoes 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_callbacksfor 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
callbacksorfunctional_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:
- 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 forNetwork:dtis not an argument here. The network time step is fixed byinitialize()/build()(required for constructingNetCondelay buffers).Simulation state is checkpointed at chunk boundaries via
state_dict_for_checkpoint()/restore_dict_from_checkpoint().
- 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 asrun().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 outsidetorch.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_callbacksfor 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.gradand 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
callbacksorfunctional_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)whenreturn_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-
Nonereturns 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, ortstop.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,vis 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_callbacksfor 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
callbacksorfunctional_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:
Notes
The call that completes a retained fractional timestep supplies that step’s
extrainput 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(). Onlydiff_scheduled_timesandsched_widthare 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
initializemay keep the defaultreinit_weights=Trueandreinit_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:
- 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)orbuild(dt). This method preserves the same event-delivery phase ordering asrun(), 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 asrun(). 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
veconflicts withextrafor that Population; suppliedintraconflicts 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_callbacksfor 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 callpre_loop_hookbefore the step andpost_loop_hookafter the step.callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through
callbacksorfunctional_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
selffor 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:
- 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.slotsandSlice.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:
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.
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
NetConinstance mediates communication between:a pre-synaptic source (population module or
NetStim),a post-synaptic synapse mechanism (module exposing
net_receive), andan implicit post population that owns the synapse state.
Conceptually, each time step performs three operations:
Event detection:
Observe a pre-synaptic variable (by default
pre.vor an explicit gate on aNetStim).Detect intrinsic events (hard or surrogate spiking) via threshold crossings, or directly consume externally scheduled events.
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).
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 tosyn.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#
NetConobjects are normally constructed bydendra.models.networks.NetworkduringNetwork.build(). Initialization and stepping are managed by the network’s simulation loop.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 )
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 )
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, )
initializewill:select
nc.advanceto point to eitheradvance_diff()oradvance_non_diff()depending onnc.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).
Simulation loop:
for step in range(T): nc.advance() # calls advance_diff or advance_non_diff
At each call,
NetCondelivers events topost_synviapost_syn.net_receive(...).
Scheduling: value- vs reference-mode#
In addition to intrinsic spiking,
NetConsupports 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:
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:
schedule_time_ref()withweightspecified as a Tensor.
Reference mode (indices into bound sources):
You bind a source tensor once via
bind_weight_source()orbind_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:
schedule_ref()for reference-mode weights,schedule_time_ref()for reference-mode times.
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:
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) )
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.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:
NetConwill look up per-event weights assched_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:
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) )
Bind the time source once:
nc.bind_time_source(sched_t)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:
NetConwill read the current values fromsched_t[time_idx].The resulting times are interpreted in one of two ways:
If
diff_scheduled_times=Trueinset_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_twhen using the differentiable configuration.
Interactions with global time#
Many scheduling methods accept an
allow_pastflag:When
allow_past=False(default), events whose scheduled steps are earlier than the current internalglobal_stepare 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 setsglobal_step) before scheduling events, orExplicitly pass
allow_past=Truewhen scheduling relative to a fixed origin (e.g., step 0) while reusing aNetCon.
Notes
NetConautomatically 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 implementdevice()anddtype(); whenpreis not aNetStim, it is also expected to expose the attribute named bypre_var(e.g.,v) which holds the pre-synaptic state used for spiking.- type pre:
- 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()anddtype()interfaces and is used mainly for device alignment.- type post:
- 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, andnet_receive(payload, netcon): function invoked each step with delivery buffer slice reshaped toshape_f.
- type post_syn:
- param weight:
Parameter-like module representing per-connection weights. Must support:
weight.init(reinit: bool),weight()returning the current weight tensor, andweight.wexposing 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)anddelay()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
preto use as the spiking variable whenpreis not aNetStim. 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 indelay.- type max_delay:
float, optional
- param track_events:
If True, allocate and maintain the historical
event_queueused for per-connection delivery introspection. If False (default), skip the large[max_delay_steps, n_connections]int32 queue and keep only the lightweight current-stepeventsbuffer, 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 callingsyn.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. Withdiff_spiking=Falsethis uses packed boolean source history and still differentiates weights and delays for realized events. Withdiff_spiking=Truethis 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.NetworkduringNetwork.build(); user code usually interacts withNetConvia 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()throughtime_idxand for itsschedule_time_ref()adapter. Instead of storing times directly inNetCon, 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), andhave a size at least as large as any
time_idxused inschedule()orschedule_time_ref().
Typically this is a
torch.nn.Parameteror another tensor that participates in the training loop.
Notes
Order of operations:
Construct the time source tensor (e.g.
nn.Parameterin ms).Call
netcon.bind_time_source(time_source).Use
schedule()withtime_idxvalues indexing into the bound tensor.
Calling this replaces any previously bound time source.
The tensor is not copied;
NetConreads 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()throughweight_idxand for itsschedule_ref()adapter. Instead of storing per-event weights directly insideNetCon, 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), andhave a size at least as large as any
weight_idxused inschedule()orschedule_ref().
Typically this is a
torch.nn.Parameteror another tensor that participates in the training loop.
Notes
Order of operations:
Construct the weight source tensor (e.g.
nn.Parameter).Call
netcon.bind_weight_source(weight_source)exactly once (or whenever you want to replace the source).Use
schedule()withweight_idxvalues indexing into the bound tensor.
Calling this replaces any previously bound weight source.
The tensor is not copied;
NetConkeeps a reference and reads from it during simulation.Gradients flow into the bound tensor through differentiable schedule evaluation.
diff_weightsseparately 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()andbind_time_source()are not modified.Notes
This is typically called between episodes or trials when you want to reuse the same
NetConinstance 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_indicesorpre_indicesmust 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 withpre_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 withcon_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 whendiff_scheduled_times=True. Omit when usingtime_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; ortensor 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 withtimes_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: omitweightor passNone. The default numericweight=1.0is treated as omitted.allow_past (bool, optional) – If False (default), events whose scheduled integer step is smaller than the current
global_stepare dropped. If True, no such filtering is applied.
Notes
Direct values are stored in
self.sched_weightandself.sched_time_ms; indexed quantities have zero value slots.schedule_ref()andschedule_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()withweight_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 viabind_weight_source().Exactly one of
con_indicesorpre_indicesmust be provided, andbind_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 withcon_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 astimes_msandcon_indices/ expanded connections.allow_past (bool, optional) – If False (default), events scheduled before the current
global_stepare 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
NetConinstances,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:
Bind a weight source tensor:
nc.bind_weight_source(weight_source)Schedule reference-mode events:
nc.schedule_ref( con_indices=..., times_ms=..., weight_idx=..., )
Run simulation (
nc.advance()in a loop).
If
bind_weight_source()has not been called, this method raises aRuntimeError.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()withtime_idx.This API is the time-reference analogue of
schedule(). Instead of providing explicit event times, you provide integer indices into a tensor bound viabind_time_source(). Weights are still supplied in value mode.Exactly one of
con_indicesorpre_indicesmust be provided, andbind_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 expandingpre_indicesif 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_stepare 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=Trueinset_diff_config(), gradients flow into the bound time tensor and can move events in time.Order of operations:
Bind a time source tensor:
nc.bind_time_source(time_source)Schedule events by time index:
nc.schedule_time_ref( con_indices=..., time_idx=..., weight=..., )
Run simulation (
nc.advance()in a loop).
If
bind_time_source()has not been called, this method raises aRuntimeError.The value-mode time slot in
sched_time_msis populated with zeros; the actual times are obtained at runtime from the bound tensor viasched_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()(viaNetCon.advancein 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
tapsandsigma). 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 viaupdate_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 bysigma.
sigma (float, optional) – Standard deviation (in steps) for the 3-tap Gaussian interpolation when
taps=3. Ignored fortaps=2.tau (float, optional) – Temperature parameter for surrogate spiking, passed through to
update_active_diff()astau. 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_configdoes not itself changetrainingmode; it only records configuration flags.NetCon.advancewill dispatch toadvance_diff()whenself.training = Trueand toadvance_non_diff()otherwise.track_events=Trueis 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.
eventsrecords the most recently delivered counts, while the denseevent_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
weightparameter 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 accessingwdirectly.
- 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.
ContinuousConis the analog counterpart ofNetCon: it gathers a presynaptic variable, applies optional weighting and integer delay, scatters the resulting values into the target synapse’s local shape, and callssyn.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.- 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
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
Nindependent NetStim generators. Any leading dimensions are treated as batch dimensions. For example, an unbatched instance withN == ihas state/parameter shape(i,); afterbatch(n)the shape is(n, i). Callingbatchagain prepends another leading batch dimension rather than flattening generators.Each generator produces a renewal process with mean interval
interval. Anoiseparameter blends deterministic intervals with exponential variability:\[T_{k+1} = T_k + (1 - \eta)\,\Delta + \eta\,\Delta\,E,\]where
Delta = interval,eta = noisein[0,1], andEis unit-rate exponential. Wheneta=0firing is periodic; wheneta=1firing is Poisson with rate1/interval. The initial clock isstart + noise * interval * E, orstartwhennoise=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 inN. 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 anotherbatch(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:
- 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:
- 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
- initialize()[source]#
Reset generator state while preserving scheduled spikes.
Notes
next_stoch_timeis set tostartplus an exponential offset whennoise>0so the first interval is drawn from the same renewal distribution used during stepping.Scheduled spikes already enqueued via
schedule()are retained.
- 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=Trueselects tensor scheduling;Falseselects 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 usediff_spiking=Trueto propagate gradients into the scheduled times or weights.time_idxreads live times frombind_time_sourceinstead oftimes/times_ms.weight_idxreads live amplitudes frombind_weight_sourceinstead ofweight. Either or both fields may be indexed. Referenced fields have no additive value offset: the default unitweight(orNone) is omitted whenweight_idxis supplied. Indices must be nonnegative. Indexed events use tensor storage;differentiable=Falseselects 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 usespike_gatefor differentiable amplitudes; downstream NetCons must usediff_spiking=Trueto 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.
shapeis 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
Low-level pure projection interfaces are documented in Functional plans and tensor packets.