04. Optimization by gradient descent#
Fit the parameters of a native Dendra model to a voltage trace using PyTorch. For the same workflow with a compiled runner, see Train models and select parameters.
General principles#
Optimization in Dendra is performed using gradient descent algorithms, which iteratively adjust model parameters to minimize a loss function. The loss function quantifies the difference between the model’s output and the target data. Common loss functions include mean squared error for fitting voltage traces or spike timing errors for fitting spike trains.
To perform optimization, we need to define:
A neuron / network model with parameters to optimize.
A loss function that measures the discrepancy between model output and target data.
An optimization algorithm (e.g., SGD, Adam) to update the parameters based on the computed gradients.
Example: Fitting a single neuron model to voltage traces#
Here, we will fit a simple neuron model to a target voltage trace using mean squared error as the loss function. For the purposes of this exercise, we will use another model as the “target” to generate synthetic data.
First, we set up the reference model and generate the target voltage trace.
import dendra as dn
import torch
from dendra.models.mod import hh
from dendra.models.callbacks import Recorder
from dendra.units import nA
dn.set_jit_enabled(True) # True to enable jit compilation globally
ref = dn.Unmyelinated([2.0], celsius=6.3, v_init=-65.0, rhoa=100.0).double()
ref.insert(hh)
rec = Recorder(['v'])
# add injection to generate data
stim_ref = dn.mono_rect(amp=2.0*nA, delay=0.1, pw=0.2)
ref[0, 10].inject(stim_ref)
# generate data
ref.initialize()
ref.run(tstop=5.0, dt=0.005, callbacks=[rec])
v_ref = rec.stack('v')
Now let’s set up the model we want to optimize. We will define a simple neuron model with parameters that we can adjust. We will deliberately choose initial parameters that are different from the target model to see how well optimization can recover them.
bad_model = dn.Unmyelinated([2.0], celsius=6.3, v_init=-65.0, rhoa=100.0).double()
bad_model.insert(hh, gnabar=0.05, gkbar=0.05) # deliberately wrong conductances
bad_rec = Recorder(['v'])
stim_test = dn.mono_rect(amp=2.0*nA, delay=0.1, pw=0.2)
bad_model[0, 10].inject(stim_test)
Call train() to put the model in training mode before fitting. Choose the parameters to optimize separately.
bad_model.train()
Unmyelinated(celsius_param=Parameter containing:
tensor(6.3000, dtype=torch.float64), cm_param=Parameter containing:
tensor(1., dtype=torch.float64), rhoa_param=Parameter containing:
tensor(100., dtype=torch.float64), rhoa_scale_param.rho=Parameter containing:
tensor(0.5413, dtype=torch.float64), cm_scale_param.rho=Parameter containing:
tensor(0.5413, dtype=torch.float64), area_scale_param.rho=Parameter containing:
tensor(0.5413, dtype=torch.float64))
Build the model so it registers its parameters, then use unfreeze_() to set requires_grad=True on the matching parameters. Here we select the sodium and potassium conductances of the Hodgkin–Huxley mechanism.
bad_model.build()
bad_model.unfreeze_('hh.gnabar', 'hh.gkbar')
print("\n", bad_model.pretty(show_mechanism_parameters=True))
Unfreezing integrator.mech.mechanisms.hh.gnabar_param
Unfreezing integrator.mech.mechanisms.hh.gkbar_param
Unmyelinated {
core_shape=(1, 101) (np=1, nc=101)
device=cpu, dtype=torch.float64, built=True, rebuild_pending=False
params: celsius=6.3 °C, cm=≈1 (const?; shape=(1, 101)), rhoa=≈100 (const?; shape=(1, 101))
mechanisms: 1 built
- hh (_hhProxy) @ everywhere, pshape=(1, 101) {
parameters {
DE.mhn.ah1_param: 0.07
DE.mhn.ah2_param: 1
DE.mhn.am1_param: 0.1
DE.mhn.am2_param: 4
DE.mhn.an1_param: 0.01
DE.mhn.an2_param: 0.125
ek_param: -77
el_param: -54.3
ena_param: 50
gkbar_param (grad): 0.05
gl_param: 0.0003
gnabar_param (grad): 0.05
}
}
ions: (none)
materials: (none)
}
Now we need to define the loss function that we will use to quantify the difference between the model’s output and the target voltage trace. We will use mean squared error (MSE) as our loss function.
def mse_loss(v_pred, v_target):
return ((v_pred - v_target) ** 2).mean()
For starters, lets just see if we can run the bad model, calculate the loss, and compute gradients with respect to the parameters we want to optimize.
bad_model.initialize()
bad_model.run(tstop=5.0, dt=0.005, callbacks=[bad_rec])
v_bad = bad_rec.stack('v')
loss = mse_loss(v_bad, v_ref)
print(f'Initial loss: {loss.item()}')
loss.backward()
print(f'Gradients:')
for name, param in bad_model.named_parameters():
if param.requires_grad:
print(f' {name}: {param.grad}')
Initial loss: 2448.761506613325
Gradients:
integrator.mech.mechanisms.hh.gnabar_param: -109476.30048841254
integrator.mech.mechanisms.hh.gkbar_param: 115167.74192863527
Let’s also visualize the difference between the bad model’s voltage trace and the reference trace before optimization.
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
# proximal voltage trace
ax1.plot(v_bad.detach().numpy()[:, 0, 0], linewidth=4)
ax1.plot(v_ref.detach().numpy()[:, 0, 0], linewidth=4, linestyle='--')
ax1.set_xlabel('Time step')
ax1.set_ylabel('Voltage (mV)')
ax1.legend(['Bad Model', 'Reference'])
ax1.set_title('Voltage Trace Comparison @ Compartment 0')
ax2.plot(v_bad.detach().numpy()[:, 0, -1], linewidth=4)
ax2.plot(v_ref.detach().numpy()[:, 0, -1], linewidth=4, linestyle='--')
ax2.set_xlabel('Time step')
ax2.set_ylabel('Voltage (mV)')
ax2.legend(['Bad Model', 'Reference'])
ax2.set_title('Voltage Trace Comparison @ Compartment -1')
plt.show()
Use dn.func.inspect_sources(bad_model) to see which tensors are trainable. The report lists aliases when several paths refer to the same tensor. Pass report.trainable_leaves to Adam to update each selected conductance once.
report = dn.func.inspect_sources(bad_model)
print(report)
optimizer = torch.optim.Adam(report.trainable_leaves, lr=5e-3)
SourceReport
Sources: 65 named paths; 25 unique tensors; 16 alias groups
Gradients: 2 trainable leaves; 0 nonleaf tensors requiring gradients
parameters (62 paths)
├─ celsius_param [shape=(), float64, cpu; requires_grad=False]
├─ cm_param [shape=(), float64, cpu; requires_grad=False]
├─ rhoa_param [shape=(), float64, cpu; requires_grad=False]
├─ rhoa_scale_param.rho [shape=(), float64, cpu; requires_grad=False]
├─ integrator.mech
│ ├─ mechanisms.hh
│ │ ├─ gnabar_param [shape=(), float64, cpu; trainable leaf] (3 aliases)
│ │ └─ gkbar_param [shape=(), float64, cpu; trainable leaf] (3 aliases)
│ └─ hh
│ ├─ gnabar_param [shape=(), float64, cpu; trainable leaf] -> parameters.integrator.mech.mechanisms.hh.gnabar_param
│ └─ gkbar_param [shape=(), float64, cpu; trainable leaf] -> parameters.integrator.mech.mechanisms.hh.gkbar_param
└─ mech
├─ mechanisms.hh
│ ├─ gnabar_param [shape=(), float64, cpu; trainable leaf] -> parameters.integrator.mech.mechanisms.hh.gnabar_param
│ └─ gkbar_param [shape=(), float64, cpu; trainable leaf] -> parameters.integrator.mech.mechanisms.hh.gkbar_param
└─ hh
├─ gnabar_param [shape=(), float64, cpu; trainable leaf] -> parameters.integrator.mech.mechanisms.hh.gnabar_param
└─ gkbar_param [shape=(), float64, cpu; trainable leaf] -> parameters.integrator.mech.mechanisms.hh.gkbar_param
... 50 paths omitted; see report.entries for the complete inventory.
constants (3 paths)
├─ diam [shape=(1, 101), float64, cpu; requires_grad=False]
├─ dx [shape=(1, 101), float64, cpu; requires_grad=False]
└─ diameters [shape=(1,), float64, cpu; requires_grad=False]
for step in range(500):
optimizer.zero_grad()
bad_model.initialize()
bad_rec.reset()
bad_model.run(tstop=5.0, dt=0.005, callbacks=[bad_rec])
v_bad = bad_rec.stack('v')
loss = mse_loss(v_bad, v_ref)
loss.backward()
optimizer.step()
if step % 50 == 0:
print(f'Step {step}, Loss: {loss.item()}')
Step 0, Loss: 2448.761506613325
Step 50, Loss: 2.427708034363033
Step 100, Loss: 0.1630302689309131
Step 150, Loss: 0.02903663422169695
Step 200, Loss: 0.00417046476144716
Step 250, Loss: 0.00043602383167878103
Step 300, Loss: 3.191033409691401e-05
Step 350, Loss: 1.5621083759952782e-06
Step 400, Loss: 4.799227737161207e-08
Step 450, Loss: 8.310715222602196e-10
Now lets check how the model’s voltage trace looks after optimization.
# Recompute after the final optimizer update.
with torch.no_grad():
bad_model.initialize()
bad_rec.reset()
bad_model.run(tstop=5.0, dt=0.005, callbacks=[bad_rec])
v_bad = bad_rec.stack('v')
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
# proximal voltage trace
ax1.plot(v_bad.detach().numpy()[:, 0, 0], linewidth=4)
ax1.plot(v_ref.detach().numpy()[:, 0, 0], linewidth=4, linestyle='--')
ax1.set_xlabel('Time step')
ax1.set_ylabel('Voltage (mV)')
ax1.legend(['Bad Model', 'Reference'])
ax1.set_title('Voltage Trace Comparison @ Compartment 0')
ax2.plot(v_bad.detach().numpy()[:, 0, -1], linewidth=4)
ax2.plot(v_ref.detach().numpy()[:, 0, -1], linewidth=4, linestyle='--')
ax2.set_xlabel('Time step')
ax2.set_ylabel('Voltage (mV)')
ax2.legend(['Bad Model', 'Reference'])
ax2.set_title('Voltage Trace Comparison @ Compartment -1')
plt.show()
print('Optimized parameters:')
print(f'gkbar: {bad_model.mech.hh.gkbar.item()}')
print(f'gnabar: {bad_model.mech.hh.gnabar.item()}')
print('Original parameters:')
print(f'gkbar: {ref.mech.hh.gkbar.item()}')
print(f'gnabar: {ref.mech.hh.gnabar.item()}')
Optimized parameters:
gkbar: 0.03599999036002251
gnabar: 0.11999997946206988
Original parameters:
gkbar: 0.035999998450279236
gnabar: 0.11999999731779099
Well done! You have successfully optimized a neuron model using gradient descent in Dendra. You can see that the optimized parameters are now much closer to the original parameters of the reference model. This demonstrates the power of gradient-based optimization for fitting neuron models to data.
The functional fitting script fits the same conductances using explicit simulation state. See Run models with explicit state for compiled runs and continuation.