Functional execution#

dn.compile creates a reusable Population or Network runner. The dn.func lifecycle also supports explicit plans and tensor packets for training, reproducible simulation, and checkpoint continuation. Start with Run models with explicit state for complete workflows; the Functional plans and tensor packets reference covers individual plans and packets.

Compilation and execution#

Compile an initialized model with either a timestep count (steps=) or an elapsed time in milliseconds (duration=). Use the solver timestep for dt. A Network runner uses the timestep set by network.initialize(dt).

import dendra as dn

program = dn.compile(model, dt=0.025, steps=400)
state, auxiliary = program()  # Same as dn.func.run(program).
state, auxiliary = dn.func.run(program, auxiliary["continuation"], steps=200)

A call without state starts from the runner’s configured initialization. Pass the continuation to resume with the same simulation state, effective sources, and callback carry. When callbacks are configured, their results are in auxiliary["callbacks"].

compile(population, *, dt, steps=None, duration=None, extra=None, chunk_steps=None, execution='scan', callbacks=None, inference=True, initialization='snapshot', checkpoint_every=None, trainable=(), pending_capacity=None, backend='inductor', options=None, **compile_options)[source]#

Create a compiled runner for an initialized Population or Network.

Supply exactly one of steps or duration for the default run length.

Parameters:
  • population (Population or Network) – Initialized source model. A Network’s timestep and training mode must match its initialized configuration.

  • dt (float) – Positive solver timestep in ms. For a Network it must match initialization.

  • steps (int, optional) – Positive default timestep count.

  • duration (float, optional) – Non-negative default elapsed time in ms. Fractional time is retained in the returned continuation until a complete timestep can be accepted.

  • extra (stimulation specification, mapping, or VarInput, optional) – Extracellular (field, waveform) pair or contact sequence. Networks use a Population-name mapping. VarInput() declares call-local deterministic stimulation; each call then supplies extra=. Explicit Inputs.ve cannot drive a Population that also has bound extracellular stimulation.

  • chunk_steps (int, optional) – Compiled kernel width. Calls may use other horizons and shorter tails. The default is the nominal default horizon, capped at 64 for runtime-extra slots. This width does not limit recording history.

  • execution ({"scan", "while"}, default "scan") – Scan supports first-order training. While is inference-only; Population while runners require a compiled width of at least four steps.

  • callbacks (mapping, optional) – Named built-in or pure custom callback configurations. For example, {"trace": dn.Recorder(("v", "t"))} records a Population trajectory.

  • inference (bool, default True) – Suppress execution gradients. Set False for training and select sources with trainable.

  • initialization ({"snapshot", "fresh"}, default "snapshot") – No-state calls restart the captured snapshot or run fresh initialization. Explicit state or a Continuation always continues without initialization.

  • checkpoint_every (int, optional) – Training-scan activation-checkpoint span. Backward recomputes these spans; gradients still cover the whole run. This is independent of kernel width.

  • trainable (selector or iterable of selectors, optional) – Exact/unique partial names, full-name globs, or re:/compiled regular expressions selecting independent runner-owned parameter leaves.

  • pending_capacity (int or mapping, optional) – Network pending-event calendar capacities. A full calendar raises before publishing a result. Lower again with more capacity from the pre-call native boundary; calendar tensor shapes belong to that plan.

  • backend (str or callable, default "inductor") – Backend passed to torch.compile.

  • options (dict, optional) – Backend options. Explicit choices override Dendra’s inference defaults.

  • **compile_options – Additional torch.compile options, such as fullgraph or disable.

Returns:

Callable returning (state, auxiliary). Continue with dn.func.run(program, auxiliary["continuation"]). Callback results are available at auxiliary["callbacks"].

Return type:

CompiledRunner or CompiledNetworkRunner

Notes

Compilation is lazy. Execution leaves the native model unchanged and preserves shared parameter aliases. Use inspect_sources() to inspect effective sources, resolve_steps() to size deterministic inputs, and initialize() for an explicit fresh trial. Call-local VarInput slots accept deterministic waveforms; randomized Poisson waveforms must be bound when compiling. Host runners run outside torch.compile and torch.func; use make_functional() for explicit tensor transforms.

run(functional, step=..., state=..., inputs=None, *, steps=None, duration=None, checkpoint_every=None, host_span_steps=None, tstop=None, dt=None, extra=..., callbacks=None, callback_state=None, draws=None, parameters=..., constants=..., initialization=...)[source]#

Execute a compiled runner or an explicit functional boundary.

Call run(program, ...) to start from the runner’s configured initial state. Resume a previous run with run(program, continuation, ...) or run(program, state=continuation, ...). The runner supplies its configured timestep, callbacks, kernel width, and checkpoint policy.

For explicit execution, use run(plan_or_kernel, continuation, ...) or run(bound, state_or_continuation, ...). A plan or kernel uses the continuation’s sources for that call. A raw binding owns its sources, which must match a supplied continuation.

Parameters:
  • functional (compiled runner, functional plan, compiled chunk or binding) – Execution target. Runner calls without state restart their configured snapshot/fresh policy. Explicit plans/kernels require a Continuation.

  • step (tensor tree or Continuation) – The second positional argument is the boundary for preferred calls; state= is also supported. A Continuation includes effective sources and callback carry. Prepared Population bindings accept explicit state/carry.

  • state (tensor tree or Continuation) – The second positional argument is the boundary for preferred calls; state= is also supported. A Continuation includes effective sources and callback carry. Prepared Population bindings accept explicit state/carry.

  • inputs (Inputs or mapping, optional) – Deterministic time-leading voltage/current tapes. Networks use Population names as keys. Supplied tapes must match the selected accepted step count.

  • steps (int or float, optional) – Exact count or elapsed time in ms; mutually exclusive. Durations include fractional carry and publish its new remainder. Explicit counts leave it unchanged. Runners retain their default horizon when neither is supplied; explicit bindings can infer length from supplied tapes.

  • duration (int or float, optional) – Exact count or elapsed time in ms; mutually exclusive. Durations include fractional carry and publish its new remainder. Explicit counts leave it unchanged. Runners retain their default horizon when neither is supplied; explicit bindings can infer length from supplied tapes.

  • draws (RuntimeDraws, optional) – Stochastic tape. Omission retains automatic host sampling.

  • callbacks (FunctionalCallbacks, optional) – Prepared collection for explicit plans/bindings. Runners use their own configured collection. Results are in auxiliary["callbacks"].

  • callback_state (FunctionalCallbackState, optional) – Carry for an explicit-state continuation. Incompatible with a Continuation, which already contains it.

  • checkpoint_every (int, optional) – Explicit-binding training-checkpoint or ordinary host span. They are mutually exclusive and independent of compiled kernel width. Runners use their construction-time checkpoint policy.

  • host_span_steps (int, optional) – Explicit-binding training-checkpoint or ordinary host span. They are mutually exclusive and independent of compiled kernel width. Runners use their construction-time checkpoint policy.

  • parameters (optional) – Runner-only call overrides. A Continuation already owns its sources; initialization overrides require a fresh no-state call.

  • constants (optional) – Runner-only call overrides. A Continuation already owns its sources; initialization overrides require a fresh no-state call.

  • initialization (optional) – Runner-only call overrides. A Continuation already owns its sources; initialization overrides require a fresh no-state call.

  • extra (stimulation specification or mapping, optional) – Call-local stimulation. Runners accept it only for declared VarInput slots; None supplies zero drive.

  • dt (float, optional) – Explicit-binding timestep override, validated against prepared execution. Runners use their configured timestep.

  • tstop (float, optional) – Duration in the supported four-positional compatibility form described below.

Returns:

(state, auxiliary). The final explicit state does not advance the native model. The auxiliary mapping contains callback results and, for runners/raw bindings/packet execution, a continuation carrying effective sources, state and callback phase.

Return type:

tuple

Notes

run(functional, step_callable, state, inputs, tstop=...) remains supported. In that compatibility form supplied drive length takes precedence over tstop. Use initialize() for an explicit fresh boundary; execution from a packet never implicitly initializes it. Raw Population bindings own each forward’s preparation graph and can reuse safe inference preparation. Gradients span all chunks and activation checkpoints. This host scheduler runs outside torch.compile and torch.func; use combined plan tensor methods inside those transforms.

initialize(functional, tensors=..., *, initialization=None, parameters=..., constants=..., draws=None)[source]#

Create a fresh functional execution boundary.

Parameters:
  • functional (compiled runner, FunctionalPopulation or FunctionalNetwork) – Receiving runner or lowered plan. Initialization does not advance its native source or update runner defaults.

  • tensors (PopulationTensors, NetworkTensors or Continuation, optional) – Explicit source/state boundary. Plans require a matching tensor bundle or Continuation. A runner uses its captured defaults when omitted; a supplied Continuation supplies effective sources and current RNG carry instead.

  • initialization (InitializationInput or NetworkInitializationInput, optional) – Initialization recipe override. Runners and Network plans retain defaults; a Population bundle supplies tensors.initialization. A Population plan with a Continuation requires this argument explicitly.

  • parameters (mapping, optional) – Runner-only source overrides. Non-None overrides cannot accompany a Continuation, whose sources are already explicit.

  • constants (mapping, optional) – Runner-only source overrides. Non-None overrides cannot accompany a Continuation, whose sources are already explicit.

  • draws (InitializationDraws, optional) – Replay complete initialization draws. Omission samples missing draws from explicit RNG carry. Cannot be combined with component draw fields retained in an initialization recipe.

Returns:

Fresh simulation state and effective parameter/constant mappings, with no callback carry. The first run starts fresh recordings and reductions.

Return type:

Continuation

Notes

Native initialization ordering, retained samples, reseeding and bound steady-state cache policies apply. Parameter-writing transforms operate on the supplied effective sources; initialization does not recover an earlier raw baseline. Tensor aliases and gradient history are retained without detaching sources. Use detach_continuation() between independent training trials when recurrent history should be cut.

This host operation runs outside compilation, torch.func and forward AD. It follows the caller’s gradient mode even for an inference-configured runner and creates versioned outputs inside inference mode. The lower-level pure plan initialize methods remain available for tensor transforms.

resolve_steps(target, state=None, *, steps=None, duration=None, dt=None)[source]#

Return an explicit request’s accepted timestep count without running it.

Parameters:
  • target (native model, functional plan, binding, compiled chunk or runner) – Native models must be initialized. Functional targets require state.

  • state (tensor tree or Continuation, optional) – Functional execution boundary; omitted for native models.

  • steps (int, optional) – Non-negative exact count. Supply exactly one of steps or duration.

  • duration (float, optional) – Non-negative elapsed time in ms, combined with retained fractional time.

  • dt (float, optional) – Native Population timestep; omission uses the native backend default. Native Networks use their initialized timestep. Functional callers normally omit it; an explicit value is validated against the target’s timestep.

Returns:

Number of complete timesteps. Use it to size time-leading Inputs. Runner horizon defaults and compiled widths are not inferred.

Return type:

int

Notes

Population duration queries use the effective timestep from a binding, Continuation constants or runner defaults. An unbound plan/chunk with plain state uses its nominal timestep. Networks use their fixed plan timestep. Native queries require canonical host duration budgeting but not functional integrator or stochastic-sampler support.

The query leaves state, fractional carry, RNG, callbacks and caches unchanged. It performs no initialization, preparation, lowering or waveform evaluation. Execute with the original duration= request so execution publishes the updated remainder; replacing it with steps=resolved_count preserves the old remainder instead. This is a host operation outside compilation, function transforms and forward AD.

longrun(functional, step, state, tstop, chunklength, inputs=None, *, dt=None, extra=None, callbacks=None, callback_state=None)[source]#

Run an explicit Population binding for a duration in host spans.

Parameters:
  • functional (FunctionalPopulation) – Lowered Population owning the binding and state schema.

  • step (callable) – Exact binding returned by bind, or a supported preparation/step partial.

  • state (dict) – Initial explicit Population state.

  • tstop (float) – Duration to advance from the supplied state, in milliseconds.

  • chunklength (int) – Positive number of steps per host span, independent of compiled kernel width.

  • inputs (Inputs or RolloutInput, optional) – Time-leading deterministic tapes and optional draw packets. Their length must match the resolved horizon.

  • dt (float, optional) – Timestep in milliseconds; defaults to the plan’s nominal timestep.

  • extra (object, optional) – Extracellular field/Waveform bindings evaluated over the execution spans.

  • callbacks (FunctionalCallbacks, optional) – Prepared callback collection for this Population.

  • callback_state (FunctionalCallbackState, optional) – Matching carry to resume without duplicating the initial sample.

Returns:

(state, outputs): final explicit state and transition outputs, including callback results when configured. Gradients span all host spans.

Return type:

tuple

See also

run

Shared interface using run(bound, state, duration=..., host_span_steps=...).

longrun_checkpointed(functional, step, state, tstop, chunklength, inputs=None, *, dt=None, extra=None, callbacks=None, callback_state=None)[source]#

Run an explicit Population binding with activation checkpointing.

Accepts the same arguments and returns as longrun(). tstop is the relative duration to advance; chunklength sets the number of steps per checkpoint span. Non-reentrant checkpointing retains gradients through the full simulation while replaying spans during backward.

Steps and callbacks must be pure, deterministic and replay-safe. Replay reuses and validates prepared inputs; automatic sampling occurs outside the replayed transition. With gradients disabled, execution uses ordinary host spans. The shared spelling is run(bound, state, duration=..., checkpoint_every=...).

class CompiledRunner(population, *, dt, steps=None, duration=None, extra=None, chunk_steps=None, execution='scan', callbacks=None, inference=True, initialization='snapshot', checkpoint_every=None, trainable=(), backend='inductor', options=None, **compile_options)[source]#

Compiled Population execution with explicit inputs and continuations.

Construct with compile(), usually exposed as dn.compile. Calling the runner returns (state, auxiliary) and does not advance its native source. Omitting state restarts the configured snapshot/fresh initialization policy; passing auxiliary["continuation"] continues effective parameters, constants, simulation state and callback carry together.

steps= or duration= overrides a call’s default horizon without changing chunk_steps. inputs=Inputs(...) supplies deterministic tapes and draws=RuntimeDraws(...) replays stochastic tapes. Named callbacks return results under auxiliary["callbacks"]. Per-call source overrides retain their Tensor identities and gradients but do not replace runner defaults.

Set inference=False for training. Scan supports first-order gradients; while is inference-only. checkpoint_every trades recomputation for saved activations while retaining full-run gradients and requested recordings. Independent training forwards own their preparation graphs; safe snapshot inference may reuse preparation.

extra=VarInput() requires call-local extra= on every invocation; extra=None selects zero drive. Waveform types and contact counts may vary. These slots accept deterministic waveforms. Bind randomized Poisson waveforms when compiling. See compile() for construction options and __call__() for invocation arguments.

property initial_state#

Captured restart snapshot; tensor leaves may be edited by the caller.

Fresh-policy calls ignore this snapshot unless it is explicitly passed as state, which always bypasses initialization.

property initialization_inputs#

Independent fresh-initialization defaults; tensor leaves are editable.

Use requires_grad_() or pass an explicit InitializationInput per fresh call to differentiate these initialization-only inputs. They are not included in parameters or selected by trainable.

property parameters#

Read-only mapping of independent, live parameter tensor leaves.

property named_parameters#

Read-only canonical names for the runner-owned default parameter leaves.

property trainable_parameters#

Read-only named defaults currently requiring gradients, including aliases.

Tensor objects remain live; freezing or unfreezing a leaf is reflected on the next access. Per-call parameter overrides are not included. Deduplicate values by identity before supplying them to an optimizer. Inference execution suppresses gradients even for selected leaves.

find_parameters(query)[source]#

Return all named defaults matching a substring, glob, or regex query.

parameter_name(query)[source]#

Resolve one exact, partial, glob, or regex match among named defaults.

get_parameter(query)[source]#

Return the live default Tensor selected by one unambiguous query.

property constants#

Read-only mapping of independent, version-checked constants.

property functional#

The lowered execution plan owned by this runner.

property callbacks#

Bound callback collection, or None when callbacks are omitted.

Use its export_state and restore_state methods to save and resume explicit callback carry with an equivalent reconstructed runner.

export_continuation(continuation)[source]#

Export owned detached data for portable continuation checkpoints.

Effective raw sources retain their Tensor ties and trainability as new leaves. Save the versioned packet with torch.save. Export runs outside compilation and function transforms; prior graphs and recording history are excluded. Packets from dn.func.initialize begin callbacks on their first execution.

restore_continuation(packet)[source]#

Restore a plain checkpoint against this compatible initialized runner.

The receiving model/schema, dtype/device and active callback carry must match. Initialized packets begin callbacks on their first execution. Returns independent ordinary Tensor leaves in a Continuation without initialization, preparation, sampling or execution. Runner defaults are unchanged.

property kernel#

The fixed-width compiled kernel used by this runner.

execution_report()[source]#

Return the underlying kernel’s latest successful execution report.

warm(state=None, *, verbose=False, **call_kwargs)[source]#

Warm forward execution with a discarded representative run.

Parameters:
  • state (tensor tree or Continuation, optional) – Select the same restart or continuation as __call__().

  • verbose (bool, optional) – Print start, elapsed-time updates and completion to standard error. Defaults to False. Progress describes the warm-up call, not a compiler percentage.

  • **call_kwargs – Invocation arguments accepted by __call__(), including inputs, draws, runtime extra, source overrides and the horizon.

Returns:

This runner, with the encountered execution variants warmed.

Return type:

CompiledRunner

Notes

Executes the selected simulation and discards its results. Model/source state, RNG carry and parameter gradients retain their values. Recorder file publication is suppressed while its numerical callback and chunk schedule are preserved. Compilation and safe preparation caches remain. Accelerator work completes before return. Training warms the forward path only; a subsequent backward may compile. Different shapes, gradient flags or horizons can require other variants.

__call__(state=None, *, steps=None, duration=None, parameters=None, constants=None, inputs=None, callback_state=None, initialization=None, extra=..., draws=None)[source]#

Run from a restart snapshot, explicit state or Continuation.

Parameters:
  • state (tensor tree or Continuation, optional) – Omission/None restarts the configured initialization policy. A Continuation also supplies effective parameters/constants and callback carry.

  • steps (int or float, optional) – Override the default horizon with an exact count or elapsed time in ms. They are mutually exclusive; per-call values may be zero.

  • duration (int or float, optional) – Override the default horizon with an exact count or elapsed time in ms. They are mutually exclusive; per-call values may be zero.

  • parameters (mapping, optional) – Call-local source overrides. They cannot accompany a Continuation.

  • constants (mapping, optional) – Call-local source overrides. They cannot accompany a Continuation.

  • inputs (Inputs or mapping, optional) – Deterministic time-leading tapes. Networks use Population-name mappings.

  • draws (RuntimeDraws, optional) – Explicit stochastic tape; omission retains automatic sampling.

  • callback_state (FunctionalCallbackState, optional) – Carry for an explicit-state call. A Continuation includes this already.

  • initialization (InitializationInput or NetworkInitializationInput, optional) – Fresh-policy initialization override; incompatible with explicit state.

  • extra (stimulation specification or mapping, optional) – Required when runtime VarInput slots were declared. None is zero drive.

Returns:

  • state (tensor tree) – Final explicit simulation state.

  • auxiliary (dict) – Contains continuation and, when configured, callback results. Fresh initialization also publishes effective parameters and constants.

class CompiledNetworkRunner(network, *, dt, steps=None, duration=None, extra=None, chunk_steps=None, execution='scan', callbacks=None, inference=True, initialization='snapshot', checkpoint_every=None, trainable=(), pending_capacity=None, backend='inductor', options=None, **compile_options)[source]#

Compiled Network execution with shared parameters and explicit continuation.

Create with compile(). Calls return (state, auxiliary) without advancing the native Network. A no-state call restarts the configured snapshot/fresh policy, including its RNG and delivery state. Pass the returned auxiliary["continuation"] to continue sources, state and callback phase.

Parameters are independent nested Tensor mappings with shared aliases preserved. named_parameters provides dotted names; trainable_parameters lists live defaults requiring gradients. Per-call overrides remain local. Training requires a Network initialized in training mode and inference=False. Scan supports gradients; while is inference-only.

Inputs map Population names to Inputs; RuntimeDraws supplies stochastic tapes. Recorders use qualified paths such as left.v or PopulationCallback for a local callback. steps/duration overrides reuse the configured kernel width and cached tails. Activation checkpointing preserves whole-run gradients, RNG and callback continuation.

extra maps Population names to extracellular field/waveform bindings. VarInput() declares deterministic runtime slots; omitted names in a supplied runtime mapping receive zero drive. Bind randomized Poisson waveforms during compilation. pending_capacity controls event-calendar capacity; overflow raises without publishing an incomplete result.

Use capture_continuation() to snapshot a native boundary and commit_continuation_() to transfer detached effective sources and state back to a compatible native model. See compile() and __call__() for construction and invocation arguments.

property initial_state#

Complete restart snapshot; explicit state always bypasses initialization.

Fresh-policy no-state calls use initialization_inputs instead.

property initialization_inputs#

Editable independent defaults for Population, clock and cache initialization.

Initialization-only leaves are separate from parameters; use requires_grad_() or explicit overrides to differentiate fresh initial values. Captured steady-state cache values are detached.

property parameters#

Read-only nested parameter packet with independent, live Tensor leaves.

property named_parameters#

Read-only dotted names for the same live leaves as parameters.

property trainable_parameters#

Read-only named defaults currently requiring gradients, including aliases.

Reflects live freezing/unfreezing on access, not per-call overrides. Deduplicate values by identity before supplying them to an optimizer. Inference execution suppresses gradients even for selected leaves.

property constants#

Read-only nested constants; edits to Tensor values apply on the next call.

property functional#

The lowered execution plan owned by this runner.

property callbacks#

Bound callback collection, or None when callbacks are omitted.

Use its export_state and restore_state methods to save and resume explicit callback carry with an equivalent reconstructed runner.

export_continuation(continuation)[source]#

Export detached owned continuation data, retaining source ties/flags.

The versioned plain data/Tensor packet supports torch.save and torch.load(..., weights_only=True). It excludes upstream graphs, recording history, input/draw tapes and optimizer state. Packets from dn.func.initialize begin callbacks on their first execution.

restore_continuation(packet)[source]#

Restore a checkpoint into this compatible initialized Network runner.

Owner/schema, dtype/device, shared source ties and active callback carry are validated before returning owned ordinary Tensor leaves in a Continuation. Initialized packets begin callbacks on their first execution. No initialization, preparation, RNG sampling or execution runs, and runner defaults retain their values.

property kernel#

The fixed-width compiled kernel used by this runner.

parameter_name(query)[source]#

Resolve one exact, partial, glob, or regex match among named defaults.

get_parameter(query)[source]#

Return the live default Tensor selected by one unambiguous query.

find_parameters(query)[source]#

Return all named defaults matching a substring, glob, or regex query.

execution_report()[source]#

Return the latest successful kernel dispatch, including tails/replay.

warm(state=None, *, verbose=False, **call_kwargs)[source]#

Warm forward execution with a discarded representative Network run.

Parameters:
  • state (tensor tree or Continuation, optional) – Select the same restart or continuation as __call__().

  • verbose (bool, optional) – Print start, elapsed-time updates and completion to standard error. Defaults to False. Progress describes the warm-up call, not a compiler percentage.

  • **call_kwargs – Invocation arguments accepted by __call__(), including Population-scoped inputs/extra, draws, sources and the horizon.

Returns:

This runner, with the encountered execution variants warmed.

Return type:

CompiledNetworkRunner

Notes

Executes the selected simulation and discards its results. Model/source state, RNG carry and parameter gradients retain their values. Recorder file publication is suppressed while its numerical callback and chunk schedule are preserved. Compilation and safe preparation caches remain. Accelerator work completes before return. Training warms the forward path only; a subsequent backward may compile. Different shapes, gradient flags or horizons can require other variants.

__call__(state=None, *, steps=None, duration=None, parameters=None, constants=None, inputs=None, callback_state=None, initialization=None, extra=..., draws=None)[source]#

Run from a restart snapshot, explicit state or Continuation.

Parameters:
  • state (tensor tree or Continuation, optional) – Omission/None restarts the configured initialization policy. A Continuation also supplies effective parameters/constants and callback carry.

  • steps (int or float, optional) – Override the default horizon with an exact count or elapsed time in ms. They are mutually exclusive; per-call values may be zero.

  • duration (int or float, optional) – Override the default horizon with an exact count or elapsed time in ms. They are mutually exclusive; per-call values may be zero.

  • parameters (mapping, optional) – Call-local source overrides. They cannot accompany a Continuation.

  • constants (mapping, optional) – Call-local source overrides. They cannot accompany a Continuation.

  • inputs (Inputs or mapping, optional) – Deterministic time-leading tapes. Networks use Population-name mappings.

  • draws (RuntimeDraws, optional) – Explicit stochastic tape; omission retains automatic sampling.

  • callback_state (FunctionalCallbackState, optional) – Carry for an explicit-state call. A Continuation includes this already.

  • initialization (InitializationInput or NetworkInitializationInput, optional) – Fresh-policy initialization override; incompatible with explicit state.

  • extra (stimulation specification or mapping, optional) – Required when runtime VarInput slots were declared. None is zero drive.

Returns:

  • state (tensor tree) – Final explicit simulation state.

  • auxiliary (dict) – Contains continuation and, when configured, callback results. Fresh initialization also publishes effective parameters and constants.

Runtime inputs and randomness#

See Stimulation, input tapes and randomness for input shapes, explicit draw replay, automatic sampling, and variable extracellular stimulation.

class Inputs(ve=None, intra=None)[source]#

Explicit extracellular voltage and intracellular current inputs.

ve and intra contain deterministic Tensor values or None. A step consumes one frame; a rollout, compiled chunk or host run consumes time-leading tapes. Their existing broadcasting rules apply. Tensor references, views and gradients remain caller-owned.

Native Population and Network step, run, longrun and longrun_checkpointed accept these same deterministic packets. Slice.inject remains the waveform interface; omitting intra retains its registered stimulation, while explicit intra conflicts with registered solver-level injections.

Networks accept a mapping from Population names to these same packets. Functional and native execution accept stochastic values and RNG timelines separately through draws=RuntimeDraws(...). Omitting draws retains automatic sampling. Existing StepInput, RolloutInput and NetworkRolloutInput packets remain supported.

Create new instance of Inputs(ve, intra)

ve: Tensor | None#

Alias for field number 0

intra: Tensor | None#

Alias for field number 1

class VarInput[source]#

Declare a required call-time extra in dendra.func.compile().

Pass extra=VarInput() when compiling, then supply extra= on every invocation. A specification contains a field/Waveform pair or a sequence of contacts. Supported deterministic waveform recipes and contact counts may change between invocations. extra=None supplies zero stimulation.

Use extra=dn.VarInput() when compiling to supply extracellular stimulation at call time.

class RuntimeDraws(draws, rng)[source]#

Explicit runtime stochastic values and their resulting RNG states.

Obtain one frame with sample_runtime_draws() without a horizon, or a time-leading tape with explicit steps= or duration=. Native initialized models use their current boundary; functional targets also require state or a Continuation. Sampling leaves the source boundary unchanged.

Pass draws=packet to native or functional execution. step consumes one frame; run/longrun methods consume a tape matching their accepted timestep count. The same duration must be used for sampling and execution so fractional carry is updated once. Families cover declared NOISE/State SDE, NetStim renewal and supported randomized Poisson waveform evaluations. Shared RNG ordering is preserved across these families.

Base draws are detached; model/distribution parameters retain their normal gradient paths. Execution publishes the supplied RNG timeline, allowing later automatic sampling to continue from that point. Keep packet leaves unchanged until activation-checkpoint backward completes. Native checkpointed training requires versioned tensors; clone externally created inference tensors outside inference mode before using them there.

Use InitializationDraws for initialization rather than runtime draws. The older component-specific sampling methods retain their packet layouts; the shared sampler supplies runtime-only Poisson invocation rows.

Create new instance of RuntimeDraws(draws, rng)

draws: dict[str, object]#

Alias for field number 0

rng: dict[str, object]#

Alias for field number 1

class InitializationDraws(random=None, stimulation=None, netstim=None, connections=None)[source]#

Replayable base draws and RNG carry for fresh initialization.

Obtain a complete packet with dendra.func.sample_initialization_draws() from an initialized native model, a lowered model and tensor bundle, or a compiled runner. Pass it through draws= to native Population/Network initialize or dendra.func.initialize(). Native initialization mutates and returns the model; functional initialization returns a Continuation. Native capture follows default initialization options and requires an already built, initialized canonical model. Explicit native replay does not support forced rebuilding. For a Population, random contains its RAND/NOISE packet and stimulation its Poisson packet. For a Network those fields map Population names to packets or None; netstim and connections contain its existing component draw packets. Generator frames retain their native publication boundaries, including intermediate frames for shared streams.

Sampling follows the ordered initializer, including transforms and cache restoration. It changes neither the native source nor the supplied carry. Distribution parameters keep their ordinary gradients during replay. Runtime execution uses the separate dendra.func.RuntimeDraws.

Create new instance of InitializationDraws(random, stimulation, netstim, connections)

random: RandomParameterDraw | Mapping[str, RandomParameterDraw | None] | None#

Alias for field number 0

stimulation: StimulationDraw | Mapping[str, StimulationDraw | None] | None#

Alias for field number 1

netstim: object#

Alias for field number 2

connections: object#

Alias for field number 3

sample_runtime_draws(target, state=None, *, steps=None, duration=None, dt=None, extra=None)[source]#

Sample detached runtime draws without advancing the incoming boundary.

Parameters:
  • target (native model, functional plan, binding, compiled chunk or runner) – Initialized native model or compatible functional execution target.

  • state (tensor tree or Continuation, optional) – Required for functional targets and omitted for native targets.

  • steps (int, optional) – Non-negative tape length. Omit both horizon arguments for a single frame.

  • duration (float, optional) – Non-negative elapsed time in ms. Produces a tape using the same effective timestep and fractional carry as execution. Mutually exclusive with steps.

  • dt (float, optional) – Native Population timestep, defaulting to the native backend setting. A supplied Native Network or functional timestep must match its target.

  • extra (stimulation specification or mapping, optional) – Native call-local extracellular bindings whose Poisson draws are sampled. Supply them again during replay. Omit for functional targets, whose stimulation bindings belong to the lowered plan.

Returns:

One draw/RNG frame, or a time-leading tape for an explicit horizon. Zero accepted steps produces fresh empty leaves without advancing RNG carry.

Return type:

RuntimeDraws

Notes

Source state, global/source RNG, waveform schedules and preparation caches are unchanged. Sampling uses isolated generators in native request order and preserves shared streams. Outputs are detached versioned tensors, including when called under inference mode. Replay with the same boundary, duration and stimulation bindings so execution alone updates fractional time and RNG.

Native sampling requires compatible canonical scheduling and a single simulation device. Functional runners require explicit state; their restart policy is not applied. This host operation runs outside compilation, function transforms and forward AD. Initialization uses sample_initialization_draws() and InitializationDraws instead.

sample_initialization_draws(functional, tensors=..., *, initialization=None, parameters=..., constants=...)[source]#

Capture replayable stochastic inputs for one fresh initialization.

Parameters:
  • functional (initialized Population/Network, compiled runner or lowered plan) – Target whose initialization protocol determines draw ordering.

  • tensors (PopulationTensors, NetworkTensors or Continuation, optional) – Required for a lowered plan, optional for a runner, and omitted for native targets. A Continuation supplies its current effective sources and RNG.

  • initialization (InitializationInput or NetworkInitializationInput, optional) – Functional recipe override. A Population plan with a Continuation requires it. Native capture uses the model’s default initialization options.

  • parameters (mapping, optional) – Runner-only source overrides, incompatible with a supplied Continuation.

  • constants (mapping, optional) – Runner-only source overrides, incompatible with a supplied Continuation.

Returns:

Base draws and resulting RNG states for replay with native model.initialize(draws=packet) or initialize().

Return type:

InitializationDraws

Notes

Capture leaves the source boundary, global RNG and runner caches unchanged. It follows initialization transforms and cache restoration under no_grad to observe draw ordering; initialized values are discarded. Native capture uses an isolated model copy and requires an initialized compatible model. Newly sampled draws are detached. Explicit component draw values already in the recipe retain their Tensor identities and gradient flags.

Capture and replay are separate initialization executions; each invokes authored transforms. Automatic initialization samples within a single call. Forced native rebuilding is unsupported with explicit draw replay. This host operation runs outside compilation, function transforms and forward AD.

Continuation and checkpoints#

See Initialize, continue and save simulations for capture, native handoff, graph detachment, and portable checkpoint examples.

class Continuation(state, parameters, constants, callback_state=None)[source]#

In-memory simulation state, effective sources and callback carry.

state#

Explicit simulation state, including clocks, solver/delivery histories and RNG carry.

Type:

tensor tree

parameters, constants

Effective sources used by the producing execution, including per-call overrides and initialization replacements.

Type:

mapping

callback_state#

Observation carry. Fresh initialization leaves it None; the first run starts callbacks.

Type:

FunctionalCallbackState or None

Notes

Pass to run() with a runner, lowered plan/kernel or matching raw binding. Bindings retain source ownership; continuing through one requires the same parameter/constant Tensor objects. bind(packet) selects sources but does not implicitly adopt its state or callback carry.

Containers are snapshots, but Tensor identities, views and autograd history are preserved without cloning. Use detach_continuation() to truncate recurrent gradients and export_continuation() for detached portable storage. initialize(target, packet) starts a fresh trial from its sources and RNG with callback carry reset; a Population plan also requires a recipe. Inputs, draw tapes and runtime extra remain per-call arguments.

capture_continuation(functional, native_model=None, *, callbacks=None, callback_state=None)[source]#

Capture an initialized native model’s current boundary as owned tensors.

Parameters:
  • functional (FunctionalPopulation, FunctionalNetwork or compiled runner) – Receiving plan/runner defining the compatible model schema.

  • native_model (Population or Network, optional) – Compatible initialized source; omission uses the plan’s native model.

  • callbacks (FunctionalCallbacks, optional) – Explicit plan’s prepared callback collection. Runners use their configured collection and require this argument omitted.

  • callback_state (FunctionalCallbackState, optional) – Carry from that collection, retaining reductions and recording phase.

Returns:

Detached owned sources/state with aliases and source trainability retained. Omitted callback carry starts fresh observations at the captured boundary.

Return type:

Continuation

Notes

No initialization, timestep or random sampling runs. Current native materializations are represented in the snapshot; the native model and runner defaults are unchanged. Captured leaves own subsequent gradients, cutting the native prefix graph. Recording payloads are not captured.

Callback recurrent history is detached. Bound LFP fields are refreshed with the caller’s gradient mode so suffix field gradients remain available. External nonleaf expressions remain caller-owned. Call outside compilation, function transforms and forward AD.

detach_continuation(functional, continuation, *, callbacks=None)[source]#

Cut recurrent autograd history while retaining live source ownership.

Parameters:
  • functional (FunctionalPopulation, FunctionalNetwork or compiled runner) – Plan/runner defining simulation and callback roles.

  • continuation (Continuation) – Packet whose simulation state and recurrent callback carry are detached.

  • callbacks (FunctionalCallbacks, optional) – Explicit plan’s prepared collection when callback carry is present. Runners select their configured callbacks and require this omitted.

Returns:

Detached recurrent state with unchanged parameters/constants, aliases, trainability, RNG, clocks, accumulated reductions and recording phase.

Return type:

Continuation

Notes

Detachment shares storage like Tensor.detach; it is not an owned snapshot. Use export_continuation() for portable owned storage. Source graphs and previous outputs remain caller-owned. Rebuild externally computed nonleaf source/field expressions when their upstream graph has been consumed.

Built-in LFP observation fields are refreshed under the caller’s gradient mode, preserving fresh suffix gradients. Other custom callback carry is recurrent. This operation does not initialize callbacks, sample, execute or write storage. Call outside compilation, function transforms and forward AD.

commit_continuation_(functional, target, continuation)[source]#

Publish detached effective sources and runtime state to a native model.

Parameters:
Returns:

The updated target. Existing native Parameter objects, trainability, gradients and source aliases are retained. Subsequent gradients belong to the receiving native sources, not the detached incoming prefix.

Return type:

Population or Network

Notes

Compatibility and equivalent source materialization are checked before publication. Unsupported layouts/configuration/overrides reject without changing the target. No fresh initialization or random sampling runs. State-only plan commit_state_ methods remain available when sources are already aligned and graph-preserving state transfer is required.

Callback carry is separate: reuse a compatible prepared collection/carry or transfer it with callback export/restore. Inputs, draw tapes and call-local extra remain execution arguments. Call outside compilation, function transforms and forward AD.

export_continuation(functional, continuation, *, callbacks=None)[source]#

Export detached owned data for a portable functional checkpoint.

Parameters:
  • functional (FunctionalPopulation, FunctionalNetwork or compiled runner) – Plan/runner that validates the packet’s sources, state and callbacks.

  • continuation (Continuation) – Execution boundary to save.

  • callbacks (FunctionalCallbacks, optional) – Explicit plan’s collection when carry is present. Runners use their own configured callbacks and require this argument omitted.

Returns:

Plain data/Tensor packet for torch.save and torch.load(..., weights_only=True). Source identity aliases and trainability are retained as owned detached leaves.

Return type:

dict

Notes

The checkpoint excludes optimizer state, upstream graphs, recording payloads, input tapes and draw tapes. Distinct Tensor views become independent snapshots. Active callback configuration must match when restored; a packet exported before execution starts callbacks on its first run. Call outside compilation, function transforms and forward AD.

restore_continuation(functional, packet, *, callbacks=None)[source]#

Restore a portable checkpoint into a compatible plan or runner.

Parameters:
Returns:

Independent detached Tensor leaves retaining saved identity aliases and trainability. Use its restored leaves for a new optimizer or raw binding.

Return type:

Continuation

Notes

Restore validates configuration, tensor schemas and callback compatibility. It does not read current native values, initialize, prepare, sample or execute. Saved materialized sources remain independent effective values; prior upstream dependencies are not reconstructed. Call outside compilation, function transforms and forward AD.

Parameter inspection#

See Train models and select parameters for source selection and optimizer groups.

inspect_sources(subject)[source]#

Inspect live parameter/constant sources and their identity aliases.

Parameters:

subject (native model, compiled runner, raw binding, tensor bundle or Continuation) – Populations and Networks expose registered raw parameters and known configuration sources, including owned waveform sources. Runner inspection reads defaults; inspect a returned Continuation for one call’s effective overrides. Raw bindings and tensor bundles expose their stored frames. Prepared-only Population bindings are currently unsupported.

Returns:

Captured metadata with live Tensor references. Paths begin with parameters. or constants.; all identity aliases are retained and trainable_leaves deduplicates gradient-requiring leaves for optimizers.

Return type:

SourceReport

Notes

Inspection performs no Tensor arithmetic, cloning, graph traversal, lowering, preparation or sampling. Native declarations become visible after the normal build lifecycle registers them. Runtime state, sampled histories, derived workspaces, callback carry and call-local input packets are not inventoried. Inspection does not validate execution or prove that a source affects output. Reinspect after changing bindings/gradient flags. Reports retain source graph references until discarded. Call outside torch.compile.

class SourceReport(entries, trainable_leaves)[source]#

An immutable source inventory with live references and captured metadata.

entries preserves every Tensor path, visiting parameters before constants in mapping/tuple order. trainable_leaves contains each Tensor identity once, at its first path, when both captured flags are true. This tuple can be supplied explicitly to a PyTorch optimizer. Flagged nonleaf values remain visible in entries but are omitted from this leaf view. select(...) returns a filtered report while retaining full identity alias groups and the captured optimizer-leaf membership.

Reinspect after replacing bindings or changing flags. A report does not prove that a Tensor influences an output or recover external upstream optimizer leaves. State, callback carry, explicit initialization-input packets and call-local stimulation sources are outside this inventory.

Printing the report shows counts and a compact parameter/constant path tree with shapes, dtypes, devices, flags and aliases, without Tensor values. Large displays prioritize gradient-bearing paths and indicate omissions; entries always retains the complete inventory.

select(queries)[source]#

Filter paths while retaining complete identity-alias groups.

Parameters:

queries (selector or iterable of selectors) – Exact/unique partial path, glob (optionally glob:), or re:/compiled regex. Paths include their parameters./constants. prefix. Each selector must match; an empty iterable returns an empty report.

Returns:

Entries in original report order, including every alias of any selected Tensor. Captured flags and deduplicated optimizer-leaf membership are reused.

Return type:

SourceReport

Notes

Selection does not change trainability or reread Tensor flags. Reinspect after changing sources. Optimizer groups built from separate selections must be disjoint by Tensor identity; overlapping selections can contain the same leaf. Call outside torch.compile.

class SourceEntry(path, domain, tensor, requires_grad, is_leaf)[source]#

One named parameter or constant Tensor in an inspected source frame.

tensor is the original live object; inspection never copies or detaches it. requires_grad and is_leaf capture its flags at inspection time. aliases lists the other paths referring to that exact object, including ties between parameters and constants. Distinct Tensor views are distinct sources even when their underlying storage is shared.

property aliases: tuple[str, ...]#

Other identity-alias paths, in their original encounter order.

Callbacks and recording#

Native callback configurations such as dn.Recorder can be prepared for functional execution. Custom callbacks implement FunctionalCallback. See Recording and online analysis for cadence, Network scopes, results, storage, and continuation.

make_callbacks(target, callbacks, *, dt=None)[source]#

Prepare named observations for a native model or functional plan.

Parameters:
  • target (Population, Network, FunctionalPopulation or FunctionalNetwork) – Initialized native model or existing lowered plan. Native targets are lowered once to bind selections; preparation does not initialize, advance or resample the source.

  • callbacks (mapping of str to callback configurations) – Supported built-in callbacks or pure FunctionalCallback objects. Recorder HDF5 settings and Network PopulationCallback scopes are supported.

  • dt (float, optional) – Required for a native Population. A native Network uses its initialized timestep; any explicit Network/functional timestep must match the plan.

Returns:

Bound collection with explicit result/carry state. Reuse with compatible native receivers, or its exact owning functional plan.

Return type:

FunctionalCallbacks

Notes

Carry belongs to this collection. Use export_state/restore_state to transfer it between equivalent independently prepared collections. Slice selections refer to the original source during preparation; native reuse applies their resolved indices to the receiver. LFP fields retain their bound sources.

This host operation runs outside compilation, function transforms and forward AD. Native preparation has functional lowering’s supported-model restrictions. Storage opens during host execution, not preparation. Runners, bindings and tensor bundles are not preparation targets; use their owning functional plan.

class FunctionalCallback[source]#

Pure observation/reduction protocol shared by native and functional execution.

Callback objects hold static configuration. Every evolving value must be returned in carry. Carry and per-step emissions are Tensor PyTrees with stable structure, leaf shapes, dtype and device. A constant-memory reducer can emit None. Final results are Tensor PyTrees; a recording’s leading sample length can vary with the execution horizon and sampling selection.

initialize(state, None) runs once for fresh callback state and returns (carry, initial_emission_or_none). update(carry, state, auxiliary) runs after every accepted model step and returns the next pair. Per-step emissions are stacked on a leading time axis before finalize(carry, emissions) runs for each public execution result. Continued calls reuse carry without another initial sample. Finalize must handle None when a segment has no emissions or known initial emission layout, returning a correctly shaped empty result if appropriate.

Implement tensor-only, deterministic, side-effect-free methods: do not mutate the callback, perform I/O, consume hidden randomness or branch in Python on Tensor values. This makes the same callback usable with gradients, compiled scan, inference-only while and checkpoint replay. Sparse per-step observations use fixed tensors/masks rather than changing emission structure.

abstractmethod initialize(state, auxiliary)[source]#

Return (carry, initial_emission_or_none) for a fresh run.

abstractmethod update(carry, state, auxiliary)[source]#

Return (next_carry, emission_or_none) after one model step.

abstractmethod finalize(carry, emissions)[source]#

Return the public tensor result for this execution segment.

checkpoint_configuration()[source]#

Describe static compatibility for portable callback checkpoints.

Return a plain dict with kind (a nonempty stable string), version (a positive integer), and fields (a string-keyed dict). Fields may contain plain scalars, acyclic dict/list/tuple containers and ordinary Tensor/Parameter values. Include every static setting affecting carry, emissions or results. Change the version when their interpretation changes.

The receiving application constructs a compatible callback; checkpoint data does not instantiate or import implementations. This deterministic, side-effect-free hook runs only during host export/restore. If a custom binding hook returns a prepared callback, implement this declaration on that returned object. It is optional for execution/in-memory continuation; custom portable export requires it. The default handles built-in callback configurations.

class FunctionalCallbacks(functional, callbacks)[source]#

Prepared named observations with explicit callback state.

Create with dendra.func.make_callbacks() for a native model or functional plan, or with a plan’s make_callbacks method. The collection binds callback configuration, scopes and state selections; execution stores evolving values in returned FunctionalCallbackState, not in callback objects.

Reuse a collection and its state to preserve recording cadence and reductions. Portable export_state/restore_state transfers carry between equivalent independently prepared collections. Recording payloads themselves are not part of callback-state checkpoints.

detach_state(state)[source]#

Truncate callback history while retaining its values and sampling phase.

Recurrent carry tensors detach with shared storage, preserving tensor aliases, views, callback identity, emission metadata, sampling phase and accumulated values. Built-in LFP fields are rematerialized from current bound sources with the caller’s gradient mode; keep gradients enabled when training those fields in the next segment.

Model state, parameters, constants and previous results are untouched. Detach model history separately for native or explicit-state execution; use dn.func.detach_continuation for a complete functional packet. Custom callback carry is recurrent. Externally computed nonleaf field sources remain caller-owned when their upstream graphs are consumed.

The state must belong to this collection. No model validation, initialization, sampling, numerical execution, checkpoint configuration hooks or storage I/O runs. This host operation runs outside compilation, function transforms and forward AD. Resume through callback_state=.

export_state(state)[source]#

Export owned detached carry for equivalent reconstructed callbacks.

The versioned plain data/Tensor packet can be saved with torch.save and loaded with torch.load(..., weights_only=True). It contains callback carry and emission metadata, without recording history. Built-in callbacks, Population scopes and custom bound callbacks with checkpoint_configuration() support portable restoration. Export runs outside compilation, function transforms and forward AD.

restore_state(packet)[source]#

Restore a checkpoint into this compatible callback collection.

Configuration, tensor structure, dtype and device must match. The returned carry owns detached ordinary tensors and uses this collection’s identity; pass it through the existing callback_state= argument. Restoring does not initialize callbacks or mutate this collection.

class FunctionalCallbackState[source]#

Plan-tagged explicit carry for one functional callback collection.

This is an output/carry type, not a user-construction API. Pass the state returned by Dendra so its static plan identity remains attached to the dynamic tensor PyTrees under torch.func and compilation.

property plan_token: object#

Collection identity used to validate live callback continuation.

property emission_schemas#

Recorded emission layouts used to validate continued callback results.

class FunctionalCallbackResults(state, outputs)[source]#

Finalized named callback outputs and carry for one execution segment.

Functional execution returns this mapping at auxiliary["callbacks"]. Native pure-callback execution returns it directly. results[name] reads that callback’s finalized output; results.state is the carry for the next call’s callback_state=. Recording outputs contain this segment’s samples; the carry retains cumulative reductions and sampling phase.

class PopulationCallback(population, callback)[source]#

Apply one callback configuration to a named Population in a Network.

Parameters:
  • population (str) – Exact top-level Population name. A concatenated MultiPopulation is one owner; a scoped Recorder can select its named Slice regions.

  • callback (FunctionalCallback or supported built-in configuration) – Observation configured against that Population. Recorder state names are local, for example v or hh.m. The outer callback mapping’s key names the returned result stream.

Notes

Local result shape, gradients, cadence and carry follow the ordinary Population callback contract. Scopes cannot be nested. dn.callbacks.PopulationCallback is the shared configuration accepted by native and functional Networks; this functional class is also supported.

class Recorder(states, max_only=False, node_indices=None, dt=None, partition=None, *, region=None)[source]#

Record selected state tensors at an optional sampling cadence.

Parameters:
  • states (sequence of str) – Population-local state names such as v or hh.m. A Network Recorder uses qualified names such as left.v; a PopulationCallback scope uses local names.

  • max_only (bool, default False) – Record the maximum over the final compartment/support axis.

  • node_indices (sequence of int, optional) – Select entries on that final axis when max_only is False.

  • partition (sequence of int, optional) – With max_only, reduce contiguous final-axis groups separately. Positive lengths must cover that axis completely.

  • dt (float, optional) – Positive recording interval in ms, spanning at least one solver step. Omission records the initial boundary and every accepted post-step state. An interval uses stride int(dt / simulation_dt); the initial sample is retained and continuation preserves the stride phase without another initial sample.

  • region (Slice, optional) – Physical selection belonging to the source Population, including named regions of a concatenated MultiPopulation. Regions select voltage, extracellular voltage and membrane current; mechanism-local state region selection is currently unsupported. Mutually exclusive with node_indices, max_only and partition.

Notes

Other selection arguments follow dendra.models.callbacks.Recorder. In-memory recordings retain gradients. For HDF5 output, configure dn.Recorder(...).set_hdf5(...) and pass that shared configuration. Host execution writes detached samples and retains callback carry; direct tensor kernels do not support HDF5 storage. Bind with make_callbacks() or supply the configuration to compile().

class LFP(v_unit, rule=None)[source]#

Record extracellular potentials from reciprocal lead fields.

Parameters:
  • v_unit (sequence of Tensor) – Non-empty, equally shaped lead fields, one per contact. Fields in mV/mA (numerically ohms) project absolute membrane current in mA to mV. Conversion to the model dtype/device preserves field gradients.

  • rule (str, optional) – Explicit torch.einsum reduction. Without a rule, fields broadcast to Population voltage shape and cell/compartment axes are summed, preserving explicit batch axes.

Notes

Construct the source model under dn.ctx(IMEM=1) to enable membrane current. Default results have shape (samples, *batch, contacts) and include the initial boundary. Native and functional projection conventions match. Continuation retains callback phase; detach_continuation() preserves fresh suffix gradients to bound fields. Only electrode projections are recorded, although autograd can retain current intermediates for backward.

class APCount(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=(5, -5), dt=None)[source]#

Count post-step threshold crossings without retaining a trajectory.

The int32 result has shape (*batch, N, K) for K checked compartments. threshold, t_start_check, t_end_check, node_check and dt use the same meanings as Raster. Crossing state, cumulative counts and window phase continue through returned callback carry. Hard counts are nondifferentiable; recording them does not detach model state or other outputs.

class Raster(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=(5, -5), dt=None)[source]#

Record post-step threshold crossings inside a time window.

The Boolean result has shape (samples, *batch, N, K) for K selected compartments. Only accepted samples inside the checked window are returned; the initial model state is not sampled. Constructor arguments follow dendra.models.callbacks.Raster: threshold is a voltage threshold, t_start_check/t_end_check bound the window in ms, node_check selects compartments and dt sets the solver timing used for that window. Continuation preserves crossing and window phase.

class Active(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=(5, -5), dt=None, inv=False, *, partition=None)[source]#

Detect whether any checked compartment crosses threshold at least once.

class ActiveAL(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=(5, -5), dt=None, at_least=1, inv=False, *, partition=None)[source]#

Detect activity at at least at_least distinct checked slots.

A slot qualifies after any upward threshold crossing. Repeated crossings at one slot do not satisfy a multi-slot target; use ActiveALCount for a total-spike target. The finalized Boolean result preserves all batch/population axes and removes only the checked-slot axis.

partition optionally groups contiguous checked slots and appends a group axis to the result. Unlike imperative is_active(partition), it is fixed when callbacks are bound, so execution remains pure and compiled. inv complements the final result. Hard activity is nondifferentiable; adding this callback does not detach model state or Recorder outputs. at_least must be a positive integer, using the same validation as native activity callbacks.

class ActiveALCount(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=(5, -5), dt=None, at_least=1, inv=False, *, partition=None)[source]#

Detect at least at_least total crossings across checked slots.

Repeated spikes at one checked slot contribute separately. Configuration, window phase, inversion, partitioning, and explicit continuation follow ActiveAL. The returned tensor is Boolean, not a spike count.

class AnomalyDetector[source]#

Return a cumulative mask of non-finite post-step voltages.

This mirrors the ordinary callback’s public result semantics while keeping only a Boolean mask in carry; it emits no trajectory and therefore uses constant callback memory.

Construct with dn.func.AnomalyDetector().

Diagnostics#

class ExecutionCapabilities(execution, inference, compiled_reverse_mode, compiled_higher_order_reverse_mode, functional_transforms, forward_mode, structured_inference, structured_training)[source]#

Execution choices offered by one compiled functional kernel.

These are Dendra’s dispatch contracts, subject to the selected model and PyTorch backend supporting their tensor operations. They do not guarantee native code generation, speed, memory use, or successful compilation. compiled_higher_order_reverse_mode describes differentiating an already compiled kernel: transform fallback does not intercept create_graph=True.

class ExecutionReport(requested_execution, strategy, steps, callbacks, grad_enabled, backend, reason=None)[source]#

The most recent successfully completed kernel dispatch.

Tail and callback specializations share this report with their original kernel. Checkpoint replay can update it during backward. A failed call leaves the previous report unchanged, and an empty run makes no dispatch. This is not a summary of a whole host run or a performance measurement.

A compiled_* strategy means Dendra called its torch.compile boundary; it does not promise native code generation by backend. The while-loop strategy additionally means the captured inference loop was selected and the timestep count includes at least one loop iteration. Reports contain only scalar metadata and never retain live tensors or autograd graphs.

exception FunctionalizationError[source]#

Raised when functional execution cannot preserve its declared contract.