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
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
¶
Source code in unaiverse/modules/hl/hl_utils.py
Runs one integration step for every group under torch.no_grad(). With the default flip=-1 and the step delta read from the model:
p_xi ← (1 - theta) · p_xi + delta · grad(h).local=Truefirst appliesw ← w - delta · beta · p_wand thenp_w ← (1 - theta) · p_w + delta · grad(w).local=Falsefirst appliesp_w ← (1 - theta) · p_w + delta · grad(w)and thenw ← 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
¶
Source code in unaiverse/modules/hl/hl_utils.py
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
¶
Source code in unaiverse/modules/hl/hl_utils.py
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.