Skip to content

Bilevel optimizer base class

vertax.bilevelopt.bilevelopt

_BilevelOptimizer holds the settings and methods that PbcBilevelOptimizer and BoundedBilevelOptimizer share. Its name starts with an underscore because it is not meant to be instantiated, but it is exported by vertax and its attributes are the ones you set on either optimizer.

Bi-level optimizers abstract class.

BETA_DEFAULT module-attribute

BETA_DEFAULT = 0.01

Value beta resolves to when an EP run leaves it unset. Applied with a warning, never silently.

_BilevelOptimizer

_BilevelOptimizer()

Abstract base class for Bi-level optimizers.

Use the specialezed corresponding ones:

  • to optimize a PbcMesh use a PbcBilevelOptimizer,
  • to optimize a BoundedMesh use a BoundedBilevelOptimizer.

Initialize shared parameters and hyper-parameters between Bi-level optimizers.

outer_solver instance-attribute

outer_solver: GradientTransformation = optax.adam(learning_rate=0.0001, nesterov=True)

Which outer solver to use. Defaults to optax.adam(learning_rate=0.0001, nesterov=True)

loss_function_inner instance-attribute

loss_function_inner: Callable | None = None

Define your inner loss function.

loss_function_outer instance-attribute

loss_function_outer: Callable | None = None

Define your outer loss function.

params_regularizer instance-attribute

params_regularizer: Callable | None = None

Optional regularization term on the parameters themselves, as (vert_params, he_params, face_params) -> scalar.

Its gradient is added to the outer gradients before the outer solver's update, so the term is optimized jointly with the outer loss rather than applied as a separate step. This is the only place such a term can act: loss_function_outer is called without the parameters, and a parameter-only term added to loss_function_inner cancels exactly in equilibrium propagation's (grad_nudged - grad_free) difference. Defaults to None.

Honoured by ALL estimator paths.

CAUTION: a parameter-space penalty is mis-scaled against a filtered hypergradient. If the inner solve is truncated or preconditioned, the data gradient carries the filter factor and grad R(theta) does not, so the effective weight scales as 1/f_k. Do not use this to fix the mean of a parameter -- use params_normalization. See outer_optimization.

ep_variant instance-attribute

ep_variant: EPVariant = EPVariant.CENTERED

Which EP finite-difference form to use (EQUILIBRIUM_PROPAGATION only). CENTERED (default) is second-order in beta; ONE_SIDED is first-order and is provided for ablation. See vertax.method_enum.EPVariant.

params_normalization instance-attribute

params_normalization: dict[str, float] | None = None

Mean-value normalization constraints, per parameter array, or None for no constraint.

A dict from parameter-array name to the target mean, e.g. {"faces_params": 4.1} for E1 shape factors or {"edges_params": 1.0} for E2 line tensions. Applied as an additive projection after every outer step: p <- p - (mean(p) - target). Valid keys are vertices_params, edges_params and faces_params. Off by default.

This is a normalization CONSTRAINT, not a gauge, and the distinction is load-bearing: a gauge transformation leaves the physics invariant; a uniform shift of these parameters does not. For E2 tensions, M 1 != 0: measured on the benchmark, ||M.1|| = 1.40-1.72 against ||M.Lambda|| = 1.04-1.55, so a shift of size std(Lambda) produces 10-14% of the tension force. For E1 shape factors the same holds -- a uniform increase in p0 makes every cell prefer a longer perimeter, which moves the equilibrium. The uniform direction is near-null, not null: least observable by a wide margin, which is precisely why it must be supplied from outside the data.

It is an ASSUMPTION, not bookkeeping. Fixing the mean injects the true value of one direction -- the one that would need ~100x more data to determine than the best-conditioned one -- and it is known only because the benchmark was constructed with that mean. Legitimate and standard, but it must be stated. On real images there is no ground-truth mean, so the corresponding error metric must be CENTRED (subtract the mean from both the recovered and the reference field) rather than normalised against an assumed level.

The additive convention is deliberate. The force-inference literature normalises multiplicatively (p -> a p), which for E2 is equivalent to K -> K/a and so trades against the area stiffness instead of being near-invariant. State which convention is used; a reader from that literature will assume the other one.

Generalises mean_tension_gauge, which reached edges_params only and is why E1's faces_params were never constrained. Setting both is an error.

mean_tension_gauge instance-attribute

mean_tension_gauge: float | None = None

Target for the mean line tension, fixed by parameter renormalisation after every outer step (Lambda <- Lambda - (mean(Lambda) - target)), or None to leave the gauge free.

The additive freedom of E2 line tensions is the least observable direction in the problem and carries no information, so it is fixed by convention rather than inferred. Set to 1.0 for E2 drivers. Leave None for E1 (per-cell shape factors have no analogous freedom) and for bounded inverse-design runs. Prefer this to a params_regularizer penalty: see outer_optimization for why a penalty is mis-scaled against a filtered hypergradient.

persist_outer_state instance-attribute

persist_outer_state: bool = False

If True, the outer optimizer's moment/accumulator state is carried across bilevel epochs instead of being re-initialised at every call. Only honoured by the EQUILIBRIUM_PROPAGATION method in PbcBilevelOptimizer; setting it with any other method, or with a BoundedBilevelOptimizer, raises ValueError at the first outer step. Defaults to False (current behaviour).

custom_metrics instance-attribute

custom_metrics: dict[str, tuple[Callable[[Any, Any], float], list[float], list[float]]] = {}

Define custom metrics that can be saved during optimization. The function must take two arguments : a mesh and a bilevel optimizer ; and return a float.

max_nb_iterations instance-attribute

max_nb_iterations: int = 1000

Maximum number of iterations during an optimization step.

tolerance instance-attribute

tolerance: float = 0.0001

Below this level, we consider that the loss is stagnating.

patience instance-attribute

patience: int = 5

Maximum number of consecutive stagnating loss before we stop.

min_dist_T1 instance-attribute

min_dist_T1: float = 0.005

Threshold to perform T1 transitions.

cap_vertex_step instance-attribute

cap_vertex_step: bool | None = None

Cap each per-step vertex displacement at MAX_VERTEX_STEP_FACTOR * min_dist_T1.

None (the default) means AUTO: on for line-search solvers, off for fixed-step ones. Set True or False to force it either way; an explicit value always wins. The choice is passed to every relaxation the optimizer runs, including the inner solves of every hypergradient estimator.

Line-search solvers (gd_linesearch, cg_linesearch, optax.lbfgs()) pick their own step and can take one of order 1: a vertex then crosses whole cells in a single iteration, which defeats the incremental T1 detector and can turn a cell inside out (its boundary winding flips). Nothing in the periodic energy objects to that, because get_area takes the absolute value of the shoelace sum: an inverted cell scores like a sound one of equal area, so the fold is never pushed back out (get_area_bounded did the same before 0.2.1; it now returns the signed area, which is not positive for a folded bounded cell). On the 20-cell tissue of the mitotic-spindle notebook, the first gd_linesearch step moves a vertex by 124 min_dist_T1 on cells about 0.75 wide and leaves a cell with signed area -0.056; with the cap the same step is 5 min_dist_T1 and no cell is inverted (measured by Michael Corbeau).

Fixed-step solvers (optax.sgd, optax.adam) are left alone because the cap is not inert for them: sgd(0.01) with min_dist_T1 = 0.005 gives a cap of 0.025, which bites. Their results are therefore bit-identical to those of a library without the option.

vertices_target instance-attribute

vertices_target = jnp.array([])

Vertices table of a target mesh if any.

edges_target instance-attribute

edges_target = jnp.array([])

Edges table of a target mesh if any.

faces_target instance-attribute

faces_target = jnp.array([])

Faces table of a target mesh if any.

image_target instance-attribute

image_target: Array = jnp.array([])

Passed to the outer cost as its last argument, image_target; no cost of the library uses it.

beta instance-attribute

beta: Any = _UNSET

β parameter used for Equilibrium Propagation.

Defaults to the sentinel _UNSET, not to a number, so that an EP run which never assigns it produces a WARNING instead of silently adopting a default: an implicit default can differ from the intended value by a large factor with nothing reporting the discrepancy. Resolved to BETA_DEFAULT by _check_attribute_dispatch before any dispatch, so downstream code always sees a float.

update_T1 property writable

update_T1: bool

Whether to process T1 topological operations or not.

inner_solver property writable

inner_solver: GradientTransformation

Optax inner solver used.

bilevel_optimization_method property writable

bilevel_optimization_method: BilevelOptimizationMethod

The bilevel optimization method currently used.

compute_outer_loss

compute_outer_loss(mesh: Mesh, only_on_vertices: None | list[int] = None, only_on_edges: None | list[int] = None, only_on_faces: None | list[int] = None) -> float

Get the result of self.loss_function_outer called with the correct arguments.

Must be implemented by child classes.

compute_inner_loss

compute_inner_loss(mesh: Mesh, only_on_vertices: None | list[int] = None, only_on_edges: None | list[int] = None, only_on_faces: None | list[int] = None) -> float

Get the result of self.loss_function_inner called with the correct arguments.

Must be implemented by child classes.

inner_optimization

inner_optimization(mesh: Mesh, perform_energy_check: bool = True, only_on_vertices: None | list[int] = None, only_on_edges: None | list[int] = None, only_on_faces: None | list[int] = None) -> list[float]

Optimize the mesh for the inner loss function.

Parameters:

Name Type Description Default
mesh Mesh

The mesh to act on.

required
perform_energy_check bool = True

Allow T1 only if the energy is decreased by doing so. Should be true if forward mode is used only.

True
only_on_vertices None | list[int] = None

Consider only a subset of vertices for the loss function. All vertices if None.

None
only_on_edges None | list[int] = None

Consider only a subset of edges for the loss function. All edges if None.

None
only_on_faces None | list[int] = None

Consider only a subset of faces for the loss function. All faces if None.

None

Returns:

Type Description
list[float]

list[float]: Histor of loss values during optimization.

outer_optimization

outer_optimization(mesh: Mesh, only_on_vertices: None | list[int] = None, only_on_edges: None | list[int] = None, only_on_faces: None | list[int] = None) -> None

Optimize the mesh for the outer loss function.

Parameters:

Name Type Description Default
mesh Mesh

The mesh to act on.

required
only_on_vertices None | list[int] = None

Consider only a subset of vertices for the loss function. All vertices if None.

None
only_on_edges None | list[int] = None

Consider only a subset of edges for the loss function. All edges if None.

None
only_on_faces None | list[int] = None

Consider only a subset of faces for the loss function. All faces if None.

None

bilevel_optimization

bilevel_optimization(mesh: Mesh, perform_energy_check: bool = False, only_on_vertices: None | list[int] = None, only_on_edges: None | list[int] = None, only_on_faces: None | list[int] = None) -> list[float]

Optimize the mesh for the loss functions given.

Parameters:

Name Type Description Default
mesh Mesh

The mesh to act on.

required
perform_energy_check bool = True

Allow T1 only if the energy is decreased by doing so. Should be true if forward mode is used only.

False
only_on_vertices None | list[int] = None

Consider only a subset of vertices for the loss function. All vertices if None.

None
only_on_edges None | list[int] = None

Consider only a subset of edges for the loss function. All edges if None.

None
only_on_faces None | list[int] = None

Consider only a subset of faces for the loss function. All faces if None.

None

Returns:

Type Description
list[float]

list[float]: History of loss values during optimization.

do_n_bilevel_optimization

do_n_bilevel_optimization(nb_epochs: int, mesh: Mesh, only_on_vertices: None | list[int] = None, only_on_edges: None | list[int] = None, only_on_faces: None | list[int] = None, pre_inner_optimization: bool = False, report_every: int = 0, also_report_to_stdout: bool = False, save_plotmesh_every: int = 0, save_mesh_data_every: int = 0, save_folder: str = '.') -> None

Optimize the mesh for the loss function given.

Parameters:

Name Type Description Default
nb_epochs int

The number of bilevel optimization steps to perform.

required
mesh Mesh

The mesh to act on.

required
only_on_vertices None | list[int] = None

Consider only a subset of vertices for the loss function. All vertices if None.

None
only_on_edges None | list[int] = None

Consider only a subset of edges for the loss function. All edges if None.

None
only_on_faces None | list[int] = None

Consider only a subset of faces for the loss function. All faces if None.

None
pre_inner_optimization bool = False

Whether to perform an optional initial inner optimization first.

False
report_every int = 0

If strictly positive, report current state (costs, metrics, time) at this frequency.

0
also_report_to_stdout bool = False

Whether to also report to stdout (print).

False
save_plotmesh_every int = 0

If positive, save the plot of the mesh at this frequency.

0
save_mesh_data_every int = 0

If positive, save the mesh data at this frequency.

0
save_folder str

(str = "."): Base folder where to save data if needed.

'.'

self_summary

self_summary() -> str

Give a summary of hyper-parameters of the optimizer.

add_custom_metric

add_custom_metric(name: str, function: Callable[[Any, Any], float]) -> None

Add a custom metric to the metrics to save when performing n bilevel optimizations.

The function must take two arguments : a mesh and a bilevel optimizer.

remove_custom_metric

remove_custom_metric(name: str) -> None

Remove a custom metric from the metrics to save when performing n bilevel optimizations.