Optimizers
13 built-in optimizers, dispatched into 5 families at construction time
(before JIT). Each family owns its own grad-step factory in
optimizers/<family>.py; the generic step is make_grad_step_standard.
| Family | Names | Step shape |
|---|---|---|
| STANDARD | adam, sgd, adamw, lion, muon, ngd, shampoo |
jax.grad → opt.update(grads, state, params) |
| PCGRAD | (gradient_surgery: pcgrad) |
Per-equation grads with conflict projection |
| MAO | mao, mao_kfac |
Per-equation Jacobian via jax.jacrev → MAO update |
| LBFGS | lbfgs |
Optax LBFGS with line search (needs value, grad, value_fn) |
| GN | gn, ign, lm |
Gauss-Newton / Levenberg-Marquardt: Δθ = −(JᵀJ)⁻¹ Jᵀr |
Registration uses the @register_optimizer(name, kind) decorator in
each module; optimizers/__init__.py imports every module to trigger
registration. create_optimizer(config) looks up the registry and
chains optax.clip_by_global_norm for STANDARD optimizers
automatically when grad_clip is set.
MAO uses _MAOFactory for deferred n_tasks resolution (the model's
equation count is known only at create_train_state time).
Composite loss is rejected with MAO/GN/IGN/LM/LBFGS and PCGrad
(TrainConfig._validate_ranges enforces this); on those paths the
optimizer's update doesn't see the auxiliary terms.
For adding a new optimizer, see Adding an optimizer.
deqn_jax.optimizers.registry
Optimizer registry for DEQN-JAX.
Maps optimizer names to factory functions and optimizer kinds. The kind determines which train_step variant is used.
OptimizerKind
Bases: str, Enum
Determines which train_step variant runs.
Source code in src/deqn_jax/optimizers/registry.py
13 14 15 16 17 18 19 | |
ReduceLROnPlateau
Keras-style loss-reactive LR decay.
Mirrors DEQN-MAO's lr_scheduler: ReduceLROnPlateau with the same
knob names (factor, patience, cooldown, min_delta, min_lr). Unlike
the other schedules here, this one is stateful and must be called
with the current loss at every cycle, not just the step index.
Call signature: self(ep_num, loss=None) -> lr. loss=None is
treated as "no update this cycle" -- the scheduler returns the
current LR without advancing state. Used so the schedule callable
can be probed early in training (e.g. for logging) before a first
loss is available.
Source code in src/deqn_jax/optimizers/registry.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
register_optimizer
register_optimizer(
name: str, kind: OptimizerKind = OptimizerKind.STANDARD
)
Decorator to register an optimizer factory.
Source code in src/deqn_jax/optimizers/registry.py
26 27 28 29 30 31 32 33 34 35 36 | |
create_optimizer
create_optimizer(
config, total_steps: Optional[int] = None
) -> Tuple[Any, OptimizerKind]
Create optimizer from config.
LR schedules are NOT applied here — they break XLA kernel fusion
and cause 5-6x slowdowns. Instead, the training loop periodically
recreates the optimizer with an updated constant LR. See
_build_lr_schedule for computing schedule values and
train_from_config for the periodic update logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
OptimizerConfig with at least a |
required | |
total_steps
|
Optional[int]
|
Unused (kept for API compat). Schedule is handled by the training loop. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[Any, OptimizerKind]
|
Tuple of (optimizer, OptimizerKind) |
Source code in src/deqn_jax/optimizers/registry.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
list_optimizers
list_optimizers() -> List[str]
Return sorted list of registered optimizer names.
Source code in src/deqn_jax/optimizers/registry.py
176 177 178 | |
deqn_jax.optimizers.ngd
Natural Gradient Descent (diagonal Fisher approximation).
Running diagonal Fisher via EMA of g², preconditioned step: θ ← θ - lr * g / (sqrt(F) + damping)
Cheap and effective for PINN-style losses.
NGDState
Bases: NamedTuple
State for diagonal Fisher NGD.
Source code in src/deqn_jax/optimizers/ngd.py
19 20 21 22 23 | |
ngd
ngd(
learning_rate: float = 0.001,
damping: float = 0.0001,
decay: float = 0.999,
) -> optax.GradientTransformation
Diagonal Fisher Natural Gradient Descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Step size |
0.001
|
damping
|
float
|
Regularization added to sqrt(Fisher) |
0.0001
|
decay
|
float
|
EMA decay for Fisher diagonal estimate |
0.999
|
Returns:
| Type | Description |
|---|---|
GradientTransformation
|
optax.GradientTransformation |
Source code in src/deqn_jax/optimizers/ngd.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
deqn_jax.optimizers.mao
Multi-Adaptive Optimizer (MAO) for per-equation optimization.
MAO maintains separate Adam-style moment estimates for each equation, then combines updates via per-task adaptive learning rates.
This is NOT an optax.GradientTransformation -- it has a custom interface because it receives per-equation Jacobians instead of standard gradients.
Usage in training
eq_jac = jax.jacrev(per_eq_loss_fn)(params) # pytree, each leaf [n_eq, *shape] updates, new_state = mao.update(eq_jac, state, params) new_params = optax.apply_updates(params, updates)
MAOState
Bases: NamedTuple
State for MAO optimizer.
Source code in src/deqn_jax/optimizers/mao.py
24 25 26 27 28 29 | |
MAOTransform
Multi-Adaptive Optimizer.
Maintains per-equation moment estimates and combines updates.
Source code in src/deqn_jax/optimizers/mao.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
init
init(params: Any) -> MAOState
Initialize MAO state with per-equation moments.
Source code in src/deqn_jax/optimizers/mao.py
52 53 54 55 56 57 58 59 60 61 62 | |
update
update(
eq_jacobian: Any, state: MAOState, params: Any
) -> Tuple[Any, MAOState]
Compute MAO update from per-equation Jacobians.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eq_jacobian
|
Any
|
Pytree matching params, each leaf [n_eq, *param_shape] (output of jax.jacrev over per-equation losses) |
required |
state
|
MAOState
|
Current MAO state |
required |
params
|
Any
|
Current parameters (unused but kept for API consistency) |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Any, MAOState]
|
Tuple of (updates pytree, new_state) |
Source code in src/deqn_jax/optimizers/mao.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
make_grad_step_mao
make_grad_step_mao(
model,
mao_opt: Any,
mc_samples: int,
quad_nodes,
quad_weights,
loss_reweight: str,
reweight_alpha: float,
use_target_network: bool,
compute_loss_fn,
grad_clip,
)
JIT'd: one MAO (per-equation Jacobian) gradient update on a minibatch.
Source code in src/deqn_jax/optimizers/mao.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
deqn_jax.optimizers.shampoo
In-house Kronecker-factored Shampoo optimizer.
For 2D parameters (weight matrices), maintains Kronecker factors: L = EMA(G @ G^T), R = EMA(G^T @ G) update = L^{-1/4} @ G @ R^{-1/4}
For 1D parameters (biases), reshapes to [1, n] to avoid data-dependent branching.
Preconditioners are updated every precond_update_freq steps.
ShampooState
Bases: NamedTuple
Shampoo optimizer state.
Source code in src/deqn_jax/optimizers/shampoo.py
22 23 24 25 26 27 | |
shampoo
shampoo(
learning_rate: float = 0.001,
beta: float = 0.9,
precond_update_freq: int = 10,
epsilon: float = 1e-12,
) -> optax.GradientTransformation
Kronecker-factored Shampoo optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Step size |
0.001
|
beta
|
float
|
EMA decay for preconditioner statistics |
0.9
|
precond_update_freq
|
int
|
Steps between preconditioner updates |
10
|
epsilon
|
float
|
Ridge for numerical stability |
1e-12
|
Returns:
| Type | Description |
|---|---|
GradientTransformation
|
optax.GradientTransformation |
Source code in src/deqn_jax/optimizers/shampoo.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
deqn_jax.optimizers.lbfgs
L-BFGS optimizer via optax.
Thin wrapper around optax.lbfgs() which is a GradientTransformationExtraArgs --
it needs value and value_fn passed to update() for line search.
make_grad_step_lbfgs
make_grad_step_lbfgs(
model: ModelSpec,
opt: Any,
mc_samples: int,
quad_nodes: Optional[Array],
quad_weights: Optional[Array],
loss_reweight: str,
reweight_alpha: float,
use_target_network: bool,
compute_loss_fn: Optional[Callable],
)
JIT'd: one L-BFGS gradient update on a minibatch (with line search).
Source code in src/deqn_jax/optimizers/lbfgs.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
deqn_jax.optimizers.gauss_newton
Gauss-Newton and Levenberg-Marquardt optimizers for JAX.
For DEQN, we minimize L = ||r(θ)||² where r are equilibrium residuals. Gauss-Newton approximates Hessian as H ≈ J^T J where J = ∂r/∂θ.
Key advantage over first-order methods: quadratic convergence near solution.
This implementation uses JAX autodiff (jacrev/jacfwd) for efficient Jacobian computation - much faster than finite differences.
Note on optimistix: optimistix's LevenbergMarquardt and GaussNewton
solvers are excellent for full-convergence least-squares problems
(curve fitting, SS solving) and are used in this codebase for those
cases (see models/disaster/equations.py:solve_omega_bar and
models/disaster/steady_state.py). They do not fit DEQN's
per-minibatch optimizer contract, where each update() is called
once with a fresh residual function (different minibatch's residuals)
and we want exactly one step. Optimistix's trust-region update is
conservative on first call (init→step counts as ≥1 step internally,
returning y0 with max_steps=1; max_steps=2 takes only a half-step) and
re-initializing per call defeats the purpose. So the classes below
remain hand-rolled.
Usage
opt = gauss_newton(learning_rate=1.0) state = opt.init(params)
def residual_fn(p): return model.equations(states, p(states), ...)
params, state = opt.update(residual_fn, params, state)
GaussNewtonState
Bases: NamedTuple
State for Gauss-Newton optimizer.
last_loss is a JAX scalar Array at runtime (sum of squared
residuals from inside the JIT'd update step). It was annotated as
Python float originally, which produced spurious
invalid-argument-type errors at every constructor call — same
pattern as the Metrics annotation lie cleared in commit
3ae741f. damping stays float because the LM update
keeps it on the Python side.
Source code in src/deqn_jax/optimizers/gauss_newton.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
ImplicitGaussNewtonState
Bases: NamedTuple
State for matrix-free damped Gauss-Newton.
last_cg_residual tracks the final linear-system residual norm from the
conjugate-gradient solve. It is diagnostic only; schedules and checkpoint
serialization treat it like the other scalar optimizer-state arrays.
Source code in src/deqn_jax/optimizers/gauss_newton.py
59 60 61 62 63 64 65 66 67 68 69 70 71 | |
GaussNewton
Gauss-Newton optimizer for nonlinear least squares.
Source code in src/deqn_jax/optimizers/gauss_newton.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
update
update(
residual_fn: Callable,
params: Any,
state: GaussNewtonState,
lr_scale: Any = 1.0,
) -> Tuple[Any, GaussNewtonState]
Perform one GN step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residual_fn
|
Callable
|
Function params -> flat residuals [n_residuals] |
required |
params
|
Any
|
Current parameters (pytree) |
required |
state
|
GaussNewtonState
|
Optimizer state |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Any, GaussNewtonState]
|
Tuple of (new_params, new_state) |
Source code in src/deqn_jax/optimizers/gauss_newton.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
ImplicitGaussNewton
Matrix-free damped Gauss-Newton / natural-gradient optimizer.
For residual least squares 0.5 * ||r(theta)||^2, the Gauss-Newton
metric is J.T @ J where J = dr/dtheta. This class solves
``(J.T @ J + damping * I) delta = -J.T @ r``
with conjugate gradients using only JVP/VJP products. It avoids storing the dense Fisher/GN matrix and avoids materializing the full residual Jacobian, which is the practical route for DEQN-sized policy networks.
Source code in src/deqn_jax/optimizers/gauss_newton.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | |
LevenbergMarquardt
Levenberg-Marquardt optimizer (adaptive damped Gauss-Newton).
Source code in src/deqn_jax/optimizers/gauss_newton.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
update
update(
residual_fn: Callable,
params: Any,
state: GaussNewtonState,
lr_scale: Any = 1.0,
) -> Tuple[Any, GaussNewtonState]
Perform one LM step with adaptive damping.
Source code in src/deqn_jax/optimizers/gauss_newton.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
gauss_newton
gauss_newton(
learning_rate: float = 1.0, damping: float = 0.0
) -> GaussNewton
Create Gauss-Newton optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Step size multiplier (1.0 = full GN step) |
1.0
|
damping
|
float
|
Fixed damping (0 = pure GN, >0 = LM-style regularization) |
0.0
|
Returns:
| Type | Description |
|---|---|
GaussNewton
|
GaussNewton optimizer instance |
Source code in src/deqn_jax/optimizers/gauss_newton.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
implicit_gauss_newton
implicit_gauss_newton(
learning_rate: float = 1.0,
damping: float = 0.0001,
cg_iters: int = 20,
cg_tol: float = 1e-06,
) -> ImplicitGaussNewton
Create a matrix-free damped Gauss-Newton optimizer.
Source code in src/deqn_jax/optimizers/gauss_newton.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |
levenberg_marquardt
levenberg_marquardt(
learning_rate: float = 1.0,
initial_damping: float = 0.001,
damping_increase: float = 10.0,
damping_decrease: float = 0.1,
min_damping: float = 1e-08,
max_damping: float = 100000000.0,
) -> LevenbergMarquardt
Create Levenberg-Marquardt optimizer (adaptive damped GN).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Step size multiplier |
1.0
|
initial_damping
|
float
|
Starting damping value |
0.001
|
damping_increase
|
float
|
Factor when step is bad |
10.0
|
damping_decrease
|
float
|
Factor when step is good |
0.1
|
min_damping
|
float
|
Minimum damping |
1e-08
|
max_damping
|
float
|
Maximum damping |
100000000.0
|
Returns:
| Type | Description |
|---|---|
LevenbergMarquardt
|
LevenbergMarquardt optimizer instance |
Source code in src/deqn_jax/optimizers/gauss_newton.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 | |
make_grad_step_gn
make_grad_step_gn(
model,
opt: Any,
mc_samples: int,
batch_size: int,
quad_nodes,
quad_weights,
loss_reweight: str,
reweight_alpha: float,
use_target_network: bool,
compute_loss_fn,
)
JIT'd: one Gauss-Newton / Levenberg-Marquardt update on a minibatch.
Source code in src/deqn_jax/optimizers/gauss_newton.py
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | |