Skip to content

unaiverse.modules.hl.hl_utils

Hamiltonian Learning treats the training of a recurrent network on a stream as an optimal control problem in time. The state of the network xi and its weights w evolve forward in time. Each of them has a costate (p_xi, p_w) that carries the sensitivity of the loss. The learning rule integrates the costates with an Euler step on the gradients of a Hamiltonian and moves the weights against the costates. No backpropagation through time is needed because the costates travel forward with the stream. This module provides HL, an optimizer-like object that runs these integration steps for one or more models (see Learning over time and Models).

HL works with the inner module that the state-space processors of networks (CSSM, CDiagR, CTE, CTB, CTBE and their variants) keep in their attribute module. A custom model works too when it exposes the attributes below:

Attribute Content
h_init The initial state, a tensor of shape [batch_size, h_dim].
h The state of the current step, a tensor with requires_grad that forward stores.
dh The time derivative (h_new - h) / delta of the state on the current step.
delta The time step, a float.

A training loop on a stream looks like this:

import torch
from unaiverse.modules.networks import CTB
from unaiverse.modules.hl.hl_utils import HL

proc = CTB(u_shape=(3,), d_dim=2, y_dim=1, h_dim=8, delta=0.1, local=True)
net = proc.module                                 # The inner module carries h, dh and delta
hl = HL(net, theta=0.1, beta=1.0)

for t, (u, du, target) in enumerate(stream):      # One sample per step
    y = net(u, du, first=(t == 0))
    H = hl.compute_hamiltonian(((y - target) ** 2).sum())
    H.backward()                                  # Gradients of H with respect to h and to the weights
    hl.step()                                     # Euler steps on the costates and on the weights
    hl.zero_grad()

HL

HL(models: Module | Iterable[Dict[str, Module | Any]], *, gamma=1.0, flip=-1.0, theta=0.1, beta=1.0, reset_neuron_costate=False, reset_weight_costate=False, local=True)
Source code in unaiverse/modules/hl/hl_utils.py
def __init__(self, models: torch.nn.Module | Iterable[Dict[str, torch.nn.Module | Any]], *,
             gamma=1., flip=-1., theta=0.1, beta=1., reset_neuron_costate=False, reset_weight_costate=False,
             local=True):
    """
    Args:
        models (list of dict): List of parameter groups, each containing:
            - 'params': the Model or list of parameters
            - 'gamma', 'beta', 'theta', etc.: Hyperparameters for the group.
    """

    # Set defaults
    defaults = dict(params=None, gamma=gamma, flip=flip, theta=theta, beta=beta,
                    reset_neuron_costate=reset_neuron_costate, reset_weight_costate=reset_weight_costate,
                    local=local)

    # Ensure models is a list of dicts and assign the specified values
    if isinstance(models, torch.nn.Module):
        models = [{**defaults, 'params': models}]

    self.param_groups = []
    for group in models:
        assert 'params' in group, "Each parameter group must contain a 'params' key storing the model."
        self.param_groups.append({**defaults, **group})

    # Store the optimizer state for each model in a list of dicts, not to be confused with the state of the model
    self.state = [_init_state_and_costate(group['params']) for group in self.param_groups]

Holds the parameter groups and the costates of one or more models.

Argument Type Default Meaning
models torch.nn.Module or iterable of dict required One model or a list of groups. Each group is a dict with the key params (the model) plus any of the keyword arguments below to override their defaults for that group. A group without params raises AssertionError.
gamma float 1.0 The weight of the potential term (the loss) in the Hamiltonian.
flip float -1.0 The sign of the costate dynamics. The steps below assume the default.
theta float 0.1 The dissipation of the costates. With flip=-1 each costate update first multiplies the costate by 1 - theta.
beta float 1.0 The scale of the weight update.
reset_neuron_costate bool False True zeroes p_xi on every zero_grad.
reset_weight_costate bool False True zeroes p_w on every zero_grad.
local bool True True updates the weights with the costates of the previous step and then updates the costates. False updates the costates first and then moves the weights with the new ones.

All the arguments after models are keyword-only. The constructor stores the groups in param_groups and the costates in state, a list with one dict per group: {"x": {"xi": ..., "w": {...}}, "p": {"xi": ..., "w": {...}}}. The costates start at zero. p_w holds one entry per parameter with requires_grad=True.

Frozen parameters

step() raises AssertionError: Dictionaries should have the same keys. when the model has a parameter with requires_grad=False. The costates cover only the trainable parameters while the update reads all of them. Train a model whose parameters are all trainable.

step

step()
Source code in unaiverse/modules/hl/hl_utils.py
@torch.no_grad()
def step(self):
    """Perform one optimization step for all parameter groups."""

    for group, state in zip(self.param_groups, self.state):
        model = group['params']
        delta = model.delta

        # Copy the state (of the model) just to track it during the optimization and get the costate
        # the locality of these operations is handled by the model
        state['x']['xi'] = model.h
        dp_xi = _get_grad(model.h)
        _euler_step(state['p']['xi'], dp_xi, step_size=-delta * group['flip'],
                    decay=-group['flip'] * group['theta'], in_place=True)

        # Copy the weights from the network just to track it during the optimization and get the costates
        dp_w = {}
        for name, param in model.named_parameters():
            state['x']['w'][name] = param
            dp_w[name] = _get_grad(param)

        if group['local']:

            # Local HL uses the old costates to update the weights
            d_w = state['p']['w']
            _euler_step(state['x']['w'], d_w, step_size=-delta*group['beta'], decay=None, in_place=True)
            _euler_step(state['p']['w'], dp_w, step_size=-delta*group['flip'],
                        decay=-group['flip']*group['theta'], in_place=True)
        else:

            # Non-local HL updates the costates before updating the weights
            d_w = _euler_step(state['p']['w'], dp_w, step_size=-delta * group['flip'],
                              decay=-group['flip'] * group['theta'], in_place=True)
            _euler_step(state['x']['w'], d_w, step_size=-delta * group['beta'], decay=None, in_place=True)

Runs one integration step for every group under torch.no_grad(). With the default flip=-1 and the step delta read from the model:

  1. p_xi ← (1 - theta) · p_xi + delta · grad(h).
  2. local=True first applies w ← w - delta · beta · p_w and then p_w ← (1 - theta) · p_w + delta · grad(w).
  3. local=False first applies p_w ← (1 - theta) · p_w + delta · grad(w) and then w ← w - delta · beta · p_w.

The weights change in place. A missing gradient (a tensor whose .grad is None, such as a state that is not a leaf) counts as zero. Call it after backward() on the Hamiltonian of the step.

compute_hamiltonian

compute_hamiltonian(*potential_terms: Tensor) -> Tensor
Source code in unaiverse/modules/hl/hl_utils.py
def compute_hamiltonian(self, *potential_terms: torch.Tensor) -> torch.Tensor:
    """Computes the Hamiltonian for all models."""

    # The number of potential terms provided should be equal to the number of models
    assert len(potential_terms) == len(self.param_groups), f"A potential term for each model is expected."

    ham = torch.tensor(0., dtype=potential_terms[0].dtype, device=potential_terms[0].device)
    for group, state, potential_term in zip(self.param_groups, self.state, potential_terms):
        model = group['params']
        ham += group['gamma'] * potential_term + torch.dot(model.dh.view(-1), state['p']['xi'].view(-1)).real
    return ham

Takes one potential term per group (a scalar tensor, usually the loss of the step) and returns the Hamiltonian as a scalar tensor. The Hamiltonian is the sum over the groups of gamma · potential + <dh, p_xi> with <·,·> the real part of the dot product of the flattened tensors. A number of terms different from the number of groups raises AssertionError. The result keeps the graph of the potentials and of dh for backward().

zero_grad

zero_grad(set_to_none: bool = False) -> None
Source code in unaiverse/modules/hl/hl_utils.py
def zero_grad(self, set_to_none: bool = False) -> None:
    """Zeroes the gradients and resets co-states if needed."""

    for group, state in zip(self.param_groups, self.state):
        model = group['params']
        _zero_grad(model.h, set_to_none)
        for param in model.parameters():
            _zero_grad(param, set_to_none)

        # Eventually reset costates
        if group['reset_neuron_costate']:
            _zero_inplace(state['p']['xi'], detach=True)
        if group['reset_weight_costate']:
            _zero_inplace(state['p']['w'], detach=True)

Zeroes the gradients of the state h and of all the parameters of every model. set_to_none=True drops them to None instead. It then zeroes p_xi and p_w of the groups that asked for it with reset_neuron_costate and reset_weight_costate.