Model parameterization#
Dendra lets you optimize model parameters while still exposing clean, simulation-ready values at the model surface. In practice, that means you can work with attributes such as model.celsius, model.cm, or model.rhoa as the values the model will actually use during initialize() and simulation, while Dendra handles the bookkeeping needed for trainable sources, positivity constraints, and region-specific overrides.
This page focuses on the user-facing mental model:
when to use
GLOBAL,BATCH,RANGE, andPARAMETERhow to think about exposed values such as
model.rhoawhy
initialize()is the moment when those values are refreshedhow to automate relationships with parametrizations, pure initialization APIs, and imperative hooks
Parameter types at a glance#
Declaration |
User-facing meaning |
Effective shape |
Typical use |
|---|---|---|---|
|
One value shared across the whole model |
Scalar-like tensor |
Temperature, a global scale factor, a shared offset |
|
One value per population cell and explicit batch index, shared over compartments |
|
Cell-specific conductances or parameters varied across independent replicas |
|
One value per compartment (and per axon in a population) |
|
Axial resistivity, capacitance, compartment-wise conductance |
|
A generic learnable object used by your own logic |
Whatever you provide |
Helper coefficients, custom transforms, grouped coefficients |
|
Same as above, but constrained to be positive / negative |
Same as the corresponding non-positive form |
Positive-only or negative-only physical quantities (e.g., |
Three practical rules matter most:
Use
GLOBALwhen the model should consume a single shared value.Use
BATCHfor one value per population cell and explicit batch index, shared over compartments.Use
RANGEwhen the model should consume a full compartment-wise tensor.
A RANGE parameter does not force every compartment to be different. It simply means the model can hold a different value at every compartment. A scalar default such as RANGE(rhoa=35.4) is still valid; Dendra materializes it as a full tensor over compartments.
The key mental model#
For everyday use, it is helpful to think in terms of effective values:
model.celsiusis the temperature thatinitialize()and the mechanisms see.model.rhoais the compartment-wise axial resistivity tensor that the model actually uses.model.cmis the compartment-wise capacitance tensor that the model actually uses.
That is why user code usually reads naturally:
model.celsius
model.rhoa
model.cm
The important distinction is that GLOBAL and RANGE expose simulation-ready values, while Dendra keeps the underlying trainable sources and bookkeeping behind the scenes. This is what makes it possible to:
refresh values during
initialize()impose positivity / negativity constraints with
GLOBALP/BATCHP/RANGEP, etc.define region-specific overrides for a
RANGEvariableregister derived relationships without manually editing leaf tensors
Note For
PARAMETERP(...), the attribute itself is a positive parameter object, so useself.evaluate('name')when you need the numeric value. ForGLOBALP(...)andRANGEP(...), the model attribute is already the usable positive value, soself.namegives you the numeric value directly.
RANGE means “per compartment”#
This is the most important user-facing point to internalize:
A
GLOBALparameter gives the model one shared value.A
RANGEparameter gives the model one value for every compartment.
That compartment-wise tensor can be used in several styles:
Uniform: every compartment gets the same value.
Region-wise: several compartments share a value because they belong to the same region.
Fully compartment-specific: every compartment can take a different value.
The figure below shows region-wise sharing (above) and a fully compartment-specific range tensor (below).
from range_viz import render, render2; render()
Real examples in Dendra models#
In the core axon models, you will see declarations such as:
P.RANGE(cm=1.0, rhoa=35.4)
P.GLOBAL(celsius=37.0)
That gives the following user-facing behavior:
model.celsius # one shared value
model.cm # one value per compartment
model.rhoa # one value per compartment
model.rhoa.shape # matches the model's compartment shape
So even though rhoa might start from a scalar default like 35.4, the model-facing value is still a full compartment-wise tensor.
Region-specific parameterization of a RANGE variable#
A very common pattern is to start from one baseline RANGE value and then override selected compartments with additional learned sources.
For example, suppose you want one baseline rhoa everywhere, but different values for nodes, internodes, and terminals:
# Example sketch: keys identify subsets of compartments
node_key = ...
internode_key = ...
terminal_key = ...
# Baseline RANGE source already exists because rhoa was declared with RANGE(...)
# Add three more region-specific sources
model.parametrize("rhoa", 70.0, key=node_key) # creates rhoa_param_0
model.parametrize("rhoa", 40.0, key=internode_key) # creates rhoa_param_1
model.parametrize("rhoa", 55.0, key=terminal_key) # creates rhoa_param_2
# equivalently, parameterize via Slice objects
model[node_key].parametrize("rhoa", 70.0)
model[internode_key].parametrize("rhoa", 40.0)
model[terminal_key].parametrize("rhoa", 55.0)
# parameters associated with mechanisms can be set during insertion
model[node_key].insert(hh, gnabar=0.5)
model[internode_key].insert(hh, gnabar=0.01)
model[terminal_key].insert(hh, gnabar=0.0)
# or after building, since the parameterization system is flexible and dynamic
# note that in this case, the 'hh' mechanism must already be present at the node_key compartments, e.g., by calling model.insert(hh) before
model.insert(hh) # ensure hh is present everywhere
model.build()
model[node_key].mech.hh.parametrize("gnabar", 0.5)
# it is also possible to use a torch.nn.Parameter or equivalent (e.g., Dendra's own PositiveParam), if you want e.g., different regions to be governed by the same underlying parameter object
gnabar_param = torch.nn.Parameter(torch.tensor(0.5))
model[node_key].mech.hh.parametrize("gnabar", gnabar_param)
model[internode_key].mech.hh.parametrize("gnabar", gnabar_param)
# After all parameterizations are in place, call initialize() to materialize the final compartment-wise tensor seen by the model
model.initialize()
After initialize(), model.rhoa contains the final compartment tensor seen by the model.
Two useful details:
If you call
parametrize(...)without an alias, Dendra creates names such asrhoa_param_0,rhoa_param_1, and so on.If you pass
alias="node",alias="internode", etc., the added sources become easier to inspect by name.
This is the key reason RANGE is so flexible: the model consumes a compartment-wise tensor, but you are free to parameterize that tensor with one source, a few region-wise sources, or a fully compartment-specific construction.
What initialize() does in practice#
From a user’s point of view, initialize() is the moment when Dendra refreshes the effective parameter values that the model will actually consume.
A good working summary is:
build the model graph if needed
refresh population-level
GLOBAL,BATCH, andRANGEvalues from their sources, including region-specific overrides and registered parametrizationsreset voltage and run registered pre-initialize transforms/hooks
initialize mechanisms and their State bundles, including their effective parameters, derived workspaces, and initial carry
run registered post-initialize transforms/hooks
That is why, after changing a parameterization, the usual next step is to call:
model.initialize()
The two diagrams below show the flow for one GLOBAL variable and one RANGE variable.
Call graph: initialize() for a GLOBAL variable (celsius)#
Here the important point is that one hidden source gives rise to one shared effective value, and that effective value is what the mechanism initialization reads.
from IPython.display import Image, display
display(Image(filename='global_param.png'))
Call graph: initialize() for a RANGE variable (rhoa) with region-specific sources#
This example shows a baseline rhoa source plus three extra sources that control different subsets of compartments. The model still consumes a single final tensor, model.rhoa, but that tensor can be assembled from multiple underlying learned values.
display(Image(filename='range_param.png'))
render2()
Automating relationships without manual tensor surgery#
Dendra provides several automation patterns, each with a distinct contract.
1. Parametrizations for differentiable relationships#
Use a parametrization when one model quantity should be computed from another quantity or from learned coefficients.
Examples from the built-in models include:
deriving node diameter from fiber diameter
scaling
rhoafrom geometric quantities in the myelinated model
This keeps the transformation attached to the model logic rather than forcing you to edit a learnable tensor in place.
2. In-graph parametrizations for exposed GLOBAL / RANGE values#
When you want the exposed value (for example model.rhoa) to be transformed automatically during buffer refresh, register a parametrization on that value instead of editing the underlying learnable source manually.
This is especially helpful when the model should consume a derived tensor, but you still want the trainable sources to stay clean and stable.
3. Pure initialization APIs#
Use the declared pure APIs when setup should remain differentiable and composable with dn.func:
derive_buffers()constructs initialization-staticDERIVED_BUFFERworkspaces from populated parameters, temperature, and local geometry.initial_values(v, values)returns initial Mechanism/StateSTATEandCARRYvalues without mutating the module.registered pre/post initialization transforms make Population-level tensor remapping explicit through declared inputs and outputs.
Initial voltage has the dedicated set_v_init(...) configuration method.
# Example pattern
model.set_v_init(-80.0)
model.initialize()
See the model-initialization and mechanism-authoring guides for these contracts.
4. Imperative pre/post initialize hooks#
Arbitrary hooks are an escape hatch for setup, diagnostics, or integration with external Python code. They run with ordinary Population.initialize(), but imperative hooks are not lowered by dn.func.make_functional.
For example, a post-initialize hook can report completed state:
def report_setup(model):
print("initialized rhoa shape:", tuple(model.rhoa.shape))
model.register_post_initialize_hook(report_setup)
model.initialize()
Which one should you choose?#
Use a parametrization when the relationship should be part of the model’s learnable transformation pipeline.
Use a pure initialization API when initialized tensors must compose with functional transforms, autograd, or compilation.
Use an imperative hook for side effects or setup that intentionally stays outside the functional contract.
In every case, avoid manually rewriting the leaf trainable tensors that Dendra is optimizing.
Random parameters and runtime noise#
Dendra has two related stochastic declaration families.
Quenched random parameters: GLOBALRAND, BATCHRAND, RANGERAND#
Use RAND declarations for heterogeneity that is sampled during initialization and then held fixed during the simulation:
from dendra.models.mechanisms import Mechanism
class NoisyLeak(Mechanism):
Mechanism.RANGERAND(
"g_scale",
distribution="truncated_normal",
mu=1.0,
sigma=0.10,
low=0.5,
high=1.5,
)
This creates a sampled buffer named g_scale plus ordinary Dendra distribution-parameter buffers:
g_scale_mu
g_scale_sigma
g_scale_low
g_scale_high
The distribution parameters can be overridden locally at insertion time just like normal RANGE parameters:
cell.soma.insert(NoisyLeak, alias="soma", g_scale_sigma=0.02)
cell.dend.insert(NoisyLeak, alias="dend", g_scale_sigma=0.15)
By default, RAND samples are re-generated on each top-level initialize() call. reseed_on_initialize=False (the default) advances the persistent RNG stream. reseed_on_initialize=True resets it to its current configured or checkpointed seed before drawing; that seed can differ from the declaration’s original seed after reseeding or loading a checkpoint. A shared rng_name stream resets at most once per initialization generation.
resample_on_initialize=False retains the saved sample without drawing or resetting its stream, regardless of reseed_on_initialize. Both options belong on the RAND declaration. You can explicitly resample with:
cell.resample_random_parameters("g_scale")
Explicit resampling advances the current stream without applying the initialization reset policy.
RAND samples use the reparameterized path by default for continuous distributions, so gradients can flow to distribution parameters such as g_scale_mu and g_scale_sigma when the rest of the computation graph supports it.
For compiled Population and Network execution, see Stimulation, input tapes and randomness for explicit draws, RNG continuation, and the pure custom-distribution contract.
Runtime noise: GLOBALNOISE, BATCHNOISE, RANGENOISE#
Use NOISE declarations for exogenous stochastic drives that are resampled during simulation before mechanism state advancement:
from dendra.models.mechanisms import Mechanism
class NoisyCurrent(Mechanism):
Mechanism.NONSPECIFIC_CURRENT("i")
Mechanism.RANGENOISE(
"eta",
distribution="normal",
mu=0.0,
sigma=1.0,
)
Mechanism.RANGE(sigma_i=0.01)
def i(self, v):
return self.sigma_i * self.eta
Runtime NOISE values are detached from distribution parameters, base draws and timestep scaling. Ordinary coefficients such as sigma_i still receive gradients through calculations using the detached noise. For stochastic State dynamics with gradients through drift and diffusion coefficients, use State.METHOD("euler_maruyama") for Itô SDEs or State.METHOD("euler_heun") for Stratonovich SDEs; see mechanisms and materials.
You can manually refresh runtime noise outside the normal simulation loop with:
cell.resample_runtime_noise("eta")
Runtime-noise distribution parameters are still ordinary Dendra parameters, so local overrides work:
cell.apic.insert(NoisyCurrent, alias="apical", eta_sigma=0.5)
cell.soma.insert(NoisyCurrent, alias="soma", eta_sigma=0.1)
The supported cadence and phase are cadence="step" and phase="pre_state": noise is refreshed once per mechanism advance. Inputs and randomness describes explicit sampling and replay in native and functional execution.
Built-in and custom distributions#
Built-in distributions include:
normal(mu, sigma)
lognormal(mu, sigma)
uniform(low, high)
truncated_normal(mu, sigma, low, high)
You can register a custom distribution globally:
def constant_sampler(parameters, rng, shape, *, device, dtype):
return torch.empty(shape, device=device, dtype=dtype).fill_(parameters["value"])
dn.register_random_distribution(
"constant",
{"value": 1.0},
sampler=constant_sampler,
)
Takeaways#
GLOBALmeans one effective value shared across the model.BATCHmeans one effective value per population cell and explicit batch index, shared over compartments.RANGEmeans one effective value per compartment.A
RANGEparameter can be uniform, region-wise, or fully compartment-specific.model.rhoais best understood as the final compartment tensor the model uses, not just a raw leaf parameter.Re-running
initialize()refreshes those effective values after you change parameterization.Parametrizations and pure initialization APIs are the preferred way to express differentiable transformations while keeping the underlying trainable sources well behaved.
Arbitrary pre/post initialize hooks remain available for imperative side effects, but are not part of functional lowering.
RANDdeclarations represent initialization-time heterogeneity;NOISEdeclarations represent detached runtime stochastic drives.NOISEvariables are optimized for simulation and do not preserve gradients through their distribution parameters.State.METHOD("euler_maruyama")implements Itô State SDEs;State.METHOD("euler_heun")implements Stratonovich State SDEs.