Connected networks#

A Network advances populations, artificial event sources and their connections together. Use this guide to choose connection targets, share spike signals, and control the memory used by delayed events. The examples compare the same small NetStim-driven projection under several execution settings.

For a complete connected-network simulation with recording, start with functional execution. The ordinary connection APIs configure both native execution and dn.compile(Network).

Simulation timing#

Each timestep updates artificial sources, delivers connection inputs from the populations’ current state, then advances the populations. A newly computed population voltage therefore affects later connection processing, rather than a population that happens to be visited later in the same step.

The following setup defines the small projection and optional measurement helpers used below.

import gc
import time
from contextlib import nullcontext

import dendra as dn
from dendra.models.mod import exp2syn

import torch
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DTYPE = "float32"


def synchronize():
    if torch.cuda.is_available():
        torch.cuda.synchronize()


def cleanup_cuda():
    synchronize()
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()


def compact_int(n) -> str:
    if n is None:
        return "—"
    n = int(n)
    a = abs(n)
    if a >= 1_000_000_000:
        return f"{n / 1_000_000_000:.2g}B"
    if a >= 1_000_000:
        return f"{n / 1_000_000:.2g}M"
    if a >= 10_000:
        return f"{n / 1_000:.2g}k"
    return f"{n:,}"


def format_bytes(n: int | None) -> str:
    if n is None:
        return "—"
    n = float(n)
    units = ("B", "KiB", "MiB", "GiB", "TiB")
    for unit in units:
        if abs(n) < 1024.0 or unit == units[-1]:
            if unit == "B":
                return f"{int(n)} B"
            if abs(n) < 10.0:
                return f"{n:.2g} {unit}"
            if abs(n) < 100.0:
                return f"{n:.1f} {unit}"
            return f"{n:.0f} {unit}"
        n /= 1024.0


def tensor_bytes(x) -> int:
    if torch.is_tensor(x):
        return int(x.numel() * x.element_size())
    return 0


def compact_shape(shape) -> str:
    if shape is None:
        return "—"
    if torch.is_tensor(shape):
        shape = tuple(shape.shape)
    if not isinstance(shape, tuple):
        try:
            shape = tuple(shape)
        except TypeError:
            return "—"
    if len(shape) == 0:
        return "scalar"
    return "×".join(compact_int(d) for d in shape)


def shape_and_bytes(x) -> str:
    if not torch.is_tensor(x) or x.numel() == 0:
        return "—"
    return f"{compact_shape(tuple(x.shape))} · {format_bytes(tensor_bytes(x))}"


def short_backend(backend) -> str:
    return {
        "dense": "dense",
        "sparse_calendar": "sparse",
        "bitpacked_history": "bitpack",
    }.get(str(backend), str(backend))


def short_text(text, width: int = 28) -> str:
    if text is None or text == "":
        return "—"
    text = str(text)
    return text if len(text) <= width else text[: max(0, width - 1)] + "…"


def short_conn_name(name, width: int = 30) -> str:
    text = str(name)
    text = text.replace("->", "→").replace("~>", "↝")
    text = text.replace(":spike", "")
    text = text.replace("mech_", "")
    return short_text(text, width)


def format_seconds(x) -> str:
    if x is None:
        return "—"
    return f"{float(x):.3g}s"


def maybe_dataframe(rows, columns=None):
    """Return a compact docs-friendly DataFrame when pandas is available."""
    try:
        import pandas as pd

        df = pd.DataFrame(rows)
        if columns is not None and len(df.columns) > 0:
            df = df[[c for c in columns if c in df.columns]]
        return df
    except Exception:
        for row in rows:
            print(row)
        return rows

Device and dtype placement#

Construct large models on their intended device and dtype to avoid temporary copies of populations and connection state:

with dn.ctx(DEVICE="cuda", DTYPE="float32"):
    ...  # Construct the populations, sources and Network here.

A native Network may contain populations on different devices. Inspect every population with net.devices() and net.dtypes(); connections deliver on their target synapse’s device. Cross-device signals require copies, so keep tightly coupled populations together when possible. See batching and devices. Functional Network lowering requires a single device.

Attach artificial sources#

Supply netstim=source to dn.Network(...), or call network.attach_netstim(source) after creating the cellular network. The latter is useful when several stimulation protocols share the same cellular model.

Attaching or replacing a source, or adding a connection, invalidates the built connectivity. Call network.initialize(dt) before executing the changed network. The projection factory below uses this attachment pattern.

Independent synapses on one compartment#

Use copies=... when one physical compartment needs independent synaptic contacts:

post.dend.insert(exp2syn, alias="exc", copies=30, tau1=0.2, tau2=2.0)
slots = post.dend.slots(post.mech.exc)

Pass a slot selection to connect(...) or connect_one_to_one_slots(...) to identify the contacts. Multiple slots can contribute current to one compartment while keeping independent state. See synapse banks for a complete example and slot selection.

For built-in expsyn and exp2syn, event weights are bare numbers in µS: weight=0.05 means 0.05 µS. Do not multiply these weights by dendra.units.uS. Other receiving mechanisms define their own weight units.

Share an explicit spike signal#

A mechanism such as spikedetect can expose one event signal to several outgoing projections. For an already configured source and target selection:

from dendra.models.mod import spikedetect

pre.soma.insert(spikedetect, alias="detector", threshold=-30.0)
network.connect_one_to_one_slots(
    pre.soma, target_slots,
    pre_var="mech.detector.spikes", threshold=None,
    weight=0.05, delay=1.0,
)

threshold=None consumes the selected variable as an event/gate signal instead of applying another voltage threshold. This is useful when the presynaptic mechanism already defines spikes, or many projections should share the same event decision.

Independent network replicas#

Call network.batch(n) after defining an unbatched network to create independent replicas for parameter sweeps or stimulus conditions. Select synapse slots normally; batching handles their indices. See batching and devices for a runnable example.

def build_netstim_projection(
    *,
    backend: str = "dense",
    N: int = 256,
    fanout: int = 8,
    dt: float = 0.025,
    max_delay_ms: float = 25.0,
    seed: int = 1,
    device: str = DEVICE,
    dtype: str = DTYPE,
):
    # Build a small but scalable NetStim -> Population projection.
    #
    # NetStim sources are useful for backend comparisons because the presynaptic
    # event stream is already binary and source-side, making it eligible for the
    # bitpacked_history backend.
    dev = torch.device(device)
    torch_dtype = torch.float32 if str(dtype) in ("float32", "torch.float32") else torch.float64

    with dn.ctx(DEVICE=device, DTYPE=dtype):
        ns = dn.NetStim(N, interval=10.0, noise=1.0, seed=seed)
        cells = dn.Population(C=N, v_init=-65.0)
        cells.insert(exp2syn, tau1=0.2, tau2=2.0)

        net = dn.Network(
            {"cells": cells},
            netcon_delay_backend=backend,
            track_netcon_events=False,
        )
        net.attach_netstim(ns)

        gen = torch.Generator(device=dev).manual_seed(seed)
        pre_idx = torch.arange(N, device=dev, dtype=torch.long).repeat_interleave(fanout)
        post_idx = torch.randint(N, (pre_idx.numel(),), device=dev, generator=gen)

        max_delay_steps = max(1, int(round(max_delay_ms / dt)))
        delay_steps = torch.randint(
            1,
            max_delay_steps + 1,
            (pre_idx.numel(),),
            device=dev,
            generator=gen,
        )
        delays_ms = delay_steps.to(torch_dtype) * float(dt)

        net.connect_one_to_one(
            net.netstim[pre_idx],
            net.cells[:, post_idx],
            net.cells.mech.exp2syn,
            threshold=None,
            weight=0.05,  # µS for exp2syn
            delay=delays_ms,
            allow_multapses=True
        )

    return net

Optional memory measurements#

The helper below summarizes the delay-related tensors in the example networks. Its short column names describe connections (n), receiving synapse elements (S), delay depth (D) and memory (mem). The printed implementation attributes are diagnostics for this notebook; simulation code does not need to read or modify them.

def _netcon_summary_row(name, nc):
    delivery = getattr(nc, "delivery_buffer", None)
    event_queue = getattr(nc, "event_queue", None)
    spike_hist = getattr(nc, "spike_history_packed", None)
    backend = getattr(nc, "delay_backend", "unknown")
    bit_mode = getattr(nc, "_bitpack_mode", None)
    bit_can_use = getattr(nc, "_bitpack_can_use", None)
    bit_reason = getattr(nc, "_bitpack_ineligible_reason", None)

    if backend == "bitpacked_history":
        if bit_can_use:
            bit = f"{bit_mode or 'yes'} ✓"
        else:
            bit = "no: " + short_text(bit_reason, 20)
    else:
        bit = "—"

    state_bytes = tensor_bytes(delivery) + tensor_bytes(event_queue) + tensor_bytes(spike_hist)
    n_conn = int(nc.numel()) if hasattr(nc, "numel") else None
    syn_numel = int(getattr(nc, "_syn_numel", 0))
    max_delay_steps = int(getattr(nc, "max_delay_steps", 0))

    return {
        # Compact columns for docs output.
        "conn": short_conn_name(name),
        "bkd": short_backend(backend),
        "run": "train" if bool(getattr(nc, "training", False)) else "eval",
        "n/S/D": f"{compact_int(n_conn)}/{compact_int(syn_numel)}/{compact_int(max_delay_steps)}",
        "buf": shape_and_bytes(delivery),
        "evt": shape_and_bytes(event_queue),
        "hist": shape_and_bytes(spike_hist),
        "bit": bit,
        "mem": format_bytes(state_bytes),
        # Full diagnostic fields for interactive exploration.
        "name": name,
        "backend": backend,
        "training": bool(getattr(nc, "training", False)),
        "n_connections": n_conn,
        "syn_numel": syn_numel,
        "max_delay_steps": max_delay_steps,
        "delivery_shape": tuple(delivery.shape) if torch.is_tensor(delivery) else None,
        "delivery_bytes": format_bytes(tensor_bytes(delivery)),
        "event_queue_shape": tuple(event_queue.shape) if torch.is_tensor(event_queue) else None,
        "event_queue_bytes": format_bytes(tensor_bytes(event_queue)),
        "spike_history_shape": tuple(spike_hist.shape) if torch.is_tensor(spike_hist) else None,
        "spike_history_bytes": format_bytes(tensor_bytes(spike_hist)),
        "bitpack_mode": bit_mode,
        "bitpack_can_use": bit_can_use,
        "bitpack_reason": bit_reason,
    }


def summarize_netcons(net, *, compact: bool = True):
    rows = [_netcon_summary_row(name, nc) for name, nc in net.synapses.items()]
    if compact:
        return maybe_dataframe(
            rows,
            columns=("conn", "bkd", "run", "n/S/D", "buf", "evt", "hist", "bit", "mem"),
        )
    return maybe_dataframe(
        rows,
        columns=(
            "name",
            "backend",
            "training",
            "n_connections",
            "syn_numel",
            "max_delay_steps",
            "delivery_shape",
            "delivery_bytes",
            "event_queue_shape",
            "event_queue_bytes",
            "spike_history_shape",
            "spike_history_bytes",
            "bitpack_mode",
            "bitpack_can_use",
            "bitpack_reason",
        ),
    )


net = build_netstim_projection(backend="dense", N=128, fanout=4)
net.initialize(dt=0.025)
summarize_netcons(net)
conn bkd run n/S/D buf evt hist bit mem
0 netstim→cells:exp2syn dense eval 512/128/1,001 1,001×128 · 500 KiB — — — 500 KiB

Choose a delayed-event representation#

For inference, configure netcon_delay_backend when constructing the Network:

Backend

Useful starting point

Tradeoff

"dense"

General event connections; frequent events

Regular delivery operations, with memory increasing with delay horizon and target size.

"sparse_calendar"

Sparse pending deliveries or long delays

Stores pending nonzero deliveries; speed depends on event traffic and device.

"bitpacked_history"

Large networks with binary source events

Compact shared source history; requires the same event decision for a source across its outgoing edges.

Training uses the separate netcon_train_backend setting. Its default, "auto", selects "source_history" when source-level event semantics are exact, and otherwise uses "dense". Both training representations support weight and delay gradients. Source-history training uses hard packed events when spike gradients are disabled, or floating source gates when surrogate spike gradients are enabled.

Choose a representation by measuring the intended workload; a smaller state does not guarantee a faster rollout. Reinitialize after changing training/evaluation mode or differentiation settings.

Compare memory on one projection#

The following cell builds the same small projection under each inference setting. Increase population size or fanout only after checking the memory required on your device.

def inspect_backend_layouts(backends=("dense", "sparse_calendar", "bitpacked_history")):
    rows = []
    for backend in backends:
        cleanup_cuda()
        try:
            net = build_netstim_projection(backend=backend, N=256, fanout=8)
            net.initialize(dt=0.025)
            for name, nc in net.synapses.items():
                delivery = getattr(nc, "delivery_buffer", None)
                spike_hist = getattr(nc, "spike_history_packed", None)
                event_queue = getattr(nc, "event_queue", None)
                total = tensor_bytes(delivery) + tensor_bytes(spike_hist) + tensor_bytes(event_queue)
                rows.append(
                    {
                        "bkd": short_backend(backend),
                        "conn": short_conn_name(name),
                        "n/S/D": f"{compact_int(int(nc.numel()))}/{compact_int(int(getattr(nc, '_syn_numel', 0)))}/{compact_int(int(nc.max_delay_steps))}",
                        "buf": shape_and_bytes(delivery),
                        "hist": shape_and_bytes(spike_hist),
                        "mem": format_bytes(total),
                    }
                )
        except Exception as exc:
            rows.append({"bkd": short_backend(backend), "error": short_text(repr(exc), 72)})
        finally:
            try:
                del net
            except UnboundLocalError:
                pass
            cleanup_cuda()

    return maybe_dataframe(rows, columns=("bkd", "conn", "n/S/D", "buf", "hist", "mem", "error"))


inspect_backend_layouts()
bkd conn n/S/D buf hist mem
0 dense netstim→cells:exp2syn 2,048/256/1,001 1,001×256 · 1001 KiB — 1001 KiB
1 sparse netstim→cells:exp2syn 2,048/256/1,001 1×256 · 1 KiB — 1 KiB
2 bitpack netstim→cells:exp2syn 2,048/256/1,001 1×256 · 1 KiB 1,001×5 · 39.1 KiB 40.1 KiB

Compare rollout times#

Use the same connectivity, timestep and duration when comparing backends. Separate startup costs from repeated rollout time, and synchronize an accelerator before reading elapsed time. The helper below provides one such comparison; results depend on your network and hardware.

def benchmark_backend(
    backend: str,
    *,
    N: int = 1024,
    fanout: int = 16,
    tstop: float = 10.0,
    dt: float = 0.025,
    use_jit: bool = False,
):
    cleanup_cuda()
    if torch.cuda.is_available():
        torch.cuda.reset_peak_memory_stats()

    t0 = time.perf_counter()
    net = build_netstim_projection(backend=backend, N=N, fanout=fanout, dt=dt)
    synchronize()
    build_s = time.perf_counter() - t0

    ctx = dn.ctx(JIT=1) if use_jit else nullcontext()

    t0 = time.perf_counter()
    with ctx:
        net.initialize(dt=dt)
        synchronize()
    init_s = time.perf_counter() - t0

    t0 = time.perf_counter()
    with ctx:
        net.run(tstop=tstop)
        synchronize()
    run_s = time.perf_counter() - t0

    peak = torch.cuda.max_memory_allocated() if torch.cuda.is_available() else None

    return {
        "bkd": short_backend(backend),
        "N": compact_int(N),
        "F": compact_int(fanout),
        "steps": compact_int(int(tstop / dt)),
        "build": format_seconds(build_s),
        "init": format_seconds(init_s),
        "run": format_seconds(run_s),
        "peak": format_bytes(peak) if peak is not None else "—",
        "net": net,
    }


results = []
for backend in ("dense", "sparse_calendar", "bitpacked_history"):
    try:
        out = benchmark_backend(backend, N=512, fanout=8, tstop=2.0)
        net = out.pop("net")
        results.append(out)
        del net
    except Exception as exc:
        results.append({"bkd": short_backend(backend), "error": short_text(repr(exc), 72)})
    cleanup_cuda()

maybe_dataframe(results, columns=("bkd", "N", "F", "steps", "build", "init", "run", "peak", "error"))
bkd N F steps build init run peak
0 dense 512 8 80 0.0139s 0.00916s 0.0343s —
1 sparse 512 8 80 0.0138s 0.00822s 0.0449s —
2 bitpack 512 8 80 0.0133s 0.0081s 0.0359s —

Dense delivery#

Dense delivery is the general choice when no source-level compact representation is eligible. Delay state grows with both the receiving synapse size and delay horizon. The following cell prints this example’s allocation.

Differentiable event delays can use two-tap linear or three-tap Gaussian-like interpolation, configured through set_synaptic_diff_config(...). These options apply to event NetCons, including eligible source-history training.

dense_net = build_netstim_projection(backend="dense", N=128, fanout=4)
dense_net.initialize(dt=0.025)

nc = next(iter(dense_net.synapses.values()))
print("advance function:", nc.advance.__name__)
print("delivery_buffer:", tuple(nc.delivery_buffer.shape), format_bytes(tensor_bytes(nc.delivery_buffer)))
print("track_events:", getattr(nc, "track_events", None))
print("event_queue present:", hasattr(nc, "event_queue"))
advance function: advance_non_diff_dense_mixed
delivery_buffer: (1001, 128) 500 KiB
track_events: False
event_queue present: False

Sparse pending deliveries#

The sparse calendar stores pending nonzero event payloads and preserves their delivery order. Native storage can grow as needed. Functional execution uses a fixed capacity and reports overflow instead of returning an incomplete simulation; increase pending_capacity when compiling or lowering a network that needs more pending events.

The implementation uses tensor calendar operations. Benchmark it on the intended device and event traffic rather than assuming that sparse storage is always faster.

sparse_net = build_netstim_projection(backend="sparse_calendar", N=128, fanout=4)
sparse_net.initialize(dt=0.025)

nc = next(iter(sparse_net.synapses.values()))
print("advance function:", nc.advance.__name__)
print("delivery_buffer:", tuple(nc.delivery_buffer.shape), format_bytes(tensor_bytes(nc.delivery_buffer)))
print("pending calendar buckets:", len(getattr(nc, "_sparse_calendar", {})))
advance function: advance_non_diff_sparse_calendar
delivery_buffer: (1, 128) 512 B
pending calendar buckets: 0

Binary source history#

Bitpacked inference shares a compact history of binary source events across outgoing edges. Suitable sources include NetStim events, an explicit binary mechanism variable with threshold=None, and voltage crossings whose thresholds are consistent for every outgoing edge of a source.

A connection with different threshold decisions on different edges needs the general dense representation. Delay length, source count and fanout determine how much memory the shared history saves.

bitpack_net = build_netstim_projection(backend="bitpacked_history", N=128, fanout=4)
bitpack_net.initialize(dt=0.025)

nc = next(iter(bitpack_net.synapses.values()))
print("advance function:", nc.advance.__name__)
print("bitpack_can_use:", getattr(nc, "_bitpack_can_use", None))
print("bitpack_mode:", getattr(nc, "_bitpack_mode", None))
print("bitpack_reason:", getattr(nc, "_bitpack_ineligible_reason", None))
print("delivery_buffer:", tuple(nc.delivery_buffer.shape), format_bytes(tensor_bytes(nc.delivery_buffer)))
print("spike_history_packed:", tuple(nc.spike_history_packed.shape), format_bytes(tensor_bytes(nc.spike_history_packed)))
advance function: advance_non_diff_bitpacked_history
bitpack_can_use: True
bitpack_mode: netstim
bitpack_reason: None
delivery_buffer: (1, 128) 512 B
spike_history_packed: (1001, 3) 23.5 KiB

Optional CUDA diagnostic#

The following cell reports availability of the optional CUDA acceleration used by eligible bitpacked inference. A PyTorch fallback is available. This diagnostic is not required to build or run a Network.

try:
    from dendra.models.networks import netcon_bitpack_ops
    print("available:", netcon_bitpack_ops.is_available())
    if hasattr(netcon_bitpack_ops, "build_info"):
        for key, value in netcon_bitpack_ops.build_info().items():
            print(f"{key}: {value}")
except Exception as exc:
    print("bitpack extension diagnostics unavailable:", repr(exc))
available: False
disabled: False
loaded: False

Check event semantics#

An explicit source event variable makes the intended event semantics clear: use its path as pre_var and set threshold=None. If initialization reports that bitpacked inference is ineligible, check that the variable is binary and that every outgoing edge of a source uses the same event decision, or select "dense".

The next cell prints eligibility details for the notebook’s example only.

# Example diagnostic pattern for a model you already built:
for name, nc in bitpack_net.synapses.items():
    print(name)
    print("  eligible:", getattr(nc, "_bitpack_can_use", None))
    print("  mode:    ", getattr(nc, "_bitpack_mode", None))
    print("  reason:  ", getattr(nc, "_bitpack_ineligible_reason", None))
netstim:spike->cells:exp2syn
  eligible: True
  mode:     netstim
  reason:   None

Differentiate a connected simulation#

Call network.train() and configure the needed derivatives with set_synaptic_diff_config(...) before initialization. For example, diff_delays=True enables interpolation gradients and diff_spiking=True enables surrogate threshold gradients. The training backend is independent of the requested inference backend: the default netcon_train_backend="auto" retains weight and delay gradients while choosing eligible source-history execution.

The following example enables weight, delay and spike derivatives. Training and parameters describes source selection, optimizer ownership and gradient boundaries.

train_net = build_netstim_projection(backend="bitpacked_history", N=128, fanout=4)
train_net.train()
train_net.set_synaptic_diff_config(
    diff_weights=True,
    diff_delays=True,
    diff_spiking=True,
    taps=2,
)

train_net.initialize(dt=0.025)
nc = next(iter(train_net.synapses.values()))
print("requested backend:", nc.delay_backend)
print("training:", nc.training)
print("advance function:", nc.advance.__name__)
print("delivery_buffer shape in training:", tuple(nc.delivery_buffer.shape))
requested backend: bitpacked_history
training: True
advance function: advance_diff
delivery_buffer shape in training: (1001, 128)

Reuse a steady-state warm start#

steady_state(...) caches an initialized warm start, so repeated trials can avoid a long equilibration. Initialize again at the desired timestep before each trial, as shown below.

When connection weights or delays change, use initialize(..., reinit_weights=True, reinit_delays=True) to refresh their expanded values. See initialization and checkpoints for cache policies, stochastic state and exact continuation.

cache_net = build_netstim_projection(backend="bitpacked_history", N=128, fanout=4)

# Long, coarse warmup. Keep this small in the docs notebook.
cache_net.steady_state(tstop=25.0, dt=0.1, progressbar=False)

# Later: shorter, finer simulation initialized from the cached state.
# Use reinit_weights=True / reinit_delays=True when parameters may have changed.
with dn.ctx(JIT=1):
    cache_net.initialize(
        dt=0.025,
        reinit_weights=True,
        reinit_delays=True,
    )
    cache_net.run(tstop=2.0)

print("state cache keys:", list(cache_net._state_cache.keys()))
print("synapse cache keys:", list(cache_net._syn_cache.keys()))
state cache keys: ['cells']
synapse cache keys: ['event', 'continuous']

Short training windows#

The following commented template illustrates repeated training from a cached warm start. A cached population state is not necessarily a fixed point of updated parameters; choose whether this approximation fits the protocol. Use a continuation checkpoint when the next window should continue the preceding simulation exactly.

# Pseudocode template; adapt the loss and optimizer to your model.

# net = build_large_model(...)
# optimizer = torch.optim.Adam(net.parameters(), lr=1e-3)
#
# net.eval()
# net.steady_state(tstop=1000.0, dt=0.1)
#
# for batch in batches:
#     optimizer.zero_grad(set_to_none=True)
#     net.train()
#     net.set_synaptic_diff_config(diff_weights=True, diff_delays=True, diff_spiking=True)
#
#     # Reinitialize from cached state using updated parameter values.
#     net.initialize(dt=0.025, reinit_weights=True, reinit_delays=True)
#     net.run(tstop=25.0, callbacks=[...])
#
#     loss = ...
#     loss.backward()
#     optimizer.step()

Structural edits and ambiguous targets#

After attaching a NetStim or adding connectivity, initialize again before execution. If one physical compartment contains several copies of a point-process mechanism, select its synapse slots explicitly; the compartment alone does not identify the intended contact.

Continuous projections#

Use connect_continuous(...) for an analog presynaptic signal rather than discrete events. Choose the target input, optional deterministic function or module, weight, delay and reduction. Transforms can contain trainable parameters, and the receiving mechanism declares its input through State.INPUT.

ContinuousCon delays are rounded to timestep offsets. The two- and three-tap differentiable delay policies described above apply to event NetCons. Continuous weights and transform parameters retain their gradients.

The product of the transformed signal and weight must have the units expected by the receiving input. There is no universal continuous-connection weight unit. See custom models for the receiving hooks and transform contract.

Scheduled events#

NetStim.schedule(...) and event connections’ schedule(...) accept predetermined event times and amplitudes, either as values or indexed live sources. Use these for reproducible stimulation or to train event timing and amplitude. The Network API documents the binding forms and differentiation controls.

Starting choices#

Goal

Configuration to try

Train weights or event delays

network.train() and netcon_train_backend="auto"; enable the required derivatives.

Require general per-connection event semantics

Dense training/inference.

Reduce inference memory for sparse traffic

netcon_delay_backend="sparse_calendar".

Reduce inference memory for shared binary source events

netcon_delay_backend="bitpacked_history".

Diagnose individual deliveries

track_netcon_events=True, for a small debugging run.

Leave event tracking disabled for large runs unless those diagnostics are needed; it can allocate substantial per-connection delay state.

Troubleshooting#

  • Memory exhaustion: construct on the final device, disable unneeded event tracking, and compare compact inference representations when their semantics fit the model.

  • Ineligible binary history: use a binary source variable with threshold=None, use source-consistent thresholds, or choose dense delivery.

  • Changed weights or delays appear stale: initialize with reinit_weights=True and reinit_delays=True.

  • Functional event capacity overflow: raise the configured pending_capacity and rerun from the unchanged starting continuation.

  • Unexpected performance: compare warmed rollouts on the actual hardware and traffic. Sparse calendars trade memory against calendar processing; their performance is not determined by storage size alone.

Larger models#

Apply the same choices to a larger model: build on its intended device, select the connection representation, then initialize. Use eval() for inference and train() with explicit differentiation controls for training. Keep initial experiments small enough to check event timing and memory before increasing population size.

Continue the workflow#

Functional execution compiles an ordinary connected Network. Inputs and randomness covers stimulation and replay, while recording and callbacks covers named Population recording. The Network API lists connectivity, scheduling and initialization arguments.