Writing your own synapse#
A synapse combines a current with a rule for receiving presynaptic input.
For discrete weighted deliveries, inherit Synapse and implement the pure
net_receive_values hook. For a signal sampled every timestep, inherit
ContinuousSynapse and declare its named analog inputs. A prescribed
conductance waveform, such as the built-in alphasynapse, needs neither
connection interface.
This tutorial implements both kinds of connected synapse from scratch. The
examples use CPU float64 and disable compilation so the first run is quick.
They run with the installed Dendra package and require no companion models or
NEURON simulation. Download the complete scripts:
custom_event_synapse.py and
custom_continuous_synapse.py.
Run them with python custom_event_synapse.py and
python custom_continuous_synapse.py. The documentation executes these same
files and checks their numerical results.
Choose a value’s lifetime first#
The declarations determine how Dendra initializes, advances, checkpoints, and functionally represents each value. Use the same roles in a synapse as in any other mechanism:
Value |
Declaration and producer |
|---|---|
Solver-evolved conductance or gate |
|
Persistent counter, latch, or history |
|
Repeatable current-stage algebra |
|
Workspace derived from parameters, temperature, or geometry |
|
Prepared workspace that also depends on the timestep |
|
A continuously delivered projection |
|
A read-only input to a nested State equation |
|
The returned-value hooks shown here return mappings containing Tensor outputs;
current methods return a Tensor. Treat arguments and module state as read-only.
Read evolving values from the explicit values frame in returned-value hooks;
parameters are available through self. Runtime replacements preserve the
declared shape, dtype, and device. Avoid in-place additions such as
values["g"].add_(weights).
State.state_defaults(v, values) supplies fallback solver-state initial
conditions. An insertion-time ic overrides those defaults. Later
initial_values(v, values) overlays may intentionally replace initial State
or carry values; they do not advance time. Declared carry starts at zero when
freshly initialized unless an initial-value overlay changes it. Prepared
workspaces are reproducible coefficients rather than simulation history:
reinitialize an imperative model after changing preparation inputs, or call
functional prepare again with the new parameters/constants.
The two scopes of advance have different jobs:
A State’s default
advance(v, dt, values)executes its declared equations. Override it only for a custom transition; then return every declared solver tensor and any updated carry belonging to that State.Mechanism.advance(v, dt, values)returns a partial mapping of its direct carry and owned writable/additive shared fields once per accepted timestep. Omitted carry is retained. It does not replace the State solver. State and Mechanism transitions read the same incoming snapshot, so the Mechanism hook cannot assume it sees a newly solved State value.
assigned_values and current methods may be evaluated several times during
one step. Keep timers and counters out of them. See the
mechanism authoring guide
and API reference for the complete hook
contracts and worked preparation/initialization examples.
An event-driven exponential point synapse#
Our first synapse stores conductance g, adds each weighted delivery to it,
and decays it between deliveries:
Synapse supplies the receive interface. Combining it with PointProcess
selects a lumped current: g and weights are numerical conductances in µS,
v and e are in mV, tau is in ms, and the outward-positive current is
in nA. Thus weight=0.05 means 0.05 µS; do not multiply that weight by
dendra.units.uS. Dendra handles the target compartment’s area conversion.
Declare the state and current#
import torch
import dendra as dn
from dendra.models.mechanisms import PointProcess, State, Synapse
from dendra.models.mod import pas
class ExponentialConductance(State):
State.STATE("g")
State.RANGE(tau=2.0) # ms; choose a strictly positive time constant.
State.DERIVATIVE("g' = -g / tau")
def state_defaults(self, v, values):
return {"g": torch.zeros_like(v)} # Preserve local shape/device/dtype.
class CustomExpSyn(PointProcess, Synapse):
"""Lumped conductance synapse: weights and g in µS, e in mV, i in nA."""
PointProcess.STATE_BUNDLE(ExponentialConductance)
PointProcess.RANGE(e=0.0)
PointProcess.NONSPECIFIC_CURRENT("i")
def i(self, v):
return self.g * (v - self.e) # Outward-positive current.
def net_receive_values(self, weights, dt, values):
# The adapter handles imperative writes; this hook returns replacements.
# ODE decay runs during the population step, not once per receive call.
return {"states": {"g": values["g"] + weights}}
state_defaults creates one zero conductance per local slot. Using
zeros_like(v) preserves its shape, dtype, and device. STATE_BUNDLE
registers the State class; its g tensor becomes available to the owning
synapse’s current as self.g. tau belongs to the State and can still be
configured when inserting the synapse.
The receive hook returns a partial, namespaced update. Here states replaces
the flattened State variable g; more elaborate receivers can also return
direct carry or nested state_carry replacements. Omitted values are
retained. Reception itself does not advance the clock or perform ODE decay.
Leave the standard net_receive adapter in place: it commits these same
returned updates during ordinary Network execution.
Insert it and deliver a Network event#
def make_cells(*, gradients=False):
with dn.ctx(DEVICE="cpu", DTYPE=torch.float64, JIT=0, REQUIRE_GRAD=int(gradients)):
cells = dn.SingleCompartment(
N=1,
C=1,
v_init=-65.0,
dtype=torch.float64,
integrator=dn.bwd_euler_sc(imem=False),
)
cells.insert(pas, g=0.001, e=-65.0) # Distributed leak: g in S/cm².
cells.insert(CustomExpSyn.rename("syn"), tau=2.0, e=0.0)
cells.train(gradients)
cells.initialize()
return cells
The distributed passive leak in this helper uses S/cm², while the synapse
uses µS. Each mechanism keeps its own unit contract. The helper initializes
the population for standalone use; Network.initialize subsequently
establishes the complete network starting state.
def network_demo():
dt = 0.1
cells = make_cells()
with dn.ctx(DEVICE="cpu", DTYPE=torch.float64, JIT=0, REQUIRE_GRAD=0):
source = dn.NetStim(N=1, start=0.0, interval=100.0, noise=0.0, max_spikes=1)
net = dn.Network({"cells": cells}, netstim=source)
net.connect_one_to_one(
net.netstim[:],
net.cells[:],
net.cells.mech.syn,
threshold=None, # NetStim supplies an event flag, not a voltage.
weight=0.05, # 0.05 µS; do not multiply by dendra.units.uS.
delay=dt,
)
net.eval()
net.initialize(dt)
net.step() # Detect the t=0 event and schedule its future delivery.
torch.testing.assert_close(net.cells.mech.syn.g, torch.zeros_like(cells.v))
net.step() # Deliver 0.05 µS, then advance the ODE and membrane voltage.
expected = torch.full_like(cells.v, 0.05) * torch.exp(cells.v.new_tensor(-dt / 2.0))
torch.testing.assert_close(net.cells.mech.syn.g, expected)
net.step() # A zero-payload receive does not add conductance; decay continues.
torch.testing.assert_close(
net.cells.mech.syn.g, expected * torch.exp(cells.v.new_tensor(-dt / 2.0))
)
return net
network_demo() supplies one deterministic NetStim event. The first step
detects and queues it; the configured 0.1 ms delay delivers it on the next
step. Delivery occurs before the population solve, so the conductance
observed after that step is already decayed. The assertions check both the
delivery and the following event-free decay. This linear State equation uses
Dendra’s generated exponential update, even though the membrane integrator
is backward Euler.
Use the same receiver with explicit functional state#
def functional_demo():
cells = make_cells(gradients=True)
original_voltage = cells.v.detach().clone()
functional, tensors = dn.func.make_functional(cells, dt=0.1)
prepared = functional.prepare(tensors.parameters, tensors.constants)
initial_g = tensors.state["mechanisms"]["syn"]["g"]
payload = torch.full_like(initial_g, 0.05, requires_grad=True)
received = functional.receive(
tensors.parameters, prepared, tensors.state, target="syn", payload=payload
)
torch.testing.assert_close(received["mechanisms"]["syn"]["g"], initial_g + payload)
torch.testing.assert_close(received["clock"]["t"], tensors.state["clock"]["t"])
state, _ = functional.step(tensors.parameters, prepared, received)
decay = torch.exp(-tensors.constants["dt"] / 2.0)
conductance = state["mechanisms"]["syn"]["g"]
torch.testing.assert_close(conductance, (initial_g + payload) * decay)
(gradient,) = torch.autograd.grad(conductance.sum(), payload)
torch.testing.assert_close(gradient, torch.ones_like(payload) * decay)
# Functional delivery and stepping leave the original population unchanged.
torch.testing.assert_close(cells.mech.syn.g, torch.zeros_like(initial_g))
torch.testing.assert_close(cells.v, original_voltage)
return state, gradient
functional_demo() checks the conductance jump, unchanged clock during
reception, subsequent decay, payload gradient, and unchanged source
Population. The payload is already weighted and follows the synapse’s local
slot order. full_like gives it the correct dtype, device, and runtime shape,
including any explicit batch axes. A smaller Tensor may be broadcast to that
shape; a returned replacement must have the exact declared shape.
The gradient of the next conductance with respect to its payload is
\(\exp(-0.1/2) \approx 0.95122942\). Functional reception handles this local
transition. A shared dense fixed-delay NetCon core supplies explicit queued
payloads as described in Run models with explicit state.
Shared threshold detection and ordered source observation are described in
Run models with explicit state. Shared NetStim generation
with explicit draws and clock/RNG state is described in
Run models with explicit state. Shared tensor schedules and
indexed bindings are described in Run models with explicit state.
Consuming heap calendars are described in Run models with explicit state.
Construct connected Networks with the ordinary Network API, then execute them
natively or with dn.compile(network). See
Run models with explicit state for compiled execution and
Run models with explicit state for the full functional receive contract.
The complete event example runs here:
Custom synapse: Network delivery and conductance decay checks passed.
Functional payload gradient: 0.95122942
Keep timestep recovery separate from delivery#
A receiver may be called several times in one timestep by different NetCons, including calls with zero payloads. A call is a connection delivery, not necessarily a single biological event. Adding zero leaves this synapse unchanged, while a plasticity rule must explicitly define how it responds. Preserve call order for receivers with counters, gates, or other effects.
Put continuous conductance decay in a State equation, as above, and use
Mechanism.advance for once-per-accepted-step carry updates. Applying a full
timestep of decay inside each receive call would multiply the decay when
several connections target the same synapse. For independent contacts at the
same compartment, use separate local slots as described in
Synapse banks and slots.
A continuous conductance synapse#
For graded transmission, a Network samples a presynaptic variable on every
step instead of detecting a discrete event. A dimensionless presynaptic gate
s can drive a weighted conductance input g_pre:
The second script declares the source gate, the target’s continuous input and
current, and their connection. It uses the ordinary distributed
ContinuousSynapse contract: weights and g_pre are in S/cm², and the
outward-positive current is in mA/cm². To model a lumped continuous point
synapse instead, combine PointProcess with ContinuousSynapse and document
weights in µS and current in nA.
Declare a source gate and a receiving current#
import torch
import dendra as dn
from dendra.models.callbacks import RecorderLambda
from dendra.models.mechanisms import ContinuousSynapse, Mechanism, State
from dendra.models.mod import pas
class ReleaseGate(State):
"""A dimensionless presynaptic gate relaxing toward a voltage-dependent level."""
State.STATE("release")
State.ASSIGNED("release_inf")
State.RANGE(tau=2.0, midpoint=-45.0, slope=5.0, initial_release=0.25)
State.DERIVATIVE("release' = (release_inf - release) / tau")
def state_defaults(self, v, values):
return {"release": torch.zeros_like(v) + self.initial_release}
def assigned_values(self, v, values):
return {"release_inf": torch.sigmoid((v - self.midpoint) / self.slope)}
class AnalogSource(Mechanism):
Mechanism.STATE_BUNDLE(ReleaseGate)
class GradedSynapse(ContinuousSynapse):
# g_pre is conductance density in S/cm²; its previous value is g_pre_old.
ContinuousSynapse.INPUT("g_pre")
ContinuousSynapse.RANGE(e=-10.0)
ContinuousSynapse.NONSPECIFIC_CURRENT("i")
ContinuousSynapse.AFFINE("i")
def i(self, v):
# S/cm² * mV = mA/cm², with outward-positive current.
return self.g_pre * (v - self.e)
The source’s release is solver-evolved State. Its instantaneous target
release_inf is ephemeral ASSIGNED algebra; assigned_values can safely
be reevaluated at each required voltage. state_defaults supplies an initial
release of 0.25. The source contributes no membrane current itself.
AFFINE("i") explicitly asserts that the current is affine in the local
voltage while the delivered conductance is held fixed during current assembly.
Dendra can also infer this property from a simple expression such as this one.
The target declares ContinuousSynapse.INPUT("g_pre"). Before each round of
continuous delivery, the Network saves the previous input as g_pre_old and
resets g_pre to zero. Connections then accumulate their weighted values with
reduce="sum", before the target population advances. Inputs describe the
current timestep’s projection; they do not accumulate indefinitely across
timesteps. Declare keep_old=False if the previous-input buffer is unnecessary.
ContinuousSynapse.INPUT and State.INPUT serve different scopes. The former
declares persistent, checkpointed delivery buffers managed by the Network.
The latter exposes a read-only, ephemeral value to a nested State equation;
Population.bind_input supplies it from a declared field within the same
Population. Declaring State.INPUT alone creates no intercellular connection.
See Run models with explicit state for the binding contract.
Connect and verify the analog projection#
def make_network():
"""Connect two presynaptic cells to two postsynaptic cells one-to-one."""
pre = dn.SingleCompartment(N=2, C=1, v_init=-35.0, dtype=torch.float64)
pre.insert(pas, g=0.001, e=-35.0) # Holds the release target level constant.
pre.insert(AnalogSource.rename("source"))
post = dn.SingleCompartment(N=2, C=1, v_init=-65.0, dtype=torch.float64)
post.insert(pas, g=0.001, e=-65.0)
post.insert(GradedSynapse.rename("graded"))
network = dn.Network({"pre": pre, "post": post})
g_max = torch.tensor([0.002, 0.004], dtype=torch.float64) # S/cm² per edge.
network.connect_continuous_one_to_one(
pre[:],
post[:],
post.mech.graded,
pre_var="mech.source.release", # Live declared State, selected each step.
input="g_pre",
weight=g_max,
delay=0.0,
reduce="sum",
)
return network, g_max
pre_var="mech.source.release" selects the live presynaptic State by its
inserted mechanism alias and flattened State name. Each source cell connects
to its corresponding target, with weights of 0.002 and 0.004 S/cm². The
dimensionless gate multiplied by this weight produces the conductance density
expected by g_pre. The source voltage is held at its passive reversal, so
the gate trajectory has a simple analytic reference.
def run_demo():
"""Run four timesteps and check delivered conductances and density currents."""
dt, steps = 0.1, 4 # Time is in ms.
with dn.ctx(JIT=0, REQUIRE_GRAD=0, DEVICE="cpu", DTYPE=torch.float64, IMEM=False):
network, g_max = make_network()
network.eval()
network.initialize(dt)
recorder = RecorderLambda(
{
"t": lambda net: net.t.clone(),
"release": lambda net: net.pre.mech.source.release.clone(),
"g_pre": lambda net: net.post.mech.graded.g_pre.clone(),
"g_pre_old": lambda net: net.post.mech.graded.g_pre_old.clone(),
"v_post": lambda net: net.post.v.clone(),
"i_density": lambda net: net.post.mech.graded.i(net.post.v).clone(),
}
)
network.run(tstop=steps * dt, callbacks=[recorder])
traces = {name: recorder.stack(name) for name in recorder.funcs}
# Recorder includes t=0. Zero-delay delivery samples release BEFORE
# either population advances, so sample k drives the next recorded frame.
expected_input = traces["release"][:-1] * g_max.reshape(1, 2, 1)
torch.testing.assert_close(traces["g_pre"][1:], expected_input)
torch.testing.assert_close(traces["g_pre_old"][1:], traces["g_pre"][:-1])
torch.testing.assert_close(
traces["i_density"],
traces["g_pre"] * (traces["v_post"] - network.post.mech.graded.e),
)
assert torch.all(traces["i_density"][1:] < 0) # Inward at v < e.
# Constant presynaptic voltage makes the gate's analytic trajectory known.
steady = torch.sigmoid(traces["t"].new_tensor(2.0))
expected_release = steady + (0.25 - steady) * torch.exp(-traces["t"] / 2.0)
torch.testing.assert_close(
traces["release"],
expected_release[:, None, None].expand_as(traces["release"]),
)
assert traces["g_pre"].shape[0] == steps + 1
return traces
Call run_demo() to initialize the Network and run four timesteps. The
recorder includes the initial frame. Zero-delay connections read the source
at the start of a timestep, before either population advances, so the input
in recorded frame k+1 equals the weight times release in frame k.
The assertions check this ordering, input history, the analytic gate dynamics,
and the current’s inward sign below reversal.
The complete continuous example runs here:
Final conductance density [S/cm²]: [0.0006757300029133994, 0.0013514600058267988]
Final outward current density [mA/cm²]: [-0.03095508423963432, -0.0521659534052462]
Verified zero-delay analog sampling, input history, and release dynamics.
The ordinary Network owns continuous input resets, sampling, reductions, and
delays. These operations share pure tensor cores with the explicit functional
projection and receiver APIs. See
Run models with explicit state for a complete connected
example, differentiable weights and source values, and checkpoint continuation.
Custom reception uses continuous_receive_values; leave the standard reset
and receive adapters in place. See Run models with explicit state
for automatic canonical single-device Network composition with the same
component plans and native ordering.
What to check when adapting these examples#
Initialize a new mechanism eagerly before compiling it. Check that one known delivery changes the intended local state or input, that current has the expected sign and units, and that decay or recovery runs once per timestep. For differentiable models, also check a gradient against a known expression or a finite difference. Reuse the exact declared shapes, devices, and dtypes in returned-value hooks.
Functional lowering trusts authored hooks to keep the pure, deterministic
contract by default. While developing a synapse, create its functional plan or
compiled Network inside with dn.ctx(CHECK_PURITY=True): to enable diagnostic
dependency and evaluation checks. Each plan captures the mode when it is
created; required state schemas, tensor layouts, and canonical receive adapters
remain checked in either mode. Diagnostics help find violations but do not
prove purity for every payload or state.
For migration from the earlier mutation-based hook API, see Upgrading Dendra. Initialization precedence and workspace timing are detailed in Model initialization and the mechanism API reference.