Loss
Two loss paths. Switch via TrainConfig.loss_type.
Base MSE (compute_loss)
loss_type: "mse" (default). Per batch element:
- Per-shock residuals via
equations_fn. - Shock-expectation: weighted mean across MC samples (uniform) or Gauss-Hermite nodes (Hermite weights).
- Square the mean:
(E_shock[r])²— MC-correct for E[r]=0 conditions; biased under the Jensen-unsafe forms (see the residual trap). - Aggregate across batch: mean (or Huber if
loss_choice="huber"). - Aggregate across equations: mean (DEQN-MAO convention; not sum).
compute_residuals is the inner per-shock-realization helper;
sample_antithetic_shocks handles MC variance reduction;
gauss_hermite_nd constructs the quadrature grid (lru_cached).
Aux losses keyed aux_* are filtered out of adaptive reweighting via
eq_losses_to_array.
Composite (make_composite_loss)
loss_type: "composite". Adds anchor + Jacobian + barrier + Newton aux
terms layered on the base MSE. Pre-computes anchor sample points and
the Blanchard-Kahn P matrix at setup time; every term is logged
under its own aux_* key.
For the math, decay schedules, and configuration knobs see Composite loss.
deqn_jax.training.loss
Loss computation with Monte Carlo or Gauss-Hermite quadrature expectations.
The DEQN loss is the mean squared residual of equilibrium equations:
L = E_s[ E_ε[ r(s, π(s), s', π(s'))² ] ]
where the expectation is over: 1. States s drawn from episode trajectories 2. Shocks ε determining next state s' = step(s, π(s), ε)
Expectation methods: - MC: Antithetic variates (pair each ε with -ε for variance reduction) - Quadrature: Gauss-Hermite tensor-product nodes (exact for polynomial integrands)
Residual aggregation uses (E[r])² (average THEN square): - Correct loss for E[r]=0 equilibrium conditions - Robust to outlier residuals (averages first, tames singularities) - With quadrature weights: weighted mean then square
sample_antithetic_shocks
sample_antithetic_shocks(
key: Array,
n_samples: int,
batch_size: int,
shock_dim: int,
shock_scale: float | Array = 1.0,
) -> Array
Generate Monte Carlo shocks with antithetic variates.
Antithetic sampling pairs each shock ε with -ε, reducing variance for symmetric distributions (like standard normal).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
JAX PRNG key |
required |
n_samples
|
int
|
Number of MC samples (will be rounded to even) |
required |
batch_size
|
int
|
Batch size |
required |
shock_dim
|
int
|
Dimension of shock vector |
required |
shock_scale
|
float | Array
|
Curriculum scaling for shocks (0→1 ramp) |
1.0
|
Returns:
| Type | Description |
|---|---|
Array
|
Shocks array [n_samples, batch_size, shock_dim] |
Source code in src/deqn_jax/training/loss.py
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 | |
gauss_hermite_nd
gauss_hermite_nd(
n_points: int, dim: int, max_points: int = 4096
) -> Optional[Tuple[np.ndarray, np.ndarray]]
Tensor-product Gauss-Hermite nodes/weights for standard normal.
Transforms from Hermite basis (weight exp(-x²)) to standard normal: - Nodes: x' = sqrt(2) * x - Weights: w' = w / sqrt(π)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_points
|
int
|
Quadrature points per dimension |
required |
dim
|
int
|
Number of shock dimensions |
required |
max_points
|
int
|
Safety cap on total grid points |
4096
|
Returns:
| Type | Description |
|---|---|
Optional[Tuple[ndarray, ndarray]]
|
Tuple of (nodes [n_nodes, dim], weights [n_nodes]), or None if too many. |
Source code in src/deqn_jax/training/loss.py
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 | |
compute_residuals
compute_residuals(
model: ModelSpec,
policy_fn: Callable[[Array], Array],
train_batch: Array,
shock: Array,
target_policy_fn: Optional[
Callable[[Array], Array]
] = None,
residual_fn: Optional[
Callable[..., Dict[str, Array]]
] = None,
) -> Dict[str, Array]
Compute equilibrium equation residuals for a single shock realization.
Handles both MLP [B, D] and sequence [B, H, D] inputs: - For [B, D]: standard MLP path, policy_fn(states) - For [B, H, D]: extract current state from last timestep, compute next_state, shift history window for next_policy
The ndim check resolves at JAX trace time (no runtime branching).
If target_policy_fn is provided (target network mode), next_policy is computed from the frozen target network with stop_gradient. This breaks the self-referential gradient loop where the network must simultaneously satisfy today's equations and be consistent with its own future outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelSpec
|
Model specification |
required |
policy_fn
|
Callable[[Array], Array]
|
Policy network (states -> policies) or (history -> policies) |
required |
train_batch
|
Array
|
Current states [batch, n_states] or history windows [batch, H, n_states] |
required |
shock
|
Array
|
Shock realization [batch, n_shocks] |
required |
target_policy_fn
|
Optional[Callable[[Array], Array]]
|
Frozen policy for next_policy (None = use policy_fn) |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Array]
|
Dict mapping equation names to residuals [batch] |
Source code in src/deqn_jax/training/loss.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 | |
huber
huber(x: Array, delta: float) -> Array
Huber function: quadratic near 0, linear beyond |x| = delta.
huber(x, δ) = 0.5·x² for |x| ≤ δ
huber(x, δ) = δ·(|x| - 0.5·δ) for |x| > δ
Matches DEQN_MAO's Huber_loss convention. Gradient saturates at ±δ for large residuals, which limits the influence of outlier batch elements on parameter updates — useful when a few ZLB-binding or extreme-shock states produce residuals ≫ typical.
Source code in src/deqn_jax/training/loss.py
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
compute_loss
compute_loss(
model: ModelSpec,
policy_fn: Callable[[Array], Array],
states: Array,
key: Array,
mc_samples: int = 5,
weights: Optional[Array] = None,
shock_scale: float | Array = 1.0,
quad_nodes: Optional[Array] = None,
quad_weights: Optional[Array] = None,
barrier_weight: float | Array = 0.0,
target_policy_fn: Optional[
Callable[[Array], Array]
] = None,
loss_choice: str = "mse",
huber_delta: float | Array = 1.0,
) -> Tuple[Array, Dict[str, Array]]
Compute DEQN loss with MC or quadrature expectations.
Aggregation: (E[r])² — square the weighted mean residual per batch element. This is the correct loss for E[r]=0 equilibrium conditions and is robust to outlier residuals (averages first, then squares).
For MC: shocks ~ N(0, shock_scale²), uniform weights 1/N For quadrature: shocks = nodes * shock_scale, Gauss-Hermite weights
Handles both MLP [batch, n_states] and sequence [batch, H, n_states] inputs transparently (dispatched inside compute_residuals via ndim check).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelSpec
|
Model specification |
required |
policy_fn
|
Callable[[Array], Array]
|
Policy network (states -> policies) or (history -> policies) |
required |
states
|
Array
|
State batch [batch, n_states] or history windows [batch, H, n_states] |
required |
key
|
Array
|
PRNG key for MC shock sampling (ignored for quadrature) |
required |
mc_samples
|
int
|
Number of Monte Carlo samples (ignored for quadrature) |
5
|
weights
|
Optional[Array]
|
Per-equation loss weights [n_eq] (default: uniform) |
None
|
shock_scale
|
float | Array
|
Curriculum scaling for shocks (0→1 ramp) |
1.0
|
quad_nodes
|
Optional[Array]
|
Quadrature nodes [n_nodes, shock_dim] (None -> use MC) |
None
|
quad_weights
|
Optional[Array]
|
Quadrature weights [n_nodes] (None -> use MC) |
None
|
barrier_weight
|
float | Array
|
Weight for state barrier penalty (0 = off) |
0.0
|
Returns:
| Type | Description |
|---|---|
Tuple[Array, Dict[str, Array]]
|
Tuple of (scalar loss, dict of per-equation losses) |
Source code in src/deqn_jax/training/loss.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 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 423 424 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 454 455 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 | |
eq_losses_to_array
eq_losses_to_array(eq_losses: Dict[str, Array]) -> Array
Convert per-equation loss dict to stacked array [n_eq].
Filters out aux_ prefixed keys so that adaptive reweighting (lr_annealing, relobralo) and per-equation gradient surgery (PCGrad, MAO) only see base equilibrium equation losses.
Source code in src/deqn_jax/training/loss.py
586 587 588 589 590 591 592 593 | |
compute_loss_for_grad
compute_loss_for_grad(
params,
model: ModelSpec,
states: Array,
key: Array,
mc_samples: int = 5,
) -> Array
Loss function signature suitable for jax.grad.
Source code in src/deqn_jax/training/loss.py
596 597 598 599 600 601 602 603 604 605 | |
make_loss_fn
make_loss_fn(
model: ModelSpec, mc_samples: int = 5
) -> Callable
Create a loss function closed over model spec.
Returns a function (params, states, key) -> (loss, eq_losses) suitable for use with jax.value_and_grad.
Source code in src/deqn_jax/training/loss.py
608 609 610 611 612 613 614 615 616 617 618 619 620 621 | |
deqn_jax.training.composite_loss
Composite loss: anchor + Jacobian + Sobolev-anchor + model-supplied aux.
Drop-in replacement for compute_loss() — returns the same (total_loss, eq_losses_dict) signature, with auxiliary losses keyed with "aux_" prefix so adaptive reweighting and per-equation gradient surgery only see the base equilibrium residuals.
The generic terms here are MODEL-AGNOSTIC:
aux_anchor= ||π_θ(s) − π_BK(s)||² at sampled-near-SS pointsaux_jac= ||J_π_θ(s_ss) − P||²_Faux_jac_anchor= same as aux_jac but at every anchor point (Sobolev)
Per-model auxiliary terms (e.g. economic-feasibility barriers, Newton-solver
diagnostics) flow through ModelSpec.composite_aux_fn. The hook receives
the per-batch defs dict, the precomputed CompositeData, and a
weights dict containing every weight knob the trainer was given (so the
hook can pick the ones it cares about, e.g. barrier_weight,
leverage_mult, newton_weight). See models/disaster/composite_aux.py
for the canonical pattern (BGG net-worth barrier, leverage barrier,
consumption barrier, Newton-conditioning diagnostics).
Usage
data = prepare_composite_data(model, P, Q) loss_fn = make_composite_loss(model, data, config.composite_loss)
loss_fn has the same signature as compute_loss
CompositeData
Bases: NamedTuple
Pre-computed linearization data for composite loss terms.
Attributes:
| Name | Type | Description |
|---|---|---|
P |
Array
|
Policy rule matrix [n_policies, n_states] from Blanchard-Kahn |
ss_state |
Array
|
Steady state [n_states] |
ss_policy |
Array
|
Steady state policy [n_policies] |
ergodic_cov_chol |
Array
|
Cholesky of ergodic covariance [n_states, n_states] |
anchor_points |
Array
|
Pre-sampled states near SS [n_anchor, n_states] |
anchor_deviations |
Array
|
anchor_points - ss_state [n_anchor, n_states] |
anchor_lin_policy |
Array
|
Linear policy at anchor points [n_anchor, n_policies] |
aux_constants |
Dict[str, Any]
|
Generic dict for model-specific precomputed constants
(e.g. disaster's ss_leverage). Populated by the model's
|
Source code in src/deqn_jax/training/composite_loss.py
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 | |
prepare_composite_data
prepare_composite_data(
model: ModelSpec,
P: Array,
Q: Array,
n_anchor_points: int = 64,
anchor_sigma: float = 1.0,
seed: int = 12345,
verbose: bool = True,
) -> CompositeData
Build CompositeData from linearization results.
Pre-computes anchor sample points from the ergodic distribution so the anchor loss is deterministic (no per-step randomness = no gradient noise).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelSpec
|
Model specification |
required |
P
|
Array
|
Policy rule matrix from linearize_model |
required |
Q
|
Array
|
Transition matrix from linearize_model |
required |
n_anchor_points
|
int
|
Number of fixed sample points near SS |
64
|
anchor_sigma
|
float
|
Scale factor for sampling spread |
1.0
|
seed
|
int
|
RNG seed for anchor point sampling |
12345
|
verbose
|
bool
|
Print diagnostic info |
True
|
Source code in src/deqn_jax/training/composite_loss.py
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 127 128 129 130 | |
make_composite_loss
make_composite_loss(
model: ModelSpec,
data: CompositeData,
anchor_weight: float = 0.1,
jac_weight: float = 0.01,
jac_anchor_weight: float = 0.0,
barrier_weight: float = 0.01,
newton_weight: float = 0.01,
leverage_mult: float = 5.0,
aux_decay_floor: float = 0.2,
history_len: int = 1,
loss_choice: str = "mse",
huber_delta: float = 1.0,
) -> Callable
Create composite loss function as drop-in replacement for compute_loss.
Returns a function with the same signature as compute_loss(): (model, policy_fn, states, key, mc_samples, weights, shock_scale, quad_nodes, quad_weights) -> (total_loss, eq_losses_dict)
Anchor and Jacobian losses decay with shock_scale but maintain a floor
decay = max(floor, 1 - shock_scale)
During curriculum (shock_scale ramps 0.1 → 1.0), they fade from 90% → floor. With floor=0.2, anchor/jac stay active throughout training to prevent the network from drifting into degenerate far-from-SS basins.
Auxiliary loss entries are keyed with "aux_" prefix.
Source code in src/deqn_jax/training/composite_loss.py
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |