Context and execution settings#
dn.ctx scopes defaults for model creation and execution. Functional plans
capture CHECK_PURITY when created. Set it to True to diagnose mutation,
implicit randomness, or hidden hook dependencies; it defaults to False.
These checks are diagnostic and cannot prove purity for every input. Tensor
schemas and explicit lifecycle requirements are validated in either mode.
- class ctx(**kwargs)[source]#
Context manager for temporarily setting Dendra ContextVar values.
These flags control compilation and runtime behaviors across Dendra:
BACKEND(str): torch.compile backend (e.g.,"inductor").FULLGRAPH(int/bool): request full-graph compilation.DYNAMIC(int/bool): enable dynamic shape compilation.JIT(int/bool): enable standalone population/integrator JIT and opt into aggressive network-side compilation where supported.JIT_NETWORK_SOLVES(int/bool): enable population/integrator JIT only for populations stepped by a Network. This replaces the legacyJIT_IN_NETWORKname.JIT_NETWORK_OPS(int/bool): enable network-side/event/synapse JIT where a component exposes a compile-safe kernel.COMPILE_MODE(str): torch.compile mode (e.g.,"default").COMPILE_OPTIONS(dict/str/None): optionaltorch.compileoptions dictionary forwarded to supported compiled kernels.DEBUG(int/bool): increase logging verbosity for mechanism/state compilation (symbolic transforms, conductance differentiation).CHECK_PURITY(bool/int): opt into diagnostic purity checking when lowering or compiling functional models. The default isFalse: Dendra trusts authored hooks to obey their pure API contracts.Trueinspects dependencies and probes disposable execution copies for hidden mutation and implicit randomness. Tensor schemas and binding contracts required for execution remain checked in both modes. Plans retain the policy selected when they are lowered.DEVICE(str/torch.device/None): default device for newly constructed Dendra modules and eligible PyTorch factory calls without an explicitdevice.DTYPE(str/torch.dtype/None): default floating dtype for newly constructed Dendra modules and, when supported as a default by the installed PyTorch release, PyTorch factories that infer a floating dtype.IMEM(int/bool): whether integrators compute/storei_membranein populations (required for LFP calculations).MEMBRANE_ASSEMBLY(str):"auto"(default) uses affine membrane coefficients when all currents support that contract;"off"forces ordinary current/conductance assembly;"validate"additionally checks affine coefficients against fixed-state voltage probes. Validation is diagnostic and deliberately adds work, not a proof of global affinity.PRESERVE_MECHANISM_POPULATION_AXIS(bool/int/None): construction-time policy for population-axis-preserving mechanism storage.True/1enables it,False/0disables it, andNoneor"default"defers to the model-family default. Existing models are not changed when this value changes; it is consumed only while a model is constructed.USETABLES(int/bool): toggle lookup tables declared viaTABLEon State/Mechanism.RUNTIME_CONTRACT_VALIDATION(str): runtime validation policy for protected model contracts."versioned"(default) performs cheap mutation-version checks, revalidates frozen values after a change, and rejects stale solver-workspace dependencies."strict"performs full frozen-value validation at every public execution boundary, while"initialize"skips repeated boundary scans. Mandatory checks remain at construction, initialization/workspace rebuild, state restore, and direct geometry access. The last mode is unsafe if protected geometry or solver-affecting inputs are mutated after initialization. Writes through.data, NumPy/DLPack aliases, or raw storage can bypass mutation-version tracking;"strict"can diagnose frozen-contract corruption, but such writes remain unsupported for mutable workspace inputs.NATIVE_EXTENSION_POLICY(str): policy for optional native accelerator extensions."fallback"(default) silently uses the correct portable implementation when a native extension cannot load or launch,"warn"emits a warning before falling back, and"require"raises instead of permitting a silent performance-path change. The policy is enforced only when a native accelerator path is eligible; CPU execution is unaffected.TF32is available but typically not toggled here.
Example
>>> with ctx(DEBUG=1, JIT=0): ... net.build(...) >>> with ctx(DEVICE="cpu", DTYPE=torch.float64): ... values = torch.zeros(5) >>> values.device, values.dtype (device(type='cpu'), torch.float64)
- Parameters:
**kwargs – Mapping from ContextVar key to temporary value. Restored on exit.
Notes
Explicit
device=anddtype=factory arguments override these defaults. PassingNoneor"default"selects Dendra’s ordinarycpu/float32construction default within that scope. Dendra’s context values and PyTorch’s default floating dtype are process-global, while PyTorch’s device scope is not isolated between asynchronous tasks; overlappingctxscopes in different threads or tasks are unsupported. PyTorch 2.8 cannot usebfloat16as its default dtype; on affected releases Dendra still uses the requested dtype, while implicit PyTorch factories retain their prior default and emit a warning. Integer-inferred,*_like, and storage-sharing factories retain their normal PyTorch dtype/device behavior.
Context values#
- DEVICE#
- DTYPE#
- CHECK_PURITY#
- NATIVE_EXTENSION_POLICY#
- MEMBRANE_ASSEMBLY#
- PRESERVE_MECHANISM_POPULATION_AXIS#
- RUNTIME_CONTRACT_VALIDATION#
- COMPILE_OPTIONS#
Reading and normalizing settings#
- current_device(default=None)[source]#
Return the active Dendra default device, or
defaultwhen unset.
- current_check_purity()[source]#
Return whether new functional plans enable optional purity diagnostics.
- current_native_extension_policy()[source]#
Return the active canonical optional-native-extension policy.
- normalize_native_extension_policy(value)[source]#
Return a canonical optional-native-extension policy.
- current_preserve_mechanism_population_axis()[source]#
Return the active construction-time mechanism layout policy.
- normalize_preserve_mechanism_population_axis(value)[source]#
Normalize the construction-time mechanism population-axis policy.
Trueand1enable population-axis-preserving mechanism storage;Falseand0disable it.None, an empty string, and"default"defer to the model-family default. String forms are limited to"0"and"1"so misspelled environment values fail loudly.
- current_runtime_contract_validation()[source]#
Return the active canonical runtime-contract validation mode.
- normalize_runtime_contract_validation(value)[source]#
Return a canonical runtime-contract validation mode.
Modes are case-insensitive and surrounding whitespace is ignored. The canonical values are
"versioned","strict", and"initialize".
- current_compile_options(default=None)[source]#
Return the active normalized
torch.compileoptions dictionary.
- normalize_compile_options(options=None)[source]#
Normalize a Dendra compile-options value for
torch.compile.- Parameters:
options (dict, Mapping, str, or None) – Optional backend-specific options to forward to
torch.compile.None, an empty string,"none","null","default", and"{}"all mean no options. Strings that are not sentinels must be a JSON object.- Returns:
A shallow
dictcopy suitable for passing asoptions=...totorch.compile.- Return type:
dict or None
Compilation controls#
- set_compile_options(options=None, **kwargs)[source]#
Set global
torch.compile(options=...)for Dendra JIT call sites.Examples
>>> set_compile_options({"triton.cudagraphs": True}) >>> set_compile_options(None) # clear options >>> set_compile_options(**{"trace.enabled": True})
- Parameters:
options (Mapping, JSON str, or None) – Options to normalize and store.
Nonewith no keyword arguments clears the global options.**kwargs – Convenience option entries merged into
options. Keyword entries override entries fromoptions.
- Returns:
The normalized options value that was stored.
- Return type:
dict or None
- set_jit_enabled(enable=True)[source]#
Enable or disable JIT compilation globally for Dendra models (Populations and Networks).
- Parameters:
enable (bool) – If True, enable JIT compilation. If False, disable it. Default is True.
- set_jit_network_solves_enabled(enable=True)[source]#
Enable or disable population/integrator kernel compilation for populations stepped by a Network.
This is the preferred spelling for the legacy
set_jit_in_network_enabled()helper.
- set_jit_network_ops_enabled(enable=True)[source]#
Enable or disable network-side/event/synapse compilation where supported.
This flag is intentionally separate from population solve compilation, because NetCon/NetStim/event delivery has much more Python-side state.
- set_jit_in_network_enabled(enable=True)[source]#
Deprecated alias for
set_jit_network_solves_enabled().
- nojit(fn=None, recursive=True, *, reason=None, wrapping=True)#
Decorator to disable TorchDynamo
If recursive=True, Dynamo is completely skipped on the decorated function frame as well as the recursively invoked functions.
If recursive=False, Dynamo skips frames associated with the function code, but still process recursively invoked frames.
If reason is provided, it will be printed when Dynamo attempts to trace the disabled function.
Timing#
- tic(message=None, log=True)[source]#
Start a wall-clock timer.
- Parameters:
message (str, optional) – Optional message to log when starting the timer.
log (bool, optional) – If True (default), log the message via the module logger.
- toc(message=None, log=True)[source]#
Stop the most recent timer and return elapsed seconds.
- Parameters:
message (str, optional) – Optional message to prefix the elapsed time.
log (bool, optional) – If True (default), log the elapsed time via the module logger.
- Returns:
Elapsed time in seconds.
- Return type:
float
Notes
Raises a log error if called without a matching
tic().