Batching and devices#

Batching creates independent model replicas for stimulus sweeps, parameter trials or Monte Carlo experiments. Device placement controls where each population and its connections execute. These are separate choices: a batched Network can still be placed on one device.

Run several stimulus conditions together#

Build an unbatched Network first, then call batch(n). This complete example applies a different current amplitude to each of three independent passive cells:

import torch
import dendra as dn
from dendra.models.mod import pas
from dendra.units import nA

DT = 0.025
with dn.ctx(DEVICE="cpu", DTYPE=torch.float64, JIT=0):
    cells = dn.SingleCompartment(
        N=1, C=1, v_init=-65.0, integrator=dn.bwd_euler_sc(imem=False)
    )
    cells.insert(pas, g=0.001, e=-65.0)
    network = dn.Network({"cells": cells}).batch(3)
    amplitudes = torch.tensor([0.05, 0.1, 0.2]).reshape(3, 1, 1, 1) * nA
    network.cells[:].inject(dn.mono_rect(amp=amplitudes, delay=0.1, pw=0.2))
    network.initialize(DT)
    network.run(steps=40)
    print(network.cells.v.shape)  # (batch=3, population=1, compartment=1)

Use Population.batch(n) for a standalone Population. Use Network.batch(n) for a connected model; its populations must be unbatched when the Network is constructed. Existing registered injections and synapse-slot targets are rebased by batching, so users do not adjust their indices manually.

Make batch and spatial axes explicit#

Let N be population size and C compartment count. A Population has shape [N,C], or [*B,N,C] with explicit batch dimensions *B. A selected Slice has the corresponding selected spatial shape.

Waveforms return time last. An intracellular waveform for a selection shaped [*B,Ns,Cs] can return:

Waveform output

Meaning

[T]

One waveform shared by every selected site and replica.

[Cs,T]

One waveform per selected compartment, shared over cells and replicas.

[Ns,1,T]

One waveform per selected cell, shared over compartments and replicas.

[*B,1,1,T]

One waveform per batch condition, shared over selected spatial sites.

[*B,Ns,Cs,T]

A fully specified waveform at every selected site.

For rectangular-pulse parameters, a final singleton axis represents time. The example therefore uses amplitude shape (batch, 1, 1, 1) to produce samples shaped (batch, 1, 1, time).

Dendra first tries ordinary trailing PyTorch broadcasting. If that fails, low-rank value axes may broadcast over the explicit batch grid, with spatial singleton axes added. This fallback requires the batch grid to remain a leading Cartesian prefix; advanced or integer indexing can change that layout. Explicit spatial singleton axes are the clearest choice for sweeps, as in the amplitude example above.

Equal-size axes can be ambiguous. For shape [3,N,3], a per-step [3] already broadcasts as compartments, so it is shared over batches. Use [3,1,1] to state per-batch intent. Ordinary trailing broadcasting takes precedence over the batch fallback.

Use tensor inputs on Populations and Networks#

dn.func.Inputs supplies deterministic extracellular voltage (ve) and intracellular current (intra) in both native and functional execution. A step consumes one spatial frame; a run consumes a time-leading tape. Networks accept a mapping keyed by Population name.

Continuing the previous example, this supplies extracellular samples while retaining the registered intracellular waveform:

steps = 40
voltage = torch.zeros(
    steps, *network.cells.shape,
    dtype=network.cells.dtype(), device=network.cells.device(),
)
network.initialize(DT)
network.run(steps=steps, inputs={"cells": dn.func.Inputs(ve=voltage)})

The time axis is first for Inputs, in contrast to Waveform output. Fully specified tape shapes are [T,*B,N,C]; each per-step spatial payload follows the Population’s broadcasting rules. Omitting intra keeps Slice.inject(...) stimulation. Supplying explicit intra conflicts with registered solver-level intracellular injections.

The legacy direct Population.run(ve=...) spelling also uses time first. For a Network, use the named Inputs mapping to provide precomputed extracellular voltage. See inputs and randomness and the complete shared-input example for gradients, stepping and chunked execution.

Separate spatial fields from temporal waveforms#

Use extra=(field, waveform) for a standalone Population, or extra={"name": (field, waveform)} for a Network. This is useful when a spatial extracellular field is fixed while stimulus timing or amplitude changes. A list of such pairs represents several independently parameterized contacts.

The field broadcasts to [*B,N,C]; the temporal waveform broadcasts to [*B,N,T], with time last. Ordinary trailing broadcasting takes precedence, with the same batch-only fallback for low-rank values. Explicit [*B,1,1] fields and [*B,1,T] temporal values state per-batch intent. Population temporal inputs also accept time-last tensors; Network extra temporal entries are Waveforms.

Slice.inject(...) remains the convenient interface for intracellular Waveforms. Inputs and randomness explains runtime-replaceable extra, direct tensor drives and random stimulation.

Choose and inspect devices#

A native Network can contain populations on CPU, CUDA or MPS devices. Connections execute on their target synapse’s device, and cross-device source signals require copies. Keep tightly coupled populations colocated unless splitting them serves a measured workload.

For an existing Network, inspect placement per Population:

network.devices()  # Population name -> device
network.dtypes()   # Population name -> dtype

network.device() describes only the first Population. Use the mappings for a heterogeneous model. Construct large models in a dn.ctx(DEVICE=..., DTYPE=...) context to avoid temporary copies during later placement changes.

dn.compile(Network) requires a single device. Choose an integrator supported by the target device; MPS supports float32 rather than float64. See custom models for functional model and solver support, and connected networks for event-memory choices.