Python API
Most work with DendriNet goes through configuration files and the command-line programs (Command-line reference). This page documents the functions and classes for doing the same from Python: loading a configuration, building a model, adding components to the registries, running analyses and saving training state. The descriptions are taken from the docstrings in the source.
Configuration
- dendritic_modeling.config.load_config(path: str | None = None, overrides: Mapping[str, Any] | None = None) Config[source]
Load a configuration file, or return the validated defaults.
The file may
extendsa parent file (resolved relative to the file that names it). A sweep file is accepted as well; itsbase_configsection is loaded. Every section is checked against the keys the library reads: unknown keys raiseUnknownConfigKeyError, and keys retired from earlier library versions warn (seeRETIRED_KEYS). Each call parses the file again, so edits are always picked up.overridesmaps dotted paths ("training.main.common.epochs") to values. They are applied to the composed file before validation, so an override is checked exactly like a value written in the file.
- dendritic_modeling.config.config_from_mapping(data: Mapping[str, Any]) Config[source]
Build and validate a Config from an in-memory mapping.
The mapping has the layout of a config file (
experiment,data,model, …); it is checked exactly asload_config()checks a file.
- dendritic_modeling.config.load_analysis_config(path: str, *, distributed_mode: str = 'none') AnalysisConfig[source]
Load a standalone, typed
analysis:YAML profile.Checkpoint analyses often need to reuse an immutable training config while applying a newer measurement profile. Keeping the analysis profile in a separate YAML avoids copying or mutating the scientific training config. The input may either contain an
analysis:root or be the analysis mapping itself.
Building models
- dendritic_modeling.networks.architectures.factory.get_architecture(type: str, parameters: dict[str, Any] | DictConfig, input_dim: int | None = None, suffix_input_dim: int | None = None) Module[source]
Factory method for creating network architectures.
- Parameters:
type – Architecture type name
parameters – Either flat parameters dict or structured config
input_dim – Optional input dimension (needed for EINet from config)
suffix_input_dim – Optional suffix input dimension. Used by spatial dendritic cores (e.g.,
hierarchical_dendritic_tensor_map) to add an output projection when the EINet output dim doesn’t match the downstream decoder’s expected input.
- Returns:
Initialized network module
- dendritic_modeling.networks.architectures.biological_constraints.biological_violations(core: Module) list[str][source]
Return a description of every biological constraint
corebreaks.
- dendritic_modeling.analysis.utils.model_resources.topk_parameter_inventory(model: Module) dict[str, int][source]
Count trainable storage versus retained dense-candidate Top-K weights.
Works for conventional affine controls as well as dendritic models. Other parameter families are counted at their stored size; dynamic indexed or scheduled sparse policies require their own resource records. This is a parameter count, not a claim about executable bytes or runtime.
Extension registries
Each function adds a named component that configuration files can then select; Extension registries describes what each registry covers.
- dendritic_modeling.networks.architectures.registry.register_architecture(name: str, builder: Callable[[...], Module], *, aliases: tuple[str, ...] | list[str] = (), description: str = '', allow_override: bool = False) None[source]
Register an architecture builder.
Builders are called as
builder(parameters, input_dim=..., suffix_input_dim=...). Existing names are protected unlessallow_override=Trueis supplied.
- dendritic_modeling.networks.architectures.excitation_inhibition.synapse.factory.register_sparse_layer(name: str, layer_class: type[Module], *, allow_override: bool = False) None[source]
Register a sparse synapse implementation under a new type name.
Replacing an existing type (built-in or registered) requires
allow_override=True.
- dendritic_modeling.networks.activations.factory.register_activation_builder(act_type: str, builder: Callable[[...], Module], *, allow_override: bool = False) None[source]
Register an activation builder by normalized activation type.
- dendritic_modeling.datasets.registry.register_dataset(name: str, builder: Callable[[Any], tuple[Dataset, Dataset, Dataset]], *, aliases: tuple[str, ...] | list[str] = (), description: str = '', sequence: bool = False, required_strategy: str | None = None, processing: frozenset[str] | set[str] | tuple[str, ...] | None = None, allow_override: bool = False) None[source]
Register a dataset builder.
Builders receive the original task/data config object and must return
(train_ds, valid_ds, test_ds).
- dendritic_modeling.datasets.sequence.builders.registry.register_sequence_dataset_builder(name: str, builder: Callable[[str, str | None, dict[str, Any]], SequenceDatasetBuild], *, allow_override: bool = False) None[source]
Register a sequence dataset builder by exact dataset name.
- dendritic_modeling.training.factory.register_trainer_strategy(name: str, trainer_class: type[Trainer] | str, *, fixed_kwargs: dict[str, Any] | None = None, allow_override: bool = False) None[source]
Register a trainer strategy without editing
get_trainer.trainer_classis aTrainersubclass or a"module:Class"reference, which is imported when the strategy is first used (plugins register strategies this way, so that loading them stays light). Replacing an existing strategy (built-in or registered) requiresallow_override=True.
- dendritic_modeling.training.loss.functions.register_loss_function(name: str, builder: Callable[[], LossFunction], *, aliases: tuple[str, ...] | list[str] = (), allow_override: bool = False) None[source]
Register a loss-function builder.
Names are stored as written;
get_loss_functionfalls back to a case-insensitive match. Builders are zero-argument callables that return aLossFunction.
- dendritic_modeling.training.optimizers.factory.register_optimizer(name: str, builder: Callable[[Iterator[Parameter], OptimizerConfig], Optimizer], *, aliases: tuple[str, ...] | list[str] = (), allow_override: bool = False) None[source]
Register an optimizer builder.
Builders are called as
builder(model_parameters, config).
- dendritic_modeling.analysis.registry.register_analyzer(name: str, *, config_field: str, class_path: str, attribute_name: str, save_subdir: str, constructor_style: Literal['params', 'model_params', 'none'] = 'params', supports_training: bool = True, requires_training: bool = False, description: str = '', phase: Literal['pre_weight', 'post_reactivation', 'model_only'] | None = None, pass_training: bool = False, require_analyzer: bool = False, allow_override: bool = False) None[source]
Register an analyzer.
Without
phasethe analyzer is metadata only:AnalysisManagerbuilds it when its section is enabled but never runs it. Withphaseit runs there, receiving the test dataset (pre_weight,post_reactivation) or only the model (model_only).
Plugins
Installed plugins and the registries that only plugins use; Extending DendriNet describes them.
- dendritic_modeling.plugins.load_plugins() tuple[PluginRecord, ...][source]
Load every installed plugin once and return the loaded plugins.
Later calls return the same plugins without loading anything again, or raise
PluginLoadErroragain when a plugin failed to load.
- dendritic_modeling.plugins.activate_plugin(name: str, register: Callable[[], Any]) PluginRecord[source]
Register a plugin that is not installed as a distribution.
For notebooks and tests:
registerruns now and the plugin is recorded undernamelike an installed one. Activating the same name again raises, and a failed activation is kept like a failed installed plugin.
- dendritic_modeling.plugins.loaded_plugins() tuple[PluginRecord, ...][source]
The plugins loaded in this process, in loading order.
- class dendritic_modeling.plugins.PluginRecord(name: str, target: str, distribution: str | None = None, version: str | None = None, module_path: str | None = None)[source]
One loaded plugin, as recorded in a run’s provenance.
- exception dendritic_modeling.plugins.PluginLoadError[source]
An installed plugin could not be imported or failed to register.
- dendritic_modeling.config.extensions.register_config_section(path: str, builder: Callable[[Any], Any], *, allow_override: bool = False) None[source]
Register the builder of an extension section.
builderreceives the section’s mapping (possibly empty) and returns the typed section; it raises for invalid content. Replacing a registered builder requiresallow_override=True.
- dendritic_modeling.config.extensions.register_config_migration(name: str, migrate: Callable[[dict[str, Any]], list[str] | None], *, allow_override: bool = False) None[source]
Register a migration of historical configuration keys.
migrate(data)receives a configuration mapping (the layout of a config file, as plain dicts and lists) and rewrites, in place, keys that earlier versions of the plugin’s components read into their current form. It changes only keys it recognises, leaves current configurations unchanged, and returns one note per change, which the loader logs as a warning.
- dendritic_modeling.models.builders.register_model_builder(name: str, *, applies: Callable[[Any], bool], build: Callable[[Any], tuple[Module, Module, Module, Module]], allow_override: bool = False) None[source]
Register a builder of the encoder, core and decoder of some models.
- class dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.branch_dynamics.AdditiveRule(voltage: ~collections.abc.Callable[[...], ~typing.Any], options: ~collections.abc.Mapping[str, ~typing.Any] = <factory>, setup: ~collections.abc.Callable[[~typing.Any, dict[str, ~typing.Any]], None] | None = None)[source]
An additive integration rule that a plugin provides.
voltage(layer, *, excitation, inhibition, child_current, child_conductance, raw_voltage, inputs)returns the compartment voltage before reactivation. The currents are those of the built-in rules (raw_voltageisexcitation - inhibition + child_current);inputsmapsx,inhibitory_inputandbranch_inputto the layer’s inputs on the feedforward path, and is None where voltages are computed from stored currents (recurrent and analysis paths), where a rule that needs the inputs must raise.optionsholds the rule’s options and their defaults; a layer receives them asadditive_options.setup(layer, options), if given, runs once while the layer is constructed (after its leak parameter) to create the rule’s parameters and buffers and to check the layer.
- dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.branch_dynamics.register_additive_rule(name: str, rule: AdditiveRule, *, allow_override: bool = False) None[source]
Register an additive integration rule under
additive_mode: <name>.
- IndexedSparseLinear.effective_sparse_weight() Tensor[source]
Return the
[out_features, K]weights of the sparse projection.These are the transformed weights after the optional row normalization, the values
forward()multiplies the gathered inputs by (subclasses whose forward adds release noise or rounding apply those on top).
- IndexedSparseLinear.project_with_weights(x: Tensor, weight: Tensor) Tensor[source]
Project
xthrough this layer’s contacts with other weights.weighthas the shape[out_features, K]ofsparse_weight(); the result isout[..., i] = sum_j weight[i, j] * x[..., connection_indices[i, j]], computed with the layer’s projection backend. For exampleproject_with_weights(x.abs(), effective_sparse_weight().abs())sums the magnitudes of the synaptic drives. The layer’s state, including its resolved backend, is unchanged.
Analysis
- class dendritic_modeling.analysis.managers.analysis_manager.AnalysisManager(model: BaseModel, data: dict[str, Dataset], analysis_config: AnalysisConfig, save_root: str | None = None, device: str = 'cpu', evaluation_seed: int | None = None, probe_seed: int | None = None)[source]
Coordinates and orchestrates all analysis tools for dendritic modeling.
This class manages the initialization and execution of various analysis tools based on configuration settings, providing a unified interface for running comprehensive model analysis.
- run_analysis(filename: str = 'final', training: bool = False)[source]
Run all enabled analysis tools.
- Parameters:
filename – Base filename for saving analysis results
training – Whether this is being called during training (affects which analyses run)
- Returns:
The pass record also written to
analysis_status.jsoninsave_root: for every requested analyzer its status (completed,skipped,failedorempty), and whether the pass finished and completed every analysis.- Raises:
AnalysisIncompleteError – with
analysis.require_completion, when a requested analysis did not complete.
- dendritic_modeling.scripts.analysis.run_checkpoint_analysis.run_checkpoint_analysis(*, config_path: str | Path, checkpoint_path: str | Path, analysis_config_path: str | Path, output_dir: str | Path, filename: str = 'final', device: str | None = None, strict: bool = True) dict[str, Any][source]
Execute one reproducible, post-training checkpoint analysis.
Returns the run directory the analyzers wrote into, the files it holds and the provenance record (also saved as
checkpoint_analysis_provenance.json), which includes the completion status of every requested analyzer.
- class dendritic_modeling.analysis.utils.streaming_covariance.StreamingCovariance(n_features)[source]
Merge batch-centered moments; O(features**2) state, no retained observations.
- dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.branch_layer.capture_analysis_currents(layers)[source]
Capture the graph-connected forward currents of branch layers in a block.
layersis oneDendriticBranchLayeror an iterable of them. Inside the block each forward of these layers keeps its currents, voltage and output with their autograd graph, asset_analysis_currents()describes; read them withget_analysis_currents(). On exit, also after an error, every layer returns to its previous setting and the captured tensors are discarded. Yields the layers as a tuple.
- DendriticBranchLayer.set_analysis_currents(enabled: bool = True) None[source]
Enable or disable capture of the forward currents with their graph.
While enabled, each forward keeps the layer’s pre-gate feedforward, recurrent and upstream currents, its pre-gate voltage and its post-gate output (
pre_gate_excitation_current,pre_gate_inhibition_current,pre_gate_recurrent_excitation_current,pre_gate_recurrent_inhibition_current,pre_gate_upstream_current,pre_gate_voltage,post_gate_output) attached to the autograd graph, so analyses can differentiate a loss with respect to them. Unlikeset_branch_diagnostics(), nothing is detached. Missing pathways areNone. Capture that would bypass a fused shunting gate requirestorch.no_grad(): its backward need not match the explicit voltage path. For gradient analyses, construct an unfused model withreactivation.memory_efficient=False. Stateful steps, parallel/star forwards and current-substitution methods reject capture. Disabling discards the tensors.
- DendriticBranchLayer.get_analysis_currents() dict[source]
Return a shallow copy of the most recent graph-connected currents.
Besides the names listed in
set_analysis_currents(), the dictionary carries the older aliasesexcitation,inhibitionandbranch_input. It is empty before a forward with capture enabled.
- DendriticBranchLayer.clear_analysis_currents() None[source]
Discard the most recently captured analysis currents.
- class dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.compartment_perturbation.CompartmentPerturbation(offset: Tensor, coordinate: str = 'output')[source]
An additive offset for one branch layer’s compartments in one coordinate.
- dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.branch_layer.perturb_compartments(perturbations)[source]
Perturb branch-layer compartments in a block.
perturbationsmapsDendriticBranchLayermodules toCompartmentPerturbationvalues. Inside the block every forward of these layers adds its offset once, asset_compartment_perturbation()describes. On exit, also after an error, every layer returns to its previous perturbation (usually none). Yields the mapping.
- DendriticBranchLayer.set_compartment_perturbation(perturbation: CompartmentPerturbation | None) None[source]
Add
perturbation’s offset in every forward until it is cleared.The offset enters the layer’s own forward pass once, in the perturbation’s coordinate (
output,voltageor, for a shunting layer,current; seecompartment_perturbation). While a perturbation is set, a shunting layer forms its voltage explicitly instead of through the fused gate, with the same output for a zero offset.Noneclears it.
- DendriticBranchLayer.clear_compartment_perturbation() None[source]
Stop perturbing this layer’s forward.
- class dendritic_modeling.analysis.tools.node_perturbation_credit.NodePerturbationCreditAnalyzer(params: NodePerturbationCreditAnalysisParams)[source]
Estimate compartment credit by node perturbation and compare it with exact errors.
- analyze(model: Module, test_dataset: Dataset, device: str | device = 'cpu', save_path: str | None = None, filename: str = 'final', training: bool = False, runtime: EvaluationRuntimeConfig | None = None, **_kwargs: Any) dict[str, Any][source]
Run every configured level, dictionary, scale and draw count.
- LocalCreditAssignment.assign_gradients(model: BaseModel, inputs: Tensor, targets: Tensor, *, epoch: int | None = None) Tensor[source]
Assign one batch’s update to the parameters’
.grad; no step.Runs the forward, local signals and gradient assignment of a training step and stops where the step calls
optimizer.step(): the local rule’s gradients, the encoder and decoder updates, the distributed average and clipping.epoch(counted from 1, as in training) selects the update modes and HSIC warmup of that epoch (freeze windows andtraining_schedule); by default the trainer’s current epoch, the first beforetrain()has run. Model gradients are reset before the batch, including parameters outside the optimizer. The model keeps its mode: intrain()mode this is a training step’s update, including the forward’s updates of sparse synapse statistics. Undercore_update_mode: nonethe core is held fixed as in training: its parameters do not require gradients during the call and the forward leaves its sparse state unchanged. The configured gate policy is applied on every call, including gates outside the core. Beforetrainhas run, the trainer first preparesmodelastraindoes, without copying a best state. Restores the epoch counter, and undercore_update_mode: nonethe pre-call trainability, including when initialization or the batch raises. Returns the batch loss.
Training state
Resuming from an epoch boundary describes saving and restoring the state of a run at an epoch boundary.
Dendritic levels and delivered errors
Levels that differ describes per-level overrides, re-initialization recipes and level outputs; Delivered errors with autograd eligibilities the delivered-error building blocks.
- class dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.level_overrides.DendriticLevelOverride(depth: int, excitatory: bool = True, inhibitory: bool = True, activation: str | None = None, excitatory_contacts: tuple[tuple[int, ...], ...] | None = None, inhibitory_contacts: tuple[tuple[int, ...], ...] | None = None)[source]
Structure of one DendriNet level that differs from the shared settings.
depthcounts levels from the soma: 0 is the soma, 1 the level whose compartments couple into the soma, and the terminal level has depthlen(branch_factors).excitatory: falseorinhibitory: falseremove that feedforward pathway from the level. The pathway is built and initialized with the others and removed afterwards, so every remaining parameter receives the same random draws and initial values as in the model with the pathway (matched initialization across pathway ablations).excitatory_contactsandinhibitory_contactsdeclare the inputs each compartment of the level contacts: a list of input indices per compartment, either for every compartment of the level or once for the compartments of one neuron, repeated for every neuron (compartments are ordered neuron by neuron). They become the pathway’s connection mask, which is derived from configuration and not saved in checkpoints. Selection by the pathway’s synapse count still applies among the declared contacts; declare at most that many per compartment for all of them to be active.activationnames the level’s activation (any registered activation type;identityornonefor none).Nonekeeps the network-wide setting.
- DendriNet.forward_levels(x, inhibitory_input=None, *, detach_child_inputs=False, interventions=None)[source]
Return the output of every level, terminal level first, soma last.
The outputs stay connected to the autograd graph. With
detach_child_inputseach level receives its children’s output detached, so a level’s own parameters are the only ones its output depends on through the graph (local learning rules differentiate these outputs).interventionsmaps a level’s depth (0 = soma) to a labelled intervention such asCurrentInjection; the level’s output is replaced by the intervention’s and passed on to its parent, so a level cannot also carry a compartment perturbation. Current capture on an intervened level raises before any forward and clears its old captures; other levels can still capture their outputs. Without these options the last output equalsforward.
- DendriNet.reinitialize(recipe: LogNormalReinitialization) None[source]
Redraw the log-conductances with an explicit recipe.
The draws come from the global random stream when this is called, in the order the recipe documents, so a protocol decides where in its stream they fall.
- class dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.reinitialization.LogNormalReinitialization(synapse_log_sd: float, coupling_log_sd: float, synapse_log_mean: float = 0.0, coupling_log_mean: float = 0.0, log_offsets: tuple[LogOffset, ...] = ())[source]
Redraw synaptic and coupling log-weights from normal distributions.
Levels are visited in construction order (terminal level first, soma last). At each level the excitatory, then the inhibitory synaptic log-weights are drawn from N(
synapse_log_mean,synapse_log_sd) over the full dense tensors (entries outside the connection mask included), then the level’s coupling log-weights from N(coupling_log_mean,coupling_log_sd). Thelog_offsetsare added after all draws, in the order given. Requires exponential weight transforms (the parameters are log-conductances) and dense synapse layers.
- class dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.reinitialization.LogOffset(depth: int, target: str, value: float)[source]
A constant added to one level’s log-weights after the draws.
- class dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.level_interventions.CurrentInjection(reference_inhibitory_input: Tensor, anchor: Tensor)[source]
Replace a shunting level’s inhibitory conductance by injected current.
The inhibition beyond a reference input acts as a current at a fixed voltage
anchorinstead of as a conductance:V = (E + C - (I - I_ref) * anchor) / (leak + E + G + I_ref), followed by the level’s activation, whereIandI_refare the level’s inhibitory conductances for the actual and the reference inhibitory input,CandGthe child current and coupling conductance andEthe excitatory conductance (absent at levels without that pathway). The level’s ordinary forward still runs first, so its diagnostics describe the unperturbed conductance state.anchorhas one value per compartment (for example a training-set mean voltage); it is the caller’s to calibrate.
- dendritic_modeling.training.local_delivery.soma_error(loss: Tensor, soma_output: Tensor) Tensor[source]
Detached gradient of
losswith respect to the soma outputs.
- dendritic_modeling.training.local_delivery.delivered_error_objective(level_outputs: Sequence[Tensor], error: Tensor, gains: Sequence[Tensor | None]) Tensor[source]
Sum over levels of output x (error repeated over compartments x gain).
errorhas one column per neuron; each level’s outputs are ordered neuron by neuron, so the error is repeated over each neuron’s compartments. A gain ofNonedelivers the repeated error unchanged. The error and the gains must be detached: a graph-connected one would add its own derivative to the update, so it raises. Add the result to the loss and backpropagate.
- dendritic_modeling.training.local_delivery.relative_resistance(layer: Any, inhibitory_input: Tensor, excitatory_input=None) Tensor[source]
(D0 + eps) / (D0 + I + eps) for every compartment of a shunting level.
Iis the level’s inhibitory conductance forinhibitory_inputandD0its total conductance without inhibition: leak plus coupling conductance, plus the excitatory conductance at levels with an excitatory pathway (passexcitatory_inputthere).epsis the level’sepsilon, which the forward pass adds to the denominator. This is the input resistance left by inhibition relative to the uninhibited compartment.
- dendritic_modeling.training.local_delivery.coupling_ratios(layer: Any, excitatory_input=None) Tensor[source]
g_child / (D0 + eps) for every child of every parent compartment.
D0andepsare as inrelative_resistance: the parent’s conductance without inhibition (leak plus coupling conductance, plus the excitatory conductance at levels with an excitatory pathway; passexcitatory_inputthere) and itsepsilon. Shape[parents, children per parent], or[batch, parents, children per parent]when the excitatory conductance enters. Timesrelative_resistanceit is the exact ratio g_child / (D + eps) by which a child’s output moves its parent’s voltage.
- dendritic_modeling.training.local_delivery.activation_slope(layer: Any) Tensor[source]
The level’s activation derivative at its last forward voltage.
Needs branch diagnostics on the level (
set_branch_diagnostics(True)before the forward pass). Supported activations: identity and tanh.
- dendritic_modeling.training.local_delivery.expand_to_children(values: Tensor, branch_factor: int) Tensor[source]
Repeat per-parent values over each parent’s children (last dimension).
Node-perturbation estimates describes the node-perturbation estimates.
- dendritic_modeling.training.node_perturbation.node_perturbation_estimates(loss: Callable[[Tensor], Tensor], shape: Sequence[int], *, scale: float, draws: Iterable[int], generator: Generator, basis: Tensor | None = None, chunk: int = 16, dtype: dtype = torch.float32, device: device | str | None = None) NodePerturbationEstimate[source]
Antithetic node-perturbation estimates of per-example errors.
loss(offset)maps perturbations of shape[c, B, D](shapeis(B, D)) to per-example losses of shape[c, B], without reducing over examples, and is called with+scale * noiseand-scale * noisefor each chunk of at mostchunkdraws.basisrestricts the noise to orthonormal columns ([D, m]; seegroup_basis()).generatormakes the draws reproducible, independently ofchunk; the draws are made ondevice, by default the generator’s, which must be the generator’s device. The estimates for all counts indrawsshare the same draws in order, so larger counts extend smaller ones. Returns aNodePerturbationEstimate.
- class dendritic_modeling.training.node_perturbation.NodePerturbationEstimate(estimates: dict[int, Tensor], scale: float, rank: int)[source]
Running estimates after each requested number of draws.
estimatesmaps a draw count to the estimate of shape[B, D];rankis the number of perturbed directions per example (D, or the basis width). One draw costs two loss evaluations per example.
- dendritic_modeling.training.node_perturbation.group_basis(groups: Sequence[Sequence[int]], size: int, *, dtype: dtype = torch.float32, device: device | str | None = None) Tensor[source]
Orthonormal columns that each average one group of coordinates.
Column
kis the normalized indicator ofgroups[k]amongsizecoordinates. Groups must be non-empty, disjoint and within range; coordinates in no group are not perturbed.
- dendritic_modeling.training.node_perturbation.check_orthonormal_basis(basis: Tensor, size: int) None[source]
Raise unless columns are orthonormal within the basis dtype’s precision.
The absolute Gram-matrix tolerance is at least one dtype epsilon. Half- precision Gram products accumulate in float32, with autocast disabled; the basis itself is unchanged.
Comparison models
Baselines and comparison models describes the parameter-budget model families built by
dendritic_modeling.networks.benchmarks.parameter_budget.build_model.
- dendritic_modeling.networks.benchmarks.parameter_budget.match_parameter_budget(spec: dict, target_parameters: int, tolerance: float = 0.02) tuple[dict, dict][source]
Find the nearest feasible integer width by counted monotone search.
All fields other than width remain fixed. A match is accepted only when the instantiated whole-model count differs from target by at most tolerance. Failure is explicit; neither extra inert weights nor an over-budget-only convention is used. Matching does not equalize compute or activation memory.
- dendritic_modeling.networks.benchmarks.parameter_budget.model_report(model: Module) dict[source]
Count unique registered scalars and storage, including the affine head.
- dendritic_modeling.networks.utils.readouts.make_signed_readout(input_dim: int, output_dim: int, *, rank: int | None = None, topk: int | None = None, bias: bool = False, init_std: float = 0.02, seed: int | None = None, projection_backend: str = 'eager') Module[source]
Construct a signed readout with one explicit parameterization.
Omitting both budgets produces a dense map.
rankchooses two dense factors, andtopkchooses fixed indexed support. Indexed initialization follows the synapse initializer; its weights are not rescaled by init_std. An affine bias for indexed readouts must be applied by the caller.
- dendritic_modeling.networks.architectures.excitation_inhibition.dendritic.passive_equilibrium.passive_star_soma_voltage(excitation: Tensor, membrane_conductance: Tensor, axial_conductance: Tensor, soma_leak: float = 1.0) Tensor[source]
Solve independent passive stars, reducing the final branch dimension.
For branch current E, membrane load h and axial coupling g, the branch equilibrium is (E + g*s)/(h + g). The soma has leak to reversal zero and no direct input. Inputs broadcast; h and soma_leak must be positive and g nonnegative. Excitation is a current, not an extra conductance; callers construct h according to their model’s reversal potentials.
This positive-denominator expression avoids cancellation at large g. Its operation order is fixed, so results are reproducible bit for bit. It adds no model state, changes no layer defaults and performs no casts.
Compact checkpoints
- dendritic_modeling.deployment.compression.freeze_sparse_topology_(model: Module, config: ModelCompressionConfig | None = None) list[FrozenSparseModuleRecord][source]
Replace deterministic dynamic sparse layers with exact fixed topology.
The operation mutates
modeland is intended for inference/export after training. ExistingIndexedSparseLinearmodules are already compact and are left unchanged.
- dendritic_modeling.deployment.compression.bitmask_slot_order_keys(model: Module, state_dict: Mapping[str, Tensor] | None = None) set[str][source]
connection_indiceskeys whose contacts keep their slot order.The bitmask encoding of a compact checkpoint may reorder a layer’s contacts into ascending input order only when that changes nothing but the order in which they are summed: the layer’s class itself (not only a parent class) declares
SLOT_ORDER_MATTERS = Falsewithpre_was its only per-contact tensor (CONTACT_SLOT_STATE), and its state holds no other tensor with one entry per contact. Of the library’s layers only the fixedIndexedSparseLinearqualifies. Every other layer keeps its slot order (seecompact_sparse_bitmask_state_dict()):indexed_release(per-contact impact and ages; release draws and cellwise rewiring follow slot positions),indexed_rewire(pruning ties, pairing of new inputs with pruned slots),indexed_dynamic(Top-K ties, selection noise) and layer types defined elsewhere.
- dendritic_modeling.networks.checkpoints.compact_sparse_bitmask_state_dict(state_dict: Mapping[str, Tensor], *, keep_slot_order: bool | Collection[str] = False) tuple[dict[str, Tensor], dict[str, str]][source]
Encode row-wise topology as bitmasks instead of integer indices.
This is useful for moderately dense topology, where even uint16 costs two index bytes per retained weight while a bitmask costs one bit per possible connection. Every
connection_indicestensor with apre_wof the same shape is encoded. A bitmask records which inputs a row contacts, not in which slot each contact is stored, so each key uses one of two layouts:ascending(default; label"bitmask")The contacts of each row and the matching
pre_wentries are reordered into ascending input order, so the mask and the weights reconstruct the layer. This suits a layer whose only per-contact tensor ispre_wand whose training updates do not depend on the slot order, such as a fixedIndexedSparseLinear; its outputs can differ in the last bits because the contacts are summed in another order. A row that is not already ascending raisesValueErrorwhen the module holds another tensor with one entry per contact (indexed_releaseimpact and ages, for example), which the reordering would misalign.slot order(keys inkeep_slot_order; label"bitmask_slot_order")The contacts keep their slots and no other tensor changes. A key with a row that is not ascending also stores, under
<key>.__bitmask_slot_order, the slot of each ascending contact (one byte per contact up to 256 contacts per row, two up to 65,536), and its metadata gains a fourth entry. Decoding restores the indices exactly. Library versions before 2026-10-13 cannot decode such keys and raise.
keep_slot_orderisTrue(every key),False(none) or theconnection_indiceskeys that keep their slot order.
- dendritic_modeling.networks.checkpoints.decode_sparse_bitmask_state_dict(state_dict: Mapping[str, Tensor]) dict[str, Tensor][source]
Restore row-wise indices from
compact_sparse_bitmask_state_dict().Keys in the ascending layout decode to ascending indices, aligned with the stored (reordered)
pre_w; keys with a stored slot order decode to the indices in their original slots. Malformed or inconsistent entries raiseRuntimeError.
Project provenance
Project provenance describes the source contract, export and evidence formats these functions read and the receipts they write.
- dendritic_modeling.utils.project_source.read_contract(path: Path) dict[str, Any][source]
Load the small, versioned source contract stored with a paper’s code.
library.lineiscore,llmorhistorical. Acoreorllmcontract nameslibrary.maintained_ref, the full branch ref (refs/heads/...orrefs/remotes/...) whose history must contain the pinned commit; ahistoricalcontract records an original source and names no maintained branch.library.release_bridgeoptionally names asource_commitand arelease_commitfor a release built by squashing (seeverify_contract()). RaisesSourceContractErrorfor a malformed contract.
- dendritic_modeling.utils.project_source.verify_contract(contract_path: Path, library_root: Path, *, paper_root: Path | None = None) dict[str, Any][source]
Check exact source identity and cleanliness without running paper code.
The library checkout must be clean, its
HEADandlibrary.refmust both belibrary.commit, and for acoreorllmcontract that commit must belibrary.maintained_refor one of its ancestors. A release built by squashing has none of the source commits as ancestors; for it the contract declareslibrary.release_bridgeinstead, and verification requires that the pinned commit issource_commitor one of its ancestors, thatrelease_commitis the maintained ref or one of its ancestors, and that both commits have the same tree. The paper checkout must be clean and hold every declared source path and entry point.paper_rootpermits a contract in a subdirectory of that explicit Git root. Omitting it retains the contract-directory default. All declared source paths remain relative to the paper root.Returns the receipt: contract, paper and library identities, the maintained ref and its commit, the verified bridge with its tree (only when one is declared), the package and configuration roots and the interpreter. Raises
SourceContractErrorwhen a check fails.
- dendritic_modeling.utils.project_source.activate_source(receipt: dict[str, Any]) None[source]
Select the verified package and reject an already imported wrong copy.
- exception dendritic_modeling.utils.project_source.SourceContractError[source]
The selected source does not satisfy a project’s declared dependency.
- dendritic_modeling.utils.project_export.export_project(manifest: Path, commit: str, output: Path, *, paper_root: Path | None = None) dict[source]
Write committed Git blobs;
paper_rootopts into a nested manifest.
- dendritic_modeling.utils.project_evidence.check_evidence(manifest: Path, roots: dict[str, Path]) dict[source]
Check explicit files and result mappings; never regenerate a baseline.
- exception dendritic_modeling.utils.project_evidence.EvidenceError[source]
An evidence manifest is invalid or does not identify preserved files.
- dendritic_modeling.utils.exact_file_inventory.build_inventory(files: Sequence[Mapping[str, Any]], *, generation_binding: Mapping[str, Any], path_bindings: Sequence[Mapping[str, Any]] = (), directory_bindings: Sequence[Mapping[str, Any]] = ()) dict[str, Any][source]
Canonicalize a frozen application-supplied exact-file inventory.
- dendritic_modeling.utils.exact_file_inventory.validate_inventory(value: Mapping[str, Any]) dict[str, Any][source]
Validate an inventory without trusting or reading its target files.
- dendritic_modeling.utils.exact_file_inventory.balanced_assignment(inventory: Mapping[str, Any], *, world_size: int) dict[str, int][source]
Assign files deterministically by largest-first cumulative bytes.
- dendritic_modeling.utils.exact_file_inventory.verify_shard(inventory: Mapping[str, Any], *, rank: int, world_size: int) dict[str, Any][source]
Live-hash one deterministic rank shard and bracket every read by stats.
- dendritic_modeling.utils.exact_file_inventory.merge_verified_shards(inventory: Mapping[str, Any], shards: Sequence[Mapping[str, Any]], *, world_size: int) tuple[dict[str, Any], dict[str, dict[str, Any]]][source]
Fail closed unless all and only canonical rank assignments were verified.