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 extends a parent file (resolved relative to the file that names it). A sweep file is accepted as well; its base_config section is loaded. Every section is checked against the keys the library reads: unknown keys raise UnknownConfigKeyError, and keys retired from earlier library versions warn (see RETIRED_KEYS). Each call parses the file again, so edits are always picked up.

overrides maps 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 as load_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 core breaks.

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 unless allow_override=True is 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_class is a Trainer subclass 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) requires allow_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_function falls back to a case-insensitive match. Builders are zero-argument callables that return a LossFunction.

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 phase the analyzer is metadata only: AnalysisManager builds it when its section is enabled but never runs it. With phase it 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 PluginLoadError again 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: register runs now and the plugin is recorded under name like 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.

builder receives the section’s mapping (possibly empty) and returns the typed section; it raises for invalid content. Replacing a registered builder requires allow_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_voltage is excitation - inhibition + child_current); inputs maps x, inhibitory_input and branch_input to 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.

options holds the rule’s options and their defaults; a layer receives them as additive_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 x through this layer’s contacts with other weights.

weight has the shape [out_features, K] of sparse_weight(); the result is out[..., i] = sum_j weight[i, j] * x[..., connection_indices[i, j]], computed with the layer’s projection backend. For example project_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.json in save_root: for every requested analyzer its status (completed, skipped, failed or empty), 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.

layers is one DendriticBranchLayer or an iterable of them. Inside the block each forward of these layers keeps its currents, voltage and output with their autograd graph, as set_analysis_currents() describes; read them with get_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. Unlike set_branch_diagnostics(), nothing is detached. Missing pathways are None. Capture that would bypass a fused shunting gate requires torch.no_grad(): its backward need not match the explicit voltage path. For gradient analyses, construct an unfused model with reactivation.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 aliases excitation, inhibition and branch_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.

perturbations maps DendriticBranchLayer modules to CompartmentPerturbation values. Inside the block every forward of these layers adds its offset once, as set_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, voltage or, for a shunting layer, current; see compartment_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. None clears 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 and training_schedule); by default the trainer’s current epoch, the first before train() has run. Model gradients are reset before the batch, including parameters outside the optimizer. The model keeps its mode: in train() mode this is a training step’s update, including the forward’s updates of sparse synapse statistics. Under core_update_mode: none the 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. Before train has run, the trainer first prepares model as train does, without copying a best state. Restores the epoch counter, and under core_update_mode: none the 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_modeling.training.state.capture_random_state() → dict[str, Any][source]

Capture Python, NumPy and all visible Torch generators without draws.

dendritic_modeling.training.state.restore_random_state(state: Mapping[str, Any]) → None[source]

Restore a trusted state on the same device topology and environment.

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.

depth counts levels from the soma: 0 is the soma, 1 the level whose compartments couple into the soma, and the terminal level has depth len(branch_factors).

excitatory: false or inhibitory: false remove 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_contacts and inhibitory_contacts declare 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.

activation names the level’s activation (any registered activation type; identity or none for none). None keeps 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_inputs each 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). interventions maps a level’s depth (0 = soma) to a labelled intervention such as CurrentInjection; 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 equals forward.

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). The log_offsets are 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 anchor instead of as a conductance: V = (E + C - (I - I_ref) * anchor) / (leak + E + G + I_ref), followed by the level’s activation, where I and I_ref are the level’s inhibitory conductances for the actual and the reference inhibitory input, C and G the child current and coupling conductance and E the excitatory conductance (absent at levels without that pathway). The level’s ordinary forward still runs first, so its diagnostics describe the unperturbed conductance state. anchor has 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 loss with 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).

error has 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 of None delivers 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.

I is the level’s inhibitory conductance for inhibitory_input and D0 its total conductance without inhibition: leak plus coupling conductance, plus the excitatory conductance at levels with an excitatory pathway (pass excitatory_input there). eps is the level’s epsilon, 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.

D0 and eps are as in relative_resistance: the parent’s conductance without inhibition (leak plus coupling conductance, plus the excitatory conductance at levels with an excitatory pathway; pass excitatory_input there) and its epsilon. Shape [parents, children per parent], or [batch, parents, children per parent] when the excitatory conductance enters. Times relative_resistance it 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] (shape is (B, D)) to per-example losses of shape [c, B], without reducing over examples, and is called with +scale * noise and -scale * noise for each chunk of at most chunk draws. basis restricts the noise to orthonormal columns ([D, m]; see group_basis()). generator makes the draws reproducible, independently of chunk; the draws are made on device, by default the generator’s, which must be the generator’s device. The estimates for all counts in draws share the same draws in order, so larger counts extend smaller ones. Returns a NodePerturbationEstimate.

class dendritic_modeling.training.node_perturbation.NodePerturbationEstimate(estimates: dict[int, Tensor], scale: float, rank: int)[source]

Running estimates after each requested number of draws.

estimates maps a draw count to the estimate of shape [B, D]; rank is the number of perturbed directions per example (D, or the basis width). One draw costs two loss evaluations per example.

static evaluations_per_example(draws: int) → int[source]

Loss evaluations per example behind an estimate from draws draws.

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 k is the normalized indicator of groups[k] among size coordinates. 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. rank chooses two dense factors, and topk chooses 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 model and is intended for inference/export after training. Existing IndexedSparseLinear modules 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_indices keys 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 = False with pre_w as 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 fixed IndexedSparseLinear qualifies. Every other layer keeps its slot order (see compact_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_indices tensor with a pre_w of 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_w entries are reordered into ascending input order, so the mask and the weights reconstruct the layer. This suits a layer whose only per-contact tensor is pre_w and whose training updates do not depend on the slot order, such as a fixed IndexedSparseLinear; its outputs can differ in the last bits because the contacts are summed in another order. A row that is not already ascending raises ValueError when the module holds another tensor with one entry per contact (indexed_release impact and ages, for example), which the reordering would misalign.

slot order (keys in keep_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_order is True (every key), False (none) or the connection_indices keys 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 raise RuntimeError.

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.line is core, llm or historical. A core or llm contract names library.maintained_ref, the full branch ref (refs/heads/... or refs/remotes/...) whose history must contain the pinned commit; a historical contract records an original source and names no maintained branch. library.release_bridge optionally names a source_commit and a release_commit for a release built by squashing (see verify_contract()). Raises SourceContractError for 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 HEAD and library.ref must both be library.commit, and for a core or llm contract that commit must be library.maintained_ref or one of its ancestors. A release built by squashing has none of the source commits as ancestors; for it the contract declares library.release_bridge instead, and verification requires that the pinned commit is source_commit or one of its ancestors, that release_commit is 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_root permits 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 SourceContractError when 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_root opts 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.

dendritic_modeling.utils.project_evidence.sha256_file(path: Path) → str[source]
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.

dendritic_modeling.utils.exact_file_inventory.file_snapshot(path: Path) → dict[str, Any][source]

Return a symlink-aware mutation snapshot without reading file bytes.

dendritic_modeling.utils.exact_file_inventory.canonical_sha256(value: object) → str[source]

Hash one finite canonical-JSON value.